| 6 | * worker thread — even though fd 2 is a real TTY (verified via tty.isatty). |
| 7 | * |
| 8 | * Writes directly to fd 2 so it works from both the main thread |
| 9 | * and the loader worker thread. |
| 10 | */ |
| 11 |
| 12 | import process from "node:process"; |
| 13 | import { writeSync } from "node:fs"; |
| 14 | import { isatty, WriteStream } from "node:tty"; |
| 15 |
| 16 | const BAR_WIDTH = 10; |
| 17 | const SNAKE_LEN = 3; |
| 18 | const TICK_INTERVAL = 80; |
| 19 |
| 20 | /** |
| 21 | * File descriptor for stderr. |
| 22 | * In the loader worker thread (spawned by module.register()), process.stderr |
| 23 | * is not a real WriteStream so `.fd` is undefined — but the underlying fd 2 |
| 24 | * is still inherited from the parent process and works with writeSync/isatty. |
| 25 | */ |
| 26 | const STDERR_FD: number = process.stderr.fd ?? 2; |
| 27 |
| 28 | // ── ANSI helpers ──────────────────────────────────────────────── |
| 29 |
| 30 | /** |
| 31 | * Respect the NO_COLOR convention (https://no-color.org/) and |
| 32 | * NODE_DISABLE_COLORS, same as styleText() from node:util. |
| 33 | */ |
| 34 | const useColor: boolean = |
| 35 | !("NO_COLOR" in process.env) && !("NODE_DISABLE_COLORS" in process.env); |
| 36 |
| 37 | const RESET = "\x1b[0m"; |
| 38 | const DIM = "\x1b[2m"; |
| 39 | const GREEN = "\x1b[32m"; |
| 40 | const YELLOW = "\x1b[33m"; |
| 41 | const CYAN = "\x1b[36m"; |
| 42 |
| 43 | function color(code: string, text: string): string { |
| 44 | return isTTY && useColor ? `${code}${text}${RESET}` : text; |
| 45 | } |
| 46 |
| 47 | // ── State ─────────────────────────────────────────────────────── |
| 48 |
| 49 | interface ProgressState { |
| 50 | total: number; |
| 51 | done: number; |
| 52 | currentUrl: string; |
| 53 | startTime: number; |
| 54 | active: boolean; |
| 55 | tick: number; |
| 56 | timer: ReturnType<typeof setInterval> | null; |
| 57 | } |
| 58 |
| 59 | const state: ProgressState = { |
| 60 | total: 0, |
| 61 | done: 0, |
| 62 | currentUrl: "", |
| 63 | startTime: 0, |
| 64 | active: false, |
| 65 | tick: 0, |
| 66 | timer: null, |
| 67 | }; |
| 68 |
| 69 | const isTTY: boolean = isatty(STDERR_FD); |
| 70 |
| 71 | let stderrStream: { write(str: string): void }; |
| 72 | if (process.stderr.fd !== undefined) { |
| 73 | stderrStream = process.stderr; |
| 74 | } else if (isTTY) { |
| 75 | try { |
| 76 | // In the loader worker thread on Windows, writeSync(2, utf8_string) prints mojibake. |
| 77 | // Creating a real WriteStream invokes uv_tty_init which properly handles Windows console APIs. |
| 78 | stderrStream = new WriteStream(STDERR_FD); |
| 79 | } catch { |
| 80 | stderrStream = { write: (str) => writeSync(STDERR_FD, str) }; |
| 81 | } |
| 82 | } else { |
| 83 | stderrStream = { write: (str) => writeSync(STDERR_FD, str) }; |
| 84 | } |
| 85 |
| 86 | function writeStderr(str: string): void { |
| 87 | stderrStream.write(str); |
| 88 | } |
| 89 |
| 90 | // ── Formatting ────────────────────────────────────────────────── |
| 91 |
| 92 | function formatElapsed(ms: number): string { |
| 93 | const totalSec = Math.floor(ms / 1000); |
| 94 | const min = String(Math.floor(totalSec / 60)).padStart(2, "0"); |
| 95 | const sec = String(totalSec % 60).padStart(2, "0"); |
| 96 | return `[${min}:${sec}]`; |
| 97 | } |
| 98 |
| 99 | function progressBar(done: number, total: number, tick: number): string { |
| 100 | const filled = |
| 101 | total > 0 ? Math.min(Math.round((done / total) * BAR_WIDTH), BAR_WIDTH) : 0; |
| 102 | const empty = BAR_WIDTH - filled; |
| 103 |
| 104 | if (empty === 0) { |
| 105 | return "█".repeat(BAR_WIDTH); |
| 106 | } |
| 107 |
| 108 | const head = tick % empty; |
| 109 |
| 110 | const chars: string[] = []; |
| 111 | for (let i = 0; i < BAR_WIDTH; i++) { |
| 112 | if (i < filled) { |
| 113 | chars.push("█"); |
| 114 | } else { |
| 115 | const ei = i - filled; |
| 116 | const dist = (ei - head + empty) % empty; |
| 117 | const inSnake = dist === 0 || dist > empty - SNAKE_LEN; |
| 118 | chars.push(inSnake ? "▓" : "░"); |
| 119 | } |
| 120 | } |
| 121 | return chars.join(""); |
| 122 | } |
| 123 |
| 124 | // ── Rendering ─────────────────────────────────────────────────── |
| 125 |
| 126 | function render(): void { |
| 127 | if (!isTTY) return; |
| 128 |
| 129 | const elapsed = formatElapsed(Date.now() - state.startTime); |
| 130 | const bar = progressBar(state.done, state.total, state.tick); |
| 131 | const counter = `${state.done}/${state.total}`; |
| 132 |
| 133 | const line1 = `${color(GREEN, "Download")} ${color(CYAN, bar)} ${color(DIM, elapsed)} ${color(YELLOW, counter)}`; |
| 134 | const line2 = ` ${color(DIM, state.currentUrl)}`; |
| 135 |
| 136 | if (state.active) { |
| 137 | writeStderr("\x1b[2A\x1b[0J"); |
| 138 | } |
| 139 | writeStderr(line1 + "\n" + line2 + "\n"); |
| 140 | state.active = true; |
| 141 | } |
| 142 |
| 143 | function startTimer(): void { |
| 144 | if (state.timer || !isTTY) return; |
| 145 | state.timer = setInterval(() => { |
| 146 | state.tick++; |
| 147 | render(); |
| 148 | }, TICK_INTERVAL); |
| 149 | state.timer.unref(); |
| 150 | } |
| 151 |
| 152 | function stopTimer(): void { |
| 153 | if (state.timer) { |
| 154 | clearInterval(state.timer); |
| 155 | state.timer = null; |
| 156 | } |
| 157 | } |
| 158 |
| 159 | // ── Public API ────────────────────────────────────────────────── |
| 160 |
| 161 | /** |
| 162 | * Register a queued download. Starts a fresh session (resetting counters and |
| 163 | * the elapsed clock) if none is currently in flight — so a later batch of |
| 164 | * downloads doesn't inherit stale done/total values from a completed one. |
| 165 | */ |
| 166 | export function downloadAdd(): void { |
| 167 | if (state.done >= state.total) { |
| 168 | // No session in flight — begin a new one. |
| 169 | state.total = 0; |
| 170 | state.done = 0; |
| 171 | state.tick = 0; |
| 172 | state.startTime = Date.now(); |
| 173 | state.active = false; |
| 174 | startTimer(); |
| 175 | } |
| 176 | state.total++; |
| 177 | } |
| 178 |
| 179 | export function downloadBegin(url: string): void { |
| 180 | state.currentUrl = url; |
| 181 | render(); |
| 182 | } |
| 183 |
| 184 | export function downloadDone(): void { |
| 185 | state.done++; |
| 186 | if (state.done >= state.total) { |
| 187 | downloadEnd(); |
| 188 | } else { |
| 189 | render(); |
| 190 | } |
| 191 | } |
| 192 |
| 193 | export function downloadEnd(): void { |
| 194 | stopTimer(); |
| 195 | if (!isTTY || !state.active) return; |
| 196 | writeStderr("\x1b[2A\x1b[0J"); |
| 197 | state.active = false; |
| 198 | } |
| 199 |