-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogger.ts
More file actions
1891 lines (1795 loc) · 55.7 KB
/
logger.ts
File metadata and controls
1891 lines (1795 loc) · 55.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @fileoverview Console logging utilities with line prefix support.
* Provides enhanced console methods with formatted output capabilities.
*/
import process from 'node:process'
import isUnicodeSupported from './external/@socketregistry/is-unicode-supported'
import yoctocolorsCjs from './external/yoctocolors-cjs'
import {
ArrayPrototypeAt,
ArrayPrototypeSlice,
ErrorCtor,
MathMin,
ObjectDefineProperties,
ObjectEntries,
ObjectGetOwnPropertySymbols,
ProxyCtor,
ReflectApply,
ReflectConstruct,
ReflectOwnKeys,
StringPrototypeReplace,
WeakMapCtor,
} from './primordials'
import { applyLinePrefix, isBlankString } from './strings'
import { getTheme, onThemeChange } from './themes/context'
import { THEMES } from './themes/themes'
import type { ColorValue } from './colors'
/**
* Log symbols for terminal output with colored indicators.
*
* Each symbol provides visual feedback for different message types, with
* Unicode and ASCII fallback support.
*
* @example
* ```typescript
* import { LOG_SYMBOLS } from '@socketsecurity/lib'
*
* console.log(`${LOG_SYMBOLS.success} Operation completed`)
* console.log(`${LOG_SYMBOLS.fail} Operation failed`)
* console.log(`${LOG_SYMBOLS.warn} Warning message`)
* console.log(`${LOG_SYMBOLS.info} Information message`)
* console.log(`${LOG_SYMBOLS.step} Processing step`)
* console.log(`${LOG_SYMBOLS.progress} Working on task`)
* ```
*/
type LogSymbols = {
/** Red colored failure symbol (✖ or × in ASCII) */
fail: string
/** Blue colored information symbol (ℹ or i in ASCII) */
info: string
/** Cyan colored progress indicator symbol (∴ or :. in ASCII) */
progress: string
/** Cyan colored skip symbol (↻ or @ in ASCII) */
skip: string
/** Cyan colored step symbol (→ or > in ASCII) */
step: string
/** Green colored success symbol (✔ or √ in ASCII) */
success: string
/** Yellow colored warning symbol (⚠ or ‼ in ASCII) */
warn: string
}
/**
* Type definition for logger methods that mirror console methods.
*
* All methods return the logger instance for method chaining.
*/
type LoggerMethods = {
[K in keyof typeof console]: (typeof console)[K] extends (
...args: infer A
) => any
? (...args: A) => Logger
: (typeof console)[K]
}
/**
* A task that can be executed with automatic start/complete logging.
*
* @example
* ```typescript
* const task = logger.createTask('Database migration')
* task.run(() => {
* // Migration logic here
* })
* // Logs: "Starting task: Database migration"
* // Logs: "Completed task: Database migration"
* ```
*/
interface Task {
/**
* Executes the task function with automatic logging.
*
* @template T - The return type of the task function
* @param f - The function to execute
* @returns The result of the task function
*/
run<T>(f: () => T): T
}
export type { LogSymbols, LoggerMethods, Task }
const globalConsole = console
let _Console: typeof import('node:console').Console | undefined
let _consoleSymbols: symbol[] | undefined
let _kGroupIndentationWidthSymbol: symbol | undefined
let _prototypeInitialized = false
// Private singleton instance
let _logger: Logger | undefined
/**
* Log symbols for terminal output with colored indicators.
*
* Provides colored Unicode symbols (✖, ℹ, ∴, →, ✔, ⚠) with ASCII fallbacks (×, i, :., >, √, ‼)
* for terminals that don't support Unicode. Symbols are colored according to the active
* theme's color palette (error, info, reason, step, success, warning).
*
* The symbols are lazily initialized on first access and automatically update when the
* fallback theme changes (via setTheme()). Note that LOG_SYMBOLS reflect the global
* fallback theme, not async-local theme contexts from withTheme().
*
* @example
* ```typescript
* import { LOG_SYMBOLS } from '@socketsecurity/lib'
*
* console.log(`${LOG_SYMBOLS.fail} Build failed`) // Theme error color ✖
* console.log(`${LOG_SYMBOLS.info} Starting process`) // Theme info color ℹ
* console.log(`${LOG_SYMBOLS.progress} Working on task`) // Theme step color ∴
* console.log(`${LOG_SYMBOLS.step} Processing files`) // Theme step color →
* console.log(`${LOG_SYMBOLS.success} Build completed`) // Theme success color ✔
* console.log(`${LOG_SYMBOLS.warn} Deprecated API used`) // Theme warning color ⚠
* ```
*/
export const LOG_SYMBOLS = /*@__PURE__*/ (() => {
const target: Record<string, string> = {
__proto__: null,
} as unknown as Record<string, string>
let initialized = false
// Mutable handler to simulate a frozen target.
const handler: ProxyHandler<Record<string, string>> = {
__proto__: null,
} as unknown as ProxyHandler<Record<string, string>>
const updateSymbols = () => {
const supported = isUnicodeSupported()
const colors = getYoctocolors()
const theme = getTheme()
// Get colors from theme
const successColor = theme.colors.success
const errorColor = theme.colors.error
const warningColor = theme.colors.warning
const infoColor = theme.colors.info
const stepColor = theme.colors.step
// Update symbol values
target['fail'] = applyColor(supported ? '✖' : '×', errorColor, colors)
target['info'] = applyColor(supported ? 'ℹ' : 'i', infoColor, colors)
target['progress'] = applyColor(supported ? '∴' : ':.', stepColor, colors)
target['reason'] = colors.dim(
applyColor(supported ? '∴' : ':.', warningColor, colors),
)
target['skip'] = applyColor(supported ? '↻' : '@', stepColor, colors)
target['step'] = applyColor(supported ? '→' : '>', stepColor, colors)
target['success'] = applyColor(supported ? '✔' : '√', successColor, colors)
target['warn'] = applyColor(supported ? '⚠' : '‼', warningColor, colors)
}
const init = () => {
if (initialized) {
return
}
updateSymbols()
initialized = true
// The handler of a Proxy is mutable after proxy instantiation.
// We delete the traps to defer to native behavior for better performance.
for (const trapName in handler) {
delete handler[trapName as keyof ProxyHandler<Record<string, string>>]
}
}
const reset = () => {
if (!initialized) {
return
}
// Update symbols with new theme colors
updateSymbols()
}
for (const trapName of ReflectOwnKeys(Reflect)) {
const fn = (Reflect as Record<PropertyKey, unknown>)[trapName]
if (typeof fn === 'function') {
;(handler as Record<string, (...args: unknown[]) => unknown>)[
trapName as string
] = (...args: unknown[]) => {
init()
return fn(...args)
}
}
}
// Listen for theme changes and reset symbols
onThemeChange(() => {
reset()
})
return new ProxyCtor(target, handler)
})()
const boundConsoleEntries = [
// Add bound properties from console[kBindProperties](ignoreErrors, colorMode, groupIndentation).
// https://github.com/nodejs/node/blob/v24.0.1/lib/internal/console/constructor.js#L230-L265
'_stderrErrorHandler',
'_stdoutErrorHandler',
// Add methods that need to be bound to function properly.
'assert',
'clear',
'count',
'countReset',
'createTask',
'debug',
'dir',
'dirxml',
'error',
// Skip group methods because in at least Node 20 with the Node --frozen-intrinsics
// flag it triggers a readonly property for Symbol(kGroupIndent). Instead, we
// implement these methods ourselves.
//'group',
//'groupCollapsed',
//'groupEnd',
'info',
'log',
'table',
'time',
'timeEnd',
'timeLog',
'trace',
'warn',
]
.filter(n => typeof (globalConsole as any)[n] === 'function')
.map(n => [n, (globalConsole as any)[n].bind(globalConsole)])
const consolePropAttributes = {
__proto__: null,
writable: true,
enumerable: false,
configurable: true,
}
const maxIndentation = 1000
/**
* WeakMap storing the Console instance for each Logger.
*
* Console creation is lazy - deferred until first logging method call.
* This allows logger to be imported during early Node.js bootstrap before
* stdout is ready, avoiding ERR_CONSOLE_WRITABLE_STREAM errors.
*/
const privateConsole = new WeakMapCtor()
/**
* WeakMap storing constructor arguments for lazy Console initialization.
*
* WeakMap is required instead of a private field (#constructorArgs) because:
* 1. Private fields can't be accessed from dynamically created functions
* 2. Logger adds console methods dynamically to its prototype (lines 1560+)
* 3. These dynamic methods need constructor args for lazy initialization
* 4. WeakMap allows both regular methods and dynamic functions to access args
*
* The args are deleted from the WeakMap after Console is created (memory cleanup).
*/
const privateConstructorArgs = new WeakMapCtor()
/**
* Symbol for incrementing the internal log call counter.
*
* This is an internal symbol used to track the number of times logging
* methods have been called on a logger instance.
*/
export const incLogCallCountSymbol = Symbol.for('logger.logCallCount++')
/**
* Symbol for tracking whether the last logged line was blank.
*
* This is used internally to prevent multiple consecutive blank lines
* and to determine whether to add spacing before certain messages.
*/
export const lastWasBlankSymbol = Symbol.for('logger.lastWasBlank')
/**
* Enhanced console logger with indentation, colored symbols, and stream management.
*
* Provides a fluent API for logging with automatic indentation tracking, colored
* status symbols, separate stderr/stdout management, and method chaining. All
* methods return `this` for easy chaining.
*
* Features:
* - Automatic line prefixing with indentation
* - Colored status symbols (success, fail, warn, info)
* - Separate indentation tracking for stderr and stdout
* - Stream-bound logger instances via `.stderr` and `.stdout`
* - Group/indentation management
* - Progress indicators with clearable lines
* - Task execution with automatic logging
*
* @example
* ```typescript
* import { logger } from '@socketsecurity/lib'
*
* // Basic logging with symbols
* logger.success('Build completed')
* logger.fail('Build failed')
* logger.warn('Deprecated API')
* logger.info('Starting process')
*
* // Indentation and grouping
* logger.log('Processing files:')
* logger.indent()
* logger.log('file1.js')
* logger.log('file2.js')
* logger.dedent()
*
* // Method chaining
* logger
* .log('Step 1')
* .indent()
* .log('Substep 1.1')
* .log('Substep 1.2')
* .dedent()
* .log('Step 2')
*
* // Stream-specific logging
* logger.stdout.log('Normal output')
* logger.stderr.error('Error message')
*
* // Progress indicators
* logger.progress('Processing...')
* // ... do work ...
* logger.clearLine()
* logger.success('Done')
*
* // Task execution
* const task = logger.createTask('Migration')
* task.run(() => {
* // Migration logic
* })
* ```
*/
/*@__PURE__*/
export class Logger {
/**
* Static reference to log symbols for convenience.
*
* @example
* ```typescript
* console.log(`${Logger.LOG_SYMBOLS.success} Done`)
* ```
*/
static LOG_SYMBOLS = LOG_SYMBOLS
#parent?: Logger
#boundStream?: 'stderr' | 'stdout'
#stderrLogger?: Logger
#stdoutLogger?: Logger
#stderrIndention = ''
#stdoutIndention = ''
#stderrLastWasBlank = false
#stdoutLastWasBlank = false
#logCallCount = 0
#options: Record<string, unknown>
#originalStdout?: NodeJS.WritableStream | undefined
#theme?: import('./themes/types').Theme
/**
* Creates a new Logger instance.
*
* When called without arguments, creates a logger using the default
* `process.stdout` and `process.stderr` streams. Can accept custom
* console constructor arguments for advanced use cases.
*
* @param args - Optional console constructor arguments
*
* @example
* ```typescript
* // Default logger
* const logger = new Logger()
*
* // Custom streams (advanced)
* const customLogger = new Logger({
* stdout: customWritableStream,
* stderr: customErrorStream
* })
* ```
*/
constructor(...args: unknown[]) {
// Store constructor args for lazy Console initialization.
privateConstructorArgs.set(this, args)
// Store options if provided (for future extensibility)
const options = args['0']
if (typeof options === 'object' && options !== null) {
this.#options = { __proto__: null, ...options }
// Store reference to original stdout stream to bypass Console formatting
this.#originalStdout = (
options as { stdout?: NodeJS.WritableStream }
).stdout
// Handle theme option
const themeOption = (options as { theme?: unknown }).theme
if (themeOption) {
if (typeof themeOption === 'string') {
// Theme name - resolve to Theme object
const resolved = THEMES[themeOption as keyof typeof THEMES]
if (resolved) {
this.#theme = resolved
}
} else {
// Theme object
this.#theme = themeOption as import('./themes/types').Theme
}
}
} else {
this.#options = { __proto__: null }
}
// Note: Console initialization is now lazy (happens on first use).
// This allows logger to be imported during early bootstrap before
// stdout is ready, avoiding ERR_CONSOLE_WRITABLE_STREAM errors.
}
/**
* Apply a console method with indentation.
* @private
*/
#apply(
methodName: string,
args: unknown[],
stream?: 'stderr' | 'stdout',
): this {
const con = this.#getConsole()
const text = ArrayPrototypeAt(args, 0)
const hasText = typeof text === 'string'
// Determine which stream this method writes to
const targetStream = stream || (methodName === 'log' ? 'stdout' : 'stderr')
const indent = this.#getIndent(targetStream)
const logArgs = hasText
? [
applyLinePrefix(text, { prefix: indent }),
...ArrayPrototypeSlice(args, 1),
]
: args
ReflectApply(
con[methodName] as (...args: unknown[]) => unknown,
con,
logArgs,
)
this[lastWasBlankSymbol](hasText && isBlankString(logArgs[0]), targetStream)
;(this as any)[incLogCallCountSymbol]()
return this
}
/**
* Get the Console instance for this logger, creating it lazily on first access.
*
* This lazy initialization allows the logger to be imported during early
* Node.js bootstrap before stdout is ready, avoiding Console initialization
* errors (ERR_CONSOLE_WRITABLE_STREAM).
*
* @private
*/
#getConsole(): typeof console & Record<string, unknown> {
// Ensure prototype is initialized before creating Console.
ensurePrototypeInitialized()
let con = privateConsole.get(this)
if (!con) {
// Lazy initialization - create Console on first use.
const ctorArgs = privateConstructorArgs.get(this) ?? []
if (ctorArgs.length) {
con = constructConsole(...ctorArgs)
} else {
// Create a new console that acts like the builtin one so that it will
// work with Node's --frozen-intrinsics flag.
con = constructConsole({
stdout: process.stdout,
stderr: process.stderr,
}) as typeof console & Record<string, unknown>
for (const { 0: key, 1: method } of boundConsoleEntries) {
con[key] = method
}
}
privateConsole.set(this, con)
// Clean up constructor args - no longer needed after Console creation.
privateConstructorArgs.delete(this)
}
return con
}
/**
* Get indentation for a specific stream.
* @private
*/
#getIndent(stream: 'stderr' | 'stdout'): string {
const root = this.#getRoot()
return stream === 'stderr' ? root.#stderrIndention : root.#stdoutIndention
}
/**
* Get lastWasBlank state for a specific stream.
* @private
*/
#getLastWasBlank(stream: 'stderr' | 'stdout'): boolean {
const root = this.#getRoot()
return stream === 'stderr'
? root.#stderrLastWasBlank
: root.#stdoutLastWasBlank
}
/**
* Get the root logger (for accessing shared indentation state).
* @private
*/
#getRoot(): Logger {
return this.#parent || this
}
/**
* Get logger-specific symbols using the resolved theme.
* @private
*/
#getSymbols(): LogSymbols {
const theme = this.#getTheme()
const supported = isUnicodeSupported()
const colors = getYoctocolors()
return {
__proto__: null,
fail: applyColor(supported ? '✖' : '×', theme.colors.error, colors),
info: applyColor(supported ? 'ℹ' : 'i', theme.colors.info, colors),
progress: applyColor(supported ? '∴' : ':.', theme.colors.step, colors),
skip: applyColor(supported ? '↻' : '@', theme.colors.step, colors),
step: applyColor(supported ? '→' : '>', theme.colors.step, colors),
success: applyColor(supported ? '✔' : '√', theme.colors.success, colors),
warn: applyColor(supported ? '⚠' : '‼', theme.colors.warning, colors),
} as LogSymbols
}
/**
* Get the target stream for this logger instance.
* @private
*/
#getTargetStream(): 'stderr' | 'stdout' {
return this.#boundStream || 'stderr'
}
/**
* Get the resolved theme for this logger instance.
* Returns instance theme if set, otherwise falls back to context theme.
* @private
*/
#getTheme(): import('./themes/types').Theme {
return this.#theme ?? getTheme()
}
/**
* Set indentation for a specific stream.
* @private
*/
#setIndent(stream: 'stderr' | 'stdout', value: string): void {
const root = this.#getRoot()
if (stream === 'stderr') {
root.#stderrIndention = value
} else {
root.#stdoutIndention = value
}
}
/**
* Set lastWasBlank state for a specific stream.
* @private
*/
#setLastWasBlank(stream: 'stderr' | 'stdout', value: boolean): void {
const root = this.#getRoot()
if (stream === 'stderr') {
root.#stderrLastWasBlank = value
} else {
root.#stdoutLastWasBlank = value
}
}
/**
* Strip log symbols from the start of text.
* @private
*/
#stripSymbols(text: string): string {
// Strip both unicode and emoji forms of log symbols from the start.
// Matches Unicode: ✖, ✗, ×, ✖️, ⚠, ‼, ⚠️, ✔, ✓, √, ✔️, ✓️, ℹ, ℹ️, →, ∴, ↻
// Matches ASCII fallbacks: ×, ‼, √, i, >, :., @
// Also handles variation selectors (U+FE0F) and whitespace after symbol.
// Note: We don't strip standalone 'i', '>', or '@' to avoid breaking words, but we do strip ':.' as it's unambiguous.
return StringPrototypeReplace(
text,
/^(?:[✖✗×⚠‼✔✓√ℹ→∴↻]|:.)[\uFE0F\s]*/u,
'',
)
}
/**
* Apply a method with a symbol prefix.
* @private
*/
#symbolApply(symbolType: string, args: unknown[]): this {
const con = this.#getConsole()
let text = ArrayPrototypeAt(args, 0)
// biome-ignore lint/suspicious/noImplicitAnyLet: Flexible argument handling.
let extras
if (typeof text === 'string') {
text = this.#stripSymbols(text)
extras = ArrayPrototypeSlice(args, 1)
} else {
extras = args
text = ''
}
// Note: Meta status messages (info/fail/etc) always go to stderr.
const indent = this.#getIndent('stderr')
const symbols = this.#getSymbols()
con.error(
applyLinePrefix(`${symbols[symbolType as keyof LogSymbols]} ${text}`, {
prefix: indent,
}),
...extras,
)
this[lastWasBlankSymbol](false, 'stderr')
;(this as any)[incLogCallCountSymbol]()
return this
}
/**
* Gets a logger instance bound exclusively to stderr.
*
* All logging operations on this instance will write to stderr only.
* Indentation is tracked separately from stdout. The instance is
* cached and reused on subsequent accesses.
*
* @returns A logger instance bound to stderr
*
* @example
* ```typescript
* // Write errors to stderr
* logger.stderr.error('Configuration invalid')
* logger.stderr.warn('Using fallback settings')
*
* // Indent only affects stderr
* logger.stderr.indent()
* logger.stderr.error('Nested error details')
* logger.stderr.dedent()
* ```
*/
get stderr(): Logger {
if (!this.#stderrLogger) {
// Pass parent's constructor args to maintain config.
const ctorArgs = privateConstructorArgs.get(this) ?? []
const instance = new Logger(...ctorArgs)
instance.#parent = this
instance.#boundStream = 'stderr'
instance.#options = { __proto__: null, ...this.#options }
if (this.#theme) {
instance.#theme = this.#theme
}
this.#stderrLogger = instance
}
return this.#stderrLogger
}
/**
* Gets a logger instance bound exclusively to stdout.
*
* All logging operations on this instance will write to stdout only.
* Indentation is tracked separately from stderr. The instance is
* cached and reused on subsequent accesses.
*
* @returns A logger instance bound to stdout
*
* @example
* ```typescript
* // Write normal output to stdout
* logger.stdout.log('Processing started')
* logger.stdout.log('Items processed: 42')
*
* // Indent only affects stdout
* logger.stdout.indent()
* logger.stdout.log('Detailed output')
* logger.stdout.dedent()
* ```
*/
get stdout(): Logger {
if (!this.#stdoutLogger) {
// Pass parent's constructor args to maintain config.
const ctorArgs = privateConstructorArgs.get(this) ?? []
const instance = new Logger(...ctorArgs)
instance.#parent = this
instance.#boundStream = 'stdout'
instance.#options = { __proto__: null, ...this.#options }
if (this.#theme) {
instance.#theme = this.#theme
}
this.#stdoutLogger = instance
}
return this.#stdoutLogger
}
/**
* Gets the total number of log calls made on this logger instance.
*
* Tracks all logging method calls including `log()`, `error()`, `warn()`,
* `success()`, `fail()`, etc. Useful for testing and monitoring logging activity.
*
* @returns The number of times logging methods have been called
*
* @example
* ```typescript
* logger.log('Message 1')
* logger.error('Message 2')
* console.log(logger.logCallCount) // 2
* ```
*/
get logCallCount() {
const root = this.#getRoot()
return root.#logCallCount
}
/**
* Increments the internal log call counter.
*
* This is called automatically by logging methods and should not
* be called directly in normal usage.
*
* @returns The logger instance for chaining
*/
[incLogCallCountSymbol]() {
const root = this.#getRoot()
root.#logCallCount += 1
return this
}
/**
* Sets whether the last logged line was blank.
*
* Used internally to track blank lines and prevent duplicate spacing.
* This is called automatically by logging methods.
*
* @param value - Whether the last line was blank
* @param stream - Optional stream to update (defaults to both streams if not bound, or target stream if bound)
* @returns The logger instance for chaining
*/
[lastWasBlankSymbol](value: unknown, stream?: 'stderr' | 'stdout'): this {
if (stream) {
// Explicit stream specified
this.#setLastWasBlank(stream, !!value)
} else if (this.#boundStream) {
// Stream-bound logger - affect only the bound stream
this.#setLastWasBlank(this.#boundStream, !!value)
} else {
// Root logger with no stream specified - affect both streams
this.#setLastWasBlank('stderr', !!value)
this.#setLastWasBlank('stdout', !!value)
}
return this
}
/**
* Logs an assertion failure message if the value is falsy.
*
* Works like `console.assert()` but returns the logger for chaining.
* If the value is truthy, nothing is logged. If falsy, logs an error
* message with an assertion failure.
*
* @param value - The value to test
* @param message - Optional message and additional arguments to log
* @returns The logger instance for chaining
*
* @example
* ```typescript
* logger.assert(true, 'This will not log')
* logger.assert(false, 'Assertion failed: value is false')
* logger.assert(items.length > 0, 'No items found')
* ```
*/
assert(value: unknown, ...message: unknown[]): this {
const con = this.#getConsole()
con.assert(value, message[0] as string, ...message.slice(1))
this[lastWasBlankSymbol](false)
return value ? this : this[incLogCallCountSymbol]()
}
/**
* Clears the current line in the terminal.
*
* Moves the cursor to the beginning of the line and clears all content.
* Works in both TTY and non-TTY environments. Useful for clearing
* progress indicators created with `progress()`.
*
* The stream to clear (stderr or stdout) depends on whether the logger
* is stream-bound.
*
* @returns The logger instance for chaining
*
* @example
* ```typescript
* logger.progress('Loading...')
* // ... do work ...
* logger.clearLine()
* logger.success('Loaded')
*
* // Clear multiple progress updates
* for (const file of files) {
* logger.progress(`Processing ${file}`)
* processFile(file)
* logger.clearLine()
* }
* logger.success('All files processed')
* ```
*/
clearLine(): this {
const con = this.#getConsole()
const stream = this.#getTargetStream()
const streamObj = (
stream === 'stderr' ? con['_stderr'] : con['_stdout']
) as NodeJS.WriteStream & {
isTTY: boolean
cursorTo: (x: number) => void
clearLine: (dir: number) => void
write: (text: string) => boolean
}
if (streamObj.isTTY) {
streamObj.cursorTo(0)
streamObj.clearLine(0)
} else {
streamObj.write('\r\x1b[K')
}
return this
}
/**
* Clears the visible terminal screen.
*
* Only available on the main logger instance, not on stream-bound instances
* (`.stderr` or `.stdout`). Resets the log call count and blank line tracking
* if the output is a TTY.
*
* @returns The logger instance for chaining
* @throws {Error} If called on a stream-bound logger instance
*
* @example
* ```typescript
* logger.log('Some output')
* logger.clearVisible() // Screen is now clear
*
* // Error: Can't call on stream-bound instance
* logger.stderr.clearVisible() // throws
* ```
*/
clearVisible() {
if (this.#boundStream) {
throw new ErrorCtor(
'clearVisible() is only available on the main logger instance, not on stream-bound instances',
)
}
const con = this.#getConsole()
con.clear()
if ((con as any)._stdout.isTTY) {
;(this as any)[lastWasBlankSymbol](true)
this.#logCallCount = 0
}
return this
}
/**
* Increments and logs a counter for the given label.
*
* Each unique label maintains its own counter. Works like `console.count()`.
*
* @param label - Optional label for the counter
* @default 'default'
* @returns The logger instance for chaining
*
* @example
* ```typescript
* logger.count('requests') // requests: 1
* logger.count('requests') // requests: 2
* logger.count('errors') // errors: 1
* logger.count() // default: 1
* ```
*/
count(label?: string | undefined): this {
const con = this.#getConsole()
con.count(label)
this[lastWasBlankSymbol](false)
return this[incLogCallCountSymbol]()
}
/**
* Creates a task that logs start and completion messages automatically.
*
* Returns a task object with a `run()` method that executes the provided
* function and logs "Starting task: {name}" before execution and
* "Completed task: {name}" after completion.
*
* @param name - The name of the task
* @returns A task object with a `run()` method
*
* @example
* ```typescript
* const task = logger.createTask('Database Migration')
* const result = task.run(() => {
* // Logs: "Starting task: Database Migration"
* migrateDatabase()
* return 'success'
* // Logs: "Completed task: Database Migration"
* })
* console.log(result) // 'success'
* ```
*/
createTask(name: string): Task {
return {
run: <T>(f: () => T): T => {
this.log(`Starting task: ${name}`)
const result = f()
this.log(`Completed task: ${name}`)
return result
},
}
}
/**
* Decreases the indentation level by removing spaces from the prefix.
*
* When called on the main logger, affects both stderr and stdout indentation.
* When called on a stream-bound logger (`.stderr` or `.stdout`), affects
* only that stream's indentation.
*
* @param spaces - Number of spaces to remove from indentation
* @default 2
* @returns The logger instance for chaining
*
* @example
* ```typescript
* logger.indent()
* logger.log('Indented')
* logger.dedent()
* logger.log('Back to normal')
*
* // Remove custom amount
* logger.indent(4)
* logger.log('Four spaces')
* logger.dedent(4)
*
* // Stream-specific dedent
* logger.stdout.indent()
* logger.stdout.log('Indented stdout')
* logger.stdout.dedent()
* ```
*/
dedent(spaces = 2) {
if (this.#boundStream) {
// Only affect bound stream
const current = this.#getIndent(this.#boundStream)
this.#setIndent(this.#boundStream, current.slice(0, -spaces))
} else {
// Affect both streams
const stderrCurrent = this.#getIndent('stderr')
const stdoutCurrent = this.#getIndent('stdout')
this.#setIndent('stderr', stderrCurrent.slice(0, -spaces))
this.#setIndent('stdout', stdoutCurrent.slice(0, -spaces))
}
return this
}
/**
* Displays an object's properties in a formatted way.
*
* Works like `console.dir()` with customizable options for depth,
* colors, etc. Useful for inspecting complex objects.
*
* @param obj - The object to display
* @param options - Optional formatting options (Node.js inspect options)
* @returns The logger instance for chaining
*
* @example
* ```typescript
* const obj = { a: 1, b: { c: 2, d: { e: 3 } } }
* logger.dir(obj)