-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspinner.ts
More file actions
1661 lines (1540 loc) · 55 KB
/
spinner.ts
File metadata and controls
1661 lines (1540 loc) · 55 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 CLI spinner utilities for long-running operations.
* Provides animated progress indicators with CI environment detection.
*/
import process from 'node:process'
import type { Writable } from 'node:stream'
import colors from './external/yoctocolors-cjs'
import type { ColorInherit, ColorRgb, ColorValue } from './colors'
import { isRgbTuple, toRgb } from './colors'
import { getAbortSignal } from './constants/process'
import { getCI } from './env/ci'
import { isDebug } from './debug'
import { generateSocketSpinnerFrames } from './effects/pulse-frames'
import type {
ShimmerColorGradient,
ShimmerConfig,
ShimmerDirection,
ShimmerState,
} from './effects/text-shimmer'
import { applyShimmer, COLOR_INHERIT, DIR_LTR } from './effects/text-shimmer'
import yoctoSpinner from './external/@socketregistry/yocto-spinner'
import {
LOG_SYMBOLS,
getDefaultLogger,
incLogCallCountSymbol,
lastWasBlankSymbol,
} from './logger'
import { hasOwn } from './objects'
import { isBlankString, stringWidth } from './strings'
import { getTheme } from './themes/context'
import { THEMES } from './themes/themes'
import { resolveColor } from './themes/utils'
/**
* Symbol types for status messages.
* Maps to log symbols: fail (✗), info (ℹ), skip (↻), success (✓), warn (⚠).
*/
export type SymbolType = 'fail' | 'info' | 'skip' | 'success' | 'warn'
/**
* Progress tracking information for display in spinner.
* Used by `progress()` and `progressStep()` methods to show animated progress bars.
*/
export type ProgressInfo = {
/** Current progress value */
current: number
/** Total/maximum progress value */
total: number
/** Optional unit label displayed after the progress count (e.g., 'files', 'items') */
unit?: string | undefined
}
/**
* Internal shimmer state with color configuration.
* Extends `ShimmerState` with additional color property that can be inherited from spinner.
*/
export type ShimmerInfo = ShimmerState & {
/** Color for shimmer effect - can inherit from spinner, use explicit color, or gradient */
color: ColorInherit | ColorValue | ShimmerColorGradient
}
/**
* Spinner instance for displaying animated loading indicators.
* Provides methods for status updates, progress tracking, and text shimmer effects.
*
* KEY BEHAVIORS:
* - Methods WITHOUT "AndStop" keep the spinner running (e.g., `success()`, `fail()`)
* - Methods WITH "AndStop" auto-clear the spinner line (e.g., `successAndStop()`, `failAndStop()`)
* - Status messages (done, success, fail, info, warn, reason, step, substep) go to stderr
* - Data messages (`log()`) go to stdout
*
* @example
* ```ts
* import { Spinner } from '@socketsecurity/lib/spinner'
*
* const spinner = Spinner({ text: 'Loading…' })
* spinner.start()
*
* // Show success while continuing to spin
* spinner.success('Step 1 complete')
*
* // Stop the spinner with success message
* spinner.successAndStop('All done!')
* ```
*/
export type Spinner = {
/** Current spinner color as RGB tuple */
color: ColorRgb
/** Current spinner animation style */
spinner: SpinnerStyle
/** Whether spinner is currently animating */
get isSpinning(): boolean
/** Get current shimmer state (enabled/disabled and configuration) */
get shimmerState(): ShimmerInfo | undefined
/** Clear the current line without stopping the spinner */
clear(): Spinner
/** Show debug message without stopping (only if debug mode enabled) */
debug(text?: string | undefined, ...extras: unknown[]): Spinner
/** Show debug message and stop the spinner (only if debug mode enabled) */
debugAndStop(text?: string | undefined, ...extras: unknown[]): Spinner
/** Decrease indentation by specified spaces (default: 2) */
dedent(spaces?: number | undefined): Spinner
/** Disable shimmer effect (preserves config for later re-enable) */
disableShimmer(): Spinner
/** Alias for `success()` - show success without stopping */
done(text?: string | undefined, ...extras: unknown[]): Spinner
/** Alias for `successAndStop()` - show success and stop */
doneAndStop(text?: string | undefined, ...extras: unknown[]): Spinner
/** Enable shimmer effect (restores saved config or uses defaults) */
enableShimmer(): Spinner
/** Alias for `fail()` - show error without stopping */
error(text?: string | undefined, ...extras: unknown[]): Spinner
/** Alias for `failAndStop()` - show error and stop */
errorAndStop(text?: string | undefined, ...extras: unknown[]): Spinner
/** Show failure (✗) without stopping the spinner */
fail(text?: string | undefined, ...extras: unknown[]): Spinner
/** Show failure (✗) and stop the spinner, auto-clearing the line */
failAndStop(text?: string | undefined, ...extras: unknown[]): Spinner
/** Increase indentation by specified spaces (default: 2) */
indent(spaces?: number | undefined): Spinner
/** Show info (ℹ) message without stopping the spinner */
info(text?: string | undefined, ...extras: unknown[]): Spinner
/** Show info (ℹ) message and stop the spinner, auto-clearing the line */
infoAndStop(text?: string | undefined, ...extras: unknown[]): Spinner
/** Log to stdout without stopping the spinner */
log(text?: string | undefined, ...extras: unknown[]): Spinner
/** Log and stop the spinner, auto-clearing the line */
logAndStop(text?: string | undefined, ...extras: unknown[]): Spinner
/** Update progress bar with current/total values and optional unit */
progress(current: number, total: number, unit?: string | undefined): Spinner
/** Increment progress by specified amount (default: 1) */
progressStep(amount?: number): Spinner
/** Set complete shimmer configuration */
setShimmer(config: ShimmerConfig): Spinner
/** Show skip (↻) message without stopping the spinner */
skip(text?: string | undefined, ...extras: unknown[]): Spinner
/** Show skip (↻) message and stop the spinner, auto-clearing the line */
skipAndStop(text?: string | undefined, ...extras: unknown[]): Spinner
/** Start spinning with optional text */
start(text?: string | undefined): Spinner
/** Show main step message to stderr without stopping */
step(text?: string | undefined, ...extras: unknown[]): Spinner
/** Stop spinning and clear internal state, auto-clearing the line */
stop(text?: string | undefined): Spinner
/** Stop and show final text without clearing the line */
stopAndPersist(text?: string | undefined): Spinner
/** Show indented substep message to stderr without stopping */
substep(text?: string | undefined, ...extras: unknown[]): Spinner
/** Show success (✓) without stopping the spinner */
success(text?: string | undefined, ...extras: unknown[]): Spinner
/** Show success (✓) and stop the spinner, auto-clearing the line */
successAndStop(text?: string | undefined, ...extras: unknown[]): Spinner
/** Get current spinner text (getter) or set new text (setter) */
text(value: string): Spinner
text(): string
/** Update partial shimmer configuration */
updateShimmer(config: Partial<ShimmerConfig>): Spinner
/** Show warning (⚠) without stopping the spinner */
warn(text?: string | undefined, ...extras: unknown[]): Spinner
/** Show warning (⚠) and stop the spinner, auto-clearing the line */
warnAndStop(text?: string | undefined, ...extras: unknown[]): Spinner
}
/**
* Configuration options for creating a spinner instance.
*/
export type SpinnerOptions = {
/**
* Spinner color as RGB tuple or color name.
* @default [140, 82, 255] Socket purple
*/
readonly color?: ColorValue | undefined
/**
* Shimmer effect configuration or direction string.
* When enabled, text will have an animated shimmer effect.
* @default undefined No shimmer effect
*/
readonly shimmer?: ShimmerConfig | ShimmerDirection | undefined
/**
* Animation style with frames and timing.
* @default 'socket' Custom Socket animation in CLI, minimal in CI
*/
readonly spinner?: SpinnerStyle | undefined
/**
* Abort signal for cancelling the spinner.
* @default getAbortSignal() from process constants
*/
readonly signal?: AbortSignal | undefined
/**
* Output stream for spinner rendering.
* @default process.stderr
*/
readonly stream?: Writable | undefined
/**
* Initial text to display with the spinner.
* @default undefined No initial text
*/
readonly text?: string | undefined
/**
* Theme to use for spinner colors.
* Accepts theme name ('socket', 'sunset', etc.) or Theme object.
* @default Current theme from getTheme()
*/
readonly theme?:
| import('./themes/types').Theme
| import('./themes/themes').ThemeName
| undefined
}
/**
* Animation style definition for spinner frames.
* Defines the visual appearance and timing of the spinner animation.
*/
export type SpinnerStyle = {
/** Array of animation frames (strings to display sequentially) */
readonly frames: string[]
/**
* Milliseconds between frame changes.
* @default 80 Standard frame rate
*/
readonly interval?: number | undefined
}
/**
* Minimal spinner style for CI environments.
* Uses empty frame and max interval to effectively disable animation in CI.
*/
export const ciSpinner: SpinnerStyle = {
frames: [''],
interval: 2_147_483_647,
}
/**
* Create a property descriptor for defining non-enumerable properties.
* Used for adding aliased methods to the Spinner prototype.
* @param value - Value for the property
* @returns Property descriptor object
* @private
*/
function desc(value: unknown) {
return {
__proto__: null,
configurable: true,
value,
writable: true,
}
}
/**
* Format progress information as a visual progress bar with percentage and count.
* @param progress - Progress tracking information
* @returns Formatted string with colored progress bar, percentage, and count
* @private
* @example "███████░░░░░░░░░░░░░ 35% (7/20 files)"
*/
function formatProgress(progress: ProgressInfo): string {
const { current, total, unit } = progress
const percentage = total === 0 ? 0 : Math.round((current / total) * 100)
const bar = renderProgressBar(percentage)
const count = unit ? `${current}/${total} ${unit}` : `${current}/${total}`
return `${bar} ${percentage}% (${count})`
}
/**
* Normalize text input by trimming leading whitespace.
* Non-string values are converted to empty string.
* @param value - Text to normalize
* @returns Normalized string with leading whitespace removed
* @private
*/
function normalizeText(value: unknown) {
return typeof value === 'string' ? value.trimStart() : ''
}
/**
* Render a progress bar using block characters (█ for filled, ░ for empty).
* @param percentage - Progress percentage (0-100)
* @param width - Total width of progress bar in characters
* @returns Colored progress bar string
* @default width=20
* @private
*/
function renderProgressBar(percentage: number, width: number = 20): string {
const filled = Math.max(
0,
Math.min(width, Math.round((percentage / 100) * width)),
)
const empty = Math.max(0, width - filled)
const bar = '█'.repeat(filled) + '░'.repeat(empty)
// Use cyan color for the progress bar
// colors is imported at the top
return colors.cyan(bar)
}
let _cliSpinners: Record<string, SpinnerStyle> | undefined
/**
* Get available CLI spinner styles or a specific style by name.
* Extends the standard cli-spinners collection with Socket custom spinners.
*
* Custom spinners:
* - `socket` (default): Socket pulse animation with sparkles and lightning
*
* @param styleName - Optional name of specific spinner style to retrieve
* @returns Specific spinner style if name provided, all styles if omitted, `undefined` if style not found
* @see https://github.com/sindresorhus/cli-spinners/blob/main/spinners.json
*
* @example
* ```ts
* // Get all available spinner styles
* const allSpinners = getCliSpinners()
*
* // Get specific style
* const socketStyle = getCliSpinners('socket')
* const dotsStyle = getCliSpinners('dots')
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
export function getCliSpinners(
styleName?: string | undefined,
): SpinnerStyle | Record<string, SpinnerStyle> | undefined {
if (_cliSpinners === undefined) {
/* c8 ignore start - External yoctoSpinner initialization */
const YoctoCtor: any = yoctoSpinner as any
// Get the YoctoSpinner class to access static properties.
const tempInstance: any = YoctoCtor({})
const YoctoSpinnerClass: any = tempInstance.constructor as any
/* c8 ignore stop */
// Extend the standard cli-spinners collection with Socket custom spinners.
_cliSpinners = {
__proto__: null,
...YoctoSpinnerClass.spinners,
socket: generateSocketSpinnerFrames(),
}
}
if (typeof styleName === 'string' && _cliSpinners) {
return hasOwn(_cliSpinners, styleName) ? _cliSpinners[styleName] : undefined
}
return _cliSpinners
}
let _Spinner: {
new (options?: SpinnerOptions | undefined): Spinner
}
let _defaultSpinner: SpinnerStyle | undefined
let _spinner: ReturnType<typeof Spinner> | undefined
/**
* Get the default spinner instance.
* Lazily creates the spinner to avoid circular dependencies during module initialization.
* Reuses the same instance across calls.
*
* @returns Shared default spinner instance
*
* @example
* ```ts
* import { getDefaultSpinner } from '@socketsecurity/lib/spinner'
*
* const spinner = getDefaultSpinner()
* spinner.start('Loading…')
* ```
*/
export function getDefaultSpinner(): ReturnType<typeof Spinner> {
if (_spinner === undefined) {
_spinner = Spinner()
}
return _spinner
}
// REMOVED: Deprecated `spinner` export
// Migration: Use getDefaultSpinner() instead
// See: getDefaultSpinner() function above
/**
* Create a spinner instance for displaying loading indicators.
* Provides an animated CLI spinner with status messages, progress tracking, and shimmer effects.
*
* AUTO-CLEAR BEHAVIOR:
* - All *AndStop() methods AUTO-CLEAR the spinner line via yocto-spinner.stop()
* Examples: `doneAndStop()`, `successAndStop()`, `failAndStop()`, etc.
*
* - Methods WITHOUT "AndStop" do NOT clear (spinner keeps spinning)
* Examples: `done()`, `success()`, `fail()`, etc.
*
* STREAM USAGE:
* - Spinner animation: stderr (yocto-spinner default)
* - Status methods (done, success, fail, info, warn, step, substep): stderr
* - Data methods (`log()`): stdout
*
* COMPARISON WITH LOGGER:
* - `logger.done()` does NOT auto-clear (requires manual `logger.clearLine()`)
* - `spinner.doneAndStop()` DOES auto-clear (built into yocto-spinner.stop())
* - Pattern: `logger.clearLine().done()` vs `spinner.doneAndStop()`
*
* @param options - Configuration options for the spinner
* @returns New spinner instance
*
* @example
* ```ts
* import { Spinner } from '@socketsecurity/lib/spinner'
*
* // Basic usage
* const spinner = Spinner({ text: 'Loading data…' })
* spinner.start()
* await fetchData()
* spinner.successAndStop('Data loaded!')
*
* // With custom color
* const spinner = Spinner({
* text: 'Processing…',
* color: [255, 0, 0] // Red
* })
*
* // With shimmer effect
* const spinner = Spinner({
* text: 'Building…',
* shimmer: { dir: 'ltr', speed: 0.5 }
* })
*
* // Show progress
* spinner.progress(5, 10, 'files')
* spinner.progressStep() // Increment by 1
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
export function Spinner(options?: SpinnerOptions | undefined): Spinner {
if (_Spinner === undefined) {
/* c8 ignore start - External yoctoSpinner initialization */
const YoctoCtor = yoctoSpinner as any
// Get the actual YoctoSpinner class from an instance
const tempInstance = YoctoCtor({})
const YoctoSpinnerClass = tempInstance.constructor
/* c8 ignore stop */
const logger = getDefaultLogger()
/*@__PURE__*/
_Spinner = class SpinnerClass extends (YoctoSpinnerClass as any) {
declare isSpinning: boolean
#baseText: string = ''
#indentation: string = ''
#progress?: ProgressInfo | undefined
#shimmer?: ShimmerInfo | undefined
#shimmerSavedConfig?: ShimmerInfo | undefined
constructor(options?: SpinnerOptions | undefined) {
const opts = { __proto__: null, ...options } as SpinnerOptions
// Get theme from options or current theme
let theme = getTheme()
if (opts.theme) {
// Resolve theme name or use Theme object directly
if (typeof opts.theme === 'string') {
theme = THEMES[opts.theme] ?? theme
} else {
theme = opts.theme
}
}
// Get default color from theme if not specified
let defaultColor: ColorValue = theme.colors.primary
if (theme.effects?.spinner?.color) {
const resolved = resolveColor(
theme.effects.spinner.color,
theme.colors,
)
// resolveColor can return 'inherit' or gradients which aren't valid for spinner
// Fall back to primary for these cases
if (resolved === 'inherit' || Array.isArray(resolved[0])) {
defaultColor = theme.colors.primary
} else {
defaultColor = resolved as ColorValue
}
}
// Convert color option to RGB (default from theme).
const spinnerColor = opts.color ?? defaultColor
// Validate RGB tuple if provided.
if (
isRgbTuple(spinnerColor) &&
(spinnerColor.length !== 3 ||
!spinnerColor.every(
n => typeof n === 'number' && n >= 0 && n <= 255,
))
) {
throw new TypeError(
'RGB color must be an array of 3 numbers between 0 and 255',
)
}
const spinnerColorRgb = toRgb(spinnerColor)
// Parse shimmer config - can be object or direction string.
let shimmerInfo: ShimmerInfo | undefined
if (opts.shimmer) {
let shimmerDir: ShimmerDirection
let shimmerColor:
| ColorInherit
| ColorValue
| ShimmerColorGradient
| undefined
// Default: 0.33 steps per frame (~150ms per step).
let shimmerSpeed: number = 1 / 3
if (typeof opts.shimmer === 'string') {
shimmerDir = opts.shimmer
} else {
const shimmerConfig = {
__proto__: null,
...opts.shimmer,
} as ShimmerConfig
shimmerDir = shimmerConfig.dir ?? DIR_LTR
shimmerColor = shimmerConfig.color ?? COLOR_INHERIT
shimmerSpeed = shimmerConfig.speed ?? 1 / 3
}
// Create shimmer info with initial animation state:
// - COLOR_INHERIT means use spinner color dynamically
// - ColorValue (name or RGB tuple) is an explicit override color
// - undefined color defaults to COLOR_INHERIT
// - speed controls steps per frame (lower = slower, e.g., 0.33 = ~150ms per step)
shimmerInfo = {
__proto__: null,
color: shimmerColor === undefined ? COLOR_INHERIT : shimmerColor,
currentDir: DIR_LTR,
mode: shimmerDir,
speed: shimmerSpeed,
step: 0,
} as ShimmerInfo
}
// eslint-disable-next-line constructor-super
super({
signal: getAbortSignal(),
...opts,
// Pass RGB color directly to yocto-spinner (it now supports RGB).
color: spinnerColorRgb,
// onRenderFrame callback provides full control over frame + text layout.
// Calculates spacing based on frame width to prevent text jumping.
onRenderFrame: (
frame: string,
text: string,
applyColor: (text: string) => string,
) => {
const width = stringWidth(frame)
// Narrow frames (width 1) get 2 spaces, wide frames (width 2) get 1 space.
// Total width is consistent: 3 characters (frame + spacing) before text.
const spacing = width === 1 ? ' ' : ' '
return frame ? `${applyColor(frame)}${spacing}${text}` : text
},
// onFrameUpdate callback is called by yocto-spinner whenever a frame advances.
// This ensures shimmer updates are perfectly synchronized with animation beats.
onFrameUpdate: shimmerInfo
? () => {
// Update parent's text without triggering render.
// Parent's #skipRender flag prevents nested render calls.
// Only update if we have base text to avoid blank frames.
if (this.#baseText) {
super.text = this.#buildDisplayText()
}
}
: undefined,
})
this.#shimmer = shimmerInfo
this.#shimmerSavedConfig = shimmerInfo
}
// Override color getter to ensure it's always RGB.
get color(): ColorRgb {
const value = super.color
return isRgbTuple(value) ? value : toRgb(value)
}
// Override color setter to always convert to RGB before passing to yocto-spinner.
set color(value: ColorValue | ColorRgb) {
super.color = isRgbTuple(value) ? value : toRgb(value)
}
// Getter to expose current shimmer state.
get shimmerState(): ShimmerInfo | undefined {
if (!this.#shimmer) {
return undefined
}
return {
color: this.#shimmer.color,
currentDir: this.#shimmer.currentDir,
mode: this.#shimmer.mode,
speed: this.#shimmer.speed,
step: this.#shimmer.step,
} as ShimmerInfo
}
/**
* Apply a yocto-spinner method and update logger state.
* Handles text normalization, extra arguments, and logger tracking.
* @private
*/
#apply(methodName: string, args: unknown[]) {
let extras: unknown[]
let text = args.at(0)
if (typeof text === 'string') {
extras = args.slice(1)
} else {
extras = args
text = ''
}
const wasSpinning = this.isSpinning
const normalized = normalizeText(text)
if (methodName === 'stop' && !normalized) {
super[methodName]()
} else {
super[methodName](normalized)
}
if (methodName === 'stop') {
if (wasSpinning && normalized) {
logger[lastWasBlankSymbol](isBlankString(normalized))
logger[incLogCallCountSymbol]()
}
} else {
logger[lastWasBlankSymbol](false)
logger[incLogCallCountSymbol]()
}
if (extras.length) {
logger.log(...extras)
logger[lastWasBlankSymbol](false)
}
return this
}
/**
* Build the complete display text with progress, shimmer, and indentation.
* Combines base text, progress bar, shimmer effects, and indentation.
* @private
*/
#buildDisplayText() {
let displayText = this.#baseText
if (this.#progress) {
const progressText = formatProgress(this.#progress)
displayText = displayText
? `${displayText} ${progressText}`
: progressText
}
// Apply shimmer effect if enabled.
if (displayText && this.#shimmer) {
// If shimmer color is 'inherit', use current spinner color (getter ensures RGB).
// Otherwise, check if it's a gradient (array of arrays) or single color.
let shimmerColor: ColorRgb | ShimmerColorGradient
if (this.#shimmer.color === COLOR_INHERIT) {
shimmerColor = this.color
} else if (Array.isArray(this.#shimmer.color[0])) {
// It's a gradient - use as is.
shimmerColor = this.#shimmer.color as ShimmerColorGradient
} else {
// It's a single color - convert to RGB.
shimmerColor = toRgb(this.#shimmer.color as ColorValue)
}
displayText = applyShimmer(displayText, this.#shimmer, {
color: shimmerColor,
direction: this.#shimmer.mode,
})
}
// Apply indentation
if (this.#indentation && displayText) {
displayText = this.#indentation + displayText
}
return displayText
}
/**
* Show a status message without stopping the spinner.
* Outputs the symbol and message to stderr, then continues spinning.
* @private
*/
#showStatusAndKeepSpinning(symbolType: SymbolType, args: unknown[]) {
let text = args.at(0)
let extras: unknown[]
if (typeof text === 'string') {
extras = args.slice(1)
} else {
extras = args
text = ''
}
// Note: Status messages always go to stderr.
logger.error(`${LOG_SYMBOLS[symbolType]} ${text}`, ...extras)
return this
}
/**
* Update the spinner's displayed text.
* Rebuilds display text and triggers render.
* @private
*/
#updateSpinnerText() {
// Call the parent class's text setter, which triggers render.
super.text = this.#buildDisplayText()
}
/**
* Show a debug message (ℹ) without stopping the spinner.
* Only displays if debug mode is enabled via environment variable.
* Outputs to stderr and continues spinning.
*
* @param text - Debug message to display
* @param extras - Additional values to log
* @returns This spinner for chaining
*/
debug(text?: string | undefined, ...extras: unknown[]) {
if (isDebug()) {
return this.#showStatusAndKeepSpinning('info', [text, ...extras])
}
return this
}
/**
* Show a debug message (ℹ) and stop the spinner.
* Only displays if debug mode is enabled via environment variable.
* Auto-clears the spinner line before displaying the message.
*
* @param text - Debug message to display
* @param extras - Additional values to log
* @returns This spinner for chaining
*/
debugAndStop(text?: string | undefined, ...extras: unknown[]) {
if (isDebug()) {
return this.#apply('info', [text, ...extras])
}
return this
}
/**
* Decrease indentation level by removing spaces from the left.
* Pass 0 to reset indentation to zero completely.
*
* @param spaces - Number of spaces to remove
* @returns This spinner for chaining
* @default spaces=2
*
* @example
* ```ts
* spinner.dedent() // Remove 2 spaces
* spinner.dedent(4) // Remove 4 spaces
* spinner.dedent(0) // Reset to zero indentation
* ```
*/
dedent(spaces?: number | undefined) {
// Pass 0 to reset indentation
if (spaces === 0) {
this.#indentation = ''
} else {
const amount = spaces ?? 2
const newLength = Math.max(0, this.#indentation.length - amount)
this.#indentation = this.#indentation.slice(0, newLength)
}
this.#updateSpinnerText()
return this
}
/**
* Disable shimmer effect.
* Preserves config for later re-enable via enableShimmer().
*
* @returns This spinner for chaining
*
* @example
* spinner.disableShimmer()
*/
disableShimmer(): Spinner {
// Disable shimmer but preserve config.
this.#shimmer = undefined
this.#updateSpinnerText()
return this as unknown as Spinner
}
/**
* Show a done/success message (✓) without stopping the spinner.
* Alias for `success()` with a shorter name.
*
* DESIGN DECISION: Unlike yocto-spinner, our `done()` does NOT stop the spinner.
* Use `doneAndStop()` if you want to stop the spinner.
*
* @param text - Message to display
* @param extras - Additional values to log
* @returns This spinner for chaining
*/
done(text?: string | undefined, ...extras: unknown[]) {
return this.#showStatusAndKeepSpinning('success', [text, ...extras])
}
/**
* Show a done/success message (✓) and stop the spinner.
* Auto-clears the spinner line before displaying the success message.
*
* @param text - Message to display
* @param extras - Additional values to log
* @returns This spinner for chaining
*/
doneAndStop(text?: string | undefined, ...extras: unknown[]) {
return this.#apply('success', [text, ...extras])
}
/**
* Enable shimmer effect.
* Restores saved config or uses defaults if no saved config exists.
*
* @returns This spinner for chaining
*
* @example
* spinner.enableShimmer()
*/
enableShimmer(): Spinner {
if (this.#shimmerSavedConfig) {
// Restore saved config.
this.#shimmer = { ...this.#shimmerSavedConfig }
} else {
// Create default config.
this.#shimmer = {
color: COLOR_INHERIT,
currentDir: DIR_LTR,
mode: DIR_LTR,
speed: 1 / 3,
step: 0,
} as ShimmerInfo
this.#shimmerSavedConfig = this.#shimmer
}
this.#updateSpinnerText()
return this as unknown as Spinner
}
/**
* Show a failure message (✗) without stopping the spinner.
* DESIGN DECISION: Unlike yocto-spinner, our `fail()` does NOT stop the spinner.
* This allows displaying errors while continuing to spin.
* Use `failAndStop()` if you want to stop the spinner.
*
* @param text - Error message to display
* @param extras - Additional values to log
* @returns This spinner for chaining
*/
fail(text?: string | undefined, ...extras: unknown[]) {
return this.#showStatusAndKeepSpinning('fail', [text, ...extras])
}
/**
* Show a failure message (✗) and stop the spinner.
* Auto-clears the spinner line before displaying the error message.
*
* @param text - Error message to display
* @param extras - Additional values to log
* @returns This spinner for chaining
*/
failAndStop(text?: string | undefined, ...extras: unknown[]) {
return this.#apply('error', [text, ...extras])
}
/**
* Increase indentation level by adding spaces to the left.
* Pass 0 to reset indentation to zero completely.
*
* @param spaces - Number of spaces to add
* @returns This spinner for chaining
* @default spaces=2
*
* @example
* ```ts
* spinner.indent() // Add 2 spaces
* spinner.indent(4) // Add 4 spaces
* spinner.indent(0) // Reset to zero indentation
* ```
*/
indent(spaces?: number | undefined) {
// Pass 0 to reset indentation
if (spaces === 0) {
this.#indentation = ''
} else {
const amount = spaces ?? 2
this.#indentation += ' '.repeat(amount)
}
this.#updateSpinnerText()
return this
}
/**
* Show an info message (ℹ) without stopping the spinner.
* Outputs to stderr and continues spinning.
*
* @param text - Info message to display
* @param extras - Additional values to log
* @returns This spinner for chaining
*/
info(text?: string | undefined, ...extras: unknown[]) {
return this.#showStatusAndKeepSpinning('info', [text, ...extras])
}
/**
* Show an info message (ℹ) and stop the spinner.
* Auto-clears the spinner line before displaying the message.
*
* @param text - Info message to display
* @param extras - Additional values to log
* @returns This spinner for chaining
*/
infoAndStop(text?: string | undefined, ...extras: unknown[]) {
return this.#apply('info', [text, ...extras])
}
/**
* Log a message to stdout without stopping the spinner.
* Unlike other status methods, this outputs to stdout for data logging.
*
* @param args - Values to log to stdout
* @returns This spinner for chaining
*/
log(...args: unknown[]) {
logger.log(...args)
return this
}
/**
* Log a message to stdout and stop the spinner.
* Auto-clears the spinner line before displaying the message.
*
* @param text - Message to display
* @param extras - Additional values to log
* @returns This spinner for chaining
*/
logAndStop(text?: string | undefined, ...extras: unknown[]) {
return this.#apply('stop', [text, ...extras])
}
/**
* Update progress information displayed with the spinner.
* Shows a progress bar with percentage and optional unit label.
*
* @param current - Current progress value
* @param total - Total/maximum progress value
* @param unit - Optional unit label (e.g., 'files', 'items')
* @returns This spinner for chaining
*
* @example
* ```ts
* spinner.progress(5, 10) // "███████░░░░░░░░░░░░░ 50% (5/10)"
* spinner.progress(7, 20, 'files') // "███████░░░░░░░░░░░░░ 35% (7/20 files)"
* ```
*/
progress = (
current: number,
total: number,
unit?: string | undefined,
) => {
this.#progress = {
__proto__: null,
current,
total,
...(unit ? { unit } : {}),
} as ProgressInfo
this.#updateSpinnerText()
return this
}
/**
* Increment progress by a specified amount.
* Updates the progress bar displayed with the spinner.
* Clamps the result between 0 and the total value.
*
* @param amount - Amount to increment by