@innei/pretty-logger-core 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,1054 @@
1
+ // consola.instance.ts
2
+ import { isDevelopment as isDevelopment2 } from "std-env";
3
+
4
+ // consola/index.ts
5
+ import { isCI as isCI2, isDebug, isTest } from "std-env";
6
+
7
+ // consola/consola.ts
8
+ import { defu } from "defu";
9
+
10
+ // consola/constants.ts
11
+ var LogLevels = {
12
+ silent: Number.NEGATIVE_INFINITY,
13
+ fatal: 0,
14
+ error: 0,
15
+ warn: 1,
16
+ log: 2,
17
+ info: 3,
18
+ success: 3,
19
+ fail: 3,
20
+ ready: 3,
21
+ start: 3,
22
+ box: 3,
23
+ debug: 4,
24
+ trace: 5,
25
+ verbose: Number.POSITIVE_INFINITY
26
+ };
27
+ var LogTypes = {
28
+ // Silent
29
+ silent: {
30
+ level: -1
31
+ },
32
+ // Level 0
33
+ fatal: {
34
+ level: LogLevels.fatal
35
+ },
36
+ error: {
37
+ level: LogLevels.error
38
+ },
39
+ // Level 1
40
+ warn: {
41
+ level: LogLevels.warn
42
+ },
43
+ // Level 2
44
+ log: {
45
+ level: LogLevels.log
46
+ },
47
+ // Level 3
48
+ info: {
49
+ level: LogLevels.info
50
+ },
51
+ success: {
52
+ level: LogLevels.success
53
+ },
54
+ fail: {
55
+ level: LogLevels.fail
56
+ },
57
+ ready: {
58
+ level: LogLevels.info
59
+ },
60
+ start: {
61
+ level: LogLevels.info
62
+ },
63
+ box: {
64
+ level: LogLevels.info
65
+ },
66
+ // Level 4
67
+ debug: {
68
+ level: LogLevels.debug
69
+ },
70
+ // Level 5
71
+ trace: {
72
+ level: LogLevels.trace
73
+ },
74
+ // Verbose
75
+ verbose: {
76
+ level: LogLevels.verbose
77
+ }
78
+ };
79
+
80
+ // consola/utils/log.ts
81
+ function isPlainObject(obj) {
82
+ return Object.prototype.toString.call(obj) === "[object Object]";
83
+ }
84
+ function isLogObj(arg) {
85
+ if (!isPlainObject(arg)) {
86
+ return false;
87
+ }
88
+ if (!arg.message && !arg.args) {
89
+ return false;
90
+ }
91
+ if (arg.stack) {
92
+ return false;
93
+ }
94
+ return true;
95
+ }
96
+
97
+ // consola/consola.ts
98
+ var paused = false;
99
+ var queue = [];
100
+ var Consola = class _Consola {
101
+ constructor(options = {}) {
102
+ const types = options.types || LogTypes;
103
+ this.options = defu(
104
+ {
105
+ ...options,
106
+ defaults: { ...options.defaults },
107
+ level: _normalizeLogLevel(options.level, types),
108
+ reporters: [...options.reporters || []]
109
+ },
110
+ {
111
+ types: LogTypes,
112
+ throttle: 1e3,
113
+ throttleMin: 5,
114
+ formatOptions: {
115
+ date: true,
116
+ colors: false,
117
+ compact: true
118
+ }
119
+ }
120
+ );
121
+ for (const type in types) {
122
+ const defaults = {
123
+ type,
124
+ ...this.options.defaults,
125
+ ...types[type]
126
+ };
127
+ this[type] = this._wrapLogFn(defaults);
128
+ this[type].raw = this._wrapLogFn(
129
+ defaults,
130
+ true
131
+ );
132
+ }
133
+ if (this.options.mockFn) {
134
+ this.mockTypes();
135
+ }
136
+ this._lastLog = {};
137
+ }
138
+ get level() {
139
+ return this.options.level;
140
+ }
141
+ set level(level) {
142
+ this.options.level = _normalizeLogLevel(
143
+ level,
144
+ this.options.types,
145
+ this.options.level
146
+ );
147
+ }
148
+ create(options) {
149
+ const instance = new _Consola({
150
+ ...this.options,
151
+ ...options
152
+ });
153
+ if (this._mockFn) {
154
+ instance.mockTypes(this._mockFn);
155
+ }
156
+ return instance;
157
+ }
158
+ withDefaults(defaults) {
159
+ return this.create({
160
+ ...this.options,
161
+ defaults: {
162
+ ...this.options.defaults,
163
+ ...defaults
164
+ }
165
+ });
166
+ }
167
+ withTag(tag) {
168
+ return this.withDefaults({
169
+ tag: this.options.defaults.tag ? `${this.options.defaults.tag}:${tag}` : tag
170
+ });
171
+ }
172
+ addReporter(reporter) {
173
+ this.options.reporters.push(reporter);
174
+ return this;
175
+ }
176
+ removeReporter(reporter) {
177
+ if (reporter) {
178
+ const i = this.options.reporters.indexOf(reporter);
179
+ if (i >= 0) {
180
+ return this.options.reporters.splice(i, 1);
181
+ }
182
+ } else {
183
+ this.options.reporters.splice(0);
184
+ }
185
+ return this;
186
+ }
187
+ setReporters(reporters) {
188
+ this.options.reporters = Array.isArray(reporters) ? reporters : [reporters];
189
+ return this;
190
+ }
191
+ wrapAll() {
192
+ this.wrapConsole();
193
+ this.wrapStd();
194
+ }
195
+ restoreAll() {
196
+ this.restoreConsole();
197
+ this.restoreStd();
198
+ }
199
+ wrapConsole() {
200
+ for (const type in this.options.types) {
201
+ if (!console[`__${type}`]) {
202
+ ;
203
+ console[`__${type}`] = console[type];
204
+ }
205
+ ;
206
+ console[type] = this[type].raw;
207
+ }
208
+ }
209
+ restoreConsole() {
210
+ for (const type in this.options.types) {
211
+ if (console[`__${type}`]) {
212
+ ;
213
+ console[type] = console[`__${type}`];
214
+ delete console[`__${type}`];
215
+ }
216
+ }
217
+ }
218
+ wrapStd() {
219
+ this._wrapStream(this.options.stdout, "log");
220
+ this._wrapStream(this.options.stderr, "log");
221
+ }
222
+ _wrapStream(stream, type) {
223
+ if (!stream) {
224
+ return;
225
+ }
226
+ if (!stream.__write) {
227
+ ;
228
+ stream.__write = stream.write;
229
+ }
230
+ ;
231
+ stream.write = (data) => {
232
+ ;
233
+ this[type].raw(String(data).trim());
234
+ };
235
+ }
236
+ restoreStd() {
237
+ this._restoreStream(this.options.stdout);
238
+ this._restoreStream(this.options.stderr);
239
+ }
240
+ _restoreStream(stream) {
241
+ if (!stream) {
242
+ return;
243
+ }
244
+ if (stream.__write) {
245
+ stream.write = stream.__write;
246
+ delete stream.__write;
247
+ }
248
+ }
249
+ pauseLogs() {
250
+ paused = true;
251
+ }
252
+ resumeLogs() {
253
+ paused = false;
254
+ const _queue = queue.splice(0);
255
+ for (const item of _queue) {
256
+ item[0]._logFn(item[1], item[2]);
257
+ }
258
+ }
259
+ mockTypes(mockFn) {
260
+ const _mockFn = mockFn || this.options.mockFn;
261
+ this._mockFn = _mockFn;
262
+ if (typeof _mockFn !== "function") {
263
+ return;
264
+ }
265
+ for (const type in this.options.types) {
266
+ ;
267
+ this[type] = _mockFn(type, this.options.types[type]) || this[type];
268
+ this[type].raw = this[type];
269
+ }
270
+ }
271
+ _wrapLogFn(defaults, isRaw) {
272
+ return (...args) => {
273
+ if (paused) {
274
+ queue.push([this, defaults, args, isRaw]);
275
+ return;
276
+ }
277
+ return this._logFn(defaults, args, isRaw);
278
+ };
279
+ }
280
+ _logFn(defaults, args, isRaw) {
281
+ if ((defaults.level || 0) > this.level) {
282
+ return false;
283
+ }
284
+ const logObj = {
285
+ date: /* @__PURE__ */ new Date(),
286
+ args: [],
287
+ ...defaults,
288
+ level: _normalizeLogLevel(defaults.level, this.options.types)
289
+ };
290
+ if (!isRaw && args.length === 1 && isLogObj(args[0])) {
291
+ Object.assign(logObj, args[0]);
292
+ } else {
293
+ logObj.args = [...args];
294
+ }
295
+ if (logObj.message) {
296
+ logObj.args.unshift(logObj.message);
297
+ delete logObj.message;
298
+ }
299
+ if (logObj.additional) {
300
+ if (!Array.isArray(logObj.additional)) {
301
+ logObj.additional = logObj.additional.split("\n");
302
+ }
303
+ logObj.args.push(`
304
+ ${logObj.additional.join("\n")}`);
305
+ delete logObj.additional;
306
+ }
307
+ logObj.type = typeof logObj.type === "string" ? logObj.type.toLowerCase() : "log";
308
+ logObj.tag = typeof logObj.tag === "string" ? logObj.tag : "";
309
+ const resolveLog = (newLog = false) => {
310
+ const repeated = (this._lastLog.count || 0) - this.options.throttleMin;
311
+ if (this._lastLog.object && repeated > 0) {
312
+ const args2 = [...this._lastLog.object.args];
313
+ if (repeated > 1) {
314
+ args2.push(`(repeated ${repeated} times)`);
315
+ }
316
+ this._log({ ...this._lastLog.object, args: args2 });
317
+ this._lastLog.count = 1;
318
+ }
319
+ if (newLog) {
320
+ this._lastLog.object = logObj;
321
+ this._log(logObj);
322
+ }
323
+ };
324
+ clearTimeout(this._lastLog.timeout);
325
+ const diffTime = this._lastLog.time && logObj.date ? logObj.date.getTime() - this._lastLog.time.getTime() : 0;
326
+ this._lastLog.time = logObj.date;
327
+ if (diffTime < this.options.throttle) {
328
+ try {
329
+ const serializedLog = JSON.stringify([
330
+ logObj.type,
331
+ logObj.tag,
332
+ logObj.args
333
+ ]);
334
+ const isSameLog = this._lastLog.serialized === serializedLog;
335
+ this._lastLog.serialized = serializedLog;
336
+ if (isSameLog) {
337
+ this._lastLog.count = (this._lastLog.count || 0) + 1;
338
+ if (this._lastLog.count > this.options.throttleMin) {
339
+ this._lastLog.timeout = setTimeout(
340
+ resolveLog,
341
+ this.options.throttle
342
+ );
343
+ return;
344
+ }
345
+ }
346
+ } catch {
347
+ }
348
+ }
349
+ resolveLog(true);
350
+ }
351
+ _log(logObj) {
352
+ for (const reporter of this.options.reporters) {
353
+ reporter.log(logObj, {
354
+ options: this.options
355
+ });
356
+ }
357
+ }
358
+ };
359
+ function _normalizeLogLevel(input, types = {}, defaultLevel = 3) {
360
+ if (input === void 0) {
361
+ return defaultLevel;
362
+ }
363
+ if (typeof input === "number") {
364
+ return input;
365
+ }
366
+ if (types[input] && types[input].level !== void 0) {
367
+ return types[input].level;
368
+ }
369
+ return defaultLevel;
370
+ }
371
+ Consola.prototype.add = Consola.prototype.addReporter;
372
+ Consola.prototype.remove = Consola.prototype.removeReporter;
373
+ Consola.prototype.clear = Consola.prototype.removeReporter;
374
+ Consola.prototype.withScope = Consola.prototype.withTag;
375
+ Consola.prototype.mock = Consola.prototype.mockTypes;
376
+ Consola.prototype.pause = Consola.prototype.pauseLogs;
377
+ Consola.prototype.resume = Consola.prototype.resumeLogs;
378
+ function createConsola(options = {}) {
379
+ return new Consola(options);
380
+ }
381
+
382
+ // consola/reporters/basic.ts
383
+ import { formatWithOptions } from "util";
384
+
385
+ // consola/utils/error.ts
386
+ import { sep } from "path";
387
+ function parseStack(stack) {
388
+ const cwd = process.cwd() + sep;
389
+ const lines = stack.split("\n").splice(1).map((l) => l.trim().replace("file://", "").replace(cwd, ""));
390
+ return lines;
391
+ }
392
+
393
+ // consola/utils/stream.ts
394
+ function writeStream(data, stream) {
395
+ const write = stream.__write || stream.write;
396
+ return write.call(stream, data);
397
+ }
398
+
399
+ // consola/reporters/basic.ts
400
+ var bracket = (x) => x ? `[${x}]` : "";
401
+ var BasicReporter = class {
402
+ formatStack(stack, opts) {
403
+ return ` ${parseStack(stack).join("\n ")}`;
404
+ }
405
+ formatArgs(args, opts) {
406
+ const _args = args.map((arg) => {
407
+ if (arg && typeof arg.stack === "string") {
408
+ return `${arg.message}
409
+ ${this.formatStack(arg.stack, opts)}`;
410
+ }
411
+ return arg;
412
+ });
413
+ return formatWithOptions(opts, ..._args);
414
+ }
415
+ formatDate(date, opts) {
416
+ return opts.date ? date.toLocaleTimeString() : "";
417
+ }
418
+ filterAndJoin(arr) {
419
+ return arr.filter(Boolean).join(" ");
420
+ }
421
+ formatLogObj(logObj, opts) {
422
+ const message = this.formatArgs(logObj.args, opts);
423
+ if (logObj.type === "box") {
424
+ return `
425
+ ${[
426
+ bracket(logObj.tag),
427
+ logObj.title && logObj.title,
428
+ ...message.split("\n")
429
+ ].filter(Boolean).map((l) => ` > ${l}`).join("\n")}
430
+ `;
431
+ }
432
+ return this.filterAndJoin([
433
+ bracket(logObj.type),
434
+ bracket(logObj.tag),
435
+ message
436
+ ]);
437
+ }
438
+ log(logObj, ctx) {
439
+ const line = this.formatLogObj(logObj, {
440
+ columns: ctx.options.stdout.columns || 0,
441
+ ...ctx.options.formatOptions
442
+ });
443
+ return writeStream(
444
+ `${line}
445
+ `,
446
+ logObj.level < 2 ? ctx.options.stderr || process.stderr : ctx.options.stdout || process.stdout
447
+ );
448
+ }
449
+ };
450
+
451
+ // consola/reporters/fancy.ts
452
+ import _stringWidth from "string-width";
453
+
454
+ // consola/utils/color.ts
455
+ import * as tty from "tty";
456
+ var {
457
+ env = {},
458
+ argv = [],
459
+ platform = ""
460
+ } = typeof process === "undefined" ? {} : process;
461
+ var isDisabled = "NO_COLOR" in env || argv.includes("--no-color");
462
+ var isForced = "FORCE_COLOR" in env || argv.includes("--color");
463
+ var isWindows = platform === "win32";
464
+ var isDumbTerminal = env.TERM === "dumb";
465
+ var isCompatibleTerminal = tty && tty.isatty && tty.isatty(1) && env.TERM && !isDumbTerminal;
466
+ var isCI = "CI" in env && ("GITHUB_ACTIONS" in env || "GITLAB_CI" in env || "CIRCLECI" in env);
467
+ var isColorSupported = !isDisabled && (isForced || isWindows && !isDumbTerminal || isCompatibleTerminal || isCI);
468
+ function replaceClose(index, string, close, replace, head = string.slice(0, Math.max(0, index)) + replace, tail = string.slice(Math.max(0, index + close.length)), next = tail.indexOf(close)) {
469
+ return head + (next < 0 ? tail : replaceClose(next, tail, close, replace));
470
+ }
471
+ function clearBleed(index, string, open, close, replace) {
472
+ return index < 0 ? open + string + close : open + replaceClose(index, string, close, replace) + close;
473
+ }
474
+ function filterEmpty(open, close, replace = open, at = open.length + 1) {
475
+ return (string) => string || !(string === "" || string === void 0) ? clearBleed(`${string}`.indexOf(close, at), string, open, close, replace) : "";
476
+ }
477
+ function init(open, close, replace) {
478
+ return filterEmpty(`\x1B[${open}m`, `\x1B[${close}m`, replace);
479
+ }
480
+ var colorDefs = {
481
+ reset: init(0, 0),
482
+ bold: init(1, 22, "\x1B[22m\x1B[1m"),
483
+ dim: init(2, 22, "\x1B[22m\x1B[2m"),
484
+ italic: init(3, 23),
485
+ underline: init(4, 24),
486
+ inverse: init(7, 27),
487
+ hidden: init(8, 28),
488
+ strikethrough: init(9, 29),
489
+ black: init(30, 39),
490
+ red: init(31, 39),
491
+ green: init(32, 39),
492
+ yellow: init(33, 39),
493
+ blue: init(34, 39),
494
+ magenta: init(35, 39),
495
+ cyan: init(36, 39),
496
+ white: init(37, 39),
497
+ gray: init(90, 39),
498
+ bgBlack: init(40, 49),
499
+ bgRed: init(41, 49),
500
+ bgGreen: init(42, 49),
501
+ bgYellow: init(43, 49),
502
+ bgBlue: init(44, 49),
503
+ bgMagenta: init(45, 49),
504
+ bgCyan: init(46, 49),
505
+ bgWhite: init(47, 49),
506
+ blackBright: init(90, 39),
507
+ redBright: init(91, 39),
508
+ greenBright: init(92, 39),
509
+ yellowBright: init(93, 39),
510
+ blueBright: init(94, 39),
511
+ magentaBright: init(95, 39),
512
+ cyanBright: init(96, 39),
513
+ whiteBright: init(97, 39),
514
+ bgBlackBright: init(100, 49),
515
+ bgRedBright: init(101, 49),
516
+ bgGreenBright: init(102, 49),
517
+ bgYellowBright: init(103, 49),
518
+ bgBlueBright: init(104, 49),
519
+ bgMagentaBright: init(105, 49),
520
+ bgCyanBright: init(106, 49),
521
+ bgWhiteBright: init(107, 49)
522
+ };
523
+ function createColors(useColor = isColorSupported) {
524
+ return useColor ? colorDefs : Object.fromEntries(Object.keys(colorDefs).map((key) => [key, String]));
525
+ }
526
+ var colors = createColors();
527
+ function getColor(color, fallback = "reset") {
528
+ return colors[color] || colors[fallback];
529
+ }
530
+
531
+ // consola/utils/string.ts
532
+ var ansiRegex = [
533
+ "[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)",
534
+ "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"
535
+ ].join("|");
536
+ function stripAnsi(text) {
537
+ return text.replace(new RegExp(ansiRegex, "g"), "");
538
+ }
539
+
540
+ // consola/utils/box.ts
541
+ var boxStylePresets = {
542
+ solid: {
543
+ tl: "\u250C",
544
+ tr: "\u2510",
545
+ bl: "\u2514",
546
+ br: "\u2518",
547
+ h: "\u2500",
548
+ v: "\u2502"
549
+ },
550
+ double: {
551
+ tl: "\u2554",
552
+ tr: "\u2557",
553
+ bl: "\u255A",
554
+ br: "\u255D",
555
+ h: "\u2550",
556
+ v: "\u2551"
557
+ },
558
+ doubleSingle: {
559
+ tl: "\u2553",
560
+ tr: "\u2556",
561
+ bl: "\u2559",
562
+ br: "\u255C",
563
+ h: "\u2500",
564
+ v: "\u2551"
565
+ },
566
+ doubleSingleRounded: {
567
+ tl: "\u256D",
568
+ tr: "\u256E",
569
+ bl: "\u2570",
570
+ br: "\u256F",
571
+ h: "\u2500",
572
+ v: "\u2551"
573
+ },
574
+ singleThick: {
575
+ tl: "\u250F",
576
+ tr: "\u2513",
577
+ bl: "\u2517",
578
+ br: "\u251B",
579
+ h: "\u2501",
580
+ v: "\u2503"
581
+ },
582
+ singleDouble: {
583
+ tl: "\u2552",
584
+ tr: "\u2555",
585
+ bl: "\u2558",
586
+ br: "\u255B",
587
+ h: "\u2550",
588
+ v: "\u2502"
589
+ },
590
+ singleDoubleRounded: {
591
+ tl: "\u256D",
592
+ tr: "\u256E",
593
+ bl: "\u2570",
594
+ br: "\u256F",
595
+ h: "\u2550",
596
+ v: "\u2502"
597
+ },
598
+ rounded: {
599
+ tl: "\u256D",
600
+ tr: "\u256E",
601
+ bl: "\u2570",
602
+ br: "\u256F",
603
+ h: "\u2500",
604
+ v: "\u2502"
605
+ }
606
+ };
607
+ var defaultStyle = {
608
+ borderColor: "white",
609
+ borderStyle: "rounded",
610
+ valign: "center",
611
+ padding: 2,
612
+ marginLeft: 1,
613
+ marginTop: 1,
614
+ marginBottom: 1
615
+ };
616
+ function box(text, _opts = {}) {
617
+ const opts = {
618
+ ..._opts,
619
+ style: {
620
+ ...defaultStyle,
621
+ ..._opts.style
622
+ }
623
+ };
624
+ const textLines = text.split("\n");
625
+ const boxLines = [];
626
+ const _color = getColor(opts.style.borderColor);
627
+ const borderStyle = {
628
+ ...typeof opts.style.borderStyle === "string" ? boxStylePresets[opts.style.borderStyle] || boxStylePresets.solid : opts.style.borderStyle
629
+ };
630
+ if (_color) {
631
+ for (const key in borderStyle) {
632
+ borderStyle[key] = _color(
633
+ borderStyle[key]
634
+ );
635
+ }
636
+ }
637
+ const paddingOffset = opts.style.padding % 2 === 0 ? opts.style.padding : opts.style.padding + 1;
638
+ const height = textLines.length + paddingOffset;
639
+ const width = Math.max(...textLines.map((line) => line.length)) + paddingOffset;
640
+ const widthOffset = width + paddingOffset;
641
+ const leftSpace = opts.style.marginLeft > 0 ? " ".repeat(opts.style.marginLeft) : "";
642
+ if (opts.style.marginTop > 0) {
643
+ boxLines.push("".repeat(opts.style.marginTop));
644
+ }
645
+ if (opts.title) {
646
+ const left = borderStyle.h.repeat(
647
+ Math.floor((width - stripAnsi(opts.title).length) / 2)
648
+ );
649
+ const right = borderStyle.h.repeat(
650
+ width - stripAnsi(opts.title).length - stripAnsi(left).length + paddingOffset
651
+ );
652
+ boxLines.push(
653
+ `${leftSpace}${borderStyle.tl}${left}${opts.title}${right}${borderStyle.tr}`
654
+ );
655
+ } else {
656
+ boxLines.push(
657
+ `${leftSpace}${borderStyle.tl}${borderStyle.h.repeat(widthOffset)}${borderStyle.tr}`
658
+ );
659
+ }
660
+ const valignOffset = opts.style.valign === "center" ? Math.floor((height - textLines.length) / 2) : opts.style.valign === "top" ? height - textLines.length - paddingOffset : height - textLines.length;
661
+ for (let i = 0; i < height; i++) {
662
+ if (i < valignOffset || i >= valignOffset + textLines.length) {
663
+ boxLines.push(
664
+ `${leftSpace}${borderStyle.v}${" ".repeat(widthOffset)}${borderStyle.v}`
665
+ );
666
+ } else {
667
+ const line = textLines[i - valignOffset];
668
+ const left = " ".repeat(paddingOffset);
669
+ const right = " ".repeat(width - stripAnsi(line).length);
670
+ boxLines.push(
671
+ `${leftSpace}${borderStyle.v}${left}${line}${right}${borderStyle.v}`
672
+ );
673
+ }
674
+ }
675
+ boxLines.push(
676
+ `${leftSpace}${borderStyle.bl}${borderStyle.h.repeat(widthOffset)}${borderStyle.br}`
677
+ );
678
+ if (opts.style.marginBottom > 0) {
679
+ boxLines.push("".repeat(opts.style.marginBottom));
680
+ }
681
+ return boxLines.join("\n");
682
+ }
683
+
684
+ // consola/utils/tester.ts
685
+ function isUnicodeSupported() {
686
+ if (process.platform !== "win32") {
687
+ return process.env.TERM !== "linux";
688
+ }
689
+ return Boolean(process.env.WT_SESSION) || // Windows Terminal
690
+ Boolean(process.env.TERMINUS_SUBLIME) || // Terminus (<0.2.27)
691
+ process.env.ConEmuTask === "{cmd::Cmder}" || // ConEmu and cmder
692
+ process.env.TERM_PROGRAM === "Terminus-Sublime" || process.env.TERM_PROGRAM === "vscode" || process.env.TERM === "xterm-256color" || process.env.TERM === "alacritty" || process.env.TERMINAL_EMULATOR === "JetBrains-JediTerm";
693
+ }
694
+
695
+ // consola/reporters/fancy.ts
696
+ var TYPE_COLOR_MAP = {
697
+ info: "cyan",
698
+ fail: "red",
699
+ success: "green",
700
+ ready: "green",
701
+ start: "magenta"
702
+ };
703
+ var LEVEL_COLOR_MAP = {
704
+ 0: "red",
705
+ 1: "yellow"
706
+ };
707
+ var unicode = isUnicodeSupported();
708
+ var s = (c, fallback) => unicode ? c : fallback;
709
+ var TYPE_ICONS = {
710
+ error: s("\u2716", "\xD7"),
711
+ fatal: s("\u2716", "\xD7"),
712
+ ready: s("\u2714", "\u221A"),
713
+ warn: s("\u26A0", "\u203C"),
714
+ info: s("\u2139", "i"),
715
+ success: s("\u2714", "\u221A"),
716
+ debug: s("\u2699", "D"),
717
+ trace: s("\u2192", "\u2192"),
718
+ fail: s("\u2716", "\xD7"),
719
+ start: s("\u25D0", "o"),
720
+ log: ""
721
+ };
722
+ function stringWidth(str) {
723
+ if (!Intl.Segmenter) {
724
+ return stripAnsi(str).length;
725
+ }
726
+ return _stringWidth(str);
727
+ }
728
+ var FancyReporter = class extends BasicReporter {
729
+ formatStack(stack) {
730
+ return `
731
+ ${parseStack(stack).map(
732
+ (line) => ` ${line.replace(/^at +/, (m) => colors.gray(m)).replace(/\((.+)\)/, (_, m) => `(${colors.cyan(m)})`)}`
733
+ ).join("\n")}`;
734
+ }
735
+ formatType(logObj, isBadge, opts) {
736
+ const typeColor = TYPE_COLOR_MAP[logObj.type] || LEVEL_COLOR_MAP[logObj.level] || "gray";
737
+ if (isBadge) {
738
+ return getBgColor(typeColor)(
739
+ colors.black(` ${logObj.type.toUpperCase()} `)
740
+ );
741
+ }
742
+ const _type = typeof TYPE_ICONS[logObj.type] === "string" ? TYPE_ICONS[logObj.type] : logObj.icon || logObj.type;
743
+ return _type ? getColor2(typeColor)(_type) : "";
744
+ }
745
+ formatLogObj(logObj, opts) {
746
+ const [message, ...additional] = this.formatArgs(logObj.args, opts).split(
747
+ "\n"
748
+ );
749
+ if (logObj.type === "box") {
750
+ return box(
751
+ characterFormat(
752
+ message + (additional.length > 0 ? `
753
+ ${additional.join("\n")}` : "")
754
+ ),
755
+ {
756
+ title: logObj.title ? characterFormat(logObj.title) : void 0,
757
+ style: logObj.style
758
+ }
759
+ );
760
+ }
761
+ const date = this.formatDate(logObj.date, opts);
762
+ const coloredDate = date && colors.gray(date);
763
+ const isBadge = logObj.badge ?? logObj.level < 2;
764
+ const type = this.formatType(logObj, isBadge, opts);
765
+ const tag = logObj.tag ? colors.gray(logObj.tag) : "";
766
+ let line;
767
+ const left = this.filterAndJoin([type, characterFormat(message)]);
768
+ const right = this.filterAndJoin(opts.columns ? [tag, coloredDate] : [tag]);
769
+ const space = (opts.columns || 0) - stringWidth(left) - stringWidth(right) - 2;
770
+ line = space > 0 && (opts.columns || 0) >= 80 ? left + " ".repeat(space) + right : (right ? `${colors.gray(`[${right}]`)} ` : "") + left;
771
+ line += characterFormat(
772
+ additional.length > 0 ? `
773
+ ${additional.join("\n")}` : ""
774
+ );
775
+ if (logObj.type === "trace") {
776
+ const _err = new Error(`Trace: ${logObj.message}`);
777
+ line += this.formatStack(_err.stack || "");
778
+ }
779
+ return isBadge ? `
780
+ ${line}
781
+ ` : line;
782
+ }
783
+ };
784
+ function characterFormat(str) {
785
+ return str.replace(/`([^`]+)`/gm, (_, m) => colors.cyan(m)).replace(/\s+_([^_]+)_\s+/gm, (_, m) => ` ${colors.underline(m)} `);
786
+ }
787
+ function getColor2(color = "white") {
788
+ return colors[color] || colors.white;
789
+ }
790
+ function getBgColor(color = "bgWhite") {
791
+ return colors[`bg${color[0].toUpperCase()}${color.slice(1)}`] || colors.bgWhite;
792
+ }
793
+
794
+ // consola/index.ts
795
+ function createConsola2(options = {}) {
796
+ let level = _getDefaultLogLevel();
797
+ if (process.env.CONSOLA_LEVEL) {
798
+ level = Number.parseInt(process.env.CONSOLA_LEVEL) ?? level;
799
+ }
800
+ const consola2 = createConsola({
801
+ level,
802
+ defaults: { level },
803
+ stdout: process.stdout,
804
+ stderr: process.stderr,
805
+ reporters: options.reporters || [
806
+ options.fancy ?? !(isCI2 || isTest) ? new FancyReporter() : new BasicReporter()
807
+ ],
808
+ ...options
809
+ });
810
+ return consola2;
811
+ }
812
+ function _getDefaultLogLevel() {
813
+ if (isDebug) {
814
+ return LogLevels.debug;
815
+ }
816
+ if (isTest) {
817
+ return LogLevels.warn;
818
+ }
819
+ return LogLevels.info;
820
+ }
821
+ var consola = createConsola2();
822
+
823
+ // consola/reporters/file.ts
824
+ import { createWriteStream } from "fs";
825
+ import * as fs from "fs";
826
+ import { dirname } from "path";
827
+ import { CronJob } from "cron";
828
+
829
+ // tool.util.ts
830
+ import path from "path";
831
+ var getShortTime = (date) => {
832
+ return Intl.DateTimeFormat("en-US", {
833
+ timeStyle: "medium",
834
+ hour12: false
835
+ }).format(date);
836
+ };
837
+ var getShortDate = (date) => {
838
+ return Intl.DateTimeFormat("en-US", {
839
+ dateStyle: "short"
840
+ }).format(date).replace(/\//g, "-");
841
+ };
842
+ var getLogFilePath = (logDir, formatString) => path.resolve(logDir, formatString.replace(/%d/g, getShortDate(/* @__PURE__ */ new Date())));
843
+
844
+ // consola/reporters/logger.ts
845
+ import picocolors from "picocolors";
846
+ import { isDevelopment } from "std-env";
847
+ var LoggerReporter = class extends FancyReporter {
848
+ constructor() {
849
+ super(...arguments);
850
+ this.latestLogTime = Date.now();
851
+ }
852
+ formatDate(date, opts) {
853
+ const isInVirtualTerminal = typeof opts.columns === "undefined";
854
+ if (isDevelopment) {
855
+ const now = Date.now();
856
+ const delta = now - this.latestLogTime;
857
+ this.latestLogTime = now;
858
+ return `+${delta | 0}ms ${super.formatDate(date, opts)}`;
859
+ }
860
+ return isInVirtualTerminal ? "" : super.formatDate(date, opts);
861
+ }
862
+ formatLogObj(logObj, opts) {
863
+ const isInVirtualTerminal = typeof opts.columns === "undefined";
864
+ return isInVirtualTerminal ? `${picocolors.gray(getShortTime(/* @__PURE__ */ new Date()))} ${super.formatLogObj(logObj, opts).replace(/^\n/, "")}`.trimEnd() : super.formatLogObj(logObj, opts);
865
+ }
866
+ };
867
+
868
+ // consola/reporters/file.ts
869
+ var FileReporter = class extends LoggerReporter {
870
+ constructor(configs) {
871
+ super();
872
+ this.configs = configs;
873
+ this.refreshWriteStream();
874
+ this.scheduleRefreshWriteStream();
875
+ }
876
+ scheduleRefreshWriteStream() {
877
+ const { cron = "0 0 * * *" } = this.configs;
878
+ const job = new CronJob(cron, this.refreshWriteStream.bind(this));
879
+ job.start();
880
+ this.__job = job;
881
+ }
882
+ teardown() {
883
+ this.__job?.stop();
884
+ this.stdoutStream?.end();
885
+ this.stderrStream?.end();
886
+ }
887
+ refreshWriteStream() {
888
+ const {
889
+ loggerDir,
890
+ stderrFileFormat = "error.log",
891
+ stdoutFileFormat = "stdout_%d.log"
892
+ } = this.configs;
893
+ const stdoutPath = getLogFilePath(loggerDir, stdoutFileFormat);
894
+ const stderrPath = getLogFilePath(loggerDir, stderrFileFormat);
895
+ createLoggerFileIfNotExist(stdoutPath);
896
+ createLoggerFileIfNotExist(stderrPath);
897
+ const options = {
898
+ encoding: "utf-8",
899
+ flags: "a+"
900
+ };
901
+ [this.stderrStream, this.stdoutStream].forEach((stream) => {
902
+ stream?.end();
903
+ });
904
+ this.stdoutStream = createWriteStream(stdoutPath, options);
905
+ this.stderrStream = createWriteStream(stderrPath, options);
906
+ [this.stderrStream, this.stdoutStream].forEach((stream) => {
907
+ writeStream(
908
+ "\n========================================================\n",
909
+ stream
910
+ );
911
+ });
912
+ }
913
+ log(logObj, ctx) {
914
+ if (!this.stdoutStream || !this.stderrStream) {
915
+ return;
916
+ }
917
+ const finalStdout = this.stdoutStream;
918
+ const finalStderr = this.stderrStream || this.stdoutStream;
919
+ const line = super.formatLogObj(logObj, {
920
+ ...ctx.options.formatOptions,
921
+ columns: void 0
922
+ });
923
+ if (this.configs.errWriteToStdout && logObj.level < 2) {
924
+ writeStream(`${line}
925
+ `, finalStdout);
926
+ }
927
+ return writeStream(
928
+ `${line}
929
+ `,
930
+ logObj.level < 2 ? finalStderr : finalStdout
931
+ );
932
+ }
933
+ };
934
+ var createLoggerFileIfNotExist = (path2) => {
935
+ const dirPath = dirname(path2);
936
+ if (!fs.existsSync(dirPath)) {
937
+ fs.mkdirSync(dirPath, { recursive: true });
938
+ }
939
+ if (!fs.existsSync(path2)) {
940
+ fs.writeFileSync(path2, "", { flag: "wx" });
941
+ }
942
+ };
943
+
944
+ // consola/reporters/subscriber.ts
945
+ import EventEmitter from "events";
946
+ var wrapperSubscribers = (consola2) => {
947
+ Object.assign(consola2, {
948
+ onData: (handler) => SubscriberReporter.subscriber.on("log", handler),
949
+ onStdOut: (handler) => SubscriberReporter.subscriber.on("stdout", handler),
950
+ onStdErr: (handler) => SubscriberReporter.subscriber.on("stderr", handler)
951
+ });
952
+ return consola2;
953
+ };
954
+ var _SubscriberReporter = class _SubscriberReporter extends LoggerReporter {
955
+ log(logObj, ctx) {
956
+ const line = super.formatLogObj(logObj, ctx);
957
+ const event = logObj.level < 2 ? "stderr" : "stdout";
958
+ _SubscriberReporter.subscriber.emit(event, line);
959
+ _SubscriberReporter.subscriber.emit("log", line);
960
+ }
961
+ };
962
+ _SubscriberReporter.subscriber = new EventEmitter();
963
+ var SubscriberReporter = _SubscriberReporter;
964
+
965
+ // consola.instance.ts
966
+ var createLoggerConsola = (options) => {
967
+ const reporters = [
968
+ new FancyReporter(),
969
+ new SubscriberReporter()
970
+ ];
971
+ if (options?.writeToFile) {
972
+ reporters.push(new FileReporter(options.writeToFile));
973
+ }
974
+ const consola2 = createConsola2({
975
+ formatOptions: {
976
+ date: true
977
+ },
978
+ reporters,
979
+ level: isDevelopment2 ? LogLevels.trace : LogLevels.info,
980
+ ...options
981
+ });
982
+ return wrapperSubscribers(consola2);
983
+ };
984
+
985
+ // consola/reporters/browser.ts
986
+ var BrowserReporter = class {
987
+ constructor(options) {
988
+ this.options = { ...options };
989
+ this.defaultColor = "#7f8c8d";
990
+ this.levelColorMap = {
991
+ 0: "#c0392b",
992
+ // Red
993
+ 1: "#f39c12",
994
+ // Yellow
995
+ 3: "#00BCD4"
996
+ // Cyan
997
+ };
998
+ this.typeColorMap = {
999
+ success: "#2ecc71"
1000
+ // Green
1001
+ };
1002
+ }
1003
+ _getLogFn(level) {
1004
+ if (level < 1) {
1005
+ return console.__error || console.error;
1006
+ }
1007
+ if (level === 1) {
1008
+ return console.__warn || console.warn;
1009
+ }
1010
+ return console.__log || console.log;
1011
+ }
1012
+ log(logObj) {
1013
+ const consoleLogFn = this._getLogFn(logObj.level);
1014
+ const type = logObj.type === "log" ? "" : logObj.type;
1015
+ const tag = logObj.tag || "";
1016
+ const color = this.typeColorMap[logObj.type] || this.levelColorMap[logObj.level] || this.defaultColor;
1017
+ const style = `
1018
+ background: ${color};
1019
+ border-radius: 0.5em;
1020
+ color: white;
1021
+ font-weight: bold;
1022
+ padding: 2px 0.5em;
1023
+ `;
1024
+ const badge = `%c${[tag, type].filter(Boolean).join(":")}`;
1025
+ if (typeof logObj.args[0] === "string") {
1026
+ consoleLogFn(
1027
+ `${badge}%c ${logObj.args[0]}`,
1028
+ style,
1029
+ // Empty string as style resets to default console style
1030
+ "",
1031
+ ...logObj.args.slice(1)
1032
+ );
1033
+ } else {
1034
+ consoleLogFn(badge, style, ...logObj.args);
1035
+ }
1036
+ }
1037
+ };
1038
+ export {
1039
+ BasicReporter,
1040
+ BrowserReporter,
1041
+ Consola,
1042
+ FancyReporter,
1043
+ FileReporter,
1044
+ LEVEL_COLOR_MAP,
1045
+ LogLevels,
1046
+ LogTypes,
1047
+ LoggerReporter,
1048
+ SubscriberReporter,
1049
+ TYPE_COLOR_MAP,
1050
+ consola,
1051
+ createConsola2 as createConsola,
1052
+ createLoggerConsola,
1053
+ wrapperSubscribers
1054
+ };