UNPKG

428 kBJavaScriptView Raw
1#!/usr/bin/env node
2'use strict';
3
4function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
5
6var util = _interopDefault(require('util'));
7var path = _interopDefault(require('path'));
8var tty = _interopDefault(require('tty'));
9var fs = _interopDefault(require('fs'));
10var readableStream = _interopDefault(require('readable-stream'));
11var os = _interopDefault(require('os'));
12var zlib = _interopDefault(require('zlib'));
13var stream = _interopDefault(require('stream'));
14var events = _interopDefault(require('events'));
15var buffer$1 = _interopDefault(require('buffer'));
16var url = _interopDefault(require('url'));
17var http = _interopDefault(require('http'));
18var https = _interopDefault(require('https'));
19var net = _interopDefault(require('net'));
20var assert = _interopDefault(require('assert'));
21var child_process = _interopDefault(require('child_process'));
22
23var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
24
25function commonjsRequire () {
26 throw new Error('Dynamic requires are not currently supported by rollup-plugin-commonjs');
27}
28
29function unwrapExports (x) {
30 return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
31}
32
33function createCommonjsModule(fn, module) {
34 return module = { exports: {} }, fn(module, module.exports), module.exports;
35}
36
37function getCjsExportFromNamespace (n) {
38 return n && n['default'] || n;
39}
40
41var argv = process.argv;
42
43var terminator = argv.indexOf('--');
44var hasFlag = function (flag) {
45 flag = '--' + flag;
46 var pos = argv.indexOf(flag);
47 return pos !== -1 && (terminator !== -1 ? pos < terminator : true);
48};
49
50var supportsColor = (function () {
51 if ('FORCE_COLOR' in process.env) {
52 return true;
53 }
54
55 if (hasFlag('no-color') ||
56 hasFlag('no-colors') ||
57 hasFlag('color=false')) {
58 return false;
59 }
60
61 if (hasFlag('color') ||
62 hasFlag('colors') ||
63 hasFlag('color=true') ||
64 hasFlag('color=always')) {
65 return true;
66 }
67
68 if (process.stdout && !process.stdout.isTTY) {
69 return false;
70 }
71
72 if (process.platform === 'win32') {
73 return true;
74 }
75
76 if ('COLORTERM' in process.env) {
77 return true;
78 }
79
80 if (process.env.TERM === 'dumb') {
81 return false;
82 }
83
84 if (/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(process.env.TERM)) {
85 return true;
86 }
87
88 return false;
89})();
90
91/**
92 * Helpers.
93 */
94
95var s = 1000;
96var m = s * 60;
97var h = m * 60;
98var d = h * 24;
99var w = d * 7;
100var y = d * 365.25;
101
102/**
103 * Parse or format the given `val`.
104 *
105 * Options:
106 *
107 * - `long` verbose formatting [false]
108 *
109 * @param {String|Number} val
110 * @param {Object} [options]
111 * @throws {Error} throw an error if val is not a non-empty string or a number
112 * @return {String|Number}
113 * @api public
114 */
115
116var ms = function(val, options) {
117 options = options || {};
118 var type = typeof val;
119 if (type === 'string' && val.length > 0) {
120 return parse(val);
121 } else if (type === 'number' && isNaN(val) === false) {
122 return options.long ? fmtLong(val) : fmtShort(val);
123 }
124 throw new Error(
125 'val is not a non-empty string or a valid number. val=' +
126 JSON.stringify(val)
127 );
128};
129
130/**
131 * Parse the given `str` and return milliseconds.
132 *
133 * @param {String} str
134 * @return {Number}
135 * @api private
136 */
137
138function parse(str) {
139 str = String(str);
140 if (str.length > 100) {
141 return;
142 }
143 var match = /^((?:\d+)?\-?\d?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
144 str
145 );
146 if (!match) {
147 return;
148 }
149 var n = parseFloat(match[1]);
150 var type = (match[2] || 'ms').toLowerCase();
151 switch (type) {
152 case 'years':
153 case 'year':
154 case 'yrs':
155 case 'yr':
156 case 'y':
157 return n * y;
158 case 'weeks':
159 case 'week':
160 case 'w':
161 return n * w;
162 case 'days':
163 case 'day':
164 case 'd':
165 return n * d;
166 case 'hours':
167 case 'hour':
168 case 'hrs':
169 case 'hr':
170 case 'h':
171 return n * h;
172 case 'minutes':
173 case 'minute':
174 case 'mins':
175 case 'min':
176 case 'm':
177 return n * m;
178 case 'seconds':
179 case 'second':
180 case 'secs':
181 case 'sec':
182 case 's':
183 return n * s;
184 case 'milliseconds':
185 case 'millisecond':
186 case 'msecs':
187 case 'msec':
188 case 'ms':
189 return n;
190 default:
191 return undefined;
192 }
193}
194
195/**
196 * Short format for `ms`.
197 *
198 * @param {Number} ms
199 * @return {String}
200 * @api private
201 */
202
203function fmtShort(ms) {
204 var msAbs = Math.abs(ms);
205 if (msAbs >= d) {
206 return Math.round(ms / d) + 'd';
207 }
208 if (msAbs >= h) {
209 return Math.round(ms / h) + 'h';
210 }
211 if (msAbs >= m) {
212 return Math.round(ms / m) + 'm';
213 }
214 if (msAbs >= s) {
215 return Math.round(ms / s) + 's';
216 }
217 return ms + 'ms';
218}
219
220/**
221 * Long format for `ms`.
222 *
223 * @param {Number} ms
224 * @return {String}
225 * @api private
226 */
227
228function fmtLong(ms) {
229 var msAbs = Math.abs(ms);
230 if (msAbs >= d) {
231 return plural(ms, msAbs, d, 'day');
232 }
233 if (msAbs >= h) {
234 return plural(ms, msAbs, h, 'hour');
235 }
236 if (msAbs >= m) {
237 return plural(ms, msAbs, m, 'minute');
238 }
239 if (msAbs >= s) {
240 return plural(ms, msAbs, s, 'second');
241 }
242 return ms + ' ms';
243}
244
245/**
246 * Pluralization helper.
247 */
248
249function plural(ms, msAbs, n, name) {
250 var isPlural = msAbs >= n * 1.5;
251 return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
252}
253
254/**
255 * This is the common logic for both the Node.js and web browser
256 * implementations of `debug()`.
257 */
258
259function setup(env) {
260 createDebug.debug = createDebug;
261 createDebug.default = createDebug;
262 createDebug.coerce = coerce;
263 createDebug.disable = disable;
264 createDebug.enable = enable;
265 createDebug.enabled = enabled;
266 createDebug.humanize = ms;
267
268 Object.keys(env).forEach(key => {
269 createDebug[key] = env[key];
270 });
271
272 /**
273 * Active `debug` instances.
274 */
275 createDebug.instances = [];
276
277 /**
278 * The currently active debug mode names, and names to skip.
279 */
280
281 createDebug.names = [];
282 createDebug.skips = [];
283
284 /**
285 * Map of special "%n" handling functions, for the debug "format" argument.
286 *
287 * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
288 */
289 createDebug.formatters = {};
290
291 /**
292 * Selects a color for a debug namespace
293 * @param {String} namespace The namespace string for the for the debug instance to be colored
294 * @return {Number|String} An ANSI color code for the given namespace
295 * @api private
296 */
297 function selectColor(namespace) {
298 let hash = 0;
299
300 for (let i = 0; i < namespace.length; i++) {
301 hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
302 hash |= 0; // Convert to 32bit integer
303 }
304
305 return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
306 }
307 createDebug.selectColor = selectColor;
308
309 /**
310 * Create a debugger with the given `namespace`.
311 *
312 * @param {String} namespace
313 * @return {Function}
314 * @api public
315 */
316 function createDebug(namespace) {
317 let prevTime;
318
319 function debug(...args) {
320 // Disabled?
321 if (!debug.enabled) {
322 return;
323 }
324
325 const self = debug;
326
327 // Set `diff` timestamp
328 const curr = Number(new Date());
329 const ms = curr - (prevTime || curr);
330 self.diff = ms;
331 self.prev = prevTime;
332 self.curr = curr;
333 prevTime = curr;
334
335 args[0] = createDebug.coerce(args[0]);
336
337 if (typeof args[0] !== 'string') {
338 // Anything else let's inspect with %O
339 args.unshift('%O');
340 }
341
342 // Apply any `formatters` transformations
343 let index = 0;
344 args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
345 // If we encounter an escaped % then don't increase the array index
346 if (match === '%%') {
347 return match;
348 }
349 index++;
350 const formatter = createDebug.formatters[format];
351 if (typeof formatter === 'function') {
352 const val = args[index];
353 match = formatter.call(self, val);
354
355 // Now we need to remove `args[index]` since it's inlined in the `format`
356 args.splice(index, 1);
357 index--;
358 }
359 return match;
360 });
361
362 // Apply env-specific formatting (colors, etc.)
363 createDebug.formatArgs.call(self, args);
364
365 const logFn = self.log || createDebug.log;
366 logFn.apply(self, args);
367 }
368
369 debug.namespace = namespace;
370 debug.enabled = createDebug.enabled(namespace);
371 debug.useColors = createDebug.useColors();
372 debug.color = selectColor(namespace);
373 debug.destroy = destroy;
374 debug.extend = extend;
375 // Debug.formatArgs = formatArgs;
376 // debug.rawLog = rawLog;
377
378 // env-specific initialization logic for debug instances
379 if (typeof createDebug.init === 'function') {
380 createDebug.init(debug);
381 }
382
383 createDebug.instances.push(debug);
384
385 return debug;
386 }
387
388 function destroy() {
389 const index = createDebug.instances.indexOf(this);
390 if (index !== -1) {
391 createDebug.instances.splice(index, 1);
392 return true;
393 }
394 return false;
395 }
396
397 function extend(namespace, delimiter) {
398 const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
399 newDebug.log = this.log;
400 return newDebug;
401 }
402
403 /**
404 * Enables a debug mode by namespaces. This can include modes
405 * separated by a colon and wildcards.
406 *
407 * @param {String} namespaces
408 * @api public
409 */
410 function enable(namespaces) {
411 createDebug.save(namespaces);
412
413 createDebug.names = [];
414 createDebug.skips = [];
415
416 let i;
417 const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
418 const len = split.length;
419
420 for (i = 0; i < len; i++) {
421 if (!split[i]) {
422 // ignore empty strings
423 continue;
424 }
425
426 namespaces = split[i].replace(/\*/g, '.*?');
427
428 if (namespaces[0] === '-') {
429 createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
430 } else {
431 createDebug.names.push(new RegExp('^' + namespaces + '$'));
432 }
433 }
434
435 for (i = 0; i < createDebug.instances.length; i++) {
436 const instance = createDebug.instances[i];
437 instance.enabled = createDebug.enabled(instance.namespace);
438 }
439 }
440
441 /**
442 * Disable debug output.
443 *
444 * @return {String} namespaces
445 * @api public
446 */
447 function disable() {
448 const namespaces = [
449 ...createDebug.names.map(toNamespace),
450 ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
451 ].join(',');
452 createDebug.enable('');
453 return namespaces;
454 }
455
456 /**
457 * Returns true if the given mode name is enabled, false otherwise.
458 *
459 * @param {String} name
460 * @return {Boolean}
461 * @api public
462 */
463 function enabled(name) {
464 if (name[name.length - 1] === '*') {
465 return true;
466 }
467
468 let i;
469 let len;
470
471 for (i = 0, len = createDebug.skips.length; i < len; i++) {
472 if (createDebug.skips[i].test(name)) {
473 return false;
474 }
475 }
476
477 for (i = 0, len = createDebug.names.length; i < len; i++) {
478 if (createDebug.names[i].test(name)) {
479 return true;
480 }
481 }
482
483 return false;
484 }
485
486 /**
487 * Convert regexp to namespace
488 *
489 * @param {RegExp} regxep
490 * @return {String} namespace
491 * @api private
492 */
493 function toNamespace(regexp) {
494 return regexp.toString()
495 .substring(2, regexp.toString().length - 2)
496 .replace(/\.\*\?$/, '*');
497 }
498
499 /**
500 * Coerce `val`.
501 *
502 * @param {Mixed} val
503 * @return {Mixed}
504 * @api private
505 */
506 function coerce(val) {
507 if (val instanceof Error) {
508 return val.stack || val.message;
509 }
510 return val;
511 }
512
513 createDebug.enable(createDebug.load());
514
515 return createDebug;
516}
517
518var common = setup;
519
520var node = createCommonjsModule(function (module, exports) {
521/**
522 * Module dependencies.
523 */
524
525
526
527
528/**
529 * This is the Node.js implementation of `debug()`.
530 */
531
532exports.init = init;
533exports.log = log;
534exports.formatArgs = formatArgs;
535exports.save = save;
536exports.load = load;
537exports.useColors = useColors;
538
539/**
540 * Colors.
541 */
542
543exports.colors = [6, 2, 3, 4, 5, 1];
544
545try {
546 // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)
547 // eslint-disable-next-line import/no-extraneous-dependencies
548 const supportsColor$1 = supportsColor;
549
550 if (supportsColor$1 && (supportsColor$1.stderr || supportsColor$1).level >= 2) {
551 exports.colors = [
552 20,
553 21,
554 26,
555 27,
556 32,
557 33,
558 38,
559 39,
560 40,
561 41,
562 42,
563 43,
564 44,
565 45,
566 56,
567 57,
568 62,
569 63,
570 68,
571 69,
572 74,
573 75,
574 76,
575 77,
576 78,
577 79,
578 80,
579 81,
580 92,
581 93,
582 98,
583 99,
584 112,
585 113,
586 128,
587 129,
588 134,
589 135,
590 148,
591 149,
592 160,
593 161,
594 162,
595 163,
596 164,
597 165,
598 166,
599 167,
600 168,
601 169,
602 170,
603 171,
604 172,
605 173,
606 178,
607 179,
608 184,
609 185,
610 196,
611 197,
612 198,
613 199,
614 200,
615 201,
616 202,
617 203,
618 204,
619 205,
620 206,
621 207,
622 208,
623 209,
624 214,
625 215,
626 220,
627 221
628 ];
629 }
630} catch (error) {
631 // Swallow - we only care if `supports-color` is available; it doesn't have to be.
632}
633
634/**
635 * Build up the default `inspectOpts` object from the environment variables.
636 *
637 * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
638 */
639
640exports.inspectOpts = Object.keys(process.env).filter(key => {
641 return /^debug_/i.test(key);
642}).reduce((obj, key) => {
643 // Camel-case
644 const prop = key
645 .substring(6)
646 .toLowerCase()
647 .replace(/_([a-z])/g, (_, k) => {
648 return k.toUpperCase();
649 });
650
651 // Coerce string value into JS value
652 let val = process.env[key];
653 if (/^(yes|on|true|enabled)$/i.test(val)) {
654 val = true;
655 } else if (/^(no|off|false|disabled)$/i.test(val)) {
656 val = false;
657 } else if (val === 'null') {
658 val = null;
659 } else {
660 val = Number(val);
661 }
662
663 obj[prop] = val;
664 return obj;
665}, {});
666
667/**
668 * Is stdout a TTY? Colored output is enabled when `true`.
669 */
670
671function useColors() {
672 return 'colors' in exports.inspectOpts ?
673 Boolean(exports.inspectOpts.colors) :
674 tty.isatty(process.stderr.fd);
675}
676
677/**
678 * Adds ANSI color escape codes if enabled.
679 *
680 * @api public
681 */
682
683function formatArgs(args) {
684 const {namespace: name, useColors} = this;
685
686 if (useColors) {
687 const c = this.color;
688 const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c);
689 const prefix = ` ${colorCode};1m${name} \u001B[0m`;
690
691 args[0] = prefix + args[0].split('\n').join('\n' + prefix);
692 args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m');
693 } else {
694 args[0] = getDate() + name + ' ' + args[0];
695 }
696}
697
698function getDate() {
699 if (exports.inspectOpts.hideDate) {
700 return '';
701 }
702 return new Date().toISOString() + ' ';
703}
704
705/**
706 * Invokes `util.format()` with the specified arguments and writes to stderr.
707 */
708
709function log(...args) {
710 return process.stderr.write(util.format(...args) + '\n');
711}
712
713/**
714 * Save `namespaces`.
715 *
716 * @param {String} namespaces
717 * @api private
718 */
719function save(namespaces) {
720 if (namespaces) {
721 process.env.DEBUG = namespaces;
722 } else {
723 // If you set a process.env field to null or undefined, it gets cast to the
724 // string 'null' or 'undefined'. Just delete instead.
725 delete process.env.DEBUG;
726 }
727}
728
729/**
730 * Load `namespaces`.
731 *
732 * @return {String} returns the previously persisted debug modes
733 * @api private
734 */
735
736function load() {
737 return process.env.DEBUG;
738}
739
740/**
741 * Init logic for `debug` instances.
742 *
743 * Create a new `inspectOpts` object in case `useColors` is set
744 * differently for a particular `debug` instance.
745 */
746
747function init(debug) {
748 debug.inspectOpts = {};
749
750 const keys = Object.keys(exports.inspectOpts);
751 for (let i = 0; i < keys.length; i++) {
752 debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
753 }
754}
755
756module.exports = common(exports);
757
758const {formatters} = module.exports;
759
760/**
761 * Map %o to `util.inspect()`, all on a single line.
762 */
763
764formatters.o = function (v) {
765 this.inspectOpts.colors = this.useColors;
766 return util.inspect(v, this.inspectOpts)
767 .replace(/\s*\n\s*/g, ' ');
768};
769
770/**
771 * Map %O to `util.inspect()`, allowing multiple lines if needed.
772 */
773
774formatters.O = function (v) {
775 this.inspectOpts.colors = this.useColors;
776 return util.inspect(v, this.inspectOpts);
777};
778});
779var node_1 = node.init;
780var node_2 = node.log;
781var node_3 = node.formatArgs;
782var node_4 = node.save;
783var node_5 = node.load;
784var node_6 = node.useColors;
785var node_7 = node.colors;
786var node_8 = node.inspectOpts;
787
788// Returns a wrapper function that returns a wrapped callback
789// The wrapper function should do some stuff, and return a
790// presumably different callback function.
791// This makes sure that own properties are retained, so that
792// decorations and such are not lost along the way.
793var wrappy_1 = wrappy;
794function wrappy (fn, cb) {
795 if (fn && cb) return wrappy(fn)(cb)
796
797 if (typeof fn !== 'function')
798 throw new TypeError('need wrapper function')
799
800 Object.keys(fn).forEach(function (k) {
801 wrapper[k] = fn[k];
802 });
803
804 return wrapper
805
806 function wrapper() {
807 var args = new Array(arguments.length);
808 for (var i = 0; i < args.length; i++) {
809 args[i] = arguments[i];
810 }
811 var ret = fn.apply(this, args);
812 var cb = args[args.length-1];
813 if (typeof ret === 'function' && ret !== cb) {
814 Object.keys(cb).forEach(function (k) {
815 ret[k] = cb[k];
816 });
817 }
818 return ret
819 }
820}
821
822var once_1 = wrappy_1(once);
823var strict = wrappy_1(onceStrict);
824
825once.proto = once(function () {
826 Object.defineProperty(Function.prototype, 'once', {
827 value: function () {
828 return once(this)
829 },
830 configurable: true
831 });
832
833 Object.defineProperty(Function.prototype, 'onceStrict', {
834 value: function () {
835 return onceStrict(this)
836 },
837 configurable: true
838 });
839});
840
841function once (fn) {
842 var f = function () {
843 if (f.called) return f.value
844 f.called = true;
845 return f.value = fn.apply(this, arguments)
846 };
847 f.called = false;
848 return f
849}
850
851function onceStrict (fn) {
852 var f = function () {
853 if (f.called)
854 throw new Error(f.onceError)
855 f.called = true;
856 return f.value = fn.apply(this, arguments)
857 };
858 var name = fn.name || 'Function wrapped with `once`';
859 f.onceError = name + " shouldn't be called more than once";
860 f.called = false;
861 return f
862}
863once_1.strict = strict;
864
865var noop = function() {};
866
867var isRequest = function(stream) {
868 return stream.setHeader && typeof stream.abort === 'function';
869};
870
871var isChildProcess = function(stream) {
872 return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3
873};
874
875var eos = function(stream, opts, callback) {
876 if (typeof opts === 'function') return eos(stream, null, opts);
877 if (!opts) opts = {};
878
879 callback = once_1(callback || noop);
880
881 var ws = stream._writableState;
882 var rs = stream._readableState;
883 var readable = opts.readable || (opts.readable !== false && stream.readable);
884 var writable = opts.writable || (opts.writable !== false && stream.writable);
885
886 var onlegacyfinish = function() {
887 if (!stream.writable) onfinish();
888 };
889
890 var onfinish = function() {
891 writable = false;
892 if (!readable) callback.call(stream);
893 };
894
895 var onend = function() {
896 readable = false;
897 if (!writable) callback.call(stream);
898 };
899
900 var onexit = function(exitCode) {
901 callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null);
902 };
903
904 var onerror = function(err) {
905 callback.call(stream, err);
906 };
907
908 var onclose = function() {
909 if (readable && !(rs && rs.ended)) return callback.call(stream, new Error('premature close'));
910 if (writable && !(ws && ws.ended)) return callback.call(stream, new Error('premature close'));
911 };
912
913 var onrequest = function() {
914 stream.req.on('finish', onfinish);
915 };
916
917 if (isRequest(stream)) {
918 stream.on('complete', onfinish);
919 stream.on('abort', onclose);
920 if (stream.req) onrequest();
921 else stream.on('request', onrequest);
922 } else if (writable && !ws) { // legacy streams
923 stream.on('end', onlegacyfinish);
924 stream.on('close', onlegacyfinish);
925 }
926
927 if (isChildProcess(stream)) stream.on('exit', onexit);
928
929 stream.on('end', onend);
930 stream.on('finish', onfinish);
931 if (opts.error !== false) stream.on('error', onerror);
932 stream.on('close', onclose);
933
934 return function() {
935 stream.removeListener('complete', onfinish);
936 stream.removeListener('abort', onclose);
937 stream.removeListener('request', onrequest);
938 if (stream.req) stream.req.removeListener('finish', onfinish);
939 stream.removeListener('end', onlegacyfinish);
940 stream.removeListener('close', onlegacyfinish);
941 stream.removeListener('finish', onfinish);
942 stream.removeListener('exit', onexit);
943 stream.removeListener('end', onend);
944 stream.removeListener('error', onerror);
945 stream.removeListener('close', onclose);
946 };
947};
948
949var endOfStream = eos;
950
951// we only need fs to get the ReadStream and WriteStream prototypes
952
953var noop$1 = function () {};
954var ancient = /^v?\.0/.test(process.version);
955
956var isFn = function (fn) {
957 return typeof fn === 'function'
958};
959
960var isFS = function (stream) {
961 if (!ancient) return false // newer node version do not need to care about fs is a special way
962 if (!fs) return false // browser
963 return (stream instanceof (fs.ReadStream || noop$1) || stream instanceof (fs.WriteStream || noop$1)) && isFn(stream.close)
964};
965
966var isRequest$1 = function (stream) {
967 return stream.setHeader && isFn(stream.abort)
968};
969
970var destroyer = function (stream, reading, writing, callback) {
971 callback = once_1(callback);
972
973 var closed = false;
974 stream.on('close', function () {
975 closed = true;
976 });
977
978 endOfStream(stream, {readable: reading, writable: writing}, function (err) {
979 if (err) return callback(err)
980 closed = true;
981 callback();
982 });
983
984 var destroyed = false;
985 return function (err) {
986 if (closed) return
987 if (destroyed) return
988 destroyed = true;
989
990 if (isFS(stream)) return stream.close(noop$1) // use close for fs streams to avoid fd leaks
991 if (isRequest$1(stream)) return stream.abort() // request.destroy just do .end - .abort is what we want
992
993 if (isFn(stream.destroy)) return stream.destroy()
994
995 callback(err || new Error('stream was destroyed'));
996 }
997};
998
999var call = function (fn) {
1000 fn();
1001};
1002
1003var pipe = function (from, to) {
1004 return from.pipe(to)
1005};
1006
1007var pump = function () {
1008 var streams = Array.prototype.slice.call(arguments);
1009 var callback = isFn(streams[streams.length - 1] || noop$1) && streams.pop() || noop$1;
1010
1011 if (Array.isArray(streams[0])) streams = streams[0];
1012 if (streams.length < 2) throw new Error('pump requires two streams per minimum')
1013
1014 var error;
1015 var destroys = streams.map(function (stream, i) {
1016 var reading = i < streams.length - 1;
1017 var writing = i > 0;
1018 return destroyer(stream, reading, writing, function (err) {
1019 if (!error) error = err;
1020 if (err) destroys.forEach(call);
1021 if (reading) return
1022 destroys.forEach(call);
1023 callback(error);
1024 })
1025 });
1026
1027 return streams.reduce(pipe)
1028};
1029
1030var pump_1 = pump;
1031
1032var streamShift = shift;
1033
1034function shift (stream) {
1035 var rs = stream._readableState;
1036 if (!rs) return null
1037 return rs.objectMode ? stream.read() : stream.read(getStateLength(rs))
1038}
1039
1040function getStateLength (state) {
1041 if (state.buffer.length) {
1042 // Since node 6.3.0 state.buffer is a BufferList not an array
1043 if (state.buffer.head) {
1044 return state.buffer.head.data.length
1045 }
1046
1047 return state.buffer[0].length
1048 }
1049
1050 return state.length
1051}
1052
1053var streamEach = each;
1054
1055function each (stream, fn, cb) {
1056 var want = true;
1057 var error = null;
1058 var ended = false;
1059 var running = false;
1060 var calling = false;
1061
1062 stream.on('readable', onreadable);
1063 onreadable();
1064
1065 if (cb) endOfStream(stream, {readable: true, writable: false}, done);
1066 return stream
1067
1068 function done (err) {
1069 if (!error) error = err;
1070 ended = true;
1071 if (!running) cb(error);
1072 }
1073
1074 function onreadable () {
1075 if (want) read();
1076 }
1077
1078 function afterRead (err) {
1079 running = false;
1080
1081 if (err) {
1082 error = err;
1083 if (ended) return cb(error)
1084 stream.destroy(err);
1085 return
1086 }
1087 if (ended) return cb(error)
1088 if (!calling) read();
1089 }
1090
1091 function read () {
1092 while (!running && !ended) {
1093 want = false;
1094
1095 var data = streamShift(stream);
1096 if (ended) return
1097 if (data === null) {
1098 want = true;
1099 return
1100 }
1101
1102 running = true;
1103 calling = true;
1104 fn(data, afterRead);
1105 calling = false;
1106 }
1107 }
1108}
1109
1110// we only need fs to get the ReadStream and WriteStream prototypes
1111
1112var noop$2 = function () {};
1113var ancient$1 = /^v?\.0/.test(process.version);
1114
1115var isFn$1 = function (fn) {
1116 return typeof fn === 'function'
1117};
1118
1119var isFS$1 = function (stream) {
1120 if (!ancient$1) return false // newer node version do not need to care about fs is a special way
1121 if (!fs) return false // browser
1122 return (stream instanceof (fs.ReadStream || noop$2) || stream instanceof (fs.WriteStream || noop$2)) && isFn$1(stream.close)
1123};
1124
1125var isRequest$2 = function (stream) {
1126 return stream.setHeader && isFn$1(stream.abort)
1127};
1128
1129var destroyer$1 = function (stream, reading, writing, callback) {
1130 callback = once_1(callback);
1131
1132 var closed = false;
1133 stream.on('close', function () {
1134 closed = true;
1135 });
1136
1137 endOfStream(stream, {readable: reading, writable: writing}, function (err) {
1138 if (err) return callback(err)
1139 closed = true;
1140 callback();
1141 });
1142
1143 var destroyed = false;
1144 return function (err) {
1145 if (closed) return
1146 if (destroyed) return
1147 destroyed = true;
1148
1149 if (isFS$1(stream)) return stream.close(noop$2) // use close for fs streams to avoid fd leaks
1150 if (isRequest$2(stream)) return stream.abort() // request.destroy just do .end - .abort is what we want
1151
1152 if (isFn$1(stream.destroy)) return stream.destroy()
1153
1154 callback(err || new Error('stream was destroyed'));
1155 }
1156};
1157
1158var call$1 = function (fn) {
1159 fn();
1160};
1161
1162var pipe$1 = function (from, to) {
1163 return from.pipe(to)
1164};
1165
1166var pump$1 = function () {
1167 var streams = Array.prototype.slice.call(arguments);
1168 var callback = isFn$1(streams[streams.length - 1] || noop$2) && streams.pop() || noop$2;
1169
1170 if (Array.isArray(streams[0])) streams = streams[0];
1171 if (streams.length < 2) throw new Error('pump requires two streams per minimum')
1172
1173 var error;
1174 var destroys = streams.map(function (stream, i) {
1175 var reading = i < streams.length - 1;
1176 var writing = i > 0;
1177 return destroyer$1(stream, reading, writing, function (err) {
1178 if (!error) error = err;
1179 if (err) destroys.forEach(call$1);
1180 if (reading) return
1181 destroys.forEach(call$1);
1182 callback(error);
1183 })
1184 });
1185
1186 streams.reduce(pipe$1);
1187};
1188
1189var pump_1$1 = pump$1;
1190
1191var inherits_browser = createCommonjsModule(function (module) {
1192if (typeof Object.create === 'function') {
1193 // implementation from standard node.js 'util' module
1194 module.exports = function inherits(ctor, superCtor) {
1195 ctor.super_ = superCtor;
1196 ctor.prototype = Object.create(superCtor.prototype, {
1197 constructor: {
1198 value: ctor,
1199 enumerable: false,
1200 writable: true,
1201 configurable: true
1202 }
1203 });
1204 };
1205} else {
1206 // old school shim for old browsers
1207 module.exports = function inherits(ctor, superCtor) {
1208 ctor.super_ = superCtor;
1209 var TempCtor = function () {};
1210 TempCtor.prototype = superCtor.prototype;
1211 ctor.prototype = new TempCtor();
1212 ctor.prototype.constructor = ctor;
1213 };
1214}
1215});
1216
1217var inherits = createCommonjsModule(function (module) {
1218try {
1219 var util$1 = util;
1220 if (typeof util$1.inherits !== 'function') throw '';
1221 module.exports = util$1.inherits;
1222} catch (e) {
1223 module.exports = inherits_browser;
1224}
1225});
1226
1227var SIGNAL_FLUSH = (Buffer.from && Buffer.from !== Uint8Array.from)
1228 ? Buffer.from([0])
1229 : new Buffer([0]);
1230
1231var onuncork = function(self, fn) {
1232 if (self._corked) self.once('uncork', fn);
1233 else fn();
1234};
1235
1236var autoDestroy = function (self, err) {
1237 if (self._autoDestroy) self.destroy(err);
1238};
1239
1240var destroyer$2 = function(self, end) {
1241 return function(err) {
1242 if (err) autoDestroy(self, err.message === 'premature close' ? null : err);
1243 else if (end && !self._ended) self.end();
1244 }
1245};
1246
1247var end = function(ws, fn) {
1248 if (!ws) return fn()
1249 if (ws._writableState && ws._writableState.finished) return fn()
1250 if (ws._writableState) return ws.end(fn)
1251 ws.end();
1252 fn();
1253};
1254
1255var toStreams2 = function(rs) {
1256 return new (readableStream.Readable)({objectMode:true, highWaterMark:16}).wrap(rs)
1257};
1258
1259var Duplexify = function(writable, readable, opts) {
1260 if (!(this instanceof Duplexify)) return new Duplexify(writable, readable, opts)
1261 readableStream.Duplex.call(this, opts);
1262
1263 this._writable = null;
1264 this._readable = null;
1265 this._readable2 = null;
1266
1267 this._autoDestroy = !opts || opts.autoDestroy !== false;
1268 this._forwardDestroy = !opts || opts.destroy !== false;
1269 this._forwardEnd = !opts || opts.end !== false;
1270 this._corked = 1; // start corked
1271 this._ondrain = null;
1272 this._drained = false;
1273 this._forwarding = false;
1274 this._unwrite = null;
1275 this._unread = null;
1276 this._ended = false;
1277
1278 this.destroyed = false;
1279
1280 if (writable) this.setWritable(writable);
1281 if (readable) this.setReadable(readable);
1282};
1283
1284inherits(Duplexify, readableStream.Duplex);
1285
1286Duplexify.obj = function(writable, readable, opts) {
1287 if (!opts) opts = {};
1288 opts.objectMode = true;
1289 opts.highWaterMark = 16;
1290 return new Duplexify(writable, readable, opts)
1291};
1292
1293Duplexify.prototype.cork = function() {
1294 if (++this._corked === 1) this.emit('cork');
1295};
1296
1297Duplexify.prototype.uncork = function() {
1298 if (this._corked && --this._corked === 0) this.emit('uncork');
1299};
1300
1301Duplexify.prototype.setWritable = function(writable) {
1302 if (this._unwrite) this._unwrite();
1303
1304 if (this.destroyed) {
1305 if (writable && writable.destroy) writable.destroy();
1306 return
1307 }
1308
1309 if (writable === null || writable === false) {
1310 this.end();
1311 return
1312 }
1313
1314 var self = this;
1315 var unend = endOfStream(writable, {writable:true, readable:false}, destroyer$2(this, this._forwardEnd));
1316
1317 var ondrain = function() {
1318 var ondrain = self._ondrain;
1319 self._ondrain = null;
1320 if (ondrain) ondrain();
1321 };
1322
1323 var clear = function() {
1324 self._writable.removeListener('drain', ondrain);
1325 unend();
1326 };
1327
1328 if (this._unwrite) process.nextTick(ondrain); // force a drain on stream reset to avoid livelocks
1329
1330 this._writable = writable;
1331 this._writable.on('drain', ondrain);
1332 this._unwrite = clear;
1333
1334 this.uncork(); // always uncork setWritable
1335};
1336
1337Duplexify.prototype.setReadable = function(readable) {
1338 if (this._unread) this._unread();
1339
1340 if (this.destroyed) {
1341 if (readable && readable.destroy) readable.destroy();
1342 return
1343 }
1344
1345 if (readable === null || readable === false) {
1346 this.push(null);
1347 this.resume();
1348 return
1349 }
1350
1351 var self = this;
1352 var unend = endOfStream(readable, {writable:false, readable:true}, destroyer$2(this));
1353
1354 var onreadable = function() {
1355 self._forward();
1356 };
1357
1358 var onend = function() {
1359 self.push(null);
1360 };
1361
1362 var clear = function() {
1363 self._readable2.removeListener('readable', onreadable);
1364 self._readable2.removeListener('end', onend);
1365 unend();
1366 };
1367
1368 this._drained = true;
1369 this._readable = readable;
1370 this._readable2 = readable._readableState ? readable : toStreams2(readable);
1371 this._readable2.on('readable', onreadable);
1372 this._readable2.on('end', onend);
1373 this._unread = clear;
1374
1375 this._forward();
1376};
1377
1378Duplexify.prototype._read = function() {
1379 this._drained = true;
1380 this._forward();
1381};
1382
1383Duplexify.prototype._forward = function() {
1384 if (this._forwarding || !this._readable2 || !this._drained) return
1385 this._forwarding = true;
1386
1387 var data;
1388
1389 while (this._drained && (data = streamShift(this._readable2)) !== null) {
1390 if (this.destroyed) continue
1391 this._drained = this.push(data);
1392 }
1393
1394 this._forwarding = false;
1395};
1396
1397Duplexify.prototype.destroy = function(err) {
1398 if (this.destroyed) return
1399 this.destroyed = true;
1400
1401 var self = this;
1402 process.nextTick(function() {
1403 self._destroy(err);
1404 });
1405};
1406
1407Duplexify.prototype._destroy = function(err) {
1408 if (err) {
1409 var ondrain = this._ondrain;
1410 this._ondrain = null;
1411 if (ondrain) ondrain(err);
1412 else this.emit('error', err);
1413 }
1414
1415 if (this._forwardDestroy) {
1416 if (this._readable && this._readable.destroy) this._readable.destroy();
1417 if (this._writable && this._writable.destroy) this._writable.destroy();
1418 }
1419
1420 this.emit('close');
1421};
1422
1423Duplexify.prototype._write = function(data, enc, cb) {
1424 if (this.destroyed) return cb()
1425 if (this._corked) return onuncork(this, this._write.bind(this, data, enc, cb))
1426 if (data === SIGNAL_FLUSH) return this._finish(cb)
1427 if (!this._writable) return cb()
1428
1429 if (this._writable.write(data) === false) this._ondrain = cb;
1430 else cb();
1431};
1432
1433Duplexify.prototype._finish = function(cb) {
1434 var self = this;
1435 this.emit('preend');
1436 onuncork(this, function() {
1437 end(self._forwardEnd && self._writable, function() {
1438 // haxx to not emit prefinish twice
1439 if (self._writableState.prefinished === false) self._writableState.prefinished = true;
1440 self.emit('prefinish');
1441 onuncork(self, cb);
1442 });
1443 });
1444};
1445
1446Duplexify.prototype.end = function(data, enc, cb) {
1447 if (typeof data === 'function') return this.end(null, null, data)
1448 if (typeof enc === 'function') return this.end(data, null, enc)
1449 this._ended = true;
1450 if (data) this.write(data);
1451 if (!this._writableState.ending) this.write(SIGNAL_FLUSH);
1452 return readableStream.Writable.prototype.end.call(this, cb)
1453};
1454
1455var duplexify = Duplexify;
1456
1457var toArray = function(args) {
1458 if (!args.length) return []
1459 return Array.isArray(args[0]) ? args[0] : Array.prototype.slice.call(args)
1460};
1461
1462var define = function(opts) {
1463 var Pumpify = function() {
1464 var streams = toArray(arguments);
1465 if (!(this instanceof Pumpify)) return new Pumpify(streams)
1466 duplexify.call(this, null, null, opts);
1467 if (streams.length) this.setPipeline(streams);
1468 };
1469
1470 inherits(Pumpify, duplexify);
1471
1472 Pumpify.prototype.setPipeline = function() {
1473 var streams = toArray(arguments);
1474 var self = this;
1475 var ended = false;
1476 var w = streams[0];
1477 var r = streams[streams.length-1];
1478
1479 r = r.readable ? r : null;
1480 w = w.writable ? w : null;
1481
1482 var onclose = function() {
1483 streams[0].emit('error', new Error('stream was destroyed'));
1484 };
1485
1486 this.on('close', onclose);
1487 this.on('prefinish', function() {
1488 if (!ended) self.cork();
1489 });
1490
1491 pump_1$1(streams, function(err) {
1492 self.removeListener('close', onclose);
1493 if (err) return self.destroy(err.message === 'premature close' ? null : err)
1494 ended = true;
1495 // pump ends after the last stream is not writable *but*
1496 // pumpify still forwards the readable part so we need to catch errors
1497 // still, so reenable autoDestroy in this case
1498 if (self._autoDestroy === false) self._autoDestroy = true;
1499 self.uncork();
1500 });
1501
1502 if (this.destroyed) return onclose()
1503 this.setWritable(w);
1504 this.setReadable(r);
1505 };
1506
1507 return Pumpify
1508};
1509
1510var pumpify = define({autoDestroy:false, destroy:false});
1511var obj = define({autoDestroy: false, destroy:false, objectMode:true, highWaterMark:16});
1512var ctor = define;
1513pumpify.obj = obj;
1514pumpify.ctor = ctor;
1515
1516var SIGNAL_FLUSH$1 = (Buffer.from && Buffer.from !== Uint8Array.from)
1517 ? Buffer.from([0])
1518 : new Buffer([0]);
1519
1520var onuncork$1 = function(self, fn) {
1521 if (self._corked) self.once('uncork', fn);
1522 else fn();
1523};
1524
1525var autoDestroy$1 = function (self, err) {
1526 if (self._autoDestroy) self.destroy(err);
1527};
1528
1529var destroyer$3 = function(self, end) {
1530 return function(err) {
1531 if (err) autoDestroy$1(self, err.message === 'premature close' ? null : err);
1532 else if (end && !self._ended) self.end();
1533 }
1534};
1535
1536var end$1 = function(ws, fn) {
1537 if (!ws) return fn()
1538 if (ws._writableState && ws._writableState.finished) return fn()
1539 if (ws._writableState) return ws.end(fn)
1540 ws.end();
1541 fn();
1542};
1543
1544var toStreams2$1 = function(rs) {
1545 return new (readableStream.Readable)({objectMode:true, highWaterMark:16}).wrap(rs)
1546};
1547
1548var Duplexify$1 = function(writable, readable, opts) {
1549 if (!(this instanceof Duplexify$1)) return new Duplexify$1(writable, readable, opts)
1550 readableStream.Duplex.call(this, opts);
1551
1552 this._writable = null;
1553 this._readable = null;
1554 this._readable2 = null;
1555
1556 this._autoDestroy = !opts || opts.autoDestroy !== false;
1557 this._forwardDestroy = !opts || opts.destroy !== false;
1558 this._forwardEnd = !opts || opts.end !== false;
1559 this._corked = 1; // start corked
1560 this._ondrain = null;
1561 this._drained = false;
1562 this._forwarding = false;
1563 this._unwrite = null;
1564 this._unread = null;
1565 this._ended = false;
1566
1567 this.destroyed = false;
1568
1569 if (writable) this.setWritable(writable);
1570 if (readable) this.setReadable(readable);
1571};
1572
1573inherits(Duplexify$1, readableStream.Duplex);
1574
1575Duplexify$1.obj = function(writable, readable, opts) {
1576 if (!opts) opts = {};
1577 opts.objectMode = true;
1578 opts.highWaterMark = 16;
1579 return new Duplexify$1(writable, readable, opts)
1580};
1581
1582Duplexify$1.prototype.cork = function() {
1583 if (++this._corked === 1) this.emit('cork');
1584};
1585
1586Duplexify$1.prototype.uncork = function() {
1587 if (this._corked && --this._corked === 0) this.emit('uncork');
1588};
1589
1590Duplexify$1.prototype.setWritable = function(writable) {
1591 if (this._unwrite) this._unwrite();
1592
1593 if (this.destroyed) {
1594 if (writable && writable.destroy) writable.destroy();
1595 return
1596 }
1597
1598 if (writable === null || writable === false) {
1599 this.end();
1600 return
1601 }
1602
1603 var self = this;
1604 var unend = endOfStream(writable, {writable:true, readable:false}, destroyer$3(this, this._forwardEnd));
1605
1606 var ondrain = function() {
1607 var ondrain = self._ondrain;
1608 self._ondrain = null;
1609 if (ondrain) ondrain();
1610 };
1611
1612 var clear = function() {
1613 self._writable.removeListener('drain', ondrain);
1614 unend();
1615 };
1616
1617 if (this._unwrite) process.nextTick(ondrain); // force a drain on stream reset to avoid livelocks
1618
1619 this._writable = writable;
1620 this._writable.on('drain', ondrain);
1621 this._unwrite = clear;
1622
1623 this.uncork(); // always uncork setWritable
1624};
1625
1626Duplexify$1.prototype.setReadable = function(readable) {
1627 if (this._unread) this._unread();
1628
1629 if (this.destroyed) {
1630 if (readable && readable.destroy) readable.destroy();
1631 return
1632 }
1633
1634 if (readable === null || readable === false) {
1635 this.push(null);
1636 this.resume();
1637 return
1638 }
1639
1640 var self = this;
1641 var unend = endOfStream(readable, {writable:false, readable:true}, destroyer$3(this));
1642
1643 var onreadable = function() {
1644 self._forward();
1645 };
1646
1647 var onend = function() {
1648 self.push(null);
1649 };
1650
1651 var clear = function() {
1652 self._readable2.removeListener('readable', onreadable);
1653 self._readable2.removeListener('end', onend);
1654 unend();
1655 };
1656
1657 this._drained = true;
1658 this._readable = readable;
1659 this._readable2 = readable._readableState ? readable : toStreams2$1(readable);
1660 this._readable2.on('readable', onreadable);
1661 this._readable2.on('end', onend);
1662 this._unread = clear;
1663
1664 this._forward();
1665};
1666
1667Duplexify$1.prototype._read = function() {
1668 this._drained = true;
1669 this._forward();
1670};
1671
1672Duplexify$1.prototype._forward = function() {
1673 if (this._forwarding || !this._readable2 || !this._drained) return
1674 this._forwarding = true;
1675
1676 var data;
1677
1678 while (this._drained && (data = streamShift(this._readable2)) !== null) {
1679 if (this.destroyed) continue
1680 this._drained = this.push(data);
1681 }
1682
1683 this._forwarding = false;
1684};
1685
1686Duplexify$1.prototype.destroy = function(err) {
1687 if (this.destroyed) return
1688 this.destroyed = true;
1689
1690 var self = this;
1691 process.nextTick(function() {
1692 self._destroy(err);
1693 });
1694};
1695
1696Duplexify$1.prototype._destroy = function(err) {
1697 if (err) {
1698 var ondrain = this._ondrain;
1699 this._ondrain = null;
1700 if (ondrain) ondrain(err);
1701 else this.emit('error', err);
1702 }
1703
1704 if (this._forwardDestroy) {
1705 if (this._readable && this._readable.destroy) this._readable.destroy();
1706 if (this._writable && this._writable.destroy) this._writable.destroy();
1707 }
1708
1709 this.emit('close');
1710};
1711
1712Duplexify$1.prototype._write = function(data, enc, cb) {
1713 if (this.destroyed) return cb()
1714 if (this._corked) return onuncork$1(this, this._write.bind(this, data, enc, cb))
1715 if (data === SIGNAL_FLUSH$1) return this._finish(cb)
1716 if (!this._writable) return cb()
1717
1718 if (this._writable.write(data) === false) this._ondrain = cb;
1719 else cb();
1720};
1721
1722Duplexify$1.prototype._finish = function(cb) {
1723 var self = this;
1724 this.emit('preend');
1725 onuncork$1(this, function() {
1726 end$1(self._forwardEnd && self._writable, function() {
1727 // haxx to not emit prefinish twice
1728 if (self._writableState.prefinished === false) self._writableState.prefinished = true;
1729 self.emit('prefinish');
1730 onuncork$1(self, cb);
1731 });
1732 });
1733};
1734
1735Duplexify$1.prototype.end = function(data, enc, cb) {
1736 if (typeof data === 'function') return this.end(null, null, data)
1737 if (typeof enc === 'function') return this.end(data, null, enc)
1738 this._ended = true;
1739 if (data) this.write(data);
1740 if (!this._writableState.ending) this.write(SIGNAL_FLUSH$1);
1741 return readableStream.Writable.prototype.end.call(this, cb)
1742};
1743
1744var duplexify$1 = Duplexify$1;
1745
1746var Transform = readableStream.Transform
1747 , inherits$1 = util.inherits;
1748
1749function DestroyableTransform(opts) {
1750 Transform.call(this, opts);
1751 this._destroyed = false;
1752}
1753
1754inherits$1(DestroyableTransform, Transform);
1755
1756DestroyableTransform.prototype.destroy = function(err) {
1757 if (this._destroyed) return
1758 this._destroyed = true;
1759
1760 var self = this;
1761 process.nextTick(function() {
1762 if (err)
1763 self.emit('error', err);
1764 self.emit('close');
1765 });
1766};
1767
1768// a noop _transform function
1769function noop$3 (chunk, enc, callback) {
1770 callback(null, chunk);
1771}
1772
1773
1774// create a new export function, used by both the main export and
1775// the .ctor export, contains common logic for dealing with arguments
1776function through2 (construct) {
1777 return function (options, transform, flush) {
1778 if (typeof options == 'function') {
1779 flush = transform;
1780 transform = options;
1781 options = {};
1782 }
1783
1784 if (typeof transform != 'function')
1785 transform = noop$3;
1786
1787 if (typeof flush != 'function')
1788 flush = null;
1789
1790 return construct(options, transform, flush)
1791 }
1792}
1793
1794
1795// main export, just make me a transform stream!
1796var through2_1 = through2(function (options, transform, flush) {
1797 var t2 = new DestroyableTransform(options);
1798
1799 t2._transform = transform;
1800
1801 if (flush)
1802 t2._flush = flush;
1803
1804 return t2
1805});
1806
1807
1808// make me a reusable prototype that I can `new`, or implicitly `new`
1809// with a constructor call
1810var ctor$1 = through2(function (options, transform, flush) {
1811 function Through2 (override) {
1812 if (!(this instanceof Through2))
1813 return new Through2(override)
1814
1815 this.options = Object.assign({}, options, override);
1816
1817 DestroyableTransform.call(this, this.options);
1818 }
1819
1820 inherits$1(Through2, DestroyableTransform);
1821
1822 Through2.prototype._transform = transform;
1823
1824 if (flush)
1825 Through2.prototype._flush = flush;
1826
1827 return Through2
1828});
1829
1830
1831var obj$1 = through2(function (options, transform, flush) {
1832 var t2 = new DestroyableTransform(Object.assign({ objectMode: true, highWaterMark: 16 }, options));
1833
1834 t2._transform = transform;
1835
1836 if (flush)
1837 t2._flush = flush;
1838
1839 return t2
1840});
1841through2_1.ctor = ctor$1;
1842through2_1.obj = obj$1;
1843
1844var toString = Object.prototype.toString;
1845
1846var isModern = (
1847 typeof Buffer.alloc === 'function' &&
1848 typeof Buffer.allocUnsafe === 'function' &&
1849 typeof Buffer.from === 'function'
1850);
1851
1852function isArrayBuffer (input) {
1853 return toString.call(input).slice(8, -1) === 'ArrayBuffer'
1854}
1855
1856function fromArrayBuffer (obj, byteOffset, length) {
1857 byteOffset >>>= 0;
1858
1859 var maxLength = obj.byteLength - byteOffset;
1860
1861 if (maxLength < 0) {
1862 throw new RangeError("'offset' is out of bounds")
1863 }
1864
1865 if (length === undefined) {
1866 length = maxLength;
1867 } else {
1868 length >>>= 0;
1869
1870 if (length > maxLength) {
1871 throw new RangeError("'length' is out of bounds")
1872 }
1873 }
1874
1875 return isModern
1876 ? Buffer.from(obj.slice(byteOffset, byteOffset + length))
1877 : new Buffer(new Uint8Array(obj.slice(byteOffset, byteOffset + length)))
1878}
1879
1880function fromString (string, encoding) {
1881 if (typeof encoding !== 'string' || encoding === '') {
1882 encoding = 'utf8';
1883 }
1884
1885 if (!Buffer.isEncoding(encoding)) {
1886 throw new TypeError('"encoding" must be a valid string encoding')
1887 }
1888
1889 return isModern
1890 ? Buffer.from(string, encoding)
1891 : new Buffer(string, encoding)
1892}
1893
1894function bufferFrom (value, encodingOrOffset, length) {
1895 if (typeof value === 'number') {
1896 throw new TypeError('"value" argument must not be a number')
1897 }
1898
1899 if (isArrayBuffer(value)) {
1900 return fromArrayBuffer(value, encodingOrOffset, length)
1901 }
1902
1903 if (typeof value === 'string') {
1904 return fromString(value, encodingOrOffset)
1905 }
1906
1907 return isModern
1908 ? Buffer.from(value)
1909 : new Buffer(value)
1910}
1911
1912var bufferFrom_1 = bufferFrom;
1913
1914var typedarray = createCommonjsModule(function (module, exports) {
1915var undefined$1 = (void 0); // Paranoia
1916
1917// Beyond this value, index getters/setters (i.e. array[0], array[1]) are so slow to
1918// create, and consume so much memory, that the browser appears frozen.
1919var MAX_ARRAY_LENGTH = 1e5;
1920
1921// Approximations of internal ECMAScript conversion functions
1922var ECMAScript = (function() {
1923 // Stash a copy in case other scripts modify these
1924 var opts = Object.prototype.toString,
1925 ophop = Object.prototype.hasOwnProperty;
1926
1927 return {
1928 // Class returns internal [[Class]] property, used to avoid cross-frame instanceof issues:
1929 Class: function(v) { return opts.call(v).replace(/^\[object *|\]$/g, ''); },
1930 HasProperty: function(o, p) { return p in o; },
1931 HasOwnProperty: function(o, p) { return ophop.call(o, p); },
1932 IsCallable: function(o) { return typeof o === 'function'; },
1933 ToInt32: function(v) { return v >> 0; },
1934 ToUint32: function(v) { return v >>> 0; }
1935 };
1936}());
1937
1938// Snapshot intrinsics
1939var LN2 = Math.LN2,
1940 abs = Math.abs,
1941 floor = Math.floor,
1942 log = Math.log,
1943 min = Math.min,
1944 pow = Math.pow,
1945 round = Math.round;
1946
1947// ES5: lock down object properties
1948function configureProperties(obj) {
1949 if (getOwnPropNames && defineProp) {
1950 var props = getOwnPropNames(obj), i;
1951 for (i = 0; i < props.length; i += 1) {
1952 defineProp(obj, props[i], {
1953 value: obj[props[i]],
1954 writable: false,
1955 enumerable: false,
1956 configurable: false
1957 });
1958 }
1959 }
1960}
1961
1962// emulate ES5 getter/setter API using legacy APIs
1963// http://blogs.msdn.com/b/ie/archive/2010/09/07/transitioning-existing-code-to-the-es5-getter-setter-apis.aspx
1964// (second clause tests for Object.defineProperty() in IE<9 that only supports extending DOM prototypes, but
1965// note that IE<9 does not support __defineGetter__ or __defineSetter__ so it just renders the method harmless)
1966var defineProp;
1967if (Object.defineProperty && (function() {
1968 try {
1969 Object.defineProperty({}, 'x', {});
1970 return true;
1971 } catch (e) {
1972 return false;
1973 }
1974 })()) {
1975 defineProp = Object.defineProperty;
1976} else {
1977 defineProp = function(o, p, desc) {
1978 if (!o === Object(o)) throw new TypeError("Object.defineProperty called on non-object");
1979 if (ECMAScript.HasProperty(desc, 'get') && Object.prototype.__defineGetter__) { Object.prototype.__defineGetter__.call(o, p, desc.get); }
1980 if (ECMAScript.HasProperty(desc, 'set') && Object.prototype.__defineSetter__) { Object.prototype.__defineSetter__.call(o, p, desc.set); }
1981 if (ECMAScript.HasProperty(desc, 'value')) { o[p] = desc.value; }
1982 return o;
1983 };
1984}
1985
1986var getOwnPropNames = Object.getOwnPropertyNames || function (o) {
1987 if (o !== Object(o)) throw new TypeError("Object.getOwnPropertyNames called on non-object");
1988 var props = [], p;
1989 for (p in o) {
1990 if (ECMAScript.HasOwnProperty(o, p)) {
1991 props.push(p);
1992 }
1993 }
1994 return props;
1995};
1996
1997// ES5: Make obj[index] an alias for obj._getter(index)/obj._setter(index, value)
1998// for index in 0 ... obj.length
1999function makeArrayAccessors(obj) {
2000 if (!defineProp) { return; }
2001
2002 if (obj.length > MAX_ARRAY_LENGTH) throw new RangeError("Array too large for polyfill");
2003
2004 function makeArrayAccessor(index) {
2005 defineProp(obj, index, {
2006 'get': function() { return obj._getter(index); },
2007 'set': function(v) { obj._setter(index, v); },
2008 enumerable: true,
2009 configurable: false
2010 });
2011 }
2012
2013 var i;
2014 for (i = 0; i < obj.length; i += 1) {
2015 makeArrayAccessor(i);
2016 }
2017}
2018
2019// Internal conversion functions:
2020// pack<Type>() - take a number (interpreted as Type), output a byte array
2021// unpack<Type>() - take a byte array, output a Type-like number
2022
2023function as_signed(value, bits) { var s = 32 - bits; return (value << s) >> s; }
2024function as_unsigned(value, bits) { var s = 32 - bits; return (value << s) >>> s; }
2025
2026function packI8(n) { return [n & 0xff]; }
2027function unpackI8(bytes) { return as_signed(bytes[0], 8); }
2028
2029function packU8(n) { return [n & 0xff]; }
2030function unpackU8(bytes) { return as_unsigned(bytes[0], 8); }
2031
2032function packU8Clamped(n) { n = round(Number(n)); return [n < 0 ? 0 : n > 0xff ? 0xff : n & 0xff]; }
2033
2034function packI16(n) { return [(n >> 8) & 0xff, n & 0xff]; }
2035function unpackI16(bytes) { return as_signed(bytes[0] << 8 | bytes[1], 16); }
2036
2037function packU16(n) { return [(n >> 8) & 0xff, n & 0xff]; }
2038function unpackU16(bytes) { return as_unsigned(bytes[0] << 8 | bytes[1], 16); }
2039
2040function packI32(n) { return [(n >> 24) & 0xff, (n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff]; }
2041function unpackI32(bytes) { return as_signed(bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], 32); }
2042
2043function packU32(n) { return [(n >> 24) & 0xff, (n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff]; }
2044function unpackU32(bytes) { return as_unsigned(bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], 32); }
2045
2046function packIEEE754(v, ebits, fbits) {
2047
2048 var bias = (1 << (ebits - 1)) - 1,
2049 s, e, f, i, bits, str, bytes;
2050
2051 function roundToEven(n) {
2052 var w = floor(n), f = n - w;
2053 if (f < 0.5)
2054 return w;
2055 if (f > 0.5)
2056 return w + 1;
2057 return w % 2 ? w + 1 : w;
2058 }
2059
2060 // Compute sign, exponent, fraction
2061 if (v !== v) {
2062 // NaN
2063 // http://dev.w3.org/2006/webapi/WebIDL/#es-type-mapping
2064 e = (1 << ebits) - 1; f = pow(2, fbits - 1); s = 0;
2065 } else if (v === Infinity || v === -Infinity) {
2066 e = (1 << ebits) - 1; f = 0; s = (v < 0) ? 1 : 0;
2067 } else if (v === 0) {
2068 e = 0; f = 0; s = (1 / v === -Infinity) ? 1 : 0;
2069 } else {
2070 s = v < 0;
2071 v = abs(v);
2072
2073 if (v >= pow(2, 1 - bias)) {
2074 e = min(floor(log(v) / LN2), 1023);
2075 f = roundToEven(v / pow(2, e) * pow(2, fbits));
2076 if (f / pow(2, fbits) >= 2) {
2077 e = e + 1;
2078 f = 1;
2079 }
2080 if (e > bias) {
2081 // Overflow
2082 e = (1 << ebits) - 1;
2083 f = 0;
2084 } else {
2085 // Normalized
2086 e = e + bias;
2087 f = f - pow(2, fbits);
2088 }
2089 } else {
2090 // Denormalized
2091 e = 0;
2092 f = roundToEven(v / pow(2, 1 - bias - fbits));
2093 }
2094 }
2095
2096 // Pack sign, exponent, fraction
2097 bits = [];
2098 for (i = fbits; i; i -= 1) { bits.push(f % 2 ? 1 : 0); f = floor(f / 2); }
2099 for (i = ebits; i; i -= 1) { bits.push(e % 2 ? 1 : 0); e = floor(e / 2); }
2100 bits.push(s ? 1 : 0);
2101 bits.reverse();
2102 str = bits.join('');
2103
2104 // Bits to bytes
2105 bytes = [];
2106 while (str.length) {
2107 bytes.push(parseInt(str.substring(0, 8), 2));
2108 str = str.substring(8);
2109 }
2110 return bytes;
2111}
2112
2113function unpackIEEE754(bytes, ebits, fbits) {
2114
2115 // Bytes to bits
2116 var bits = [], i, j, b, str,
2117 bias, s, e, f;
2118
2119 for (i = bytes.length; i; i -= 1) {
2120 b = bytes[i - 1];
2121 for (j = 8; j; j -= 1) {
2122 bits.push(b % 2 ? 1 : 0); b = b >> 1;
2123 }
2124 }
2125 bits.reverse();
2126 str = bits.join('');
2127
2128 // Unpack sign, exponent, fraction
2129 bias = (1 << (ebits - 1)) - 1;
2130 s = parseInt(str.substring(0, 1), 2) ? -1 : 1;
2131 e = parseInt(str.substring(1, 1 + ebits), 2);
2132 f = parseInt(str.substring(1 + ebits), 2);
2133
2134 // Produce number
2135 if (e === (1 << ebits) - 1) {
2136 return f !== 0 ? NaN : s * Infinity;
2137 } else if (e > 0) {
2138 // Normalized
2139 return s * pow(2, e - bias) * (1 + f / pow(2, fbits));
2140 } else if (f !== 0) {
2141 // Denormalized
2142 return s * pow(2, -(bias - 1)) * (f / pow(2, fbits));
2143 } else {
2144 return s < 0 ? -0 : 0;
2145 }
2146}
2147
2148function unpackF64(b) { return unpackIEEE754(b, 11, 52); }
2149function packF64(v) { return packIEEE754(v, 11, 52); }
2150function unpackF32(b) { return unpackIEEE754(b, 8, 23); }
2151function packF32(v) { return packIEEE754(v, 8, 23); }
2152
2153
2154//
2155// 3 The ArrayBuffer Type
2156//
2157
2158(function() {
2159
2160 /** @constructor */
2161 var ArrayBuffer = function ArrayBuffer(length) {
2162 length = ECMAScript.ToInt32(length);
2163 if (length < 0) throw new RangeError('ArrayBuffer size is not a small enough positive integer');
2164
2165 this.byteLength = length;
2166 this._bytes = [];
2167 this._bytes.length = length;
2168
2169 var i;
2170 for (i = 0; i < this.byteLength; i += 1) {
2171 this._bytes[i] = 0;
2172 }
2173
2174 configureProperties(this);
2175 };
2176
2177 exports.ArrayBuffer = exports.ArrayBuffer || ArrayBuffer;
2178
2179 //
2180 // 4 The ArrayBufferView Type
2181 //
2182
2183 // NOTE: this constructor is not exported
2184 /** @constructor */
2185 var ArrayBufferView = function ArrayBufferView() {
2186 //this.buffer = null;
2187 //this.byteOffset = 0;
2188 //this.byteLength = 0;
2189 };
2190
2191 //
2192 // 5 The Typed Array View Types
2193 //
2194
2195 function makeConstructor(bytesPerElement, pack, unpack) {
2196 // Each TypedArray type requires a distinct constructor instance with
2197 // identical logic, which this produces.
2198
2199 var ctor;
2200 ctor = function(buffer, byteOffset, length) {
2201 var array, sequence, i, s;
2202
2203 if (!arguments.length || typeof arguments[0] === 'number') {
2204 // Constructor(unsigned long length)
2205 this.length = ECMAScript.ToInt32(arguments[0]);
2206 if (length < 0) throw new RangeError('ArrayBufferView size is not a small enough positive integer');
2207
2208 this.byteLength = this.length * this.BYTES_PER_ELEMENT;
2209 this.buffer = new ArrayBuffer(this.byteLength);
2210 this.byteOffset = 0;
2211 } else if (typeof arguments[0] === 'object' && arguments[0].constructor === ctor) {
2212 // Constructor(TypedArray array)
2213 array = arguments[0];
2214
2215 this.length = array.length;
2216 this.byteLength = this.length * this.BYTES_PER_ELEMENT;
2217 this.buffer = new ArrayBuffer(this.byteLength);
2218 this.byteOffset = 0;
2219
2220 for (i = 0; i < this.length; i += 1) {
2221 this._setter(i, array._getter(i));
2222 }
2223 } else if (typeof arguments[0] === 'object' &&
2224 !(arguments[0] instanceof ArrayBuffer || ECMAScript.Class(arguments[0]) === 'ArrayBuffer')) {
2225 // Constructor(sequence<type> array)
2226 sequence = arguments[0];
2227
2228 this.length = ECMAScript.ToUint32(sequence.length);
2229 this.byteLength = this.length * this.BYTES_PER_ELEMENT;
2230 this.buffer = new ArrayBuffer(this.byteLength);
2231 this.byteOffset = 0;
2232
2233 for (i = 0; i < this.length; i += 1) {
2234 s = sequence[i];
2235 this._setter(i, Number(s));
2236 }
2237 } else if (typeof arguments[0] === 'object' &&
2238 (arguments[0] instanceof ArrayBuffer || ECMAScript.Class(arguments[0]) === 'ArrayBuffer')) {
2239 // Constructor(ArrayBuffer buffer,
2240 // optional unsigned long byteOffset, optional unsigned long length)
2241 this.buffer = buffer;
2242
2243 this.byteOffset = ECMAScript.ToUint32(byteOffset);
2244 if (this.byteOffset > this.buffer.byteLength) {
2245 throw new RangeError("byteOffset out of range");
2246 }
2247
2248 if (this.byteOffset % this.BYTES_PER_ELEMENT) {
2249 // The given byteOffset must be a multiple of the element
2250 // size of the specific type, otherwise an exception is raised.
2251 throw new RangeError("ArrayBuffer length minus the byteOffset is not a multiple of the element size.");
2252 }
2253
2254 if (arguments.length < 3) {
2255 this.byteLength = this.buffer.byteLength - this.byteOffset;
2256
2257 if (this.byteLength % this.BYTES_PER_ELEMENT) {
2258 throw new RangeError("length of buffer minus byteOffset not a multiple of the element size");
2259 }
2260 this.length = this.byteLength / this.BYTES_PER_ELEMENT;
2261 } else {
2262 this.length = ECMAScript.ToUint32(length);
2263 this.byteLength = this.length * this.BYTES_PER_ELEMENT;
2264 }
2265
2266 if ((this.byteOffset + this.byteLength) > this.buffer.byteLength) {
2267 throw new RangeError("byteOffset and length reference an area beyond the end of the buffer");
2268 }
2269 } else {
2270 throw new TypeError("Unexpected argument type(s)");
2271 }
2272
2273 this.constructor = ctor;
2274
2275 configureProperties(this);
2276 makeArrayAccessors(this);
2277 };
2278
2279 ctor.prototype = new ArrayBufferView();
2280 ctor.prototype.BYTES_PER_ELEMENT = bytesPerElement;
2281 ctor.prototype._pack = pack;
2282 ctor.prototype._unpack = unpack;
2283 ctor.BYTES_PER_ELEMENT = bytesPerElement;
2284
2285 // getter type (unsigned long index);
2286 ctor.prototype._getter = function(index) {
2287 if (arguments.length < 1) throw new SyntaxError("Not enough arguments");
2288
2289 index = ECMAScript.ToUint32(index);
2290 if (index >= this.length) {
2291 return undefined$1;
2292 }
2293
2294 var bytes = [], i, o;
2295 for (i = 0, o = this.byteOffset + index * this.BYTES_PER_ELEMENT;
2296 i < this.BYTES_PER_ELEMENT;
2297 i += 1, o += 1) {
2298 bytes.push(this.buffer._bytes[o]);
2299 }
2300 return this._unpack(bytes);
2301 };
2302
2303 // NONSTANDARD: convenience alias for getter: type get(unsigned long index);
2304 ctor.prototype.get = ctor.prototype._getter;
2305
2306 // setter void (unsigned long index, type value);
2307 ctor.prototype._setter = function(index, value) {
2308 if (arguments.length < 2) throw new SyntaxError("Not enough arguments");
2309
2310 index = ECMAScript.ToUint32(index);
2311 if (index >= this.length) {
2312 return undefined$1;
2313 }
2314
2315 var bytes = this._pack(value), i, o;
2316 for (i = 0, o = this.byteOffset + index * this.BYTES_PER_ELEMENT;
2317 i < this.BYTES_PER_ELEMENT;
2318 i += 1, o += 1) {
2319 this.buffer._bytes[o] = bytes[i];
2320 }
2321 };
2322
2323 // void set(TypedArray array, optional unsigned long offset);
2324 // void set(sequence<type> array, optional unsigned long offset);
2325 ctor.prototype.set = function(index, value) {
2326 if (arguments.length < 1) throw new SyntaxError("Not enough arguments");
2327 var array, sequence, offset, len,
2328 i, s, d,
2329 byteOffset, byteLength, tmp;
2330
2331 if (typeof arguments[0] === 'object' && arguments[0].constructor === this.constructor) {
2332 // void set(TypedArray array, optional unsigned long offset);
2333 array = arguments[0];
2334 offset = ECMAScript.ToUint32(arguments[1]);
2335
2336 if (offset + array.length > this.length) {
2337 throw new RangeError("Offset plus length of array is out of range");
2338 }
2339
2340 byteOffset = this.byteOffset + offset * this.BYTES_PER_ELEMENT;
2341 byteLength = array.length * this.BYTES_PER_ELEMENT;
2342
2343 if (array.buffer === this.buffer) {
2344 tmp = [];
2345 for (i = 0, s = array.byteOffset; i < byteLength; i += 1, s += 1) {
2346 tmp[i] = array.buffer._bytes[s];
2347 }
2348 for (i = 0, d = byteOffset; i < byteLength; i += 1, d += 1) {
2349 this.buffer._bytes[d] = tmp[i];
2350 }
2351 } else {
2352 for (i = 0, s = array.byteOffset, d = byteOffset;
2353 i < byteLength; i += 1, s += 1, d += 1) {
2354 this.buffer._bytes[d] = array.buffer._bytes[s];
2355 }
2356 }
2357 } else if (typeof arguments[0] === 'object' && typeof arguments[0].length !== 'undefined') {
2358 // void set(sequence<type> array, optional unsigned long offset);
2359 sequence = arguments[0];
2360 len = ECMAScript.ToUint32(sequence.length);
2361 offset = ECMAScript.ToUint32(arguments[1]);
2362
2363 if (offset + len > this.length) {
2364 throw new RangeError("Offset plus length of array is out of range");
2365 }
2366
2367 for (i = 0; i < len; i += 1) {
2368 s = sequence[i];
2369 this._setter(offset + i, Number(s));
2370 }
2371 } else {
2372 throw new TypeError("Unexpected argument type(s)");
2373 }
2374 };
2375
2376 // TypedArray subarray(long begin, optional long end);
2377 ctor.prototype.subarray = function(start, end) {
2378 function clamp(v, min, max) { return v < min ? min : v > max ? max : v; }
2379
2380 start = ECMAScript.ToInt32(start);
2381 end = ECMAScript.ToInt32(end);
2382
2383 if (arguments.length < 1) { start = 0; }
2384 if (arguments.length < 2) { end = this.length; }
2385
2386 if (start < 0) { start = this.length + start; }
2387 if (end < 0) { end = this.length + end; }
2388
2389 start = clamp(start, 0, this.length);
2390 end = clamp(end, 0, this.length);
2391
2392 var len = end - start;
2393 if (len < 0) {
2394 len = 0;
2395 }
2396
2397 return new this.constructor(
2398 this.buffer, this.byteOffset + start * this.BYTES_PER_ELEMENT, len);
2399 };
2400
2401 return ctor;
2402 }
2403
2404 var Int8Array = makeConstructor(1, packI8, unpackI8);
2405 var Uint8Array = makeConstructor(1, packU8, unpackU8);
2406 var Uint8ClampedArray = makeConstructor(1, packU8Clamped, unpackU8);
2407 var Int16Array = makeConstructor(2, packI16, unpackI16);
2408 var Uint16Array = makeConstructor(2, packU16, unpackU16);
2409 var Int32Array = makeConstructor(4, packI32, unpackI32);
2410 var Uint32Array = makeConstructor(4, packU32, unpackU32);
2411 var Float32Array = makeConstructor(4, packF32, unpackF32);
2412 var Float64Array = makeConstructor(8, packF64, unpackF64);
2413
2414 exports.Int8Array = exports.Int8Array || Int8Array;
2415 exports.Uint8Array = exports.Uint8Array || Uint8Array;
2416 exports.Uint8ClampedArray = exports.Uint8ClampedArray || Uint8ClampedArray;
2417 exports.Int16Array = exports.Int16Array || Int16Array;
2418 exports.Uint16Array = exports.Uint16Array || Uint16Array;
2419 exports.Int32Array = exports.Int32Array || Int32Array;
2420 exports.Uint32Array = exports.Uint32Array || Uint32Array;
2421 exports.Float32Array = exports.Float32Array || Float32Array;
2422 exports.Float64Array = exports.Float64Array || Float64Array;
2423}());
2424
2425//
2426// 6 The DataView View Type
2427//
2428
2429(function() {
2430 function r(array, index) {
2431 return ECMAScript.IsCallable(array.get) ? array.get(index) : array[index];
2432 }
2433
2434 var IS_BIG_ENDIAN = (function() {
2435 var u16array = new(exports.Uint16Array)([0x1234]),
2436 u8array = new(exports.Uint8Array)(u16array.buffer);
2437 return r(u8array, 0) === 0x12;
2438 }());
2439
2440 // Constructor(ArrayBuffer buffer,
2441 // optional unsigned long byteOffset,
2442 // optional unsigned long byteLength)
2443 /** @constructor */
2444 var DataView = function DataView(buffer, byteOffset, byteLength) {
2445 if (arguments.length === 0) {
2446 buffer = new exports.ArrayBuffer(0);
2447 } else if (!(buffer instanceof exports.ArrayBuffer || ECMAScript.Class(buffer) === 'ArrayBuffer')) {
2448 throw new TypeError("TypeError");
2449 }
2450
2451 this.buffer = buffer || new exports.ArrayBuffer(0);
2452
2453 this.byteOffset = ECMAScript.ToUint32(byteOffset);
2454 if (this.byteOffset > this.buffer.byteLength) {
2455 throw new RangeError("byteOffset out of range");
2456 }
2457
2458 if (arguments.length < 3) {
2459 this.byteLength = this.buffer.byteLength - this.byteOffset;
2460 } else {
2461 this.byteLength = ECMAScript.ToUint32(byteLength);
2462 }
2463
2464 if ((this.byteOffset + this.byteLength) > this.buffer.byteLength) {
2465 throw new RangeError("byteOffset and length reference an area beyond the end of the buffer");
2466 }
2467
2468 configureProperties(this);
2469 };
2470
2471 function makeGetter(arrayType) {
2472 return function(byteOffset, littleEndian) {
2473
2474 byteOffset = ECMAScript.ToUint32(byteOffset);
2475
2476 if (byteOffset + arrayType.BYTES_PER_ELEMENT > this.byteLength) {
2477 throw new RangeError("Array index out of range");
2478 }
2479 byteOffset += this.byteOffset;
2480
2481 var uint8Array = new exports.Uint8Array(this.buffer, byteOffset, arrayType.BYTES_PER_ELEMENT),
2482 bytes = [], i;
2483 for (i = 0; i < arrayType.BYTES_PER_ELEMENT; i += 1) {
2484 bytes.push(r(uint8Array, i));
2485 }
2486
2487 if (Boolean(littleEndian) === Boolean(IS_BIG_ENDIAN)) {
2488 bytes.reverse();
2489 }
2490
2491 return r(new arrayType(new exports.Uint8Array(bytes).buffer), 0);
2492 };
2493 }
2494
2495 DataView.prototype.getUint8 = makeGetter(exports.Uint8Array);
2496 DataView.prototype.getInt8 = makeGetter(exports.Int8Array);
2497 DataView.prototype.getUint16 = makeGetter(exports.Uint16Array);
2498 DataView.prototype.getInt16 = makeGetter(exports.Int16Array);
2499 DataView.prototype.getUint32 = makeGetter(exports.Uint32Array);
2500 DataView.prototype.getInt32 = makeGetter(exports.Int32Array);
2501 DataView.prototype.getFloat32 = makeGetter(exports.Float32Array);
2502 DataView.prototype.getFloat64 = makeGetter(exports.Float64Array);
2503
2504 function makeSetter(arrayType) {
2505 return function(byteOffset, value, littleEndian) {
2506
2507 byteOffset = ECMAScript.ToUint32(byteOffset);
2508 if (byteOffset + arrayType.BYTES_PER_ELEMENT > this.byteLength) {
2509 throw new RangeError("Array index out of range");
2510 }
2511
2512 // Get bytes
2513 var typeArray = new arrayType([value]),
2514 byteArray = new exports.Uint8Array(typeArray.buffer),
2515 bytes = [], i, byteView;
2516
2517 for (i = 0; i < arrayType.BYTES_PER_ELEMENT; i += 1) {
2518 bytes.push(r(byteArray, i));
2519 }
2520
2521 // Flip if necessary
2522 if (Boolean(littleEndian) === Boolean(IS_BIG_ENDIAN)) {
2523 bytes.reverse();
2524 }
2525
2526 // Write them
2527 byteView = new exports.Uint8Array(this.buffer, byteOffset, arrayType.BYTES_PER_ELEMENT);
2528 byteView.set(bytes);
2529 };
2530 }
2531
2532 DataView.prototype.setUint8 = makeSetter(exports.Uint8Array);
2533 DataView.prototype.setInt8 = makeSetter(exports.Int8Array);
2534 DataView.prototype.setUint16 = makeSetter(exports.Uint16Array);
2535 DataView.prototype.setInt16 = makeSetter(exports.Int16Array);
2536 DataView.prototype.setUint32 = makeSetter(exports.Uint32Array);
2537 DataView.prototype.setInt32 = makeSetter(exports.Int32Array);
2538 DataView.prototype.setFloat32 = makeSetter(exports.Float32Array);
2539 DataView.prototype.setFloat64 = makeSetter(exports.Float64Array);
2540
2541 exports.DataView = exports.DataView || DataView;
2542
2543}());
2544});
2545var typedarray_1 = typedarray.ArrayBuffer;
2546var typedarray_2 = typedarray.Int8Array;
2547var typedarray_3 = typedarray.Uint8Array;
2548var typedarray_4 = typedarray.Uint8ClampedArray;
2549var typedarray_5 = typedarray.Int16Array;
2550var typedarray_6 = typedarray.Uint16Array;
2551var typedarray_7 = typedarray.Int32Array;
2552var typedarray_8 = typedarray.Uint32Array;
2553var typedarray_9 = typedarray.Float32Array;
2554var typedarray_10 = typedarray.Float64Array;
2555var typedarray_11 = typedarray.DataView;
2556
2557var Writable = readableStream.Writable;
2558
2559
2560
2561if (typeof Uint8Array === 'undefined') {
2562 var U8 = typedarray.Uint8Array;
2563} else {
2564 var U8 = Uint8Array;
2565}
2566
2567function ConcatStream(opts, cb) {
2568 if (!(this instanceof ConcatStream)) return new ConcatStream(opts, cb)
2569
2570 if (typeof opts === 'function') {
2571 cb = opts;
2572 opts = {};
2573 }
2574 if (!opts) opts = {};
2575
2576 var encoding = opts.encoding;
2577 var shouldInferEncoding = false;
2578
2579 if (!encoding) {
2580 shouldInferEncoding = true;
2581 } else {
2582 encoding = String(encoding).toLowerCase();
2583 if (encoding === 'u8' || encoding === 'uint8') {
2584 encoding = 'uint8array';
2585 }
2586 }
2587
2588 Writable.call(this, { objectMode: true });
2589
2590 this.encoding = encoding;
2591 this.shouldInferEncoding = shouldInferEncoding;
2592
2593 if (cb) this.on('finish', function () { cb(this.getBody()); });
2594 this.body = [];
2595}
2596
2597var concatStream = ConcatStream;
2598inherits(ConcatStream, Writable);
2599
2600ConcatStream.prototype._write = function(chunk, enc, next) {
2601 this.body.push(chunk);
2602 next();
2603};
2604
2605ConcatStream.prototype.inferEncoding = function (buff) {
2606 var firstBuffer = buff === undefined ? this.body[0] : buff;
2607 if (Buffer.isBuffer(firstBuffer)) return 'buffer'
2608 if (typeof Uint8Array !== 'undefined' && firstBuffer instanceof Uint8Array) return 'uint8array'
2609 if (Array.isArray(firstBuffer)) return 'array'
2610 if (typeof firstBuffer === 'string') return 'string'
2611 if (Object.prototype.toString.call(firstBuffer) === "[object Object]") return 'object'
2612 return 'buffer'
2613};
2614
2615ConcatStream.prototype.getBody = function () {
2616 if (!this.encoding && this.body.length === 0) return []
2617 if (this.shouldInferEncoding) this.encoding = this.inferEncoding();
2618 if (this.encoding === 'array') return arrayConcat(this.body)
2619 if (this.encoding === 'string') return stringConcat(this.body)
2620 if (this.encoding === 'buffer') return bufferConcat(this.body)
2621 if (this.encoding === 'uint8array') return u8Concat(this.body)
2622 return this.body
2623};
2624
2625function isArrayish (arr) {
2626 return /Array\]$/.test(Object.prototype.toString.call(arr))
2627}
2628
2629function isBufferish (p) {
2630 return typeof p === 'string' || isArrayish(p) || (p && typeof p.subarray === 'function')
2631}
2632
2633function stringConcat (parts) {
2634 var strings = [];
2635 for (var i = 0; i < parts.length; i++) {
2636 var p = parts[i];
2637 if (typeof p === 'string') {
2638 strings.push(p);
2639 } else if (Buffer.isBuffer(p)) {
2640 strings.push(p);
2641 } else if (isBufferish(p)) {
2642 strings.push(bufferFrom_1(p));
2643 } else {
2644 strings.push(bufferFrom_1(String(p)));
2645 }
2646 }
2647 if (Buffer.isBuffer(parts[0])) {
2648 strings = Buffer.concat(strings);
2649 strings = strings.toString('utf8');
2650 } else {
2651 strings = strings.join('');
2652 }
2653 return strings
2654}
2655
2656function bufferConcat (parts) {
2657 var bufs = [];
2658 for (var i = 0; i < parts.length; i++) {
2659 var p = parts[i];
2660 if (Buffer.isBuffer(p)) {
2661 bufs.push(p);
2662 } else if (isBufferish(p)) {
2663 bufs.push(bufferFrom_1(p));
2664 } else {
2665 bufs.push(bufferFrom_1(String(p)));
2666 }
2667 }
2668 return Buffer.concat(bufs)
2669}
2670
2671function arrayConcat (parts) {
2672 var res = [];
2673 for (var i = 0; i < parts.length; i++) {
2674 res.push.apply(res, parts[i]);
2675 }
2676 return res
2677}
2678
2679function u8Concat (parts) {
2680 var len = 0;
2681 for (var i = 0; i < parts.length; i++) {
2682 if (typeof parts[i] === 'string') {
2683 parts[i] = bufferFrom_1(parts[i]);
2684 }
2685 len += parts[i].length;
2686 }
2687 var u8 = new U8(len);
2688 for (var i = 0, offset = 0; i < parts.length; i++) {
2689 var part = parts[i];
2690 for (var j = 0; j < part.length; j++) {
2691 u8[offset++] = part[j];
2692 }
2693 }
2694 return u8
2695}
2696
2697var Readable = readableStream.Readable;
2698
2699
2700var from2_1 = from2;
2701
2702from2.ctor = ctor$2;
2703from2.obj = obj$2;
2704
2705var Proto = ctor$2();
2706
2707function toFunction(list) {
2708 list = list.slice();
2709 return function (_, cb) {
2710 var err = null;
2711 var item = list.length ? list.shift() : null;
2712 if (item instanceof Error) {
2713 err = item;
2714 item = null;
2715 }
2716
2717 cb(err, item);
2718 }
2719}
2720
2721function from2(opts, read) {
2722 if (typeof opts !== 'object' || Array.isArray(opts)) {
2723 read = opts;
2724 opts = {};
2725 }
2726
2727 var rs = new Proto(opts);
2728 rs._from = Array.isArray(read) ? toFunction(read) : (read || noop$4);
2729 return rs
2730}
2731
2732function ctor$2(opts, read) {
2733 if (typeof opts === 'function') {
2734 read = opts;
2735 opts = {};
2736 }
2737
2738 opts = defaults(opts);
2739
2740 inherits(Class, Readable);
2741 function Class(override) {
2742 if (!(this instanceof Class)) return new Class(override)
2743 this._reading = false;
2744 this._callback = check;
2745 this.destroyed = false;
2746 Readable.call(this, override || opts);
2747
2748 var self = this;
2749 var hwm = this._readableState.highWaterMark;
2750
2751 function check(err, data) {
2752 if (self.destroyed) return
2753 if (err) return self.destroy(err)
2754 if (data === null) return self.push(null)
2755 self._reading = false;
2756 if (self.push(data)) self._read(hwm);
2757 }
2758 }
2759
2760 Class.prototype._from = read || noop$4;
2761 Class.prototype._read = function(size) {
2762 if (this._reading || this.destroyed) return
2763 this._reading = true;
2764 this._from(size, this._callback);
2765 };
2766
2767 Class.prototype.destroy = function(err) {
2768 if (this.destroyed) return
2769 this.destroyed = true;
2770
2771 var self = this;
2772 process.nextTick(function() {
2773 if (err) self.emit('error', err);
2774 self.emit('close');
2775 });
2776 };
2777
2778 return Class
2779}
2780
2781function obj$2(opts, read) {
2782 if (typeof opts === 'function' || Array.isArray(opts)) {
2783 read = opts;
2784 opts = {};
2785 }
2786
2787 opts = defaults(opts);
2788 opts.objectMode = true;
2789 opts.highWaterMark = 16;
2790
2791 return from2(opts, read)
2792}
2793
2794function noop$4 () {}
2795
2796function defaults(opts) {
2797 opts = opts || {};
2798 return opts
2799}
2800
2801var SIGNAL_FLUSH$2 =(Buffer.from && Buffer.from !== Uint8Array.from)
2802 ? Buffer.from([0])
2803 : new Buffer([0]);
2804
2805var flushWriteStream = WriteStream;
2806
2807function WriteStream (opts, write, flush) {
2808 if (!(this instanceof WriteStream)) return new WriteStream(opts, write, flush)
2809
2810 if (typeof opts === 'function') {
2811 flush = write;
2812 write = opts;
2813 opts = {};
2814 }
2815
2816 readableStream.Writable.call(this, opts);
2817
2818 this.destroyed = false;
2819 this._worker = write || null;
2820 this._flush = flush || null;
2821}
2822
2823inherits(WriteStream, readableStream.Writable);
2824
2825WriteStream.obj = function (opts, worker, flush) {
2826 if (typeof opts === 'function') return WriteStream.obj(null, opts, worker)
2827 if (!opts) opts = {};
2828 opts.objectMode = true;
2829 return new WriteStream(opts, worker, flush)
2830};
2831
2832WriteStream.prototype._write = function (data, enc, cb) {
2833 if (SIGNAL_FLUSH$2 === data) this._flush(cb);
2834 else this._worker(data, enc, cb);
2835};
2836
2837WriteStream.prototype.end = function (data, enc, cb) {
2838 if (!this._flush) return readableStream.Writable.prototype.end.apply(this, arguments)
2839 if (typeof data === 'function') return this.end(null, null, data)
2840 if (typeof enc === 'function') return this.end(data, null, enc)
2841 if (data) this.write(data);
2842 if (!this._writableState.ending) this.write(SIGNAL_FLUSH$2);
2843 return readableStream.Writable.prototype.end.call(this, cb)
2844};
2845
2846WriteStream.prototype.destroy = function (err) {
2847 if (this.destroyed) return
2848 this.destroyed = true;
2849 if (err) this.emit('error', err);
2850 this.emit('close');
2851};
2852
2853var ensureTwoPower = function(n) {
2854 if (n && !(n & (n - 1))) return n;
2855 var p = 1;
2856 while (p < n) p <<= 1;
2857 return p;
2858};
2859
2860var Cyclist = function(size) {
2861 if (!(this instanceof Cyclist)) return new Cyclist(size);
2862 size = ensureTwoPower(size);
2863 this.mask = size-1;
2864 this.size = size;
2865 this.values = new Array(size);
2866};
2867
2868Cyclist.prototype.put = function(index, val) {
2869 var pos = index & this.mask;
2870 this.values[pos] = val;
2871 return pos;
2872};
2873
2874Cyclist.prototype.get = function(index) {
2875 return this.values[index & this.mask];
2876};
2877
2878Cyclist.prototype.del = function(index) {
2879 var pos = index & this.mask;
2880 var val = this.values[pos];
2881 this.values[pos] = undefined;
2882 return val;
2883};
2884
2885var cyclist = Cyclist;
2886
2887var Transform$1 = readableStream.Transform;
2888
2889
2890
2891
2892var ParallelTransform = function(maxParallel, opts, ontransform) {
2893 if (!(this instanceof ParallelTransform)) return new ParallelTransform(maxParallel, opts, ontransform);
2894
2895 if (typeof maxParallel === 'function') {
2896 ontransform = maxParallel;
2897 opts = null;
2898 maxParallel = 1;
2899 }
2900 if (typeof opts === 'function') {
2901 ontransform = opts;
2902 opts = null;
2903 }
2904
2905 if (!opts) opts = {};
2906 if (!opts.highWaterMark) opts.highWaterMark = Math.max(maxParallel, 16);
2907 if (opts.objectMode !== false) opts.objectMode = true;
2908
2909 Transform$1.call(this, opts);
2910
2911 this._maxParallel = maxParallel;
2912 this._ontransform = ontransform;
2913 this._destroyed = false;
2914 this._flushed = false;
2915 this._ordered = opts.ordered !== false;
2916 this._buffer = this._ordered ? cyclist(maxParallel) : [];
2917 this._top = 0;
2918 this._bottom = 0;
2919 this._ondrain = null;
2920};
2921
2922inherits(ParallelTransform, Transform$1);
2923
2924ParallelTransform.prototype.destroy = function() {
2925 if (this._destroyed) return;
2926 this._destroyed = true;
2927 this.emit('close');
2928};
2929
2930ParallelTransform.prototype._transform = function(chunk, enc, callback) {
2931 var self = this;
2932 var pos = this._top++;
2933
2934 this._ontransform(chunk, function(err, data) {
2935 if (self._destroyed) return;
2936 if (err) {
2937 self.emit('error', err);
2938 self.push(null);
2939 self.destroy();
2940 return;
2941 }
2942 if (self._ordered) {
2943 self._buffer.put(pos, (data === undefined || data === null) ? null : data);
2944 }
2945 else {
2946 self._buffer.push(data);
2947 }
2948 self._drain();
2949 });
2950
2951 if (this._top - this._bottom < this._maxParallel) return callback();
2952 this._ondrain = callback;
2953};
2954
2955ParallelTransform.prototype._flush = function(callback) {
2956 this._flushed = true;
2957 this._ondrain = callback;
2958 this._drain();
2959};
2960
2961ParallelTransform.prototype._drain = function() {
2962 if (this._ordered) {
2963 while (this._buffer.get(this._bottom) !== undefined) {
2964 var data = this._buffer.del(this._bottom++);
2965 if (data === null) continue;
2966 this.push(data);
2967 }
2968 }
2969 else {
2970 while (this._buffer.length > 0) {
2971 var data = this._buffer.pop();
2972 this._bottom++;
2973 if (data === null) continue;
2974 this.push(data);
2975 }
2976 }
2977
2978
2979 if (!this._drained() || !this._ondrain) return;
2980
2981 var ondrain = this._ondrain;
2982 this._ondrain = null;
2983 ondrain();
2984};
2985
2986ParallelTransform.prototype._drained = function() {
2987 var diff = this._top - this._bottom;
2988 return this._flushed ? !diff : diff < this._maxParallel;
2989};
2990
2991var parallelTransform = ParallelTransform;
2992
2993var pipe$2 = pump_1;
2994var each$1 = streamEach;
2995var pipeline = pumpify;
2996var duplex = duplexify$1;
2997var through = through2_1;
2998var concat = concatStream;
2999var finished = endOfStream;
3000var from_1 = from2_1;
3001var to = flushWriteStream;
3002var parallel = parallelTransform;
3003
3004var mississippi = {
3005 pipe: pipe$2,
3006 each: each$1,
3007 pipeline: pipeline,
3008 duplex: duplex,
3009 through: through,
3010 concat: concat,
3011 finished: finished,
3012 from: from_1,
3013 to: to,
3014 parallel: parallel
3015};
3016
3017var githubParseLink = function (link) {
3018 if (typeof link !== 'string') {
3019 return {};
3020 }
3021
3022 return link.split(', ').reduce(function (result, part) {
3023 var match = part.match('<(.*?)>; rel="(.*?)"');
3024
3025 if (match && match.length === 3) {
3026 result[match[2]] = match[1];
3027 }
3028
3029 return result;
3030 }, {});
3031};
3032
3033const pDoWhilst = async (action, condition) => {
3034 const actionResult = await action();
3035
3036 if (condition(actionResult)) {
3037 return pDoWhilst(action, condition);
3038 }
3039};
3040
3041var pDoWhilst_1 = pDoWhilst;
3042// TODO: Remove this for the next major release
3043var default_1 = pDoWhilst;
3044pDoWhilst_1.default = default_1;
3045
3046var name = "get-deno";
3047var version = "1.2.6";
3048var description = "deno installation script for npx";
3049var keywords = [
3050 "deno",
3051 "download",
3052 "install",
3053 "installer"
3054];
3055var homepage = "https://github.com/vladimyr/get-deno";
3056var bugs = {
3057 url: "https://github.com/vladimyr/get-deno/issues"
3058};
3059var repository = {
3060 type: "git",
3061 url: "git://github.com/vladimyr/get-deno.git"
3062};
3063var license = "MIT";
3064var author = {
3065 name: "Dario Vladovic",
3066 email: "d.vladimyr+dev@gmail.com",
3067 url: "https://github.com/vladimyr"
3068};
3069var bin = "cli.compact.js";
3070var files = [
3071 "cli.compact.js"
3072];
3073var scripts = {
3074 build: "rollup -c rollup.config.js",
3075 lint: "eslint .",
3076 prepublishOnly: "npm run build",
3077 release: "np",
3078 test: "tape test.js | tap-spec"
3079};
3080var config = {
3081 artifacts: {
3082 win32: [
3083 "deno_win_x64.zip",
3084 "deno-x86_64-pc-windows-msvc.zip"
3085 ],
3086 darwin: [
3087 "deno_osx_x64.gz",
3088 "deno-x86_64-apple-darwin.zip"
3089 ],
3090 linux: [
3091 "deno_linux_x64.gz",
3092 "deno-x86_64-unknown-linux-gnu.zip"
3093 ]
3094 },
3095 repo: "denoland/deno",
3096 umask: 755
3097};
3098var dependencies = {
3099};
3100var devDependencies = {
3101 "@vladimyr/eslint-config": "^1.1.1",
3102 debug: "^4.1.1",
3103 eslint: "^6.3.0",
3104 "eslint-config-semistandard": "^15.0.0",
3105 "eslint-config-standard": "^14.1.0",
3106 "eslint-plugin-import": "^2.18.2",
3107 "eslint-plugin-node": "^11.0.0",
3108 "eslint-plugin-promise": "^4.2.1",
3109 "eslint-plugin-standard": "^4.0.1",
3110 "exit-hook": "^2.2.0",
3111 gauge: "^2.7.4",
3112 "gh-got": "^8.1.0",
3113 "github-parse-link": "^1.1.1",
3114 kleur: "^3.0.3",
3115 "make-dir": "^3.0.0",
3116 minimist: "^1.2.5",
3117 "minimist-options": "^4.0.1",
3118 mississippi: "^4.0.0",
3119 ms: "^2.1.2",
3120 ora: "^4.0.0",
3121 "p-do-whilst": "^1.1.0",
3122 "pretty-bytes": "^5.3.0",
3123 rollup: "^2.0.0",
3124 "rollup-plugin-commonjs": "^10.1.0",
3125 "rollup-plugin-json": "^4.0.0",
3126 "rollup-plugin-node-resolve": "^5.2.0",
3127 "rollup-plugin-postprocess": "^1.0.2",
3128 "rollup-plugin-re": "^1.0.7",
3129 "rollup-plugin-visualizer": "^1.1.1",
3130 semver: "^7.0.0",
3131 "shell-profile": "^1.0.3",
3132 "tap-spec": "^5.0.0",
3133 tape: "^4.11.0",
3134 yauzl: "^2.10.0"
3135};
3136var _package = {
3137 name: name,
3138 version: version,
3139 description: description,
3140 keywords: keywords,
3141 homepage: homepage,
3142 bugs: bugs,
3143 repository: repository,
3144 license: license,
3145 author: author,
3146 bin: bin,
3147 files: files,
3148 scripts: scripts,
3149 config: config,
3150 dependencies: dependencies,
3151 devDependencies: devDependencies
3152};
3153
3154var _package$1 = /*#__PURE__*/Object.freeze({
3155 __proto__: null,
3156 name: name,
3157 version: version,
3158 description: description,
3159 keywords: keywords,
3160 homepage: homepage,
3161 bugs: bugs,
3162 repository: repository,
3163 license: license,
3164 author: author,
3165 bin: bin,
3166 files: files,
3167 scripts: scripts,
3168 config: config,
3169 dependencies: dependencies,
3170 devDependencies: devDependencies,
3171 'default': _package
3172});
3173
3174var pend = Pend;
3175
3176function Pend() {
3177 this.pending = 0;
3178 this.max = Infinity;
3179 this.listeners = [];
3180 this.waiting = [];
3181 this.error = null;
3182}
3183
3184Pend.prototype.go = function(fn) {
3185 if (this.pending < this.max) {
3186 pendGo(this, fn);
3187 } else {
3188 this.waiting.push(fn);
3189 }
3190};
3191
3192Pend.prototype.wait = function(cb) {
3193 if (this.pending === 0) {
3194 cb(this.error);
3195 } else {
3196 this.listeners.push(cb);
3197 }
3198};
3199
3200Pend.prototype.hold = function() {
3201 return pendHold(this);
3202};
3203
3204function pendHold(self) {
3205 self.pending += 1;
3206 var called = false;
3207 return onCb;
3208 function onCb(err) {
3209 if (called) throw new Error("callback called twice");
3210 called = true;
3211 self.error = self.error || err;
3212 self.pending -= 1;
3213 if (self.waiting.length > 0 && self.pending < self.max) {
3214 pendGo(self, self.waiting.shift());
3215 } else if (self.pending === 0) {
3216 var listeners = self.listeners;
3217 self.listeners = [];
3218 listeners.forEach(cbListener);
3219 }
3220 }
3221 function cbListener(listener) {
3222 listener(self.error);
3223 }
3224}
3225
3226function pendGo(self, fn) {
3227 fn(pendHold(self));
3228}
3229
3230var Readable$1 = stream.Readable;
3231var Writable$1 = stream.Writable;
3232var PassThrough = stream.PassThrough;
3233
3234var EventEmitter = events.EventEmitter;
3235
3236var createFromBuffer_1 = createFromBuffer;
3237var createFromFd_1 = createFromFd;
3238var BufferSlicer_1 = BufferSlicer;
3239var FdSlicer_1 = FdSlicer;
3240
3241util.inherits(FdSlicer, EventEmitter);
3242function FdSlicer(fd, options) {
3243 options = options || {};
3244 EventEmitter.call(this);
3245
3246 this.fd = fd;
3247 this.pend = new pend();
3248 this.pend.max = 1;
3249 this.refCount = 0;
3250 this.autoClose = !!options.autoClose;
3251}
3252
3253FdSlicer.prototype.read = function(buffer, offset, length, position, callback) {
3254 var self = this;
3255 self.pend.go(function(cb) {
3256 fs.read(self.fd, buffer, offset, length, position, function(err, bytesRead, buffer) {
3257 cb();
3258 callback(err, bytesRead, buffer);
3259 });
3260 });
3261};
3262
3263FdSlicer.prototype.write = function(buffer, offset, length, position, callback) {
3264 var self = this;
3265 self.pend.go(function(cb) {
3266 fs.write(self.fd, buffer, offset, length, position, function(err, written, buffer) {
3267 cb();
3268 callback(err, written, buffer);
3269 });
3270 });
3271};
3272
3273FdSlicer.prototype.createReadStream = function(options) {
3274 return new ReadStream(this, options);
3275};
3276
3277FdSlicer.prototype.createWriteStream = function(options) {
3278 return new WriteStream$1(this, options);
3279};
3280
3281FdSlicer.prototype.ref = function() {
3282 this.refCount += 1;
3283};
3284
3285FdSlicer.prototype.unref = function() {
3286 var self = this;
3287 self.refCount -= 1;
3288
3289 if (self.refCount > 0) return;
3290 if (self.refCount < 0) throw new Error("invalid unref");
3291
3292 if (self.autoClose) {
3293 fs.close(self.fd, onCloseDone);
3294 }
3295
3296 function onCloseDone(err) {
3297 if (err) {
3298 self.emit('error', err);
3299 } else {
3300 self.emit('close');
3301 }
3302 }
3303};
3304
3305util.inherits(ReadStream, Readable$1);
3306function ReadStream(context, options) {
3307 options = options || {};
3308 Readable$1.call(this, options);
3309
3310 this.context = context;
3311 this.context.ref();
3312
3313 this.start = options.start || 0;
3314 this.endOffset = options.end;
3315 this.pos = this.start;
3316 this.destroyed = false;
3317}
3318
3319ReadStream.prototype._read = function(n) {
3320 var self = this;
3321 if (self.destroyed) return;
3322
3323 var toRead = Math.min(self._readableState.highWaterMark, n);
3324 if (self.endOffset != null) {
3325 toRead = Math.min(toRead, self.endOffset - self.pos);
3326 }
3327 if (toRead <= 0) {
3328 self.destroyed = true;
3329 self.push(null);
3330 self.context.unref();
3331 return;
3332 }
3333 self.context.pend.go(function(cb) {
3334 if (self.destroyed) return cb();
3335 var buffer = new Buffer(toRead);
3336 fs.read(self.context.fd, buffer, 0, toRead, self.pos, function(err, bytesRead) {
3337 if (err) {
3338 self.destroy(err);
3339 } else if (bytesRead === 0) {
3340 self.destroyed = true;
3341 self.push(null);
3342 self.context.unref();
3343 } else {
3344 self.pos += bytesRead;
3345 self.push(buffer.slice(0, bytesRead));
3346 }
3347 cb();
3348 });
3349 });
3350};
3351
3352ReadStream.prototype.destroy = function(err) {
3353 if (this.destroyed) return;
3354 err = err || new Error("stream destroyed");
3355 this.destroyed = true;
3356 this.emit('error', err);
3357 this.context.unref();
3358};
3359
3360util.inherits(WriteStream$1, Writable$1);
3361function WriteStream$1(context, options) {
3362 options = options || {};
3363 Writable$1.call(this, options);
3364
3365 this.context = context;
3366 this.context.ref();
3367
3368 this.start = options.start || 0;
3369 this.endOffset = (options.end == null) ? Infinity : +options.end;
3370 this.bytesWritten = 0;
3371 this.pos = this.start;
3372 this.destroyed = false;
3373
3374 this.on('finish', this.destroy.bind(this));
3375}
3376
3377WriteStream$1.prototype._write = function(buffer, encoding, callback) {
3378 var self = this;
3379 if (self.destroyed) return;
3380
3381 if (self.pos + buffer.length > self.endOffset) {
3382 var err = new Error("maximum file length exceeded");
3383 err.code = 'ETOOBIG';
3384 self.destroy();
3385 callback(err);
3386 return;
3387 }
3388 self.context.pend.go(function(cb) {
3389 if (self.destroyed) return cb();
3390 fs.write(self.context.fd, buffer, 0, buffer.length, self.pos, function(err, bytes) {
3391 if (err) {
3392 self.destroy();
3393 cb();
3394 callback(err);
3395 } else {
3396 self.bytesWritten += bytes;
3397 self.pos += bytes;
3398 self.emit('progress');
3399 cb();
3400 callback();
3401 }
3402 });
3403 });
3404};
3405
3406WriteStream$1.prototype.destroy = function() {
3407 if (this.destroyed) return;
3408 this.destroyed = true;
3409 this.context.unref();
3410};
3411
3412util.inherits(BufferSlicer, EventEmitter);
3413function BufferSlicer(buffer, options) {
3414 EventEmitter.call(this);
3415
3416 options = options || {};
3417 this.refCount = 0;
3418 this.buffer = buffer;
3419 this.maxChunkSize = options.maxChunkSize || Number.MAX_SAFE_INTEGER;
3420}
3421
3422BufferSlicer.prototype.read = function(buffer, offset, length, position, callback) {
3423 var end = position + length;
3424 var delta = end - this.buffer.length;
3425 var written = (delta > 0) ? delta : length;
3426 this.buffer.copy(buffer, offset, position, end);
3427 setImmediate(function() {
3428 callback(null, written);
3429 });
3430};
3431
3432BufferSlicer.prototype.write = function(buffer, offset, length, position, callback) {
3433 buffer.copy(this.buffer, position, offset, offset + length);
3434 setImmediate(function() {
3435 callback(null, length, buffer);
3436 });
3437};
3438
3439BufferSlicer.prototype.createReadStream = function(options) {
3440 options = options || {};
3441 var readStream = new PassThrough(options);
3442 readStream.destroyed = false;
3443 readStream.start = options.start || 0;
3444 readStream.endOffset = options.end;
3445 // by the time this function returns, we'll be done.
3446 readStream.pos = readStream.endOffset || this.buffer.length;
3447
3448 // respect the maxChunkSize option to slice up the chunk into smaller pieces.
3449 var entireSlice = this.buffer.slice(readStream.start, readStream.pos);
3450 var offset = 0;
3451 while (true) {
3452 var nextOffset = offset + this.maxChunkSize;
3453 if (nextOffset >= entireSlice.length) {
3454 // last chunk
3455 if (offset < entireSlice.length) {
3456 readStream.write(entireSlice.slice(offset, entireSlice.length));
3457 }
3458 break;
3459 }
3460 readStream.write(entireSlice.slice(offset, nextOffset));
3461 offset = nextOffset;
3462 }
3463
3464 readStream.end();
3465 readStream.destroy = function() {
3466 readStream.destroyed = true;
3467 };
3468 return readStream;
3469};
3470
3471BufferSlicer.prototype.createWriteStream = function(options) {
3472 var bufferSlicer = this;
3473 options = options || {};
3474 var writeStream = new Writable$1(options);
3475 writeStream.start = options.start || 0;
3476 writeStream.endOffset = (options.end == null) ? this.buffer.length : +options.end;
3477 writeStream.bytesWritten = 0;
3478 writeStream.pos = writeStream.start;
3479 writeStream.destroyed = false;
3480 writeStream._write = function(buffer, encoding, callback) {
3481 if (writeStream.destroyed) return;
3482
3483 var end = writeStream.pos + buffer.length;
3484 if (end > writeStream.endOffset) {
3485 var err = new Error("maximum file length exceeded");
3486 err.code = 'ETOOBIG';
3487 writeStream.destroyed = true;
3488 callback(err);
3489 return;
3490 }
3491 buffer.copy(bufferSlicer.buffer, writeStream.pos, 0, buffer.length);
3492
3493 writeStream.bytesWritten += buffer.length;
3494 writeStream.pos = end;
3495 writeStream.emit('progress');
3496 callback();
3497 };
3498 writeStream.destroy = function() {
3499 writeStream.destroyed = true;
3500 };
3501 return writeStream;
3502};
3503
3504BufferSlicer.prototype.ref = function() {
3505 this.refCount += 1;
3506};
3507
3508BufferSlicer.prototype.unref = function() {
3509 this.refCount -= 1;
3510
3511 if (this.refCount < 0) {
3512 throw new Error("invalid unref");
3513 }
3514};
3515
3516function createFromBuffer(buffer, options) {
3517 return new BufferSlicer(buffer, options);
3518}
3519
3520function createFromFd(fd, options) {
3521 return new FdSlicer(fd, options);
3522}
3523
3524var fdSlicer = {
3525 createFromBuffer: createFromBuffer_1,
3526 createFromFd: createFromFd_1,
3527 BufferSlicer: BufferSlicer_1,
3528 FdSlicer: FdSlicer_1
3529};
3530
3531var Buffer$1 = buffer$1.Buffer;
3532
3533var CRC_TABLE = [
3534 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419,
3535 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4,
3536 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07,
3537 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de,
3538 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856,
3539 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
3540 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4,
3541 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,
3542 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3,
3543 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a,
3544 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599,
3545 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
3546 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190,
3547 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f,
3548 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e,
3549 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,
3550 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed,
3551 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
3552 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3,
3553 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2,
3554 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a,
3555 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5,
3556 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010,
3557 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
3558 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17,
3559 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6,
3560 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615,
3561 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8,
3562 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344,
3563 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
3564 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a,
3565 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,
3566 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1,
3567 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c,
3568 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef,
3569 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
3570 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe,
3571 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31,
3572 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c,
3573 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,
3574 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b,
3575 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
3576 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1,
3577 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c,
3578 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278,
3579 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7,
3580 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66,
3581 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
3582 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605,
3583 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8,
3584 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b,
3585 0x2d02ef8d
3586];
3587
3588if (typeof Int32Array !== 'undefined') {
3589 CRC_TABLE = new Int32Array(CRC_TABLE);
3590}
3591
3592function ensureBuffer(input) {
3593 if (Buffer$1.isBuffer(input)) {
3594 return input;
3595 }
3596
3597 var hasNewBufferAPI =
3598 typeof Buffer$1.alloc === "function" &&
3599 typeof Buffer$1.from === "function";
3600
3601 if (typeof input === "number") {
3602 return hasNewBufferAPI ? Buffer$1.alloc(input) : new Buffer$1(input);
3603 }
3604 else if (typeof input === "string") {
3605 return hasNewBufferAPI ? Buffer$1.from(input) : new Buffer$1(input);
3606 }
3607 else {
3608 throw new Error("input must be buffer, number, or string, received " +
3609 typeof input);
3610 }
3611}
3612
3613function bufferizeInt(num) {
3614 var tmp = ensureBuffer(4);
3615 tmp.writeInt32BE(num, 0);
3616 return tmp;
3617}
3618
3619function _crc32(buf, previous) {
3620 buf = ensureBuffer(buf);
3621 if (Buffer$1.isBuffer(previous)) {
3622 previous = previous.readUInt32BE(0);
3623 }
3624 var crc = ~~previous ^ -1;
3625 for (var n = 0; n < buf.length; n++) {
3626 crc = CRC_TABLE[(crc ^ buf[n]) & 0xff] ^ (crc >>> 8);
3627 }
3628 return (crc ^ -1);
3629}
3630
3631function crc32() {
3632 return bufferizeInt(_crc32.apply(null, arguments));
3633}
3634crc32.signed = function () {
3635 return _crc32.apply(null, arguments);
3636};
3637crc32.unsigned = function () {
3638 return _crc32.apply(null, arguments) >>> 0;
3639};
3640
3641var bufferCrc32 = crc32;
3642
3643var EventEmitter$1 = events.EventEmitter;
3644var Transform$2 = stream.Transform;
3645var PassThrough$1 = stream.PassThrough;
3646var Writable$2 = stream.Writable;
3647
3648var open_1 = open;
3649var fromFd_1 = fromFd;
3650var fromBuffer_1 = fromBuffer;
3651var fromRandomAccessReader_1 = fromRandomAccessReader;
3652var dosDateTimeToDate_1 = dosDateTimeToDate;
3653var validateFileName_1 = validateFileName;
3654var ZipFile_1 = ZipFile;
3655var Entry_1 = Entry;
3656var RandomAccessReader_1 = RandomAccessReader;
3657
3658function open(path, options, callback) {
3659 if (typeof options === "function") {
3660 callback = options;
3661 options = null;
3662 }
3663 if (options == null) options = {};
3664 if (options.autoClose == null) options.autoClose = true;
3665 if (options.lazyEntries == null) options.lazyEntries = false;
3666 if (options.decodeStrings == null) options.decodeStrings = true;
3667 if (options.validateEntrySizes == null) options.validateEntrySizes = true;
3668 if (options.strictFileNames == null) options.strictFileNames = false;
3669 if (callback == null) callback = defaultCallback;
3670 fs.open(path, "r", function(err, fd) {
3671 if (err) return callback(err);
3672 fromFd(fd, options, function(err, zipfile) {
3673 if (err) fs.close(fd, defaultCallback);
3674 callback(err, zipfile);
3675 });
3676 });
3677}
3678
3679function fromFd(fd, options, callback) {
3680 if (typeof options === "function") {
3681 callback = options;
3682 options = null;
3683 }
3684 if (options == null) options = {};
3685 if (options.autoClose == null) options.autoClose = false;
3686 if (options.lazyEntries == null) options.lazyEntries = false;
3687 if (options.decodeStrings == null) options.decodeStrings = true;
3688 if (options.validateEntrySizes == null) options.validateEntrySizes = true;
3689 if (options.strictFileNames == null) options.strictFileNames = false;
3690 if (callback == null) callback = defaultCallback;
3691 fs.fstat(fd, function(err, stats) {
3692 if (err) return callback(err);
3693 var reader = fdSlicer.createFromFd(fd, {autoClose: true});
3694 fromRandomAccessReader(reader, stats.size, options, callback);
3695 });
3696}
3697
3698function fromBuffer(buffer, options, callback) {
3699 if (typeof options === "function") {
3700 callback = options;
3701 options = null;
3702 }
3703 if (options == null) options = {};
3704 options.autoClose = false;
3705 if (options.lazyEntries == null) options.lazyEntries = false;
3706 if (options.decodeStrings == null) options.decodeStrings = true;
3707 if (options.validateEntrySizes == null) options.validateEntrySizes = true;
3708 if (options.strictFileNames == null) options.strictFileNames = false;
3709 // limit the max chunk size. see https://github.com/thejoshwolfe/yauzl/issues/87
3710 var reader = fdSlicer.createFromBuffer(buffer, {maxChunkSize: 0x10000});
3711 fromRandomAccessReader(reader, buffer.length, options, callback);
3712}
3713
3714function fromRandomAccessReader(reader, totalSize, options, callback) {
3715 if (typeof options === "function") {
3716 callback = options;
3717 options = null;
3718 }
3719 if (options == null) options = {};
3720 if (options.autoClose == null) options.autoClose = true;
3721 if (options.lazyEntries == null) options.lazyEntries = false;
3722 if (options.decodeStrings == null) options.decodeStrings = true;
3723 var decodeStrings = !!options.decodeStrings;
3724 if (options.validateEntrySizes == null) options.validateEntrySizes = true;
3725 if (options.strictFileNames == null) options.strictFileNames = false;
3726 if (callback == null) callback = defaultCallback;
3727 if (typeof totalSize !== "number") throw new Error("expected totalSize parameter to be a number");
3728 if (totalSize > Number.MAX_SAFE_INTEGER) {
3729 throw new Error("zip file too large. only file sizes up to 2^52 are supported due to JavaScript's Number type being an IEEE 754 double.");
3730 }
3731
3732 // the matching unref() call is in zipfile.close()
3733 reader.ref();
3734
3735 // eocdr means End of Central Directory Record.
3736 // search backwards for the eocdr signature.
3737 // the last field of the eocdr is a variable-length comment.
3738 // the comment size is encoded in a 2-byte field in the eocdr, which we can't find without trudging backwards through the comment to find it.
3739 // as a consequence of this design decision, it's possible to have ambiguous zip file metadata if a coherent eocdr was in the comment.
3740 // we search backwards for a eocdr signature, and hope that whoever made the zip file was smart enough to forbid the eocdr signature in the comment.
3741 var eocdrWithoutCommentSize = 22;
3742 var maxCommentSize = 0xffff; // 2-byte size
3743 var bufferSize = Math.min(eocdrWithoutCommentSize + maxCommentSize, totalSize);
3744 var buffer = newBuffer(bufferSize);
3745 var bufferReadStart = totalSize - buffer.length;
3746 readAndAssertNoEof(reader, buffer, 0, bufferSize, bufferReadStart, function(err) {
3747 if (err) return callback(err);
3748 for (var i = bufferSize - eocdrWithoutCommentSize; i >= 0; i -= 1) {
3749 if (buffer.readUInt32LE(i) !== 0x06054b50) continue;
3750 // found eocdr
3751 var eocdrBuffer = buffer.slice(i);
3752
3753 // 0 - End of central directory signature = 0x06054b50
3754 // 4 - Number of this disk
3755 var diskNumber = eocdrBuffer.readUInt16LE(4);
3756 if (diskNumber !== 0) {
3757 return callback(new Error("multi-disk zip files are not supported: found disk number: " + diskNumber));
3758 }
3759 // 6 - Disk where central directory starts
3760 // 8 - Number of central directory records on this disk
3761 // 10 - Total number of central directory records
3762 var entryCount = eocdrBuffer.readUInt16LE(10);
3763 // 12 - Size of central directory (bytes)
3764 // 16 - Offset of start of central directory, relative to start of archive
3765 var centralDirectoryOffset = eocdrBuffer.readUInt32LE(16);
3766 // 20 - Comment length
3767 var commentLength = eocdrBuffer.readUInt16LE(20);
3768 var expectedCommentLength = eocdrBuffer.length - eocdrWithoutCommentSize;
3769 if (commentLength !== expectedCommentLength) {
3770 return callback(new Error("invalid comment length. expected: " + expectedCommentLength + ". found: " + commentLength));
3771 }
3772 // 22 - Comment
3773 // the encoding is always cp437.
3774 var comment = decodeStrings ? decodeBuffer(eocdrBuffer, 22, eocdrBuffer.length, false)
3775 : eocdrBuffer.slice(22);
3776
3777 if (!(entryCount === 0xffff || centralDirectoryOffset === 0xffffffff)) {
3778 return callback(null, new ZipFile(reader, centralDirectoryOffset, totalSize, entryCount, comment, options.autoClose, options.lazyEntries, decodeStrings, options.validateEntrySizes, options.strictFileNames));
3779 }
3780
3781 // ZIP64 format
3782
3783 // ZIP64 Zip64 end of central directory locator
3784 var zip64EocdlBuffer = newBuffer(20);
3785 var zip64EocdlOffset = bufferReadStart + i - zip64EocdlBuffer.length;
3786 readAndAssertNoEof(reader, zip64EocdlBuffer, 0, zip64EocdlBuffer.length, zip64EocdlOffset, function(err) {
3787 if (err) return callback(err);
3788
3789 // 0 - zip64 end of central dir locator signature = 0x07064b50
3790 if (zip64EocdlBuffer.readUInt32LE(0) !== 0x07064b50) {
3791 return callback(new Error("invalid zip64 end of central directory locator signature"));
3792 }
3793 // 4 - number of the disk with the start of the zip64 end of central directory
3794 // 8 - relative offset of the zip64 end of central directory record
3795 var zip64EocdrOffset = readUInt64LE(zip64EocdlBuffer, 8);
3796 // 16 - total number of disks
3797
3798 // ZIP64 end of central directory record
3799 var zip64EocdrBuffer = newBuffer(56);
3800 readAndAssertNoEof(reader, zip64EocdrBuffer, 0, zip64EocdrBuffer.length, zip64EocdrOffset, function(err) {
3801 if (err) return callback(err);
3802
3803 // 0 - zip64 end of central dir signature 4 bytes (0x06064b50)
3804 if (zip64EocdrBuffer.readUInt32LE(0) !== 0x06064b50) {
3805 return callback(new Error("invalid zip64 end of central directory record signature"));
3806 }
3807 // 4 - size of zip64 end of central directory record 8 bytes
3808 // 12 - version made by 2 bytes
3809 // 14 - version needed to extract 2 bytes
3810 // 16 - number of this disk 4 bytes
3811 // 20 - number of the disk with the start of the central directory 4 bytes
3812 // 24 - total number of entries in the central directory on this disk 8 bytes
3813 // 32 - total number of entries in the central directory 8 bytes
3814 entryCount = readUInt64LE(zip64EocdrBuffer, 32);
3815 // 40 - size of the central directory 8 bytes
3816 // 48 - offset of start of central directory with respect to the starting disk number 8 bytes
3817 centralDirectoryOffset = readUInt64LE(zip64EocdrBuffer, 48);
3818 // 56 - zip64 extensible data sector (variable size)
3819 return callback(null, new ZipFile(reader, centralDirectoryOffset, totalSize, entryCount, comment, options.autoClose, options.lazyEntries, decodeStrings, options.validateEntrySizes, options.strictFileNames));
3820 });
3821 });
3822 return;
3823 }
3824 callback(new Error("end of central directory record signature not found"));
3825 });
3826}
3827
3828util.inherits(ZipFile, EventEmitter$1);
3829function ZipFile(reader, centralDirectoryOffset, fileSize, entryCount, comment, autoClose, lazyEntries, decodeStrings, validateEntrySizes, strictFileNames) {
3830 var self = this;
3831 EventEmitter$1.call(self);
3832 self.reader = reader;
3833 // forward close events
3834 self.reader.on("error", function(err) {
3835 // error closing the fd
3836 emitError(self, err);
3837 });
3838 self.reader.once("close", function() {
3839 self.emit("close");
3840 });
3841 self.readEntryCursor = centralDirectoryOffset;
3842 self.fileSize = fileSize;
3843 self.entryCount = entryCount;
3844 self.comment = comment;
3845 self.entriesRead = 0;
3846 self.autoClose = !!autoClose;
3847 self.lazyEntries = !!lazyEntries;
3848 self.decodeStrings = !!decodeStrings;
3849 self.validateEntrySizes = !!validateEntrySizes;
3850 self.strictFileNames = !!strictFileNames;
3851 self.isOpen = true;
3852 self.emittedError = false;
3853
3854 if (!self.lazyEntries) self._readEntry();
3855}
3856ZipFile.prototype.close = function() {
3857 if (!this.isOpen) return;
3858 this.isOpen = false;
3859 this.reader.unref();
3860};
3861
3862function emitErrorAndAutoClose(self, err) {
3863 if (self.autoClose) self.close();
3864 emitError(self, err);
3865}
3866function emitError(self, err) {
3867 if (self.emittedError) return;
3868 self.emittedError = true;
3869 self.emit("error", err);
3870}
3871
3872ZipFile.prototype.readEntry = function() {
3873 if (!this.lazyEntries) throw new Error("readEntry() called without lazyEntries:true");
3874 this._readEntry();
3875};
3876ZipFile.prototype._readEntry = function() {
3877 var self = this;
3878 if (self.entryCount === self.entriesRead) {
3879 // done with metadata
3880 setImmediate(function() {
3881 if (self.autoClose) self.close();
3882 if (self.emittedError) return;
3883 self.emit("end");
3884 });
3885 return;
3886 }
3887 if (self.emittedError) return;
3888 var buffer = newBuffer(46);
3889 readAndAssertNoEof(self.reader, buffer, 0, buffer.length, self.readEntryCursor, function(err) {
3890 if (err) return emitErrorAndAutoClose(self, err);
3891 if (self.emittedError) return;
3892 var entry = new Entry();
3893 // 0 - Central directory file header signature
3894 var signature = buffer.readUInt32LE(0);
3895 if (signature !== 0x02014b50) return emitErrorAndAutoClose(self, new Error("invalid central directory file header signature: 0x" + signature.toString(16)));
3896 // 4 - Version made by
3897 entry.versionMadeBy = buffer.readUInt16LE(4);
3898 // 6 - Version needed to extract (minimum)
3899 entry.versionNeededToExtract = buffer.readUInt16LE(6);
3900 // 8 - General purpose bit flag
3901 entry.generalPurposeBitFlag = buffer.readUInt16LE(8);
3902 // 10 - Compression method
3903 entry.compressionMethod = buffer.readUInt16LE(10);
3904 // 12 - File last modification time
3905 entry.lastModFileTime = buffer.readUInt16LE(12);
3906 // 14 - File last modification date
3907 entry.lastModFileDate = buffer.readUInt16LE(14);
3908 // 16 - CRC-32
3909 entry.crc32 = buffer.readUInt32LE(16);
3910 // 20 - Compressed size
3911 entry.compressedSize = buffer.readUInt32LE(20);
3912 // 24 - Uncompressed size
3913 entry.uncompressedSize = buffer.readUInt32LE(24);
3914 // 28 - File name length (n)
3915 entry.fileNameLength = buffer.readUInt16LE(28);
3916 // 30 - Extra field length (m)
3917 entry.extraFieldLength = buffer.readUInt16LE(30);
3918 // 32 - File comment length (k)
3919 entry.fileCommentLength = buffer.readUInt16LE(32);
3920 // 34 - Disk number where file starts
3921 // 36 - Internal file attributes
3922 entry.internalFileAttributes = buffer.readUInt16LE(36);
3923 // 38 - External file attributes
3924 entry.externalFileAttributes = buffer.readUInt32LE(38);
3925 // 42 - Relative offset of local file header
3926 entry.relativeOffsetOfLocalHeader = buffer.readUInt32LE(42);
3927
3928 if (entry.generalPurposeBitFlag & 0x40) return emitErrorAndAutoClose(self, new Error("strong encryption is not supported"));
3929
3930 self.readEntryCursor += 46;
3931
3932 buffer = newBuffer(entry.fileNameLength + entry.extraFieldLength + entry.fileCommentLength);
3933 readAndAssertNoEof(self.reader, buffer, 0, buffer.length, self.readEntryCursor, function(err) {
3934 if (err) return emitErrorAndAutoClose(self, err);
3935 if (self.emittedError) return;
3936 // 46 - File name
3937 var isUtf8 = (entry.generalPurposeBitFlag & 0x800) !== 0;
3938 entry.fileName = self.decodeStrings ? decodeBuffer(buffer, 0, entry.fileNameLength, isUtf8)
3939 : buffer.slice(0, entry.fileNameLength);
3940
3941 // 46+n - Extra field
3942 var fileCommentStart = entry.fileNameLength + entry.extraFieldLength;
3943 var extraFieldBuffer = buffer.slice(entry.fileNameLength, fileCommentStart);
3944 entry.extraFields = [];
3945 var i = 0;
3946 while (i < extraFieldBuffer.length - 3) {
3947 var headerId = extraFieldBuffer.readUInt16LE(i + 0);
3948 var dataSize = extraFieldBuffer.readUInt16LE(i + 2);
3949 var dataStart = i + 4;
3950 var dataEnd = dataStart + dataSize;
3951 if (dataEnd > extraFieldBuffer.length) return emitErrorAndAutoClose(self, new Error("extra field length exceeds extra field buffer size"));
3952 var dataBuffer = newBuffer(dataSize);
3953 extraFieldBuffer.copy(dataBuffer, 0, dataStart, dataEnd);
3954 entry.extraFields.push({
3955 id: headerId,
3956 data: dataBuffer,
3957 });
3958 i = dataEnd;
3959 }
3960
3961 // 46+n+m - File comment
3962 entry.fileComment = self.decodeStrings ? decodeBuffer(buffer, fileCommentStart, fileCommentStart + entry.fileCommentLength, isUtf8)
3963 : buffer.slice(fileCommentStart, fileCommentStart + entry.fileCommentLength);
3964 // compatibility hack for https://github.com/thejoshwolfe/yauzl/issues/47
3965 entry.comment = entry.fileComment;
3966
3967 self.readEntryCursor += buffer.length;
3968 self.entriesRead += 1;
3969
3970 if (entry.uncompressedSize === 0xffffffff ||
3971 entry.compressedSize === 0xffffffff ||
3972 entry.relativeOffsetOfLocalHeader === 0xffffffff) {
3973 // ZIP64 format
3974 // find the Zip64 Extended Information Extra Field
3975 var zip64EiefBuffer = null;
3976 for (var i = 0; i < entry.extraFields.length; i++) {
3977 var extraField = entry.extraFields[i];
3978 if (extraField.id === 0x0001) {
3979 zip64EiefBuffer = extraField.data;
3980 break;
3981 }
3982 }
3983 if (zip64EiefBuffer == null) {
3984 return emitErrorAndAutoClose(self, new Error("expected zip64 extended information extra field"));
3985 }
3986 var index = 0;
3987 // 0 - Original Size 8 bytes
3988 if (entry.uncompressedSize === 0xffffffff) {
3989 if (index + 8 > zip64EiefBuffer.length) {
3990 return emitErrorAndAutoClose(self, new Error("zip64 extended information extra field does not include uncompressed size"));
3991 }
3992 entry.uncompressedSize = readUInt64LE(zip64EiefBuffer, index);
3993 index += 8;
3994 }
3995 // 8 - Compressed Size 8 bytes
3996 if (entry.compressedSize === 0xffffffff) {
3997 if (index + 8 > zip64EiefBuffer.length) {
3998 return emitErrorAndAutoClose(self, new Error("zip64 extended information extra field does not include compressed size"));
3999 }
4000 entry.compressedSize = readUInt64LE(zip64EiefBuffer, index);
4001 index += 8;
4002 }
4003 // 16 - Relative Header Offset 8 bytes
4004 if (entry.relativeOffsetOfLocalHeader === 0xffffffff) {
4005 if (index + 8 > zip64EiefBuffer.length) {
4006 return emitErrorAndAutoClose(self, new Error("zip64 extended information extra field does not include relative header offset"));
4007 }
4008 entry.relativeOffsetOfLocalHeader = readUInt64LE(zip64EiefBuffer, index);
4009 index += 8;
4010 }
4011 // 24 - Disk Start Number 4 bytes
4012 }
4013
4014 // check for Info-ZIP Unicode Path Extra Field (0x7075)
4015 // see https://github.com/thejoshwolfe/yauzl/issues/33
4016 if (self.decodeStrings) {
4017 for (var i = 0; i < entry.extraFields.length; i++) {
4018 var extraField = entry.extraFields[i];
4019 if (extraField.id === 0x7075) {
4020 if (extraField.data.length < 6) {
4021 // too short to be meaningful
4022 continue;
4023 }
4024 // Version 1 byte version of this extra field, currently 1
4025 if (extraField.data.readUInt8(0) !== 1) {
4026 // > Changes may not be backward compatible so this extra
4027 // > field should not be used if the version is not recognized.
4028 continue;
4029 }
4030 // NameCRC32 4 bytes File Name Field CRC32 Checksum
4031 var oldNameCrc32 = extraField.data.readUInt32LE(1);
4032 if (bufferCrc32.unsigned(buffer.slice(0, entry.fileNameLength)) !== oldNameCrc32) {
4033 // > If the CRC check fails, this UTF-8 Path Extra Field should be
4034 // > ignored and the File Name field in the header should be used instead.
4035 continue;
4036 }
4037 // UnicodeName Variable UTF-8 version of the entry File Name
4038 entry.fileName = decodeBuffer(extraField.data, 5, extraField.data.length, true);
4039 break;
4040 }
4041 }
4042 }
4043
4044 // validate file size
4045 if (self.validateEntrySizes && entry.compressionMethod === 0) {
4046 var expectedCompressedSize = entry.uncompressedSize;
4047 if (entry.isEncrypted()) {
4048 // traditional encryption prefixes the file data with a header
4049 expectedCompressedSize += 12;
4050 }
4051 if (entry.compressedSize !== expectedCompressedSize) {
4052 var msg = "compressed/uncompressed size mismatch for stored file: " + entry.compressedSize + " != " + entry.uncompressedSize;
4053 return emitErrorAndAutoClose(self, new Error(msg));
4054 }
4055 }
4056
4057 if (self.decodeStrings) {
4058 if (!self.strictFileNames) {
4059 // allow backslash
4060 entry.fileName = entry.fileName.replace(/\\/g, "/");
4061 }
4062 var errorMessage = validateFileName(entry.fileName, self.validateFileNameOptions);
4063 if (errorMessage != null) return emitErrorAndAutoClose(self, new Error(errorMessage));
4064 }
4065 self.emit("entry", entry);
4066
4067 if (!self.lazyEntries) self._readEntry();
4068 });
4069 });
4070};
4071
4072ZipFile.prototype.openReadStream = function(entry, options, callback) {
4073 var self = this;
4074 // parameter validation
4075 var relativeStart = 0;
4076 var relativeEnd = entry.compressedSize;
4077 if (callback == null) {
4078 callback = options;
4079 options = {};
4080 } else {
4081 // validate options that the caller has no excuse to get wrong
4082 if (options.decrypt != null) {
4083 if (!entry.isEncrypted()) {
4084 throw new Error("options.decrypt can only be specified for encrypted entries");
4085 }
4086 if (options.decrypt !== false) throw new Error("invalid options.decrypt value: " + options.decrypt);
4087 if (entry.isCompressed()) {
4088 if (options.decompress !== false) throw new Error("entry is encrypted and compressed, and options.decompress !== false");
4089 }
4090 }
4091 if (options.decompress != null) {
4092 if (!entry.isCompressed()) {
4093 throw new Error("options.decompress can only be specified for compressed entries");
4094 }
4095 if (!(options.decompress === false || options.decompress === true)) {
4096 throw new Error("invalid options.decompress value: " + options.decompress);
4097 }
4098 }
4099 if (options.start != null || options.end != null) {
4100 if (entry.isCompressed() && options.decompress !== false) {
4101 throw new Error("start/end range not allowed for compressed entry without options.decompress === false");
4102 }
4103 if (entry.isEncrypted() && options.decrypt !== false) {
4104 throw new Error("start/end range not allowed for encrypted entry without options.decrypt === false");
4105 }
4106 }
4107 if (options.start != null) {
4108 relativeStart = options.start;
4109 if (relativeStart < 0) throw new Error("options.start < 0");
4110 if (relativeStart > entry.compressedSize) throw new Error("options.start > entry.compressedSize");
4111 }
4112 if (options.end != null) {
4113 relativeEnd = options.end;
4114 if (relativeEnd < 0) throw new Error("options.end < 0");
4115 if (relativeEnd > entry.compressedSize) throw new Error("options.end > entry.compressedSize");
4116 if (relativeEnd < relativeStart) throw new Error("options.end < options.start");
4117 }
4118 }
4119 // any further errors can either be caused by the zipfile,
4120 // or were introduced in a minor version of yauzl,
4121 // so should be passed to the client rather than thrown.
4122 if (!self.isOpen) return callback(new Error("closed"));
4123 if (entry.isEncrypted()) {
4124 if (options.decrypt !== false) return callback(new Error("entry is encrypted, and options.decrypt !== false"));
4125 }
4126 // make sure we don't lose the fd before we open the actual read stream
4127 self.reader.ref();
4128 var buffer = newBuffer(30);
4129 readAndAssertNoEof(self.reader, buffer, 0, buffer.length, entry.relativeOffsetOfLocalHeader, function(err) {
4130 try {
4131 if (err) return callback(err);
4132 // 0 - Local file header signature = 0x04034b50
4133 var signature = buffer.readUInt32LE(0);
4134 if (signature !== 0x04034b50) {
4135 return callback(new Error("invalid local file header signature: 0x" + signature.toString(16)));
4136 }
4137 // all this should be redundant
4138 // 4 - Version needed to extract (minimum)
4139 // 6 - General purpose bit flag
4140 // 8 - Compression method
4141 // 10 - File last modification time
4142 // 12 - File last modification date
4143 // 14 - CRC-32
4144 // 18 - Compressed size
4145 // 22 - Uncompressed size
4146 // 26 - File name length (n)
4147 var fileNameLength = buffer.readUInt16LE(26);
4148 // 28 - Extra field length (m)
4149 var extraFieldLength = buffer.readUInt16LE(28);
4150 // 30 - File name
4151 // 30+n - Extra field
4152 var localFileHeaderEnd = entry.relativeOffsetOfLocalHeader + buffer.length + fileNameLength + extraFieldLength;
4153 var decompress;
4154 if (entry.compressionMethod === 0) {
4155 // 0 - The file is stored (no compression)
4156 decompress = false;
4157 } else if (entry.compressionMethod === 8) {
4158 // 8 - The file is Deflated
4159 decompress = options.decompress != null ? options.decompress : true;
4160 } else {
4161 return callback(new Error("unsupported compression method: " + entry.compressionMethod));
4162 }
4163 var fileDataStart = localFileHeaderEnd;
4164 var fileDataEnd = fileDataStart + entry.compressedSize;
4165 if (entry.compressedSize !== 0) {
4166 // bounds check now, because the read streams will probably not complain loud enough.
4167 // since we're dealing with an unsigned offset plus an unsigned size,
4168 // we only have 1 thing to check for.
4169 if (fileDataEnd > self.fileSize) {
4170 return callback(new Error("file data overflows file bounds: " +
4171 fileDataStart + " + " + entry.compressedSize + " > " + self.fileSize));
4172 }
4173 }
4174 var readStream = self.reader.createReadStream({
4175 start: fileDataStart + relativeStart,
4176 end: fileDataStart + relativeEnd,
4177 });
4178 var endpointStream = readStream;
4179 if (decompress) {
4180 var destroyed = false;
4181 var inflateFilter = zlib.createInflateRaw();
4182 readStream.on("error", function(err) {
4183 // setImmediate here because errors can be emitted during the first call to pipe()
4184 setImmediate(function() {
4185 if (!destroyed) inflateFilter.emit("error", err);
4186 });
4187 });
4188 readStream.pipe(inflateFilter);
4189
4190 if (self.validateEntrySizes) {
4191 endpointStream = new AssertByteCountStream(entry.uncompressedSize);
4192 inflateFilter.on("error", function(err) {
4193 // forward zlib errors to the client-visible stream
4194 setImmediate(function() {
4195 if (!destroyed) endpointStream.emit("error", err);
4196 });
4197 });
4198 inflateFilter.pipe(endpointStream);
4199 } else {
4200 // the zlib filter is the client-visible stream
4201 endpointStream = inflateFilter;
4202 }
4203 // this is part of yauzl's API, so implement this function on the client-visible stream
4204 endpointStream.destroy = function() {
4205 destroyed = true;
4206 if (inflateFilter !== endpointStream) inflateFilter.unpipe(endpointStream);
4207 readStream.unpipe(inflateFilter);
4208 // TODO: the inflateFilter may cause a memory leak. see Issue #27.
4209 readStream.destroy();
4210 };
4211 }
4212 callback(null, endpointStream);
4213 } finally {
4214 self.reader.unref();
4215 }
4216 });
4217};
4218
4219function Entry() {
4220}
4221Entry.prototype.getLastModDate = function() {
4222 return dosDateTimeToDate(this.lastModFileDate, this.lastModFileTime);
4223};
4224Entry.prototype.isEncrypted = function() {
4225 return (this.generalPurposeBitFlag & 0x1) !== 0;
4226};
4227Entry.prototype.isCompressed = function() {
4228 return this.compressionMethod === 8;
4229};
4230
4231function dosDateTimeToDate(date, time) {
4232 var day = date & 0x1f; // 1-31
4233 var month = (date >> 5 & 0xf) - 1; // 1-12, 0-11
4234 var year = (date >> 9 & 0x7f) + 1980; // 0-128, 1980-2108
4235
4236 var millisecond = 0;
4237 var second = (time & 0x1f) * 2; // 0-29, 0-58 (even numbers)
4238 var minute = time >> 5 & 0x3f; // 0-59
4239 var hour = time >> 11 & 0x1f; // 0-23
4240
4241 return new Date(year, month, day, hour, minute, second, millisecond);
4242}
4243
4244function validateFileName(fileName) {
4245 if (fileName.indexOf("\\") !== -1) {
4246 return "invalid characters in fileName: " + fileName;
4247 }
4248 if (/^[a-zA-Z]:/.test(fileName) || /^\//.test(fileName)) {
4249 return "absolute path: " + fileName;
4250 }
4251 if (fileName.split("/").indexOf("..") !== -1) {
4252 return "invalid relative path: " + fileName;
4253 }
4254 // all good
4255 return null;
4256}
4257
4258function readAndAssertNoEof(reader, buffer, offset, length, position, callback) {
4259 if (length === 0) {
4260 // fs.read will throw an out-of-bounds error if you try to read 0 bytes from a 0 byte file
4261 return setImmediate(function() { callback(null, newBuffer(0)); });
4262 }
4263 reader.read(buffer, offset, length, position, function(err, bytesRead) {
4264 if (err) return callback(err);
4265 if (bytesRead < length) {
4266 return callback(new Error("unexpected EOF"));
4267 }
4268 callback();
4269 });
4270}
4271
4272util.inherits(AssertByteCountStream, Transform$2);
4273function AssertByteCountStream(byteCount) {
4274 Transform$2.call(this);
4275 this.actualByteCount = 0;
4276 this.expectedByteCount = byteCount;
4277}
4278AssertByteCountStream.prototype._transform = function(chunk, encoding, cb) {
4279 this.actualByteCount += chunk.length;
4280 if (this.actualByteCount > this.expectedByteCount) {
4281 var msg = "too many bytes in the stream. expected " + this.expectedByteCount + ". got at least " + this.actualByteCount;
4282 return cb(new Error(msg));
4283 }
4284 cb(null, chunk);
4285};
4286AssertByteCountStream.prototype._flush = function(cb) {
4287 if (this.actualByteCount < this.expectedByteCount) {
4288 var msg = "not enough bytes in the stream. expected " + this.expectedByteCount + ". got only " + this.actualByteCount;
4289 return cb(new Error(msg));
4290 }
4291 cb();
4292};
4293
4294util.inherits(RandomAccessReader, EventEmitter$1);
4295function RandomAccessReader() {
4296 EventEmitter$1.call(this);
4297 this.refCount = 0;
4298}
4299RandomAccessReader.prototype.ref = function() {
4300 this.refCount += 1;
4301};
4302RandomAccessReader.prototype.unref = function() {
4303 var self = this;
4304 self.refCount -= 1;
4305
4306 if (self.refCount > 0) return;
4307 if (self.refCount < 0) throw new Error("invalid unref");
4308
4309 self.close(onCloseDone);
4310
4311 function onCloseDone(err) {
4312 if (err) return self.emit('error', err);
4313 self.emit('close');
4314 }
4315};
4316RandomAccessReader.prototype.createReadStream = function(options) {
4317 var start = options.start;
4318 var end = options.end;
4319 if (start === end) {
4320 var emptyStream = new PassThrough$1();
4321 setImmediate(function() {
4322 emptyStream.end();
4323 });
4324 return emptyStream;
4325 }
4326 var stream = this._readStreamForRange(start, end);
4327
4328 var destroyed = false;
4329 var refUnrefFilter = new RefUnrefFilter(this);
4330 stream.on("error", function(err) {
4331 setImmediate(function() {
4332 if (!destroyed) refUnrefFilter.emit("error", err);
4333 });
4334 });
4335 refUnrefFilter.destroy = function() {
4336 stream.unpipe(refUnrefFilter);
4337 refUnrefFilter.unref();
4338 stream.destroy();
4339 };
4340
4341 var byteCounter = new AssertByteCountStream(end - start);
4342 refUnrefFilter.on("error", function(err) {
4343 setImmediate(function() {
4344 if (!destroyed) byteCounter.emit("error", err);
4345 });
4346 });
4347 byteCounter.destroy = function() {
4348 destroyed = true;
4349 refUnrefFilter.unpipe(byteCounter);
4350 refUnrefFilter.destroy();
4351 };
4352
4353 return stream.pipe(refUnrefFilter).pipe(byteCounter);
4354};
4355RandomAccessReader.prototype._readStreamForRange = function(start, end) {
4356 throw new Error("not implemented");
4357};
4358RandomAccessReader.prototype.read = function(buffer, offset, length, position, callback) {
4359 var readStream = this.createReadStream({start: position, end: position + length});
4360 var writeStream = new Writable$2();
4361 var written = 0;
4362 writeStream._write = function(chunk, encoding, cb) {
4363 chunk.copy(buffer, offset + written, 0, chunk.length);
4364 written += chunk.length;
4365 cb();
4366 };
4367 writeStream.on("finish", callback);
4368 readStream.on("error", function(error) {
4369 callback(error);
4370 });
4371 readStream.pipe(writeStream);
4372};
4373RandomAccessReader.prototype.close = function(callback) {
4374 setImmediate(callback);
4375};
4376
4377util.inherits(RefUnrefFilter, PassThrough$1);
4378function RefUnrefFilter(context) {
4379 PassThrough$1.call(this);
4380 this.context = context;
4381 this.context.ref();
4382 this.unreffedYet = false;
4383}
4384RefUnrefFilter.prototype._flush = function(cb) {
4385 this.unref();
4386 cb();
4387};
4388RefUnrefFilter.prototype.unref = function(cb) {
4389 if (this.unreffedYet) return;
4390 this.unreffedYet = true;
4391 this.context.unref();
4392};
4393
4394var cp437 = '\u0000☺☻♥♦♣♠•◘○◙♂♀♪♫☼►◄↕‼¶§▬↨↑↓→←∟↔▲▼ !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~⌂ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ ';
4395function decodeBuffer(buffer, start, end, isUtf8) {
4396 if (isUtf8) {
4397 return buffer.toString("utf8", start, end);
4398 } else {
4399 var result = "";
4400 for (var i = start; i < end; i++) {
4401 result += cp437[buffer[i]];
4402 }
4403 return result;
4404 }
4405}
4406
4407function readUInt64LE(buffer, offset) {
4408 // there is no native function for this, because we can't actually store 64-bit integers precisely.
4409 // after 53 bits, JavaScript's Number type (IEEE 754 double) can't store individual integers anymore.
4410 // but since 53 bits is a whole lot more than 32 bits, we do our best anyway.
4411 var lower32 = buffer.readUInt32LE(offset);
4412 var upper32 = buffer.readUInt32LE(offset + 4);
4413 // we can't use bitshifting here, because JavaScript bitshifting only works on 32-bit integers.
4414 return upper32 * 0x100000000 + lower32;
4415 // as long as we're bounds checking the result of this function against the total file size,
4416 // we'll catch any overflow errors, because we already made sure the total file size was within reason.
4417}
4418
4419// Node 10 deprecated new Buffer().
4420var newBuffer;
4421if (typeof Buffer.allocUnsafe === "function") {
4422 newBuffer = function(len) {
4423 return Buffer.allocUnsafe(len);
4424 };
4425} else {
4426 newBuffer = function(len) {
4427 return new Buffer(len);
4428 };
4429}
4430
4431function defaultCallback(err) {
4432 if (err) throw err;
4433}
4434
4435var yauzl = {
4436 open: open_1,
4437 fromFd: fromFd_1,
4438 fromBuffer: fromBuffer_1,
4439 fromRandomAccessReader: fromRandomAccessReader_1,
4440 dosDateTimeToDate: dosDateTimeToDate_1,
4441 validateFileName: validateFileName_1,
4442 ZipFile: ZipFile_1,
4443 Entry: Entry_1,
4444 RandomAccessReader: RandomAccessReader_1
4445};
4446
4447var name$1 = "got";
4448var version$1 = "9.5.0";
4449var description$1 = "Simplified HTTP requests";
4450var license$1 = "MIT";
4451var repository$1 = "sindresorhus/got";
4452var main = "source";
4453var engines = {
4454 node: ">=8.6"
4455};
4456var scripts$1 = {
4457 test: "xo && nyc ava",
4458 release: "np"
4459};
4460var files$1 = [
4461 "source"
4462];
4463var keywords$1 = [
4464 "http",
4465 "https",
4466 "get",
4467 "got",
4468 "url",
4469 "uri",
4470 "request",
4471 "util",
4472 "utility",
4473 "simple",
4474 "curl",
4475 "wget",
4476 "fetch",
4477 "net",
4478 "network",
4479 "electron"
4480];
4481var dependencies$1 = {
4482 "@sindresorhus/is": "^0.14.0",
4483 "@szmarczak/http-timer": "^1.1.0",
4484 "cacheable-request": "^5.1.0",
4485 "decompress-response": "^3.3.0",
4486 duplexer3: "^0.1.4",
4487 "get-stream": "^4.1.0",
4488 "lowercase-keys": "^1.0.1",
4489 "mimic-response": "^1.0.1",
4490 "p-cancelable": "^1.0.0",
4491 "to-readable-stream": "^1.0.0",
4492 "url-parse-lax": "^3.0.0"
4493};
4494var devDependencies$1 = {
4495 ava: "^1.0.1",
4496 coveralls: "^3.0.0",
4497 delay: "^4.1.0",
4498 "form-data": "^2.3.3",
4499 "get-port": "^4.0.0",
4500 np: "^3.1.0",
4501 nyc: "^13.1.0",
4502 "p-event": "^2.1.0",
4503 pem: "^1.13.2",
4504 proxyquire: "^2.0.1",
4505 sinon: "^7.2.2",
4506 "slow-stream": "0.0.4",
4507 tempfile: "^2.0.0",
4508 tempy: "^0.2.1",
4509 "tough-cookie": "^2.4.3",
4510 xo: "^0.23.0"
4511};
4512var ava = {
4513 concurrency: 4
4514};
4515var browser = {
4516 "decompress-response": false,
4517 electron: false
4518};
4519var _resolved = "https://registry.npmjs.org/got/-/got-9.5.0.tgz";
4520var _integrity = "sha512-N+4kb6i9t1lauJ4NwLVVoFVLxZNa6i+iivtNzCSVw7+bVbTXoq0qXctdd8i9rj3lrI0zDk5NGzcO4bfpEP6Uuw==";
4521var _from = "got@9.5.0";
4522var _package$2 = {
4523 name: name$1,
4524 version: version$1,
4525 description: description$1,
4526 license: license$1,
4527 repository: repository$1,
4528 main: main,
4529 engines: engines,
4530 scripts: scripts$1,
4531 files: files$1,
4532 keywords: keywords$1,
4533 dependencies: dependencies$1,
4534 devDependencies: devDependencies$1,
4535 ava: ava,
4536 browser: browser,
4537 _resolved: _resolved,
4538 _integrity: _integrity,
4539 _from: _from
4540};
4541
4542var _package$3 = /*#__PURE__*/Object.freeze({
4543 __proto__: null,
4544 name: name$1,
4545 version: version$1,
4546 description: description$1,
4547 license: license$1,
4548 repository: repository$1,
4549 main: main,
4550 engines: engines,
4551 scripts: scripts$1,
4552 files: files$1,
4553 keywords: keywords$1,
4554 dependencies: dependencies$1,
4555 devDependencies: devDependencies$1,
4556 ava: ava,
4557 browser: browser,
4558 _resolved: _resolved,
4559 _integrity: _integrity,
4560 _from: _from,
4561 'default': _package$2
4562});
4563
4564class CancelError extends Error {
4565 constructor(reason) {
4566 super(reason || 'Promise was canceled');
4567 this.name = 'CancelError';
4568 }
4569
4570 get isCanceled() {
4571 return true;
4572 }
4573}
4574
4575class PCancelable {
4576 static fn(userFn) {
4577 return (...args) => {
4578 return new PCancelable((resolve, reject, onCancel) => {
4579 args.push(onCancel);
4580 userFn(...args).then(resolve, reject);
4581 });
4582 };
4583 }
4584
4585 constructor(executor) {
4586 this._cancelHandlers = [];
4587 this._isPending = true;
4588 this._isCanceled = false;
4589 this._rejectOnCancel = true;
4590
4591 this._promise = new Promise((resolve, reject) => {
4592 this._reject = reject;
4593
4594 const onResolve = value => {
4595 this._isPending = false;
4596 resolve(value);
4597 };
4598
4599 const onReject = error => {
4600 this._isPending = false;
4601 reject(error);
4602 };
4603
4604 const onCancel = handler => {
4605 this._cancelHandlers.push(handler);
4606 };
4607
4608 Object.defineProperties(onCancel, {
4609 shouldReject: {
4610 get: () => this._rejectOnCancel,
4611 set: bool => {
4612 this._rejectOnCancel = bool;
4613 }
4614 }
4615 });
4616
4617 return executor(onResolve, onReject, onCancel);
4618 });
4619 }
4620
4621 then(onFulfilled, onRejected) {
4622 return this._promise.then(onFulfilled, onRejected);
4623 }
4624
4625 catch(onRejected) {
4626 return this._promise.catch(onRejected);
4627 }
4628
4629 finally(onFinally) {
4630 return this._promise.finally(onFinally);
4631 }
4632
4633 cancel(reason) {
4634 if (!this._isPending || this._isCanceled) {
4635 return;
4636 }
4637
4638 if (this._cancelHandlers.length > 0) {
4639 try {
4640 for (const handler of this._cancelHandlers) {
4641 handler();
4642 }
4643 } catch (error) {
4644 this._reject(error);
4645 }
4646 }
4647
4648 this._isCanceled = true;
4649 if (this._rejectOnCancel) {
4650 this._reject(new CancelError(reason));
4651 }
4652 }
4653
4654 get isCanceled() {
4655 return this._isCanceled;
4656 }
4657}
4658
4659Object.setPrototypeOf(PCancelable.prototype, Promise.prototype);
4660
4661var pCancelable = PCancelable;
4662var CancelError_1 = CancelError;
4663pCancelable.CancelError = CancelError_1;
4664
4665var dist = createCommonjsModule(function (module, exports) {
4666/// <reference lib="es2016"/>
4667/// <reference lib="es2017.sharedmemory"/>
4668/// <reference lib="esnext.asynciterable"/>
4669/// <reference lib="dom"/>
4670Object.defineProperty(exports, "__esModule", { value: true });
4671// TODO: Use the `URL` global when targeting Node.js 10
4672// tslint:disable-next-line
4673const URLGlobal = typeof URL === 'undefined' ? url.URL : URL;
4674const toString = Object.prototype.toString;
4675const isOfType = (type) => (value) => typeof value === type;
4676const isBuffer = (input) => !is.nullOrUndefined(input) && !is.nullOrUndefined(input.constructor) && is.function_(input.constructor.isBuffer) && input.constructor.isBuffer(input);
4677const getObjectType = (value) => {
4678 const objectName = toString.call(value).slice(8, -1);
4679 if (objectName) {
4680 return objectName;
4681 }
4682 return null;
4683};
4684const isObjectOfType = (type) => (value) => getObjectType(value) === type;
4685function is(value) {
4686 switch (value) {
4687 case null:
4688 return "null" /* null */;
4689 case true:
4690 case false:
4691 return "boolean" /* boolean */;
4692 }
4693 switch (typeof value) {
4694 case 'undefined':
4695 return "undefined" /* undefined */;
4696 case 'string':
4697 return "string" /* string */;
4698 case 'number':
4699 return "number" /* number */;
4700 case 'symbol':
4701 return "symbol" /* symbol */;
4702 }
4703 if (is.function_(value)) {
4704 return "Function" /* Function */;
4705 }
4706 if (is.observable(value)) {
4707 return "Observable" /* Observable */;
4708 }
4709 if (Array.isArray(value)) {
4710 return "Array" /* Array */;
4711 }
4712 if (isBuffer(value)) {
4713 return "Buffer" /* Buffer */;
4714 }
4715 const tagType = getObjectType(value);
4716 if (tagType) {
4717 return tagType;
4718 }
4719 if (value instanceof String || value instanceof Boolean || value instanceof Number) {
4720 throw new TypeError('Please don\'t use object wrappers for primitive types');
4721 }
4722 return "Object" /* Object */;
4723}
4724(function (is) {
4725 // tslint:disable-next-line:strict-type-predicates
4726 const isObject = (value) => typeof value === 'object';
4727 // tslint:disable:variable-name
4728 is.undefined = isOfType('undefined');
4729 is.string = isOfType('string');
4730 is.number = isOfType('number');
4731 is.function_ = isOfType('function');
4732 // tslint:disable-next-line:strict-type-predicates
4733 is.null_ = (value) => value === null;
4734 is.class_ = (value) => is.function_(value) && value.toString().startsWith('class ');
4735 is.boolean = (value) => value === true || value === false;
4736 is.symbol = isOfType('symbol');
4737 // tslint:enable:variable-name
4738 is.numericString = (value) => is.string(value) && value.length > 0 && !Number.isNaN(Number(value));
4739 is.array = Array.isArray;
4740 is.buffer = isBuffer;
4741 is.nullOrUndefined = (value) => is.null_(value) || is.undefined(value);
4742 is.object = (value) => !is.nullOrUndefined(value) && (is.function_(value) || isObject(value));
4743 is.iterable = (value) => !is.nullOrUndefined(value) && is.function_(value[Symbol.iterator]);
4744 is.asyncIterable = (value) => !is.nullOrUndefined(value) && is.function_(value[Symbol.asyncIterator]);
4745 is.generator = (value) => is.iterable(value) && is.function_(value.next) && is.function_(value.throw);
4746 is.nativePromise = (value) => isObjectOfType("Promise" /* Promise */)(value);
4747 const hasPromiseAPI = (value) => !is.null_(value) &&
4748 isObject(value) &&
4749 is.function_(value.then) &&
4750 is.function_(value.catch);
4751 is.promise = (value) => is.nativePromise(value) || hasPromiseAPI(value);
4752 is.generatorFunction = isObjectOfType("GeneratorFunction" /* GeneratorFunction */);
4753 is.asyncFunction = isObjectOfType("AsyncFunction" /* AsyncFunction */);
4754 is.boundFunction = (value) => is.function_(value) && !value.hasOwnProperty('prototype');
4755 is.regExp = isObjectOfType("RegExp" /* RegExp */);
4756 is.date = isObjectOfType("Date" /* Date */);
4757 is.error = isObjectOfType("Error" /* Error */);
4758 is.map = (value) => isObjectOfType("Map" /* Map */)(value);
4759 is.set = (value) => isObjectOfType("Set" /* Set */)(value);
4760 is.weakMap = (value) => isObjectOfType("WeakMap" /* WeakMap */)(value);
4761 is.weakSet = (value) => isObjectOfType("WeakSet" /* WeakSet */)(value);
4762 is.int8Array = isObjectOfType("Int8Array" /* Int8Array */);
4763 is.uint8Array = isObjectOfType("Uint8Array" /* Uint8Array */);
4764 is.uint8ClampedArray = isObjectOfType("Uint8ClampedArray" /* Uint8ClampedArray */);
4765 is.int16Array = isObjectOfType("Int16Array" /* Int16Array */);
4766 is.uint16Array = isObjectOfType("Uint16Array" /* Uint16Array */);
4767 is.int32Array = isObjectOfType("Int32Array" /* Int32Array */);
4768 is.uint32Array = isObjectOfType("Uint32Array" /* Uint32Array */);
4769 is.float32Array = isObjectOfType("Float32Array" /* Float32Array */);
4770 is.float64Array = isObjectOfType("Float64Array" /* Float64Array */);
4771 is.arrayBuffer = isObjectOfType("ArrayBuffer" /* ArrayBuffer */);
4772 is.sharedArrayBuffer = isObjectOfType("SharedArrayBuffer" /* SharedArrayBuffer */);
4773 is.dataView = isObjectOfType("DataView" /* DataView */);
4774 is.directInstanceOf = (instance, klass) => Object.getPrototypeOf(instance) === klass.prototype;
4775 is.urlInstance = (value) => isObjectOfType("URL" /* URL */)(value);
4776 is.urlString = (value) => {
4777 if (!is.string(value)) {
4778 return false;
4779 }
4780 try {
4781 new URLGlobal(value); // tslint:disable-line no-unused-expression
4782 return true;
4783 }
4784 catch (_a) {
4785 return false;
4786 }
4787 };
4788 is.truthy = (value) => Boolean(value);
4789 is.falsy = (value) => !value;
4790 is.nan = (value) => Number.isNaN(value);
4791 const primitiveTypes = new Set([
4792 'undefined',
4793 'string',
4794 'number',
4795 'boolean',
4796 'symbol'
4797 ]);
4798 is.primitive = (value) => is.null_(value) || primitiveTypes.has(typeof value);
4799 is.integer = (value) => Number.isInteger(value);
4800 is.safeInteger = (value) => Number.isSafeInteger(value);
4801 is.plainObject = (value) => {
4802 // From: https://github.com/sindresorhus/is-plain-obj/blob/master/index.js
4803 let prototype;
4804 return getObjectType(value) === "Object" /* Object */ &&
4805 (prototype = Object.getPrototypeOf(value), prototype === null || // tslint:disable-line:ban-comma-operator
4806 prototype === Object.getPrototypeOf({}));
4807 };
4808 const typedArrayTypes = new Set([
4809 "Int8Array" /* Int8Array */,
4810 "Uint8Array" /* Uint8Array */,
4811 "Uint8ClampedArray" /* Uint8ClampedArray */,
4812 "Int16Array" /* Int16Array */,
4813 "Uint16Array" /* Uint16Array */,
4814 "Int32Array" /* Int32Array */,
4815 "Uint32Array" /* Uint32Array */,
4816 "Float32Array" /* Float32Array */,
4817 "Float64Array" /* Float64Array */
4818 ]);
4819 is.typedArray = (value) => {
4820 const objectType = getObjectType(value);
4821 if (objectType === null) {
4822 return false;
4823 }
4824 return typedArrayTypes.has(objectType);
4825 };
4826 const isValidLength = (value) => is.safeInteger(value) && value > -1;
4827 is.arrayLike = (value) => !is.nullOrUndefined(value) && !is.function_(value) && isValidLength(value.length);
4828 is.inRange = (value, range) => {
4829 if (is.number(range)) {
4830 return value >= Math.min(0, range) && value <= Math.max(range, 0);
4831 }
4832 if (is.array(range) && range.length === 2) {
4833 return value >= Math.min(...range) && value <= Math.max(...range);
4834 }
4835 throw new TypeError(`Invalid range: ${JSON.stringify(range)}`);
4836 };
4837 const NODE_TYPE_ELEMENT = 1;
4838 const DOM_PROPERTIES_TO_CHECK = [
4839 'innerHTML',
4840 'ownerDocument',
4841 'style',
4842 'attributes',
4843 'nodeValue'
4844 ];
4845 is.domElement = (value) => is.object(value) && value.nodeType === NODE_TYPE_ELEMENT && is.string(value.nodeName) &&
4846 !is.plainObject(value) && DOM_PROPERTIES_TO_CHECK.every(property => property in value);
4847 is.observable = (value) => {
4848 if (!value) {
4849 return false;
4850 }
4851 if (value[Symbol.observable] && value === value[Symbol.observable]()) {
4852 return true;
4853 }
4854 if (value['@@observable'] && value === value['@@observable']()) {
4855 return true;
4856 }
4857 return false;
4858 };
4859 is.nodeStream = (value) => !is.nullOrUndefined(value) && isObject(value) && is.function_(value.pipe) && !is.observable(value);
4860 is.infinite = (value) => value === Infinity || value === -Infinity;
4861 const isAbsoluteMod2 = (rem) => (value) => is.integer(value) && Math.abs(value % 2) === rem;
4862 is.even = isAbsoluteMod2(0);
4863 is.odd = isAbsoluteMod2(1);
4864 const isWhiteSpaceString = (value) => is.string(value) && /\S/.test(value) === false;
4865 is.emptyArray = (value) => is.array(value) && value.length === 0;
4866 is.nonEmptyArray = (value) => is.array(value) && value.length > 0;
4867 is.emptyString = (value) => is.string(value) && value.length === 0;
4868 is.nonEmptyString = (value) => is.string(value) && value.length > 0;
4869 is.emptyStringOrWhitespace = (value) => is.emptyString(value) || isWhiteSpaceString(value);
4870 is.emptyObject = (value) => is.object(value) && !is.map(value) && !is.set(value) && Object.keys(value).length === 0;
4871 is.nonEmptyObject = (value) => is.object(value) && !is.map(value) && !is.set(value) && Object.keys(value).length > 0;
4872 is.emptySet = (value) => is.set(value) && value.size === 0;
4873 is.nonEmptySet = (value) => is.set(value) && value.size > 0;
4874 is.emptyMap = (value) => is.map(value) && value.size === 0;
4875 is.nonEmptyMap = (value) => is.map(value) && value.size > 0;
4876 const predicateOnArray = (method, predicate, values) => {
4877 if (is.function_(predicate) === false) {
4878 throw new TypeError(`Invalid predicate: ${JSON.stringify(predicate)}`);
4879 }
4880 if (values.length === 0) {
4881 throw new TypeError('Invalid number of values');
4882 }
4883 return method.call(values, predicate);
4884 };
4885 // tslint:disable variable-name
4886 is.any = (predicate, ...values) => predicateOnArray(Array.prototype.some, predicate, values);
4887 is.all = (predicate, ...values) => predicateOnArray(Array.prototype.every, predicate, values);
4888 // tslint:enable variable-name
4889})(is || (is = {}));
4890// Some few keywords are reserved, but we'll populate them for Node.js users
4891// See https://github.com/Microsoft/TypeScript/issues/2536
4892Object.defineProperties(is, {
4893 class: {
4894 value: is.class_
4895 },
4896 function: {
4897 value: is.function_
4898 },
4899 null: {
4900 value: is.null_
4901 }
4902});
4903exports.default = is;
4904// For CommonJS default export support
4905module.exports = is;
4906module.exports.default = is;
4907
4908});
4909
4910unwrapExports(dist);
4911
4912class GotError extends Error {
4913 constructor(message, error, options) {
4914 super(message);
4915 Error.captureStackTrace(this, this.constructor);
4916 this.name = 'GotError';
4917
4918 if (!dist.undefined(error.code)) {
4919 this.code = error.code;
4920 }
4921
4922 Object.assign(this, {
4923 host: options.host,
4924 hostname: options.hostname,
4925 method: options.method,
4926 path: options.path,
4927 socketPath: options.socketPath,
4928 protocol: options.protocol,
4929 url: options.href,
4930 gotOptions: options
4931 });
4932 }
4933}
4934
4935var GotError_1 = GotError;
4936
4937var CacheError = class extends GotError {
4938 constructor(error, options) {
4939 super(error.message, error, options);
4940 this.name = 'CacheError';
4941 }
4942};
4943
4944var RequestError = class extends GotError {
4945 constructor(error, options) {
4946 super(error.message, error, options);
4947 this.name = 'RequestError';
4948 }
4949};
4950
4951var ReadError = class extends GotError {
4952 constructor(error, options) {
4953 super(error.message, error, options);
4954 this.name = 'ReadError';
4955 }
4956};
4957
4958var ParseError = class extends GotError {
4959 constructor(error, statusCode, options, data) {
4960 super(`${error.message} in "${url.format(options)}": \n${data.slice(0, 77)}...`, error, options);
4961 this.name = 'ParseError';
4962 this.statusCode = statusCode;
4963 this.statusMessage = http.STATUS_CODES[this.statusCode];
4964 }
4965};
4966
4967var HTTPError = class extends GotError {
4968 constructor(response, options) {
4969 const {statusCode} = response;
4970 let {statusMessage} = response;
4971
4972 if (statusMessage) {
4973 statusMessage = statusMessage.replace(/\r?\n/g, ' ').trim();
4974 } else {
4975 statusMessage = http.STATUS_CODES[statusCode];
4976 }
4977 super(`Response code ${statusCode} (${statusMessage})`, {}, options);
4978 this.name = 'HTTPError';
4979 this.statusCode = statusCode;
4980 this.statusMessage = statusMessage;
4981 this.headers = response.headers;
4982 this.body = response.body;
4983 }
4984};
4985
4986var MaxRedirectsError = class extends GotError {
4987 constructor(statusCode, redirectUrls, options) {
4988 super('Redirected 10 times. Aborting.', {}, options);
4989 this.name = 'MaxRedirectsError';
4990 this.statusCode = statusCode;
4991 this.statusMessage = http.STATUS_CODES[this.statusCode];
4992 this.redirectUrls = redirectUrls;
4993 }
4994};
4995
4996var UnsupportedProtocolError = class extends GotError {
4997 constructor(options) {
4998 super(`Unsupported protocol "${options.protocol}"`, {}, options);
4999 this.name = 'UnsupportedProtocolError';
5000 }
5001};
5002
5003var TimeoutError = class extends GotError {
5004 constructor(error, options) {
5005 super(error.message, {code: 'ETIMEDOUT'}, options);
5006 this.name = 'TimeoutError';
5007 this.event = error.event;
5008 }
5009};
5010
5011var CancelError$1 = pCancelable.CancelError;
5012
5013var errors = {
5014 GotError: GotError_1,
5015 CacheError: CacheError,
5016 RequestError: RequestError,
5017 ReadError: ReadError,
5018 ParseError: ParseError,
5019 HTTPError: HTTPError,
5020 MaxRedirectsError: MaxRedirectsError,
5021 UnsupportedProtocolError: UnsupportedProtocolError,
5022 TimeoutError: TimeoutError,
5023 CancelError: CancelError$1
5024};
5025
5026function DuplexWrapper(options, writable, readable) {
5027 if (typeof readable === "undefined") {
5028 readable = writable;
5029 writable = options;
5030 options = null;
5031 }
5032
5033 stream.Duplex.call(this, options);
5034
5035 if (typeof readable.read !== "function") {
5036 readable = (new stream.Readable(options)).wrap(readable);
5037 }
5038
5039 this._writable = writable;
5040 this._readable = readable;
5041 this._waiting = false;
5042
5043 var self = this;
5044
5045 writable.once("finish", function() {
5046 self.end();
5047 });
5048
5049 this.once("finish", function() {
5050 writable.end();
5051 });
5052
5053 readable.on("readable", function() {
5054 if (self._waiting) {
5055 self._waiting = false;
5056 self._read();
5057 }
5058 });
5059
5060 readable.once("end", function() {
5061 self.push(null);
5062 });
5063
5064 if (!options || typeof options.bubbleErrors === "undefined" || options.bubbleErrors) {
5065 writable.on("error", function(err) {
5066 self.emit("error", err);
5067 });
5068
5069 readable.on("error", function(err) {
5070 self.emit("error", err);
5071 });
5072 }
5073}
5074
5075DuplexWrapper.prototype = Object.create(stream.Duplex.prototype, {constructor: {value: DuplexWrapper}});
5076
5077DuplexWrapper.prototype._write = function _write(input, encoding, done) {
5078 this._writable.write(input, encoding, done);
5079};
5080
5081DuplexWrapper.prototype._read = function _read() {
5082 var buf;
5083 var reads = 0;
5084 while ((buf = this._readable.read()) !== null) {
5085 this.push(buf);
5086 reads++;
5087 }
5088 if (reads === 0) {
5089 this._waiting = true;
5090 }
5091};
5092
5093var duplexer3 = function duplex2(options, writable, readable) {
5094 return new DuplexWrapper(options, writable, readable);
5095};
5096
5097var DuplexWrapper_1 = DuplexWrapper;
5098duplexer3.DuplexWrapper = DuplexWrapper_1;
5099
5100// TODO: Use the `URL` global when targeting Node.js 10
5101const URLParser = typeof URL === 'undefined' ? url.URL : URL;
5102
5103const testParameter = (name, filters) => {
5104 return filters.some(filter => filter instanceof RegExp ? filter.test(name) : filter === name);
5105};
5106
5107var normalizeUrl = (urlString, opts) => {
5108 opts = Object.assign({
5109 defaultProtocol: 'http:',
5110 normalizeProtocol: true,
5111 forceHttp: false,
5112 forceHttps: false,
5113 stripHash: true,
5114 stripWWW: true,
5115 removeQueryParameters: [/^utm_\w+/i],
5116 removeTrailingSlash: true,
5117 removeDirectoryIndex: false,
5118 sortQueryParameters: true
5119 }, opts);
5120
5121 // Backwards compatibility
5122 if (Reflect.has(opts, 'normalizeHttps')) {
5123 opts.forceHttp = opts.normalizeHttps;
5124 }
5125
5126 if (Reflect.has(opts, 'normalizeHttp')) {
5127 opts.forceHttps = opts.normalizeHttp;
5128 }
5129
5130 if (Reflect.has(opts, 'stripFragment')) {
5131 opts.stripHash = opts.stripFragment;
5132 }
5133
5134 urlString = urlString.trim();
5135
5136 const hasRelativeProtocol = urlString.startsWith('//');
5137 const isRelativeUrl = !hasRelativeProtocol && /^\.*\//.test(urlString);
5138
5139 // Prepend protocol
5140 if (!isRelativeUrl) {
5141 urlString = urlString.replace(/^(?!(?:\w+:)?\/\/)|^\/\//, opts.defaultProtocol);
5142 }
5143
5144 const urlObj = new URLParser(urlString);
5145
5146 if (opts.forceHttp && opts.forceHttps) {
5147 throw new Error('The `forceHttp` and `forceHttps` options cannot be used together');
5148 }
5149
5150 if (opts.forceHttp && urlObj.protocol === 'https:') {
5151 urlObj.protocol = 'http:';
5152 }
5153
5154 if (opts.forceHttps && urlObj.protocol === 'http:') {
5155 urlObj.protocol = 'https:';
5156 }
5157
5158 // Remove hash
5159 if (opts.stripHash) {
5160 urlObj.hash = '';
5161 }
5162
5163 // Remove duplicate slashes if not preceded by a protocol
5164 if (urlObj.pathname) {
5165 // TODO: Use the following instead when targeting Node.js 10
5166 // `urlObj.pathname = urlObj.pathname.replace(/(?<!https?:)\/{2,}/g, '/');`
5167 urlObj.pathname = urlObj.pathname.replace(/((?![https?:]).)\/{2,}/g, (_, p1) => {
5168 if (/^(?!\/)/g.test(p1)) {
5169 return `${p1}/`;
5170 }
5171 return '/';
5172 });
5173 }
5174
5175 // Decode URI octets
5176 if (urlObj.pathname) {
5177 urlObj.pathname = decodeURI(urlObj.pathname);
5178 }
5179
5180 // Remove directory index
5181 if (opts.removeDirectoryIndex === true) {
5182 opts.removeDirectoryIndex = [/^index\.[a-z]+$/];
5183 }
5184
5185 if (Array.isArray(opts.removeDirectoryIndex) && opts.removeDirectoryIndex.length > 0) {
5186 let pathComponents = urlObj.pathname.split('/');
5187 const lastComponent = pathComponents[pathComponents.length - 1];
5188
5189 if (testParameter(lastComponent, opts.removeDirectoryIndex)) {
5190 pathComponents = pathComponents.slice(0, pathComponents.length - 1);
5191 urlObj.pathname = pathComponents.slice(1).join('/') + '/';
5192 }
5193 }
5194
5195 if (urlObj.hostname) {
5196 // Remove trailing dot
5197 urlObj.hostname = urlObj.hostname.replace(/\.$/, '');
5198
5199 // Remove `www.`
5200 // eslint-disable-next-line no-useless-escape
5201 if (opts.stripWWW && /^www\.([a-z\-\d]{2,63})\.([a-z\.]{2,5})$/.test(urlObj.hostname)) {
5202 // Each label should be max 63 at length (min: 2).
5203 // The extension should be max 5 at length (min: 2).
5204 // Source: https://en.wikipedia.org/wiki/Hostname#Restrictions_on_valid_host_names
5205 urlObj.hostname = urlObj.hostname.replace(/^www\./, '');
5206 }
5207 }
5208
5209 // Remove query unwanted parameters
5210 if (Array.isArray(opts.removeQueryParameters)) {
5211 for (const key of [...urlObj.searchParams.keys()]) {
5212 if (testParameter(key, opts.removeQueryParameters)) {
5213 urlObj.searchParams.delete(key);
5214 }
5215 }
5216 }
5217
5218 // Sort query parameters
5219 if (opts.sortQueryParameters) {
5220 urlObj.searchParams.sort();
5221 }
5222
5223 // Take advantage of many of the Node `url` normalizations
5224 urlString = urlObj.toString();
5225
5226 // Remove ending `/`
5227 if (opts.removeTrailingSlash || urlObj.pathname === '/') {
5228 urlString = urlString.replace(/\/$/, '');
5229 }
5230
5231 // Restore relative protocol, if applicable
5232 if (hasRelativeProtocol && !opts.normalizeProtocol) {
5233 urlString = urlString.replace(/^http:\/\//, '//');
5234 }
5235
5236 return urlString;
5237};
5238
5239const {PassThrough: PassThrough$2} = stream;
5240
5241var bufferStream = options => {
5242 options = Object.assign({}, options);
5243
5244 const {array} = options;
5245 let {encoding} = options;
5246 const buffer = encoding === 'buffer';
5247 let objectMode = false;
5248
5249 if (array) {
5250 objectMode = !(encoding || buffer);
5251 } else {
5252 encoding = encoding || 'utf8';
5253 }
5254
5255 if (buffer) {
5256 encoding = null;
5257 }
5258
5259 let len = 0;
5260 const ret = [];
5261 const stream = new PassThrough$2({objectMode});
5262
5263 if (encoding) {
5264 stream.setEncoding(encoding);
5265 }
5266
5267 stream.on('data', chunk => {
5268 ret.push(chunk);
5269
5270 if (objectMode) {
5271 len = ret.length;
5272 } else {
5273 len += chunk.length;
5274 }
5275 });
5276
5277 stream.getBufferedValue = () => {
5278 if (array) {
5279 return ret;
5280 }
5281
5282 return buffer ? Buffer.concat(ret, len) : ret.join('');
5283 };
5284
5285 stream.getBufferedLength = () => len;
5286
5287 return stream;
5288};
5289
5290class MaxBufferError extends Error {
5291 constructor() {
5292 super('maxBuffer exceeded');
5293 this.name = 'MaxBufferError';
5294 }
5295}
5296
5297function getStream(inputStream, options) {
5298 if (!inputStream) {
5299 return Promise.reject(new Error('Expected a stream'));
5300 }
5301
5302 options = Object.assign({maxBuffer: Infinity}, options);
5303
5304 const {maxBuffer} = options;
5305
5306 let stream;
5307 return new Promise((resolve, reject) => {
5308 const rejectPromise = error => {
5309 if (error) { // A null check
5310 error.bufferedData = stream.getBufferedValue();
5311 }
5312 reject(error);
5313 };
5314
5315 stream = pump_1(inputStream, bufferStream(options), error => {
5316 if (error) {
5317 rejectPromise(error);
5318 return;
5319 }
5320
5321 resolve();
5322 });
5323
5324 stream.on('data', () => {
5325 if (stream.getBufferedLength() > maxBuffer) {
5326 rejectPromise(new MaxBufferError());
5327 }
5328 });
5329 }).then(() => stream.getBufferedValue());
5330}
5331
5332var getStream_1 = getStream;
5333var buffer = (stream, options) => getStream(stream, Object.assign({}, options, {encoding: 'buffer'}));
5334var array = (stream, options) => getStream(stream, Object.assign({}, options, {array: true}));
5335var MaxBufferError_1 = MaxBufferError;
5336getStream_1.buffer = buffer;
5337getStream_1.array = array;
5338getStream_1.MaxBufferError = MaxBufferError_1;
5339
5340// rfc7231 6.1
5341const statusCodeCacheableByDefault = [200, 203, 204, 206, 300, 301, 404, 405, 410, 414, 501];
5342
5343// This implementation does not understand partial responses (206)
5344const understoodStatuses = [200, 203, 204, 300, 301, 302, 303, 307, 308, 404, 405, 410, 414, 501];
5345
5346const hopByHopHeaders = {
5347 'date': true, // included, because we add Age update Date
5348 'connection':true, 'keep-alive':true, 'proxy-authenticate':true, 'proxy-authorization':true, 'te':true, 'trailer':true, 'transfer-encoding':true, 'upgrade':true
5349};
5350const excludedFromRevalidationUpdate = {
5351 // Since the old body is reused, it doesn't make sense to change properties of the body
5352 'content-length': true, 'content-encoding': true, 'transfer-encoding': true,
5353 'content-range': true,
5354};
5355
5356function parseCacheControl(header) {
5357 const cc = {};
5358 if (!header) return cc;
5359
5360 // TODO: When there is more than one value present for a given directive (e.g., two Expires header fields, multiple Cache-Control: max-age directives),
5361 // the directive's value is considered invalid. Caches are encouraged to consider responses that have invalid freshness information to be stale
5362 const parts = header.trim().split(/\s*,\s*/); // TODO: lame parsing
5363 for(const part of parts) {
5364 const [k,v] = part.split(/\s*=\s*/, 2);
5365 cc[k] = (v === undefined) ? true : v.replace(/^"|"$/g, ''); // TODO: lame unquoting
5366 }
5367
5368 return cc;
5369}
5370
5371function formatCacheControl(cc) {
5372 let parts = [];
5373 for(const k in cc) {
5374 const v = cc[k];
5375 parts.push(v === true ? k : k + '=' + v);
5376 }
5377 if (!parts.length) {
5378 return undefined;
5379 }
5380 return parts.join(', ');
5381}
5382
5383var httpCacheSemantics = class CachePolicy {
5384 constructor(req, res, {shared, cacheHeuristic, immutableMinTimeToLive, ignoreCargoCult, trustServerDate, _fromObject} = {}) {
5385 if (_fromObject) {
5386 this._fromObject(_fromObject);
5387 return;
5388 }
5389
5390 if (!res || !res.headers) {
5391 throw Error("Response headers missing");
5392 }
5393 this._assertRequestHasHeaders(req);
5394
5395 this._responseTime = this.now();
5396 this._isShared = shared !== false;
5397 this._trustServerDate = undefined !== trustServerDate ? trustServerDate : true;
5398 this._cacheHeuristic = undefined !== cacheHeuristic ? cacheHeuristic : 0.1; // 10% matches IE
5399 this._immutableMinTtl = undefined !== immutableMinTimeToLive ? immutableMinTimeToLive : 24*3600*1000;
5400
5401 this._status = 'status' in res ? res.status : 200;
5402 this._resHeaders = res.headers;
5403 this._rescc = parseCacheControl(res.headers['cache-control']);
5404 this._method = 'method' in req ? req.method : 'GET';
5405 this._url = req.url;
5406 this._host = req.headers.host;
5407 this._noAuthorization = !req.headers.authorization;
5408 this._reqHeaders = res.headers.vary ? req.headers : null; // Don't keep all request headers if they won't be used
5409 this._reqcc = parseCacheControl(req.headers['cache-control']);
5410
5411 // Assume that if someone uses legacy, non-standard uncecessary options they don't understand caching,
5412 // so there's no point stricly adhering to the blindly copy&pasted directives.
5413 if (ignoreCargoCult && "pre-check" in this._rescc && "post-check" in this._rescc) {
5414 delete this._rescc['pre-check'];
5415 delete this._rescc['post-check'];
5416 delete this._rescc['no-cache'];
5417 delete this._rescc['no-store'];
5418 delete this._rescc['must-revalidate'];
5419 this._resHeaders = Object.assign({}, this._resHeaders, {'cache-control': formatCacheControl(this._rescc)});
5420 delete this._resHeaders.expires;
5421 delete this._resHeaders.pragma;
5422 }
5423
5424 // When the Cache-Control header field is not present in a request, caches MUST consider the no-cache request pragma-directive
5425 // as having the same effect as if "Cache-Control: no-cache" were present (see Section 5.2.1).
5426 if (!res.headers['cache-control'] && /no-cache/.test(res.headers.pragma)) {
5427 this._rescc['no-cache'] = true;
5428 }
5429 }
5430
5431 now() {
5432 return Date.now();
5433 }
5434
5435 storable() {
5436 // The "no-store" request directive indicates that a cache MUST NOT store any part of either this request or any response to it.
5437 return !!(!this._reqcc['no-store'] &&
5438 // A cache MUST NOT store a response to any request, unless:
5439 // The request method is understood by the cache and defined as being cacheable, and
5440 ('GET' === this._method || 'HEAD' === this._method || ('POST' === this._method && this._hasExplicitExpiration())) &&
5441 // the response status code is understood by the cache, and
5442 understoodStatuses.indexOf(this._status) !== -1 &&
5443 // the "no-store" cache directive does not appear in request or response header fields, and
5444 !this._rescc['no-store'] &&
5445 // the "private" response directive does not appear in the response, if the cache is shared, and
5446 (!this._isShared || !this._rescc.private) &&
5447 // the Authorization header field does not appear in the request, if the cache is shared,
5448 (!this._isShared || this._noAuthorization || this._allowsStoringAuthenticated()) &&
5449 // the response either:
5450 (
5451 // contains an Expires header field, or
5452 this._resHeaders.expires ||
5453 // contains a max-age response directive, or
5454 // contains a s-maxage response directive and the cache is shared, or
5455 // contains a public response directive.
5456 this._rescc.public || this._rescc['max-age'] || this._rescc['s-maxage'] ||
5457 // has a status code that is defined as cacheable by default
5458 statusCodeCacheableByDefault.indexOf(this._status) !== -1
5459 ));
5460 }
5461
5462 _hasExplicitExpiration() {
5463 // 4.2.1 Calculating Freshness Lifetime
5464 return (this._isShared && this._rescc['s-maxage']) ||
5465 this._rescc['max-age'] ||
5466 this._resHeaders.expires;
5467 }
5468
5469 _assertRequestHasHeaders(req) {
5470 if (!req || !req.headers) {
5471 throw Error("Request headers missing");
5472 }
5473 }
5474
5475 satisfiesWithoutRevalidation(req) {
5476 this._assertRequestHasHeaders(req);
5477
5478 // When presented with a request, a cache MUST NOT reuse a stored response, unless:
5479 // the presented request does not contain the no-cache pragma (Section 5.4), nor the no-cache cache directive,
5480 // unless the stored response is successfully validated (Section 4.3), and
5481 const requestCC = parseCacheControl(req.headers['cache-control']);
5482 if (requestCC['no-cache'] || /no-cache/.test(req.headers.pragma)) {
5483 return false;
5484 }
5485
5486 if (requestCC['max-age'] && this.age() > requestCC['max-age']) {
5487 return false;
5488 }
5489
5490 if (requestCC['min-fresh'] && this.timeToLive() < 1000*requestCC['min-fresh']) {
5491 return false;
5492 }
5493
5494 // the stored response is either:
5495 // fresh, or allowed to be served stale
5496 if (this.stale()) {
5497 const allowsStale = requestCC['max-stale'] && !this._rescc['must-revalidate'] && (true === requestCC['max-stale'] || requestCC['max-stale'] > this.age() - this.maxAge());
5498 if (!allowsStale) {
5499 return false;
5500 }
5501 }
5502
5503 return this._requestMatches(req, false);
5504 }
5505
5506 _requestMatches(req, allowHeadMethod) {
5507 // The presented effective request URI and that of the stored response match, and
5508 return (!this._url || this._url === req.url) &&
5509 (this._host === req.headers.host) &&
5510 // the request method associated with the stored response allows it to be used for the presented request, and
5511 (!req.method || this._method === req.method || (allowHeadMethod && 'HEAD' === req.method)) &&
5512 // selecting header fields nominated by the stored response (if any) match those presented, and
5513 this._varyMatches(req);
5514 }
5515
5516 _allowsStoringAuthenticated() {
5517 // following Cache-Control response directives (Section 5.2.2) have such an effect: must-revalidate, public, and s-maxage.
5518 return this._rescc['must-revalidate'] || this._rescc.public || this._rescc['s-maxage'];
5519 }
5520
5521 _varyMatches(req) {
5522 if (!this._resHeaders.vary) {
5523 return true;
5524 }
5525
5526 // A Vary header field-value of "*" always fails to match
5527 if (this._resHeaders.vary === '*') {
5528 return false;
5529 }
5530
5531 const fields = this._resHeaders.vary.trim().toLowerCase().split(/\s*,\s*/);
5532 for(const name of fields) {
5533 if (req.headers[name] !== this._reqHeaders[name]) return false;
5534 }
5535 return true;
5536 }
5537
5538 _copyWithoutHopByHopHeaders(inHeaders) {
5539 const headers = {};
5540 for(const name in inHeaders) {
5541 if (hopByHopHeaders[name]) continue;
5542 headers[name] = inHeaders[name];
5543 }
5544 // 9.1. Connection
5545 if (inHeaders.connection) {
5546 const tokens = inHeaders.connection.trim().split(/\s*,\s*/);
5547 for(const name of tokens) {
5548 delete headers[name];
5549 }
5550 }
5551 if (headers.warning) {
5552 const warnings = headers.warning.split(/,/).filter(warning => {
5553 return !/^\s*1[0-9][0-9]/.test(warning);
5554 });
5555 if (!warnings.length) {
5556 delete headers.warning;
5557 } else {
5558 headers.warning = warnings.join(',').trim();
5559 }
5560 }
5561 return headers;
5562 }
5563
5564 responseHeaders() {
5565 const headers = this._copyWithoutHopByHopHeaders(this._resHeaders);
5566 const age = this.age();
5567
5568 // A cache SHOULD generate 113 warning if it heuristically chose a freshness
5569 // lifetime greater than 24 hours and the response's age is greater than 24 hours.
5570 if (age > 3600*24 && !this._hasExplicitExpiration() && this.maxAge() > 3600*24) {
5571 headers.warning = (headers.warning ? `${headers.warning}, ` : '') + '113 - "rfc7234 5.5.4"';
5572 }
5573 headers.age = `${Math.round(age)}`;
5574 headers.date = new Date(this.now()).toUTCString();
5575 return headers;
5576 }
5577
5578 /**
5579 * Value of the Date response header or current time if Date was demed invalid
5580 * @return timestamp
5581 */
5582 date() {
5583 if (this._trustServerDate) {
5584 return this._serverDate();
5585 }
5586 return this._responseTime;
5587 }
5588
5589 _serverDate() {
5590 const dateValue = Date.parse(this._resHeaders.date);
5591 if (isFinite(dateValue)) {
5592 const maxClockDrift = 8*3600*1000;
5593 const clockDrift = Math.abs(this._responseTime - dateValue);
5594 if (clockDrift < maxClockDrift) {
5595 return dateValue;
5596 }
5597 }
5598 return this._responseTime;
5599 }
5600
5601 /**
5602 * Value of the Age header, in seconds, updated for the current time.
5603 * May be fractional.
5604 *
5605 * @return Number
5606 */
5607 age() {
5608 let age = Math.max(0, (this._responseTime - this.date())/1000);
5609 if (this._resHeaders.age) {
5610 let ageValue = this._ageValue();
5611 if (ageValue > age) age = ageValue;
5612 }
5613
5614 const residentTime = (this.now() - this._responseTime)/1000;
5615 return age + residentTime;
5616 }
5617
5618 _ageValue() {
5619 const ageValue = parseInt(this._resHeaders.age);
5620 return isFinite(ageValue) ? ageValue : 0;
5621 }
5622
5623 /**
5624 * Value of applicable max-age (or heuristic equivalent) in seconds. This counts since response's `Date`.
5625 *
5626 * For an up-to-date value, see `timeToLive()`.
5627 *
5628 * @return Number
5629 */
5630 maxAge() {
5631 if (!this.storable() || this._rescc['no-cache']) {
5632 return 0;
5633 }
5634
5635 // Shared responses with cookies are cacheable according to the RFC, but IMHO it'd be unwise to do so by default
5636 // so this implementation requires explicit opt-in via public header
5637 if (this._isShared && (this._resHeaders['set-cookie'] && !this._rescc.public && !this._rescc.immutable)) {
5638 return 0;
5639 }
5640
5641 if (this._resHeaders.vary === '*') {
5642 return 0;
5643 }
5644
5645 if (this._isShared) {
5646 if (this._rescc['proxy-revalidate']) {
5647 return 0;
5648 }
5649 // if a response includes the s-maxage directive, a shared cache recipient MUST ignore the Expires field.
5650 if (this._rescc['s-maxage']) {
5651 return parseInt(this._rescc['s-maxage'], 10);
5652 }
5653 }
5654
5655 // If a response includes a Cache-Control field with the max-age directive, a recipient MUST ignore the Expires field.
5656 if (this._rescc['max-age']) {
5657 return parseInt(this._rescc['max-age'], 10);
5658 }
5659
5660 const defaultMinTtl = this._rescc.immutable ? this._immutableMinTtl : 0;
5661
5662 const dateValue = this._serverDate();
5663 if (this._resHeaders.expires) {
5664 const expires = Date.parse(this._resHeaders.expires);
5665 // A cache recipient MUST interpret invalid date formats, especially the value "0", as representing a time in the past (i.e., "already expired").
5666 if (Number.isNaN(expires) || expires < dateValue) {
5667 return 0;
5668 }
5669 return Math.max(defaultMinTtl, (expires - dateValue)/1000);
5670 }
5671
5672 if (this._resHeaders['last-modified']) {
5673 const lastModified = Date.parse(this._resHeaders['last-modified']);
5674 if (isFinite(lastModified) && dateValue > lastModified) {
5675 return Math.max(defaultMinTtl, (dateValue - lastModified)/1000 * this._cacheHeuristic);
5676 }
5677 }
5678
5679 return defaultMinTtl;
5680 }
5681
5682 timeToLive() {
5683 return Math.max(0, this.maxAge() - this.age())*1000;
5684 }
5685
5686 stale() {
5687 return this.maxAge() <= this.age();
5688 }
5689
5690 static fromObject(obj) {
5691 return new this(undefined, undefined, {_fromObject:obj});
5692 }
5693
5694 _fromObject(obj) {
5695 if (this._responseTime) throw Error("Reinitialized");
5696 if (!obj || obj.v !== 1) throw Error("Invalid serialization");
5697
5698 this._responseTime = obj.t;
5699 this._isShared = obj.sh;
5700 this._cacheHeuristic = obj.ch;
5701 this._immutableMinTtl = obj.imm !== undefined ? obj.imm : 24*3600*1000;
5702 this._status = obj.st;
5703 this._resHeaders = obj.resh;
5704 this._rescc = obj.rescc;
5705 this._method = obj.m;
5706 this._url = obj.u;
5707 this._host = obj.h;
5708 this._noAuthorization = obj.a;
5709 this._reqHeaders = obj.reqh;
5710 this._reqcc = obj.reqcc;
5711 }
5712
5713 toObject() {
5714 return {
5715 v:1,
5716 t: this._responseTime,
5717 sh: this._isShared,
5718 ch: this._cacheHeuristic,
5719 imm: this._immutableMinTtl,
5720 st: this._status,
5721 resh: this._resHeaders,
5722 rescc: this._rescc,
5723 m: this._method,
5724 u: this._url,
5725 h: this._host,
5726 a: this._noAuthorization,
5727 reqh: this._reqHeaders,
5728 reqcc: this._reqcc,
5729 };
5730 }
5731
5732 /**
5733 * Headers for sending to the origin server to revalidate stale response.
5734 * Allows server to return 304 to allow reuse of the previous response.
5735 *
5736 * Hop by hop headers are always stripped.
5737 * Revalidation headers may be added or removed, depending on request.
5738 */
5739 revalidationHeaders(incomingReq) {
5740 this._assertRequestHasHeaders(incomingReq);
5741 const headers = this._copyWithoutHopByHopHeaders(incomingReq.headers);
5742
5743 // This implementation does not understand range requests
5744 delete headers['if-range'];
5745
5746 if (!this._requestMatches(incomingReq, true) || !this.storable()) { // revalidation allowed via HEAD
5747 // not for the same resource, or wasn't allowed to be cached anyway
5748 delete headers['if-none-match'];
5749 delete headers['if-modified-since'];
5750 return headers;
5751 }
5752
5753 /* MUST send that entity-tag in any cache validation request (using If-Match or If-None-Match) if an entity-tag has been provided by the origin server. */
5754 if (this._resHeaders.etag) {
5755 headers['if-none-match'] = headers['if-none-match'] ? `${headers['if-none-match']}, ${this._resHeaders.etag}` : this._resHeaders.etag;
5756 }
5757
5758 // Clients MAY issue simple (non-subrange) GET requests with either weak validators or strong validators. Clients MUST NOT use weak validators in other forms of request.
5759 const forbidsWeakValidators = headers['accept-ranges'] || headers['if-match'] || headers['if-unmodified-since'] || (this._method && this._method != 'GET');
5760
5761 /* SHOULD send the Last-Modified value in non-subrange cache validation requests (using If-Modified-Since) if only a Last-Modified value has been provided by the origin server.
5762 Note: This implementation does not understand partial responses (206) */
5763 if (forbidsWeakValidators) {
5764 delete headers['if-modified-since'];
5765
5766 if (headers['if-none-match']) {
5767 const etags = headers['if-none-match'].split(/,/).filter(etag => {
5768 return !/^\s*W\//.test(etag);
5769 });
5770 if (!etags.length) {
5771 delete headers['if-none-match'];
5772 } else {
5773 headers['if-none-match'] = etags.join(',').trim();
5774 }
5775 }
5776 } else if (this._resHeaders['last-modified'] && !headers['if-modified-since']) {
5777 headers['if-modified-since'] = this._resHeaders['last-modified'];
5778 }
5779
5780 return headers;
5781 }
5782
5783 /**
5784 * Creates new CachePolicy with information combined from the previews response,
5785 * and the new revalidation response.
5786 *
5787 * Returns {policy, modified} where modified is a boolean indicating
5788 * whether the response body has been modified, and old cached body can't be used.
5789 *
5790 * @return {Object} {policy: CachePolicy, modified: Boolean}
5791 */
5792 revalidatedPolicy(request, response) {
5793 this._assertRequestHasHeaders(request);
5794 if (!response || !response.headers) {
5795 throw Error("Response headers missing");
5796 }
5797
5798 // These aren't going to be supported exactly, since one CachePolicy object
5799 // doesn't know about all the other cached objects.
5800 let matches = false;
5801 if (response.status !== undefined && response.status != 304) {
5802 matches = false;
5803 } else if (response.headers.etag && !/^\s*W\//.test(response.headers.etag)) {
5804 // "All of the stored responses with the same strong validator are selected.
5805 // If none of the stored responses contain the same strong validator,
5806 // then the cache MUST NOT use the new response to update any stored responses."
5807 matches = this._resHeaders.etag && this._resHeaders.etag.replace(/^\s*W\//,'') === response.headers.etag;
5808 } else if (this._resHeaders.etag && response.headers.etag) {
5809 // "If the new response contains a weak validator and that validator corresponds
5810 // to one of the cache's stored responses,
5811 // then the most recent of those matching stored responses is selected for update."
5812 matches = this._resHeaders.etag.replace(/^\s*W\//,'') === response.headers.etag.replace(/^\s*W\//,'');
5813 } else if (this._resHeaders['last-modified']) {
5814 matches = this._resHeaders['last-modified'] === response.headers['last-modified'];
5815 } else {
5816 // If the new response does not include any form of validator (such as in the case where
5817 // a client generates an If-Modified-Since request from a source other than the Last-Modified
5818 // response header field), and there is only one stored response, and that stored response also
5819 // lacks a validator, then that stored response is selected for update.
5820 if (!this._resHeaders.etag && !this._resHeaders['last-modified'] &&
5821 !response.headers.etag && !response.headers['last-modified']) {
5822 matches = true;
5823 }
5824 }
5825
5826 if (!matches) {
5827 return {
5828 policy: new this.constructor(request, response),
5829 modified: true,
5830 }
5831 }
5832
5833 // use other header fields provided in the 304 (Not Modified) response to replace all instances
5834 // of the corresponding header fields in the stored response.
5835 const headers = {};
5836 for(const k in this._resHeaders) {
5837 headers[k] = k in response.headers && !excludedFromRevalidationUpdate[k] ? response.headers[k] : this._resHeaders[k];
5838 }
5839
5840 const newResponse = Object.assign({}, response, {
5841 status: this._status,
5842 method: this._method,
5843 headers,
5844 });
5845 return {
5846 policy: new this.constructor(request, newResponse, {shared: this._isShared, cacheHeuristic: this._cacheHeuristic, immutableMinTimeToLive: this._immutableMinTtl, trustServerDate: this._trustServerDate}),
5847 modified: false,
5848 };
5849 }
5850};
5851
5852var lowercaseKeys = function (obj) {
5853 var ret = {};
5854 var keys = Object.keys(Object(obj));
5855
5856 for (var i = 0; i < keys.length; i++) {
5857 ret[keys[i].toLowerCase()] = obj[keys[i]];
5858 }
5859
5860 return ret;
5861};
5862
5863const Readable$2 = stream.Readable;
5864
5865
5866class Response extends Readable$2 {
5867 constructor(statusCode, headers, body, url) {
5868 if (typeof statusCode !== 'number') {
5869 throw new TypeError('Argument `statusCode` should be a number');
5870 }
5871 if (typeof headers !== 'object') {
5872 throw new TypeError('Argument `headers` should be an object');
5873 }
5874 if (!(body instanceof Buffer)) {
5875 throw new TypeError('Argument `body` should be a buffer');
5876 }
5877 if (typeof url !== 'string') {
5878 throw new TypeError('Argument `url` should be a string');
5879 }
5880
5881 super();
5882 this.statusCode = statusCode;
5883 this.headers = lowercaseKeys(headers);
5884 this.body = body;
5885 this.url = url;
5886 }
5887
5888 _read() {
5889 this.push(this.body);
5890 this.push(null);
5891 }
5892}
5893
5894var src = Response;
5895
5896// We define these manually to ensure they're always copied
5897// even if they would move up the prototype chain
5898// https://nodejs.org/api/http.html#http_class_http_incomingmessage
5899const knownProps = [
5900 'destroy',
5901 'setTimeout',
5902 'socket',
5903 'headers',
5904 'trailers',
5905 'rawHeaders',
5906 'statusCode',
5907 'httpVersion',
5908 'httpVersionMinor',
5909 'httpVersionMajor',
5910 'rawTrailers',
5911 'statusMessage'
5912];
5913
5914var mimicResponse = (fromStream, toStream) => {
5915 const fromProps = new Set(Object.keys(fromStream).concat(knownProps));
5916
5917 for (const prop of fromProps) {
5918 // Don't overwrite existing properties
5919 if (prop in toStream) {
5920 continue;
5921 }
5922
5923 toStream[prop] = typeof fromStream[prop] === 'function' ? fromStream[prop].bind(fromStream) : fromStream[prop];
5924 }
5925};
5926
5927const PassThrough$3 = stream.PassThrough;
5928
5929
5930const cloneResponse = response => {
5931 if (!(response && response.pipe)) {
5932 throw new TypeError('Parameter `response` must be a response stream.');
5933 }
5934
5935 const clone = new PassThrough$3();
5936 mimicResponse(response, clone);
5937
5938 return response.pipe(clone);
5939};
5940
5941var src$1 = cloneResponse;
5942
5943//TODO: handle reviver/dehydrate function like normal
5944//and handle indentation, like normal.
5945//if anyone needs this... please send pull request.
5946
5947var stringify = function stringify (o) {
5948 if('undefined' == typeof o) return o
5949
5950 if(o && Buffer.isBuffer(o))
5951 return JSON.stringify(':base64:' + o.toString('base64'))
5952
5953 if(o && o.toJSON)
5954 o = o.toJSON();
5955
5956 if(o && 'object' === typeof o) {
5957 var s = '';
5958 var array = Array.isArray(o);
5959 s = array ? '[' : '{';
5960 var first = true;
5961
5962 for(var k in o) {
5963 var ignore = 'function' == typeof o[k] || (!array && 'undefined' === typeof o[k]);
5964 if(Object.hasOwnProperty.call(o, k) && !ignore) {
5965 if(!first)
5966 s += ',';
5967 first = false;
5968 if (array) {
5969 if(o[k] == undefined)
5970 s += 'null';
5971 else
5972 s += stringify(o[k]);
5973 } else if (o[k] !== void(0)) {
5974 s += stringify(k) + ':' + stringify(o[k]);
5975 }
5976 }
5977 }
5978
5979 s += array ? ']' : '}';
5980
5981 return s
5982 } else if ('string' === typeof o) {
5983 return JSON.stringify(/^:/.test(o) ? ':' + o : o)
5984 } else if ('undefined' === typeof o) {
5985 return 'null';
5986 } else
5987 return JSON.stringify(o)
5988};
5989
5990var parse$1 = function (s) {
5991 return JSON.parse(s, function (key, value) {
5992 if('string' === typeof value) {
5993 if(/^:base64:/.test(value))
5994 return new Buffer(value.substring(8), 'base64')
5995 else
5996 return /^:/.test(value) ? value.substring(1) : value
5997 }
5998 return value
5999 })
6000};
6001
6002var jsonBuffer = {
6003 stringify: stringify,
6004 parse: parse$1
6005};
6006
6007const loadStore = opts => {
6008 if (opts.adapter || opts.uri) {
6009 const adapter = opts.adapter || /^[^:]*/.exec(opts.uri)[0];
6010 return new (commonjsRequire())(opts);
6011 }
6012 return new Map();
6013};
6014
6015class Keyv extends events {
6016 constructor(uri, opts) {
6017 super();
6018 this.opts = Object.assign(
6019 {
6020 namespace: 'keyv',
6021 serialize: jsonBuffer.stringify,
6022 deserialize: jsonBuffer.parse
6023 },
6024 (typeof uri === 'string') ? { uri } : uri,
6025 opts
6026 );
6027
6028 if (!this.opts.store) {
6029 const adapterOpts = Object.assign({}, this.opts);
6030 this.opts.store = loadStore(adapterOpts);
6031 }
6032
6033 if (typeof this.opts.store.on === 'function') {
6034 this.opts.store.on('error', err => this.emit('error', err));
6035 }
6036
6037 this.opts.store.namespace = this.opts.namespace;
6038 }
6039
6040 _getKeyPrefix(key) {
6041 return `${this.opts.namespace}:${key}`;
6042 }
6043
6044 get(key) {
6045 key = this._getKeyPrefix(key);
6046 const store = this.opts.store;
6047 return Promise.resolve()
6048 .then(() => store.get(key))
6049 .then(data => {
6050 data = (typeof data === 'string') ? this.opts.deserialize(data) : data;
6051 if (data === undefined) {
6052 return undefined;
6053 }
6054 if (typeof data.expires === 'number' && Date.now() > data.expires) {
6055 this.delete(key);
6056 return undefined;
6057 }
6058 return data.value;
6059 });
6060 }
6061
6062 set(key, value, ttl) {
6063 key = this._getKeyPrefix(key);
6064 if (typeof ttl === 'undefined') {
6065 ttl = this.opts.ttl;
6066 }
6067 if (ttl === 0) {
6068 ttl = undefined;
6069 }
6070 const store = this.opts.store;
6071
6072 return Promise.resolve()
6073 .then(() => {
6074 const expires = (typeof ttl === 'number') ? (Date.now() + ttl) : null;
6075 value = { value, expires };
6076 return store.set(key, this.opts.serialize(value), ttl);
6077 })
6078 .then(() => true);
6079 }
6080
6081 delete(key) {
6082 key = this._getKeyPrefix(key);
6083 const store = this.opts.store;
6084 return Promise.resolve()
6085 .then(() => store.delete(key));
6086 }
6087
6088 clear() {
6089 const store = this.opts.store;
6090 return Promise.resolve()
6091 .then(() => store.clear());
6092 }
6093}
6094
6095var src$2 = Keyv;
6096
6097class CacheableRequest {
6098 constructor(request, cacheAdapter) {
6099 if (typeof request !== 'function') {
6100 throw new TypeError('Parameter `request` must be a function');
6101 }
6102
6103 this.cache = new src$2({
6104 uri: typeof cacheAdapter === 'string' && cacheAdapter,
6105 store: typeof cacheAdapter !== 'string' && cacheAdapter,
6106 namespace: 'cacheable-request'
6107 });
6108
6109 return this.createCacheableRequest(request);
6110 }
6111
6112 createCacheableRequest(request) {
6113 return (opts, cb) => {
6114 let url$1;
6115 if (typeof opts === 'string') {
6116 url$1 = normalizeUrlObject(url.parse(opts));
6117 opts = {};
6118 } else if (opts instanceof url.URL) {
6119 url$1 = normalizeUrlObject(url.parse(opts.toString()));
6120 opts = {};
6121 } else {
6122 const [pathname, ...searchParts] = (opts.path || '').split('?');
6123 const search = searchParts.length > 0 ?
6124 `?${searchParts.join('?')}` :
6125 '';
6126 url$1 = normalizeUrlObject({ ...opts, pathname, search });
6127 }
6128 opts = {
6129 headers: {},
6130 method: 'GET',
6131 cache: true,
6132 strictTtl: false,
6133 automaticFailover: false,
6134 ...opts,
6135 ...urlObjectToRequestOptions(url$1)
6136 };
6137 opts.headers = lowercaseKeys(opts.headers);
6138
6139 const ee = new events();
6140 const normalizedUrlString = normalizeUrl(
6141 url.format(url$1),
6142 {
6143 stripWWW: false,
6144 removeTrailingSlash: false
6145 }
6146 );
6147 const key = `${opts.method}:${normalizedUrlString}`;
6148 let revalidate = false;
6149 let madeRequest = false;
6150
6151 const makeRequest = opts => {
6152 madeRequest = true;
6153 let requestErrored = false;
6154 let requestErrorCallback;
6155
6156 const requestErrorPromise = new Promise(resolve => {
6157 requestErrorCallback = () => {
6158 requestErrored = true;
6159 resolve();
6160 };
6161 });
6162
6163 const handler = response => {
6164 if (revalidate && !opts.forceRefresh) {
6165 response.status = response.statusCode;
6166 const revalidatedPolicy = httpCacheSemantics.fromObject(revalidate.cachePolicy).revalidatedPolicy(opts, response);
6167 if (!revalidatedPolicy.modified) {
6168 const headers = revalidatedPolicy.policy.responseHeaders();
6169 response = new src(response.statusCode, headers, revalidate.body, revalidate.url);
6170 response.cachePolicy = revalidatedPolicy.policy;
6171 response.fromCache = true;
6172 }
6173 }
6174
6175 if (!response.fromCache) {
6176 response.cachePolicy = new httpCacheSemantics(opts, response, opts);
6177 response.fromCache = false;
6178 }
6179
6180 let clonedResponse;
6181 if (opts.cache && response.cachePolicy.storable()) {
6182 clonedResponse = src$1(response);
6183
6184 (async () => {
6185 try {
6186 const bodyPromise = getStream_1.buffer(response);
6187
6188 await Promise.race([
6189 requestErrorPromise,
6190 new Promise(resolve => response.once('end', resolve))
6191 ]);
6192
6193 if (requestErrored) {
6194 return;
6195 }
6196
6197 const body = await bodyPromise;
6198
6199 const value = {
6200 cachePolicy: response.cachePolicy.toObject(),
6201 url: response.url,
6202 statusCode: response.fromCache ? revalidate.statusCode : response.statusCode,
6203 body
6204 };
6205
6206 let ttl = opts.strictTtl ? response.cachePolicy.timeToLive() : undefined;
6207 if (opts.maxTtl) {
6208 ttl = ttl ? Math.min(ttl, opts.maxTtl) : opts.maxTtl;
6209 }
6210
6211 await this.cache.set(key, value, ttl);
6212 } catch (err) {
6213 ee.emit('error', new CacheableRequest.CacheError(err));
6214 }
6215 })();
6216 } else if (opts.cache && revalidate) {
6217 (async () => {
6218 try {
6219 await this.cache.delete(key);
6220 } catch (err) {
6221 ee.emit('error', new CacheableRequest.CacheError(err));
6222 }
6223 })();
6224 }
6225
6226 ee.emit('response', clonedResponse || response);
6227 if (typeof cb === 'function') {
6228 cb(clonedResponse || response);
6229 }
6230 };
6231
6232 try {
6233 const req = request(opts, handler);
6234 req.once('error', requestErrorCallback);
6235 req.once('abort', requestErrorCallback);
6236 ee.emit('request', req);
6237 } catch (err) {
6238 ee.emit('error', new CacheableRequest.RequestError(err));
6239 }
6240 };
6241
6242 (async () => {
6243 const get = async opts => {
6244 await Promise.resolve();
6245
6246 const cacheEntry = opts.cache ? await this.cache.get(key) : undefined;
6247 if (typeof cacheEntry === 'undefined') {
6248 return makeRequest(opts);
6249 }
6250
6251 const policy = httpCacheSemantics.fromObject(cacheEntry.cachePolicy);
6252 if (policy.satisfiesWithoutRevalidation(opts) && !opts.forceRefresh) {
6253 const headers = policy.responseHeaders();
6254 const response = new src(cacheEntry.statusCode, headers, cacheEntry.body, cacheEntry.url);
6255 response.cachePolicy = policy;
6256 response.fromCache = true;
6257
6258 ee.emit('response', response);
6259 if (typeof cb === 'function') {
6260 cb(response);
6261 }
6262 } else {
6263 revalidate = cacheEntry;
6264 opts.headers = policy.revalidationHeaders(opts);
6265 makeRequest(opts);
6266 }
6267 };
6268
6269 this.cache.on('error', err => ee.emit('error', new CacheableRequest.CacheError(err)));
6270
6271 try {
6272 await get(opts);
6273 } catch (err) {
6274 if (opts.automaticFailover && !madeRequest) {
6275 makeRequest(opts);
6276 }
6277 ee.emit('error', new CacheableRequest.CacheError(err));
6278 }
6279 })();
6280
6281 return ee;
6282 };
6283 }
6284}
6285
6286function urlObjectToRequestOptions(url) {
6287 const options = { ...url };
6288 options.path = `${url.pathname || '/'}${url.search || ''}`;
6289 delete options.pathname;
6290 delete options.search;
6291 return options;
6292}
6293
6294function normalizeUrlObject(url) {
6295 // If url was parsed by url.parse or new URL:
6296 // - hostname will be set
6297 // - host will be hostname[:port]
6298 // - port will be set if it was explicit in the parsed string
6299 // Otherwise, url was from request options:
6300 // - hostname or host may be set
6301 // - host shall not have port encoded
6302 return {
6303 protocol: url.protocol,
6304 auth: url.auth,
6305 hostname: url.hostname || url.host || 'localhost',
6306 port: url.port,
6307 pathname: url.pathname,
6308 search: url.search
6309 };
6310}
6311
6312CacheableRequest.RequestError = class extends Error {
6313 constructor(err) {
6314 super(err.message);
6315 this.name = 'RequestError';
6316 Object.assign(this, err);
6317 }
6318};
6319
6320CacheableRequest.CacheError = class extends Error {
6321 constructor(err) {
6322 super(err.message);
6323 this.name = 'CacheError';
6324 Object.assign(this, err);
6325 }
6326};
6327
6328var src$3 = CacheableRequest;
6329
6330const {Readable: Readable$3} = stream;
6331
6332var toReadableStream = input => (
6333 new Readable$3({
6334 read() {
6335 this.push(input);
6336 this.push(null);
6337 }
6338 })
6339);
6340
6341// Inspired by https://github.com/nodejs/node/blob/949e8851484c016c07f6cc9e5889f0f2e56baf2a/lib/_http_client.js#L706
6342var deferToConnect = (socket, method, ...args) => {
6343 let call;
6344 if (typeof method === 'function') {
6345 call = method;
6346 } else {
6347 call = () => socket[method](...args);
6348 }
6349
6350 if (socket.writable && !socket.connecting) {
6351 call();
6352 } else {
6353 socket.once('connect', call);
6354 }
6355};
6356
6357var source = request => {
6358 const timings = {
6359 start: Date.now(),
6360 socket: null,
6361 lookup: null,
6362 connect: null,
6363 upload: null,
6364 response: null,
6365 end: null,
6366 error: null,
6367 phases: {
6368 wait: null,
6369 dns: null,
6370 tcp: null,
6371 request: null,
6372 firstByte: null,
6373 download: null,
6374 total: null
6375 }
6376 };
6377
6378 const handleError = origin => {
6379 const emit = origin.emit.bind(origin);
6380 origin.emit = (event, ...args) => {
6381 // Catches the `error` event
6382 if (event === 'error') {
6383 timings.error = Date.now();
6384 timings.phases.total = timings.error - timings.start;
6385
6386 origin.emit = emit;
6387 }
6388
6389 // Saves the original behavior
6390 return emit(event, ...args);
6391 };
6392 };
6393
6394 let uploadFinished = false;
6395 const onUpload = () => {
6396 timings.upload = Date.now();
6397 timings.phases.request = timings.upload - timings.connect;
6398 };
6399
6400 handleError(request);
6401
6402 request.once('socket', socket => {
6403 timings.socket = Date.now();
6404 timings.phases.wait = timings.socket - timings.start;
6405
6406 const lookupListener = () => {
6407 timings.lookup = Date.now();
6408 timings.phases.dns = timings.lookup - timings.socket;
6409 };
6410
6411 socket.once('lookup', lookupListener);
6412
6413 deferToConnect(socket, () => {
6414 timings.connect = Date.now();
6415
6416 if (timings.lookup === null) {
6417 socket.removeListener('lookup', lookupListener);
6418 timings.lookup = timings.connect;
6419 timings.phases.dns = timings.lookup - timings.socket;
6420 }
6421
6422 timings.phases.tcp = timings.connect - timings.lookup;
6423
6424 if (uploadFinished && !timings.upload) {
6425 onUpload();
6426 }
6427 });
6428 });
6429
6430 request.once('finish', () => {
6431 uploadFinished = true;
6432
6433 if (timings.connect) {
6434 onUpload();
6435 }
6436 });
6437
6438 request.once('response', response => {
6439 timings.response = Date.now();
6440 timings.phases.firstByte = timings.response - timings.upload;
6441
6442 handleError(response);
6443
6444 response.once('end', () => {
6445 timings.end = Date.now();
6446 timings.phases.download = timings.end - timings.response;
6447 timings.phases.total = timings.end - timings.start;
6448 });
6449 });
6450
6451 return timings;
6452};
6453
6454class TimeoutError$1 extends Error {
6455 constructor(threshold, event) {
6456 super(`Timeout awaiting '${event}' for ${threshold}ms`);
6457 this.name = 'TimeoutError';
6458 this.code = 'ETIMEDOUT';
6459 this.event = event;
6460 }
6461}
6462
6463const reentry = Symbol('reentry');
6464
6465const noop$5 = () => {};
6466
6467var timedOut = (request, delays, options) => {
6468 /* istanbul ignore next: this makes sure timed-out isn't called twice */
6469 if (request[reentry]) {
6470 return;
6471 }
6472
6473 request[reentry] = true;
6474
6475 let stopNewTimeouts = false;
6476
6477 const addTimeout = (delay, callback, ...args) => {
6478 // An error had been thrown before. Going further would result in uncaught errors.
6479 // See https://github.com/sindresorhus/got/issues/631#issuecomment-435675051
6480 if (stopNewTimeouts) {
6481 return noop$5;
6482 }
6483
6484 // Event loop order is timers, poll, immediates.
6485 // The timed event may emit during the current tick poll phase, so
6486 // defer calling the handler until the poll phase completes.
6487 let immediate;
6488 const timeout = setTimeout(() => {
6489 immediate = setImmediate(callback, delay, ...args);
6490 /* istanbul ignore next: added in node v9.7.0 */
6491 if (immediate.unref) {
6492 immediate.unref();
6493 }
6494 }, delay);
6495
6496 /* istanbul ignore next: in order to support electron renderer */
6497 if (timeout.unref) {
6498 timeout.unref();
6499 }
6500
6501 const cancel = () => {
6502 clearTimeout(timeout);
6503 clearImmediate(immediate);
6504 };
6505
6506 cancelers.push(cancel);
6507
6508 return cancel;
6509 };
6510
6511 const {host, hostname} = options;
6512 const timeoutHandler = (delay, event) => {
6513 request.emit('error', new TimeoutError$1(delay, event));
6514 request.once('error', () => {}); // Ignore the `socket hung up` error made by request.abort()
6515
6516 request.abort();
6517 };
6518
6519 const cancelers = [];
6520 const cancelTimeouts = () => {
6521 stopNewTimeouts = true;
6522 cancelers.forEach(cancelTimeout => cancelTimeout());
6523 };
6524
6525 request.once('error', cancelTimeouts);
6526 request.once('response', response => {
6527 response.once('end', cancelTimeouts);
6528 });
6529
6530 if (delays.request !== undefined) {
6531 addTimeout(delays.request, timeoutHandler, 'request');
6532 }
6533
6534 if (delays.socket !== undefined) {
6535 request.setTimeout(delays.socket, () => {
6536 timeoutHandler(delays.socket, 'socket');
6537 });
6538
6539 cancelers.push(() => request.setTimeout(0));
6540 }
6541
6542 if (delays.lookup !== undefined && !request.socketPath && !net.isIP(hostname || host)) {
6543 request.once('socket', socket => {
6544 /* istanbul ignore next: hard to test */
6545 if (socket.connecting) {
6546 const cancelTimeout = addTimeout(delays.lookup, timeoutHandler, 'lookup');
6547 socket.once('lookup', cancelTimeout);
6548 }
6549 });
6550 }
6551
6552 if (delays.connect !== undefined) {
6553 request.once('socket', socket => {
6554 /* istanbul ignore next: hard to test */
6555 if (socket.connecting) {
6556 const timeConnect = () => addTimeout(delays.connect, timeoutHandler, 'connect');
6557
6558 if (request.socketPath || net.isIP(hostname || host)) {
6559 socket.once('connect', timeConnect());
6560 } else {
6561 socket.once('lookup', error => {
6562 if (error === null) {
6563 socket.once('connect', timeConnect());
6564 }
6565 });
6566 }
6567 }
6568 });
6569 }
6570
6571 if (delays.secureConnect !== undefined && options.protocol === 'https:') {
6572 request.once('socket', socket => {
6573 /* istanbul ignore next: hard to test */
6574 if (socket.connecting) {
6575 socket.once('connect', () => {
6576 const cancelTimeout = addTimeout(delays.secureConnect, timeoutHandler, 'secureConnect');
6577 socket.once('secureConnect', cancelTimeout);
6578 });
6579 }
6580 });
6581 }
6582
6583 if (delays.send !== undefined) {
6584 request.once('socket', socket => {
6585 const timeRequest = () => addTimeout(delays.send, timeoutHandler, 'send');
6586 /* istanbul ignore next: hard to test */
6587 if (socket.connecting) {
6588 socket.once('connect', () => {
6589 request.once('upload-complete', timeRequest());
6590 });
6591 } else {
6592 request.once('upload-complete', timeRequest());
6593 }
6594 });
6595 }
6596
6597 if (delays.response !== undefined) {
6598 request.once('upload-complete', () => {
6599 const cancelTimeout = addTimeout(delays.response, timeoutHandler, 'response');
6600 request.once('response', cancelTimeout);
6601 });
6602 }
6603};
6604
6605var TimeoutError_1 = TimeoutError$1;
6606timedOut.TimeoutError = TimeoutError_1;
6607
6608var isFormData = body => dist.nodeStream(body) && dist.function(body.getBoundary);
6609
6610var getBodySize = async options => {
6611 const {body} = options;
6612
6613 if (options.headers['content-length']) {
6614 return Number(options.headers['content-length']);
6615 }
6616
6617 if (!body && !options.stream) {
6618 return 0;
6619 }
6620
6621 if (dist.string(body)) {
6622 return Buffer.byteLength(body);
6623 }
6624
6625 if (isFormData(body)) {
6626 return util.promisify(body.getLength.bind(body))();
6627 }
6628
6629 if (body instanceof fs.ReadStream) {
6630 const {size} = await util.promisify(fs.stat)(body.path);
6631 return size;
6632 }
6633
6634 return null;
6635};
6636
6637const PassThrough$4 = stream.PassThrough;
6638
6639
6640
6641var decompressResponse = response => {
6642 // TODO: Use Array#includes when targeting Node.js 6
6643 if (['gzip', 'deflate'].indexOf(response.headers['content-encoding']) === -1) {
6644 return response;
6645 }
6646
6647 const unzip = zlib.createUnzip();
6648 const stream = new PassThrough$4();
6649
6650 mimicResponse(response, stream);
6651
6652 unzip.on('error', err => {
6653 if (err.code === 'Z_BUF_ERROR') {
6654 stream.end();
6655 return;
6656 }
6657
6658 stream.emit('error', err);
6659 });
6660
6661 response.pipe(unzip).pipe(stream);
6662
6663 return stream;
6664};
6665
6666const {Transform: Transform$3} = stream;
6667
6668var progress = {
6669 download(response, emitter, downloadBodySize) {
6670 let downloaded = 0;
6671
6672 return new Transform$3({
6673 transform(chunk, encoding, callback) {
6674 downloaded += chunk.length;
6675
6676 const percent = downloadBodySize ? downloaded / downloadBodySize : 0;
6677
6678 // Let `flush()` be responsible for emitting the last event
6679 if (percent < 1) {
6680 emitter.emit('downloadProgress', {
6681 percent,
6682 transferred: downloaded,
6683 total: downloadBodySize
6684 });
6685 }
6686
6687 callback(null, chunk);
6688 },
6689
6690 flush(callback) {
6691 emitter.emit('downloadProgress', {
6692 percent: 1,
6693 transferred: downloaded,
6694 total: downloadBodySize
6695 });
6696
6697 callback();
6698 }
6699 });
6700 },
6701
6702 upload(request, emitter, uploadBodySize) {
6703 const uploadEventFrequency = 150;
6704 let uploaded = 0;
6705 let progressInterval;
6706
6707 emitter.emit('uploadProgress', {
6708 percent: 0,
6709 transferred: 0,
6710 total: uploadBodySize
6711 });
6712
6713 request.once('error', () => {
6714 clearInterval(progressInterval);
6715 });
6716
6717 request.once('response', () => {
6718 clearInterval(progressInterval);
6719
6720 emitter.emit('uploadProgress', {
6721 percent: 1,
6722 transferred: uploaded,
6723 total: uploadBodySize
6724 });
6725 });
6726
6727 request.once('socket', socket => {
6728 const onSocketConnect = () => {
6729 progressInterval = setInterval(() => {
6730 const lastUploaded = uploaded;
6731 /* istanbul ignore next: see #490 (occurs randomly!) */
6732 const headersSize = request._header ? Buffer.byteLength(request._header) : 0;
6733 uploaded = socket.bytesWritten - headersSize;
6734
6735 // Don't emit events with unchanged progress and
6736 // prevent last event from being emitted, because
6737 // it's emitted when `response` is emitted
6738 if (uploaded === lastUploaded || uploaded === uploadBodySize) {
6739 return;
6740 }
6741
6742 emitter.emit('uploadProgress', {
6743 percent: uploadBodySize ? uploaded / uploadBodySize : 0,
6744 transferred: uploaded,
6745 total: uploadBodySize
6746 });
6747 }, uploadEventFrequency);
6748 };
6749
6750 /* istanbul ignore next: hard to test */
6751 if (socket.connecting) {
6752 socket.once('connect', onSocketConnect);
6753 } else if (socket.writable) {
6754 // The socket is being reused from pool,
6755 // so the connect event will not be emitted
6756 onSocketConnect();
6757 }
6758 });
6759 }
6760};
6761
6762var getResponse = (response, options, emitter) => {
6763 const downloadBodySize = Number(response.headers['content-length']) || null;
6764
6765 const progressStream = progress.download(response, emitter, downloadBodySize);
6766
6767 mimicResponse(response, progressStream);
6768
6769 const newResponse = options.decompress === true &&
6770 dist.function(decompressResponse) &&
6771 options.method !== 'HEAD' ? decompressResponse(progressStream) : progressStream;
6772
6773 if (!options.decompress && ['gzip', 'deflate'].includes(response.headers['content-encoding'])) {
6774 options.encoding = null;
6775 }
6776
6777 emitter.emit('response', newResponse);
6778
6779 emitter.emit('downloadProgress', {
6780 percent: 0,
6781 transferred: 0,
6782 total: downloadBodySize
6783 });
6784
6785 response.pipe(progressStream);
6786};
6787
6788var urlToOptions = url => {
6789 const options = {
6790 protocol: url.protocol,
6791 hostname: url.hostname.startsWith('[') ? url.hostname.slice(1, -1) : url.hostname,
6792 hash: url.hash,
6793 search: url.search,
6794 pathname: url.pathname,
6795 href: url.href
6796 };
6797
6798 if (dist.string(url.port) && url.port.length > 0) {
6799 options.port = Number(url.port);
6800 }
6801
6802 if (url.username || url.password) {
6803 options.auth = `${url.username}:${url.password}`;
6804 }
6805
6806 options.path = dist.null(url.search) ? url.pathname : `${url.pathname}${url.search}`;
6807
6808 return options;
6809};
6810
6811const {URL: URL$1} = url; // TODO: Use the `URL` global when targeting Node.js 10
6812
6813
6814
6815
6816const urlLib = url;
6817
6818
6819
6820
6821
6822
6823
6824
6825const {CacheError: CacheError$1, UnsupportedProtocolError: UnsupportedProtocolError$1, MaxRedirectsError: MaxRedirectsError$1, RequestError: RequestError$1, TimeoutError: TimeoutError$2} = errors;
6826
6827
6828const getMethodRedirectCodes = new Set([300, 301, 302, 303, 304, 305, 307, 308]);
6829const allMethodRedirectCodes = new Set([300, 303, 307, 308]);
6830
6831var requestAsEventEmitter = (options, input) => {
6832 const emitter = new events();
6833 const redirects = [];
6834 let currentRequest;
6835 let requestUrl;
6836 let redirectString;
6837 let uploadBodySize;
6838 let retryCount = 0;
6839 let shouldAbort = false;
6840
6841 const setCookie = options.cookieJar ? util.promisify(options.cookieJar.setCookie.bind(options.cookieJar)) : null;
6842 const getCookieString = options.cookieJar ? util.promisify(options.cookieJar.getCookieString.bind(options.cookieJar)) : null;
6843 const agents = dist.object(options.agent) ? options.agent : null;
6844
6845 const get = async options => {
6846 const currentUrl = redirectString || requestUrl;
6847
6848 if (options.protocol !== 'http:' && options.protocol !== 'https:') {
6849 throw new UnsupportedProtocolError$1(options);
6850 }
6851
6852 let fn;
6853 if (dist.function(options.request)) {
6854 fn = {request: options.request};
6855 } else {
6856 fn = options.protocol === 'https:' ? https : http;
6857 }
6858
6859 if (agents) {
6860 const protocolName = options.protocol === 'https:' ? 'https' : 'http';
6861 options.agent = agents[protocolName] || options.agent;
6862 }
6863
6864 /* istanbul ignore next: electron.net is broken */
6865 if (options.useElectronNet && process.versions.electron) {
6866 const r = ({x: commonjsRequire})['yx'.slice(1)]; // Trick webpack
6867 const electron = r('electron');
6868 fn = electron.net || electron.remote.net;
6869 }
6870
6871 if (options.cookieJar) {
6872 const cookieString = await getCookieString(currentUrl, {});
6873
6874 if (dist.nonEmptyString(cookieString)) {
6875 options.headers.cookie = cookieString;
6876 }
6877 }
6878
6879 let timings;
6880 const handleResponse = async response => {
6881 try {
6882 /* istanbul ignore next: fixes https://github.com/electron/electron/blob/cbb460d47628a7a146adf4419ed48550a98b2923/lib/browser/api/net.js#L59-L65 */
6883 if (options.useElectronNet) {
6884 response = new Proxy(response, {
6885 get: (target, name) => {
6886 if (name === 'trailers' || name === 'rawTrailers') {
6887 return [];
6888 }
6889
6890 const value = target[name];
6891 return dist.function(value) ? value.bind(target) : value;
6892 }
6893 });
6894 }
6895
6896 const {statusCode} = response;
6897 response.url = currentUrl;
6898 response.requestUrl = requestUrl;
6899 response.retryCount = retryCount;
6900 response.timings = timings;
6901 response.redirectUrls = redirects;
6902 response.request = {
6903 gotOptions: options
6904 };
6905
6906 const rawCookies = response.headers['set-cookie'];
6907 if (options.cookieJar && rawCookies) {
6908 await Promise.all(rawCookies.map(rawCookie => setCookie(rawCookie, response.url)));
6909 }
6910
6911 if (options.followRedirect && 'location' in response.headers) {
6912 if (allMethodRedirectCodes.has(statusCode) || (getMethodRedirectCodes.has(statusCode) && (options.method === 'GET' || options.method === 'HEAD'))) {
6913 response.resume(); // We're being redirected, we don't care about the response.
6914
6915 if (statusCode === 303) {
6916 // Server responded with "see other", indicating that the resource exists at another location,
6917 // and the client should request it from that location via GET or HEAD.
6918 options.method = 'GET';
6919 }
6920
6921 if (redirects.length >= 10) {
6922 throw new MaxRedirectsError$1(statusCode, redirects, options);
6923 }
6924
6925 // Handles invalid URLs. See https://github.com/sindresorhus/got/issues/604
6926 const redirectBuffer = Buffer.from(response.headers.location, 'binary').toString();
6927 const redirectURL = new URL$1(redirectBuffer, currentUrl);
6928 redirectString = redirectURL.toString();
6929
6930 redirects.push(redirectString);
6931
6932 const redirectOptions = {
6933 ...options,
6934 ...urlToOptions(redirectURL)
6935 };
6936
6937 for (const hook of options.hooks.beforeRedirect) {
6938 // eslint-disable-next-line no-await-in-loop
6939 await hook(redirectOptions);
6940 }
6941
6942 emitter.emit('redirect', response, redirectOptions);
6943
6944 await get(redirectOptions);
6945 return;
6946 }
6947 }
6948
6949 getResponse(response, options, emitter);
6950 } catch (error) {
6951 emitter.emit('error', error);
6952 }
6953 };
6954
6955 const handleRequest = request => {
6956 if (shouldAbort) {
6957 request.once('error', () => {});
6958 request.abort();
6959 return;
6960 }
6961
6962 currentRequest = request;
6963
6964 request.once('error', error => {
6965 if (request.aborted) {
6966 return;
6967 }
6968
6969 if (error instanceof timedOut.TimeoutError) {
6970 error = new TimeoutError$2(error, options);
6971 } else {
6972 error = new RequestError$1(error, options);
6973 }
6974
6975 if (emitter.retry(error) === false) {
6976 emitter.emit('error', error);
6977 }
6978 });
6979
6980 timings = source(request);
6981
6982 progress.upload(request, emitter, uploadBodySize);
6983
6984 if (options.gotTimeout) {
6985 timedOut(request, options.gotTimeout, options);
6986 }
6987
6988 emitter.emit('request', request);
6989
6990 const uploadComplete = () => {
6991 request.emit('upload-complete');
6992 };
6993
6994 try {
6995 if (dist.nodeStream(options.body)) {
6996 options.body.once('end', uploadComplete);
6997 options.body.pipe(request);
6998 options.body = undefined;
6999 } else if (options.body) {
7000 request.end(options.body, uploadComplete);
7001 } else if (input && (options.method === 'POST' || options.method === 'PUT' || options.method === 'PATCH')) {
7002 input.once('end', uploadComplete);
7003 input.pipe(request);
7004 } else {
7005 request.end(uploadComplete);
7006 }
7007 } catch (error) {
7008 emitter.emit('error', new RequestError$1(error, options));
7009 }
7010 };
7011
7012 if (options.cache) {
7013 const cacheableRequest = new src$3(fn.request, options.cache);
7014 const cacheRequest = cacheableRequest(options, handleResponse);
7015
7016 cacheRequest.once('error', error => {
7017 if (error instanceof src$3.RequestError) {
7018 emitter.emit('error', new RequestError$1(error, options));
7019 } else {
7020 emitter.emit('error', new CacheError$1(error, options));
7021 }
7022 });
7023
7024 cacheRequest.once('request', handleRequest);
7025 } else {
7026 // Catches errors thrown by calling fn.request(...)
7027 try {
7028 handleRequest(fn.request(options, handleResponse));
7029 } catch (error) {
7030 emitter.emit('error', new RequestError$1(error, options));
7031 }
7032 }
7033 };
7034
7035 emitter.retry = error => {
7036 let backoff;
7037
7038 try {
7039 backoff = options.retry.retries(++retryCount, error);
7040 } catch (error2) {
7041 emitter.emit('error', error2);
7042 return;
7043 }
7044
7045 if (backoff) {
7046 const retry = async options => {
7047 try {
7048 for (const hook of options.hooks.beforeRetry) {
7049 // eslint-disable-next-line no-await-in-loop
7050 await hook(options, error, retryCount);
7051 }
7052
7053 await get(options);
7054 } catch (error) {
7055 emitter.emit('error', error);
7056 }
7057 };
7058
7059 setTimeout(retry, backoff, {...options, forceRefresh: true});
7060 return true;
7061 }
7062
7063 return false;
7064 };
7065
7066 emitter.abort = () => {
7067 if (currentRequest) {
7068 currentRequest.once('error', () => {});
7069 currentRequest.abort();
7070 } else {
7071 shouldAbort = true;
7072 }
7073 };
7074
7075 setImmediate(async () => {
7076 try {
7077 // Convert buffer to stream to receive upload progress events (#322)
7078 const {body} = options;
7079 if (dist.buffer(body)) {
7080 options.body = toReadableStream(body);
7081 uploadBodySize = body.length;
7082 } else {
7083 uploadBodySize = await getBodySize(options);
7084 }
7085
7086 if (dist.undefined(options.headers['content-length']) && dist.undefined(options.headers['transfer-encoding'])) {
7087 if ((uploadBodySize > 0 || options.method === 'PUT') && !dist.null(uploadBodySize)) {
7088 options.headers['content-length'] = uploadBodySize;
7089 }
7090 }
7091
7092 for (const hook of options.hooks.beforeRequest) {
7093 // eslint-disable-next-line no-await-in-loop
7094 await hook(options);
7095 }
7096
7097 requestUrl = options.href || (new URL$1(options.path, urlLib.format(options))).toString();
7098
7099 await get(options);
7100 } catch (error) {
7101 emitter.emit('error', error);
7102 }
7103 });
7104
7105 return emitter;
7106};
7107
7108const {PassThrough: PassThrough$5} = stream;
7109
7110
7111const {HTTPError: HTTPError$1, ReadError: ReadError$1} = errors;
7112
7113var asStream = options => {
7114 const input = new PassThrough$5();
7115 const output = new PassThrough$5();
7116 const proxy = duplexer3(input, output);
7117 const piped = new Set();
7118 let isFinished = false;
7119
7120 options.retry.retries = () => 0;
7121
7122 if (options.body) {
7123 proxy.write = () => {
7124 throw new Error('Got\'s stream is not writable when the `body` option is used');
7125 };
7126 }
7127
7128 const emitter = requestAsEventEmitter(options, input);
7129
7130 // Cancels the request
7131 proxy._destroy = emitter.abort;
7132
7133 emitter.on('response', response => {
7134 const {statusCode} = response;
7135
7136 response.on('error', error => {
7137 proxy.emit('error', new ReadError$1(error, options));
7138 });
7139
7140 if (options.throwHttpErrors && statusCode !== 304 && (statusCode < 200 || statusCode > 299)) {
7141 proxy.emit('error', new HTTPError$1(response, options), null, response);
7142 return;
7143 }
7144
7145 isFinished = true;
7146
7147 response.pipe(output);
7148
7149 for (const destination of piped) {
7150 if (destination.headersSent) {
7151 continue;
7152 }
7153
7154 for (const [key, value] of Object.entries(response.headers)) {
7155 // Got gives *decompressed* data. Overriding `content-encoding` header would result in an error.
7156 // It's not possible to decompress already decompressed data, is it?
7157 const allowed = options.decompress ? key !== 'content-encoding' : true;
7158 if (allowed) {
7159 destination.setHeader(key, value);
7160 }
7161 }
7162
7163 destination.statusCode = response.statusCode;
7164 }
7165
7166 proxy.emit('response', response);
7167 });
7168
7169 [
7170 'error',
7171 'request',
7172 'redirect',
7173 'uploadProgress',
7174 'downloadProgress'
7175 ].forEach(event => emitter.on(event, (...args) => proxy.emit(event, ...args)));
7176
7177 const pipe = proxy.pipe.bind(proxy);
7178 const unpipe = proxy.unpipe.bind(proxy);
7179 proxy.pipe = (destination, options) => {
7180 if (isFinished) {
7181 throw new Error('Failed to pipe. The response has been emitted already.');
7182 }
7183
7184 const result = pipe(destination, options);
7185
7186 if (Reflect.has(destination, 'setHeader')) {
7187 piped.add(destination);
7188 }
7189
7190 return result;
7191 };
7192 proxy.unpipe = stream => {
7193 piped.delete(stream);
7194 return unpipe(stream);
7195 };
7196
7197 return proxy;
7198};
7199
7200var knownHookEvents = [
7201 'beforeRequest',
7202 'beforeRedirect',
7203 'beforeRetry',
7204 'afterResponse'
7205];
7206
7207const {URL: URL$2} = url;
7208
7209
7210
7211const merge = (target, ...sources) => {
7212 for (const source of sources) {
7213 for (const [key, sourceValue] of Object.entries(source)) {
7214 if (dist.undefined(sourceValue)) {
7215 continue;
7216 }
7217
7218 const targetValue = target[key];
7219 if (dist.urlInstance(targetValue) && (dist.urlInstance(sourceValue) || dist.string(sourceValue))) {
7220 target[key] = new URL$2(sourceValue, targetValue);
7221 } else if (dist.plainObject(sourceValue)) {
7222 if (dist.plainObject(targetValue)) {
7223 target[key] = merge({}, targetValue, sourceValue);
7224 } else {
7225 target[key] = merge({}, sourceValue);
7226 }
7227 } else if (dist.array(sourceValue)) {
7228 target[key] = merge([], sourceValue);
7229 } else {
7230 target[key] = sourceValue;
7231 }
7232 }
7233 }
7234
7235 return target;
7236};
7237
7238const mergeOptions = (...sources) => {
7239 sources = sources.map(source => source || {});
7240 const merged = merge({}, ...sources);
7241
7242 const hooks = {};
7243 for (const hook of knownHookEvents) {
7244 hooks[hook] = [];
7245 }
7246
7247 for (const source of sources) {
7248 if (source.hooks) {
7249 for (const hook of knownHookEvents) {
7250 hooks[hook] = hooks[hook].concat(source.hooks[hook]);
7251 }
7252 }
7253 }
7254
7255 merged.hooks = hooks;
7256
7257 return merged;
7258};
7259
7260const mergeInstances = (instances, methods) => {
7261 const handlers = instances.map(instance => instance.defaults.handler);
7262 const size = instances.length - 1;
7263
7264 return {
7265 methods,
7266 options: mergeOptions(...instances.map(instance => instance.defaults.options)),
7267 handler: (options, next) => {
7268 let iteration = -1;
7269 const iterate = options => handlers[++iteration](options, iteration === size ? next : iterate);
7270
7271 return iterate(options);
7272 }
7273 };
7274};
7275
7276var merge_1 = merge;
7277var options = mergeOptions;
7278var instances = mergeInstances;
7279merge_1.options = options;
7280merge_1.instances = instances;
7281
7282var prependHttp = (url, opts) => {
7283 if (typeof url !== 'string') {
7284 throw new TypeError(`Expected \`url\` to be of type \`string\`, got \`${typeof url}\``);
7285 }
7286
7287 url = url.trim();
7288 opts = Object.assign({https: false}, opts);
7289
7290 if (/^\.*\/|^(?!localhost)\w+:/.test(url)) {
7291 return url;
7292 }
7293
7294 return url.replace(/^(?!(?:\w+:)?\/\/)/, opts.https ? 'https://' : 'http://');
7295};
7296
7297var urlParseLax = (input, options) => {
7298 if (typeof input !== 'string') {
7299 throw new TypeError(`Expected \`url\` to be of type \`string\`, got \`${typeof input}\` instead.`);
7300 }
7301
7302 const finalUrl = prependHttp(input, Object.assign({https: true}, options));
7303 return url.parse(finalUrl);
7304};
7305
7306const {URL: URL$3, URLSearchParams} = url; // TODO: Use the `URL` global when targeting Node.js 10
7307const urlLib$1 = url;
7308
7309
7310
7311
7312
7313
7314
7315
7316const retryAfterStatusCodes = new Set([413, 429, 503]);
7317
7318// `preNormalize` handles static things (lowercasing headers; normalizing baseUrl, timeout, retry)
7319// While `normalize` does `preNormalize` + handles things which need to be reworked when user changes them
7320const preNormalize = (options, defaults) => {
7321 if (dist.nullOrUndefined(options.headers)) {
7322 options.headers = {};
7323 } else {
7324 options.headers = lowercaseKeys(options.headers);
7325 }
7326
7327 if (options.baseUrl && !options.baseUrl.toString().endsWith('/')) {
7328 options.baseUrl += '/';
7329 }
7330
7331 if (options.stream) {
7332 options.json = false;
7333 }
7334
7335 if (dist.nullOrUndefined(options.hooks)) {
7336 options.hooks = {};
7337 } else if (!dist.object(options.hooks)) {
7338 throw new TypeError(`Parameter \`hooks\` must be an object, not ${dist(options.hooks)}`);
7339 }
7340
7341 for (const event of knownHookEvents) {
7342 if (dist.nullOrUndefined(options.hooks[event])) {
7343 if (defaults) {
7344 options.hooks[event] = [...defaults.hooks[event]];
7345 } else {
7346 options.hooks[event] = [];
7347 }
7348 }
7349 }
7350
7351 if (dist.number(options.timeout)) {
7352 options.gotTimeout = {request: options.timeout};
7353 } else if (dist.object(options.timeout)) {
7354 options.gotTimeout = options.timeout;
7355 }
7356 delete options.timeout;
7357
7358 const {retry} = options;
7359 options.retry = {
7360 retries: 0,
7361 methods: [],
7362 statusCodes: [],
7363 errorCodes: []
7364 };
7365
7366 if (dist.nonEmptyObject(defaults) && retry !== false) {
7367 options.retry = {...defaults.retry};
7368 }
7369
7370 if (retry !== false) {
7371 if (dist.number(retry)) {
7372 options.retry.retries = retry;
7373 } else {
7374 options.retry = {...options.retry, ...retry};
7375 }
7376 }
7377
7378 if (options.gotTimeout) {
7379 options.retry.maxRetryAfter = Math.min(...[options.gotTimeout.request, options.gotTimeout.connection].filter(n => !dist.nullOrUndefined(n)));
7380 }
7381
7382 if (dist.array(options.retry.methods)) {
7383 options.retry.methods = new Set(options.retry.methods.map(method => method.toUpperCase()));
7384 }
7385
7386 if (dist.array(options.retry.statusCodes)) {
7387 options.retry.statusCodes = new Set(options.retry.statusCodes);
7388 }
7389
7390 if (dist.array(options.retry.errorCodes)) {
7391 options.retry.errorCodes = new Set(options.retry.errorCodes);
7392 }
7393
7394 return options;
7395};
7396
7397const normalize = (url, options, defaults) => {
7398 if (dist.plainObject(url)) {
7399 options = {...url, ...options};
7400 url = options.url || {};
7401 delete options.url;
7402 }
7403
7404 if (defaults) {
7405 options = merge_1({}, defaults.options, options ? preNormalize(options, defaults.options) : {});
7406 } else {
7407 options = merge_1({}, preNormalize(options));
7408 }
7409
7410 if (!dist.string(url) && !dist.object(url)) {
7411 throw new TypeError(`Parameter \`url\` must be a string or object, not ${dist(url)}`);
7412 }
7413
7414 if (dist.string(url)) {
7415 if (options.baseUrl) {
7416 if (url.toString().startsWith('/')) {
7417 url = url.toString().slice(1);
7418 }
7419
7420 url = urlToOptions(new URL$3(url, options.baseUrl));
7421 } else {
7422 url = url.replace(/^unix:/, 'http://$&');
7423 url = urlParseLax(url);
7424 }
7425 } else if (dist(url) === 'URL') {
7426 url = urlToOptions(url);
7427 }
7428
7429 // Override both null/undefined with default protocol
7430 options = merge_1({path: ''}, url, {protocol: url.protocol || 'https:'}, options);
7431
7432 const {baseUrl} = options;
7433 Object.defineProperty(options, 'baseUrl', {
7434 set: () => {
7435 throw new Error('Failed to set baseUrl. Options are normalized already.');
7436 },
7437 get: () => baseUrl
7438 });
7439
7440 const {query} = options;
7441 if (dist.nonEmptyString(query) || dist.nonEmptyObject(query) || query instanceof URLSearchParams) {
7442 if (!dist.string(query)) {
7443 options.query = (new URLSearchParams(query)).toString();
7444 }
7445 options.path = `${options.path.split('?')[0]}?${options.query}`;
7446 delete options.query;
7447 }
7448
7449 if (options.hostname === 'unix') {
7450 const matches = /(.+?):(.+)/.exec(options.path);
7451
7452 if (matches) {
7453 const [, socketPath, path] = matches;
7454 options = {
7455 ...options,
7456 socketPath,
7457 path,
7458 host: null
7459 };
7460 }
7461 }
7462
7463 const {headers} = options;
7464 for (const [key, value] of Object.entries(headers)) {
7465 if (dist.nullOrUndefined(value)) {
7466 delete headers[key];
7467 }
7468 }
7469
7470 if (options.json && dist.undefined(headers.accept)) {
7471 headers.accept = 'application/json';
7472 }
7473
7474 if (options.decompress && dist.undefined(headers['accept-encoding'])) {
7475 headers['accept-encoding'] = 'gzip, deflate';
7476 }
7477
7478 const {body} = options;
7479 if (dist.nullOrUndefined(body)) {
7480 options.method = options.method ? options.method.toUpperCase() : 'GET';
7481 } else {
7482 const isObject = dist.object(body) && !dist.buffer(body) && !dist.nodeStream(body);
7483 if (!dist.nodeStream(body) && !dist.string(body) && !dist.buffer(body) && !(options.form || options.json)) {
7484 throw new TypeError('The `body` option must be a stream.Readable, string or Buffer');
7485 }
7486
7487 if (options.json && !(isObject || dist.array(body))) {
7488 throw new TypeError('The `body` option must be an Object or Array when the `json` option is used');
7489 }
7490
7491 if (options.form && !isObject) {
7492 throw new TypeError('The `body` option must be an Object when the `form` option is used');
7493 }
7494
7495 if (isFormData(body)) {
7496 // Special case for https://github.com/form-data/form-data
7497 headers['content-type'] = headers['content-type'] || `multipart/form-data; boundary=${body.getBoundary()}`;
7498 } else if (options.form) {
7499 headers['content-type'] = headers['content-type'] || 'application/x-www-form-urlencoded';
7500 options.body = (new URLSearchParams(body)).toString();
7501 } else if (options.json) {
7502 headers['content-type'] = headers['content-type'] || 'application/json';
7503 options.body = JSON.stringify(body);
7504 }
7505
7506 options.method = options.method ? options.method.toUpperCase() : 'POST';
7507 }
7508
7509 if (!dist.function(options.retry.retries)) {
7510 const {retries} = options.retry;
7511
7512 options.retry.retries = (iteration, error) => {
7513 if (iteration > retries) {
7514 return 0;
7515 }
7516
7517 if ((!error || !options.retry.errorCodes.has(error.code)) && (!options.retry.methods.has(error.method) || !options.retry.statusCodes.has(error.statusCode))) {
7518 return 0;
7519 }
7520
7521 if (Reflect.has(error, 'headers') && Reflect.has(error.headers, 'retry-after') && retryAfterStatusCodes.has(error.statusCode)) {
7522 let after = Number(error.headers['retry-after']);
7523 if (dist.nan(after)) {
7524 after = Date.parse(error.headers['retry-after']) - Date.now();
7525 } else {
7526 after *= 1000;
7527 }
7528
7529 if (after > options.retry.maxRetryAfter) {
7530 return 0;
7531 }
7532
7533 return after;
7534 }
7535
7536 if (error.statusCode === 413) {
7537 return 0;
7538 }
7539
7540 const noise = Math.random() * 100;
7541 return ((2 ** (iteration - 1)) * 1000) + noise;
7542 };
7543 }
7544
7545 return options;
7546};
7547
7548const reNormalize = options => normalize(urlLib$1.format(options), options);
7549
7550var normalizeArguments = normalize;
7551var preNormalize_1 = preNormalize;
7552var reNormalize_1 = reNormalize;
7553normalizeArguments.preNormalize = preNormalize_1;
7554normalizeArguments.reNormalize = reNormalize_1;
7555
7556const {HTTPError: HTTPError$2, ParseError: ParseError$1, ReadError: ReadError$2} = errors;
7557const {options: mergeOptions$1} = merge_1;
7558const {reNormalize: reNormalize$1} = normalizeArguments;
7559
7560const asPromise = options => {
7561 const proxy = new events();
7562
7563 const promise = new pCancelable((resolve, reject, onCancel) => {
7564 const emitter = requestAsEventEmitter(options);
7565
7566 onCancel(emitter.abort);
7567
7568 emitter.on('response', async response => {
7569 proxy.emit('response', response);
7570
7571 const stream = dist.null(options.encoding) ? getStream_1.buffer(response) : getStream_1(response, options);
7572
7573 let data;
7574 try {
7575 data = await stream;
7576 } catch (error) {
7577 reject(new ReadError$2(error, options));
7578 return;
7579 }
7580
7581 const limitStatusCode = options.followRedirect ? 299 : 399;
7582
7583 response.body = data;
7584
7585 try {
7586 for (const [index, hook] of Object.entries(options.hooks.afterResponse)) {
7587 // eslint-disable-next-line no-await-in-loop
7588 response = await hook(response, updatedOptions => {
7589 updatedOptions = reNormalize$1(mergeOptions$1(options, {
7590 ...updatedOptions,
7591 retry: 0,
7592 throwHttpErrors: false
7593 }));
7594
7595 // Remove any further hooks for that request, because we we'll call them anyway.
7596 // The loop continues. We don't want duplicates (asPromise recursion).
7597 updatedOptions.hooks.afterResponse = options.hooks.afterResponse.slice(0, index);
7598
7599 return asPromise(updatedOptions);
7600 });
7601 }
7602 } catch (error) {
7603 reject(error);
7604 return;
7605 }
7606
7607 const {statusCode} = response;
7608
7609 if (options.json && response.body) {
7610 try {
7611 response.body = JSON.parse(response.body);
7612 } catch (error) {
7613 if (statusCode >= 200 && statusCode < 300) {
7614 const parseError = new ParseError$1(error, statusCode, options, data);
7615 Object.defineProperty(parseError, 'response', {value: response});
7616 reject(parseError);
7617 return;
7618 }
7619 }
7620 }
7621
7622 if (statusCode !== 304 && (statusCode < 200 || statusCode > limitStatusCode)) {
7623 const error = new HTTPError$2(response, options);
7624 Object.defineProperty(error, 'response', {value: response});
7625 if (emitter.retry(error) === false) {
7626 if (options.throwHttpErrors) {
7627 reject(error);
7628 return;
7629 }
7630
7631 resolve(response);
7632 }
7633 return;
7634 }
7635
7636 resolve(response);
7637 });
7638
7639 emitter.once('error', reject);
7640 [
7641 'request',
7642 'redirect',
7643 'uploadProgress',
7644 'downloadProgress'
7645 ].forEach(event => emitter.on(event, (...args) => proxy.emit(event, ...args)));
7646 });
7647
7648 promise.on = (name, fn) => {
7649 proxy.on(name, fn);
7650 return promise;
7651 };
7652
7653 return promise;
7654};
7655
7656var asPromise_1 = asPromise;
7657
7658var deepFreeze = function deepFreeze(object) {
7659 for (const [key, value] of Object.entries(object)) {
7660 if (dist.plainObject(value) || dist.array(value)) {
7661 deepFreeze(object[key]);
7662 }
7663 }
7664
7665 return Object.freeze(object);
7666};
7667
7668const getPromiseOrStream = options => options.stream ? asStream(options) : asPromise_1(options);
7669
7670const aliases = [
7671 'get',
7672 'post',
7673 'put',
7674 'patch',
7675 'head',
7676 'delete'
7677];
7678
7679const create = defaults => {
7680 defaults = merge_1({}, defaults);
7681 normalizeArguments.preNormalize(defaults.options);
7682
7683 if (!defaults.handler) {
7684 // This can't be getPromiseOrStream, because when merging
7685 // the chain would stop at this point and no further handlers would be called.
7686 defaults.handler = (options, next) => next(options);
7687 }
7688
7689 function got(url, options) {
7690 try {
7691 return defaults.handler(normalizeArguments(url, options, defaults), getPromiseOrStream);
7692 } catch (error) {
7693 if (options && options.stream) {
7694 throw error;
7695 } else {
7696 return Promise.reject(error);
7697 }
7698 }
7699 }
7700
7701 got.create = create;
7702 got.extend = options => {
7703 let mutableDefaults;
7704 if (options && Reflect.has(options, 'mutableDefaults')) {
7705 mutableDefaults = options.mutableDefaults;
7706 delete options.mutableDefaults;
7707 } else {
7708 mutableDefaults = defaults.mutableDefaults;
7709 }
7710
7711 return create({
7712 options: merge_1.options(defaults.options, options),
7713 handler: defaults.handler,
7714 mutableDefaults
7715 });
7716 };
7717
7718 got.mergeInstances = (...args) => create(merge_1.instances(args));
7719
7720 got.stream = (url, options) => got(url, {...options, stream: true});
7721
7722 for (const method of aliases) {
7723 got[method] = (url, options) => got(url, {...options, method});
7724 got.stream[method] = (url, options) => got.stream(url, {...options, method});
7725 }
7726
7727 Object.assign(got, {...errors, mergeOptions: merge_1.options});
7728 Object.defineProperty(got, 'defaults', {
7729 value: defaults.mutableDefaults ? defaults : deepFreeze(defaults),
7730 writable: defaults.mutableDefaults,
7731 configurable: defaults.mutableDefaults,
7732 enumerable: true
7733 });
7734
7735 return got;
7736};
7737
7738var create_1 = create;
7739
7740var pkg = getCjsExportFromNamespace(_package$3);
7741
7742const defaults$1 = {
7743 options: {
7744 retry: {
7745 retries: 2,
7746 methods: [
7747 'GET',
7748 'PUT',
7749 'HEAD',
7750 'DELETE',
7751 'OPTIONS',
7752 'TRACE'
7753 ],
7754 statusCodes: [
7755 408,
7756 413,
7757 429,
7758 500,
7759 502,
7760 503,
7761 504
7762 ],
7763 errorCodes: [
7764 'ETIMEDOUT',
7765 'ECONNRESET',
7766 'EADDRINUSE',
7767 'ECONNREFUSED',
7768 'EPIPE',
7769 'ENOTFOUND',
7770 'ENETUNREACH',
7771 'EAI_AGAIN'
7772 ]
7773 },
7774 headers: {
7775 'user-agent': `${pkg.name}/${pkg.version} (https://github.com/sindresorhus/got)`
7776 },
7777 hooks: {
7778 beforeRequest: [],
7779 beforeRedirect: [],
7780 beforeRetry: [],
7781 afterResponse: []
7782 },
7783 decompress: true,
7784 throwHttpErrors: true,
7785 followRedirect: true,
7786 stream: false,
7787 form: false,
7788 json: false,
7789 cache: false,
7790 useElectronNet: false
7791 },
7792 mutableDefaults: false
7793};
7794
7795const got = create_1(defaults$1);
7796
7797var source$1 = got;
7798
7799var ghGot = createCommonjsModule(function (module) {
7800
7801
7802const getRateLimit = ({headers}) => ({
7803 limit: parseInt(headers['x-ratelimit-limit'], 10),
7804 remaining: parseInt(headers['x-ratelimit-remaining'], 10),
7805 reset: new Date(parseInt(headers['x-ratelimit-reset'], 10) * 1000)
7806});
7807
7808const create = () => source$1.create({
7809 options: source$1.mergeOptions(source$1.defaults.options, {
7810 json: true,
7811 token: process.env.GITHUB_TOKEN,
7812 baseUrl: process.env.GITHUB_ENDPOINT || 'https://api.github.com',
7813 headers: {
7814 accept: 'application/vnd.github.v3+json',
7815 'user-agent': 'https://github.com/sindresorhus/gh-got'
7816 }
7817 }),
7818
7819 methods: source$1.defaults.methods,
7820
7821 handler: (options, next) => {
7822 if (options.token) {
7823 options.headers.authorization = options.headers.authorization || `token ${options.token}`;
7824 }
7825
7826 if (options.stream) {
7827 return next(options);
7828 }
7829
7830 // TODO: Use async/await here when Got supports the `handler` being an async function
7831 return next(options)
7832 .then(response => { // eslint-disable-line promise/prefer-await-to-then
7833 response.rateLimit = getRateLimit(response);
7834 return response;
7835 })
7836 .catch(error => {
7837 const {response} = error;
7838
7839 if (response && response.body) {
7840 error.name = 'GitHubError';
7841 error.message = `${response.body.message} (${error.statusCode})`;
7842 }
7843
7844 if (response) {
7845 error.rateLimit = getRateLimit(response);
7846 }
7847
7848 throw error;
7849 });
7850 }
7851});
7852
7853module.exports = create();
7854
7855if (process.env.NODE_ENV === 'test') {
7856 module.exports.recreate = create;
7857}
7858});
7859var ghGot_1 = ghGot.recreate;
7860
7861var pkg$1 = getCjsExportFromNamespace(_package$1);
7862
7863const { promisify } = util;
7864const { extname, join } = path;
7865const debug = node('http');
7866
7867
7868
7869
7870const platform = os.platform();
7871
7872
7873
7874const ua = join(pkg$1.name, pkg$1.version);
7875const client = ghGot.extend({
7876 headers: { 'user-agent': ua }
7877});
7878
7879const castArray = arg => Array.isArray(arg) ? arg : [arg];
7880const isHttpError = err => err instanceof client.HTTPError;
7881const loadZip = promisify(yauzl.fromBuffer);
7882
7883class InstallationError extends Error {}
7884
7885var getDeno = {
7886 download,
7887 fetchRelease,
7888 listReleases,
7889 InstallationError
7890};
7891
7892async function download(version = 'latest', os = platform) {
7893 const release = await fetchRelease(version);
7894 debug('found release: %j', release);
7895 debug('available artifacts: %j', Array.from(release.files.keys()));
7896 const filenames = castArray(pkg$1.config.artifacts[os] || []);
7897 const filename = filenames.find(it => release.files.has(it));
7898 if (!filename) {
7899 throw new InstallationError(`Unsupported platform: ${platform}`);
7900 }
7901 const type = extname(filename).replace(/^\./, '');
7902 const { size, downloadUrl: url } = release.files.get(filename);
7903 debug('downloading binary from: url=%s [type=%s, size=%i]', url, type, size);
7904 let unarchiver;
7905 if (type === 'gz') unarchiver = zlib.createGunzip();
7906 else if (type === 'zip') unarchiver = createUnzip();
7907 else throw new InstallationError(`Unsupported file type: ${filename}`);
7908 let downloadedSize = 0;
7909 const downloadStream = client.stream(url, { token: null });
7910 const outputStream = mississippi.pipe(downloadStream, unarchiver);
7911 downloadStream.on('data', buf => {
7912 downloadedSize += Buffer.byteLength(buf);
7913 outputStream.emit('download:progress', downloadedSize / size, downloadedSize, size);
7914 });
7915 const metadata = { filename, size, url, version: release.tag };
7916 return Object.assign(outputStream, { metadata });
7917}
7918
7919async function fetchRelease(version = 'latest') {
7920 debug('fetch single release: %s', version);
7921 try {
7922 const [release] = await listReleases(version);
7923 return release;
7924 } catch (reason) {
7925 if (!isHttpError(reason) || reason.statusCode !== 404) throw reason;
7926 const err = new InstallationError(`Release not found: ${version}`);
7927 err.reason = reason;
7928 throw err;
7929 }
7930}
7931
7932async function listReleases(version) {
7933 const releases = [];
7934 let url = join('/repos/', pkg$1.config.repo, '/releases');
7935 if (version === 'latest') url = join(url, '/latest');
7936 else if (version) url = join(url, '/tags/', version);
7937 let finished = false;
7938 await pDoWhilst_1(async () => {
7939 debug('fetch releases: url=%s', url);
7940 const resp = await client.get(url);
7941 const link = githubParseLink(resp.headers.link);
7942 debug('`Link` header: %j', link);
7943 if (link.next) url = link.next;
7944 else finished = true;
7945 releases.push(...castArray(resp.body).map(it => processRelease(it)));
7946 }, () => !finished);
7947 return releases;
7948}
7949
7950function processRelease(release) {
7951 const files = new Map(release.assets.map(it => [
7952 it.name, {
7953 filename: it.name,
7954 size: it.size,
7955 downloadUrl: it.browser_download_url,
7956 ...getTimestamps(it)
7957 }
7958 ]));
7959 return {
7960 tag: release.tag_name,
7961 url: release.html_url,
7962 prerelase: release.prerelase,
7963 ...getTimestamps(release),
7964 files
7965 };
7966}
7967
7968function getTimestamps({ created_at: createdAt, published_at: publishedAt }) {
7969 return { createdAt, publishedAt };
7970}
7971
7972function createUnzip() {
7973 const debug = node('unzip');
7974 const writer = mississippi.through();
7975 const reader = mississippi.concat(async buf => {
7976 try {
7977 const zipfile = await loadZip(buf, { lazyEntries: true });
7978 const openReadStream = promisify(zipfile.openReadStream.bind(zipfile));
7979 zipfile.on('error', err => writer.emit('error', err));
7980 zipfile.on('entry', async entry => {
7981 debug('entry found: %s', entry.fileName);
7982 try {
7983 const stream = await openReadStream(entry);
7984 mississippi.pipe(stream, writer);
7985 } catch (err) {
7986 writer.emit('error', err);
7987 }
7988 });
7989 zipfile.readEntry();
7990 } catch (err) {
7991 writer.emit('error', err);
7992 }
7993 });
7994 return mississippi.duplex(reader, writer);
7995}
7996
7997const callbacks = new Set();
7998let called = false;
7999
8000function exit(exit, signal) {
8001 if (called) {
8002 return;
8003 }
8004
8005 called = true;
8006
8007 for (const callback of callbacks) {
8008 callback();
8009 }
8010
8011 if (exit === true) {
8012 process.exit(128 + signal); // eslint-disable-line unicorn/no-process-exit
8013 }
8014}
8015
8016var exitHook = callback => {
8017 callbacks.add(callback);
8018
8019 if (callbacks.size === 1) {
8020 process.once('exit', exit);
8021 process.once('SIGINT', exit.bind(null, true, 2));
8022 process.once('SIGTERM', exit.bind(null, true, 15));
8023
8024 // PM2 Cluster shutdown message. Caught to support async handlers with pm2, needed because
8025 // explicitly calling process.exit() doesn't trigger the beforeExit event, and the exit
8026 // event cannot support async handlers, since the event loop is never called after it.
8027 process.on('message', message => {
8028 if (message === 'shutdown') {
8029 exit(true, -128);
8030 }
8031 });
8032 }
8033
8034 return () => {
8035 callbacks.delete(callback);
8036 };
8037};
8038
8039// These tables borrowed from `ansi`
8040
8041var prefix = '\x1b[';
8042
8043var up = function up (num) {
8044 return prefix + (num || '') + 'A'
8045};
8046
8047var down = function down (num) {
8048 return prefix + (num || '') + 'B'
8049};
8050
8051var forward = function forward (num) {
8052 return prefix + (num || '') + 'C'
8053};
8054
8055var back = function back (num) {
8056 return prefix + (num || '') + 'D'
8057};
8058
8059var nextLine = function nextLine (num) {
8060 return prefix + (num || '') + 'E'
8061};
8062
8063var previousLine = function previousLine (num) {
8064 return prefix + (num || '') + 'F'
8065};
8066
8067var horizontalAbsolute = function horizontalAbsolute (num) {
8068 if (num == null) throw new Error('horizontalAboslute requires a column to position to')
8069 return prefix + num + 'G'
8070};
8071
8072var eraseData = function eraseData () {
8073 return prefix + 'J'
8074};
8075
8076var eraseLine = function eraseLine () {
8077 return prefix + 'K'
8078};
8079
8080var goto_1 = function (x, y) {
8081 return prefix + y + ';' + x + 'H'
8082};
8083
8084var gotoSOL = function () {
8085 return '\r'
8086};
8087
8088var beep = function () {
8089 return '\x07'
8090};
8091
8092var hideCursor = function hideCursor () {
8093 return prefix + '?25l'
8094};
8095
8096var showCursor = function showCursor () {
8097 return prefix + '?25h'
8098};
8099
8100var colors = {
8101 reset: 0,
8102// styles
8103 bold: 1,
8104 italic: 3,
8105 underline: 4,
8106 inverse: 7,
8107// resets
8108 stopBold: 22,
8109 stopItalic: 23,
8110 stopUnderline: 24,
8111 stopInverse: 27,
8112// colors
8113 white: 37,
8114 black: 30,
8115 blue: 34,
8116 cyan: 36,
8117 green: 32,
8118 magenta: 35,
8119 red: 31,
8120 yellow: 33,
8121 bgWhite: 47,
8122 bgBlack: 40,
8123 bgBlue: 44,
8124 bgCyan: 46,
8125 bgGreen: 42,
8126 bgMagenta: 45,
8127 bgRed: 41,
8128 bgYellow: 43,
8129
8130 grey: 90,
8131 brightBlack: 90,
8132 brightRed: 91,
8133 brightGreen: 92,
8134 brightYellow: 93,
8135 brightBlue: 94,
8136 brightMagenta: 95,
8137 brightCyan: 96,
8138 brightWhite: 97,
8139
8140 bgGrey: 100,
8141 bgBrightBlack: 100,
8142 bgBrightRed: 101,
8143 bgBrightGreen: 102,
8144 bgBrightYellow: 103,
8145 bgBrightBlue: 104,
8146 bgBrightMagenta: 105,
8147 bgBrightCyan: 106,
8148 bgBrightWhite: 107
8149};
8150
8151var color = function color (colorWith) {
8152 if (arguments.length !== 1 || !Array.isArray(colorWith)) {
8153 colorWith = Array.prototype.slice.call(arguments);
8154 }
8155 return prefix + colorWith.map(colorNameToCode).join(';') + 'm'
8156};
8157
8158function colorNameToCode (color) {
8159 if (colors[color] != null) return colors[color]
8160 throw new Error('Unknown color or style name: ' + color)
8161}
8162
8163var consoleControlStrings = {
8164 up: up,
8165 down: down,
8166 forward: forward,
8167 back: back,
8168 nextLine: nextLine,
8169 previousLine: previousLine,
8170 horizontalAbsolute: horizontalAbsolute,
8171 eraseData: eraseData,
8172 eraseLine: eraseLine,
8173 goto: goto_1,
8174 gotoSOL: gotoSOL,
8175 beep: beep,
8176 hideCursor: hideCursor,
8177 showCursor: showCursor,
8178 color: color
8179};
8180
8181var ansiRegex = () => {
8182 const pattern = [
8183 '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[a-zA-Z\\d]*)*)?\\u0007)',
8184 '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))'
8185 ].join('|');
8186
8187 return new RegExp(pattern, 'g');
8188};
8189
8190var stripAnsi = input => typeof input === 'string' ? input.replace(ansiRegex(), '') : input;
8191
8192/* eslint-disable yoda */
8193var isFullwidthCodePoint = x => {
8194 if (Number.isNaN(x)) {
8195 return false;
8196 }
8197
8198 // code points are derived from:
8199 // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt
8200 if (
8201 x >= 0x1100 && (
8202 x <= 0x115f || // Hangul Jamo
8203 x === 0x2329 || // LEFT-POINTING ANGLE BRACKET
8204 x === 0x232a || // RIGHT-POINTING ANGLE BRACKET
8205 // CJK Radicals Supplement .. Enclosed CJK Letters and Months
8206 (0x2e80 <= x && x <= 0x3247 && x !== 0x303f) ||
8207 // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A
8208 (0x3250 <= x && x <= 0x4dbf) ||
8209 // CJK Unified Ideographs .. Yi Radicals
8210 (0x4e00 <= x && x <= 0xa4c6) ||
8211 // Hangul Jamo Extended-A
8212 (0xa960 <= x && x <= 0xa97c) ||
8213 // Hangul Syllables
8214 (0xac00 <= x && x <= 0xd7a3) ||
8215 // CJK Compatibility Ideographs
8216 (0xf900 <= x && x <= 0xfaff) ||
8217 // Vertical Forms
8218 (0xfe10 <= x && x <= 0xfe19) ||
8219 // CJK Compatibility Forms .. Small Form Variants
8220 (0xfe30 <= x && x <= 0xfe6b) ||
8221 // Halfwidth and Fullwidth Forms
8222 (0xff01 <= x && x <= 0xff60) ||
8223 (0xffe0 <= x && x <= 0xffe6) ||
8224 // Kana Supplement
8225 (0x1b000 <= x && x <= 0x1b001) ||
8226 // Enclosed Ideographic Supplement
8227 (0x1f200 <= x && x <= 0x1f251) ||
8228 // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane
8229 (0x20000 <= x && x <= 0x3fffd)
8230 )
8231 ) {
8232 return true;
8233 }
8234
8235 return false;
8236};
8237
8238var stringWidth = str => {
8239 if (typeof str !== 'string' || str.length === 0) {
8240 return 0;
8241 }
8242
8243 str = stripAnsi(str);
8244
8245 let width = 0;
8246
8247 for (let i = 0; i < str.length; i++) {
8248 const code = str.codePointAt(i);
8249
8250 // Ignore control characters
8251 if (code <= 0x1F || (code >= 0x7F && code <= 0x9F)) {
8252 continue;
8253 }
8254
8255 // Ignore combining characters
8256 if (code >= 0x300 && code <= 0x36F) {
8257 continue;
8258 }
8259
8260 // Surrogates
8261 if (code > 0xFFFF) {
8262 i++;
8263 }
8264
8265 width += isFullwidthCodePoint(code) ? 2 : 1;
8266 }
8267
8268 return width;
8269};
8270
8271var center = alignCenter;
8272var left = alignLeft;
8273var right = alignRight;
8274
8275// lodash's way of generating pad characters.
8276
8277function createPadding (width) {
8278 var result = '';
8279 var string = ' ';
8280 var n = width;
8281 do {
8282 if (n % 2) {
8283 result += string;
8284 }
8285 n = Math.floor(n / 2);
8286 string += string;
8287 } while (n);
8288
8289 return result;
8290}
8291
8292function alignLeft (str, width) {
8293 var trimmed = str.trimRight();
8294 if (trimmed.length === 0 && str.length >= width) return str
8295 var padding = '';
8296 var strWidth = stringWidth(trimmed);
8297
8298 if (strWidth < width) {
8299 padding = createPadding(width - strWidth);
8300 }
8301
8302 return trimmed + padding
8303}
8304
8305function alignRight (str, width) {
8306 var trimmed = str.trimLeft();
8307 if (trimmed.length === 0 && str.length >= width) return str
8308 var padding = '';
8309 var strWidth = stringWidth(trimmed);
8310
8311 if (strWidth < width) {
8312 padding = createPadding(width - strWidth);
8313 }
8314
8315 return padding + trimmed
8316}
8317
8318function alignCenter (str, width) {
8319 var trimmed = str.trim();
8320 if (trimmed.length === 0 && str.length >= width) return str
8321 var padLeft = '';
8322 var padRight = '';
8323 var strWidth = stringWidth(trimmed);
8324
8325 if (strWidth < width) {
8326 var padLeftBy = parseInt((width - strWidth) / 2, 10);
8327 padLeft = createPadding(padLeftBy);
8328 padRight = createPadding(width - (strWidth + padLeftBy));
8329 }
8330
8331 return padLeft + trimmed + padRight
8332}
8333
8334var align = {
8335 center: center,
8336 left: left,
8337 right: right
8338};
8339
8340var aproba = createCommonjsModule(function (module) {
8341
8342function isArguments (thingy) {
8343 return thingy != null && typeof thingy === 'object' && thingy.hasOwnProperty('callee')
8344}
8345
8346var types = {
8347 '*': {label: 'any', check: function () { return true }},
8348 A: {label: 'array', check: function (thingy) { return Array.isArray(thingy) || isArguments(thingy) }},
8349 S: {label: 'string', check: function (thingy) { return typeof thingy === 'string' }},
8350 N: {label: 'number', check: function (thingy) { return typeof thingy === 'number' }},
8351 F: {label: 'function', check: function (thingy) { return typeof thingy === 'function' }},
8352 O: {label: 'object', check: function (thingy) { return typeof thingy === 'object' && thingy != null && !types.A.check(thingy) && !types.E.check(thingy) }},
8353 B: {label: 'boolean', check: function (thingy) { return typeof thingy === 'boolean' }},
8354 E: {label: 'error', check: function (thingy) { return thingy instanceof Error }},
8355 Z: {label: 'null', check: function (thingy) { return thingy == null }}
8356};
8357
8358function addSchema (schema, arity) {
8359 var group = arity[schema.length] = arity[schema.length] || [];
8360 if (group.indexOf(schema) === -1) group.push(schema);
8361}
8362
8363var validate = module.exports = function (rawSchemas, args) {
8364 if (arguments.length !== 2) throw wrongNumberOfArgs(['SA'], arguments.length)
8365 if (!rawSchemas) throw missingRequiredArg(0)
8366 if (!args) throw missingRequiredArg(1)
8367 if (!types.S.check(rawSchemas)) throw invalidType(0, ['string'], rawSchemas)
8368 if (!types.A.check(args)) throw invalidType(1, ['array'], args)
8369 var schemas = rawSchemas.split('|');
8370 var arity = {};
8371
8372 schemas.forEach(function (schema) {
8373 for (var ii = 0; ii < schema.length; ++ii) {
8374 var type = schema[ii];
8375 if (!types[type]) throw unknownType(ii, type)
8376 }
8377 if (/E.*E/.test(schema)) throw moreThanOneError(schema)
8378 addSchema(schema, arity);
8379 if (/E/.test(schema)) {
8380 addSchema(schema.replace(/E.*$/, 'E'), arity);
8381 addSchema(schema.replace(/E/, 'Z'), arity);
8382 if (schema.length === 1) addSchema('', arity);
8383 }
8384 });
8385 var matching = arity[args.length];
8386 if (!matching) {
8387 throw wrongNumberOfArgs(Object.keys(arity), args.length)
8388 }
8389 for (var ii = 0; ii < args.length; ++ii) {
8390 var newMatching = matching.filter(function (schema) {
8391 var type = schema[ii];
8392 var typeCheck = types[type].check;
8393 return typeCheck(args[ii])
8394 });
8395 if (!newMatching.length) {
8396 var labels = matching.map(function (schema) {
8397 return types[schema[ii]].label
8398 }).filter(function (schema) { return schema != null });
8399 throw invalidType(ii, labels, args[ii])
8400 }
8401 matching = newMatching;
8402 }
8403};
8404
8405function missingRequiredArg (num) {
8406 return newException('EMISSINGARG', 'Missing required argument #' + (num + 1))
8407}
8408
8409function unknownType (num, type) {
8410 return newException('EUNKNOWNTYPE', 'Unknown type ' + type + ' in argument #' + (num + 1))
8411}
8412
8413function invalidType (num, expectedTypes, value) {
8414 var valueType;
8415 Object.keys(types).forEach(function (typeCode) {
8416 if (types[typeCode].check(value)) valueType = types[typeCode].label;
8417 });
8418 return newException('EINVALIDTYPE', 'Argument #' + (num + 1) + ': Expected ' +
8419 englishList(expectedTypes) + ' but got ' + valueType)
8420}
8421
8422function englishList (list) {
8423 return list.join(', ').replace(/, ([^,]+)$/, ' or $1')
8424}
8425
8426function wrongNumberOfArgs (expected, got) {
8427 var english = englishList(expected);
8428 var args = expected.every(function (ex) { return ex.length === 1 })
8429 ? 'argument'
8430 : 'arguments';
8431 return newException('EWRONGARGCOUNT', 'Expected ' + english + ' ' + args + ' but got ' + got)
8432}
8433
8434function moreThanOneError (schema) {
8435 return newException('ETOOMANYERRORTYPES',
8436 'Only one error type per argument signature is allowed, more than one found in "' + schema + '"')
8437}
8438
8439function newException (code, msg) {
8440 var e = new Error(msg);
8441 e.code = code;
8442 if (Error.captureStackTrace) Error.captureStackTrace(e, validate);
8443 return e
8444}
8445});
8446
8447/*
8448object-assign
8449(c) Sindre Sorhus
8450@license MIT
8451*/
8452/* eslint-disable no-unused-vars */
8453var getOwnPropertySymbols = Object.getOwnPropertySymbols;
8454var hasOwnProperty = Object.prototype.hasOwnProperty;
8455var propIsEnumerable = Object.prototype.propertyIsEnumerable;
8456
8457function toObject(val) {
8458 if (val === null || val === undefined) {
8459 throw new TypeError('Object.assign cannot be called with null or undefined');
8460 }
8461
8462 return Object(val);
8463}
8464
8465function shouldUseNative() {
8466 try {
8467 if (!Object.assign) {
8468 return false;
8469 }
8470
8471 // Detect buggy property enumeration order in older V8 versions.
8472
8473 // https://bugs.chromium.org/p/v8/issues/detail?id=4118
8474 var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
8475 test1[5] = 'de';
8476 if (Object.getOwnPropertyNames(test1)[0] === '5') {
8477 return false;
8478 }
8479
8480 // https://bugs.chromium.org/p/v8/issues/detail?id=3056
8481 var test2 = {};
8482 for (var i = 0; i < 10; i++) {
8483 test2['_' + String.fromCharCode(i)] = i;
8484 }
8485 var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
8486 return test2[n];
8487 });
8488 if (order2.join('') !== '0123456789') {
8489 return false;
8490 }
8491
8492 // https://bugs.chromium.org/p/v8/issues/detail?id=3056
8493 var test3 = {};
8494 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
8495 test3[letter] = letter;
8496 });
8497 if (Object.keys(Object.assign({}, test3)).join('') !==
8498 'abcdefghijklmnopqrst') {
8499 return false;
8500 }
8501
8502 return true;
8503 } catch (err) {
8504 // We don't expect any of the above to throw, but better to be safe.
8505 return false;
8506 }
8507}
8508
8509var objectAssign = shouldUseNative() ? Object.assign : function (target, source) {
8510 var from;
8511 var to = toObject(target);
8512 var symbols;
8513
8514 for (var s = 1; s < arguments.length; s++) {
8515 from = Object(arguments[s]);
8516
8517 for (var key in from) {
8518 if (hasOwnProperty.call(from, key)) {
8519 to[key] = from[key];
8520 }
8521 }
8522
8523 if (getOwnPropertySymbols) {
8524 symbols = getOwnPropertySymbols(from);
8525 for (var i = 0; i < symbols.length; i++) {
8526 if (propIsEnumerable.call(from, symbols[i])) {
8527 to[symbols[i]] = from[symbols[i]];
8528 }
8529 }
8530 }
8531 }
8532
8533 return to;
8534};
8535
8536var ansiRegex$1 = function () {
8537 return /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-PRZcf-nqry=><]/g;
8538};
8539
8540var ansiRegex$2 = ansiRegex$1();
8541
8542var stripAnsi$1 = function (str) {
8543 return typeof str === 'string' ? str.replace(ansiRegex$2, '') : str;
8544};
8545
8546/* eslint-disable babel/new-cap, xo/throw-new-error */
8547var codePointAt = function (str, pos) {
8548 if (str === null || str === undefined) {
8549 throw TypeError();
8550 }
8551
8552 str = String(str);
8553
8554 var size = str.length;
8555 var i = pos ? Number(pos) : 0;
8556
8557 if (Number.isNaN(i)) {
8558 i = 0;
8559 }
8560
8561 if (i < 0 || i >= size) {
8562 return undefined;
8563 }
8564
8565 var first = str.charCodeAt(i);
8566
8567 if (first >= 0xD800 && first <= 0xDBFF && size > i + 1) {
8568 var second = str.charCodeAt(i + 1);
8569
8570 if (second >= 0xDC00 && second <= 0xDFFF) {
8571 return ((first - 0xD800) * 0x400) + second - 0xDC00 + 0x10000;
8572 }
8573 }
8574
8575 return first;
8576};
8577
8578var numberIsNan = Number.isNaN || function (x) {
8579 return x !== x;
8580};
8581
8582var isFullwidthCodePoint$1 = function (x) {
8583 if (numberIsNan(x)) {
8584 return false;
8585 }
8586
8587 // https://github.com/nodejs/io.js/blob/cff7300a578be1b10001f2d967aaedc88aee6402/lib/readline.js#L1369
8588
8589 // code points are derived from:
8590 // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt
8591 if (x >= 0x1100 && (
8592 x <= 0x115f || // Hangul Jamo
8593 0x2329 === x || // LEFT-POINTING ANGLE BRACKET
8594 0x232a === x || // RIGHT-POINTING ANGLE BRACKET
8595 // CJK Radicals Supplement .. Enclosed CJK Letters and Months
8596 (0x2e80 <= x && x <= 0x3247 && x !== 0x303f) ||
8597 // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A
8598 0x3250 <= x && x <= 0x4dbf ||
8599 // CJK Unified Ideographs .. Yi Radicals
8600 0x4e00 <= x && x <= 0xa4c6 ||
8601 // Hangul Jamo Extended-A
8602 0xa960 <= x && x <= 0xa97c ||
8603 // Hangul Syllables
8604 0xac00 <= x && x <= 0xd7a3 ||
8605 // CJK Compatibility Ideographs
8606 0xf900 <= x && x <= 0xfaff ||
8607 // Vertical Forms
8608 0xfe10 <= x && x <= 0xfe19 ||
8609 // CJK Compatibility Forms .. Small Form Variants
8610 0xfe30 <= x && x <= 0xfe6b ||
8611 // Halfwidth and Fullwidth Forms
8612 0xff01 <= x && x <= 0xff60 ||
8613 0xffe0 <= x && x <= 0xffe6 ||
8614 // Kana Supplement
8615 0x1b000 <= x && x <= 0x1b001 ||
8616 // Enclosed Ideographic Supplement
8617 0x1f200 <= x && x <= 0x1f251 ||
8618 // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane
8619 0x20000 <= x && x <= 0x3fffd)) {
8620 return true;
8621 }
8622
8623 return false;
8624};
8625
8626// https://github.com/nodejs/io.js/blob/cff7300a578be1b10001f2d967aaedc88aee6402/lib/readline.js#L1345
8627var stringWidth$1 = function (str) {
8628 if (typeof str !== 'string' || str.length === 0) {
8629 return 0;
8630 }
8631
8632 var width = 0;
8633
8634 str = stripAnsi$1(str);
8635
8636 for (var i = 0; i < str.length; i++) {
8637 var code = codePointAt(str, i);
8638
8639 // ignore control characters
8640 if (code <= 0x1f || (code >= 0x7f && code <= 0x9f)) {
8641 continue;
8642 }
8643
8644 // surrogates
8645 if (code >= 0x10000) {
8646 i++;
8647 }
8648
8649 if (isFullwidthCodePoint$1(code)) {
8650 width += 2;
8651 } else {
8652 width++;
8653 }
8654 }
8655
8656 return width;
8657};
8658
8659var wideTruncate_1 = wideTruncate;
8660
8661function wideTruncate (str, target) {
8662 if (stringWidth$1(str) === 0) return str
8663 if (target <= 0) return ''
8664 if (stringWidth$1(str) <= target) return str
8665
8666 // We compute the number of bytes of ansi sequences here and add
8667 // that to our initial truncation to ensure that we don't slice one
8668 // that we want to keep in half.
8669 var noAnsi = stripAnsi$1(str);
8670 var ansiSize = str.length + noAnsi.length;
8671 var truncated = str.slice(0, target + ansiSize);
8672
8673 // we have to shrink the result to account for our ansi sequence buffer
8674 // (if an ansi sequence was truncated) and double width characters.
8675 while (stringWidth$1(truncated) > target) {
8676 truncated = truncated.slice(0, -1);
8677 }
8678 return truncated
8679}
8680
8681var error = createCommonjsModule(function (module, exports) {
8682
8683
8684var User = exports.User = function User (msg) {
8685 var err = new Error(msg);
8686 Error.captureStackTrace(err, User);
8687 err.code = 'EGAUGE';
8688 return err
8689};
8690
8691exports.MissingTemplateValue = function MissingTemplateValue (item, values) {
8692 var err = new User(util.format('Missing template value "%s"', item.type));
8693 Error.captureStackTrace(err, MissingTemplateValue);
8694 err.template = item;
8695 err.values = values;
8696 return err
8697};
8698
8699exports.Internal = function Internal (msg) {
8700 var err = new Error(msg);
8701 Error.captureStackTrace(err, Internal);
8702 err.code = 'EGAUGEINTERNAL';
8703 return err
8704};
8705});
8706var error_1 = error.User;
8707var error_2 = error.MissingTemplateValue;
8708var error_3 = error.Internal;
8709
8710var templateItem = TemplateItem;
8711
8712function isPercent (num) {
8713 if (typeof num !== 'string') return false
8714 return num.slice(-1) === '%'
8715}
8716
8717function percent (num) {
8718 return Number(num.slice(0, -1)) / 100
8719}
8720
8721function TemplateItem (values, outputLength) {
8722 this.overallOutputLength = outputLength;
8723 this.finished = false;
8724 this.type = null;
8725 this.value = null;
8726 this.length = null;
8727 this.maxLength = null;
8728 this.minLength = null;
8729 this.kerning = null;
8730 this.align = 'left';
8731 this.padLeft = 0;
8732 this.padRight = 0;
8733 this.index = null;
8734 this.first = null;
8735 this.last = null;
8736 if (typeof values === 'string') {
8737 this.value = values;
8738 } else {
8739 for (var prop in values) this[prop] = values[prop];
8740 }
8741 // Realize percents
8742 if (isPercent(this.length)) {
8743 this.length = Math.round(this.overallOutputLength * percent(this.length));
8744 }
8745 if (isPercent(this.minLength)) {
8746 this.minLength = Math.round(this.overallOutputLength * percent(this.minLength));
8747 }
8748 if (isPercent(this.maxLength)) {
8749 this.maxLength = Math.round(this.overallOutputLength * percent(this.maxLength));
8750 }
8751 return this
8752}
8753
8754TemplateItem.prototype = {};
8755
8756TemplateItem.prototype.getBaseLength = function () {
8757 var length = this.length;
8758 if (length == null && typeof this.value === 'string' && this.maxLength == null && this.minLength == null) {
8759 length = stringWidth$1(this.value);
8760 }
8761 return length
8762};
8763
8764TemplateItem.prototype.getLength = function () {
8765 var length = this.getBaseLength();
8766 if (length == null) return null
8767 return length + this.padLeft + this.padRight
8768};
8769
8770TemplateItem.prototype.getMaxLength = function () {
8771 if (this.maxLength == null) return null
8772 return this.maxLength + this.padLeft + this.padRight
8773};
8774
8775TemplateItem.prototype.getMinLength = function () {
8776 if (this.minLength == null) return null
8777 return this.minLength + this.padLeft + this.padRight
8778};
8779
8780var renderTemplate_1 = createCommonjsModule(function (module) {
8781
8782
8783
8784
8785
8786
8787
8788function renderValueWithValues (values) {
8789 return function (item) {
8790 return renderValue(item, values)
8791 }
8792}
8793
8794var renderTemplate = module.exports = function (width, template, values) {
8795 var items = prepareItems(width, template, values);
8796 var rendered = items.map(renderValueWithValues(values)).join('');
8797 return align.left(wideTruncate_1(rendered, width), width)
8798};
8799
8800function preType (item) {
8801 var cappedTypeName = item.type[0].toUpperCase() + item.type.slice(1);
8802 return 'pre' + cappedTypeName
8803}
8804
8805function postType (item) {
8806 var cappedTypeName = item.type[0].toUpperCase() + item.type.slice(1);
8807 return 'post' + cappedTypeName
8808}
8809
8810function hasPreOrPost (item, values) {
8811 if (!item.type) return
8812 return values[preType(item)] || values[postType(item)]
8813}
8814
8815function generatePreAndPost (baseItem, parentValues) {
8816 var item = objectAssign({}, baseItem);
8817 var values = Object.create(parentValues);
8818 var template = [];
8819 var pre = preType(item);
8820 var post = postType(item);
8821 if (values[pre]) {
8822 template.push({value: values[pre]});
8823 values[pre] = null;
8824 }
8825 item.minLength = null;
8826 item.length = null;
8827 item.maxLength = null;
8828 template.push(item);
8829 values[item.type] = values[item.type];
8830 if (values[post]) {
8831 template.push({value: values[post]});
8832 values[post] = null;
8833 }
8834 return function ($1, $2, length) {
8835 return renderTemplate(length, template, values)
8836 }
8837}
8838
8839function prepareItems (width, template, values) {
8840 function cloneAndObjectify (item, index, arr) {
8841 var cloned = new templateItem(item, width);
8842 var type = cloned.type;
8843 if (cloned.value == null) {
8844 if (!(type in values)) {
8845 if (cloned.default == null) {
8846 throw new error.MissingTemplateValue(cloned, values)
8847 } else {
8848 cloned.value = cloned.default;
8849 }
8850 } else {
8851 cloned.value = values[type];
8852 }
8853 }
8854 if (cloned.value == null || cloned.value === '') return null
8855 cloned.index = index;
8856 cloned.first = index === 0;
8857 cloned.last = index === arr.length - 1;
8858 if (hasPreOrPost(cloned, values)) cloned.value = generatePreAndPost(cloned, values);
8859 return cloned
8860 }
8861
8862 var output = template.map(cloneAndObjectify).filter(function (item) { return item != null });
8863 var remainingSpace = width;
8864 var variableCount = output.length;
8865
8866 function consumeSpace (length) {
8867 if (length > remainingSpace) length = remainingSpace;
8868 remainingSpace -= length;
8869 }
8870
8871 function finishSizing (item, length) {
8872 if (item.finished) throw new error.Internal('Tried to finish template item that was already finished')
8873 if (length === Infinity) throw new error.Internal('Length of template item cannot be infinity')
8874 if (length != null) item.length = length;
8875 item.minLength = null;
8876 item.maxLength = null;
8877 --variableCount;
8878 item.finished = true;
8879 if (item.length == null) item.length = item.getBaseLength();
8880 if (item.length == null) throw new error.Internal('Finished template items must have a length')
8881 consumeSpace(item.getLength());
8882 }
8883
8884 output.forEach(function (item) {
8885 if (!item.kerning) return
8886 var prevPadRight = item.first ? 0 : output[item.index - 1].padRight;
8887 if (!item.first && prevPadRight < item.kerning) item.padLeft = item.kerning - prevPadRight;
8888 if (!item.last) item.padRight = item.kerning;
8889 });
8890
8891 // Finish any that have a fixed (literal or intuited) length
8892 output.forEach(function (item) {
8893 if (item.getBaseLength() == null) return
8894 finishSizing(item);
8895 });
8896
8897 var resized = 0;
8898 var resizing;
8899 var hunkSize;
8900 do {
8901 resizing = false;
8902 hunkSize = Math.round(remainingSpace / variableCount);
8903 output.forEach(function (item) {
8904 if (item.finished) return
8905 if (!item.maxLength) return
8906 if (item.getMaxLength() < hunkSize) {
8907 finishSizing(item, item.maxLength);
8908 resizing = true;
8909 }
8910 });
8911 } while (resizing && resized++ < output.length)
8912 if (resizing) throw new error.Internal('Resize loop iterated too many times while determining maxLength')
8913
8914 resized = 0;
8915 do {
8916 resizing = false;
8917 hunkSize = Math.round(remainingSpace / variableCount);
8918 output.forEach(function (item) {
8919 if (item.finished) return
8920 if (!item.minLength) return
8921 if (item.getMinLength() >= hunkSize) {
8922 finishSizing(item, item.minLength);
8923 resizing = true;
8924 }
8925 });
8926 } while (resizing && resized++ < output.length)
8927 if (resizing) throw new error.Internal('Resize loop iterated too many times while determining minLength')
8928
8929 hunkSize = Math.round(remainingSpace / variableCount);
8930 output.forEach(function (item) {
8931 if (item.finished) return
8932 finishSizing(item, hunkSize);
8933 });
8934
8935 return output
8936}
8937
8938function renderFunction (item, values, length) {
8939 aproba('OON', arguments);
8940 if (item.type) {
8941 return item.value(values, values[item.type + 'Theme'] || {}, length)
8942 } else {
8943 return item.value(values, {}, length)
8944 }
8945}
8946
8947function renderValue (item, values) {
8948 var length = item.getBaseLength();
8949 var value = typeof item.value === 'function' ? renderFunction(item, values, length) : item.value;
8950 if (value == null || value === '') return ''
8951 var alignWith = align[item.align] || align.left;
8952 var leftPadding = item.padLeft ? align.left('', item.padLeft) : '';
8953 var rightPadding = item.padRight ? align.right('', item.padRight) : '';
8954 var truncated = wideTruncate_1(String(value), length);
8955 var aligned = alignWith(truncated, length);
8956 return leftPadding + aligned + rightPadding
8957}
8958});
8959
8960var plumbing = createCommonjsModule(function (module) {
8961
8962
8963
8964
8965var Plumbing = module.exports = function (theme, template, width) {
8966 if (!width) width = 80;
8967 aproba('OAN', [theme, template, width]);
8968 this.showing = false;
8969 this.theme = theme;
8970 this.width = width;
8971 this.template = template;
8972};
8973Plumbing.prototype = {};
8974
8975Plumbing.prototype.setTheme = function (theme) {
8976 aproba('O', [theme]);
8977 this.theme = theme;
8978};
8979
8980Plumbing.prototype.setTemplate = function (template) {
8981 aproba('A', [template]);
8982 this.template = template;
8983};
8984
8985Plumbing.prototype.setWidth = function (width) {
8986 aproba('N', [width]);
8987 this.width = width;
8988};
8989
8990Plumbing.prototype.hide = function () {
8991 return consoleControlStrings.gotoSOL() + consoleControlStrings.eraseLine()
8992};
8993
8994Plumbing.prototype.hideCursor = consoleControlStrings.hideCursor;
8995
8996Plumbing.prototype.showCursor = consoleControlStrings.showCursor;
8997
8998Plumbing.prototype.show = function (status) {
8999 var values = Object.create(this.theme);
9000 for (var key in status) {
9001 values[key] = status[key];
9002 }
9003
9004 return renderTemplate_1(this.width, this.template, values).trim() +
9005 consoleControlStrings.color('reset') +
9006 consoleControlStrings.eraseLine() + consoleControlStrings.gotoSOL()
9007};
9008});
9009
9010var hasUnicode_1 = createCommonjsModule(function (module) {
9011
9012
9013var hasUnicode = module.exports = function () {
9014 // Recent Win32 platforms (>XP) CAN support unicode in the console but
9015 // don't have to, and in non-english locales often use traditional local
9016 // code pages. There's no way, short of windows system calls or execing
9017 // the chcp command line program to figure this out. As such, we default
9018 // this to false and encourage your users to override it via config if
9019 // appropriate.
9020 if (os.type() == "Windows_NT") { return false }
9021
9022 var isUTF8 = /UTF-?8$/i;
9023 var ctype = process.env.LC_ALL || process.env.LC_CTYPE || process.env.LANG;
9024 return isUTF8.test(ctype)
9025};
9026});
9027
9028var hasColor = isWin32() || isColorTerm();
9029
9030function isWin32 () {
9031 return process.platform === 'win32'
9032}
9033
9034function isColorTerm () {
9035 var termHasColor = /^screen|^xterm|^vt100|color|ansi|cygwin|linux/i;
9036 return !!process.env.COLORTERM || termHasColor.test(process.env.TERM)
9037}
9038
9039var signals = createCommonjsModule(function (module) {
9040// This is not the set of all possible signals.
9041//
9042// It IS, however, the set of all signals that trigger
9043// an exit on either Linux or BSD systems. Linux is a
9044// superset of the signal names supported on BSD, and
9045// the unknown signals just fail to register, so we can
9046// catch that easily enough.
9047//
9048// Don't bother with SIGKILL. It's uncatchable, which
9049// means that we can't fire any callbacks anyway.
9050//
9051// If a user does happen to register a handler on a non-
9052// fatal signal like SIGWINCH or something, and then
9053// exit, it'll end up firing `process.emit('exit')`, so
9054// the handler will be fired anyway.
9055//
9056// SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised
9057// artificially, inherently leave the process in a
9058// state from which it is not safe to try and enter JS
9059// listeners.
9060module.exports = [
9061 'SIGABRT',
9062 'SIGALRM',
9063 'SIGHUP',
9064 'SIGINT',
9065 'SIGTERM'
9066];
9067
9068if (process.platform !== 'win32') {
9069 module.exports.push(
9070 'SIGVTALRM',
9071 'SIGXCPU',
9072 'SIGXFSZ',
9073 'SIGUSR2',
9074 'SIGTRAP',
9075 'SIGSYS',
9076 'SIGQUIT',
9077 'SIGIOT'
9078 // should detect profiler and enable/disable accordingly.
9079 // see #21
9080 // 'SIGPROF'
9081 );
9082}
9083
9084if (process.platform === 'linux') {
9085 module.exports.push(
9086 'SIGIO',
9087 'SIGPOLL',
9088 'SIGPWR',
9089 'SIGSTKFLT',
9090 'SIGUNUSED'
9091 );
9092}
9093});
9094
9095// Note: since nyc uses this module to output coverage, any lines
9096// that are in the direct sync flow of nyc's outputCoverage are
9097// ignored, since we can never get coverage for them.
9098
9099var signals$1 = signals;
9100
9101var EE = events;
9102/* istanbul ignore if */
9103if (typeof EE !== 'function') {
9104 EE = EE.EventEmitter;
9105}
9106
9107var emitter;
9108if (process.__signal_exit_emitter__) {
9109 emitter = process.__signal_exit_emitter__;
9110} else {
9111 emitter = process.__signal_exit_emitter__ = new EE();
9112 emitter.count = 0;
9113 emitter.emitted = {};
9114}
9115
9116// Because this emitter is a global, we have to check to see if a
9117// previous version of this library failed to enable infinite listeners.
9118// I know what you're about to say. But literally everything about
9119// signal-exit is a compromise with evil. Get used to it.
9120if (!emitter.infinite) {
9121 emitter.setMaxListeners(Infinity);
9122 emitter.infinite = true;
9123}
9124
9125var signalExit = function (cb, opts) {
9126 assert.equal(typeof cb, 'function', 'a callback must be provided for exit handler');
9127
9128 if (loaded === false) {
9129 load();
9130 }
9131
9132 var ev = 'exit';
9133 if (opts && opts.alwaysLast) {
9134 ev = 'afterexit';
9135 }
9136
9137 var remove = function () {
9138 emitter.removeListener(ev, cb);
9139 if (emitter.listeners('exit').length === 0 &&
9140 emitter.listeners('afterexit').length === 0) {
9141 unload();
9142 }
9143 };
9144 emitter.on(ev, cb);
9145
9146 return remove
9147};
9148
9149var unload_1 = unload;
9150function unload () {
9151 if (!loaded) {
9152 return
9153 }
9154 loaded = false;
9155
9156 signals$1.forEach(function (sig) {
9157 try {
9158 process.removeListener(sig, sigListeners[sig]);
9159 } catch (er) {}
9160 });
9161 process.emit = originalProcessEmit;
9162 process.reallyExit = originalProcessReallyExit;
9163 emitter.count -= 1;
9164}
9165
9166function emit (event, code, signal) {
9167 if (emitter.emitted[event]) {
9168 return
9169 }
9170 emitter.emitted[event] = true;
9171 emitter.emit(event, code, signal);
9172}
9173
9174// { <signal>: <listener fn>, ... }
9175var sigListeners = {};
9176signals$1.forEach(function (sig) {
9177 sigListeners[sig] = function listener () {
9178 // If there are no other listeners, an exit is coming!
9179 // Simplest way: remove us and then re-send the signal.
9180 // We know that this will kill the process, so we can
9181 // safely emit now.
9182 var listeners = process.listeners(sig);
9183 if (listeners.length === emitter.count) {
9184 unload();
9185 emit('exit', null, sig);
9186 /* istanbul ignore next */
9187 emit('afterexit', null, sig);
9188 /* istanbul ignore next */
9189 process.kill(process.pid, sig);
9190 }
9191 };
9192});
9193
9194var signals_1 = function () {
9195 return signals$1
9196};
9197
9198var load_1 = load;
9199
9200var loaded = false;
9201
9202function load () {
9203 if (loaded) {
9204 return
9205 }
9206 loaded = true;
9207
9208 // This is the number of onSignalExit's that are in play.
9209 // It's important so that we can count the correct number of
9210 // listeners on signals, and don't wait for the other one to
9211 // handle it instead of us.
9212 emitter.count += 1;
9213
9214 signals$1 = signals$1.filter(function (sig) {
9215 try {
9216 process.on(sig, sigListeners[sig]);
9217 return true
9218 } catch (er) {
9219 return false
9220 }
9221 });
9222
9223 process.emit = processEmit;
9224 process.reallyExit = processReallyExit;
9225}
9226
9227var originalProcessReallyExit = process.reallyExit;
9228function processReallyExit (code) {
9229 process.exitCode = code || 0;
9230 emit('exit', process.exitCode, null);
9231 /* istanbul ignore next */
9232 emit('afterexit', process.exitCode, null);
9233 /* istanbul ignore next */
9234 originalProcessReallyExit.call(process, process.exitCode);
9235}
9236
9237var originalProcessEmit = process.emit;
9238function processEmit (ev, arg) {
9239 if (ev === 'exit') {
9240 if (arg !== undefined) {
9241 process.exitCode = arg;
9242 }
9243 var ret = originalProcessEmit.apply(this, arguments);
9244 emit('exit', process.exitCode, null);
9245 /* istanbul ignore next */
9246 emit('afterexit', process.exitCode, null);
9247 return ret
9248 } else {
9249 return originalProcessEmit.apply(this, arguments)
9250 }
9251}
9252signalExit.unload = unload_1;
9253signalExit.signals = signals_1;
9254signalExit.load = load_1;
9255
9256var spin = function spin (spinstr, spun) {
9257 return spinstr[spun % spinstr.length]
9258};
9259
9260var progressBar = function (theme, width, completed) {
9261 aproba('ONN', [theme, width, completed]);
9262 if (completed < 0) completed = 0;
9263 if (completed > 1) completed = 1;
9264 if (width <= 0) return ''
9265 var sofar = Math.round(width * completed);
9266 var rest = width - sofar;
9267 var template = [
9268 {type: 'complete', value: repeat(theme.complete, sofar), length: sofar},
9269 {type: 'remaining', value: repeat(theme.remaining, rest), length: rest}
9270 ];
9271 return renderTemplate_1(width, template, theme)
9272};
9273
9274// lodash's way of repeating
9275function repeat (string, width) {
9276 var result = '';
9277 var n = width;
9278 do {
9279 if (n % 2) {
9280 result += string;
9281 }
9282 n = Math.floor(n / 2);
9283 /*eslint no-self-assign: 0*/
9284 string += string;
9285 } while (n && stringWidth$1(result) < width)
9286
9287 return wideTruncate_1(result, width)
9288}
9289
9290var baseTheme = {
9291 activityIndicator: function (values, theme, width) {
9292 if (values.spun == null) return
9293 return spin(theme, values.spun)
9294 },
9295 progressbar: function (values, theme, width) {
9296 if (values.completed == null) return
9297 return progressBar(theme, width, values.completed)
9298 }
9299};
9300
9301var themeSet = function () {
9302 return ThemeSetProto.newThemeSet()
9303};
9304
9305var ThemeSetProto = {};
9306
9307ThemeSetProto.baseTheme = baseTheme;
9308
9309ThemeSetProto.newTheme = function (parent, theme) {
9310 if (!theme) {
9311 theme = parent;
9312 parent = this.baseTheme;
9313 }
9314 return objectAssign({}, parent, theme)
9315};
9316
9317ThemeSetProto.getThemeNames = function () {
9318 return Object.keys(this.themes)
9319};
9320
9321ThemeSetProto.addTheme = function (name, parent, theme) {
9322 this.themes[name] = this.newTheme(parent, theme);
9323};
9324
9325ThemeSetProto.addToAllThemes = function (theme) {
9326 var themes = this.themes;
9327 Object.keys(themes).forEach(function (name) {
9328 objectAssign(themes[name], theme);
9329 });
9330 objectAssign(this.baseTheme, theme);
9331};
9332
9333ThemeSetProto.getTheme = function (name) {
9334 if (!this.themes[name]) throw this.newMissingThemeError(name)
9335 return this.themes[name]
9336};
9337
9338ThemeSetProto.setDefault = function (opts, name) {
9339 if (name == null) {
9340 name = opts;
9341 opts = {};
9342 }
9343 var platform = opts.platform == null ? 'fallback' : opts.platform;
9344 var hasUnicode = !!opts.hasUnicode;
9345 var hasColor = !!opts.hasColor;
9346 if (!this.defaults[platform]) this.defaults[platform] = {true: {}, false: {}};
9347 this.defaults[platform][hasUnicode][hasColor] = name;
9348};
9349
9350ThemeSetProto.getDefault = function (opts) {
9351 if (!opts) opts = {};
9352 var platformName = opts.platform || process.platform;
9353 var platform = this.defaults[platformName] || this.defaults.fallback;
9354 var hasUnicode = !!opts.hasUnicode;
9355 var hasColor = !!opts.hasColor;
9356 if (!platform) throw this.newMissingDefaultThemeError(platformName, hasUnicode, hasColor)
9357 if (!platform[hasUnicode][hasColor]) {
9358 if (hasUnicode && hasColor && platform[!hasUnicode][hasColor]) {
9359 hasUnicode = false;
9360 } else if (hasUnicode && hasColor && platform[hasUnicode][!hasColor]) {
9361 hasColor = false;
9362 } else if (hasUnicode && hasColor && platform[!hasUnicode][!hasColor]) {
9363 hasUnicode = false;
9364 hasColor = false;
9365 } else if (hasUnicode && !hasColor && platform[!hasUnicode][hasColor]) {
9366 hasUnicode = false;
9367 } else if (!hasUnicode && hasColor && platform[hasUnicode][!hasColor]) {
9368 hasColor = false;
9369 } else if (platform === this.defaults.fallback) {
9370 throw this.newMissingDefaultThemeError(platformName, hasUnicode, hasColor)
9371 }
9372 }
9373 if (platform[hasUnicode][hasColor]) {
9374 return this.getTheme(platform[hasUnicode][hasColor])
9375 } else {
9376 return this.getDefault(objectAssign({}, opts, {platform: 'fallback'}))
9377 }
9378};
9379
9380ThemeSetProto.newMissingThemeError = function newMissingThemeError (name) {
9381 var err = new Error('Could not find a gauge theme named "' + name + '"');
9382 Error.captureStackTrace.call(err, newMissingThemeError);
9383 err.theme = name;
9384 err.code = 'EMISSINGTHEME';
9385 return err
9386};
9387
9388ThemeSetProto.newMissingDefaultThemeError = function newMissingDefaultThemeError (platformName, hasUnicode, hasColor) {
9389 var err = new Error(
9390 'Could not find a gauge theme for your platform/unicode/color use combo:\n' +
9391 ' platform = ' + platformName + '\n' +
9392 ' hasUnicode = ' + hasUnicode + '\n' +
9393 ' hasColor = ' + hasColor);
9394 Error.captureStackTrace.call(err, newMissingDefaultThemeError);
9395 err.platform = platformName;
9396 err.hasUnicode = hasUnicode;
9397 err.hasColor = hasColor;
9398 err.code = 'EMISSINGTHEME';
9399 return err
9400};
9401
9402ThemeSetProto.newThemeSet = function () {
9403 var themeset = function (opts) {
9404 return themeset.getDefault(opts)
9405 };
9406 return objectAssign(themeset, ThemeSetProto, {
9407 themes: objectAssign({}, this.themes),
9408 baseTheme: objectAssign({}, this.baseTheme),
9409 defaults: JSON.parse(JSON.stringify(this.defaults || {}))
9410 })
9411};
9412
9413var themes_1 = createCommonjsModule(function (module) {
9414
9415
9416
9417var themes = module.exports = new themeSet();
9418
9419themes.addTheme('ASCII', {
9420 preProgressbar: '[',
9421 postProgressbar: ']',
9422 progressbarTheme: {
9423 complete: '#',
9424 remaining: '.'
9425 },
9426 activityIndicatorTheme: '-\\|/',
9427 preSubsection: '>'
9428});
9429
9430themes.addTheme('colorASCII', themes.getTheme('ASCII'), {
9431 progressbarTheme: {
9432 preComplete: consoleControlStrings.color('inverse'),
9433 complete: ' ',
9434 postComplete: consoleControlStrings.color('stopInverse'),
9435 preRemaining: consoleControlStrings.color('brightBlack'),
9436 remaining: '.',
9437 postRemaining: consoleControlStrings.color('reset')
9438 }
9439});
9440
9441themes.addTheme('brailleSpinner', {
9442 preProgressbar: '⸨',
9443 postProgressbar: '⸩',
9444 progressbarTheme: {
9445 complete: '░',
9446 remaining: '⠂'
9447 },
9448 activityIndicatorTheme: '⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏',
9449 preSubsection: '>'
9450});
9451
9452themes.addTheme('colorBrailleSpinner', themes.getTheme('brailleSpinner'), {
9453 progressbarTheme: {
9454 preComplete: consoleControlStrings.color('inverse'),
9455 complete: ' ',
9456 postComplete: consoleControlStrings.color('stopInverse'),
9457 preRemaining: consoleControlStrings.color('brightBlack'),
9458 remaining: '░',
9459 postRemaining: consoleControlStrings.color('reset')
9460 }
9461});
9462
9463themes.setDefault({}, 'ASCII');
9464themes.setDefault({hasColor: true}, 'colorASCII');
9465themes.setDefault({platform: 'darwin', hasUnicode: true}, 'brailleSpinner');
9466themes.setDefault({platform: 'darwin', hasUnicode: true, hasColor: true}, 'colorBrailleSpinner');
9467});
9468
9469// this exists so we can replace it during testing
9470var setInterval_1 = setInterval;
9471
9472// this exists so we can replace it during testing
9473var process_1 = process;
9474
9475var setImmediate_1 = createCommonjsModule(function (module) {
9476
9477try {
9478 module.exports = setImmediate;
9479} catch (ex) {
9480 module.exports = process_1.nextTick;
9481}
9482});
9483
9484var gauge = Gauge;
9485
9486function callWith (obj, method) {
9487 return function () {
9488 return method.call(obj)
9489 }
9490}
9491
9492function Gauge (arg1, arg2) {
9493 var options, writeTo;
9494 if (arg1 && arg1.write) {
9495 writeTo = arg1;
9496 options = arg2 || {};
9497 } else if (arg2 && arg2.write) {
9498 writeTo = arg2;
9499 options = arg1 || {};
9500 } else {
9501 writeTo = process_1.stderr;
9502 options = arg1 || arg2 || {};
9503 }
9504
9505 this._status = {
9506 spun: 0,
9507 section: '',
9508 subsection: ''
9509 };
9510 this._paused = false; // are we paused for back pressure?
9511 this._disabled = true; // are all progress bar updates disabled?
9512 this._showing = false; // do we WANT the progress bar on screen
9513 this._onScreen = false; // IS the progress bar on screen
9514 this._needsRedraw = false; // should we print something at next tick?
9515 this._hideCursor = options.hideCursor == null ? true : options.hideCursor;
9516 this._fixedFramerate = options.fixedFramerate == null
9517 ? !(/^v0\.8\./.test(process_1.version))
9518 : options.fixedFramerate;
9519 this._lastUpdateAt = null;
9520 this._updateInterval = options.updateInterval == null ? 50 : options.updateInterval;
9521
9522 this._themes = options.themes || themes_1;
9523 this._theme = options.theme;
9524 var theme = this._computeTheme(options.theme);
9525 var template = options.template || [
9526 {type: 'progressbar', length: 20},
9527 {type: 'activityIndicator', kerning: 1, length: 1},
9528 {type: 'section', kerning: 1, default: ''},
9529 {type: 'subsection', kerning: 1, default: ''}
9530 ];
9531 this.setWriteTo(writeTo, options.tty);
9532 var PlumbingClass = options.Plumbing || plumbing;
9533 this._gauge = new PlumbingClass(theme, template, this.getWidth());
9534
9535 this._$$doRedraw = callWith(this, this._doRedraw);
9536 this._$$handleSizeChange = callWith(this, this._handleSizeChange);
9537
9538 this._cleanupOnExit = options.cleanupOnExit == null || options.cleanupOnExit;
9539 this._removeOnExit = null;
9540
9541 if (options.enabled || (options.enabled == null && this._tty && this._tty.isTTY)) {
9542 this.enable();
9543 } else {
9544 this.disable();
9545 }
9546}
9547Gauge.prototype = {};
9548
9549Gauge.prototype.isEnabled = function () {
9550 return !this._disabled
9551};
9552
9553Gauge.prototype.setTemplate = function (template) {
9554 this._gauge.setTemplate(template);
9555 if (this._showing) this._requestRedraw();
9556};
9557
9558Gauge.prototype._computeTheme = function (theme) {
9559 if (!theme) theme = {};
9560 if (typeof theme === 'string') {
9561 theme = this._themes.getTheme(theme);
9562 } else if (theme && (Object.keys(theme).length === 0 || theme.hasUnicode != null || theme.hasColor != null)) {
9563 var useUnicode = theme.hasUnicode == null ? hasUnicode_1() : theme.hasUnicode;
9564 var useColor = theme.hasColor == null ? hasColor : theme.hasColor;
9565 theme = this._themes.getDefault({hasUnicode: useUnicode, hasColor: useColor, platform: theme.platform});
9566 }
9567 return theme
9568};
9569
9570Gauge.prototype.setThemeset = function (themes) {
9571 this._themes = themes;
9572 this.setTheme(this._theme);
9573};
9574
9575Gauge.prototype.setTheme = function (theme) {
9576 this._gauge.setTheme(this._computeTheme(theme));
9577 if (this._showing) this._requestRedraw();
9578 this._theme = theme;
9579};
9580
9581Gauge.prototype._requestRedraw = function () {
9582 this._needsRedraw = true;
9583 if (!this._fixedFramerate) this._doRedraw();
9584};
9585
9586Gauge.prototype.getWidth = function () {
9587 return ((this._tty && this._tty.columns) || 80) - 1
9588};
9589
9590Gauge.prototype.setWriteTo = function (writeTo, tty) {
9591 var enabled = !this._disabled;
9592 if (enabled) this.disable();
9593 this._writeTo = writeTo;
9594 this._tty = tty ||
9595 (writeTo === process_1.stderr && process_1.stdout.isTTY && process_1.stdout) ||
9596 (writeTo.isTTY && writeTo) ||
9597 this._tty;
9598 if (this._gauge) this._gauge.setWidth(this.getWidth());
9599 if (enabled) this.enable();
9600};
9601
9602Gauge.prototype.enable = function () {
9603 if (!this._disabled) return
9604 this._disabled = false;
9605 if (this._tty) this._enableEvents();
9606 if (this._showing) this.show();
9607};
9608
9609Gauge.prototype.disable = function () {
9610 if (this._disabled) return
9611 if (this._showing) {
9612 this._lastUpdateAt = null;
9613 this._showing = false;
9614 this._doRedraw();
9615 this._showing = true;
9616 }
9617 this._disabled = true;
9618 if (this._tty) this._disableEvents();
9619};
9620
9621Gauge.prototype._enableEvents = function () {
9622 if (this._cleanupOnExit) {
9623 this._removeOnExit = signalExit(callWith(this, this.disable));
9624 }
9625 this._tty.on('resize', this._$$handleSizeChange);
9626 if (this._fixedFramerate) {
9627 this.redrawTracker = setInterval_1(this._$$doRedraw, this._updateInterval);
9628 if (this.redrawTracker.unref) this.redrawTracker.unref();
9629 }
9630};
9631
9632Gauge.prototype._disableEvents = function () {
9633 this._tty.removeListener('resize', this._$$handleSizeChange);
9634 if (this._fixedFramerate) clearInterval(this.redrawTracker);
9635 if (this._removeOnExit) this._removeOnExit();
9636};
9637
9638Gauge.prototype.hide = function (cb) {
9639 if (this._disabled) return cb && process_1.nextTick(cb)
9640 if (!this._showing) return cb && process_1.nextTick(cb)
9641 this._showing = false;
9642 this._doRedraw();
9643 cb && setImmediate_1(cb);
9644};
9645
9646Gauge.prototype.show = function (section, completed) {
9647 this._showing = true;
9648 if (typeof section === 'string') {
9649 this._status.section = section;
9650 } else if (typeof section === 'object') {
9651 var sectionKeys = Object.keys(section);
9652 for (var ii = 0; ii < sectionKeys.length; ++ii) {
9653 var key = sectionKeys[ii];
9654 this._status[key] = section[key];
9655 }
9656 }
9657 if (completed != null) this._status.completed = completed;
9658 if (this._disabled) return
9659 this._requestRedraw();
9660};
9661
9662Gauge.prototype.pulse = function (subsection) {
9663 this._status.subsection = subsection || '';
9664 this._status.spun ++;
9665 if (this._disabled) return
9666 if (!this._showing) return
9667 this._requestRedraw();
9668};
9669
9670Gauge.prototype._handleSizeChange = function () {
9671 this._gauge.setWidth(this._tty.columns - 1);
9672 this._requestRedraw();
9673};
9674
9675Gauge.prototype._doRedraw = function () {
9676 if (this._disabled || this._paused) return
9677 if (!this._fixedFramerate) {
9678 var now = Date.now();
9679 if (this._lastUpdateAt && now - this._lastUpdateAt < this._updateInterval) return
9680 this._lastUpdateAt = now;
9681 }
9682 if (!this._showing && this._onScreen) {
9683 this._onScreen = false;
9684 var result = this._gauge.hide();
9685 if (this._hideCursor) {
9686 result += this._gauge.showCursor();
9687 }
9688 return this._writeTo.write(result)
9689 }
9690 if (!this._showing && !this._onScreen) return
9691 if (this._showing && !this._onScreen) {
9692 this._onScreen = true;
9693 this._needsRedraw = true;
9694 if (this._hideCursor) {
9695 this._writeTo.write(this._gauge.hideCursor());
9696 }
9697 }
9698 if (!this._needsRedraw) return
9699 if (!this._writeTo.write(this._gauge.show(this._status))) {
9700 this._paused = true;
9701 this._writeTo.on('drain', callWith(this, function () {
9702 this._paused = false;
9703 this._doRedraw();
9704 }));
9705 }
9706};
9707
9708const { FORCE_COLOR, NODE_DISABLE_COLORS, TERM } = process.env;
9709
9710const $ = {
9711 enabled: !NODE_DISABLE_COLORS && TERM !== 'dumb' && FORCE_COLOR !== '0',
9712
9713 // modifiers
9714 reset: init(0, 0),
9715 bold: init(1, 22),
9716 dim: init(2, 22),
9717 italic: init(3, 23),
9718 underline: init(4, 24),
9719 inverse: init(7, 27),
9720 hidden: init(8, 28),
9721 strikethrough: init(9, 29),
9722
9723 // colors
9724 black: init(30, 39),
9725 red: init(31, 39),
9726 green: init(32, 39),
9727 yellow: init(33, 39),
9728 blue: init(34, 39),
9729 magenta: init(35, 39),
9730 cyan: init(36, 39),
9731 white: init(37, 39),
9732 gray: init(90, 39),
9733 grey: init(90, 39),
9734
9735 // background colors
9736 bgBlack: init(40, 49),
9737 bgRed: init(41, 49),
9738 bgGreen: init(42, 49),
9739 bgYellow: init(43, 49),
9740 bgBlue: init(44, 49),
9741 bgMagenta: init(45, 49),
9742 bgCyan: init(46, 49),
9743 bgWhite: init(47, 49)
9744};
9745
9746function run(arr, str) {
9747 let i=0, tmp, beg='', end='';
9748 for (; i < arr.length; i++) {
9749 tmp = arr[i];
9750 beg += tmp.open;
9751 end += tmp.close;
9752 if (str.includes(tmp.close)) {
9753 str = str.replace(tmp.rgx, tmp.close + tmp.open);
9754 }
9755 }
9756 return beg + str + end;
9757}
9758
9759function chain(has, keys) {
9760 let ctx = { has, keys };
9761
9762 ctx.reset = $.reset.bind(ctx);
9763 ctx.bold = $.bold.bind(ctx);
9764 ctx.dim = $.dim.bind(ctx);
9765 ctx.italic = $.italic.bind(ctx);
9766 ctx.underline = $.underline.bind(ctx);
9767 ctx.inverse = $.inverse.bind(ctx);
9768 ctx.hidden = $.hidden.bind(ctx);
9769 ctx.strikethrough = $.strikethrough.bind(ctx);
9770
9771 ctx.black = $.black.bind(ctx);
9772 ctx.red = $.red.bind(ctx);
9773 ctx.green = $.green.bind(ctx);
9774 ctx.yellow = $.yellow.bind(ctx);
9775 ctx.blue = $.blue.bind(ctx);
9776 ctx.magenta = $.magenta.bind(ctx);
9777 ctx.cyan = $.cyan.bind(ctx);
9778 ctx.white = $.white.bind(ctx);
9779 ctx.gray = $.gray.bind(ctx);
9780 ctx.grey = $.grey.bind(ctx);
9781
9782 ctx.bgBlack = $.bgBlack.bind(ctx);
9783 ctx.bgRed = $.bgRed.bind(ctx);
9784 ctx.bgGreen = $.bgGreen.bind(ctx);
9785 ctx.bgYellow = $.bgYellow.bind(ctx);
9786 ctx.bgBlue = $.bgBlue.bind(ctx);
9787 ctx.bgMagenta = $.bgMagenta.bind(ctx);
9788 ctx.bgCyan = $.bgCyan.bind(ctx);
9789 ctx.bgWhite = $.bgWhite.bind(ctx);
9790
9791 return ctx;
9792}
9793
9794function init(open, close) {
9795 let blk = {
9796 open: `\x1b[${open}m`,
9797 close: `\x1b[${close}m`,
9798 rgx: new RegExp(`\\x1b\\[${close}m`, 'g')
9799 };
9800 return function (txt) {
9801 if (this !== void 0 && this.has !== void 0) {
9802 this.has.includes(open) || (this.has.push(open),this.keys.push(blk));
9803 return txt === void 0 ? this : $.enabled ? run(this.keys, txt+'') : txt+'';
9804 }
9805 return txt === void 0 ? chain([open], [blk]) : $.enabled ? run([blk], txt+'') : txt+'';
9806 };
9807}
9808
9809var kleur = $;
9810
9811var semver = createCommonjsModule(function (module, exports) {
9812exports = module.exports = SemVer;
9813
9814var debug;
9815/* istanbul ignore next */
9816if (typeof process === 'object' &&
9817 process.env &&
9818 process.env.NODE_DEBUG &&
9819 /\bsemver\b/i.test(process.env.NODE_DEBUG)) {
9820 debug = function () {
9821 var args = Array.prototype.slice.call(arguments, 0);
9822 args.unshift('SEMVER');
9823 console.log.apply(console, args);
9824 };
9825} else {
9826 debug = function () {};
9827}
9828
9829// Note: this is the semver.org version of the spec that it implements
9830// Not necessarily the package version of this code.
9831exports.SEMVER_SPEC_VERSION = '2.0.0';
9832
9833var MAX_LENGTH = 256;
9834var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||
9835 /* istanbul ignore next */ 9007199254740991;
9836
9837// Max safe segment length for coercion.
9838var MAX_SAFE_COMPONENT_LENGTH = 16;
9839
9840// The actual regexps go on exports.re
9841var re = exports.re = [];
9842var src = exports.src = [];
9843var t = exports.tokens = {};
9844var R = 0;
9845
9846function tok (n) {
9847 t[n] = R++;
9848}
9849
9850// The following Regular Expressions can be used for tokenizing,
9851// validating, and parsing SemVer version strings.
9852
9853// ## Numeric Identifier
9854// A single `0`, or a non-zero digit followed by zero or more digits.
9855
9856tok('NUMERICIDENTIFIER');
9857src[t.NUMERICIDENTIFIER] = '0|[1-9]\\d*';
9858tok('NUMERICIDENTIFIERLOOSE');
9859src[t.NUMERICIDENTIFIERLOOSE] = '[0-9]+';
9860
9861// ## Non-numeric Identifier
9862// Zero or more digits, followed by a letter or hyphen, and then zero or
9863// more letters, digits, or hyphens.
9864
9865tok('NONNUMERICIDENTIFIER');
9866src[t.NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*';
9867
9868// ## Main Version
9869// Three dot-separated numeric identifiers.
9870
9871tok('MAINVERSION');
9872src[t.MAINVERSION] = '(' + src[t.NUMERICIDENTIFIER] + ')\\.' +
9873 '(' + src[t.NUMERICIDENTIFIER] + ')\\.' +
9874 '(' + src[t.NUMERICIDENTIFIER] + ')';
9875
9876tok('MAINVERSIONLOOSE');
9877src[t.MAINVERSIONLOOSE] = '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\.' +
9878 '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\.' +
9879 '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')';
9880
9881// ## Pre-release Version Identifier
9882// A numeric identifier, or a non-numeric identifier.
9883
9884tok('PRERELEASEIDENTIFIER');
9885src[t.PRERELEASEIDENTIFIER] = '(?:' + src[t.NUMERICIDENTIFIER] +
9886 '|' + src[t.NONNUMERICIDENTIFIER] + ')';
9887
9888tok('PRERELEASEIDENTIFIERLOOSE');
9889src[t.PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[t.NUMERICIDENTIFIERLOOSE] +
9890 '|' + src[t.NONNUMERICIDENTIFIER] + ')';
9891
9892// ## Pre-release Version
9893// Hyphen, followed by one or more dot-separated pre-release version
9894// identifiers.
9895
9896tok('PRERELEASE');
9897src[t.PRERELEASE] = '(?:-(' + src[t.PRERELEASEIDENTIFIER] +
9898 '(?:\\.' + src[t.PRERELEASEIDENTIFIER] + ')*))';
9899
9900tok('PRERELEASELOOSE');
9901src[t.PRERELEASELOOSE] = '(?:-?(' + src[t.PRERELEASEIDENTIFIERLOOSE] +
9902 '(?:\\.' + src[t.PRERELEASEIDENTIFIERLOOSE] + ')*))';
9903
9904// ## Build Metadata Identifier
9905// Any combination of digits, letters, or hyphens.
9906
9907tok('BUILDIDENTIFIER');
9908src[t.BUILDIDENTIFIER] = '[0-9A-Za-z-]+';
9909
9910// ## Build Metadata
9911// Plus sign, followed by one or more period-separated build metadata
9912// identifiers.
9913
9914tok('BUILD');
9915src[t.BUILD] = '(?:\\+(' + src[t.BUILDIDENTIFIER] +
9916 '(?:\\.' + src[t.BUILDIDENTIFIER] + ')*))';
9917
9918// ## Full Version String
9919// A main version, followed optionally by a pre-release version and
9920// build metadata.
9921
9922// Note that the only major, minor, patch, and pre-release sections of
9923// the version string are capturing groups. The build metadata is not a
9924// capturing group, because it should not ever be used in version
9925// comparison.
9926
9927tok('FULL');
9928tok('FULLPLAIN');
9929src[t.FULLPLAIN] = 'v?' + src[t.MAINVERSION] +
9930 src[t.PRERELEASE] + '?' +
9931 src[t.BUILD] + '?';
9932
9933src[t.FULL] = '^' + src[t.FULLPLAIN] + '$';
9934
9935// like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
9936// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
9937// common in the npm registry.
9938tok('LOOSEPLAIN');
9939src[t.LOOSEPLAIN] = '[v=\\s]*' + src[t.MAINVERSIONLOOSE] +
9940 src[t.PRERELEASELOOSE] + '?' +
9941 src[t.BUILD] + '?';
9942
9943tok('LOOSE');
9944src[t.LOOSE] = '^' + src[t.LOOSEPLAIN] + '$';
9945
9946tok('GTLT');
9947src[t.GTLT] = '((?:<|>)?=?)';
9948
9949// Something like "2.*" or "1.2.x".
9950// Note that "x.x" is a valid xRange identifer, meaning "any version"
9951// Only the first item is strictly required.
9952tok('XRANGEIDENTIFIERLOOSE');
9953src[t.XRANGEIDENTIFIERLOOSE] = src[t.NUMERICIDENTIFIERLOOSE] + '|x|X|\\*';
9954tok('XRANGEIDENTIFIER');
9955src[t.XRANGEIDENTIFIER] = src[t.NUMERICIDENTIFIER] + '|x|X|\\*';
9956
9957tok('XRANGEPLAIN');
9958src[t.XRANGEPLAIN] = '[v=\\s]*(' + src[t.XRANGEIDENTIFIER] + ')' +
9959 '(?:\\.(' + src[t.XRANGEIDENTIFIER] + ')' +
9960 '(?:\\.(' + src[t.XRANGEIDENTIFIER] + ')' +
9961 '(?:' + src[t.PRERELEASE] + ')?' +
9962 src[t.BUILD] + '?' +
9963 ')?)?';
9964
9965tok('XRANGEPLAINLOOSE');
9966src[t.XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' +
9967 '(?:\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' +
9968 '(?:\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' +
9969 '(?:' + src[t.PRERELEASELOOSE] + ')?' +
9970 src[t.BUILD] + '?' +
9971 ')?)?';
9972
9973tok('XRANGE');
9974src[t.XRANGE] = '^' + src[t.GTLT] + '\\s*' + src[t.XRANGEPLAIN] + '$';
9975tok('XRANGELOOSE');
9976src[t.XRANGELOOSE] = '^' + src[t.GTLT] + '\\s*' + src[t.XRANGEPLAINLOOSE] + '$';
9977
9978// Coercion.
9979// Extract anything that could conceivably be a part of a valid semver
9980tok('COERCE');
9981src[t.COERCE] = '(^|[^\\d])' +
9982 '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' +
9983 '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' +
9984 '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' +
9985 '(?:$|[^\\d])';
9986tok('COERCERTL');
9987re[t.COERCERTL] = new RegExp(src[t.COERCE], 'g');
9988
9989// Tilde ranges.
9990// Meaning is "reasonably at or greater than"
9991tok('LONETILDE');
9992src[t.LONETILDE] = '(?:~>?)';
9993
9994tok('TILDETRIM');
9995src[t.TILDETRIM] = '(\\s*)' + src[t.LONETILDE] + '\\s+';
9996re[t.TILDETRIM] = new RegExp(src[t.TILDETRIM], 'g');
9997var tildeTrimReplace = '$1~';
9998
9999tok('TILDE');
10000src[t.TILDE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAIN] + '$';
10001tok('TILDELOOSE');
10002src[t.TILDELOOSE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAINLOOSE] + '$';
10003
10004// Caret ranges.
10005// Meaning is "at least and backwards compatible with"
10006tok('LONECARET');
10007src[t.LONECARET] = '(?:\\^)';
10008
10009tok('CARETTRIM');
10010src[t.CARETTRIM] = '(\\s*)' + src[t.LONECARET] + '\\s+';
10011re[t.CARETTRIM] = new RegExp(src[t.CARETTRIM], 'g');
10012var caretTrimReplace = '$1^';
10013
10014tok('CARET');
10015src[t.CARET] = '^' + src[t.LONECARET] + src[t.XRANGEPLAIN] + '$';
10016tok('CARETLOOSE');
10017src[t.CARETLOOSE] = '^' + src[t.LONECARET] + src[t.XRANGEPLAINLOOSE] + '$';
10018
10019// A simple gt/lt/eq thing, or just "" to indicate "any version"
10020tok('COMPARATORLOOSE');
10021src[t.COMPARATORLOOSE] = '^' + src[t.GTLT] + '\\s*(' + src[t.LOOSEPLAIN] + ')$|^$';
10022tok('COMPARATOR');
10023src[t.COMPARATOR] = '^' + src[t.GTLT] + '\\s*(' + src[t.FULLPLAIN] + ')$|^$';
10024
10025// An expression to strip any whitespace between the gtlt and the thing
10026// it modifies, so that `> 1.2.3` ==> `>1.2.3`
10027tok('COMPARATORTRIM');
10028src[t.COMPARATORTRIM] = '(\\s*)' + src[t.GTLT] +
10029 '\\s*(' + src[t.LOOSEPLAIN] + '|' + src[t.XRANGEPLAIN] + ')';
10030
10031// this one has to use the /g flag
10032re[t.COMPARATORTRIM] = new RegExp(src[t.COMPARATORTRIM], 'g');
10033var comparatorTrimReplace = '$1$2$3';
10034
10035// Something like `1.2.3 - 1.2.4`
10036// Note that these all use the loose form, because they'll be
10037// checked against either the strict or loose comparator form
10038// later.
10039tok('HYPHENRANGE');
10040src[t.HYPHENRANGE] = '^\\s*(' + src[t.XRANGEPLAIN] + ')' +
10041 '\\s+-\\s+' +
10042 '(' + src[t.XRANGEPLAIN] + ')' +
10043 '\\s*$';
10044
10045tok('HYPHENRANGELOOSE');
10046src[t.HYPHENRANGELOOSE] = '^\\s*(' + src[t.XRANGEPLAINLOOSE] + ')' +
10047 '\\s+-\\s+' +
10048 '(' + src[t.XRANGEPLAINLOOSE] + ')' +
10049 '\\s*$';
10050
10051// Star ranges basically just allow anything at all.
10052tok('STAR');
10053src[t.STAR] = '(<|>)?=?\\s*\\*';
10054
10055// Compile to actual regexp objects.
10056// All are flag-free, unless they were created above with a flag.
10057for (var i = 0; i < R; i++) {
10058 debug(i, src[i]);
10059 if (!re[i]) {
10060 re[i] = new RegExp(src[i]);
10061 }
10062}
10063
10064exports.parse = parse;
10065function parse (version, options) {
10066 if (!options || typeof options !== 'object') {
10067 options = {
10068 loose: !!options,
10069 includePrerelease: false
10070 };
10071 }
10072
10073 if (version instanceof SemVer) {
10074 return version
10075 }
10076
10077 if (typeof version !== 'string') {
10078 return null
10079 }
10080
10081 if (version.length > MAX_LENGTH) {
10082 return null
10083 }
10084
10085 var r = options.loose ? re[t.LOOSE] : re[t.FULL];
10086 if (!r.test(version)) {
10087 return null
10088 }
10089
10090 try {
10091 return new SemVer(version, options)
10092 } catch (er) {
10093 return null
10094 }
10095}
10096
10097exports.valid = valid;
10098function valid (version, options) {
10099 var v = parse(version, options);
10100 return v ? v.version : null
10101}
10102
10103exports.clean = clean;
10104function clean (version, options) {
10105 var s = parse(version.trim().replace(/^[=v]+/, ''), options);
10106 return s ? s.version : null
10107}
10108
10109exports.SemVer = SemVer;
10110
10111function SemVer (version, options) {
10112 if (!options || typeof options !== 'object') {
10113 options = {
10114 loose: !!options,
10115 includePrerelease: false
10116 };
10117 }
10118 if (version instanceof SemVer) {
10119 if (version.loose === options.loose) {
10120 return version
10121 } else {
10122 version = version.version;
10123 }
10124 } else if (typeof version !== 'string') {
10125 throw new TypeError('Invalid Version: ' + version)
10126 }
10127
10128 if (version.length > MAX_LENGTH) {
10129 throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters')
10130 }
10131
10132 if (!(this instanceof SemVer)) {
10133 return new SemVer(version, options)
10134 }
10135
10136 debug('SemVer', version, options);
10137 this.options = options;
10138 this.loose = !!options.loose;
10139
10140 var m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]);
10141
10142 if (!m) {
10143 throw new TypeError('Invalid Version: ' + version)
10144 }
10145
10146 this.raw = version;
10147
10148 // these are actually numbers
10149 this.major = +m[1];
10150 this.minor = +m[2];
10151 this.patch = +m[3];
10152
10153 if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
10154 throw new TypeError('Invalid major version')
10155 }
10156
10157 if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
10158 throw new TypeError('Invalid minor version')
10159 }
10160
10161 if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
10162 throw new TypeError('Invalid patch version')
10163 }
10164
10165 // numberify any prerelease numeric ids
10166 if (!m[4]) {
10167 this.prerelease = [];
10168 } else {
10169 this.prerelease = m[4].split('.').map(function (id) {
10170 if (/^[0-9]+$/.test(id)) {
10171 var num = +id;
10172 if (num >= 0 && num < MAX_SAFE_INTEGER) {
10173 return num
10174 }
10175 }
10176 return id
10177 });
10178 }
10179
10180 this.build = m[5] ? m[5].split('.') : [];
10181 this.format();
10182}
10183
10184SemVer.prototype.format = function () {
10185 this.version = this.major + '.' + this.minor + '.' + this.patch;
10186 if (this.prerelease.length) {
10187 this.version += '-' + this.prerelease.join('.');
10188 }
10189 return this.version
10190};
10191
10192SemVer.prototype.toString = function () {
10193 return this.version
10194};
10195
10196SemVer.prototype.compare = function (other) {
10197 debug('SemVer.compare', this.version, this.options, other);
10198 if (!(other instanceof SemVer)) {
10199 other = new SemVer(other, this.options);
10200 }
10201
10202 return this.compareMain(other) || this.comparePre(other)
10203};
10204
10205SemVer.prototype.compareMain = function (other) {
10206 if (!(other instanceof SemVer)) {
10207 other = new SemVer(other, this.options);
10208 }
10209
10210 return compareIdentifiers(this.major, other.major) ||
10211 compareIdentifiers(this.minor, other.minor) ||
10212 compareIdentifiers(this.patch, other.patch)
10213};
10214
10215SemVer.prototype.comparePre = function (other) {
10216 if (!(other instanceof SemVer)) {
10217 other = new SemVer(other, this.options);
10218 }
10219
10220 // NOT having a prerelease is > having one
10221 if (this.prerelease.length && !other.prerelease.length) {
10222 return -1
10223 } else if (!this.prerelease.length && other.prerelease.length) {
10224 return 1
10225 } else if (!this.prerelease.length && !other.prerelease.length) {
10226 return 0
10227 }
10228
10229 var i = 0;
10230 do {
10231 var a = this.prerelease[i];
10232 var b = other.prerelease[i];
10233 debug('prerelease compare', i, a, b);
10234 if (a === undefined && b === undefined) {
10235 return 0
10236 } else if (b === undefined) {
10237 return 1
10238 } else if (a === undefined) {
10239 return -1
10240 } else if (a === b) {
10241 continue
10242 } else {
10243 return compareIdentifiers(a, b)
10244 }
10245 } while (++i)
10246};
10247
10248SemVer.prototype.compareBuild = function (other) {
10249 if (!(other instanceof SemVer)) {
10250 other = new SemVer(other, this.options);
10251 }
10252
10253 var i = 0;
10254 do {
10255 var a = this.build[i];
10256 var b = other.build[i];
10257 debug('prerelease compare', i, a, b);
10258 if (a === undefined && b === undefined) {
10259 return 0
10260 } else if (b === undefined) {
10261 return 1
10262 } else if (a === undefined) {
10263 return -1
10264 } else if (a === b) {
10265 continue
10266 } else {
10267 return compareIdentifiers(a, b)
10268 }
10269 } while (++i)
10270};
10271
10272// preminor will bump the version up to the next minor release, and immediately
10273// down to pre-release. premajor and prepatch work the same way.
10274SemVer.prototype.inc = function (release, identifier) {
10275 switch (release) {
10276 case 'premajor':
10277 this.prerelease.length = 0;
10278 this.patch = 0;
10279 this.minor = 0;
10280 this.major++;
10281 this.inc('pre', identifier);
10282 break
10283 case 'preminor':
10284 this.prerelease.length = 0;
10285 this.patch = 0;
10286 this.minor++;
10287 this.inc('pre', identifier);
10288 break
10289 case 'prepatch':
10290 // If this is already a prerelease, it will bump to the next version
10291 // drop any prereleases that might already exist, since they are not
10292 // relevant at this point.
10293 this.prerelease.length = 0;
10294 this.inc('patch', identifier);
10295 this.inc('pre', identifier);
10296 break
10297 // If the input is a non-prerelease version, this acts the same as
10298 // prepatch.
10299 case 'prerelease':
10300 if (this.prerelease.length === 0) {
10301 this.inc('patch', identifier);
10302 }
10303 this.inc('pre', identifier);
10304 break
10305
10306 case 'major':
10307 // If this is a pre-major version, bump up to the same major version.
10308 // Otherwise increment major.
10309 // 1.0.0-5 bumps to 1.0.0
10310 // 1.1.0 bumps to 2.0.0
10311 if (this.minor !== 0 ||
10312 this.patch !== 0 ||
10313 this.prerelease.length === 0) {
10314 this.major++;
10315 }
10316 this.minor = 0;
10317 this.patch = 0;
10318 this.prerelease = [];
10319 break
10320 case 'minor':
10321 // If this is a pre-minor version, bump up to the same minor version.
10322 // Otherwise increment minor.
10323 // 1.2.0-5 bumps to 1.2.0
10324 // 1.2.1 bumps to 1.3.0
10325 if (this.patch !== 0 || this.prerelease.length === 0) {
10326 this.minor++;
10327 }
10328 this.patch = 0;
10329 this.prerelease = [];
10330 break
10331 case 'patch':
10332 // If this is not a pre-release version, it will increment the patch.
10333 // If it is a pre-release it will bump up to the same patch version.
10334 // 1.2.0-5 patches to 1.2.0
10335 // 1.2.0 patches to 1.2.1
10336 if (this.prerelease.length === 0) {
10337 this.patch++;
10338 }
10339 this.prerelease = [];
10340 break
10341 // This probably shouldn't be used publicly.
10342 // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction.
10343 case 'pre':
10344 if (this.prerelease.length === 0) {
10345 this.prerelease = [0];
10346 } else {
10347 var i = this.prerelease.length;
10348 while (--i >= 0) {
10349 if (typeof this.prerelease[i] === 'number') {
10350 this.prerelease[i]++;
10351 i = -2;
10352 }
10353 }
10354 if (i === -1) {
10355 // didn't increment anything
10356 this.prerelease.push(0);
10357 }
10358 }
10359 if (identifier) {
10360 // 1.2.0-beta.1 bumps to 1.2.0-beta.2,
10361 // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
10362 if (this.prerelease[0] === identifier) {
10363 if (isNaN(this.prerelease[1])) {
10364 this.prerelease = [identifier, 0];
10365 }
10366 } else {
10367 this.prerelease = [identifier, 0];
10368 }
10369 }
10370 break
10371
10372 default:
10373 throw new Error('invalid increment argument: ' + release)
10374 }
10375 this.format();
10376 this.raw = this.version;
10377 return this
10378};
10379
10380exports.inc = inc;
10381function inc (version, release, loose, identifier) {
10382 if (typeof (loose) === 'string') {
10383 identifier = loose;
10384 loose = undefined;
10385 }
10386
10387 try {
10388 return new SemVer(version, loose).inc(release, identifier).version
10389 } catch (er) {
10390 return null
10391 }
10392}
10393
10394exports.diff = diff;
10395function diff (version1, version2) {
10396 if (eq(version1, version2)) {
10397 return null
10398 } else {
10399 var v1 = parse(version1);
10400 var v2 = parse(version2);
10401 var prefix = '';
10402 if (v1.prerelease.length || v2.prerelease.length) {
10403 prefix = 'pre';
10404 var defaultResult = 'prerelease';
10405 }
10406 for (var key in v1) {
10407 if (key === 'major' || key === 'minor' || key === 'patch') {
10408 if (v1[key] !== v2[key]) {
10409 return prefix + key
10410 }
10411 }
10412 }
10413 return defaultResult // may be undefined
10414 }
10415}
10416
10417exports.compareIdentifiers = compareIdentifiers;
10418
10419var numeric = /^[0-9]+$/;
10420function compareIdentifiers (a, b) {
10421 var anum = numeric.test(a);
10422 var bnum = numeric.test(b);
10423
10424 if (anum && bnum) {
10425 a = +a;
10426 b = +b;
10427 }
10428
10429 return a === b ? 0
10430 : (anum && !bnum) ? -1
10431 : (bnum && !anum) ? 1
10432 : a < b ? -1
10433 : 1
10434}
10435
10436exports.rcompareIdentifiers = rcompareIdentifiers;
10437function rcompareIdentifiers (a, b) {
10438 return compareIdentifiers(b, a)
10439}
10440
10441exports.major = major;
10442function major (a, loose) {
10443 return new SemVer(a, loose).major
10444}
10445
10446exports.minor = minor;
10447function minor (a, loose) {
10448 return new SemVer(a, loose).minor
10449}
10450
10451exports.patch = patch;
10452function patch (a, loose) {
10453 return new SemVer(a, loose).patch
10454}
10455
10456exports.compare = compare;
10457function compare (a, b, loose) {
10458 return new SemVer(a, loose).compare(new SemVer(b, loose))
10459}
10460
10461exports.compareLoose = compareLoose;
10462function compareLoose (a, b) {
10463 return compare(a, b, true)
10464}
10465
10466exports.compareBuild = compareBuild;
10467function compareBuild (a, b, loose) {
10468 var versionA = new SemVer(a, loose);
10469 var versionB = new SemVer(b, loose);
10470 return versionA.compare(versionB) || versionA.compareBuild(versionB)
10471}
10472
10473exports.rcompare = rcompare;
10474function rcompare (a, b, loose) {
10475 return compare(b, a, loose)
10476}
10477
10478exports.sort = sort;
10479function sort (list, loose) {
10480 return list.sort(function (a, b) {
10481 return exports.compareBuild(a, b, loose)
10482 })
10483}
10484
10485exports.rsort = rsort;
10486function rsort (list, loose) {
10487 return list.sort(function (a, b) {
10488 return exports.compareBuild(b, a, loose)
10489 })
10490}
10491
10492exports.gt = gt;
10493function gt (a, b, loose) {
10494 return compare(a, b, loose) > 0
10495}
10496
10497exports.lt = lt;
10498function lt (a, b, loose) {
10499 return compare(a, b, loose) < 0
10500}
10501
10502exports.eq = eq;
10503function eq (a, b, loose) {
10504 return compare(a, b, loose) === 0
10505}
10506
10507exports.neq = neq;
10508function neq (a, b, loose) {
10509 return compare(a, b, loose) !== 0
10510}
10511
10512exports.gte = gte;
10513function gte (a, b, loose) {
10514 return compare(a, b, loose) >= 0
10515}
10516
10517exports.lte = lte;
10518function lte (a, b, loose) {
10519 return compare(a, b, loose) <= 0
10520}
10521
10522exports.cmp = cmp;
10523function cmp (a, op, b, loose) {
10524 switch (op) {
10525 case '===':
10526 if (typeof a === 'object')
10527 a = a.version;
10528 if (typeof b === 'object')
10529 b = b.version;
10530 return a === b
10531
10532 case '!==':
10533 if (typeof a === 'object')
10534 a = a.version;
10535 if (typeof b === 'object')
10536 b = b.version;
10537 return a !== b
10538
10539 case '':
10540 case '=':
10541 case '==':
10542 return eq(a, b, loose)
10543
10544 case '!=':
10545 return neq(a, b, loose)
10546
10547 case '>':
10548 return gt(a, b, loose)
10549
10550 case '>=':
10551 return gte(a, b, loose)
10552
10553 case '<':
10554 return lt(a, b, loose)
10555
10556 case '<=':
10557 return lte(a, b, loose)
10558
10559 default:
10560 throw new TypeError('Invalid operator: ' + op)
10561 }
10562}
10563
10564exports.Comparator = Comparator;
10565function Comparator (comp, options) {
10566 if (!options || typeof options !== 'object') {
10567 options = {
10568 loose: !!options,
10569 includePrerelease: false
10570 };
10571 }
10572
10573 if (comp instanceof Comparator) {
10574 if (comp.loose === !!options.loose) {
10575 return comp
10576 } else {
10577 comp = comp.value;
10578 }
10579 }
10580
10581 if (!(this instanceof Comparator)) {
10582 return new Comparator(comp, options)
10583 }
10584
10585 debug('comparator', comp, options);
10586 this.options = options;
10587 this.loose = !!options.loose;
10588 this.parse(comp);
10589
10590 if (this.semver === ANY) {
10591 this.value = '';
10592 } else {
10593 this.value = this.operator + this.semver.version;
10594 }
10595
10596 debug('comp', this);
10597}
10598
10599var ANY = {};
10600Comparator.prototype.parse = function (comp) {
10601 var r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR];
10602 var m = comp.match(r);
10603
10604 if (!m) {
10605 throw new TypeError('Invalid comparator: ' + comp)
10606 }
10607
10608 this.operator = m[1] !== undefined ? m[1] : '';
10609 if (this.operator === '=') {
10610 this.operator = '';
10611 }
10612
10613 // if it literally is just '>' or '' then allow anything.
10614 if (!m[2]) {
10615 this.semver = ANY;
10616 } else {
10617 this.semver = new SemVer(m[2], this.options.loose);
10618 }
10619};
10620
10621Comparator.prototype.toString = function () {
10622 return this.value
10623};
10624
10625Comparator.prototype.test = function (version) {
10626 debug('Comparator.test', version, this.options.loose);
10627
10628 if (this.semver === ANY || version === ANY) {
10629 return true
10630 }
10631
10632 if (typeof version === 'string') {
10633 try {
10634 version = new SemVer(version, this.options);
10635 } catch (er) {
10636 return false
10637 }
10638 }
10639
10640 return cmp(version, this.operator, this.semver, this.options)
10641};
10642
10643Comparator.prototype.intersects = function (comp, options) {
10644 if (!(comp instanceof Comparator)) {
10645 throw new TypeError('a Comparator is required')
10646 }
10647
10648 if (!options || typeof options !== 'object') {
10649 options = {
10650 loose: !!options,
10651 includePrerelease: false
10652 };
10653 }
10654
10655 var rangeTmp;
10656
10657 if (this.operator === '') {
10658 if (this.value === '') {
10659 return true
10660 }
10661 rangeTmp = new Range(comp.value, options);
10662 return satisfies(this.value, rangeTmp, options)
10663 } else if (comp.operator === '') {
10664 if (comp.value === '') {
10665 return true
10666 }
10667 rangeTmp = new Range(this.value, options);
10668 return satisfies(comp.semver, rangeTmp, options)
10669 }
10670
10671 var sameDirectionIncreasing =
10672 (this.operator === '>=' || this.operator === '>') &&
10673 (comp.operator === '>=' || comp.operator === '>');
10674 var sameDirectionDecreasing =
10675 (this.operator === '<=' || this.operator === '<') &&
10676 (comp.operator === '<=' || comp.operator === '<');
10677 var sameSemVer = this.semver.version === comp.semver.version;
10678 var differentDirectionsInclusive =
10679 (this.operator === '>=' || this.operator === '<=') &&
10680 (comp.operator === '>=' || comp.operator === '<=');
10681 var oppositeDirectionsLessThan =
10682 cmp(this.semver, '<', comp.semver, options) &&
10683 ((this.operator === '>=' || this.operator === '>') &&
10684 (comp.operator === '<=' || comp.operator === '<'));
10685 var oppositeDirectionsGreaterThan =
10686 cmp(this.semver, '>', comp.semver, options) &&
10687 ((this.operator === '<=' || this.operator === '<') &&
10688 (comp.operator === '>=' || comp.operator === '>'));
10689
10690 return sameDirectionIncreasing || sameDirectionDecreasing ||
10691 (sameSemVer && differentDirectionsInclusive) ||
10692 oppositeDirectionsLessThan || oppositeDirectionsGreaterThan
10693};
10694
10695exports.Range = Range;
10696function Range (range, options) {
10697 if (!options || typeof options !== 'object') {
10698 options = {
10699 loose: !!options,
10700 includePrerelease: false
10701 };
10702 }
10703
10704 if (range instanceof Range) {
10705 if (range.loose === !!options.loose &&
10706 range.includePrerelease === !!options.includePrerelease) {
10707 return range
10708 } else {
10709 return new Range(range.raw, options)
10710 }
10711 }
10712
10713 if (range instanceof Comparator) {
10714 return new Range(range.value, options)
10715 }
10716
10717 if (!(this instanceof Range)) {
10718 return new Range(range, options)
10719 }
10720
10721 this.options = options;
10722 this.loose = !!options.loose;
10723 this.includePrerelease = !!options.includePrerelease;
10724
10725 // First, split based on boolean or ||
10726 this.raw = range;
10727 this.set = range.split(/\s*\|\|\s*/).map(function (range) {
10728 return this.parseRange(range.trim())
10729 }, this).filter(function (c) {
10730 // throw out any that are not relevant for whatever reason
10731 return c.length
10732 });
10733
10734 if (!this.set.length) {
10735 throw new TypeError('Invalid SemVer Range: ' + range)
10736 }
10737
10738 this.format();
10739}
10740
10741Range.prototype.format = function () {
10742 this.range = this.set.map(function (comps) {
10743 return comps.join(' ').trim()
10744 }).join('||').trim();
10745 return this.range
10746};
10747
10748Range.prototype.toString = function () {
10749 return this.range
10750};
10751
10752Range.prototype.parseRange = function (range) {
10753 var loose = this.options.loose;
10754 range = range.trim();
10755 // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
10756 var hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE];
10757 range = range.replace(hr, hyphenReplace);
10758 debug('hyphen replace', range);
10759 // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`
10760 range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace);
10761 debug('comparator trim', range, re[t.COMPARATORTRIM]);
10762
10763 // `~ 1.2.3` => `~1.2.3`
10764 range = range.replace(re[t.TILDETRIM], tildeTrimReplace);
10765
10766 // `^ 1.2.3` => `^1.2.3`
10767 range = range.replace(re[t.CARETTRIM], caretTrimReplace);
10768
10769 // normalize spaces
10770 range = range.split(/\s+/).join(' ');
10771
10772 // At this point, the range is completely trimmed and
10773 // ready to be split into comparators.
10774
10775 var compRe = loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR];
10776 var set = range.split(' ').map(function (comp) {
10777 return parseComparator(comp, this.options)
10778 }, this).join(' ').split(/\s+/);
10779 if (this.options.loose) {
10780 // in loose mode, throw out any that are not valid comparators
10781 set = set.filter(function (comp) {
10782 return !!comp.match(compRe)
10783 });
10784 }
10785 set = set.map(function (comp) {
10786 return new Comparator(comp, this.options)
10787 }, this);
10788
10789 return set
10790};
10791
10792Range.prototype.intersects = function (range, options) {
10793 if (!(range instanceof Range)) {
10794 throw new TypeError('a Range is required')
10795 }
10796
10797 return this.set.some(function (thisComparators) {
10798 return (
10799 isSatisfiable(thisComparators, options) &&
10800 range.set.some(function (rangeComparators) {
10801 return (
10802 isSatisfiable(rangeComparators, options) &&
10803 thisComparators.every(function (thisComparator) {
10804 return rangeComparators.every(function (rangeComparator) {
10805 return thisComparator.intersects(rangeComparator, options)
10806 })
10807 })
10808 )
10809 })
10810 )
10811 })
10812};
10813
10814// take a set of comparators and determine whether there
10815// exists a version which can satisfy it
10816function isSatisfiable (comparators, options) {
10817 var result = true;
10818 var remainingComparators = comparators.slice();
10819 var testComparator = remainingComparators.pop();
10820
10821 while (result && remainingComparators.length) {
10822 result = remainingComparators.every(function (otherComparator) {
10823 return testComparator.intersects(otherComparator, options)
10824 });
10825
10826 testComparator = remainingComparators.pop();
10827 }
10828
10829 return result
10830}
10831
10832// Mostly just for testing and legacy API reasons
10833exports.toComparators = toComparators;
10834function toComparators (range, options) {
10835 return new Range(range, options).set.map(function (comp) {
10836 return comp.map(function (c) {
10837 return c.value
10838 }).join(' ').trim().split(' ')
10839 })
10840}
10841
10842// comprised of xranges, tildes, stars, and gtlt's at this point.
10843// already replaced the hyphen ranges
10844// turn into a set of JUST comparators.
10845function parseComparator (comp, options) {
10846 debug('comp', comp, options);
10847 comp = replaceCarets(comp, options);
10848 debug('caret', comp);
10849 comp = replaceTildes(comp, options);
10850 debug('tildes', comp);
10851 comp = replaceXRanges(comp, options);
10852 debug('xrange', comp);
10853 comp = replaceStars(comp, options);
10854 debug('stars', comp);
10855 return comp
10856}
10857
10858function isX (id) {
10859 return !id || id.toLowerCase() === 'x' || id === '*'
10860}
10861
10862// ~, ~> --> * (any, kinda silly)
10863// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0
10864// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0
10865// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0
10866// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0
10867// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0
10868function replaceTildes (comp, options) {
10869 return comp.trim().split(/\s+/).map(function (comp) {
10870 return replaceTilde(comp, options)
10871 }).join(' ')
10872}
10873
10874function replaceTilde (comp, options) {
10875 var r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE];
10876 return comp.replace(r, function (_, M, m, p, pr) {
10877 debug('tilde', comp, _, M, m, p, pr);
10878 var ret;
10879
10880 if (isX(M)) {
10881 ret = '';
10882 } else if (isX(m)) {
10883 ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';
10884 } else if (isX(p)) {
10885 // ~1.2 == >=1.2.0 <1.3.0
10886 ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';
10887 } else if (pr) {
10888 debug('replaceTilde pr', pr);
10889 ret = '>=' + M + '.' + m + '.' + p + '-' + pr +
10890 ' <' + M + '.' + (+m + 1) + '.0';
10891 } else {
10892 // ~1.2.3 == >=1.2.3 <1.3.0
10893 ret = '>=' + M + '.' + m + '.' + p +
10894 ' <' + M + '.' + (+m + 1) + '.0';
10895 }
10896
10897 debug('tilde return', ret);
10898 return ret
10899 })
10900}
10901
10902// ^ --> * (any, kinda silly)
10903// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0
10904// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0
10905// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0
10906// ^1.2.3 --> >=1.2.3 <2.0.0
10907// ^1.2.0 --> >=1.2.0 <2.0.0
10908function replaceCarets (comp, options) {
10909 return comp.trim().split(/\s+/).map(function (comp) {
10910 return replaceCaret(comp, options)
10911 }).join(' ')
10912}
10913
10914function replaceCaret (comp, options) {
10915 debug('caret', comp, options);
10916 var r = options.loose ? re[t.CARETLOOSE] : re[t.CARET];
10917 return comp.replace(r, function (_, M, m, p, pr) {
10918 debug('caret', comp, _, M, m, p, pr);
10919 var ret;
10920
10921 if (isX(M)) {
10922 ret = '';
10923 } else if (isX(m)) {
10924 ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';
10925 } else if (isX(p)) {
10926 if (M === '0') {
10927 ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';
10928 } else {
10929 ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0';
10930 }
10931 } else if (pr) {
10932 debug('replaceCaret pr', pr);
10933 if (M === '0') {
10934 if (m === '0') {
10935 ret = '>=' + M + '.' + m + '.' + p + '-' + pr +
10936 ' <' + M + '.' + m + '.' + (+p + 1);
10937 } else {
10938 ret = '>=' + M + '.' + m + '.' + p + '-' + pr +
10939 ' <' + M + '.' + (+m + 1) + '.0';
10940 }
10941 } else {
10942 ret = '>=' + M + '.' + m + '.' + p + '-' + pr +
10943 ' <' + (+M + 1) + '.0.0';
10944 }
10945 } else {
10946 debug('no pr');
10947 if (M === '0') {
10948 if (m === '0') {
10949 ret = '>=' + M + '.' + m + '.' + p +
10950 ' <' + M + '.' + m + '.' + (+p + 1);
10951 } else {
10952 ret = '>=' + M + '.' + m + '.' + p +
10953 ' <' + M + '.' + (+m + 1) + '.0';
10954 }
10955 } else {
10956 ret = '>=' + M + '.' + m + '.' + p +
10957 ' <' + (+M + 1) + '.0.0';
10958 }
10959 }
10960
10961 debug('caret return', ret);
10962 return ret
10963 })
10964}
10965
10966function replaceXRanges (comp, options) {
10967 debug('replaceXRanges', comp, options);
10968 return comp.split(/\s+/).map(function (comp) {
10969 return replaceXRange(comp, options)
10970 }).join(' ')
10971}
10972
10973function replaceXRange (comp, options) {
10974 comp = comp.trim();
10975 var r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE];
10976 return comp.replace(r, function (ret, gtlt, M, m, p, pr) {
10977 debug('xRange', comp, ret, gtlt, M, m, p, pr);
10978 var xM = isX(M);
10979 var xm = xM || isX(m);
10980 var xp = xm || isX(p);
10981 var anyX = xp;
10982
10983 if (gtlt === '=' && anyX) {
10984 gtlt = '';
10985 }
10986
10987 // if we're including prereleases in the match, then we need
10988 // to fix this to -0, the lowest possible prerelease value
10989 pr = options.includePrerelease ? '-0' : '';
10990
10991 if (xM) {
10992 if (gtlt === '>' || gtlt === '<') {
10993 // nothing is allowed
10994 ret = '<0.0.0-0';
10995 } else {
10996 // nothing is forbidden
10997 ret = '*';
10998 }
10999 } else if (gtlt && anyX) {
11000 // we know patch is an x, because we have any x at all.
11001 // replace X with 0
11002 if (xm) {
11003 m = 0;
11004 }
11005 p = 0;
11006
11007 if (gtlt === '>') {
11008 // >1 => >=2.0.0
11009 // >1.2 => >=1.3.0
11010 // >1.2.3 => >= 1.2.4
11011 gtlt = '>=';
11012 if (xm) {
11013 M = +M + 1;
11014 m = 0;
11015 p = 0;
11016 } else {
11017 m = +m + 1;
11018 p = 0;
11019 }
11020 } else if (gtlt === '<=') {
11021 // <=0.7.x is actually <0.8.0, since any 0.7.x should
11022 // pass. Similarly, <=7.x is actually <8.0.0, etc.
11023 gtlt = '<';
11024 if (xm) {
11025 M = +M + 1;
11026 } else {
11027 m = +m + 1;
11028 }
11029 }
11030
11031 ret = gtlt + M + '.' + m + '.' + p + pr;
11032 } else if (xm) {
11033 ret = '>=' + M + '.0.0' + pr + ' <' + (+M + 1) + '.0.0' + pr;
11034 } else if (xp) {
11035 ret = '>=' + M + '.' + m + '.0' + pr +
11036 ' <' + M + '.' + (+m + 1) + '.0' + pr;
11037 }
11038
11039 debug('xRange return', ret);
11040
11041 return ret
11042 })
11043}
11044
11045// Because * is AND-ed with everything else in the comparator,
11046// and '' means "any version", just remove the *s entirely.
11047function replaceStars (comp, options) {
11048 debug('replaceStars', comp, options);
11049 // Looseness is ignored here. star is always as loose as it gets!
11050 return comp.trim().replace(re[t.STAR], '')
11051}
11052
11053// This function is passed to string.replace(re[t.HYPHENRANGE])
11054// M, m, patch, prerelease, build
11055// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5
11056// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do
11057// 1.2 - 3.4 => >=1.2.0 <3.5.0
11058function hyphenReplace ($0,
11059 from, fM, fm, fp, fpr, fb,
11060 to, tM, tm, tp, tpr, tb) {
11061 if (isX(fM)) {
11062 from = '';
11063 } else if (isX(fm)) {
11064 from = '>=' + fM + '.0.0';
11065 } else if (isX(fp)) {
11066 from = '>=' + fM + '.' + fm + '.0';
11067 } else {
11068 from = '>=' + from;
11069 }
11070
11071 if (isX(tM)) {
11072 to = '';
11073 } else if (isX(tm)) {
11074 to = '<' + (+tM + 1) + '.0.0';
11075 } else if (isX(tp)) {
11076 to = '<' + tM + '.' + (+tm + 1) + '.0';
11077 } else if (tpr) {
11078 to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr;
11079 } else {
11080 to = '<=' + to;
11081 }
11082
11083 return (from + ' ' + to).trim()
11084}
11085
11086// if ANY of the sets match ALL of its comparators, then pass
11087Range.prototype.test = function (version) {
11088 if (!version) {
11089 return false
11090 }
11091
11092 if (typeof version === 'string') {
11093 try {
11094 version = new SemVer(version, this.options);
11095 } catch (er) {
11096 return false
11097 }
11098 }
11099
11100 for (var i = 0; i < this.set.length; i++) {
11101 if (testSet(this.set[i], version, this.options)) {
11102 return true
11103 }
11104 }
11105 return false
11106};
11107
11108function testSet (set, version, options) {
11109 for (var i = 0; i < set.length; i++) {
11110 if (!set[i].test(version)) {
11111 return false
11112 }
11113 }
11114
11115 if (version.prerelease.length && !options.includePrerelease) {
11116 // Find the set of versions that are allowed to have prereleases
11117 // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0
11118 // That should allow `1.2.3-pr.2` to pass.
11119 // However, `1.2.4-alpha.notready` should NOT be allowed,
11120 // even though it's within the range set by the comparators.
11121 for (i = 0; i < set.length; i++) {
11122 debug(set[i].semver);
11123 if (set[i].semver === ANY) {
11124 continue
11125 }
11126
11127 if (set[i].semver.prerelease.length > 0) {
11128 var allowed = set[i].semver;
11129 if (allowed.major === version.major &&
11130 allowed.minor === version.minor &&
11131 allowed.patch === version.patch) {
11132 return true
11133 }
11134 }
11135 }
11136
11137 // Version has a -pre, but it's not one of the ones we like.
11138 return false
11139 }
11140
11141 return true
11142}
11143
11144exports.satisfies = satisfies;
11145function satisfies (version, range, options) {
11146 try {
11147 range = new Range(range, options);
11148 } catch (er) {
11149 return false
11150 }
11151 return range.test(version)
11152}
11153
11154exports.maxSatisfying = maxSatisfying;
11155function maxSatisfying (versions, range, options) {
11156 var max = null;
11157 var maxSV = null;
11158 try {
11159 var rangeObj = new Range(range, options);
11160 } catch (er) {
11161 return null
11162 }
11163 versions.forEach(function (v) {
11164 if (rangeObj.test(v)) {
11165 // satisfies(v, range, options)
11166 if (!max || maxSV.compare(v) === -1) {
11167 // compare(max, v, true)
11168 max = v;
11169 maxSV = new SemVer(max, options);
11170 }
11171 }
11172 });
11173 return max
11174}
11175
11176exports.minSatisfying = minSatisfying;
11177function minSatisfying (versions, range, options) {
11178 var min = null;
11179 var minSV = null;
11180 try {
11181 var rangeObj = new Range(range, options);
11182 } catch (er) {
11183 return null
11184 }
11185 versions.forEach(function (v) {
11186 if (rangeObj.test(v)) {
11187 // satisfies(v, range, options)
11188 if (!min || minSV.compare(v) === 1) {
11189 // compare(min, v, true)
11190 min = v;
11191 minSV = new SemVer(min, options);
11192 }
11193 }
11194 });
11195 return min
11196}
11197
11198exports.minVersion = minVersion;
11199function minVersion (range, loose) {
11200 range = new Range(range, loose);
11201
11202 var minver = new SemVer('0.0.0');
11203 if (range.test(minver)) {
11204 return minver
11205 }
11206
11207 minver = new SemVer('0.0.0-0');
11208 if (range.test(minver)) {
11209 return minver
11210 }
11211
11212 minver = null;
11213 for (var i = 0; i < range.set.length; ++i) {
11214 var comparators = range.set[i];
11215
11216 comparators.forEach(function (comparator) {
11217 // Clone to avoid manipulating the comparator's semver object.
11218 var compver = new SemVer(comparator.semver.version);
11219 switch (comparator.operator) {
11220 case '>':
11221 if (compver.prerelease.length === 0) {
11222 compver.patch++;
11223 } else {
11224 compver.prerelease.push(0);
11225 }
11226 compver.raw = compver.format();
11227 /* fallthrough */
11228 case '':
11229 case '>=':
11230 if (!minver || gt(minver, compver)) {
11231 minver = compver;
11232 }
11233 break
11234 case '<':
11235 case '<=':
11236 /* Ignore maximum versions */
11237 break
11238 /* istanbul ignore next */
11239 default:
11240 throw new Error('Unexpected operation: ' + comparator.operator)
11241 }
11242 });
11243 }
11244
11245 if (minver && range.test(minver)) {
11246 return minver
11247 }
11248
11249 return null
11250}
11251
11252exports.validRange = validRange;
11253function validRange (range, options) {
11254 try {
11255 // Return '*' instead of '' so that truthiness works.
11256 // This will throw if it's invalid anyway
11257 return new Range(range, options).range || '*'
11258 } catch (er) {
11259 return null
11260 }
11261}
11262
11263// Determine if version is less than all the versions possible in the range
11264exports.ltr = ltr;
11265function ltr (version, range, options) {
11266 return outside(version, range, '<', options)
11267}
11268
11269// Determine if version is greater than all the versions possible in the range.
11270exports.gtr = gtr;
11271function gtr (version, range, options) {
11272 return outside(version, range, '>', options)
11273}
11274
11275exports.outside = outside;
11276function outside (version, range, hilo, options) {
11277 version = new SemVer(version, options);
11278 range = new Range(range, options);
11279
11280 var gtfn, ltefn, ltfn, comp, ecomp;
11281 switch (hilo) {
11282 case '>':
11283 gtfn = gt;
11284 ltefn = lte;
11285 ltfn = lt;
11286 comp = '>';
11287 ecomp = '>=';
11288 break
11289 case '<':
11290 gtfn = lt;
11291 ltefn = gte;
11292 ltfn = gt;
11293 comp = '<';
11294 ecomp = '<=';
11295 break
11296 default:
11297 throw new TypeError('Must provide a hilo val of "<" or ">"')
11298 }
11299
11300 // If it satisifes the range it is not outside
11301 if (satisfies(version, range, options)) {
11302 return false
11303 }
11304
11305 // From now on, variable terms are as if we're in "gtr" mode.
11306 // but note that everything is flipped for the "ltr" function.
11307
11308 for (var i = 0; i < range.set.length; ++i) {
11309 var comparators = range.set[i];
11310
11311 var high = null;
11312 var low = null;
11313
11314 comparators.forEach(function (comparator) {
11315 if (comparator.semver === ANY) {
11316 comparator = new Comparator('>=0.0.0');
11317 }
11318 high = high || comparator;
11319 low = low || comparator;
11320 if (gtfn(comparator.semver, high.semver, options)) {
11321 high = comparator;
11322 } else if (ltfn(comparator.semver, low.semver, options)) {
11323 low = comparator;
11324 }
11325 });
11326
11327 // If the edge version comparator has a operator then our version
11328 // isn't outside it
11329 if (high.operator === comp || high.operator === ecomp) {
11330 return false
11331 }
11332
11333 // If the lowest version comparator has an operator and our version
11334 // is less than it then it isn't higher than the range
11335 if ((!low.operator || low.operator === comp) &&
11336 ltefn(version, low.semver)) {
11337 return false
11338 } else if (low.operator === ecomp && ltfn(version, low.semver)) {
11339 return false
11340 }
11341 }
11342 return true
11343}
11344
11345exports.prerelease = prerelease;
11346function prerelease (version, options) {
11347 var parsed = parse(version, options);
11348 return (parsed && parsed.prerelease.length) ? parsed.prerelease : null
11349}
11350
11351exports.intersects = intersects;
11352function intersects (r1, r2, options) {
11353 r1 = new Range(r1, options);
11354 r2 = new Range(r2, options);
11355 return r1.intersects(r2)
11356}
11357
11358exports.coerce = coerce;
11359function coerce (version, options) {
11360 if (version instanceof SemVer) {
11361 return version
11362 }
11363
11364 if (typeof version === 'number') {
11365 version = String(version);
11366 }
11367
11368 if (typeof version !== 'string') {
11369 return null
11370 }
11371
11372 options = options || {};
11373
11374 var match = null;
11375 if (!options.rtl) {
11376 match = version.match(re[t.COERCE]);
11377 } else {
11378 // Find the right-most coercible string that does not share
11379 // a terminus with a more left-ward coercible string.
11380 // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'
11381 //
11382 // Walk through the string checking with a /g regexp
11383 // Manually set the index so as to pick up overlapping matches.
11384 // Stop when we get a match that ends at the string end, since no
11385 // coercible string can be more right-ward without the same terminus.
11386 var next;
11387 while ((next = re[t.COERCERTL].exec(version)) &&
11388 (!match || match.index + match[0].length !== version.length)
11389 ) {
11390 if (!match ||
11391 next.index + next[0].length !== match.index + match[0].length) {
11392 match = next;
11393 }
11394 re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length;
11395 }
11396 // leave it in a clean state
11397 re[t.COERCERTL].lastIndex = -1;
11398 }
11399
11400 if (match === null) {
11401 return null
11402 }
11403
11404 return parse(match[2] +
11405 '.' + (match[3] || '0') +
11406 '.' + (match[4] || '0'), options)
11407}
11408});
11409var semver_1 = semver.SEMVER_SPEC_VERSION;
11410var semver_2 = semver.re;
11411var semver_3 = semver.src;
11412var semver_4 = semver.tokens;
11413var semver_5 = semver.parse;
11414var semver_6 = semver.valid;
11415var semver_7 = semver.clean;
11416var semver_8 = semver.SemVer;
11417var semver_9 = semver.inc;
11418var semver_10 = semver.diff;
11419var semver_11 = semver.compareIdentifiers;
11420var semver_12 = semver.rcompareIdentifiers;
11421var semver_13 = semver.major;
11422var semver_14 = semver.minor;
11423var semver_15 = semver.patch;
11424var semver_16 = semver.compare;
11425var semver_17 = semver.compareLoose;
11426var semver_18 = semver.compareBuild;
11427var semver_19 = semver.rcompare;
11428var semver_20 = semver.sort;
11429var semver_21 = semver.rsort;
11430var semver_22 = semver.gt;
11431var semver_23 = semver.lt;
11432var semver_24 = semver.eq;
11433var semver_25 = semver.neq;
11434var semver_26 = semver.gte;
11435var semver_27 = semver.lte;
11436var semver_28 = semver.cmp;
11437var semver_29 = semver.Comparator;
11438var semver_30 = semver.Range;
11439var semver_31 = semver.toComparators;
11440var semver_32 = semver.satisfies;
11441var semver_33 = semver.maxSatisfying;
11442var semver_34 = semver.minSatisfying;
11443var semver_35 = semver.minVersion;
11444var semver_36 = semver.validRange;
11445var semver_37 = semver.ltr;
11446var semver_38 = semver.gtr;
11447var semver_39 = semver.outside;
11448var semver_40 = semver.prerelease;
11449var semver_41 = semver.intersects;
11450var semver_42 = semver.coerce;
11451
11452const {promisify: promisify$1} = util;
11453
11454
11455const defaults$2 = {
11456 mode: 0o777 & (~process.umask()),
11457 fs
11458};
11459
11460const useNativeRecursiveOption = semver.satisfies(process.version, '>=10.12.0');
11461
11462// https://github.com/nodejs/node/issues/8987
11463// https://github.com/libuv/libuv/pull/1088
11464const checkPath = pth => {
11465 if (process.platform === 'win32') {
11466 const pathHasInvalidWinCharacters = /[<>:"|?*]/.test(pth.replace(path.parse(pth).root, ''));
11467
11468 if (pathHasInvalidWinCharacters) {
11469 const error = new Error(`Path contains invalid characters: ${pth}`);
11470 error.code = 'EINVAL';
11471 throw error;
11472 }
11473 }
11474};
11475
11476const permissionError = pth => {
11477 // This replicates the exception of `fs.mkdir` with native the
11478 // `recusive` option when run on an invalid drive under Windows.
11479 const error = new Error(`operation not permitted, mkdir '${pth}'`);
11480 error.code = 'EPERM';
11481 error.errno = -4048;
11482 error.path = pth;
11483 error.syscall = 'mkdir';
11484 return error;
11485};
11486
11487const makeDir = async (input, options) => {
11488 checkPath(input);
11489 options = {
11490 ...defaults$2,
11491 ...options
11492 };
11493
11494 const mkdir = promisify$1(options.fs.mkdir);
11495 const stat = promisify$1(options.fs.stat);
11496
11497 if (useNativeRecursiveOption && options.fs.mkdir === fs.mkdir) {
11498 const pth = path.resolve(input);
11499
11500 await mkdir(pth, {
11501 mode: options.mode,
11502 recursive: true
11503 });
11504
11505 return pth;
11506 }
11507
11508 const make = async pth => {
11509 try {
11510 await mkdir(pth, options.mode);
11511
11512 return pth;
11513 } catch (error) {
11514 if (error.code === 'EPERM') {
11515 throw error;
11516 }
11517
11518 if (error.code === 'ENOENT') {
11519 if (path.dirname(pth) === pth) {
11520 throw permissionError(pth);
11521 }
11522
11523 if (error.message.includes('null bytes')) {
11524 throw error;
11525 }
11526
11527 await make(path.dirname(pth));
11528
11529 return make(pth);
11530 }
11531
11532 const stats = await stat(pth);
11533 if (!stats.isDirectory()) {
11534 throw error;
11535 }
11536
11537 return pth;
11538 }
11539 };
11540
11541 return make(path.resolve(input));
11542};
11543
11544var makeDir_1 = makeDir;
11545
11546var sync = (input, options) => {
11547 checkPath(input);
11548 options = {
11549 ...defaults$2,
11550 ...options
11551 };
11552
11553 if (useNativeRecursiveOption && options.fs.mkdirSync === fs.mkdirSync) {
11554 const pth = path.resolve(input);
11555
11556 fs.mkdirSync(pth, {
11557 mode: options.mode,
11558 recursive: true
11559 });
11560
11561 return pth;
11562 }
11563
11564 const make = pth => {
11565 try {
11566 options.fs.mkdirSync(pth, options.mode);
11567 } catch (error) {
11568 if (error.code === 'EPERM') {
11569 throw error;
11570 }
11571
11572 if (error.code === 'ENOENT') {
11573 if (path.dirname(pth) === pth) {
11574 throw permissionError(pth);
11575 }
11576
11577 if (error.message.includes('null bytes')) {
11578 throw error;
11579 }
11580
11581 make(path.dirname(pth));
11582 return make(pth);
11583 }
11584
11585 try {
11586 if (!options.fs.statSync(pth).isDirectory()) {
11587 throw new Error('The path is not a directory');
11588 }
11589 } catch (_) {
11590 throw error;
11591 }
11592 }
11593
11594 return pth;
11595 };
11596
11597 return make(path.resolve(input));
11598};
11599makeDir_1.sync = sync;
11600
11601const BYTE_UNITS = [
11602 'B',
11603 'kB',
11604 'MB',
11605 'GB',
11606 'TB',
11607 'PB',
11608 'EB',
11609 'ZB',
11610 'YB'
11611];
11612
11613const BIT_UNITS = [
11614 'b',
11615 'kbit',
11616 'Mbit',
11617 'Gbit',
11618 'Tbit',
11619 'Pbit',
11620 'Ebit',
11621 'Zbit',
11622 'Ybit'
11623];
11624
11625/*
11626Formats the given number using `Number#toLocaleString`.
11627- If locale is a string, the value is expected to be a locale-key (for example: `de`).
11628- If locale is true, the system default locale is used for translation.
11629- If no value for locale is specified, the number is returned unmodified.
11630*/
11631const toLocaleString = (number, locale) => {
11632 let result = number;
11633 if (typeof locale === 'string') {
11634 result = number.toLocaleString(locale);
11635 } else if (locale === true) {
11636 result = number.toLocaleString();
11637 }
11638
11639 return result;
11640};
11641
11642var prettyBytes = (number, options) => {
11643 if (!Number.isFinite(number)) {
11644 throw new TypeError(`Expected a finite number, got ${typeof number}: ${number}`);
11645 }
11646
11647 options = Object.assign({bits: false}, options);
11648 const UNITS = options.bits ? BIT_UNITS : BYTE_UNITS;
11649
11650 if (options.signed && number === 0) {
11651 return ' 0 ' + UNITS[0];
11652 }
11653
11654 const isNegative = number < 0;
11655 const prefix = isNegative ? '-' : (options.signed ? '+' : '');
11656
11657 if (isNegative) {
11658 number = -number;
11659 }
11660
11661 if (number < 1) {
11662 const numberString = toLocaleString(number, options.locale);
11663 return prefix + numberString + ' ' + UNITS[0];
11664 }
11665
11666 const exponent = Math.min(Math.floor(Math.log10(number) / 3), UNITS.length - 1);
11667 // eslint-disable-next-line unicorn/prefer-exponentiation-operator
11668 number = Number((number / Math.pow(1000, exponent)).toPrecision(3));
11669 const numberString = toLocaleString(number, options.locale);
11670
11671 const unit = UNITS[exponent];
11672
11673 return prefix + numberString + ' ' + unit;
11674};
11675
11676var semver$1 = createCommonjsModule(function (module, exports) {
11677const lrCache = {};
11678const lazyRequire = (path, subkey) => {
11679 const module = lrCache[path] || (lrCache[path] = commonjsRequire());
11680 return subkey ? module[subkey] : module
11681};
11682
11683const lazyExport = (key, path, subkey) => {
11684 Object.defineProperty(exports, key, {
11685 get: () => {
11686 const res = lazyRequire(path, subkey);
11687 Object.defineProperty(exports, key, {
11688 value: res,
11689 enumerable: true,
11690 configurable: true
11691 });
11692 return res
11693 },
11694 configurable: true,
11695 enumerable: true
11696 });
11697};
11698
11699lazyExport('re', './internal/re', 're');
11700lazyExport('src', './internal/re', 'src');
11701lazyExport('tokens', './internal/re', 't');
11702lazyExport('SEMVER_SPEC_VERSION', './internal/constants', 'SEMVER_SPEC_VERSION');
11703lazyExport('SemVer', './classes/semver');
11704lazyExport('compareIdentifiers', './internal/identifiers', 'compareIdentifiers');
11705lazyExport('rcompareIdentifiers', './internal/identifiers', 'rcompareIdentifiers');
11706lazyExport('parse', './functions/parse');
11707lazyExport('valid', './functions/valid');
11708lazyExport('clean', './functions/clean');
11709lazyExport('inc', './functions/inc');
11710lazyExport('diff', './functions/diff');
11711lazyExport('major', './functions/major');
11712lazyExport('minor', './functions/minor');
11713lazyExport('patch', './functions/patch');
11714lazyExport('prerelease', './functions/prerelease');
11715lazyExport('compare', './functions/compare');
11716lazyExport('rcompare', './functions/rcompare');
11717lazyExport('compareLoose', './functions/compare-loose');
11718lazyExport('compareBuild', './functions/compare-build');
11719lazyExport('sort', './functions/sort');
11720lazyExport('rsort', './functions/rsort');
11721lazyExport('gt', './functions/gt');
11722lazyExport('lt', './functions/lt');
11723lazyExport('eq', './functions/eq');
11724lazyExport('neq', './functions/neq');
11725lazyExport('gte', './functions/gte');
11726lazyExport('lte', './functions/lte');
11727lazyExport('cmp', './functions/cmp');
11728lazyExport('coerce', './functions/coerce');
11729lazyExport('Comparator', './classes/comparator');
11730lazyExport('Range', './classes/range');
11731lazyExport('satisfies', './functions/satisfies');
11732lazyExport('toComparators', './ranges/to-comparators');
11733lazyExport('maxSatisfying', './ranges/max-satisfying');
11734lazyExport('minSatisfying', './ranges/min-satisfying');
11735lazyExport('minVersion', './ranges/min-version');
11736lazyExport('validRange', './ranges/valid');
11737lazyExport('outside', './ranges/outside');
11738lazyExport('gtr', './ranges/gtr');
11739lazyExport('ltr', './ranges/ltr');
11740lazyExport('intersects', './ranges/intersects');
11741});
11742
11743var mimicFn = (to, from) => {
11744 // TODO: use `Reflect.ownKeys()` when targeting Node.js 6
11745 for (const prop of Object.getOwnPropertyNames(from).concat(Object.getOwnPropertySymbols(from))) {
11746 Object.defineProperty(to, prop, Object.getOwnPropertyDescriptor(from, prop));
11747 }
11748
11749 return to;
11750};
11751
11752var pIsPromise = x => (
11753 x instanceof Promise ||
11754 (
11755 x !== null &&
11756 typeof x === 'object' &&
11757 typeof x.then === 'function' &&
11758 typeof x.catch === 'function'
11759 )
11760);
11761
11762var pDefer = () => {
11763 const ret = {};
11764
11765 ret.promise = new Promise((resolve, reject) => {
11766 ret.resolve = resolve;
11767 ret.reject = reject;
11768 });
11769
11770 return ret;
11771};
11772
11773var dist$1 = createCommonjsModule(function (module, exports) {
11774var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
11775 return new (P || (P = Promise))(function (resolve, reject) {
11776 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
11777 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
11778 function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
11779 step((generator = generator.apply(thisArg, _arguments || [])).next());
11780 });
11781};
11782var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
11783 return (mod && mod.__esModule) ? mod : { "default": mod };
11784};
11785Object.defineProperty(exports, "__esModule", { value: true });
11786const p_defer_1 = __importDefault(pDefer);
11787function mapAgeCleaner(map, property = 'maxAge') {
11788 let processingKey;
11789 let processingTimer;
11790 let processingDeferred;
11791 const cleanup = () => __awaiter(this, void 0, void 0, function* () {
11792 if (processingKey !== undefined) {
11793 // If we are already processing an item, we can safely exit
11794 return;
11795 }
11796 const setupTimer = (item) => __awaiter(this, void 0, void 0, function* () {
11797 processingDeferred = p_defer_1.default();
11798 const delay = item[1][property] - Date.now();
11799 if (delay <= 0) {
11800 // Remove the item immediately if the delay is equal to or below 0
11801 map.delete(item[0]);
11802 processingDeferred.resolve();
11803 return;
11804 }
11805 // Keep track of the current processed key
11806 processingKey = item[0];
11807 processingTimer = setTimeout(() => {
11808 // Remove the item when the timeout fires
11809 map.delete(item[0]);
11810 if (processingDeferred) {
11811 processingDeferred.resolve();
11812 }
11813 }, delay);
11814 // tslint:disable-next-line:strict-type-predicates
11815 if (typeof processingTimer.unref === 'function') {
11816 // Don't hold up the process from exiting
11817 processingTimer.unref();
11818 }
11819 return processingDeferred.promise;
11820 });
11821 try {
11822 for (const entry of map) {
11823 yield setupTimer(entry);
11824 }
11825 }
11826 catch (_a) {
11827 // Do nothing if an error occurs, this means the timer was cleaned up and we should stop processing
11828 }
11829 processingKey = undefined;
11830 });
11831 const reset = () => {
11832 processingKey = undefined;
11833 if (processingTimer !== undefined) {
11834 clearTimeout(processingTimer);
11835 processingTimer = undefined;
11836 }
11837 if (processingDeferred !== undefined) { // tslint:disable-line:early-exit
11838 processingDeferred.reject(undefined);
11839 processingDeferred = undefined;
11840 }
11841 };
11842 const originalSet = map.set.bind(map);
11843 map.set = (key, value) => {
11844 if (map.has(key)) {
11845 // If the key already exist, remove it so we can add it back at the end of the map.
11846 map.delete(key);
11847 }
11848 // Call the original `map.set`
11849 const result = originalSet(key, value);
11850 // If we are already processing a key and the key added is the current processed key, stop processing it
11851 if (processingKey && processingKey === key) {
11852 reset();
11853 }
11854 // Always run the cleanup method in case it wasn't started yet
11855 cleanup(); // tslint:disable-line:no-floating-promises
11856 return result;
11857 };
11858 cleanup(); // tslint:disable-line:no-floating-promises
11859 return map;
11860}
11861exports.default = mapAgeCleaner;
11862// Add support for CJS
11863module.exports = mapAgeCleaner;
11864module.exports.default = mapAgeCleaner;
11865});
11866
11867unwrapExports(dist$1);
11868
11869const cacheStore = new WeakMap();
11870
11871const defaultCacheKey = (...args) => {
11872 if (args.length === 0) {
11873 return '__defaultKey';
11874 }
11875
11876 if (args.length === 1) {
11877 const [firstArgument] = args;
11878 if (
11879 firstArgument === null ||
11880 firstArgument === undefined ||
11881 (typeof firstArgument !== 'function' && typeof firstArgument !== 'object')
11882 ) {
11883 return firstArgument;
11884 }
11885 }
11886
11887 return JSON.stringify(args);
11888};
11889
11890var mem = (fn, options) => {
11891 options = Object.assign({
11892 cacheKey: defaultCacheKey,
11893 cache: new Map(),
11894 cachePromiseRejection: false
11895 }, options);
11896
11897 if (typeof options.maxAge === 'number') {
11898 dist$1(options.cache);
11899 }
11900
11901 const {cache} = options;
11902 options.maxAge = options.maxAge || 0;
11903
11904 const setData = (key, data) => {
11905 cache.set(key, {
11906 data,
11907 maxAge: Date.now() + options.maxAge
11908 });
11909 };
11910
11911 const memoized = function (...args) {
11912 const key = options.cacheKey(...args);
11913
11914 if (cache.has(key)) {
11915 const c = cache.get(key);
11916
11917 return c.data;
11918 }
11919
11920 const ret = fn.call(this, ...args);
11921
11922 setData(key, ret);
11923
11924 if (pIsPromise(ret) && options.cachePromiseRejection === false) {
11925 // Remove rejected promises from cache unless `cachePromiseRejection` is set to `true`
11926 ret.catch(() => cache.delete(key));
11927 }
11928
11929 return ret;
11930 };
11931
11932 mimicFn(memoized, fn);
11933
11934 cacheStore.set(memoized, options.cache);
11935
11936 return memoized;
11937};
11938
11939var clear = fn => {
11940 const cache = cacheStore.get(fn);
11941
11942 if (cache && typeof cache.clear === 'function') {
11943 cache.clear();
11944 }
11945};
11946mem.clear = clear;
11947
11948const { execFileSync } = child_process;
11949const { existsSync } = fs;
11950const { resolve } = path;
11951
11952
11953const shellVar = name => name.startsWith('$') ? name : `$${name}`;
11954
11955/**
11956 * Synchronously gets default shell profile path
11957 * @name getProfilePath
11958 * @returns {Promise<String?>} profile path
11959 *
11960 * @example
11961 * const profile = require('shell-profile')();
11962 * console.log('profile: %s', profile);
11963 * //=> profile: /Users/vladimyr/.zshrc
11964 */
11965var shellProfile = mem(function () {
11966 const $HOME = os.homedir();
11967 const [$BASH_VERSION, $ZSH_VERSION] = env('BASH_VERSION', 'ZSH_VERSION');
11968 if (/^win/gi.test(process.platform)) return;
11969 if ($BASH_VERSION) {
11970 if (existsSync(resolve($HOME, '.bashrc'))) {
11971 return resolve($HOME, '.bashrc');
11972 } else if (existsSync(resolve($HOME, '.bash_profile'))) {
11973 return resolve($HOME, '.bash_profile');
11974 }
11975 } else if ($ZSH_VERSION) {
11976 if (existsSync(resolve($HOME, '.zshrc'))) return resolve($HOME, '.zshrc');
11977 }
11978 const profiles = ['.profile', '.bashrc', '.bash_profile', '.zshrc'];
11979 return profiles.map(it => resolve($HOME, it)).find(it => existsSync(it));
11980});
11981
11982function env(...vars) {
11983 const shellVars = vars.map(it => shellVar(it));
11984 const cmd = `echo -n "${shellVars.join('\n')}"; exit;`;
11985 const options = { stdio: 'pipe', encoding: 'utf-8' };
11986 const result = execFileSync(process.env.SHELL, ['-c', cmd], options);
11987 return result.split('\n').slice(0, vars.length);
11988}
11989
11990var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
11991
11992var escapeStringRegexp = function (str) {
11993 if (typeof str !== 'string') {
11994 throw new TypeError('Expected a string');
11995 }
11996
11997 return str.replace(matchOperatorsRe, '\\$&');
11998};
11999
12000var colorName = {
12001 "aliceblue": [240, 248, 255],
12002 "antiquewhite": [250, 235, 215],
12003 "aqua": [0, 255, 255],
12004 "aquamarine": [127, 255, 212],
12005 "azure": [240, 255, 255],
12006 "beige": [245, 245, 220],
12007 "bisque": [255, 228, 196],
12008 "black": [0, 0, 0],
12009 "blanchedalmond": [255, 235, 205],
12010 "blue": [0, 0, 255],
12011 "blueviolet": [138, 43, 226],
12012 "brown": [165, 42, 42],
12013 "burlywood": [222, 184, 135],
12014 "cadetblue": [95, 158, 160],
12015 "chartreuse": [127, 255, 0],
12016 "chocolate": [210, 105, 30],
12017 "coral": [255, 127, 80],
12018 "cornflowerblue": [100, 149, 237],
12019 "cornsilk": [255, 248, 220],
12020 "crimson": [220, 20, 60],
12021 "cyan": [0, 255, 255],
12022 "darkblue": [0, 0, 139],
12023 "darkcyan": [0, 139, 139],
12024 "darkgoldenrod": [184, 134, 11],
12025 "darkgray": [169, 169, 169],
12026 "darkgreen": [0, 100, 0],
12027 "darkgrey": [169, 169, 169],
12028 "darkkhaki": [189, 183, 107],
12029 "darkmagenta": [139, 0, 139],
12030 "darkolivegreen": [85, 107, 47],
12031 "darkorange": [255, 140, 0],
12032 "darkorchid": [153, 50, 204],
12033 "darkred": [139, 0, 0],
12034 "darksalmon": [233, 150, 122],
12035 "darkseagreen": [143, 188, 143],
12036 "darkslateblue": [72, 61, 139],
12037 "darkslategray": [47, 79, 79],
12038 "darkslategrey": [47, 79, 79],
12039 "darkturquoise": [0, 206, 209],
12040 "darkviolet": [148, 0, 211],
12041 "deeppink": [255, 20, 147],
12042 "deepskyblue": [0, 191, 255],
12043 "dimgray": [105, 105, 105],
12044 "dimgrey": [105, 105, 105],
12045 "dodgerblue": [30, 144, 255],
12046 "firebrick": [178, 34, 34],
12047 "floralwhite": [255, 250, 240],
12048 "forestgreen": [34, 139, 34],
12049 "fuchsia": [255, 0, 255],
12050 "gainsboro": [220, 220, 220],
12051 "ghostwhite": [248, 248, 255],
12052 "gold": [255, 215, 0],
12053 "goldenrod": [218, 165, 32],
12054 "gray": [128, 128, 128],
12055 "green": [0, 128, 0],
12056 "greenyellow": [173, 255, 47],
12057 "grey": [128, 128, 128],
12058 "honeydew": [240, 255, 240],
12059 "hotpink": [255, 105, 180],
12060 "indianred": [205, 92, 92],
12061 "indigo": [75, 0, 130],
12062 "ivory": [255, 255, 240],
12063 "khaki": [240, 230, 140],
12064 "lavender": [230, 230, 250],
12065 "lavenderblush": [255, 240, 245],
12066 "lawngreen": [124, 252, 0],
12067 "lemonchiffon": [255, 250, 205],
12068 "lightblue": [173, 216, 230],
12069 "lightcoral": [240, 128, 128],
12070 "lightcyan": [224, 255, 255],
12071 "lightgoldenrodyellow": [250, 250, 210],
12072 "lightgray": [211, 211, 211],
12073 "lightgreen": [144, 238, 144],
12074 "lightgrey": [211, 211, 211],
12075 "lightpink": [255, 182, 193],
12076 "lightsalmon": [255, 160, 122],
12077 "lightseagreen": [32, 178, 170],
12078 "lightskyblue": [135, 206, 250],
12079 "lightslategray": [119, 136, 153],
12080 "lightslategrey": [119, 136, 153],
12081 "lightsteelblue": [176, 196, 222],
12082 "lightyellow": [255, 255, 224],
12083 "lime": [0, 255, 0],
12084 "limegreen": [50, 205, 50],
12085 "linen": [250, 240, 230],
12086 "magenta": [255, 0, 255],
12087 "maroon": [128, 0, 0],
12088 "mediumaquamarine": [102, 205, 170],
12089 "mediumblue": [0, 0, 205],
12090 "mediumorchid": [186, 85, 211],
12091 "mediumpurple": [147, 112, 219],
12092 "mediumseagreen": [60, 179, 113],
12093 "mediumslateblue": [123, 104, 238],
12094 "mediumspringgreen": [0, 250, 154],
12095 "mediumturquoise": [72, 209, 204],
12096 "mediumvioletred": [199, 21, 133],
12097 "midnightblue": [25, 25, 112],
12098 "mintcream": [245, 255, 250],
12099 "mistyrose": [255, 228, 225],
12100 "moccasin": [255, 228, 181],
12101 "navajowhite": [255, 222, 173],
12102 "navy": [0, 0, 128],
12103 "oldlace": [253, 245, 230],
12104 "olive": [128, 128, 0],
12105 "olivedrab": [107, 142, 35],
12106 "orange": [255, 165, 0],
12107 "orangered": [255, 69, 0],
12108 "orchid": [218, 112, 214],
12109 "palegoldenrod": [238, 232, 170],
12110 "palegreen": [152, 251, 152],
12111 "paleturquoise": [175, 238, 238],
12112 "palevioletred": [219, 112, 147],
12113 "papayawhip": [255, 239, 213],
12114 "peachpuff": [255, 218, 185],
12115 "peru": [205, 133, 63],
12116 "pink": [255, 192, 203],
12117 "plum": [221, 160, 221],
12118 "powderblue": [176, 224, 230],
12119 "purple": [128, 0, 128],
12120 "rebeccapurple": [102, 51, 153],
12121 "red": [255, 0, 0],
12122 "rosybrown": [188, 143, 143],
12123 "royalblue": [65, 105, 225],
12124 "saddlebrown": [139, 69, 19],
12125 "salmon": [250, 128, 114],
12126 "sandybrown": [244, 164, 96],
12127 "seagreen": [46, 139, 87],
12128 "seashell": [255, 245, 238],
12129 "sienna": [160, 82, 45],
12130 "silver": [192, 192, 192],
12131 "skyblue": [135, 206, 235],
12132 "slateblue": [106, 90, 205],
12133 "slategray": [112, 128, 144],
12134 "slategrey": [112, 128, 144],
12135 "snow": [255, 250, 250],
12136 "springgreen": [0, 255, 127],
12137 "steelblue": [70, 130, 180],
12138 "tan": [210, 180, 140],
12139 "teal": [0, 128, 128],
12140 "thistle": [216, 191, 216],
12141 "tomato": [255, 99, 71],
12142 "turquoise": [64, 224, 208],
12143 "violet": [238, 130, 238],
12144 "wheat": [245, 222, 179],
12145 "white": [255, 255, 255],
12146 "whitesmoke": [245, 245, 245],
12147 "yellow": [255, 255, 0],
12148 "yellowgreen": [154, 205, 50]
12149};
12150
12151var conversions = createCommonjsModule(function (module) {
12152/* MIT license */
12153
12154
12155// NOTE: conversions should only return primitive values (i.e. arrays, or
12156// values that give correct `typeof` results).
12157// do not use box values types (i.e. Number(), String(), etc.)
12158
12159var reverseKeywords = {};
12160for (var key in colorName) {
12161 if (colorName.hasOwnProperty(key)) {
12162 reverseKeywords[colorName[key]] = key;
12163 }
12164}
12165
12166var convert = module.exports = {
12167 rgb: {channels: 3, labels: 'rgb'},
12168 hsl: {channels: 3, labels: 'hsl'},
12169 hsv: {channels: 3, labels: 'hsv'},
12170 hwb: {channels: 3, labels: 'hwb'},
12171 cmyk: {channels: 4, labels: 'cmyk'},
12172 xyz: {channels: 3, labels: 'xyz'},
12173 lab: {channels: 3, labels: 'lab'},
12174 lch: {channels: 3, labels: 'lch'},
12175 hex: {channels: 1, labels: ['hex']},
12176 keyword: {channels: 1, labels: ['keyword']},
12177 ansi16: {channels: 1, labels: ['ansi16']},
12178 ansi256: {channels: 1, labels: ['ansi256']},
12179 hcg: {channels: 3, labels: ['h', 'c', 'g']},
12180 apple: {channels: 3, labels: ['r16', 'g16', 'b16']},
12181 gray: {channels: 1, labels: ['gray']}
12182};
12183
12184// hide .channels and .labels properties
12185for (var model in convert) {
12186 if (convert.hasOwnProperty(model)) {
12187 if (!('channels' in convert[model])) {
12188 throw new Error('missing channels property: ' + model);
12189 }
12190
12191 if (!('labels' in convert[model])) {
12192 throw new Error('missing channel labels property: ' + model);
12193 }
12194
12195 if (convert[model].labels.length !== convert[model].channels) {
12196 throw new Error('channel and label counts mismatch: ' + model);
12197 }
12198
12199 var channels = convert[model].channels;
12200 var labels = convert[model].labels;
12201 delete convert[model].channels;
12202 delete convert[model].labels;
12203 Object.defineProperty(convert[model], 'channels', {value: channels});
12204 Object.defineProperty(convert[model], 'labels', {value: labels});
12205 }
12206}
12207
12208convert.rgb.hsl = function (rgb) {
12209 var r = rgb[0] / 255;
12210 var g = rgb[1] / 255;
12211 var b = rgb[2] / 255;
12212 var min = Math.min(r, g, b);
12213 var max = Math.max(r, g, b);
12214 var delta = max - min;
12215 var h;
12216 var s;
12217 var l;
12218
12219 if (max === min) {
12220 h = 0;
12221 } else if (r === max) {
12222 h = (g - b) / delta;
12223 } else if (g === max) {
12224 h = 2 + (b - r) / delta;
12225 } else if (b === max) {
12226 h = 4 + (r - g) / delta;
12227 }
12228
12229 h = Math.min(h * 60, 360);
12230
12231 if (h < 0) {
12232 h += 360;
12233 }
12234
12235 l = (min + max) / 2;
12236
12237 if (max === min) {
12238 s = 0;
12239 } else if (l <= 0.5) {
12240 s = delta / (max + min);
12241 } else {
12242 s = delta / (2 - max - min);
12243 }
12244
12245 return [h, s * 100, l * 100];
12246};
12247
12248convert.rgb.hsv = function (rgb) {
12249 var rdif;
12250 var gdif;
12251 var bdif;
12252 var h;
12253 var s;
12254
12255 var r = rgb[0] / 255;
12256 var g = rgb[1] / 255;
12257 var b = rgb[2] / 255;
12258 var v = Math.max(r, g, b);
12259 var diff = v - Math.min(r, g, b);
12260 var diffc = function (c) {
12261 return (v - c) / 6 / diff + 1 / 2;
12262 };
12263
12264 if (diff === 0) {
12265 h = s = 0;
12266 } else {
12267 s = diff / v;
12268 rdif = diffc(r);
12269 gdif = diffc(g);
12270 bdif = diffc(b);
12271
12272 if (r === v) {
12273 h = bdif - gdif;
12274 } else if (g === v) {
12275 h = (1 / 3) + rdif - bdif;
12276 } else if (b === v) {
12277 h = (2 / 3) + gdif - rdif;
12278 }
12279 if (h < 0) {
12280 h += 1;
12281 } else if (h > 1) {
12282 h -= 1;
12283 }
12284 }
12285
12286 return [
12287 h * 360,
12288 s * 100,
12289 v * 100
12290 ];
12291};
12292
12293convert.rgb.hwb = function (rgb) {
12294 var r = rgb[0];
12295 var g = rgb[1];
12296 var b = rgb[2];
12297 var h = convert.rgb.hsl(rgb)[0];
12298 var w = 1 / 255 * Math.min(r, Math.min(g, b));
12299
12300 b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
12301
12302 return [h, w * 100, b * 100];
12303};
12304
12305convert.rgb.cmyk = function (rgb) {
12306 var r = rgb[0] / 255;
12307 var g = rgb[1] / 255;
12308 var b = rgb[2] / 255;
12309 var c;
12310 var m;
12311 var y;
12312 var k;
12313
12314 k = Math.min(1 - r, 1 - g, 1 - b);
12315 c = (1 - r - k) / (1 - k) || 0;
12316 m = (1 - g - k) / (1 - k) || 0;
12317 y = (1 - b - k) / (1 - k) || 0;
12318
12319 return [c * 100, m * 100, y * 100, k * 100];
12320};
12321
12322/**
12323 * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
12324 * */
12325function comparativeDistance(x, y) {
12326 return (
12327 Math.pow(x[0] - y[0], 2) +
12328 Math.pow(x[1] - y[1], 2) +
12329 Math.pow(x[2] - y[2], 2)
12330 );
12331}
12332
12333convert.rgb.keyword = function (rgb) {
12334 var reversed = reverseKeywords[rgb];
12335 if (reversed) {
12336 return reversed;
12337 }
12338
12339 var currentClosestDistance = Infinity;
12340 var currentClosestKeyword;
12341
12342 for (var keyword in colorName) {
12343 if (colorName.hasOwnProperty(keyword)) {
12344 var value = colorName[keyword];
12345
12346 // Compute comparative distance
12347 var distance = comparativeDistance(rgb, value);
12348
12349 // Check if its less, if so set as closest
12350 if (distance < currentClosestDistance) {
12351 currentClosestDistance = distance;
12352 currentClosestKeyword = keyword;
12353 }
12354 }
12355 }
12356
12357 return currentClosestKeyword;
12358};
12359
12360convert.keyword.rgb = function (keyword) {
12361 return colorName[keyword];
12362};
12363
12364convert.rgb.xyz = function (rgb) {
12365 var r = rgb[0] / 255;
12366 var g = rgb[1] / 255;
12367 var b = rgb[2] / 255;
12368
12369 // assume sRGB
12370 r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92);
12371 g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92);
12372 b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92);
12373
12374 var x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805);
12375 var y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722);
12376 var z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505);
12377
12378 return [x * 100, y * 100, z * 100];
12379};
12380
12381convert.rgb.lab = function (rgb) {
12382 var xyz = convert.rgb.xyz(rgb);
12383 var x = xyz[0];
12384 var y = xyz[1];
12385 var z = xyz[2];
12386 var l;
12387 var a;
12388 var b;
12389
12390 x /= 95.047;
12391 y /= 100;
12392 z /= 108.883;
12393
12394 x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116);
12395 y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116);
12396 z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116);
12397
12398 l = (116 * y) - 16;
12399 a = 500 * (x - y);
12400 b = 200 * (y - z);
12401
12402 return [l, a, b];
12403};
12404
12405convert.hsl.rgb = function (hsl) {
12406 var h = hsl[0] / 360;
12407 var s = hsl[1] / 100;
12408 var l = hsl[2] / 100;
12409 var t1;
12410 var t2;
12411 var t3;
12412 var rgb;
12413 var val;
12414
12415 if (s === 0) {
12416 val = l * 255;
12417 return [val, val, val];
12418 }
12419
12420 if (l < 0.5) {
12421 t2 = l * (1 + s);
12422 } else {
12423 t2 = l + s - l * s;
12424 }
12425
12426 t1 = 2 * l - t2;
12427
12428 rgb = [0, 0, 0];
12429 for (var i = 0; i < 3; i++) {
12430 t3 = h + 1 / 3 * -(i - 1);
12431 if (t3 < 0) {
12432 t3++;
12433 }
12434 if (t3 > 1) {
12435 t3--;
12436 }
12437
12438 if (6 * t3 < 1) {
12439 val = t1 + (t2 - t1) * 6 * t3;
12440 } else if (2 * t3 < 1) {
12441 val = t2;
12442 } else if (3 * t3 < 2) {
12443 val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
12444 } else {
12445 val = t1;
12446 }
12447
12448 rgb[i] = val * 255;
12449 }
12450
12451 return rgb;
12452};
12453
12454convert.hsl.hsv = function (hsl) {
12455 var h = hsl[0];
12456 var s = hsl[1] / 100;
12457 var l = hsl[2] / 100;
12458 var smin = s;
12459 var lmin = Math.max(l, 0.01);
12460 var sv;
12461 var v;
12462
12463 l *= 2;
12464 s *= (l <= 1) ? l : 2 - l;
12465 smin *= lmin <= 1 ? lmin : 2 - lmin;
12466 v = (l + s) / 2;
12467 sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s);
12468
12469 return [h, sv * 100, v * 100];
12470};
12471
12472convert.hsv.rgb = function (hsv) {
12473 var h = hsv[0] / 60;
12474 var s = hsv[1] / 100;
12475 var v = hsv[2] / 100;
12476 var hi = Math.floor(h) % 6;
12477
12478 var f = h - Math.floor(h);
12479 var p = 255 * v * (1 - s);
12480 var q = 255 * v * (1 - (s * f));
12481 var t = 255 * v * (1 - (s * (1 - f)));
12482 v *= 255;
12483
12484 switch (hi) {
12485 case 0:
12486 return [v, t, p];
12487 case 1:
12488 return [q, v, p];
12489 case 2:
12490 return [p, v, t];
12491 case 3:
12492 return [p, q, v];
12493 case 4:
12494 return [t, p, v];
12495 case 5:
12496 return [v, p, q];
12497 }
12498};
12499
12500convert.hsv.hsl = function (hsv) {
12501 var h = hsv[0];
12502 var s = hsv[1] / 100;
12503 var v = hsv[2] / 100;
12504 var vmin = Math.max(v, 0.01);
12505 var lmin;
12506 var sl;
12507 var l;
12508
12509 l = (2 - s) * v;
12510 lmin = (2 - s) * vmin;
12511 sl = s * vmin;
12512 sl /= (lmin <= 1) ? lmin : 2 - lmin;
12513 sl = sl || 0;
12514 l /= 2;
12515
12516 return [h, sl * 100, l * 100];
12517};
12518
12519// http://dev.w3.org/csswg/css-color/#hwb-to-rgb
12520convert.hwb.rgb = function (hwb) {
12521 var h = hwb[0] / 360;
12522 var wh = hwb[1] / 100;
12523 var bl = hwb[2] / 100;
12524 var ratio = wh + bl;
12525 var i;
12526 var v;
12527 var f;
12528 var n;
12529
12530 // wh + bl cant be > 1
12531 if (ratio > 1) {
12532 wh /= ratio;
12533 bl /= ratio;
12534 }
12535
12536 i = Math.floor(6 * h);
12537 v = 1 - bl;
12538 f = 6 * h - i;
12539
12540 if ((i & 0x01) !== 0) {
12541 f = 1 - f;
12542 }
12543
12544 n = wh + f * (v - wh); // linear interpolation
12545
12546 var r;
12547 var g;
12548 var b;
12549 switch (i) {
12550 default:
12551 case 6:
12552 case 0: r = v; g = n; b = wh; break;
12553 case 1: r = n; g = v; b = wh; break;
12554 case 2: r = wh; g = v; b = n; break;
12555 case 3: r = wh; g = n; b = v; break;
12556 case 4: r = n; g = wh; b = v; break;
12557 case 5: r = v; g = wh; b = n; break;
12558 }
12559
12560 return [r * 255, g * 255, b * 255];
12561};
12562
12563convert.cmyk.rgb = function (cmyk) {
12564 var c = cmyk[0] / 100;
12565 var m = cmyk[1] / 100;
12566 var y = cmyk[2] / 100;
12567 var k = cmyk[3] / 100;
12568 var r;
12569 var g;
12570 var b;
12571
12572 r = 1 - Math.min(1, c * (1 - k) + k);
12573 g = 1 - Math.min(1, m * (1 - k) + k);
12574 b = 1 - Math.min(1, y * (1 - k) + k);
12575
12576 return [r * 255, g * 255, b * 255];
12577};
12578
12579convert.xyz.rgb = function (xyz) {
12580 var x = xyz[0] / 100;
12581 var y = xyz[1] / 100;
12582 var z = xyz[2] / 100;
12583 var r;
12584 var g;
12585 var b;
12586
12587 r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986);
12588 g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415);
12589 b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570);
12590
12591 // assume sRGB
12592 r = r > 0.0031308
12593 ? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055)
12594 : r * 12.92;
12595
12596 g = g > 0.0031308
12597 ? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055)
12598 : g * 12.92;
12599
12600 b = b > 0.0031308
12601 ? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055)
12602 : b * 12.92;
12603
12604 r = Math.min(Math.max(0, r), 1);
12605 g = Math.min(Math.max(0, g), 1);
12606 b = Math.min(Math.max(0, b), 1);
12607
12608 return [r * 255, g * 255, b * 255];
12609};
12610
12611convert.xyz.lab = function (xyz) {
12612 var x = xyz[0];
12613 var y = xyz[1];
12614 var z = xyz[2];
12615 var l;
12616 var a;
12617 var b;
12618
12619 x /= 95.047;
12620 y /= 100;
12621 z /= 108.883;
12622
12623 x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116);
12624 y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116);
12625 z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116);
12626
12627 l = (116 * y) - 16;
12628 a = 500 * (x - y);
12629 b = 200 * (y - z);
12630
12631 return [l, a, b];
12632};
12633
12634convert.lab.xyz = function (lab) {
12635 var l = lab[0];
12636 var a = lab[1];
12637 var b = lab[2];
12638 var x;
12639 var y;
12640 var z;
12641
12642 y = (l + 16) / 116;
12643 x = a / 500 + y;
12644 z = y - b / 200;
12645
12646 var y2 = Math.pow(y, 3);
12647 var x2 = Math.pow(x, 3);
12648 var z2 = Math.pow(z, 3);
12649 y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
12650 x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
12651 z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
12652
12653 x *= 95.047;
12654 y *= 100;
12655 z *= 108.883;
12656
12657 return [x, y, z];
12658};
12659
12660convert.lab.lch = function (lab) {
12661 var l = lab[0];
12662 var a = lab[1];
12663 var b = lab[2];
12664 var hr;
12665 var h;
12666 var c;
12667
12668 hr = Math.atan2(b, a);
12669 h = hr * 360 / 2 / Math.PI;
12670
12671 if (h < 0) {
12672 h += 360;
12673 }
12674
12675 c = Math.sqrt(a * a + b * b);
12676
12677 return [l, c, h];
12678};
12679
12680convert.lch.lab = function (lch) {
12681 var l = lch[0];
12682 var c = lch[1];
12683 var h = lch[2];
12684 var a;
12685 var b;
12686 var hr;
12687
12688 hr = h / 360 * 2 * Math.PI;
12689 a = c * Math.cos(hr);
12690 b = c * Math.sin(hr);
12691
12692 return [l, a, b];
12693};
12694
12695convert.rgb.ansi16 = function (args) {
12696 var r = args[0];
12697 var g = args[1];
12698 var b = args[2];
12699 var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization
12700
12701 value = Math.round(value / 50);
12702
12703 if (value === 0) {
12704 return 30;
12705 }
12706
12707 var ansi = 30
12708 + ((Math.round(b / 255) << 2)
12709 | (Math.round(g / 255) << 1)
12710 | Math.round(r / 255));
12711
12712 if (value === 2) {
12713 ansi += 60;
12714 }
12715
12716 return ansi;
12717};
12718
12719convert.hsv.ansi16 = function (args) {
12720 // optimization here; we already know the value and don't need to get
12721 // it converted for us.
12722 return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);
12723};
12724
12725convert.rgb.ansi256 = function (args) {
12726 var r = args[0];
12727 var g = args[1];
12728 var b = args[2];
12729
12730 // we use the extended greyscale palette here, with the exception of
12731 // black and white. normal palette only has 4 greyscale shades.
12732 if (r === g && g === b) {
12733 if (r < 8) {
12734 return 16;
12735 }
12736
12737 if (r > 248) {
12738 return 231;
12739 }
12740
12741 return Math.round(((r - 8) / 247) * 24) + 232;
12742 }
12743
12744 var ansi = 16
12745 + (36 * Math.round(r / 255 * 5))
12746 + (6 * Math.round(g / 255 * 5))
12747 + Math.round(b / 255 * 5);
12748
12749 return ansi;
12750};
12751
12752convert.ansi16.rgb = function (args) {
12753 var color = args % 10;
12754
12755 // handle greyscale
12756 if (color === 0 || color === 7) {
12757 if (args > 50) {
12758 color += 3.5;
12759 }
12760
12761 color = color / 10.5 * 255;
12762
12763 return [color, color, color];
12764 }
12765
12766 var mult = (~~(args > 50) + 1) * 0.5;
12767 var r = ((color & 1) * mult) * 255;
12768 var g = (((color >> 1) & 1) * mult) * 255;
12769 var b = (((color >> 2) & 1) * mult) * 255;
12770
12771 return [r, g, b];
12772};
12773
12774convert.ansi256.rgb = function (args) {
12775 // handle greyscale
12776 if (args >= 232) {
12777 var c = (args - 232) * 10 + 8;
12778 return [c, c, c];
12779 }
12780
12781 args -= 16;
12782
12783 var rem;
12784 var r = Math.floor(args / 36) / 5 * 255;
12785 var g = Math.floor((rem = args % 36) / 6) / 5 * 255;
12786 var b = (rem % 6) / 5 * 255;
12787
12788 return [r, g, b];
12789};
12790
12791convert.rgb.hex = function (args) {
12792 var integer = ((Math.round(args[0]) & 0xFF) << 16)
12793 + ((Math.round(args[1]) & 0xFF) << 8)
12794 + (Math.round(args[2]) & 0xFF);
12795
12796 var string = integer.toString(16).toUpperCase();
12797 return '000000'.substring(string.length) + string;
12798};
12799
12800convert.hex.rgb = function (args) {
12801 var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
12802 if (!match) {
12803 return [0, 0, 0];
12804 }
12805
12806 var colorString = match[0];
12807
12808 if (match[0].length === 3) {
12809 colorString = colorString.split('').map(function (char) {
12810 return char + char;
12811 }).join('');
12812 }
12813
12814 var integer = parseInt(colorString, 16);
12815 var r = (integer >> 16) & 0xFF;
12816 var g = (integer >> 8) & 0xFF;
12817 var b = integer & 0xFF;
12818
12819 return [r, g, b];
12820};
12821
12822convert.rgb.hcg = function (rgb) {
12823 var r = rgb[0] / 255;
12824 var g = rgb[1] / 255;
12825 var b = rgb[2] / 255;
12826 var max = Math.max(Math.max(r, g), b);
12827 var min = Math.min(Math.min(r, g), b);
12828 var chroma = (max - min);
12829 var grayscale;
12830 var hue;
12831
12832 if (chroma < 1) {
12833 grayscale = min / (1 - chroma);
12834 } else {
12835 grayscale = 0;
12836 }
12837
12838 if (chroma <= 0) {
12839 hue = 0;
12840 } else
12841 if (max === r) {
12842 hue = ((g - b) / chroma) % 6;
12843 } else
12844 if (max === g) {
12845 hue = 2 + (b - r) / chroma;
12846 } else {
12847 hue = 4 + (r - g) / chroma + 4;
12848 }
12849
12850 hue /= 6;
12851 hue %= 1;
12852
12853 return [hue * 360, chroma * 100, grayscale * 100];
12854};
12855
12856convert.hsl.hcg = function (hsl) {
12857 var s = hsl[1] / 100;
12858 var l = hsl[2] / 100;
12859 var c = 1;
12860 var f = 0;
12861
12862 if (l < 0.5) {
12863 c = 2.0 * s * l;
12864 } else {
12865 c = 2.0 * s * (1.0 - l);
12866 }
12867
12868 if (c < 1.0) {
12869 f = (l - 0.5 * c) / (1.0 - c);
12870 }
12871
12872 return [hsl[0], c * 100, f * 100];
12873};
12874
12875convert.hsv.hcg = function (hsv) {
12876 var s = hsv[1] / 100;
12877 var v = hsv[2] / 100;
12878
12879 var c = s * v;
12880 var f = 0;
12881
12882 if (c < 1.0) {
12883 f = (v - c) / (1 - c);
12884 }
12885
12886 return [hsv[0], c * 100, f * 100];
12887};
12888
12889convert.hcg.rgb = function (hcg) {
12890 var h = hcg[0] / 360;
12891 var c = hcg[1] / 100;
12892 var g = hcg[2] / 100;
12893
12894 if (c === 0.0) {
12895 return [g * 255, g * 255, g * 255];
12896 }
12897
12898 var pure = [0, 0, 0];
12899 var hi = (h % 1) * 6;
12900 var v = hi % 1;
12901 var w = 1 - v;
12902 var mg = 0;
12903
12904 switch (Math.floor(hi)) {
12905 case 0:
12906 pure[0] = 1; pure[1] = v; pure[2] = 0; break;
12907 case 1:
12908 pure[0] = w; pure[1] = 1; pure[2] = 0; break;
12909 case 2:
12910 pure[0] = 0; pure[1] = 1; pure[2] = v; break;
12911 case 3:
12912 pure[0] = 0; pure[1] = w; pure[2] = 1; break;
12913 case 4:
12914 pure[0] = v; pure[1] = 0; pure[2] = 1; break;
12915 default:
12916 pure[0] = 1; pure[1] = 0; pure[2] = w;
12917 }
12918
12919 mg = (1.0 - c) * g;
12920
12921 return [
12922 (c * pure[0] + mg) * 255,
12923 (c * pure[1] + mg) * 255,
12924 (c * pure[2] + mg) * 255
12925 ];
12926};
12927
12928convert.hcg.hsv = function (hcg) {
12929 var c = hcg[1] / 100;
12930 var g = hcg[2] / 100;
12931
12932 var v = c + g * (1.0 - c);
12933 var f = 0;
12934
12935 if (v > 0.0) {
12936 f = c / v;
12937 }
12938
12939 return [hcg[0], f * 100, v * 100];
12940};
12941
12942convert.hcg.hsl = function (hcg) {
12943 var c = hcg[1] / 100;
12944 var g = hcg[2] / 100;
12945
12946 var l = g * (1.0 - c) + 0.5 * c;
12947 var s = 0;
12948
12949 if (l > 0.0 && l < 0.5) {
12950 s = c / (2 * l);
12951 } else
12952 if (l >= 0.5 && l < 1.0) {
12953 s = c / (2 * (1 - l));
12954 }
12955
12956 return [hcg[0], s * 100, l * 100];
12957};
12958
12959convert.hcg.hwb = function (hcg) {
12960 var c = hcg[1] / 100;
12961 var g = hcg[2] / 100;
12962 var v = c + g * (1.0 - c);
12963 return [hcg[0], (v - c) * 100, (1 - v) * 100];
12964};
12965
12966convert.hwb.hcg = function (hwb) {
12967 var w = hwb[1] / 100;
12968 var b = hwb[2] / 100;
12969 var v = 1 - b;
12970 var c = v - w;
12971 var g = 0;
12972
12973 if (c < 1) {
12974 g = (v - c) / (1 - c);
12975 }
12976
12977 return [hwb[0], c * 100, g * 100];
12978};
12979
12980convert.apple.rgb = function (apple) {
12981 return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255];
12982};
12983
12984convert.rgb.apple = function (rgb) {
12985 return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535];
12986};
12987
12988convert.gray.rgb = function (args) {
12989 return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
12990};
12991
12992convert.gray.hsl = convert.gray.hsv = function (args) {
12993 return [0, 0, args[0]];
12994};
12995
12996convert.gray.hwb = function (gray) {
12997 return [0, 100, gray[0]];
12998};
12999
13000convert.gray.cmyk = function (gray) {
13001 return [0, 0, 0, gray[0]];
13002};
13003
13004convert.gray.lab = function (gray) {
13005 return [gray[0], 0, 0];
13006};
13007
13008convert.gray.hex = function (gray) {
13009 var val = Math.round(gray[0] / 100 * 255) & 0xFF;
13010 var integer = (val << 16) + (val << 8) + val;
13011
13012 var string = integer.toString(16).toUpperCase();
13013 return '000000'.substring(string.length) + string;
13014};
13015
13016convert.rgb.gray = function (rgb) {
13017 var val = (rgb[0] + rgb[1] + rgb[2]) / 3;
13018 return [val / 255 * 100];
13019};
13020});
13021var conversions_1 = conversions.rgb;
13022var conversions_2 = conversions.hsl;
13023var conversions_3 = conversions.hsv;
13024var conversions_4 = conversions.hwb;
13025var conversions_5 = conversions.cmyk;
13026var conversions_6 = conversions.xyz;
13027var conversions_7 = conversions.lab;
13028var conversions_8 = conversions.lch;
13029var conversions_9 = conversions.hex;
13030var conversions_10 = conversions.keyword;
13031var conversions_11 = conversions.ansi16;
13032var conversions_12 = conversions.ansi256;
13033var conversions_13 = conversions.hcg;
13034var conversions_14 = conversions.apple;
13035var conversions_15 = conversions.gray;
13036
13037/*
13038 this function routes a model to all other models.
13039
13040 all functions that are routed have a property `.conversion` attached
13041 to the returned synthetic function. This property is an array
13042 of strings, each with the steps in between the 'from' and 'to'
13043 color models (inclusive).
13044
13045 conversions that are not possible simply are not included.
13046*/
13047
13048function buildGraph() {
13049 var graph = {};
13050 // https://jsperf.com/object-keys-vs-for-in-with-closure/3
13051 var models = Object.keys(conversions);
13052
13053 for (var len = models.length, i = 0; i < len; i++) {
13054 graph[models[i]] = {
13055 // http://jsperf.com/1-vs-infinity
13056 // micro-opt, but this is simple.
13057 distance: -1,
13058 parent: null
13059 };
13060 }
13061
13062 return graph;
13063}
13064
13065// https://en.wikipedia.org/wiki/Breadth-first_search
13066function deriveBFS(fromModel) {
13067 var graph = buildGraph();
13068 var queue = [fromModel]; // unshift -> queue -> pop
13069
13070 graph[fromModel].distance = 0;
13071
13072 while (queue.length) {
13073 var current = queue.pop();
13074 var adjacents = Object.keys(conversions[current]);
13075
13076 for (var len = adjacents.length, i = 0; i < len; i++) {
13077 var adjacent = adjacents[i];
13078 var node = graph[adjacent];
13079
13080 if (node.distance === -1) {
13081 node.distance = graph[current].distance + 1;
13082 node.parent = current;
13083 queue.unshift(adjacent);
13084 }
13085 }
13086 }
13087
13088 return graph;
13089}
13090
13091function link(from, to) {
13092 return function (args) {
13093 return to(from(args));
13094 };
13095}
13096
13097function wrapConversion(toModel, graph) {
13098 var path = [graph[toModel].parent, toModel];
13099 var fn = conversions[graph[toModel].parent][toModel];
13100
13101 var cur = graph[toModel].parent;
13102 while (graph[cur].parent) {
13103 path.unshift(graph[cur].parent);
13104 fn = link(conversions[graph[cur].parent][cur], fn);
13105 cur = graph[cur].parent;
13106 }
13107
13108 fn.conversion = path;
13109 return fn;
13110}
13111
13112var route = function (fromModel) {
13113 var graph = deriveBFS(fromModel);
13114 var conversion = {};
13115
13116 var models = Object.keys(graph);
13117 for (var len = models.length, i = 0; i < len; i++) {
13118 var toModel = models[i];
13119 var node = graph[toModel];
13120
13121 if (node.parent === null) {
13122 // no possible conversion, or this node is the source model.
13123 continue;
13124 }
13125
13126 conversion[toModel] = wrapConversion(toModel, graph);
13127 }
13128
13129 return conversion;
13130};
13131
13132var convert = {};
13133
13134var models = Object.keys(conversions);
13135
13136function wrapRaw(fn) {
13137 var wrappedFn = function (args) {
13138 if (args === undefined || args === null) {
13139 return args;
13140 }
13141
13142 if (arguments.length > 1) {
13143 args = Array.prototype.slice.call(arguments);
13144 }
13145
13146 return fn(args);
13147 };
13148
13149 // preserve .conversion property if there is one
13150 if ('conversion' in fn) {
13151 wrappedFn.conversion = fn.conversion;
13152 }
13153
13154 return wrappedFn;
13155}
13156
13157function wrapRounded(fn) {
13158 var wrappedFn = function (args) {
13159 if (args === undefined || args === null) {
13160 return args;
13161 }
13162
13163 if (arguments.length > 1) {
13164 args = Array.prototype.slice.call(arguments);
13165 }
13166
13167 var result = fn(args);
13168
13169 // we're assuming the result is an array here.
13170 // see notice in conversions.js; don't use box types
13171 // in conversion functions.
13172 if (typeof result === 'object') {
13173 for (var len = result.length, i = 0; i < len; i++) {
13174 result[i] = Math.round(result[i]);
13175 }
13176 }
13177
13178 return result;
13179 };
13180
13181 // preserve .conversion property if there is one
13182 if ('conversion' in fn) {
13183 wrappedFn.conversion = fn.conversion;
13184 }
13185
13186 return wrappedFn;
13187}
13188
13189models.forEach(function (fromModel) {
13190 convert[fromModel] = {};
13191
13192 Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels});
13193 Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels});
13194
13195 var routes = route(fromModel);
13196 var routeModels = Object.keys(routes);
13197
13198 routeModels.forEach(function (toModel) {
13199 var fn = routes[toModel];
13200
13201 convert[fromModel][toModel] = wrapRounded(fn);
13202 convert[fromModel][toModel].raw = wrapRaw(fn);
13203 });
13204});
13205
13206var colorConvert = convert;
13207
13208var ansiStyles = createCommonjsModule(function (module) {
13209
13210
13211const wrapAnsi16 = (fn, offset) => function () {
13212 const code = fn.apply(colorConvert, arguments);
13213 return `\u001B[${code + offset}m`;
13214};
13215
13216const wrapAnsi256 = (fn, offset) => function () {
13217 const code = fn.apply(colorConvert, arguments);
13218 return `\u001B[${38 + offset};5;${code}m`;
13219};
13220
13221const wrapAnsi16m = (fn, offset) => function () {
13222 const rgb = fn.apply(colorConvert, arguments);
13223 return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
13224};
13225
13226function assembleStyles() {
13227 const codes = new Map();
13228 const styles = {
13229 modifier: {
13230 reset: [0, 0],
13231 // 21 isn't widely supported and 22 does the same thing
13232 bold: [1, 22],
13233 dim: [2, 22],
13234 italic: [3, 23],
13235 underline: [4, 24],
13236 inverse: [7, 27],
13237 hidden: [8, 28],
13238 strikethrough: [9, 29]
13239 },
13240 color: {
13241 black: [30, 39],
13242 red: [31, 39],
13243 green: [32, 39],
13244 yellow: [33, 39],
13245 blue: [34, 39],
13246 magenta: [35, 39],
13247 cyan: [36, 39],
13248 white: [37, 39],
13249 gray: [90, 39],
13250
13251 // Bright color
13252 redBright: [91, 39],
13253 greenBright: [92, 39],
13254 yellowBright: [93, 39],
13255 blueBright: [94, 39],
13256 magentaBright: [95, 39],
13257 cyanBright: [96, 39],
13258 whiteBright: [97, 39]
13259 },
13260 bgColor: {
13261 bgBlack: [40, 49],
13262 bgRed: [41, 49],
13263 bgGreen: [42, 49],
13264 bgYellow: [43, 49],
13265 bgBlue: [44, 49],
13266 bgMagenta: [45, 49],
13267 bgCyan: [46, 49],
13268 bgWhite: [47, 49],
13269
13270 // Bright color
13271 bgBlackBright: [100, 49],
13272 bgRedBright: [101, 49],
13273 bgGreenBright: [102, 49],
13274 bgYellowBright: [103, 49],
13275 bgBlueBright: [104, 49],
13276 bgMagentaBright: [105, 49],
13277 bgCyanBright: [106, 49],
13278 bgWhiteBright: [107, 49]
13279 }
13280 };
13281
13282 // Fix humans
13283 styles.color.grey = styles.color.gray;
13284
13285 for (const groupName of Object.keys(styles)) {
13286 const group = styles[groupName];
13287
13288 for (const styleName of Object.keys(group)) {
13289 const style = group[styleName];
13290
13291 styles[styleName] = {
13292 open: `\u001B[${style[0]}m`,
13293 close: `\u001B[${style[1]}m`
13294 };
13295
13296 group[styleName] = styles[styleName];
13297
13298 codes.set(style[0], style[1]);
13299 }
13300
13301 Object.defineProperty(styles, groupName, {
13302 value: group,
13303 enumerable: false
13304 });
13305
13306 Object.defineProperty(styles, 'codes', {
13307 value: codes,
13308 enumerable: false
13309 });
13310 }
13311
13312 const ansi2ansi = n => n;
13313 const rgb2rgb = (r, g, b) => [r, g, b];
13314
13315 styles.color.close = '\u001B[39m';
13316 styles.bgColor.close = '\u001B[49m';
13317
13318 styles.color.ansi = {
13319 ansi: wrapAnsi16(ansi2ansi, 0)
13320 };
13321 styles.color.ansi256 = {
13322 ansi256: wrapAnsi256(ansi2ansi, 0)
13323 };
13324 styles.color.ansi16m = {
13325 rgb: wrapAnsi16m(rgb2rgb, 0)
13326 };
13327
13328 styles.bgColor.ansi = {
13329 ansi: wrapAnsi16(ansi2ansi, 10)
13330 };
13331 styles.bgColor.ansi256 = {
13332 ansi256: wrapAnsi256(ansi2ansi, 10)
13333 };
13334 styles.bgColor.ansi16m = {
13335 rgb: wrapAnsi16m(rgb2rgb, 10)
13336 };
13337
13338 for (let key of Object.keys(colorConvert)) {
13339 if (typeof colorConvert[key] !== 'object') {
13340 continue;
13341 }
13342
13343 const suite = colorConvert[key];
13344
13345 if (key === 'ansi16') {
13346 key = 'ansi';
13347 }
13348
13349 if ('ansi16' in suite) {
13350 styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0);
13351 styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10);
13352 }
13353
13354 if ('ansi256' in suite) {
13355 styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0);
13356 styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10);
13357 }
13358
13359 if ('rgb' in suite) {
13360 styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0);
13361 styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10);
13362 }
13363 }
13364
13365 return styles;
13366}
13367
13368// Make the export immutable
13369Object.defineProperty(module, 'exports', {
13370 enumerable: true,
13371 get: assembleStyles
13372});
13373});
13374
13375var hasFlag$1 = (flag, argv) => {
13376 argv = argv || process.argv;
13377 const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');
13378 const pos = argv.indexOf(prefix + flag);
13379 const terminatorPos = argv.indexOf('--');
13380 return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos);
13381};
13382
13383const env$1 = process.env;
13384
13385let forceColor;
13386if (hasFlag$1('no-color') ||
13387 hasFlag$1('no-colors') ||
13388 hasFlag$1('color=false')) {
13389 forceColor = false;
13390} else if (hasFlag$1('color') ||
13391 hasFlag$1('colors') ||
13392 hasFlag$1('color=true') ||
13393 hasFlag$1('color=always')) {
13394 forceColor = true;
13395}
13396if ('FORCE_COLOR' in env$1) {
13397 forceColor = env$1.FORCE_COLOR.length === 0 || parseInt(env$1.FORCE_COLOR, 10) !== 0;
13398}
13399
13400function translateLevel(level) {
13401 if (level === 0) {
13402 return false;
13403 }
13404
13405 return {
13406 level,
13407 hasBasic: true,
13408 has256: level >= 2,
13409 has16m: level >= 3
13410 };
13411}
13412
13413function supportsColor$1(stream) {
13414 if (forceColor === false) {
13415 return 0;
13416 }
13417
13418 if (hasFlag$1('color=16m') ||
13419 hasFlag$1('color=full') ||
13420 hasFlag$1('color=truecolor')) {
13421 return 3;
13422 }
13423
13424 if (hasFlag$1('color=256')) {
13425 return 2;
13426 }
13427
13428 if (stream && !stream.isTTY && forceColor !== true) {
13429 return 0;
13430 }
13431
13432 const min = forceColor ? 1 : 0;
13433
13434 if (process.platform === 'win32') {
13435 // Node.js 7.5.0 is the first version of Node.js to include a patch to
13436 // libuv that enables 256 color output on Windows. Anything earlier and it
13437 // won't work. However, here we target Node.js 8 at minimum as it is an LTS
13438 // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows
13439 // release that supports 256 colors. Windows 10 build 14931 is the first release
13440 // that supports 16m/TrueColor.
13441 const osRelease = os.release().split('.');
13442 if (
13443 Number(process.versions.node.split('.')[0]) >= 8 &&
13444 Number(osRelease[0]) >= 10 &&
13445 Number(osRelease[2]) >= 10586
13446 ) {
13447 return Number(osRelease[2]) >= 14931 ? 3 : 2;
13448 }
13449
13450 return 1;
13451 }
13452
13453 if ('CI' in env$1) {
13454 if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env$1) || env$1.CI_NAME === 'codeship') {
13455 return 1;
13456 }
13457
13458 return min;
13459 }
13460
13461 if ('TEAMCITY_VERSION' in env$1) {
13462 return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$1.TEAMCITY_VERSION) ? 1 : 0;
13463 }
13464
13465 if (env$1.COLORTERM === 'truecolor') {
13466 return 3;
13467 }
13468
13469 if ('TERM_PROGRAM' in env$1) {
13470 const version = parseInt((env$1.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
13471
13472 switch (env$1.TERM_PROGRAM) {
13473 case 'iTerm.app':
13474 return version >= 3 ? 3 : 2;
13475 case 'Apple_Terminal':
13476 return 2;
13477 // No default
13478 }
13479 }
13480
13481 if (/-256(color)?$/i.test(env$1.TERM)) {
13482 return 2;
13483 }
13484
13485 if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$1.TERM)) {
13486 return 1;
13487 }
13488
13489 if ('COLORTERM' in env$1) {
13490 return 1;
13491 }
13492
13493 if (env$1.TERM === 'dumb') {
13494 return min;
13495 }
13496
13497 return min;
13498}
13499
13500function getSupportLevel(stream) {
13501 const level = supportsColor$1(stream);
13502 return translateLevel(level);
13503}
13504
13505var supportsColor_1 = {
13506 supportsColor: getSupportLevel,
13507 stdout: getSupportLevel(process.stdout),
13508 stderr: getSupportLevel(process.stderr)
13509};
13510
13511const TEMPLATE_REGEX = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
13512const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
13513const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
13514const ESCAPE_REGEX = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi;
13515
13516const ESCAPES = new Map([
13517 ['n', '\n'],
13518 ['r', '\r'],
13519 ['t', '\t'],
13520 ['b', '\b'],
13521 ['f', '\f'],
13522 ['v', '\v'],
13523 ['0', '\0'],
13524 ['\\', '\\'],
13525 ['e', '\u001B'],
13526 ['a', '\u0007']
13527]);
13528
13529function unescape(c) {
13530 if ((c[0] === 'u' && c.length === 5) || (c[0] === 'x' && c.length === 3)) {
13531 return String.fromCharCode(parseInt(c.slice(1), 16));
13532 }
13533
13534 return ESCAPES.get(c) || c;
13535}
13536
13537function parseArguments(name, args) {
13538 const results = [];
13539 const chunks = args.trim().split(/\s*,\s*/g);
13540 let matches;
13541
13542 for (const chunk of chunks) {
13543 if (!isNaN(chunk)) {
13544 results.push(Number(chunk));
13545 } else if ((matches = chunk.match(STRING_REGEX))) {
13546 results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, chr) => escape ? unescape(escape) : chr));
13547 } else {
13548 throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
13549 }
13550 }
13551
13552 return results;
13553}
13554
13555function parseStyle(style) {
13556 STYLE_REGEX.lastIndex = 0;
13557
13558 const results = [];
13559 let matches;
13560
13561 while ((matches = STYLE_REGEX.exec(style)) !== null) {
13562 const name = matches[1];
13563
13564 if (matches[2]) {
13565 const args = parseArguments(name, matches[2]);
13566 results.push([name].concat(args));
13567 } else {
13568 results.push([name]);
13569 }
13570 }
13571
13572 return results;
13573}
13574
13575function buildStyle(chalk, styles) {
13576 const enabled = {};
13577
13578 for (const layer of styles) {
13579 for (const style of layer.styles) {
13580 enabled[style[0]] = layer.inverse ? null : style.slice(1);
13581 }
13582 }
13583
13584 let current = chalk;
13585 for (const styleName of Object.keys(enabled)) {
13586 if (Array.isArray(enabled[styleName])) {
13587 if (!(styleName in current)) {
13588 throw new Error(`Unknown Chalk style: ${styleName}`);
13589 }
13590
13591 if (enabled[styleName].length > 0) {
13592 current = current[styleName].apply(current, enabled[styleName]);
13593 } else {
13594 current = current[styleName];
13595 }
13596 }
13597 }
13598
13599 return current;
13600}
13601
13602var templates = (chalk, tmp) => {
13603 const styles = [];
13604 const chunks = [];
13605 let chunk = [];
13606
13607 // eslint-disable-next-line max-params
13608 tmp.replace(TEMPLATE_REGEX, (m, escapeChar, inverse, style, close, chr) => {
13609 if (escapeChar) {
13610 chunk.push(unescape(escapeChar));
13611 } else if (style) {
13612 const str = chunk.join('');
13613 chunk = [];
13614 chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str));
13615 styles.push({inverse, styles: parseStyle(style)});
13616 } else if (close) {
13617 if (styles.length === 0) {
13618 throw new Error('Found extraneous } in Chalk template literal');
13619 }
13620
13621 chunks.push(buildStyle(chalk, styles)(chunk.join('')));
13622 chunk = [];
13623 styles.pop();
13624 } else {
13625 chunk.push(chr);
13626 }
13627 });
13628
13629 chunks.push(chunk.join(''));
13630
13631 if (styles.length > 0) {
13632 const errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`;
13633 throw new Error(errMsg);
13634 }
13635
13636 return chunks.join('');
13637};
13638
13639var chalk = createCommonjsModule(function (module) {
13640
13641
13642const stdoutColor = supportsColor_1.stdout;
13643
13644
13645
13646const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm');
13647
13648// `supportsColor.level` → `ansiStyles.color[name]` mapping
13649const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m'];
13650
13651// `color-convert` models to exclude from the Chalk API due to conflicts and such
13652const skipModels = new Set(['gray']);
13653
13654const styles = Object.create(null);
13655
13656function applyOptions(obj, options) {
13657 options = options || {};
13658
13659 // Detect level if not set manually
13660 const scLevel = stdoutColor ? stdoutColor.level : 0;
13661 obj.level = options.level === undefined ? scLevel : options.level;
13662 obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0;
13663}
13664
13665function Chalk(options) {
13666 // We check for this.template here since calling `chalk.constructor()`
13667 // by itself will have a `this` of a previously constructed chalk object
13668 if (!this || !(this instanceof Chalk) || this.template) {
13669 const chalk = {};
13670 applyOptions(chalk, options);
13671
13672 chalk.template = function () {
13673 const args = [].slice.call(arguments);
13674 return chalkTag.apply(null, [chalk.template].concat(args));
13675 };
13676
13677 Object.setPrototypeOf(chalk, Chalk.prototype);
13678 Object.setPrototypeOf(chalk.template, chalk);
13679
13680 chalk.template.constructor = Chalk;
13681
13682 return chalk.template;
13683 }
13684
13685 applyOptions(this, options);
13686}
13687
13688// Use bright blue on Windows as the normal blue color is illegible
13689if (isSimpleWindowsTerm) {
13690 ansiStyles.blue.open = '\u001B[94m';
13691}
13692
13693for (const key of Object.keys(ansiStyles)) {
13694 ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g');
13695
13696 styles[key] = {
13697 get() {
13698 const codes = ansiStyles[key];
13699 return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key);
13700 }
13701 };
13702}
13703
13704styles.visible = {
13705 get() {
13706 return build.call(this, this._styles || [], true, 'visible');
13707 }
13708};
13709
13710ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g');
13711for (const model of Object.keys(ansiStyles.color.ansi)) {
13712 if (skipModels.has(model)) {
13713 continue;
13714 }
13715
13716 styles[model] = {
13717 get() {
13718 const level = this.level;
13719 return function () {
13720 const open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments);
13721 const codes = {
13722 open,
13723 close: ansiStyles.color.close,
13724 closeRe: ansiStyles.color.closeRe
13725 };
13726 return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
13727 };
13728 }
13729 };
13730}
13731
13732ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g');
13733for (const model of Object.keys(ansiStyles.bgColor.ansi)) {
13734 if (skipModels.has(model)) {
13735 continue;
13736 }
13737
13738 const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
13739 styles[bgModel] = {
13740 get() {
13741 const level = this.level;
13742 return function () {
13743 const open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments);
13744 const codes = {
13745 open,
13746 close: ansiStyles.bgColor.close,
13747 closeRe: ansiStyles.bgColor.closeRe
13748 };
13749 return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
13750 };
13751 }
13752 };
13753}
13754
13755const proto = Object.defineProperties(() => {}, styles);
13756
13757function build(_styles, _empty, key) {
13758 const builder = function () {
13759 return applyStyle.apply(builder, arguments);
13760 };
13761
13762 builder._styles = _styles;
13763 builder._empty = _empty;
13764
13765 const self = this;
13766
13767 Object.defineProperty(builder, 'level', {
13768 enumerable: true,
13769 get() {
13770 return self.level;
13771 },
13772 set(level) {
13773 self.level = level;
13774 }
13775 });
13776
13777 Object.defineProperty(builder, 'enabled', {
13778 enumerable: true,
13779 get() {
13780 return self.enabled;
13781 },
13782 set(enabled) {
13783 self.enabled = enabled;
13784 }
13785 });
13786
13787 // See below for fix regarding invisible grey/dim combination on Windows
13788 builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey';
13789
13790 // `__proto__` is used because we must return a function, but there is
13791 // no way to create a function with a different prototype
13792 builder.__proto__ = proto; // eslint-disable-line no-proto
13793
13794 return builder;
13795}
13796
13797function applyStyle() {
13798 // Support varags, but simply cast to string in case there's only one arg
13799 const args = arguments;
13800 const argsLen = args.length;
13801 let str = String(arguments[0]);
13802
13803 if (argsLen === 0) {
13804 return '';
13805 }
13806
13807 if (argsLen > 1) {
13808 // Don't slice `arguments`, it prevents V8 optimizations
13809 for (let a = 1; a < argsLen; a++) {
13810 str += ' ' + args[a];
13811 }
13812 }
13813
13814 if (!this.enabled || this.level <= 0 || !str) {
13815 return this._empty ? '' : str;
13816 }
13817
13818 // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe,
13819 // see https://github.com/chalk/chalk/issues/58
13820 // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop.
13821 const originalDim = ansiStyles.dim.open;
13822 if (isSimpleWindowsTerm && this.hasGrey) {
13823 ansiStyles.dim.open = '';
13824 }
13825
13826 for (const code of this._styles.slice().reverse()) {
13827 // Replace any instances already present with a re-opening code
13828 // otherwise only the part of the string until said closing code
13829 // will be colored, and the rest will simply be 'plain'.
13830 str = code.open + str.replace(code.closeRe, code.open) + code.close;
13831
13832 // Close the styling before a linebreak and reopen
13833 // after next line to fix a bleed issue on macOS
13834 // https://github.com/chalk/chalk/pull/92
13835 str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`);
13836 }
13837
13838 // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue
13839 ansiStyles.dim.open = originalDim;
13840
13841 return str;
13842}
13843
13844function chalkTag(chalk, strings) {
13845 if (!Array.isArray(strings)) {
13846 // If chalk() was called by itself or with a string,
13847 // return the string itself as a string.
13848 return [].slice.call(arguments, 1).join(' ');
13849 }
13850
13851 const args = [].slice.call(arguments, 2);
13852 const parts = [strings.raw[0]];
13853
13854 for (let i = 1; i < strings.length; i++) {
13855 parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&'));
13856 parts.push(String(strings.raw[i]));
13857 }
13858
13859 return templates(chalk, parts.join(''));
13860}
13861
13862Object.defineProperties(Chalk.prototype, styles);
13863
13864module.exports = Chalk(); // eslint-disable-line new-cap
13865module.exports.supportsColor = stdoutColor;
13866module.exports.default = module.exports; // For TypeScript
13867});
13868var chalk_1 = chalk.supportsColor;
13869
13870const mimicFn$1 = (to, from) => {
13871 for (const prop of Reflect.ownKeys(from)) {
13872 Object.defineProperty(to, prop, Object.getOwnPropertyDescriptor(from, prop));
13873 }
13874
13875 return to;
13876};
13877
13878var mimicFn_1 = mimicFn$1;
13879// TODO: Remove this for the next major release
13880var default_1$1 = mimicFn$1;
13881mimicFn_1.default = default_1$1;
13882
13883const calledFunctions = new WeakMap();
13884
13885const oneTime = (fn, options = {}) => {
13886 if (typeof fn !== 'function') {
13887 throw new TypeError('Expected a function');
13888 }
13889
13890 let ret;
13891 let isCalled = false;
13892 let callCount = 0;
13893 const functionName = fn.displayName || fn.name || '<anonymous>';
13894
13895 const onetime = function (...args) {
13896 calledFunctions.set(onetime, ++callCount);
13897
13898 if (isCalled) {
13899 if (options.throw === true) {
13900 throw new Error(`Function \`${functionName}\` can only be called once`);
13901 }
13902
13903 return ret;
13904 }
13905
13906 isCalled = true;
13907 ret = fn.apply(this, args);
13908 fn = null;
13909
13910 return ret;
13911 };
13912
13913 mimicFn_1(onetime, fn);
13914 calledFunctions.set(onetime, callCount);
13915
13916 return onetime;
13917};
13918
13919var onetime = oneTime;
13920// TODO: Remove this for the next major release
13921var default_1$2 = oneTime;
13922
13923var callCount = fn => {
13924 if (!calledFunctions.has(fn)) {
13925 throw new Error(`The given function \`${fn.name}\` is not wrapped by the \`onetime\` package`);
13926 }
13927
13928 return calledFunctions.get(fn);
13929};
13930onetime.default = default_1$2;
13931onetime.callCount = callCount;
13932
13933var restoreCursor = onetime(() => {
13934 signalExit(() => {
13935 process.stderr.write('\u001B[?25h');
13936 }, {alwaysLast: true});
13937});
13938
13939var cliCursor = createCommonjsModule(function (module, exports) {
13940
13941
13942let isHidden = false;
13943
13944exports.show = (writableStream = process.stderr) => {
13945 if (!writableStream.isTTY) {
13946 return;
13947 }
13948
13949 isHidden = false;
13950 writableStream.write('\u001B[?25h');
13951};
13952
13953exports.hide = (writableStream = process.stderr) => {
13954 if (!writableStream.isTTY) {
13955 return;
13956 }
13957
13958 restoreCursor();
13959 isHidden = true;
13960 writableStream.write('\u001B[?25l');
13961};
13962
13963exports.toggle = (force, writableStream) => {
13964 if (force !== undefined) {
13965 isHidden = force;
13966 }
13967
13968 if (isHidden) {
13969 exports.show(writableStream);
13970 } else {
13971 exports.hide(writableStream);
13972 }
13973};
13974});
13975var cliCursor_1 = cliCursor.show;
13976var cliCursor_2 = cliCursor.hide;
13977var cliCursor_3 = cliCursor.toggle;
13978
13979var dots = {
13980 interval: 80,
13981 frames: [
13982 "⠋",
13983 "⠙",
13984 "⠹",
13985 "⠸",
13986 "⠼",
13987 "⠴",
13988 "⠦",
13989 "⠧",
13990 "⠇",
13991 "⠏"
13992 ]
13993};
13994var dots2 = {
13995 interval: 80,
13996 frames: [
13997 "⣾",
13998 "⣽",
13999 "⣻",
14000 "⢿",
14001 "⡿",
14002 "⣟",
14003 "⣯",
14004 "⣷"
14005 ]
14006};
14007var dots3 = {
14008 interval: 80,
14009 frames: [
14010 "⠋",
14011 "⠙",
14012 "⠚",
14013 "⠞",
14014 "⠖",
14015 "⠦",
14016 "⠴",
14017 "⠲",
14018 "⠳",
14019 "⠓"
14020 ]
14021};
14022var dots4 = {
14023 interval: 80,
14024 frames: [
14025 "⠄",
14026 "⠆",
14027 "⠇",
14028 "⠋",
14029 "⠙",
14030 "⠸",
14031 "⠰",
14032 "⠠",
14033 "⠰",
14034 "⠸",
14035 "⠙",
14036 "⠋",
14037 "⠇",
14038 "⠆"
14039 ]
14040};
14041var dots5 = {
14042 interval: 80,
14043 frames: [
14044 "⠋",
14045 "⠙",
14046 "⠚",
14047 "⠒",
14048 "⠂",
14049 "⠂",
14050 "⠒",
14051 "⠲",
14052 "⠴",
14053 "⠦",
14054 "⠖",
14055 "⠒",
14056 "⠐",
14057 "⠐",
14058 "⠒",
14059 "⠓",
14060 "⠋"
14061 ]
14062};
14063var dots6 = {
14064 interval: 80,
14065 frames: [
14066 "⠁",
14067 "⠉",
14068 "⠙",
14069 "⠚",
14070 "⠒",
14071 "⠂",
14072 "⠂",
14073 "⠒",
14074 "⠲",
14075 "⠴",
14076 "⠤",
14077 "⠄",
14078 "⠄",
14079 "⠤",
14080 "⠴",
14081 "⠲",
14082 "⠒",
14083 "⠂",
14084 "⠂",
14085 "⠒",
14086 "⠚",
14087 "⠙",
14088 "⠉",
14089 "⠁"
14090 ]
14091};
14092var dots7 = {
14093 interval: 80,
14094 frames: [
14095 "⠈",
14096 "⠉",
14097 "⠋",
14098 "⠓",
14099 "⠒",
14100 "⠐",
14101 "⠐",
14102 "⠒",
14103 "⠖",
14104 "⠦",
14105 "⠤",
14106 "⠠",
14107 "⠠",
14108 "⠤",
14109 "⠦",
14110 "⠖",
14111 "⠒",
14112 "⠐",
14113 "⠐",
14114 "⠒",
14115 "⠓",
14116 "⠋",
14117 "⠉",
14118 "⠈"
14119 ]
14120};
14121var dots8 = {
14122 interval: 80,
14123 frames: [
14124 "⠁",
14125 "⠁",
14126 "⠉",
14127 "⠙",
14128 "⠚",
14129 "⠒",
14130 "⠂",
14131 "⠂",
14132 "⠒",
14133 "⠲",
14134 "⠴",
14135 "⠤",
14136 "⠄",
14137 "⠄",
14138 "⠤",
14139 "⠠",
14140 "⠠",
14141 "⠤",
14142 "⠦",
14143 "⠖",
14144 "⠒",
14145 "⠐",
14146 "⠐",
14147 "⠒",
14148 "⠓",
14149 "⠋",
14150 "⠉",
14151 "⠈",
14152 "⠈"
14153 ]
14154};
14155var dots9 = {
14156 interval: 80,
14157 frames: [
14158 "⢹",
14159 "⢺",
14160 "⢼",
14161 "⣸",
14162 "⣇",
14163 "⡧",
14164 "⡗",
14165 "⡏"
14166 ]
14167};
14168var dots10 = {
14169 interval: 80,
14170 frames: [
14171 "⢄",
14172 "⢂",
14173 "⢁",
14174 "⡁",
14175 "⡈",
14176 "⡐",
14177 "⡠"
14178 ]
14179};
14180var dots11 = {
14181 interval: 100,
14182 frames: [
14183 "⠁",
14184 "⠂",
14185 "⠄",
14186 "⡀",
14187 "⢀",
14188 "⠠",
14189 "⠐",
14190 "⠈"
14191 ]
14192};
14193var dots12 = {
14194 interval: 80,
14195 frames: [
14196 "⢀⠀",
14197 "⡀⠀",
14198 "⠄⠀",
14199 "⢂⠀",
14200 "⡂⠀",
14201 "⠅⠀",
14202 "⢃⠀",
14203 "⡃⠀",
14204 "⠍⠀",
14205 "⢋⠀",
14206 "⡋⠀",
14207 "⠍⠁",
14208 "⢋⠁",
14209 "⡋⠁",
14210 "⠍⠉",
14211 "⠋⠉",
14212 "⠋⠉",
14213 "⠉⠙",
14214 "⠉⠙",
14215 "⠉⠩",
14216 "⠈⢙",
14217 "⠈⡙",
14218 "⢈⠩",
14219 "⡀⢙",
14220 "⠄⡙",
14221 "⢂⠩",
14222 "⡂⢘",
14223 "⠅⡘",
14224 "⢃⠨",
14225 "⡃⢐",
14226 "⠍⡐",
14227 "⢋⠠",
14228 "⡋⢀",
14229 "⠍⡁",
14230 "⢋⠁",
14231 "⡋⠁",
14232 "⠍⠉",
14233 "⠋⠉",
14234 "⠋⠉",
14235 "⠉⠙",
14236 "⠉⠙",
14237 "⠉⠩",
14238 "⠈⢙",
14239 "⠈⡙",
14240 "⠈⠩",
14241 "⠀⢙",
14242 "⠀⡙",
14243 "⠀⠩",
14244 "⠀⢘",
14245 "⠀⡘",
14246 "⠀⠨",
14247 "⠀⢐",
14248 "⠀⡐",
14249 "⠀⠠",
14250 "⠀⢀",
14251 "⠀⡀"
14252 ]
14253};
14254var line = {
14255 interval: 130,
14256 frames: [
14257 "-",
14258 "\\",
14259 "|",
14260 "/"
14261 ]
14262};
14263var line2 = {
14264 interval: 100,
14265 frames: [
14266 "⠂",
14267 "-",
14268 "–",
14269 "—",
14270 "–",
14271 "-"
14272 ]
14273};
14274var pipe$3 = {
14275 interval: 100,
14276 frames: [
14277 "┤",
14278 "┘",
14279 "┴",
14280 "└",
14281 "├",
14282 "┌",
14283 "┬",
14284 "┐"
14285 ]
14286};
14287var simpleDots = {
14288 interval: 400,
14289 frames: [
14290 ". ",
14291 ".. ",
14292 "...",
14293 " "
14294 ]
14295};
14296var simpleDotsScrolling = {
14297 interval: 200,
14298 frames: [
14299 ". ",
14300 ".. ",
14301 "...",
14302 " ..",
14303 " .",
14304 " "
14305 ]
14306};
14307var star = {
14308 interval: 70,
14309 frames: [
14310 "✶",
14311 "✸",
14312 "✹",
14313 "✺",
14314 "✹",
14315 "✷"
14316 ]
14317};
14318var star2 = {
14319 interval: 80,
14320 frames: [
14321 "+",
14322 "x",
14323 "*"
14324 ]
14325};
14326var flip = {
14327 interval: 70,
14328 frames: [
14329 "_",
14330 "_",
14331 "_",
14332 "-",
14333 "`",
14334 "`",
14335 "'",
14336 "´",
14337 "-",
14338 "_",
14339 "_",
14340 "_"
14341 ]
14342};
14343var hamburger = {
14344 interval: 100,
14345 frames: [
14346 "☱",
14347 "☲",
14348 "☴"
14349 ]
14350};
14351var growVertical = {
14352 interval: 120,
14353 frames: [
14354 "▁",
14355 "▃",
14356 "▄",
14357 "▅",
14358 "▆",
14359 "▇",
14360 "▆",
14361 "▅",
14362 "▄",
14363 "▃"
14364 ]
14365};
14366var growHorizontal = {
14367 interval: 120,
14368 frames: [
14369 "▏",
14370 "▎",
14371 "▍",
14372 "▌",
14373 "▋",
14374 "▊",
14375 "▉",
14376 "▊",
14377 "▋",
14378 "▌",
14379 "▍",
14380 "▎"
14381 ]
14382};
14383var balloon = {
14384 interval: 140,
14385 frames: [
14386 " ",
14387 ".",
14388 "o",
14389 "O",
14390 "@",
14391 "*",
14392 " "
14393 ]
14394};
14395var balloon2 = {
14396 interval: 120,
14397 frames: [
14398 ".",
14399 "o",
14400 "O",
14401 "°",
14402 "O",
14403 "o",
14404 "."
14405 ]
14406};
14407var noise = {
14408 interval: 100,
14409 frames: [
14410 "▓",
14411 "▒",
14412 "░"
14413 ]
14414};
14415var bounce = {
14416 interval: 120,
14417 frames: [
14418 "⠁",
14419 "⠂",
14420 "⠄",
14421 "⠂"
14422 ]
14423};
14424var boxBounce = {
14425 interval: 120,
14426 frames: [
14427 "▖",
14428 "▘",
14429 "▝",
14430 "▗"
14431 ]
14432};
14433var boxBounce2 = {
14434 interval: 100,
14435 frames: [
14436 "▌",
14437 "▀",
14438 "▐",
14439 "▄"
14440 ]
14441};
14442var triangle = {
14443 interval: 50,
14444 frames: [
14445 "◢",
14446 "◣",
14447 "◤",
14448 "◥"
14449 ]
14450};
14451var arc = {
14452 interval: 100,
14453 frames: [
14454 "◜",
14455 "◠",
14456 "◝",
14457 "◞",
14458 "◡",
14459 "◟"
14460 ]
14461};
14462var circle = {
14463 interval: 120,
14464 frames: [
14465 "◡",
14466 "⊙",
14467 "◠"
14468 ]
14469};
14470var squareCorners = {
14471 interval: 180,
14472 frames: [
14473 "◰",
14474 "◳",
14475 "◲",
14476 "◱"
14477 ]
14478};
14479var circleQuarters = {
14480 interval: 120,
14481 frames: [
14482 "◴",
14483 "◷",
14484 "◶",
14485 "◵"
14486 ]
14487};
14488var circleHalves = {
14489 interval: 50,
14490 frames: [
14491 "◐",
14492 "◓",
14493 "◑",
14494 "◒"
14495 ]
14496};
14497var squish = {
14498 interval: 100,
14499 frames: [
14500 "╫",
14501 "╪"
14502 ]
14503};
14504var toggle = {
14505 interval: 250,
14506 frames: [
14507 "⊶",
14508 "⊷"
14509 ]
14510};
14511var toggle2 = {
14512 interval: 80,
14513 frames: [
14514 "▫",
14515 "▪"
14516 ]
14517};
14518var toggle3 = {
14519 interval: 120,
14520 frames: [
14521 "□",
14522 "■"
14523 ]
14524};
14525var toggle4 = {
14526 interval: 100,
14527 frames: [
14528 "■",
14529 "□",
14530 "▪",
14531 "▫"
14532 ]
14533};
14534var toggle5 = {
14535 interval: 100,
14536 frames: [
14537 "▮",
14538 "▯"
14539 ]
14540};
14541var toggle6 = {
14542 interval: 300,
14543 frames: [
14544 "ဝ",
14545 "၀"
14546 ]
14547};
14548var toggle7 = {
14549 interval: 80,
14550 frames: [
14551 "⦾",
14552 "⦿"
14553 ]
14554};
14555var toggle8 = {
14556 interval: 100,
14557 frames: [
14558 "◍",
14559 "◌"
14560 ]
14561};
14562var toggle9 = {
14563 interval: 100,
14564 frames: [
14565 "◉",
14566 "◎"
14567 ]
14568};
14569var toggle10 = {
14570 interval: 100,
14571 frames: [
14572 "㊂",
14573 "㊀",
14574 "㊁"
14575 ]
14576};
14577var toggle11 = {
14578 interval: 50,
14579 frames: [
14580 "⧇",
14581 "⧆"
14582 ]
14583};
14584var toggle12 = {
14585 interval: 120,
14586 frames: [
14587 "☗",
14588 "☖"
14589 ]
14590};
14591var toggle13 = {
14592 interval: 80,
14593 frames: [
14594 "=",
14595 "*",
14596 "-"
14597 ]
14598};
14599var arrow = {
14600 interval: 100,
14601 frames: [
14602 "←",
14603 "↖",
14604 "↑",
14605 "↗",
14606 "→",
14607 "↘",
14608 "↓",
14609 "↙"
14610 ]
14611};
14612var arrow2 = {
14613 interval: 80,
14614 frames: [
14615 "⬆️ ",
14616 "↗️ ",
14617 "➡️ ",
14618 "↘️ ",
14619 "⬇️ ",
14620 "↙️ ",
14621 "⬅️ ",
14622 "↖️ "
14623 ]
14624};
14625var arrow3 = {
14626 interval: 120,
14627 frames: [
14628 "▹▹▹▹▹",
14629 "▸▹▹▹▹",
14630 "▹▸▹▹▹",
14631 "▹▹▸▹▹",
14632 "▹▹▹▸▹",
14633 "▹▹▹▹▸"
14634 ]
14635};
14636var bouncingBar = {
14637 interval: 80,
14638 frames: [
14639 "[ ]",
14640 "[= ]",
14641 "[== ]",
14642 "[=== ]",
14643 "[ ===]",
14644 "[ ==]",
14645 "[ =]",
14646 "[ ]",
14647 "[ =]",
14648 "[ ==]",
14649 "[ ===]",
14650 "[====]",
14651 "[=== ]",
14652 "[== ]",
14653 "[= ]"
14654 ]
14655};
14656var bouncingBall = {
14657 interval: 80,
14658 frames: [
14659 "( ● )",
14660 "( ● )",
14661 "( ● )",
14662 "( ● )",
14663 "( ●)",
14664 "( ● )",
14665 "( ● )",
14666 "( ● )",
14667 "( ● )",
14668 "(● )"
14669 ]
14670};
14671var smiley = {
14672 interval: 200,
14673 frames: [
14674 "😄 ",
14675 "😝 "
14676 ]
14677};
14678var monkey = {
14679 interval: 300,
14680 frames: [
14681 "🙈 ",
14682 "🙈 ",
14683 "🙉 ",
14684 "🙊 "
14685 ]
14686};
14687var hearts = {
14688 interval: 100,
14689 frames: [
14690 "💛 ",
14691 "💙 ",
14692 "💜 ",
14693 "💚 ",
14694 "❤️ "
14695 ]
14696};
14697var clock = {
14698 interval: 100,
14699 frames: [
14700 "🕛 ",
14701 "🕐 ",
14702 "🕑 ",
14703 "🕒 ",
14704 "🕓 ",
14705 "🕔 ",
14706 "🕕 ",
14707 "🕖 ",
14708 "🕗 ",
14709 "🕘 ",
14710 "🕙 ",
14711 "🕚 "
14712 ]
14713};
14714var earth = {
14715 interval: 180,
14716 frames: [
14717 "🌍 ",
14718 "🌎 ",
14719 "🌏 "
14720 ]
14721};
14722var moon = {
14723 interval: 80,
14724 frames: [
14725 "🌑 ",
14726 "🌒 ",
14727 "🌓 ",
14728 "🌔 ",
14729 "🌕 ",
14730 "🌖 ",
14731 "🌗 ",
14732 "🌘 "
14733 ]
14734};
14735var runner = {
14736 interval: 140,
14737 frames: [
14738 "🚶 ",
14739 "🏃 "
14740 ]
14741};
14742var pong = {
14743 interval: 80,
14744 frames: [
14745 "▐⠂ ▌",
14746 "▐⠈ ▌",
14747 "▐ ⠂ ▌",
14748 "▐ ⠠ ▌",
14749 "▐ ⡀ ▌",
14750 "▐ ⠠ ▌",
14751 "▐ ⠂ ▌",
14752 "▐ ⠈ ▌",
14753 "▐ ⠂ ▌",
14754 "▐ ⠠ ▌",
14755 "▐ ⡀ ▌",
14756 "▐ ⠠ ▌",
14757 "▐ ⠂ ▌",
14758 "▐ ⠈ ▌",
14759 "▐ ⠂▌",
14760 "▐ ⠠▌",
14761 "▐ ⡀▌",
14762 "▐ ⠠ ▌",
14763 "▐ ⠂ ▌",
14764 "▐ ⠈ ▌",
14765 "▐ ⠂ ▌",
14766 "▐ ⠠ ▌",
14767 "▐ ⡀ ▌",
14768 "▐ ⠠ ▌",
14769 "▐ ⠂ ▌",
14770 "▐ ⠈ ▌",
14771 "▐ ⠂ ▌",
14772 "▐ ⠠ ▌",
14773 "▐ ⡀ ▌",
14774 "▐⠠ ▌"
14775 ]
14776};
14777var shark = {
14778 interval: 120,
14779 frames: [
14780 "▐|\\____________▌",
14781 "▐_|\\___________▌",
14782 "▐__|\\__________▌",
14783 "▐___|\\_________▌",
14784 "▐____|\\________▌",
14785 "▐_____|\\_______▌",
14786 "▐______|\\______▌",
14787 "▐_______|\\_____▌",
14788 "▐________|\\____▌",
14789 "▐_________|\\___▌",
14790 "▐__________|\\__▌",
14791 "▐___________|\\_▌",
14792 "▐____________|\\▌",
14793 "▐____________/|▌",
14794 "▐___________/|_▌",
14795 "▐__________/|__▌",
14796 "▐_________/|___▌",
14797 "▐________/|____▌",
14798 "▐_______/|_____▌",
14799 "▐______/|______▌",
14800 "▐_____/|_______▌",
14801 "▐____/|________▌",
14802 "▐___/|_________▌",
14803 "▐__/|__________▌",
14804 "▐_/|___________▌",
14805 "▐/|____________▌"
14806 ]
14807};
14808var dqpb = {
14809 interval: 100,
14810 frames: [
14811 "d",
14812 "q",
14813 "p",
14814 "b"
14815 ]
14816};
14817var weather = {
14818 interval: 100,
14819 frames: [
14820 "☀️ ",
14821 "☀️ ",
14822 "☀️ ",
14823 "🌤 ",
14824 "⛅️ ",
14825 "🌥 ",
14826 "☁️ ",
14827 "🌧 ",
14828 "🌨 ",
14829 "🌧 ",
14830 "🌨 ",
14831 "🌧 ",
14832 "🌨 ",
14833 "⛈ ",
14834 "🌨 ",
14835 "🌧 ",
14836 "🌨 ",
14837 "☁️ ",
14838 "🌥 ",
14839 "⛅️ ",
14840 "🌤 ",
14841 "☀️ ",
14842 "☀️ "
14843 ]
14844};
14845var christmas = {
14846 interval: 400,
14847 frames: [
14848 "🌲",
14849 "🎄"
14850 ]
14851};
14852var grenade = {
14853 interval: 80,
14854 frames: [
14855 "، ",
14856 "′ ",
14857 " ´ ",
14858 " ‾ ",
14859 " ⸌",
14860 " ⸊",
14861 " |",
14862 " ⁎",
14863 " ⁕",
14864 " ෴ ",
14865 " ⁓",
14866 " ",
14867 " ",
14868 " "
14869 ]
14870};
14871var point = {
14872 interval: 125,
14873 frames: [
14874 "∙∙∙",
14875 "●∙∙",
14876 "∙●∙",
14877 "∙∙●",
14878 "∙∙∙"
14879 ]
14880};
14881var layer = {
14882 interval: 150,
14883 frames: [
14884 "-",
14885 "=",
14886 "≡"
14887 ]
14888};
14889var betaWave = {
14890 interval: 80,
14891 frames: [
14892 "ρββββββ",
14893 "βρβββββ",
14894 "ββρββββ",
14895 "βββρβββ",
14896 "ββββρββ",
14897 "βββββρβ",
14898 "ββββββρ"
14899 ]
14900};
14901var spinners = {
14902 dots: dots,
14903 dots2: dots2,
14904 dots3: dots3,
14905 dots4: dots4,
14906 dots5: dots5,
14907 dots6: dots6,
14908 dots7: dots7,
14909 dots8: dots8,
14910 dots9: dots9,
14911 dots10: dots10,
14912 dots11: dots11,
14913 dots12: dots12,
14914 line: line,
14915 line2: line2,
14916 pipe: pipe$3,
14917 simpleDots: simpleDots,
14918 simpleDotsScrolling: simpleDotsScrolling,
14919 star: star,
14920 star2: star2,
14921 flip: flip,
14922 hamburger: hamburger,
14923 growVertical: growVertical,
14924 growHorizontal: growHorizontal,
14925 balloon: balloon,
14926 balloon2: balloon2,
14927 noise: noise,
14928 bounce: bounce,
14929 boxBounce: boxBounce,
14930 boxBounce2: boxBounce2,
14931 triangle: triangle,
14932 arc: arc,
14933 circle: circle,
14934 squareCorners: squareCorners,
14935 circleQuarters: circleQuarters,
14936 circleHalves: circleHalves,
14937 squish: squish,
14938 toggle: toggle,
14939 toggle2: toggle2,
14940 toggle3: toggle3,
14941 toggle4: toggle4,
14942 toggle5: toggle5,
14943 toggle6: toggle6,
14944 toggle7: toggle7,
14945 toggle8: toggle8,
14946 toggle9: toggle9,
14947 toggle10: toggle10,
14948 toggle11: toggle11,
14949 toggle12: toggle12,
14950 toggle13: toggle13,
14951 arrow: arrow,
14952 arrow2: arrow2,
14953 arrow3: arrow3,
14954 bouncingBar: bouncingBar,
14955 bouncingBall: bouncingBall,
14956 smiley: smiley,
14957 monkey: monkey,
14958 hearts: hearts,
14959 clock: clock,
14960 earth: earth,
14961 moon: moon,
14962 runner: runner,
14963 pong: pong,
14964 shark: shark,
14965 dqpb: dqpb,
14966 weather: weather,
14967 christmas: christmas,
14968 grenade: grenade,
14969 point: point,
14970 layer: layer,
14971 betaWave: betaWave
14972};
14973
14974var spinners$1 = /*#__PURE__*/Object.freeze({
14975 __proto__: null,
14976 dots: dots,
14977 dots2: dots2,
14978 dots3: dots3,
14979 dots4: dots4,
14980 dots5: dots5,
14981 dots6: dots6,
14982 dots7: dots7,
14983 dots8: dots8,
14984 dots9: dots9,
14985 dots10: dots10,
14986 dots11: dots11,
14987 dots12: dots12,
14988 line: line,
14989 line2: line2,
14990 pipe: pipe$3,
14991 simpleDots: simpleDots,
14992 simpleDotsScrolling: simpleDotsScrolling,
14993 star: star,
14994 star2: star2,
14995 flip: flip,
14996 hamburger: hamburger,
14997 growVertical: growVertical,
14998 growHorizontal: growHorizontal,
14999 balloon: balloon,
15000 balloon2: balloon2,
15001 noise: noise,
15002 bounce: bounce,
15003 boxBounce: boxBounce,
15004 boxBounce2: boxBounce2,
15005 triangle: triangle,
15006 arc: arc,
15007 circle: circle,
15008 squareCorners: squareCorners,
15009 circleQuarters: circleQuarters,
15010 circleHalves: circleHalves,
15011 squish: squish,
15012 toggle: toggle,
15013 toggle2: toggle2,
15014 toggle3: toggle3,
15015 toggle4: toggle4,
15016 toggle5: toggle5,
15017 toggle6: toggle6,
15018 toggle7: toggle7,
15019 toggle8: toggle8,
15020 toggle9: toggle9,
15021 toggle10: toggle10,
15022 toggle11: toggle11,
15023 toggle12: toggle12,
15024 toggle13: toggle13,
15025 arrow: arrow,
15026 arrow2: arrow2,
15027 arrow3: arrow3,
15028 bouncingBar: bouncingBar,
15029 bouncingBall: bouncingBall,
15030 smiley: smiley,
15031 monkey: monkey,
15032 hearts: hearts,
15033 clock: clock,
15034 earth: earth,
15035 moon: moon,
15036 runner: runner,
15037 pong: pong,
15038 shark: shark,
15039 dqpb: dqpb,
15040 weather: weather,
15041 christmas: christmas,
15042 grenade: grenade,
15043 point: point,
15044 layer: layer,
15045 betaWave: betaWave,
15046 'default': spinners
15047});
15048
15049var require$$0 = getCjsExportFromNamespace(spinners$1);
15050
15051const spinners$2 = Object.assign({}, require$$0);
15052
15053var cliSpinners = spinners$2;
15054// TODO: Remove this for the next major release
15055var default_1$3 = spinners$2;
15056cliSpinners.default = default_1$3;
15057
15058const isSupported = process.platform !== 'win32' || process.env.CI || process.env.TERM === 'xterm-256color';
15059
15060const main$1 = {
15061 info: chalk.blue('ℹ'),
15062 success: chalk.green('✔'),
15063 warning: chalk.yellow('⚠'),
15064 error: chalk.red('✖')
15065};
15066
15067const fallbacks = {
15068 info: chalk.blue('i'),
15069 success: chalk.green('√'),
15070 warning: chalk.yellow('‼'),
15071 error: chalk.red('×')
15072};
15073
15074var logSymbols = isSupported ? main$1 : fallbacks;
15075
15076var ansiRegex$3 = options => {
15077 options = Object.assign({
15078 onlyFirst: false
15079 }, options);
15080
15081 const pattern = [
15082 '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)',
15083 '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))'
15084 ].join('|');
15085
15086 return new RegExp(pattern, options.onlyFirst ? undefined : 'g');
15087};
15088
15089const stripAnsi$2 = string => typeof string === 'string' ? string.replace(ansiRegex$3(), '') : string;
15090
15091var stripAnsi_1 = stripAnsi$2;
15092var default_1$4 = stripAnsi$2;
15093stripAnsi_1.default = default_1$4;
15094
15095var clone_1 = createCommonjsModule(function (module) {
15096var clone = (function() {
15097
15098/**
15099 * Clones (copies) an Object using deep copying.
15100 *
15101 * This function supports circular references by default, but if you are certain
15102 * there are no circular references in your object, you can save some CPU time
15103 * by calling clone(obj, false).
15104 *
15105 * Caution: if `circular` is false and `parent` contains circular references,
15106 * your program may enter an infinite loop and crash.
15107 *
15108 * @param `parent` - the object to be cloned
15109 * @param `circular` - set to true if the object to be cloned may contain
15110 * circular references. (optional - true by default)
15111 * @param `depth` - set to a number if the object is only to be cloned to
15112 * a particular depth. (optional - defaults to Infinity)
15113 * @param `prototype` - sets the prototype to be used when cloning an object.
15114 * (optional - defaults to parent prototype).
15115*/
15116function clone(parent, circular, depth, prototype) {
15117 var filter;
15118 if (typeof circular === 'object') {
15119 depth = circular.depth;
15120 prototype = circular.prototype;
15121 filter = circular.filter;
15122 circular = circular.circular;
15123 }
15124 // maintain two arrays for circular references, where corresponding parents
15125 // and children have the same index
15126 var allParents = [];
15127 var allChildren = [];
15128
15129 var useBuffer = typeof Buffer != 'undefined';
15130
15131 if (typeof circular == 'undefined')
15132 circular = true;
15133
15134 if (typeof depth == 'undefined')
15135 depth = Infinity;
15136
15137 // recurse this function so we don't reset allParents and allChildren
15138 function _clone(parent, depth) {
15139 // cloning null always returns null
15140 if (parent === null)
15141 return null;
15142
15143 if (depth == 0)
15144 return parent;
15145
15146 var child;
15147 var proto;
15148 if (typeof parent != 'object') {
15149 return parent;
15150 }
15151
15152 if (clone.__isArray(parent)) {
15153 child = [];
15154 } else if (clone.__isRegExp(parent)) {
15155 child = new RegExp(parent.source, __getRegExpFlags(parent));
15156 if (parent.lastIndex) child.lastIndex = parent.lastIndex;
15157 } else if (clone.__isDate(parent)) {
15158 child = new Date(parent.getTime());
15159 } else if (useBuffer && Buffer.isBuffer(parent)) {
15160 if (Buffer.allocUnsafe) {
15161 // Node.js >= 4.5.0
15162 child = Buffer.allocUnsafe(parent.length);
15163 } else {
15164 // Older Node.js versions
15165 child = new Buffer(parent.length);
15166 }
15167 parent.copy(child);
15168 return child;
15169 } else {
15170 if (typeof prototype == 'undefined') {
15171 proto = Object.getPrototypeOf(parent);
15172 child = Object.create(proto);
15173 }
15174 else {
15175 child = Object.create(prototype);
15176 proto = prototype;
15177 }
15178 }
15179
15180 if (circular) {
15181 var index = allParents.indexOf(parent);
15182
15183 if (index != -1) {
15184 return allChildren[index];
15185 }
15186 allParents.push(parent);
15187 allChildren.push(child);
15188 }
15189
15190 for (var i in parent) {
15191 var attrs;
15192 if (proto) {
15193 attrs = Object.getOwnPropertyDescriptor(proto, i);
15194 }
15195
15196 if (attrs && attrs.set == null) {
15197 continue;
15198 }
15199 child[i] = _clone(parent[i], depth - 1);
15200 }
15201
15202 return child;
15203 }
15204
15205 return _clone(parent, depth);
15206}
15207
15208/**
15209 * Simple flat clone using prototype, accepts only objects, usefull for property
15210 * override on FLAT configuration object (no nested props).
15211 *
15212 * USE WITH CAUTION! This may not behave as you wish if you do not know how this
15213 * works.
15214 */
15215clone.clonePrototype = function clonePrototype(parent) {
15216 if (parent === null)
15217 return null;
15218
15219 var c = function () {};
15220 c.prototype = parent;
15221 return new c();
15222};
15223
15224// private utility functions
15225
15226function __objToStr(o) {
15227 return Object.prototype.toString.call(o);
15228}clone.__objToStr = __objToStr;
15229
15230function __isDate(o) {
15231 return typeof o === 'object' && __objToStr(o) === '[object Date]';
15232}clone.__isDate = __isDate;
15233
15234function __isArray(o) {
15235 return typeof o === 'object' && __objToStr(o) === '[object Array]';
15236}clone.__isArray = __isArray;
15237
15238function __isRegExp(o) {
15239 return typeof o === 'object' && __objToStr(o) === '[object RegExp]';
15240}clone.__isRegExp = __isRegExp;
15241
15242function __getRegExpFlags(re) {
15243 var flags = '';
15244 if (re.global) flags += 'g';
15245 if (re.ignoreCase) flags += 'i';
15246 if (re.multiline) flags += 'm';
15247 return flags;
15248}clone.__getRegExpFlags = __getRegExpFlags;
15249
15250return clone;
15251})();
15252
15253if ( module.exports) {
15254 module.exports = clone;
15255}
15256});
15257
15258var defaults$3 = function(options, defaults) {
15259 options = options || {};
15260
15261 Object.keys(defaults).forEach(function(key) {
15262 if (typeof options[key] === 'undefined') {
15263 options[key] = clone_1(defaults[key]);
15264 }
15265 });
15266
15267 return options;
15268};
15269
15270var combining = [
15271 [ 0x0300, 0x036F ], [ 0x0483, 0x0486 ], [ 0x0488, 0x0489 ],
15272 [ 0x0591, 0x05BD ], [ 0x05BF, 0x05BF ], [ 0x05C1, 0x05C2 ],
15273 [ 0x05C4, 0x05C5 ], [ 0x05C7, 0x05C7 ], [ 0x0600, 0x0603 ],
15274 [ 0x0610, 0x0615 ], [ 0x064B, 0x065E ], [ 0x0670, 0x0670 ],
15275 [ 0x06D6, 0x06E4 ], [ 0x06E7, 0x06E8 ], [ 0x06EA, 0x06ED ],
15276 [ 0x070F, 0x070F ], [ 0x0711, 0x0711 ], [ 0x0730, 0x074A ],
15277 [ 0x07A6, 0x07B0 ], [ 0x07EB, 0x07F3 ], [ 0x0901, 0x0902 ],
15278 [ 0x093C, 0x093C ], [ 0x0941, 0x0948 ], [ 0x094D, 0x094D ],
15279 [ 0x0951, 0x0954 ], [ 0x0962, 0x0963 ], [ 0x0981, 0x0981 ],
15280 [ 0x09BC, 0x09BC ], [ 0x09C1, 0x09C4 ], [ 0x09CD, 0x09CD ],
15281 [ 0x09E2, 0x09E3 ], [ 0x0A01, 0x0A02 ], [ 0x0A3C, 0x0A3C ],
15282 [ 0x0A41, 0x0A42 ], [ 0x0A47, 0x0A48 ], [ 0x0A4B, 0x0A4D ],
15283 [ 0x0A70, 0x0A71 ], [ 0x0A81, 0x0A82 ], [ 0x0ABC, 0x0ABC ],
15284 [ 0x0AC1, 0x0AC5 ], [ 0x0AC7, 0x0AC8 ], [ 0x0ACD, 0x0ACD ],
15285 [ 0x0AE2, 0x0AE3 ], [ 0x0B01, 0x0B01 ], [ 0x0B3C, 0x0B3C ],
15286 [ 0x0B3F, 0x0B3F ], [ 0x0B41, 0x0B43 ], [ 0x0B4D, 0x0B4D ],
15287 [ 0x0B56, 0x0B56 ], [ 0x0B82, 0x0B82 ], [ 0x0BC0, 0x0BC0 ],
15288 [ 0x0BCD, 0x0BCD ], [ 0x0C3E, 0x0C40 ], [ 0x0C46, 0x0C48 ],
15289 [ 0x0C4A, 0x0C4D ], [ 0x0C55, 0x0C56 ], [ 0x0CBC, 0x0CBC ],
15290 [ 0x0CBF, 0x0CBF ], [ 0x0CC6, 0x0CC6 ], [ 0x0CCC, 0x0CCD ],
15291 [ 0x0CE2, 0x0CE3 ], [ 0x0D41, 0x0D43 ], [ 0x0D4D, 0x0D4D ],
15292 [ 0x0DCA, 0x0DCA ], [ 0x0DD2, 0x0DD4 ], [ 0x0DD6, 0x0DD6 ],
15293 [ 0x0E31, 0x0E31 ], [ 0x0E34, 0x0E3A ], [ 0x0E47, 0x0E4E ],
15294 [ 0x0EB1, 0x0EB1 ], [ 0x0EB4, 0x0EB9 ], [ 0x0EBB, 0x0EBC ],
15295 [ 0x0EC8, 0x0ECD ], [ 0x0F18, 0x0F19 ], [ 0x0F35, 0x0F35 ],
15296 [ 0x0F37, 0x0F37 ], [ 0x0F39, 0x0F39 ], [ 0x0F71, 0x0F7E ],
15297 [ 0x0F80, 0x0F84 ], [ 0x0F86, 0x0F87 ], [ 0x0F90, 0x0F97 ],
15298 [ 0x0F99, 0x0FBC ], [ 0x0FC6, 0x0FC6 ], [ 0x102D, 0x1030 ],
15299 [ 0x1032, 0x1032 ], [ 0x1036, 0x1037 ], [ 0x1039, 0x1039 ],
15300 [ 0x1058, 0x1059 ], [ 0x1160, 0x11FF ], [ 0x135F, 0x135F ],
15301 [ 0x1712, 0x1714 ], [ 0x1732, 0x1734 ], [ 0x1752, 0x1753 ],
15302 [ 0x1772, 0x1773 ], [ 0x17B4, 0x17B5 ], [ 0x17B7, 0x17BD ],
15303 [ 0x17C6, 0x17C6 ], [ 0x17C9, 0x17D3 ], [ 0x17DD, 0x17DD ],
15304 [ 0x180B, 0x180D ], [ 0x18A9, 0x18A9 ], [ 0x1920, 0x1922 ],
15305 [ 0x1927, 0x1928 ], [ 0x1932, 0x1932 ], [ 0x1939, 0x193B ],
15306 [ 0x1A17, 0x1A18 ], [ 0x1B00, 0x1B03 ], [ 0x1B34, 0x1B34 ],
15307 [ 0x1B36, 0x1B3A ], [ 0x1B3C, 0x1B3C ], [ 0x1B42, 0x1B42 ],
15308 [ 0x1B6B, 0x1B73 ], [ 0x1DC0, 0x1DCA ], [ 0x1DFE, 0x1DFF ],
15309 [ 0x200B, 0x200F ], [ 0x202A, 0x202E ], [ 0x2060, 0x2063 ],
15310 [ 0x206A, 0x206F ], [ 0x20D0, 0x20EF ], [ 0x302A, 0x302F ],
15311 [ 0x3099, 0x309A ], [ 0xA806, 0xA806 ], [ 0xA80B, 0xA80B ],
15312 [ 0xA825, 0xA826 ], [ 0xFB1E, 0xFB1E ], [ 0xFE00, 0xFE0F ],
15313 [ 0xFE20, 0xFE23 ], [ 0xFEFF, 0xFEFF ], [ 0xFFF9, 0xFFFB ],
15314 [ 0x10A01, 0x10A03 ], [ 0x10A05, 0x10A06 ], [ 0x10A0C, 0x10A0F ],
15315 [ 0x10A38, 0x10A3A ], [ 0x10A3F, 0x10A3F ], [ 0x1D167, 0x1D169 ],
15316 [ 0x1D173, 0x1D182 ], [ 0x1D185, 0x1D18B ], [ 0x1D1AA, 0x1D1AD ],
15317 [ 0x1D242, 0x1D244 ], [ 0xE0001, 0xE0001 ], [ 0xE0020, 0xE007F ],
15318 [ 0xE0100, 0xE01EF ]
15319];
15320
15321var DEFAULTS = {
15322 nul: 0,
15323 control: 0
15324};
15325
15326var wcwidth_1 = function wcwidth(str) {
15327 return wcswidth(str, DEFAULTS)
15328};
15329
15330var config$1 = function(opts) {
15331 opts = defaults$3(opts || {}, DEFAULTS);
15332 return function wcwidth(str) {
15333 return wcswidth(str, opts)
15334 }
15335};
15336
15337/*
15338 * The following functions define the column width of an ISO 10646
15339 * character as follows:
15340 * - The null character (U+0000) has a column width of 0.
15341 * - Other C0/C1 control characters and DEL will lead to a return value
15342 * of -1.
15343 * - Non-spacing and enclosing combining characters (general category
15344 * code Mn or Me in the
15345 * Unicode database) have a column width of 0.
15346 * - SOFT HYPHEN (U+00AD) has a column width of 1.
15347 * - Other format characters (general category code Cf in the Unicode
15348 * database) and ZERO WIDTH
15349 * SPACE (U+200B) have a column width of 0.
15350 * - Hangul Jamo medial vowels and final consonants (U+1160-U+11FF)
15351 * have a column width of 0.
15352 * - Spacing characters in the East Asian Wide (W) or East Asian
15353 * Full-width (F) category as
15354 * defined in Unicode Technical Report #11 have a column width of 2.
15355 * - All remaining characters (including all printable ISO 8859-1 and
15356 * WGL4 characters, Unicode control characters, etc.) have a column
15357 * width of 1.
15358 * This implementation assumes that characters are encoded in ISO 10646.
15359*/
15360
15361function wcswidth(str, opts) {
15362 if (typeof str !== 'string') return wcwidth(str, opts)
15363
15364 var s = 0;
15365 for (var i = 0; i < str.length; i++) {
15366 var n = wcwidth(str.charCodeAt(i), opts);
15367 if (n < 0) return -1
15368 s += n;
15369 }
15370
15371 return s
15372}
15373
15374function wcwidth(ucs, opts) {
15375 // test for 8-bit control characters
15376 if (ucs === 0) return opts.nul
15377 if (ucs < 32 || (ucs >= 0x7f && ucs < 0xa0)) return opts.control
15378
15379 // binary search in table of non-spacing characters
15380 if (bisearch(ucs)) return 0
15381
15382 // if we arrive here, ucs is not a combining or C0/C1 control character
15383 return 1 +
15384 (ucs >= 0x1100 &&
15385 (ucs <= 0x115f || // Hangul Jamo init. consonants
15386 ucs == 0x2329 || ucs == 0x232a ||
15387 (ucs >= 0x2e80 && ucs <= 0xa4cf &&
15388 ucs != 0x303f) || // CJK ... Yi
15389 (ucs >= 0xac00 && ucs <= 0xd7a3) || // Hangul Syllables
15390 (ucs >= 0xf900 && ucs <= 0xfaff) || // CJK Compatibility Ideographs
15391 (ucs >= 0xfe10 && ucs <= 0xfe19) || // Vertical forms
15392 (ucs >= 0xfe30 && ucs <= 0xfe6f) || // CJK Compatibility Forms
15393 (ucs >= 0xff00 && ucs <= 0xff60) || // Fullwidth Forms
15394 (ucs >= 0xffe0 && ucs <= 0xffe6) ||
15395 (ucs >= 0x20000 && ucs <= 0x2fffd) ||
15396 (ucs >= 0x30000 && ucs <= 0x3fffd)));
15397}
15398
15399function bisearch(ucs) {
15400 var min = 0;
15401 var max = combining.length - 1;
15402 var mid;
15403
15404 if (ucs < combining[0][0] || ucs > combining[max][1]) return false
15405
15406 while (max >= min) {
15407 mid = Math.floor((min + max) / 2);
15408 if (ucs > combining[mid][1]) min = mid + 1;
15409 else if (ucs < combining[mid][0]) max = mid - 1;
15410 else return true
15411 }
15412
15413 return false
15414}
15415wcwidth_1.config = config$1;
15416
15417var isInteractive = ({stream = process.stdout} = {}) => {
15418 return Boolean(
15419 stream && stream.isTTY &&
15420 process.env.TERM !== 'dumb' &&
15421 !('CI' in process.env)
15422 );
15423};
15424
15425const TEXT = Symbol('text');
15426const PREFIX_TEXT = Symbol('prefixText');
15427
15428const noop$6 = () => {};
15429
15430const ASCII_ETX_CODE = 0x03; // Ctrl+C emits this code
15431
15432class Ora {
15433 constructor(options) {
15434 if (typeof options === 'string') {
15435 options = {
15436 text: options
15437 };
15438 }
15439
15440 this.options = {
15441 text: '',
15442 color: 'cyan',
15443 stream: process.stderr,
15444 discardStdin: true,
15445 ...options
15446 };
15447
15448 this.spinner = this.options.spinner;
15449
15450 this.color = this.options.color;
15451 this.hideCursor = this.options.hideCursor !== false;
15452 this.interval = this.options.interval || this.spinner.interval || 100;
15453 this.stream = this.options.stream;
15454 this.id = undefined;
15455 this.isEnabled = typeof this.options.isEnabled === 'boolean' ? this.options.isEnabled : isInteractive({stream: this.stream});
15456
15457 // Set *after* `this.stream`
15458 this.text = this.options.text;
15459 this.prefixText = this.options.prefixText;
15460 this.linesToClear = 0;
15461 this.indent = this.options.indent;
15462 this.discardStdin = this.options.discardStdin;
15463 }
15464
15465 get indent() {
15466 return this._indent;
15467 }
15468
15469 set indent(indent = 0) {
15470 if (!(indent >= 0 && Number.isInteger(indent))) {
15471 throw new Error('The `indent` option must be an integer from 0 and up');
15472 }
15473
15474 this._indent = indent;
15475 }
15476
15477 get spinner() {
15478 return this._spinner;
15479 }
15480
15481 set spinner(spinner) {
15482 this.frameIndex = 0;
15483
15484 if (typeof spinner === 'object') {
15485 if (spinner.frames === undefined) {
15486 throw new Error('The given spinner must have a `frames` property');
15487 }
15488
15489 if (spinner.interval !== undefined) {
15490 this.interval = spinner.interval;
15491 }
15492
15493 this._spinner = spinner;
15494 } else if (process.platform === 'win32') {
15495 this._spinner = cliSpinners.line;
15496 } else if (spinner === undefined) {
15497 // Set default spinner
15498 this._spinner = cliSpinners.dots;
15499 } else if (cliSpinners[spinner]) {
15500 this._spinner = cliSpinners[spinner];
15501 } else {
15502 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.`);
15503 }
15504 }
15505
15506 get text() {
15507 return this[TEXT];
15508 }
15509
15510 get prefixText() {
15511 return this[PREFIX_TEXT];
15512 }
15513
15514 get isSpinning() {
15515 return this.id !== undefined;
15516 }
15517
15518 updateLineCount() {
15519 const columns = this.stream.columns || 80;
15520 const fullPrefixText = (typeof this[PREFIX_TEXT] === 'string') ? this[PREFIX_TEXT] + '-' : '';
15521 this.lineCount = stripAnsi_1(fullPrefixText + '--' + this[TEXT]).split('\n').reduce((count, line) => {
15522 return count + Math.max(1, Math.ceil(wcwidth_1(line) / columns));
15523 }, 0);
15524 }
15525
15526 set text(value) {
15527 this[TEXT] = value;
15528 this.updateLineCount();
15529 }
15530
15531 set prefixText(value) {
15532 this[PREFIX_TEXT] = value;
15533 this.updateLineCount();
15534 }
15535
15536 frame() {
15537 const {frames} = this.spinner;
15538 let frame = frames[this.frameIndex];
15539
15540 if (this.color) {
15541 frame = chalk[this.color](frame);
15542 }
15543
15544 this.frameIndex = ++this.frameIndex % frames.length;
15545 const fullPrefixText = (typeof this.prefixText === 'string' && this.prefixText !== '') ? this.prefixText + ' ' : '';
15546 const fullText = typeof this.text === 'string' ? ' ' + this.text : '';
15547
15548 return fullPrefixText + frame + fullText;
15549 }
15550
15551 clear() {
15552 if (!this.isEnabled || !this.stream.isTTY) {
15553 return this;
15554 }
15555
15556 for (let i = 0; i < this.linesToClear; i++) {
15557 if (i > 0) {
15558 this.stream.moveCursor(0, -1);
15559 }
15560
15561 this.stream.clearLine();
15562 this.stream.cursorTo(this.indent);
15563 }
15564
15565 this.linesToClear = 0;
15566
15567 return this;
15568 }
15569
15570 render() {
15571 this.clear();
15572 this.stream.write(this.frame());
15573 this.linesToClear = this.lineCount;
15574
15575 return this;
15576 }
15577
15578 start(text) {
15579 if (text) {
15580 this.text = text;
15581 }
15582
15583 if (!this.isEnabled) {
15584 this.stream.write(`- ${this.text}\n`);
15585 return this;
15586 }
15587
15588 if (this.isSpinning) {
15589 return this;
15590 }
15591
15592 if (this.hideCursor) {
15593 cliCursor.hide(this.stream);
15594 }
15595
15596 if (this.discardStdin && process.stdin.isTTY) {
15597 this.startDiscardingStdin();
15598 }
15599
15600 this.render();
15601 this.id = setInterval(this.render.bind(this), this.interval);
15602
15603 return this;
15604 }
15605
15606 stop() {
15607 if (!this.isEnabled) {
15608 return this;
15609 }
15610
15611 clearInterval(this.id);
15612 this.id = undefined;
15613 this.frameIndex = 0;
15614 this.clear();
15615 if (this.hideCursor) {
15616 cliCursor.show(this.stream);
15617 }
15618
15619 if (this.discardStdin && process.stdin.isTTY) {
15620 this.stopDiscardingStdin();
15621 }
15622
15623 return this;
15624 }
15625
15626 startDiscardingStdin() {
15627 const {stdin} = process;
15628
15629 this._stdinOldRawMode = stdin.isRaw;
15630 this._stdinOldEmit = stdin.emit;
15631 this._stdinOldEmitOwnProperty = Object.prototype.hasOwnProperty.call(stdin, 'emit');
15632
15633 stdin.setRawMode(true);
15634 stdin.on('data', noop$6);
15635
15636 const self = this;
15637 stdin.emit = function (event, data, ...args) {
15638 if (event === 'data' && data.includes(ASCII_ETX_CODE)) {
15639 process.emit('SIGINT');
15640 }
15641
15642 self._stdinOldEmit.apply(this, [event, data, ...args]);
15643 };
15644 }
15645
15646 stopDiscardingStdin() {
15647 if (this._stdinOldEmit !== undefined) {
15648 const {stdin} = process;
15649 stdin.setRawMode(this._stdinOldRawMode);
15650 stdin.removeListener('data', noop$6);
15651
15652 if (stdin.listenerCount('data') === 0) {
15653 stdin.pause();
15654 }
15655
15656 if (this._stdinOldEmitOwnProperty) {
15657 stdin.emit = this._stdinOldEmit;
15658 } else {
15659 delete stdin.emit;
15660 }
15661
15662 this._stdinOldRawMode = undefined;
15663 this._stdinOldEmit = undefined;
15664 this._stdinOldEmitOwnProperty = undefined;
15665 }
15666 }
15667
15668 succeed(text) {
15669 return this.stopAndPersist({symbol: logSymbols.success, text});
15670 }
15671
15672 fail(text) {
15673 return this.stopAndPersist({symbol: logSymbols.error, text});
15674 }
15675
15676 warn(text) {
15677 return this.stopAndPersist({symbol: logSymbols.warning, text});
15678 }
15679
15680 info(text) {
15681 return this.stopAndPersist({symbol: logSymbols.info, text});
15682 }
15683
15684 stopAndPersist(options = {}) {
15685 const prefixText = options.prefixText || this.prefixText;
15686 const fullPrefixText = (typeof prefixText === 'string' && prefixText !== '') ? prefixText + ' ' : '';
15687 const text = options.text || this.text;
15688 const fullText = (typeof text === 'string') ? ' ' + text : '';
15689
15690 this.stop();
15691 this.stream.write(`${fullPrefixText}${options.symbol || ' '}${fullText}\n`);
15692
15693 return this;
15694 }
15695}
15696
15697const oraFactory = function (options) {
15698 return new Ora(options);
15699};
15700
15701var ora = oraFactory;
15702
15703var promise = (action, options) => {
15704 // eslint-disable-next-line promise/prefer-await-to-then
15705 if (typeof action.then !== 'function') {
15706 throw new TypeError('Parameter `action` must be a Promise');
15707 }
15708
15709 const spinner = new Ora(options);
15710 spinner.start();
15711
15712 (async () => {
15713 try {
15714 await action;
15715 spinner.succeed();
15716 } catch (_) {
15717 spinner.fail();
15718 }
15719 })();
15720
15721 return spinner;
15722};
15723ora.promise = promise;
15724
15725var toString$1 = Object.prototype.toString;
15726
15727var isPlainObj = function (x) {
15728 var prototype;
15729 return toString$1.call(x) === '[object Object]' && (prototype = Object.getPrototypeOf(x), prototype === null || prototype === Object.getPrototypeOf({}));
15730};
15731
15732var arrify = function (val) {
15733 if (val === null || val === undefined) {
15734 return [];
15735 }
15736
15737 return Array.isArray(val) ? val : [val];
15738};
15739
15740const push = (obj, prop, value) => {
15741 if (!obj[prop]) {
15742 obj[prop] = [];
15743 }
15744
15745 obj[prop].push(value);
15746};
15747
15748const insert = (obj, prop, key, value) => {
15749 if (!obj[prop]) {
15750 obj[prop] = {};
15751 }
15752
15753 obj[prop][key] = value;
15754};
15755
15756const passthroughOptions = ['stopEarly', 'unknown', '--'];
15757const availableTypes = ['string', 'boolean', 'number', 'array'];
15758
15759const buildOptions = options => {
15760 options = options || {};
15761
15762 const result = {};
15763
15764 passthroughOptions.forEach(key => {
15765 if (options[key]) {
15766 result[key] = options[key];
15767 }
15768 });
15769
15770 Object.keys(options).forEach(key => {
15771 let value = options[key];
15772
15773 if (key === 'arguments') {
15774 key = '_';
15775 }
15776
15777 // If short form is used
15778 // convert it to long form
15779 // e.g. { 'name': 'string' }
15780 if (typeof value === 'string') {
15781 value = {type: value};
15782 }
15783
15784 if (isPlainObj(value)) {
15785 const props = value;
15786 const {type} = props;
15787
15788 if (type) {
15789 if (!availableTypes.includes(type)) {
15790 throw new TypeError(`Expected "${key}" to be one of ["string", "boolean", "number", "array"], got ${type}`);
15791 }
15792
15793 push(result, type, key);
15794 }
15795
15796 const aliases = arrify(props.alias);
15797
15798 aliases.forEach(alias => {
15799 insert(result, 'alias', alias, key);
15800 });
15801
15802 if ({}.hasOwnProperty.call(props, 'default')) {
15803 if (type === 'array' && !Array.isArray(props.default)) {
15804 throw new TypeError(`Expected "${key}" default value to be array, got ${typeof props.default}`);
15805 }
15806
15807 if (type && type !== 'array' && typeof props.default !== type) {
15808 throw new TypeError(`Expected "${key}" default value to be ${type}, got ${typeof props.default}`);
15809 }
15810
15811 insert(result, 'default', key, props.default);
15812 }
15813 }
15814 });
15815
15816 return result;
15817};
15818
15819var minimistOptions = buildOptions;
15820var default_1$5 = buildOptions;
15821minimistOptions.default = default_1$5;
15822
15823var minimist = function (args, opts) {
15824 if (!opts) opts = {};
15825
15826 var flags = { bools : {}, strings : {}, unknownFn: null };
15827
15828 if (typeof opts['unknown'] === 'function') {
15829 flags.unknownFn = opts['unknown'];
15830 }
15831
15832 if (typeof opts['boolean'] === 'boolean' && opts['boolean']) {
15833 flags.allBools = true;
15834 } else {
15835 [].concat(opts['boolean']).filter(Boolean).forEach(function (key) {
15836 flags.bools[key] = true;
15837 });
15838 }
15839
15840 var aliases = {};
15841 Object.keys(opts.alias || {}).forEach(function (key) {
15842 aliases[key] = [].concat(opts.alias[key]);
15843 aliases[key].forEach(function (x) {
15844 aliases[x] = [key].concat(aliases[key].filter(function (y) {
15845 return x !== y;
15846 }));
15847 });
15848 });
15849
15850 [].concat(opts.string).filter(Boolean).forEach(function (key) {
15851 flags.strings[key] = true;
15852 if (aliases[key]) {
15853 flags.strings[aliases[key]] = true;
15854 }
15855 });
15856
15857 var defaults = opts['default'] || {};
15858
15859 var argv = { _ : [] };
15860 Object.keys(flags.bools).forEach(function (key) {
15861 setArg(key, defaults[key] === undefined ? false : defaults[key]);
15862 });
15863
15864 var notFlags = [];
15865
15866 if (args.indexOf('--') !== -1) {
15867 notFlags = args.slice(args.indexOf('--')+1);
15868 args = args.slice(0, args.indexOf('--'));
15869 }
15870
15871 function argDefined(key, arg) {
15872 return (flags.allBools && /^--[^=]+$/.test(arg)) ||
15873 flags.strings[key] || flags.bools[key] || aliases[key];
15874 }
15875
15876 function setArg (key, val, arg) {
15877 if (arg && flags.unknownFn && !argDefined(key, arg)) {
15878 if (flags.unknownFn(arg) === false) return;
15879 }
15880
15881 var value = !flags.strings[key] && isNumber(val)
15882 ? Number(val) : val
15883 ;
15884 setKey(argv, key.split('.'), value);
15885
15886 (aliases[key] || []).forEach(function (x) {
15887 setKey(argv, x.split('.'), value);
15888 });
15889 }
15890
15891 function setKey (obj, keys, value) {
15892 var o = obj;
15893 for (var i = 0; i < keys.length-1; i++) {
15894 var key = keys[i];
15895 if (key === '__proto__') return;
15896 if (o[key] === undefined) o[key] = {};
15897 if (o[key] === Object.prototype || o[key] === Number.prototype
15898 || o[key] === String.prototype) o[key] = {};
15899 if (o[key] === Array.prototype) o[key] = [];
15900 o = o[key];
15901 }
15902
15903 var key = keys[keys.length - 1];
15904 if (key === '__proto__') return;
15905 if (o === Object.prototype || o === Number.prototype
15906 || o === String.prototype) o = {};
15907 if (o === Array.prototype) o = [];
15908 if (o[key] === undefined || flags.bools[key] || typeof o[key] === 'boolean') {
15909 o[key] = value;
15910 }
15911 else if (Array.isArray(o[key])) {
15912 o[key].push(value);
15913 }
15914 else {
15915 o[key] = [ o[key], value ];
15916 }
15917 }
15918
15919 function aliasIsBoolean(key) {
15920 return aliases[key].some(function (x) {
15921 return flags.bools[x];
15922 });
15923 }
15924
15925 for (var i = 0; i < args.length; i++) {
15926 var arg = args[i];
15927
15928 if (/^--.+=/.test(arg)) {
15929 // Using [\s\S] instead of . because js doesn't support the
15930 // 'dotall' regex modifier. See:
15931 // http://stackoverflow.com/a/1068308/13216
15932 var m = arg.match(/^--([^=]+)=([\s\S]*)$/);
15933 var key = m[1];
15934 var value = m[2];
15935 if (flags.bools[key]) {
15936 value = value !== 'false';
15937 }
15938 setArg(key, value, arg);
15939 }
15940 else if (/^--no-.+/.test(arg)) {
15941 var key = arg.match(/^--no-(.+)/)[1];
15942 setArg(key, false, arg);
15943 }
15944 else if (/^--.+/.test(arg)) {
15945 var key = arg.match(/^--(.+)/)[1];
15946 var next = args[i + 1];
15947 if (next !== undefined && !/^-/.test(next)
15948 && !flags.bools[key]
15949 && !flags.allBools
15950 && (aliases[key] ? !aliasIsBoolean(key) : true)) {
15951 setArg(key, next, arg);
15952 i++;
15953 }
15954 else if (/^(true|false)$/.test(next)) {
15955 setArg(key, next === 'true', arg);
15956 i++;
15957 }
15958 else {
15959 setArg(key, flags.strings[key] ? '' : true, arg);
15960 }
15961 }
15962 else if (/^-[^-]+/.test(arg)) {
15963 var letters = arg.slice(1,-1).split('');
15964
15965 var broken = false;
15966 for (var j = 0; j < letters.length; j++) {
15967 var next = arg.slice(j+2);
15968
15969 if (next === '-') {
15970 setArg(letters[j], next, arg);
15971 continue;
15972 }
15973
15974 if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) {
15975 setArg(letters[j], next.split('=')[1], arg);
15976 broken = true;
15977 break;
15978 }
15979
15980 if (/[A-Za-z]/.test(letters[j])
15981 && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
15982 setArg(letters[j], next, arg);
15983 broken = true;
15984 break;
15985 }
15986
15987 if (letters[j+1] && letters[j+1].match(/\W/)) {
15988 setArg(letters[j], arg.slice(j+2), arg);
15989 broken = true;
15990 break;
15991 }
15992 else {
15993 setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg);
15994 }
15995 }
15996
15997 var key = arg.slice(-1)[0];
15998 if (!broken && key !== '-') {
15999 if (args[i+1] && !/^(-|--)[^-]/.test(args[i+1])
16000 && !flags.bools[key]
16001 && (aliases[key] ? !aliasIsBoolean(key) : true)) {
16002 setArg(key, args[i+1], arg);
16003 i++;
16004 }
16005 else if (args[i+1] && /^(true|false)$/.test(args[i+1])) {
16006 setArg(key, args[i+1] === 'true', arg);
16007 i++;
16008 }
16009 else {
16010 setArg(key, flags.strings[key] ? '' : true, arg);
16011 }
16012 }
16013 }
16014 else {
16015 if (!flags.unknownFn || flags.unknownFn(arg) !== false) {
16016 argv._.push(
16017 flags.strings['_'] || !isNumber(arg) ? arg : Number(arg)
16018 );
16019 }
16020 if (opts.stopEarly) {
16021 argv._.push.apply(argv._, args.slice(i + 1));
16022 break;
16023 }
16024 }
16025 }
16026
16027 Object.keys(defaults).forEach(function (key) {
16028 if (!hasKey(argv, key.split('.'))) {
16029 setKey(argv, key.split('.'), defaults[key]);
16030
16031 (aliases[key] || []).forEach(function (x) {
16032 setKey(argv, x.split('.'), defaults[key]);
16033 });
16034 }
16035 });
16036
16037 if (opts['--']) {
16038 argv['--'] = new Array();
16039 notFlags.forEach(function(key) {
16040 argv['--'].push(key);
16041 });
16042 }
16043 else {
16044 notFlags.forEach(function(key) {
16045 argv._.push(key);
16046 });
16047 }
16048
16049 return argv;
16050};
16051
16052function hasKey (obj, keys) {
16053 var o = obj;
16054 keys.slice(0,-1).forEach(function (key) {
16055 o = (o[key] || {});
16056 });
16057
16058 var key = keys[keys.length - 1];
16059 return key in o;
16060}
16061
16062function isNumber (x) {
16063 if (typeof x === 'number') return true;
16064 if (/^0x[0-9a-f]+$/i.test(x)) return true;
16065 return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
16066}
16067
16068const { promisify: promisify$2 } = util;
16069const { download: download$1, listReleases: listReleases$1, InstallationError: InstallationError$1 } = getDeno;
16070const debug$1 = node('cli');
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083const spinner = ora();
16084
16085kleur.enabled = Boolean(process.stdout.isTTY);
16086
16087// NOTE: Copied from bili (by @egoist): https://git.io/fxupU
16088const supportsEmoji = process.platform !== 'win32' ||
16089 process.env.TERM === 'xterm-256color';
16090
16091const isWindows = () => /^win/i.test(os.platform());
16092const formatDate = str => str.split('T')[0];
16093const formatError = msg => msg.replace(/^\w*Error:\s+/, match => kleur.red().bold(match));
16094const pipe$4 = promisify$2(mississippi.pipe);
16095
16096const options$1 = minimistOptions({
16097 help: { type: 'boolean', alias: 'h' },
16098 version: { type: 'boolean', alias: 'v' },
16099 'list-releases': { type: 'boolean', alias: 'l' },
16100 unknown: option => fail(`Error: Unknown option \`${option}\``, -1)
16101});
16102const argv$1 = minimist(process.argv.slice(2), options$1);
16103
16104const help = `
16105 ${kleur.bold(pkg$1.name)} v${pkg$1.version}
16106
16107 Usage:
16108 $ ${pkg$1.name} [version] # install specified version, defaults to latest
16109
16110 Options:
16111 -l, --list-releases List deno releases
16112 -h, --help Show help
16113 -v, --version Show version number
16114
16115 Homepage: ${kleur.green(pkg$1.homepage)}
16116 Report issue: ${kleur.green(pkg$1.bugs.url)}
16117`;
16118
16119const code = 'export PATH=$HOME/.deno/bin:$PATH';
16120const prefix$1 = supportsEmoji ? '👉 ' : '$';
16121
16122const profileUpdateWarning = () => `
16123Unable to update your shell profile.
16124Please add following line manually:
16125
16126${prefix$1} ${kleur.bold(code)}`.trim();
16127
16128const profileUpdateSuccess = profile => `
16129Shell profile ${kleur.gray(path.basename(profile))} successfully updated!
16130Reload your terminal session using:
16131
16132${prefix$1} ${kleur.bold(`source ~/${path.basename(profile)}`)}`.trim();
16133
16134program(argv$1._, argv$1).catch(err => {
16135 spinner.stop().clear();
16136 console.error(formatError(err.stack));
16137});
16138
16139async function program([input], flags) {
16140 if (flags.version) return console.log(pkg$1.version);
16141 if (flags.help) return console.log(help);
16142 input = input && `${input}`;
16143 if (flags['list-releases']) {
16144 const range = semver$1.validRange(input) || '*';
16145 debug$1('list releases inside range=`%s`', range);
16146 return printReleases(range);
16147 }
16148 let version = semver$1.valid(semver$1.coerce(input));
16149 if (input && !version) {
16150 fail('Error: Invalid version provided.', 2);
16151 }
16152 version = version ? `v${version}` : 'latest';
16153 debug$1('install version `%s`', version);
16154 try {
16155 await install(version);
16156 } catch (err) {
16157 if (!(err instanceof InstallationError$1)) throw err;
16158 fail(`Error: ${err.message}`);
16159 }
16160}
16161
16162async function install(version) {
16163 const gauge$1 = new gauge();
16164 spinner.start(`Querying ${kleur.bold(pkg$1.config.repo)} for version: ${kleur.cyan(version)}...`);
16165
16166 const dest = await makeDir_1(path.join(os.homedir(), '/.deno/bin/'));
16167 const stream = await download$1(version);
16168 stream.on('download:progress', (value, downloaded, total) => {
16169 const stats = `${prettyBytes(downloaded)}/${kleur.bold(prettyBytes(total))}`;
16170 gauge$1.show(stats, value);
16171 gauge$1.pulse();
16172 });
16173 exitHook(() => {
16174 try {
16175 fs.unlinkSync(`${binary}.download`);
16176 } catch (err) {
16177 if (err.code !== 'ENOENT') throw err;
16178 }
16179 });
16180
16181 version = stream.metadata.version.replace(/^v/, '');
16182 spinner.text = `Downloading ${kleur.bold().cyan(`deno@${version}`)} from ${kleur.gray(stream.metadata.url)}`;
16183 spinner.stopAndPersist({ symbol: supportsEmoji && '📦 ' });
16184
16185 const binary = path.join(dest, isWindows() ? 'deno.exe' : 'deno');
16186 const options = { mode: parseInt(pkg$1.config.umask, 8) };
16187 await pipe$4(stream, fs.createWriteStream(`${binary}.download`, options));
16188 gauge$1.hide();
16189 clearSpinner(spinner);
16190
16191 fs.renameSync(`${binary}.download`, binary);
16192 spinner.succeed(`${kleur.bold().cyan(`deno@${version}`)} is successfully installed!`);
16193
16194 if (isWindows()) return;
16195 const profile = shellProfile();
16196 if (!profile) return spinner.warn(profileUpdateWarning());
16197
16198 const contents = fs.readFileSync(profile, 'utf-8');
16199 if (contents.includes(code)) return;
16200
16201 fs.appendFileSync(profile, `\n# ${pkg$1.name}\n${code}\n`);
16202 spinner.succeed(profileUpdateSuccess(profile));
16203}
16204
16205async function printReleases(range) {
16206 spinner.start(`Querying ${kleur.bold(pkg$1.config.repo)} for available releases...`);
16207 const releases = await listReleases$1();
16208 if (!releases || releases.length <= 0) {
16209 fail('Error: No releases found.', 3);
16210 }
16211 const matches = releases.reduce((acc, it) => {
16212 const version = semver$1.coerce(it.tag);
16213 if (!semver$1.satisfies(version, range)) return acc;
16214 acc.push([it.tag.padEnd(10), kleur.gray(formatDate(it.publishedAt))].join(''));
16215 return acc;
16216 }, []);
16217 if (matches.length <= 0) {
16218 fail('Error: There are no releases satisfying given range.', 4);
16219 }
16220 spinner.stop().clear();
16221 console.log(matches.join('\n'));
16222}
16223
16224function fail(message, code = 1) {
16225 message = formatError(message);
16226 if (spinner.isSpinning) spinner.fail(message);
16227 else console.error(message);
16228 process.exit(code);
16229}
16230
16231function clearSpinner(spinner) {
16232 let line = 0;
16233 while (line < spinner.lineCount) {
16234 spinner.stream.moveCursor(0, -1);
16235 spinner.stream.clearLine();
16236 spinner.stream.cursorTo(0);
16237 line += 1;
16238 }
16239}
16240
16241var cli = {
16242
16243};
16244
16245module.exports = cli;
16246//# sourceMappingURL=cli.compact.js.map