@likec4/log 1.8.1 → 1.10.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/node.cjs CHANGED
@@ -1,17 +1,501 @@
1
1
  'use strict';
2
2
 
3
- const basic = require('consola/basic');
3
+ const node_util = require('node:util');
4
+ const node_path = require('node:path');
4
5
 
5
- const logger = basic.createConsola({
6
- level: basic.LogLevels.debug,
7
- fancy: true,
6
+ const LogLevels = {
7
+ silent: Number.NEGATIVE_INFINITY,
8
+ fatal: 0,
9
+ error: 0,
10
+ warn: 1,
11
+ log: 2,
12
+ info: 3,
13
+ success: 3,
14
+ fail: 3,
15
+ ready: 3,
16
+ start: 3,
17
+ box: 3,
18
+ debug: 4,
19
+ trace: 5,
20
+ verbose: Number.POSITIVE_INFINITY
21
+ };
22
+ const LogTypes = {
23
+ // Silent
24
+ silent: {
25
+ level: -1
26
+ },
27
+ // Level 0
28
+ fatal: {
29
+ level: LogLevels.fatal
30
+ },
31
+ error: {
32
+ level: LogLevels.error
33
+ },
34
+ // Level 1
35
+ warn: {
36
+ level: LogLevels.warn
37
+ },
38
+ // Level 2
39
+ log: {
40
+ level: LogLevels.log
41
+ },
42
+ // Level 3
43
+ info: {
44
+ level: LogLevels.info
45
+ },
46
+ success: {
47
+ level: LogLevels.success
48
+ },
49
+ fail: {
50
+ level: LogLevels.fail
51
+ },
52
+ ready: {
53
+ level: LogLevels.info
54
+ },
55
+ start: {
56
+ level: LogLevels.info
57
+ },
58
+ box: {
59
+ level: LogLevels.info
60
+ },
61
+ // Level 4
62
+ debug: {
63
+ level: LogLevels.debug
64
+ },
65
+ // Level 5
66
+ trace: {
67
+ level: LogLevels.trace
68
+ },
69
+ // Verbose
70
+ verbose: {
71
+ level: LogLevels.verbose
72
+ }
73
+ };
74
+
75
+ function isObject(value) {
76
+ return value !== null && typeof value === "object";
77
+ }
78
+ function _defu(baseObject, defaults, namespace = ".", merger) {
79
+ if (!isObject(defaults)) {
80
+ return _defu(baseObject, {}, namespace, merger);
81
+ }
82
+ const object = Object.assign({}, defaults);
83
+ for (const key in baseObject) {
84
+ if (key === "__proto__" || key === "constructor") {
85
+ continue;
86
+ }
87
+ const value = baseObject[key];
88
+ if (value === null || value === void 0) {
89
+ continue;
90
+ }
91
+ if (merger && merger(object, key, value, namespace)) {
92
+ continue;
93
+ }
94
+ if (Array.isArray(value) && Array.isArray(object[key])) {
95
+ object[key] = [...value, ...object[key]];
96
+ } else if (isObject(value) && isObject(object[key])) {
97
+ object[key] = _defu(
98
+ value,
99
+ object[key],
100
+ (namespace ? `${namespace}.` : "") + key.toString(),
101
+ merger
102
+ );
103
+ } else {
104
+ object[key] = value;
105
+ }
106
+ }
107
+ return object;
108
+ }
109
+ function createDefu(merger) {
110
+ return (...arguments_) => (
111
+ // eslint-disable-next-line unicorn/no-array-reduce
112
+ arguments_.reduce((p, c) => _defu(p, c, "", merger), {})
113
+ );
114
+ }
115
+ const defu = createDefu();
116
+
117
+ function isPlainObject(obj) {
118
+ return Object.prototype.toString.call(obj) === "[object Object]";
119
+ }
120
+ function isLogObj(arg) {
121
+ if (!isPlainObject(arg)) {
122
+ return false;
123
+ }
124
+ if (!arg.message && !arg.args) {
125
+ return false;
126
+ }
127
+ if (arg.stack) {
128
+ return false;
129
+ }
130
+ return true;
131
+ }
132
+
133
+ let paused = false;
134
+ const queue = [];
135
+ class Consola {
136
+ constructor(options = {}) {
137
+ const types = options.types || LogTypes;
138
+ this.options = defu(
139
+ {
140
+ ...options,
141
+ defaults: { ...options.defaults },
142
+ level: _normalizeLogLevel(options.level, types),
143
+ reporters: [...options.reporters || []]
144
+ },
145
+ {
146
+ types: LogTypes,
147
+ throttle: 1e3,
148
+ throttleMin: 5,
149
+ formatOptions: {
150
+ date: true,
151
+ colors: false,
152
+ compact: true
153
+ }
154
+ }
155
+ );
156
+ for (const type in types) {
157
+ const defaults = {
158
+ type,
159
+ ...this.options.defaults,
160
+ ...types[type]
161
+ };
162
+ this[type] = this._wrapLogFn(defaults);
163
+ this[type].raw = this._wrapLogFn(
164
+ defaults,
165
+ true
166
+ );
167
+ }
168
+ if (this.options.mockFn) {
169
+ this.mockTypes();
170
+ }
171
+ this._lastLog = {};
172
+ }
173
+ get level() {
174
+ return this.options.level;
175
+ }
176
+ set level(level) {
177
+ this.options.level = _normalizeLogLevel(
178
+ level,
179
+ this.options.types,
180
+ this.options.level
181
+ );
182
+ }
183
+ prompt(message, opts) {
184
+ if (!this.options.prompt) {
185
+ throw new Error("prompt is not supported!");
186
+ }
187
+ return this.options.prompt(message, opts);
188
+ }
189
+ create(options) {
190
+ const instance = new Consola({
191
+ ...this.options,
192
+ ...options
193
+ });
194
+ if (this._mockFn) {
195
+ instance.mockTypes(this._mockFn);
196
+ }
197
+ return instance;
198
+ }
199
+ withDefaults(defaults) {
200
+ return this.create({
201
+ ...this.options,
202
+ defaults: {
203
+ ...this.options.defaults,
204
+ ...defaults
205
+ }
206
+ });
207
+ }
208
+ withTag(tag) {
209
+ return this.withDefaults({
210
+ tag: this.options.defaults.tag ? this.options.defaults.tag + ":" + tag : tag
211
+ });
212
+ }
213
+ addReporter(reporter) {
214
+ this.options.reporters.push(reporter);
215
+ return this;
216
+ }
217
+ removeReporter(reporter) {
218
+ if (reporter) {
219
+ const i = this.options.reporters.indexOf(reporter);
220
+ if (i >= 0) {
221
+ return this.options.reporters.splice(i, 1);
222
+ }
223
+ } else {
224
+ this.options.reporters.splice(0);
225
+ }
226
+ return this;
227
+ }
228
+ setReporters(reporters) {
229
+ this.options.reporters = Array.isArray(reporters) ? reporters : [reporters];
230
+ return this;
231
+ }
232
+ wrapAll() {
233
+ this.wrapConsole();
234
+ this.wrapStd();
235
+ }
236
+ restoreAll() {
237
+ this.restoreConsole();
238
+ this.restoreStd();
239
+ }
240
+ wrapConsole() {
241
+ for (const type in this.options.types) {
242
+ if (!console["__" + type]) {
243
+ console["__" + type] = console[type];
244
+ }
245
+ console[type] = this[type].raw;
246
+ }
247
+ }
248
+ restoreConsole() {
249
+ for (const type in this.options.types) {
250
+ if (console["__" + type]) {
251
+ console[type] = console["__" + type];
252
+ delete console["__" + type];
253
+ }
254
+ }
255
+ }
256
+ wrapStd() {
257
+ this._wrapStream(this.options.stdout, "log");
258
+ this._wrapStream(this.options.stderr, "log");
259
+ }
260
+ _wrapStream(stream, type) {
261
+ if (!stream) {
262
+ return;
263
+ }
264
+ if (!stream.__write) {
265
+ stream.__write = stream.write;
266
+ }
267
+ stream.write = (data) => {
268
+ this[type].raw(String(data).trim());
269
+ };
270
+ }
271
+ restoreStd() {
272
+ this._restoreStream(this.options.stdout);
273
+ this._restoreStream(this.options.stderr);
274
+ }
275
+ _restoreStream(stream) {
276
+ if (!stream) {
277
+ return;
278
+ }
279
+ if (stream.__write) {
280
+ stream.write = stream.__write;
281
+ delete stream.__write;
282
+ }
283
+ }
284
+ pauseLogs() {
285
+ paused = true;
286
+ }
287
+ resumeLogs() {
288
+ paused = false;
289
+ const _queue = queue.splice(0);
290
+ for (const item of _queue) {
291
+ item[0]._logFn(item[1], item[2]);
292
+ }
293
+ }
294
+ mockTypes(mockFn) {
295
+ const _mockFn = mockFn || this.options.mockFn;
296
+ this._mockFn = _mockFn;
297
+ if (typeof _mockFn !== "function") {
298
+ return;
299
+ }
300
+ for (const type in this.options.types) {
301
+ this[type] = _mockFn(type, this.options.types[type]) || this[type];
302
+ this[type].raw = this[type];
303
+ }
304
+ }
305
+ _wrapLogFn(defaults, isRaw) {
306
+ return (...args) => {
307
+ if (paused) {
308
+ queue.push([this, defaults, args, isRaw]);
309
+ return;
310
+ }
311
+ return this._logFn(defaults, args, isRaw);
312
+ };
313
+ }
314
+ _logFn(defaults, args, isRaw) {
315
+ if ((defaults.level || 0) > this.level) {
316
+ return false;
317
+ }
318
+ const logObj = {
319
+ date: /* @__PURE__ */ new Date(),
320
+ args: [],
321
+ ...defaults,
322
+ level: _normalizeLogLevel(defaults.level, this.options.types)
323
+ };
324
+ if (!isRaw && args.length === 1 && isLogObj(args[0])) {
325
+ Object.assign(logObj, args[0]);
326
+ } else {
327
+ logObj.args = [...args];
328
+ }
329
+ if (logObj.message) {
330
+ logObj.args.unshift(logObj.message);
331
+ delete logObj.message;
332
+ }
333
+ if (logObj.additional) {
334
+ if (!Array.isArray(logObj.additional)) {
335
+ logObj.additional = logObj.additional.split("\n");
336
+ }
337
+ logObj.args.push("\n" + logObj.additional.join("\n"));
338
+ delete logObj.additional;
339
+ }
340
+ logObj.type = typeof logObj.type === "string" ? logObj.type.toLowerCase() : "log";
341
+ logObj.tag = typeof logObj.tag === "string" ? logObj.tag : "";
342
+ const resolveLog = (newLog = false) => {
343
+ const repeated = (this._lastLog.count || 0) - this.options.throttleMin;
344
+ if (this._lastLog.object && repeated > 0) {
345
+ const args2 = [...this._lastLog.object.args];
346
+ if (repeated > 1) {
347
+ args2.push(`(repeated ${repeated} times)`);
348
+ }
349
+ this._log({ ...this._lastLog.object, args: args2 });
350
+ this._lastLog.count = 1;
351
+ }
352
+ if (newLog) {
353
+ this._lastLog.object = logObj;
354
+ this._log(logObj);
355
+ }
356
+ };
357
+ clearTimeout(this._lastLog.timeout);
358
+ const diffTime = this._lastLog.time && logObj.date ? logObj.date.getTime() - this._lastLog.time.getTime() : 0;
359
+ this._lastLog.time = logObj.date;
360
+ if (diffTime < this.options.throttle) {
361
+ try {
362
+ const serializedLog = JSON.stringify([
363
+ logObj.type,
364
+ logObj.tag,
365
+ logObj.args
366
+ ]);
367
+ const isSameLog = this._lastLog.serialized === serializedLog;
368
+ this._lastLog.serialized = serializedLog;
369
+ if (isSameLog) {
370
+ this._lastLog.count = (this._lastLog.count || 0) + 1;
371
+ if (this._lastLog.count > this.options.throttleMin) {
372
+ this._lastLog.timeout = setTimeout(
373
+ resolveLog,
374
+ this.options.throttle
375
+ );
376
+ return;
377
+ }
378
+ }
379
+ } catch {
380
+ }
381
+ }
382
+ resolveLog(true);
383
+ }
384
+ _log(logObj) {
385
+ for (const reporter of this.options.reporters) {
386
+ reporter.log(logObj, {
387
+ options: this.options
388
+ });
389
+ }
390
+ }
391
+ }
392
+ function _normalizeLogLevel(input, types = {}, defaultLevel = 3) {
393
+ if (input === void 0) {
394
+ return defaultLevel;
395
+ }
396
+ if (typeof input === "number") {
397
+ return input;
398
+ }
399
+ if (types[input] && types[input].level !== void 0) {
400
+ return types[input].level;
401
+ }
402
+ return defaultLevel;
403
+ }
404
+ Consola.prototype.add = Consola.prototype.addReporter;
405
+ Consola.prototype.remove = Consola.prototype.removeReporter;
406
+ Consola.prototype.clear = Consola.prototype.removeReporter;
407
+ Consola.prototype.withScope = Consola.prototype.withTag;
408
+ Consola.prototype.mock = Consola.prototype.mockTypes;
409
+ Consola.prototype.pause = Consola.prototype.pauseLogs;
410
+ Consola.prototype.resume = Consola.prototype.resumeLogs;
411
+ function createConsola$1(options = {}) {
412
+ return new Consola(options);
413
+ }
414
+
415
+ function parseStack(stack) {
416
+ const cwd = process.cwd() + node_path.sep;
417
+ const lines = stack.split("\n").splice(1).map((l) => l.trim().replace("file://", "").replace(cwd, ""));
418
+ return lines;
419
+ }
420
+
421
+ function writeStream(data, stream) {
422
+ const write = stream.__write || stream.write;
423
+ return write.call(stream, data);
424
+ }
425
+
426
+ const bracket = (x) => x ? `[${x}]` : "";
427
+ class BasicReporter {
428
+ formatStack(stack, opts) {
429
+ return " " + parseStack(stack).join("\n ");
430
+ }
431
+ formatArgs(args, opts) {
432
+ const _args = args.map((arg) => {
433
+ if (arg && typeof arg.stack === "string") {
434
+ return arg.message + "\n" + this.formatStack(arg.stack, opts);
435
+ }
436
+ return arg;
437
+ });
438
+ return node_util.formatWithOptions(opts, ..._args);
439
+ }
440
+ formatDate(date, opts) {
441
+ return opts.date ? date.toLocaleTimeString() : "";
442
+ }
443
+ filterAndJoin(arr) {
444
+ return arr.filter(Boolean).join(" ");
445
+ }
446
+ formatLogObj(logObj, opts) {
447
+ const message = this.formatArgs(logObj.args, opts);
448
+ if (logObj.type === "box") {
449
+ return "\n" + [
450
+ bracket(logObj.tag),
451
+ logObj.title && logObj.title,
452
+ ...message.split("\n")
453
+ ].filter(Boolean).map((l) => " > " + l).join("\n") + "\n";
454
+ }
455
+ return this.filterAndJoin([
456
+ bracket(logObj.type),
457
+ bracket(logObj.tag),
458
+ message
459
+ ]);
460
+ }
461
+ log(logObj, ctx) {
462
+ const line = this.formatLogObj(logObj, {
463
+ columns: ctx.options.stdout.columns || 0,
464
+ ...ctx.options.formatOptions
465
+ });
466
+ return writeStream(
467
+ line + "\n",
468
+ logObj.level < 2 ? ctx.options.stderr || process.stderr : ctx.options.stdout || process.stdout
469
+ );
470
+ }
471
+ }
472
+
473
+ function createConsola(options = {}) {
474
+ let level = LogLevels.info;
475
+ if (process.env.CONSOLA_LEVEL) {
476
+ level = Number.parseInt(process.env.CONSOLA_LEVEL) ?? level;
477
+ }
478
+ const consola2 = createConsola$1({
479
+ level,
480
+ defaults: { level },
481
+ stdout: process.stdout,
482
+ stderr: process.stderr,
483
+ reporters: options.reporters || [new BasicReporter()],
484
+ ...options
485
+ });
486
+ return consola2;
487
+ }
488
+ createConsola();
489
+
490
+ const logger = createConsola({
491
+ level: LogLevels.debug,
8
492
  formatOptions: {
9
493
  colors: true,
10
494
  date: false
11
495
  }
12
496
  });
13
497
 
14
- exports.LogLevels = basic.LogLevels;
498
+ exports.LogLevels = LogLevels;
15
499
  exports.consola = logger;
16
500
  exports.logger = logger;
17
501
  exports.rootLogger = logger;
package/dist/node.d.cts CHANGED
@@ -1,7 +1,126 @@
1
- import * as consola_core from 'consola/core';
2
- export * from 'consola/basic';
3
- export { LogLevels } from 'consola/basic';
1
+ type SelectOption = {
2
+ label: string;
3
+ value: string;
4
+ hint?: string;
5
+ };
6
+ type TextOptions = {
7
+ type?: "text";
8
+ default?: string;
9
+ placeholder?: string;
10
+ initial?: string;
11
+ };
12
+ type ConfirmOptions = {
13
+ type: "confirm";
14
+ initial?: boolean;
15
+ };
16
+ type SelectOptions = {
17
+ type: "select";
18
+ initial?: string;
19
+ options: (string | SelectOption)[];
20
+ };
21
+ type MultiSelectOptions = {
22
+ type: "multiselect";
23
+ initial?: string;
24
+ options: string[] | SelectOption[];
25
+ required?: boolean;
26
+ };
27
+ type PromptOptions = TextOptions | ConfirmOptions | SelectOptions | MultiSelectOptions;
28
+ type inferPromptReturnType<T extends PromptOptions> = T extends TextOptions ? string : T extends ConfirmOptions ? boolean : T extends SelectOptions ? T["options"][number] : T extends MultiSelectOptions ? T["options"] : unknown;
29
+ declare function prompt<_ = any, __ = any, T extends PromptOptions = TextOptions>(message: string, opts?: PromptOptions): Promise<inferPromptReturnType<T>>;
4
30
 
5
- declare const logger: consola_core.ConsolaInstance;
31
+ type LogLevel = 0 | 1 | 2 | 3 | 4 | 5 | (number & {});
32
+ declare const LogLevels: Record<LogType, number>;
33
+ type LogType = "silent" | "fatal" | "error" | "warn" | "log" | "info" | "success" | "fail" | "ready" | "start" | "box" | "debug" | "trace" | "verbose";
34
+ declare const LogTypes: Record<LogType, Partial<LogObject>>;
6
35
 
7
- export { logger as consola, logger, logger as rootLogger };
36
+ interface ConsolaOptions {
37
+ reporters: ConsolaReporter[];
38
+ types: Record<LogType, InputLogObject>;
39
+ level: LogLevel;
40
+ defaults: InputLogObject;
41
+ throttle: number;
42
+ throttleMin: number;
43
+ stdout?: NodeJS.WriteStream;
44
+ stderr?: NodeJS.WriteStream;
45
+ mockFn?: (type: LogType, defaults: InputLogObject) => (...args: any) => void;
46
+ prompt?: typeof prompt | undefined;
47
+ formatOptions: FormatOptions;
48
+ }
49
+ /**
50
+ * @see https://nodejs.org/api/util.html#util_util_inspect_object_showhidden_depth_colors
51
+ */
52
+ interface FormatOptions {
53
+ columns?: number;
54
+ date?: boolean;
55
+ colors?: boolean;
56
+ compact?: boolean | number;
57
+ [key: string]: unknown;
58
+ }
59
+ interface InputLogObject {
60
+ level?: LogLevel;
61
+ tag?: string;
62
+ type?: LogType;
63
+ message?: string;
64
+ additional?: string | string[];
65
+ args?: any[];
66
+ date?: Date;
67
+ }
68
+ interface LogObject extends InputLogObject {
69
+ level: LogLevel;
70
+ type: LogType;
71
+ tag: string;
72
+ args: any[];
73
+ date: Date;
74
+ [key: string]: unknown;
75
+ }
76
+ interface ConsolaReporter {
77
+ log: (logObj: LogObject, ctx: {
78
+ options: ConsolaOptions;
79
+ }) => void;
80
+ }
81
+
82
+ declare class Consola {
83
+ options: ConsolaOptions;
84
+ _lastLog: {
85
+ serialized?: string;
86
+ object?: LogObject;
87
+ count?: number;
88
+ time?: Date;
89
+ timeout?: ReturnType<typeof setTimeout>;
90
+ };
91
+ _mockFn?: ConsolaOptions["mockFn"];
92
+ constructor(options?: Partial<ConsolaOptions>);
93
+ get level(): LogLevel;
94
+ set level(level: LogLevel);
95
+ prompt<T extends PromptOptions>(message: string, opts?: T): Promise<T extends TextOptions ? string : T extends ConfirmOptions ? boolean : T extends SelectOptions ? T["options"][number] : T extends MultiSelectOptions ? T["options"] : unknown>;
96
+ create(options: Partial<ConsolaOptions>): ConsolaInstance;
97
+ withDefaults(defaults: InputLogObject): ConsolaInstance;
98
+ withTag(tag: string): ConsolaInstance;
99
+ addReporter(reporter: ConsolaReporter): this;
100
+ removeReporter(reporter: ConsolaReporter): ConsolaReporter[] | this;
101
+ setReporters(reporters: ConsolaReporter[]): this;
102
+ wrapAll(): void;
103
+ restoreAll(): void;
104
+ wrapConsole(): void;
105
+ restoreConsole(): void;
106
+ wrapStd(): void;
107
+ _wrapStream(stream: NodeJS.WriteStream | undefined, type: LogType): void;
108
+ restoreStd(): void;
109
+ _restoreStream(stream?: NodeJS.WriteStream): void;
110
+ pauseLogs(): void;
111
+ resumeLogs(): void;
112
+ mockTypes(mockFn?: ConsolaOptions["mockFn"]): void;
113
+ _wrapLogFn(defaults: InputLogObject, isRaw?: boolean): (...args: any[]) => false | undefined;
114
+ _logFn(defaults: InputLogObject, args: any[], isRaw?: boolean): false | undefined;
115
+ _log(logObj: LogObject): void;
116
+ }
117
+ interface LogFn {
118
+ (message: InputLogObject | any, ...args: any[]): void;
119
+ raw: (...args: any[]) => void;
120
+ }
121
+ type ConsolaInstance = Consola & Record<LogType, LogFn>;
122
+ declare function createConsola(options?: Partial<ConsolaOptions>): ConsolaInstance;
123
+
124
+ declare const logger: ConsolaInstance;
125
+
126
+ export { Consola, type ConsolaInstance, type ConsolaOptions, type ConsolaReporter, type FormatOptions, type InputLogObject, type LogLevel, LogLevels, type LogObject, type LogType, LogTypes, logger as consola, createConsola, logger, logger as rootLogger };