@orkestrel/console 0.0.1
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/LICENSE +21 -0
- package/README.md +92 -0
- package/dist/src/browser/index.d.ts +214 -0
- package/dist/src/browser/index.js +275 -0
- package/dist/src/browser/index.js.map +1 -0
- package/dist/src/core/index.cjs +2183 -0
- package/dist/src/core/index.cjs.map +1 -0
- package/dist/src/core/index.d.cts +2299 -0
- package/dist/src/core/index.d.ts +2299 -0
- package/dist/src/core/index.js +2105 -0
- package/dist/src/core/index.js.map +1 -0
- package/dist/src/server/index.cjs +375 -0
- package/dist/src/server/index.cjs.map +1 -0
- package/dist/src/server/index.d.cts +443 -0
- package/dist/src/server/index.d.ts +443 -0
- package/dist/src/server/index.js +363 -0
- package/dist/src/server/index.js.map +1 -0
- package/package.json +106 -0
|
@@ -0,0 +1,2105 @@
|
|
|
1
|
+
import { Emitter } from "@orkestrel/emitter";
|
|
2
|
+
import { isArray } from "@orkestrel/contract";
|
|
3
|
+
//#region src/core/constants.ts
|
|
4
|
+
/**
|
|
5
|
+
* Each {@link Color}'s SGR FOREGROUND parameter — the 8 base colors at 30–37 and their
|
|
6
|
+
* bright variants at 90–97. `default` is intentionally absent (it emits no code).
|
|
7
|
+
*/
|
|
8
|
+
var FOREGROUND_CODES = Object.freeze({
|
|
9
|
+
black: 30,
|
|
10
|
+
red: 31,
|
|
11
|
+
green: 32,
|
|
12
|
+
yellow: 33,
|
|
13
|
+
blue: 34,
|
|
14
|
+
magenta: 35,
|
|
15
|
+
cyan: 36,
|
|
16
|
+
white: 37,
|
|
17
|
+
brightBlack: 90,
|
|
18
|
+
brightRed: 91,
|
|
19
|
+
brightGreen: 92,
|
|
20
|
+
brightYellow: 93,
|
|
21
|
+
brightBlue: 94,
|
|
22
|
+
brightMagenta: 95,
|
|
23
|
+
brightCyan: 96,
|
|
24
|
+
brightWhite: 97
|
|
25
|
+
});
|
|
26
|
+
/**
|
|
27
|
+
* Each {@link Color}'s SGR BACKGROUND parameter — the 8 base colors at 40–47 and their
|
|
28
|
+
* bright variants at 100–107. `default` is intentionally absent (it emits no code).
|
|
29
|
+
*/
|
|
30
|
+
var BACKGROUND_CODES = Object.freeze({
|
|
31
|
+
black: 40,
|
|
32
|
+
red: 41,
|
|
33
|
+
green: 42,
|
|
34
|
+
yellow: 43,
|
|
35
|
+
blue: 44,
|
|
36
|
+
magenta: 45,
|
|
37
|
+
cyan: 46,
|
|
38
|
+
white: 47,
|
|
39
|
+
brightBlack: 100,
|
|
40
|
+
brightRed: 101,
|
|
41
|
+
brightGreen: 102,
|
|
42
|
+
brightYellow: 103,
|
|
43
|
+
brightBlue: 104,
|
|
44
|
+
brightMagenta: 105,
|
|
45
|
+
brightCyan: 106,
|
|
46
|
+
brightWhite: 107
|
|
47
|
+
});
|
|
48
|
+
/**
|
|
49
|
+
* Each {@link Attribute}'s SGR "on" parameter — `bold` 1, `dim` 2, `italic` 3,
|
|
50
|
+
* `underline` 4, `inverse` 7, `strikethrough` 9. The renderer composes several by
|
|
51
|
+
* joining their codes with `;` in one SGR sequence.
|
|
52
|
+
*/
|
|
53
|
+
var ATTRIBUTE_CODES = Object.freeze({
|
|
54
|
+
bold: 1,
|
|
55
|
+
dim: 2,
|
|
56
|
+
italic: 3,
|
|
57
|
+
underline: 4,
|
|
58
|
+
inverse: 7,
|
|
59
|
+
strikethrough: 9
|
|
60
|
+
});
|
|
61
|
+
/**
|
|
62
|
+
* The EMPTY {@link Style} — no foreground, no background, no attributes — frozen. The
|
|
63
|
+
* neutral starting point a base styler builds from, and what a renderer passes through
|
|
64
|
+
* unchanged (it carries no codes). Deeply frozen, so it is safe to share as the base.
|
|
65
|
+
*/
|
|
66
|
+
var EMPTY_STYLE = Object.freeze({ attributes: Object.freeze([]) });
|
|
67
|
+
/**
|
|
68
|
+
* Every named {@link Color} except `default`, frozen — the colors the styler exposes as
|
|
69
|
+
* chainable accessors. The source of truth for the color axis; the styler drives its
|
|
70
|
+
* accessors from this array so the literals live in one place.
|
|
71
|
+
*/
|
|
72
|
+
var COLORS = Object.freeze([
|
|
73
|
+
"black",
|
|
74
|
+
"red",
|
|
75
|
+
"green",
|
|
76
|
+
"yellow",
|
|
77
|
+
"blue",
|
|
78
|
+
"magenta",
|
|
79
|
+
"cyan",
|
|
80
|
+
"white",
|
|
81
|
+
"brightBlack",
|
|
82
|
+
"brightRed",
|
|
83
|
+
"brightGreen",
|
|
84
|
+
"brightYellow",
|
|
85
|
+
"brightBlue",
|
|
86
|
+
"brightMagenta",
|
|
87
|
+
"brightCyan",
|
|
88
|
+
"brightWhite"
|
|
89
|
+
]);
|
|
90
|
+
/**
|
|
91
|
+
* Every {@link Attribute}, frozen — the attributes the styler exposes as chainable
|
|
92
|
+
* accessors. The source of truth for the attribute axis.
|
|
93
|
+
*/
|
|
94
|
+
var ATTRIBUTES = Object.freeze([
|
|
95
|
+
"bold",
|
|
96
|
+
"dim",
|
|
97
|
+
"italic",
|
|
98
|
+
"underline",
|
|
99
|
+
"inverse",
|
|
100
|
+
"strikethrough"
|
|
101
|
+
]);
|
|
102
|
+
/** The SGR RESET parameter (0) — terminates a styled run, clearing all colors and attributes. */
|
|
103
|
+
var RESET_CODE = 0;
|
|
104
|
+
/**
|
|
105
|
+
* The ESC control character (`U+001B`) that begins every ANSI escape sequence. Built
|
|
106
|
+
* with `String.fromCharCode` so no raw control character appears in source.
|
|
107
|
+
*/
|
|
108
|
+
var ESC = String.fromCharCode(27);
|
|
109
|
+
/** The BEL control character (`U+0007`) that can terminate an OSC sequence. */
|
|
110
|
+
var BEL = String.fromCharCode(7);
|
|
111
|
+
/** The Control Sequence Introducer (`ESC[`) that opens every SGR sequence. */
|
|
112
|
+
var CSI = `[`;
|
|
113
|
+
/** The full SGR reset sequence (`ESC[0m`) appended after a styled run. */
|
|
114
|
+
var RESET = `${CSI}0m`;
|
|
115
|
+
/**
|
|
116
|
+
* Matches any ANSI/VT escape sequence — CSI (SGR color/style plus cursor/erase/scroll,
|
|
117
|
+
* including colon-parameterized SGR), OSC / DCS / PM / APC / SOS string sequences
|
|
118
|
+
* (titles, hyperlinks, device strings), the `nF` charset-select family, and the
|
|
119
|
+
* two-byte `Fp` / `Fe` / `Fs` sequences (e.g. `ESC 7`, `ESC D`, `ESC c` RIS). Global, so
|
|
120
|
+
* `strip` removes every occurrence.
|
|
121
|
+
*
|
|
122
|
+
* @remarks
|
|
123
|
+
* A global `RegExp` carries a mutable `lastIndex`; a scan must build a FRESH `RegExp`
|
|
124
|
+
* from this one's `source` + `flags` rather than reuse this instance's `lastIndex`. This
|
|
125
|
+
* is the canonical definition, not a shared scanner. The alternation is ORDERED so the
|
|
126
|
+
* CSI / string-family arms (which can start with a byte a later single-byte arm would
|
|
127
|
+
* also match) win first; every arm uses disjoint, non-nested character classes, so the
|
|
128
|
+
* match is linear in input length — no catastrophic backtracking (ReDoS-safe) even on an
|
|
129
|
+
* adversarial run of digits inside an unterminated CSI. Built from `String.fromCharCode`
|
|
130
|
+
* so no control-character literal appears in a regex source (the codebase idiom).
|
|
131
|
+
*/
|
|
132
|
+
var ANSI_PATTERN = new RegExp(`(?:\\[[0-?]*[ -/]*[@-~]|\\][^]*(?:|\\\\)|[P^_X][^]*(?:|\\\\)|[ -/]+[0-~]|[0-?]|[@-OQ-WYZ\\\\]|[\`-~])`, "g");
|
|
133
|
+
/**
|
|
134
|
+
* Matches every C0 control character EXCEPT `\t` / `\n` / `\r` (which are meaningful
|
|
135
|
+
* whitespace), plus DEL (`0x7F`) — the non-printing bytes {@link
|
|
136
|
+
* import('./helpers.js').stripControls} removes. Global, ASCII-only source (no raw
|
|
137
|
+
* control-character literal), so a scan builds a fresh `RegExp` the same way as
|
|
138
|
+
* {@link ANSI_PATTERN} to avoid a mutated `lastIndex`.
|
|
139
|
+
*
|
|
140
|
+
* @remarks
|
|
141
|
+
* Deliberately SEPARATE from {@link ANSI_PATTERN}: `strip()` must stay pure ANSI-escape
|
|
142
|
+
* removal (width / alignment computations depend on it leaving raw C0 bytes alone), while
|
|
143
|
+
* C0-stripping is an ADDITIONAL, orthogonal pass a non-TTY output sink applies on top.
|
|
144
|
+
*/
|
|
145
|
+
var CONTROL_PATTERN = new RegExp(`[${String.fromCharCode(0)}-${String.fromCharCode(8)}${String.fromCharCode(11)}${String.fromCharCode(12)}${String.fromCharCode(14)}-${String.fromCharCode(31)}${String.fromCharCode(127)}]`, "g");
|
|
146
|
+
/**
|
|
147
|
+
* Each {@link LogLevel}'s numeric SEVERITY — the ascending order the level gate compares
|
|
148
|
+
* through (`debug` 0 < `info` 1 < `warn` 2 < `error` 3). A record is kept when its level's
|
|
149
|
+
* severity is at or above the logger's threshold. The source of truth for level ordering.
|
|
150
|
+
*/
|
|
151
|
+
var LEVEL_SEVERITY = Object.freeze({
|
|
152
|
+
debug: 0,
|
|
153
|
+
info: 1,
|
|
154
|
+
warn: 2,
|
|
155
|
+
error: 3
|
|
156
|
+
});
|
|
157
|
+
/**
|
|
158
|
+
* Each {@link LogLevel}'s default label {@link Color} — the level's VISUAL treatment, which
|
|
159
|
+
* is a styling choice ORTHOGONAL to the level itself (never a separate pseudo-level). The
|
|
160
|
+
* logger colors the level label through its styler with these; swapping a color never
|
|
161
|
+
* changes leveling. `debug` is cyan, `info` blue, `warn` yellow, `error` red.
|
|
162
|
+
*
|
|
163
|
+
* @remarks
|
|
164
|
+
* Excludes `default` so each value indexes a real styler accessor (the styler exposes a
|
|
165
|
+
* getter per non-`default` {@link Color}) — a level always renders in a concrete color.
|
|
166
|
+
*/
|
|
167
|
+
var LEVEL_COLORS = Object.freeze({
|
|
168
|
+
debug: "cyan",
|
|
169
|
+
info: "blue",
|
|
170
|
+
warn: "yellow",
|
|
171
|
+
error: "red"
|
|
172
|
+
});
|
|
173
|
+
/**
|
|
174
|
+
* The default bounded-retention cap for a {@link import('./types.js').LoggerInterface} — at
|
|
175
|
+
* most this many recent records are kept (oldest dropped first). Retention is ALWAYS bounded
|
|
176
|
+
* (never the unbounded buffer scsr leaked); a consumer overrides it via `options.limit`.
|
|
177
|
+
*/
|
|
178
|
+
var DEFAULT_LOG_LIMIT = 1e3;
|
|
179
|
+
/** The default {@link LogLevel} threshold a logger gates at when none is supplied — `info`. */
|
|
180
|
+
var DEFAULT_LOG_LEVEL = "info";
|
|
181
|
+
/**
|
|
182
|
+
* Every {@link LogLevel}, in ascending severity order — the levels a logger exposes as
|
|
183
|
+
* methods and the manager fans out to. The source of truth for the level axis (drives
|
|
184
|
+
* exhaustive tests); aligned with {@link LEVEL_SEVERITY}.
|
|
185
|
+
*/
|
|
186
|
+
var LEVELS = Object.freeze([
|
|
187
|
+
"debug",
|
|
188
|
+
"info",
|
|
189
|
+
"warn",
|
|
190
|
+
"error"
|
|
191
|
+
]);
|
|
192
|
+
/**
|
|
193
|
+
* The complete {@link BorderChars} junction set for each {@link BorderStyle} — the standard
|
|
194
|
+
* Unicode box-drawing glyphs at the four line weights. The renderers ({@link
|
|
195
|
+
* import('./helpers.js').renderBox} / {@link import('./helpers.js').renderTable}) look the
|
|
196
|
+
* style up here, so no glyph literal lives in a renderer. Deeply frozen.
|
|
197
|
+
*
|
|
198
|
+
* @remarks
|
|
199
|
+
* `round` shares `single`'s edges and tees — only its corners differ (the rounded `╭╮╰╯`).
|
|
200
|
+
*/
|
|
201
|
+
var BORDER_CHARS = Object.freeze({
|
|
202
|
+
single: Object.freeze({
|
|
203
|
+
horizontal: "─",
|
|
204
|
+
vertical: "│",
|
|
205
|
+
topLeft: "┌",
|
|
206
|
+
topRight: "┐",
|
|
207
|
+
bottomLeft: "└",
|
|
208
|
+
bottomRight: "┘",
|
|
209
|
+
cross: "┼",
|
|
210
|
+
teeDown: "┬",
|
|
211
|
+
teeUp: "┴",
|
|
212
|
+
teeRight: "├",
|
|
213
|
+
teeLeft: "┤"
|
|
214
|
+
}),
|
|
215
|
+
double: Object.freeze({
|
|
216
|
+
horizontal: "═",
|
|
217
|
+
vertical: "║",
|
|
218
|
+
topLeft: "╔",
|
|
219
|
+
topRight: "╗",
|
|
220
|
+
bottomLeft: "╚",
|
|
221
|
+
bottomRight: "╝",
|
|
222
|
+
cross: "╬",
|
|
223
|
+
teeDown: "╦",
|
|
224
|
+
teeUp: "╩",
|
|
225
|
+
teeRight: "╠",
|
|
226
|
+
teeLeft: "╣"
|
|
227
|
+
}),
|
|
228
|
+
round: Object.freeze({
|
|
229
|
+
horizontal: "─",
|
|
230
|
+
vertical: "│",
|
|
231
|
+
topLeft: "╭",
|
|
232
|
+
topRight: "╮",
|
|
233
|
+
bottomLeft: "╰",
|
|
234
|
+
bottomRight: "╯",
|
|
235
|
+
cross: "┼",
|
|
236
|
+
teeDown: "┬",
|
|
237
|
+
teeUp: "┴",
|
|
238
|
+
teeRight: "├",
|
|
239
|
+
teeLeft: "┤"
|
|
240
|
+
}),
|
|
241
|
+
heavy: Object.freeze({
|
|
242
|
+
horizontal: "━",
|
|
243
|
+
vertical: "┃",
|
|
244
|
+
topLeft: "┏",
|
|
245
|
+
topRight: "┓",
|
|
246
|
+
bottomLeft: "┗",
|
|
247
|
+
bottomRight: "┛",
|
|
248
|
+
cross: "╋",
|
|
249
|
+
teeDown: "┳",
|
|
250
|
+
teeUp: "┻",
|
|
251
|
+
teeRight: "┣",
|
|
252
|
+
teeLeft: "┫"
|
|
253
|
+
})
|
|
254
|
+
});
|
|
255
|
+
/**
|
|
256
|
+
* Each {@link StatusLevel}'s icon glyph — the leading mark a {@link
|
|
257
|
+
* import('./types.js').ReporterInterface.status} outcome line shows: `success` ✔, `error` ✖,
|
|
258
|
+
* `warn` ⚠, `info` ℹ. The narrative-outcome counterpart to a log level's label; frozen.
|
|
259
|
+
*/
|
|
260
|
+
var STATUS_ICONS = Object.freeze({
|
|
261
|
+
success: "✔",
|
|
262
|
+
error: "✖",
|
|
263
|
+
warn: "⚠",
|
|
264
|
+
info: "ℹ"
|
|
265
|
+
});
|
|
266
|
+
/**
|
|
267
|
+
* Each {@link StatusLevel}'s {@link Color} — the icon + message color a `status` line renders
|
|
268
|
+
* in (`success` green, `error` red, `warn` yellow, `info` blue). The VISUAL treatment of a
|
|
269
|
+
* narrative outcome, colored through the reporter's styler; orthogonal to leveling, like
|
|
270
|
+
* {@link LEVEL_COLORS}. Excludes `default` so each value indexes a real styler accessor.
|
|
271
|
+
*/
|
|
272
|
+
var STATUS_COLORS = Object.freeze({
|
|
273
|
+
success: "green",
|
|
274
|
+
error: "red",
|
|
275
|
+
warn: "yellow",
|
|
276
|
+
info: "blue"
|
|
277
|
+
});
|
|
278
|
+
/**
|
|
279
|
+
* Every {@link StatusLevel}, frozen — the outcomes a `status` line supports (drives exhaustive
|
|
280
|
+
* tests). The source of truth for the status axis; aligned with {@link STATUS_ICONS} /
|
|
281
|
+
* {@link STATUS_COLORS}.
|
|
282
|
+
*/
|
|
283
|
+
var STATUS_LEVELS = Object.freeze([
|
|
284
|
+
"success",
|
|
285
|
+
"error",
|
|
286
|
+
"warn",
|
|
287
|
+
"info"
|
|
288
|
+
]);
|
|
289
|
+
/**
|
|
290
|
+
* The tree connectors {@link import('./helpers.js').renderTree} draws — the `├─` branch (a
|
|
291
|
+
* non-last child), the `└─` corner (the last child), the `│ ` guide (carried down through an
|
|
292
|
+
* earlier branch's descendants), and the ` ` gap (under a last branch). Frozen.
|
|
293
|
+
*/
|
|
294
|
+
var TREE_CHARS = Object.freeze({
|
|
295
|
+
branch: "├─ ",
|
|
296
|
+
corner: "└─ ",
|
|
297
|
+
guide: "│ ",
|
|
298
|
+
gap: " "
|
|
299
|
+
});
|
|
300
|
+
/**
|
|
301
|
+
* The default visible column width for the width-aware renderers — the separator rule and a
|
|
302
|
+
* {@link import('./helpers.js').renderBox} with no explicit `width`, and the reporter's
|
|
303
|
+
* `section` rule. A sane terminal default (80 columns); a caller overrides it per-call or via
|
|
304
|
+
* {@link import('./types.js').ReporterOptions}`.width`.
|
|
305
|
+
*/
|
|
306
|
+
var DEFAULT_WIDTH = 80;
|
|
307
|
+
/** The default horizontal padding inside a box's edges ({@link import('./helpers.js').renderBox}) — one cell. */
|
|
308
|
+
var DEFAULT_PADDING = 1;
|
|
309
|
+
/** The default {@link BorderStyle} the box / table renderers frame with when none is given — `single`. */
|
|
310
|
+
var DEFAULT_BORDER = "single";
|
|
311
|
+
/** The default cell {@link Alignment} a {@link import('./types.js').ColumnSpec} uses when none is given — `left`. */
|
|
312
|
+
var DEFAULT_ALIGN = "left";
|
|
313
|
+
/** The default fill character {@link import('./helpers.js').renderSeparator} draws its rule with — `─`. */
|
|
314
|
+
var SEPARATOR_FILL = "─";
|
|
315
|
+
/**
|
|
316
|
+
* The single padding cell on each side of a separator's embedded title (` title `) — keeps the
|
|
317
|
+
* title from butting against the rule. One space.
|
|
318
|
+
*/
|
|
319
|
+
var SEPARATOR_TITLE_GAP = " ";
|
|
320
|
+
/**
|
|
321
|
+
* The number of milliseconds at or above which {@link import('./helpers.js').formatDuration}
|
|
322
|
+
* (and so `Reporter.timing`) switches from a `…ms` rendering to a `…s` (seconds, 2 d.p.)
|
|
323
|
+
* rendering — exactly one second.
|
|
324
|
+
*/
|
|
325
|
+
var SECOND_MS = 1e3;
|
|
326
|
+
/**
|
|
327
|
+
* Every {@link CaptureLevel}, frozen — the `console.*` methods a {@link
|
|
328
|
+
* import('./types.js').CaptureInterface} intercepts by default (and the source of truth for the
|
|
329
|
+
* capture-level axis; drives exhaustive tests). The universal console methods: `log`, `info`,
|
|
330
|
+
* `warn`, `error`, `debug`.
|
|
331
|
+
*/
|
|
332
|
+
var CAPTURE_LEVELS = Object.freeze([
|
|
333
|
+
"log",
|
|
334
|
+
"info",
|
|
335
|
+
"warn",
|
|
336
|
+
"error",
|
|
337
|
+
"debug"
|
|
338
|
+
]);
|
|
339
|
+
/**
|
|
340
|
+
* The default set of {@link CaptureLevel}s a Capture patches when `options.levels` is omitted —
|
|
341
|
+
* all five universal `console.*` methods ({@link CAPTURE_LEVELS}). A consumer narrows it (e.g. just
|
|
342
|
+
* `['warn', 'error']`) via `options.levels`.
|
|
343
|
+
*/
|
|
344
|
+
var DEFAULT_CAPTURE_LEVELS = CAPTURE_LEVELS;
|
|
345
|
+
/**
|
|
346
|
+
* The default bounded-buffer cap for a {@link import('./types.js').CaptureInterface} — at most this
|
|
347
|
+
* many recent {@link CapturedMessage}s are retained per buffer (the total buffer AND each by-level
|
|
348
|
+
* bucket; oldest dropped first). Capture retention is ALWAYS bounded so a long-running capture can
|
|
349
|
+
* never grow without bound (the same retention precedent as {@link DEFAULT_LOG_LIMIT}); a consumer
|
|
350
|
+
* overrides it via `options.limit`.
|
|
351
|
+
*/
|
|
352
|
+
var DEFAULT_CAPTURE_LIMIT = 1e3;
|
|
353
|
+
/**
|
|
354
|
+
* Each {@link CaptureLevel}'s {@link LogLevel} for the optional sink forward — the projection the
|
|
355
|
+
* Capture routes through when writing an intercepted call to a {@link
|
|
356
|
+
* import('./types.js').SinkInterface} (`sink.write(text, CAPTURE_LEVEL_MAP[level])`). `warn` /
|
|
357
|
+
* `error` / `debug` / `info` map to their matching {@link LogLevel}; `log` maps to `info` (a plain
|
|
358
|
+
* console log is informational — the default stream), so a stream-aware sink routes `warn` / `error`
|
|
359
|
+
* captures to the right stream. The source of truth for the capture-to-log projection.
|
|
360
|
+
*/
|
|
361
|
+
var CAPTURE_LEVEL_MAP = Object.freeze({
|
|
362
|
+
log: "info",
|
|
363
|
+
info: "info",
|
|
364
|
+
warn: "warn",
|
|
365
|
+
error: "error",
|
|
366
|
+
debug: "debug"
|
|
367
|
+
});
|
|
368
|
+
/**
|
|
369
|
+
* The default spinner frame cycle a {@link import('./types.js').SpinnerInterface} advances through —
|
|
370
|
+
* the ten braille-pattern glyphs (U+2800 block) that read as a smoothly rotating dot, the universal
|
|
371
|
+
* terminal-spinner convention. Frozen; a consumer swaps the whole cycle via `options.frames`.
|
|
372
|
+
*
|
|
373
|
+
* @remarks
|
|
374
|
+
* Braille glyphs are single visible cells, so every frame occupies one column — the spinner glyph
|
|
375
|
+
* never shifts the message beside it as it advances. The source of truth for the default frame axis.
|
|
376
|
+
*/
|
|
377
|
+
var SPINNER_FRAMES = Object.freeze([
|
|
378
|
+
"⠋",
|
|
379
|
+
"⠙",
|
|
380
|
+
"⠹",
|
|
381
|
+
"⠸",
|
|
382
|
+
"⠼",
|
|
383
|
+
"⠴",
|
|
384
|
+
"⠦",
|
|
385
|
+
"⠧",
|
|
386
|
+
"⠇",
|
|
387
|
+
"⠏"
|
|
388
|
+
]);
|
|
389
|
+
/**
|
|
390
|
+
* The default timer period in milliseconds between a {@link import('./types.js').SpinnerInterface}'s
|
|
391
|
+
* frames — the `setInterval` interval `start()` arms. Eighty milliseconds (≈12.5 frames/second) is
|
|
392
|
+
* the conventional spinner cadence: fast enough to read as motion, slow enough not to thrash a
|
|
393
|
+
* terminal. A consumer overrides it via `options.interval`.
|
|
394
|
+
*/
|
|
395
|
+
var DEFAULT_SPINNER_INTERVAL = 80;
|
|
396
|
+
/**
|
|
397
|
+
* The default FILLED-cell glyph {@link import('./helpers.js').renderBar} draws the completed run of a
|
|
398
|
+
* progress bar with — the full block `█` (U+2588). A single visible cell; a consumer overrides it via
|
|
399
|
+
* {@link import('./types.js').ProgressBarOptions}`.fill`.
|
|
400
|
+
*/
|
|
401
|
+
var BAR_FILL = "█";
|
|
402
|
+
/**
|
|
403
|
+
* The default EMPTY-cell glyph {@link import('./helpers.js').renderBar} draws the remaining run of a
|
|
404
|
+
* progress bar with — the light-shade block `░` (U+2591). A single visible cell; a consumer overrides
|
|
405
|
+
* it via {@link import('./types.js').ProgressBarOptions}`.empty`.
|
|
406
|
+
*/
|
|
407
|
+
var BAR_EMPTY = "░";
|
|
408
|
+
/**
|
|
409
|
+
* The default visible cell count of a progress-bar TRACK — the glyph run {@link
|
|
410
|
+
* import('./helpers.js').renderBar} fills (and a {@link import('./types.js').ProgressInterface} sizes
|
|
411
|
+
* its bar to). Thirty cells is a compact, terminal-friendly default; a consumer overrides it via
|
|
412
|
+
* `options.width`. Distinct from {@link DEFAULT_WIDTH} (the renderers' 80-column line width) — a bar
|
|
413
|
+
* track is one inline element, not a full-width rule.
|
|
414
|
+
*/
|
|
415
|
+
var DEFAULT_BAR_WIDTH = 30;
|
|
416
|
+
//#endregion
|
|
417
|
+
//#region src/core/errors.ts
|
|
418
|
+
/**
|
|
419
|
+
* An error thrown by the console layer.
|
|
420
|
+
*
|
|
421
|
+
* @remarks
|
|
422
|
+
* Carries a {@link ConsoleErrorCode} and an optional `context` bag. Thrown for: an
|
|
423
|
+
* internal invariant violated at a defensive, structurally-unreachable guard
|
|
424
|
+
* (`INVARIANT`) — the one throw site in this codebase today.
|
|
425
|
+
*/
|
|
426
|
+
var ConsoleError = class extends Error {
|
|
427
|
+
code;
|
|
428
|
+
context;
|
|
429
|
+
constructor(code, message, context) {
|
|
430
|
+
super(message);
|
|
431
|
+
this.name = "ConsoleError";
|
|
432
|
+
this.code = code;
|
|
433
|
+
this.context = context;
|
|
434
|
+
}
|
|
435
|
+
};
|
|
436
|
+
/**
|
|
437
|
+
* Narrow an unknown caught value to a {@link ConsoleError}.
|
|
438
|
+
*
|
|
439
|
+
* @param value - The value to test (typically a `catch` binding)
|
|
440
|
+
* @returns `true` when `value` is a {@link ConsoleError}
|
|
441
|
+
*
|
|
442
|
+
* @example
|
|
443
|
+
* ```ts
|
|
444
|
+
* try {
|
|
445
|
+
* createStyler().style
|
|
446
|
+
* } catch (error) {
|
|
447
|
+
* if (isConsoleError(error) && error.code === 'INVARIANT') report(error)
|
|
448
|
+
* }
|
|
449
|
+
* ```
|
|
450
|
+
*/
|
|
451
|
+
function isConsoleError(value) {
|
|
452
|
+
return value instanceof ConsoleError;
|
|
453
|
+
}
|
|
454
|
+
//#endregion
|
|
455
|
+
//#region src/core/helpers.ts
|
|
456
|
+
/**
|
|
457
|
+
* Remove every ANSI escape sequence from `text`, returning the plain visible string.
|
|
458
|
+
*
|
|
459
|
+
* @remarks
|
|
460
|
+
* Strips SGR color/style codes AND other CSI controls (cursor, erase) plus OSC
|
|
461
|
+
* sequences (titles, hyperlinks) — see {@link ANSI_PATTERN}. A FRESH `RegExp` is built
|
|
462
|
+
* per call from the canonical pattern's `source` + `flags`, so the shared global
|
|
463
|
+
* pattern's `lastIndex` is never mutated across calls (re-entrant and deterministic).
|
|
464
|
+
*
|
|
465
|
+
* @param text - Any string, styled or plain
|
|
466
|
+
* @returns `text` with all ANSI escapes removed
|
|
467
|
+
*
|
|
468
|
+
* @example
|
|
469
|
+
* ```ts
|
|
470
|
+
* strip('\x1b[31mred\x1b[0m') // 'red'
|
|
471
|
+
* ```
|
|
472
|
+
*/
|
|
473
|
+
function strip(text) {
|
|
474
|
+
return text.replace(new RegExp(ANSI_PATTERN.source, ANSI_PATTERN.flags), "");
|
|
475
|
+
}
|
|
476
|
+
/**
|
|
477
|
+
* Remove every non-printing C0 control character from `text` EXCEPT `\t` / `\n` / `\r`
|
|
478
|
+
* (meaningful whitespace), plus DEL — returning the sanitized string.
|
|
479
|
+
*
|
|
480
|
+
* @remarks
|
|
481
|
+
* Deliberately SEPARATE from {@link strip} (ANSI-escape removal only, so `width` /
|
|
482
|
+
* `align` stay untouched) — this is the additional pass a non-TTY output sink applies
|
|
483
|
+
* on top of `strip`, so a captured `\x07` bell or stray `\x00` never reaches a log file
|
|
484
|
+
* / non-terminal target. A FRESH `RegExp` is built per call from {@link CONTROL_PATTERN}'s
|
|
485
|
+
* `source` + `flags`, the same re-entrant idiom as `strip`.
|
|
486
|
+
*
|
|
487
|
+
* @param text - Any string, possibly carrying raw control bytes
|
|
488
|
+
* @returns `text` with C0 controls (other than tab/newline/CR) and DEL removed
|
|
489
|
+
*
|
|
490
|
+
* @example
|
|
491
|
+
* ```ts
|
|
492
|
+
* stripControls('a\x07b\nc') // 'ab\nc'
|
|
493
|
+
* ```
|
|
494
|
+
*/
|
|
495
|
+
function stripControls(text) {
|
|
496
|
+
return text.replace(new RegExp(CONTROL_PATTERN.source, CONTROL_PATTERN.flags), "");
|
|
497
|
+
}
|
|
498
|
+
/**
|
|
499
|
+
* The visible width of `text` — its length after ANSI escapes are stripped, counted in
|
|
500
|
+
* Unicode code points (so an astral character such as an emoji counts as one, not the
|
|
501
|
+
* two UTF-16 units `String.length` would report).
|
|
502
|
+
*
|
|
503
|
+
* @remarks
|
|
504
|
+
* The basis for terminal layout (box / table / progress alignment): the column count a
|
|
505
|
+
* styled string occupies, independent of its escape codes. It does NOT account for
|
|
506
|
+
* wide (CJK / fullwidth) glyphs occupying two cells — a deliberate, documented
|
|
507
|
+
* simplification at this layer; callers needing east-asian width handle it above.
|
|
508
|
+
*
|
|
509
|
+
* @param text - Any string, styled or plain
|
|
510
|
+
* @returns The count of visible code points
|
|
511
|
+
*
|
|
512
|
+
* @example
|
|
513
|
+
* ```ts
|
|
514
|
+
* width('\x1b[1mhi\x1b[0m') // 2
|
|
515
|
+
* ```
|
|
516
|
+
*/
|
|
517
|
+
function width(text) {
|
|
518
|
+
return [...strip(text)].length;
|
|
519
|
+
}
|
|
520
|
+
/**
|
|
521
|
+
* Whether a record at `level` passes a logger gated at `threshold` — i.e. its severity is
|
|
522
|
+
* at or above the threshold's.
|
|
523
|
+
*
|
|
524
|
+
* @remarks
|
|
525
|
+
* The level gate (AGENTS §5 — the comparison lives here, not inlined in the logger). Reads
|
|
526
|
+
* the ascending {@link LEVEL_SEVERITY} order: `meetsLevel('warn', 'error')` is `true`
|
|
527
|
+
* (error ≥ warn), `meetsLevel('warn', 'info')` is `false` (info < warn).
|
|
528
|
+
*
|
|
529
|
+
* @param threshold - The logger's configured minimum {@link LogLevel}
|
|
530
|
+
* @param level - The record's {@link LogLevel}
|
|
531
|
+
* @returns `true` when `level` is at least as severe as `threshold`
|
|
532
|
+
*
|
|
533
|
+
* @example
|
|
534
|
+
* ```ts
|
|
535
|
+
* meetsLevel('info', 'error') // true
|
|
536
|
+
* meetsLevel('error', 'warn') // false
|
|
537
|
+
* ```
|
|
538
|
+
*/
|
|
539
|
+
function meetsLevel(threshold, level) {
|
|
540
|
+
return LEVEL_SEVERITY[level] >= LEVEL_SEVERITY[threshold];
|
|
541
|
+
}
|
|
542
|
+
/**
|
|
543
|
+
* Format a {@link LogRecord}'s `time` (epoch milliseconds) as an ISO-8601 timestamp string.
|
|
544
|
+
*
|
|
545
|
+
* @remarks
|
|
546
|
+
* Deterministic and serializable — `new Date(time).toISOString()`, e.g.
|
|
547
|
+
* `1716900000000 → '2024-05-28T12:40:00.000Z'`. The timestamp portion of the formatted log
|
|
548
|
+
* line; kept a pure helper so the line layout and the logger stay decoupled.
|
|
549
|
+
*
|
|
550
|
+
* @param time - Epoch milliseconds (a record's `time`)
|
|
551
|
+
* @returns The ISO-8601 timestamp
|
|
552
|
+
*/
|
|
553
|
+
function formatTime(time) {
|
|
554
|
+
return new Date(time).toISOString();
|
|
555
|
+
}
|
|
556
|
+
/**
|
|
557
|
+
* Format a {@link LogRecord} into a single styled line — the default human line layout a
|
|
558
|
+
* {@link import('./types.js').LoggerInterface} writes to its sink.
|
|
559
|
+
*
|
|
560
|
+
* @remarks
|
|
561
|
+
* Layout: `{time} {LEVEL} {[name]} {message}{ data}` — the ISO timestamp (dimmed), the
|
|
562
|
+
* upper-cased level label (colored by {@link LEVEL_COLORS} — styling ORTHOGONAL to level),
|
|
563
|
+
* the originating logger's `name` in brackets (omitted when absent), the message, and the
|
|
564
|
+
* structured `data` appended as compact JSON (omitted when absent / empty). Coloring flows
|
|
565
|
+
* through the injected `styler`, so a disabled styler yields a plain line and a browser
|
|
566
|
+
* `%c` styler (C-f) retargets it — the layout never changes. Pure: same record + styler →
|
|
567
|
+
* same line.
|
|
568
|
+
*
|
|
569
|
+
* @param record - The {@link LogRecord} to render
|
|
570
|
+
* @param styler - The {@link StylerInterface} the labels are colored through
|
|
571
|
+
* @returns The formatted, styled line (no trailing newline — the sink's target adds it)
|
|
572
|
+
*
|
|
573
|
+
* @example
|
|
574
|
+
* ```ts
|
|
575
|
+
* formatRecord({ level: 'warn', message: 'low disk', time: 0, name: 'fs' }, createStyler())
|
|
576
|
+
* // '<dim>1970-01-01T00:00:00.000Z</> <yellow>WARN</> [fs] low disk'
|
|
577
|
+
* ```
|
|
578
|
+
*/
|
|
579
|
+
function formatRecord(record, styler) {
|
|
580
|
+
const time = styler.dim(formatTime(record.time));
|
|
581
|
+
const label = styler[LEVEL_COLORS[record.level]](record.level.toUpperCase());
|
|
582
|
+
const name = record.name === void 0 ? "" : ` ${styler.dim(`[${record.name}]`)}`;
|
|
583
|
+
const data = record.data === void 0 || Object.keys(record.data).length === 0 ? "" : ` ${styler.dim(JSON.stringify(record.data))}`;
|
|
584
|
+
return `${time} ${label}${name} ${record.message}${data}`;
|
|
585
|
+
}
|
|
586
|
+
/**
|
|
587
|
+
* Pad (or, when over budget, truncate) `text` to exactly `target` VISIBLE columns, positioning
|
|
588
|
+
* it by `alignment`. The width primitive the box / table renderers align every cell with.
|
|
589
|
+
*
|
|
590
|
+
* @remarks
|
|
591
|
+
* Measures with {@link width} (visible code points, ANSI-aware), so a styled string aligns by
|
|
592
|
+
* its visible content, not its escape codes. When `width(text) < target`, the deficit is added
|
|
593
|
+
* as spaces — all trailing (`left`), all leading (`right`), or split with the extra space on
|
|
594
|
+
* the right (`center`). When `width(text) > target`, the VISIBLE characters are sliced to
|
|
595
|
+
* `target` (a defensive guard — the renderers size columns to fit, so this is rarely hit; it
|
|
596
|
+
* slices the stripped text, so it never bisects an escape sequence into a broken half).
|
|
597
|
+
*
|
|
598
|
+
* @param text - The cell content (may be styled)
|
|
599
|
+
* @param target - The visible column count to fit `text` into
|
|
600
|
+
* @param alignment - Where to position `text` within the width; defaults to `left`
|
|
601
|
+
* @returns `text` fitted to exactly `target` visible columns
|
|
602
|
+
*
|
|
603
|
+
* @example
|
|
604
|
+
* ```ts
|
|
605
|
+
* align('hi', 5) // 'hi '
|
|
606
|
+
* align('hi', 5, 'right') // ' hi'
|
|
607
|
+
* align('hi', 5, 'center') // ' hi '
|
|
608
|
+
* ```
|
|
609
|
+
*/
|
|
610
|
+
function align(text, target, alignment = DEFAULT_ALIGN) {
|
|
611
|
+
const visible = width(text);
|
|
612
|
+
if (visible > target) return [...strip(text)].slice(0, target).join("");
|
|
613
|
+
const deficit = target - visible;
|
|
614
|
+
if (alignment === "right") return `${" ".repeat(deficit)}${text}`;
|
|
615
|
+
if (alignment === "center") {
|
|
616
|
+
const left = Math.floor(deficit / 2);
|
|
617
|
+
return `${" ".repeat(left)}${text}${" ".repeat(deficit - left)}`;
|
|
618
|
+
}
|
|
619
|
+
return `${text}${" ".repeat(deficit)}`;
|
|
620
|
+
}
|
|
621
|
+
/**
|
|
622
|
+
* Format a millisecond duration as a compact human string — `…ms` below one second, `…s`
|
|
623
|
+
* (seconds to 2 decimal places) at or above one second. The timing rendering behind
|
|
624
|
+
* {@link import('./types.js').ReporterInterface.timing}.
|
|
625
|
+
*
|
|
626
|
+
* @remarks
|
|
627
|
+
* `999 → '999ms'`, `1000 → '1.00s'`, `1230 → '1.23s'` (the threshold is {@link SECOND_MS}).
|
|
628
|
+
* Pure and deterministic; kept a shared helper so the layout and the reporter stay decoupled.
|
|
629
|
+
*
|
|
630
|
+
* @param ms - The duration in milliseconds
|
|
631
|
+
* @returns The formatted duration (`'<n>ms'` or `'<n>s'`)
|
|
632
|
+
*/
|
|
633
|
+
function formatDuration(ms) {
|
|
634
|
+
return ms < 1e3 ? `${ms}ms` : `${(ms / SECOND_MS).toFixed(2)}s`;
|
|
635
|
+
}
|
|
636
|
+
/**
|
|
637
|
+
* Color `text` through `styler`, or return it verbatim when `styler` is `undefined` — the
|
|
638
|
+
* single optional-styling primitive every renderer applies to its border / title / connector
|
|
639
|
+
* glyphs (AGENTS §5 — the ONE styler seam, shared, never re-hand-rolled per renderer).
|
|
640
|
+
*
|
|
641
|
+
* @remarks
|
|
642
|
+
* The renderers all take an OPTIONAL `styler`: present ⇒ glyphs are colored, absent ⇒ plain.
|
|
643
|
+
* Folding that `styler === undefined ? text : styler(text)` ternary into one exported helper
|
|
644
|
+
* keeps the renderers terse and the styling decision in one tested place. A disabled styler
|
|
645
|
+
* (`enabled: false`) is still a styler — it returns its text verbatim — so passing one paints
|
|
646
|
+
* a no-op, exactly as omitting it does.
|
|
647
|
+
*
|
|
648
|
+
* @param styler - The {@link StylerInterface} to color with, or `undefined` for no styling
|
|
649
|
+
* @param text - The glyphs / text to color
|
|
650
|
+
* @returns `styler(text)` when a styler is given, else `text` unchanged
|
|
651
|
+
*/
|
|
652
|
+
function paint(styler, text) {
|
|
653
|
+
return styler === void 0 ? text : styler(text);
|
|
654
|
+
}
|
|
655
|
+
/**
|
|
656
|
+
* Repeat `unit` until it fills exactly `count` VISIBLE columns, trimming a trailing partial
|
|
657
|
+
* unit so the run is never over-wide — the fill primitive the separator + box edges draw with.
|
|
658
|
+
*
|
|
659
|
+
* @remarks
|
|
660
|
+
* Counts in code points ({@link width}-consistent), so a multi-cell or astral `unit` is laid
|
|
661
|
+
* down whole and the result is sliced to exactly `count` visible columns. `count <= 0` (or an
|
|
662
|
+
* empty / zero-width `unit`) yields `''`.
|
|
663
|
+
*
|
|
664
|
+
* @param unit - The (possibly multi-character) fill unit
|
|
665
|
+
* @param count - The visible column count to fill
|
|
666
|
+
* @returns `unit` tiled to exactly `count` visible columns
|
|
667
|
+
*
|
|
668
|
+
* @example
|
|
669
|
+
* ```ts
|
|
670
|
+
* repeatTo('─', 4) // '────'
|
|
671
|
+
* repeatTo('=-', 5) // '=-=-='
|
|
672
|
+
* ```
|
|
673
|
+
*/
|
|
674
|
+
function repeatTo(unit, count) {
|
|
675
|
+
if (count <= 0) return "";
|
|
676
|
+
const per = width(unit);
|
|
677
|
+
if (per === 0) return "";
|
|
678
|
+
return [...unit.repeat(Math.ceil(count / per))].slice(0, count).join("");
|
|
679
|
+
}
|
|
680
|
+
/**
|
|
681
|
+
* The cell at `index` of a (possibly ragged) row — `''` when the row is shorter than the
|
|
682
|
+
* column count, so a short row pads out instead of throwing (the ragged-row guard
|
|
683
|
+
* {@link renderTable} reads every cell through).
|
|
684
|
+
*
|
|
685
|
+
* @param row - The row's cells
|
|
686
|
+
* @param index - The column index to read
|
|
687
|
+
* @returns The cell text, or `''` when the row has no cell at `index`
|
|
688
|
+
*/
|
|
689
|
+
function cellAt(row, index) {
|
|
690
|
+
return row[index] ?? "";
|
|
691
|
+
}
|
|
692
|
+
/**
|
|
693
|
+
* Render a horizontal rule — an optional centered title embedded in a line of fill characters,
|
|
694
|
+
* to a fixed visible width. Pure: same {@link SeparatorOptions} → same string.
|
|
695
|
+
*
|
|
696
|
+
* @remarks
|
|
697
|
+
* - **Plain rule.** With no `title`, returns `fill` repeated to `width` visible columns.
|
|
698
|
+
* - **Titled rule.** With a `title`, centers ` title ` (one {@link SEPARATOR_TITLE_GAP} each
|
|
699
|
+
* side) in the line, splitting the remaining fill between the two sides (the extra column,
|
|
700
|
+
* when the remainder is odd, goes to the right). The visible width stays exactly `width`,
|
|
701
|
+
* even when the title is styled (the title's escape codes don't count toward the budget) —
|
|
702
|
+
* a title at least as wide as `width` yields just the gapped title (no fill).
|
|
703
|
+
* - **Styling.** When `options.styler` is given, the fill runs (and the embedded title) are
|
|
704
|
+
* colored through it; the layout is identical with or without color, since width is measured
|
|
705
|
+
* on the visible content (AGENTS — width-aware via {@link width}).
|
|
706
|
+
*
|
|
707
|
+
* @param options - See {@link SeparatorOptions}
|
|
708
|
+
* @returns The rule line (no trailing newline)
|
|
709
|
+
*
|
|
710
|
+
* @example
|
|
711
|
+
* ```ts
|
|
712
|
+
* renderSeparator({ width: 10 }) // '──────────'
|
|
713
|
+
* renderSeparator({ title: 'Build', width: 13 }) // '── Build ──' (centered)
|
|
714
|
+
* ```
|
|
715
|
+
*/
|
|
716
|
+
function renderSeparator(options) {
|
|
717
|
+
const total = options.width ?? 80;
|
|
718
|
+
const fill = options.fill ?? "─";
|
|
719
|
+
if (options.title === void 0) return paint(options.styler, repeatTo(fill, total));
|
|
720
|
+
const gapped = ` ${paint(options.styler, options.title)} `;
|
|
721
|
+
const room = total - width(options.title) - 2;
|
|
722
|
+
if (room <= 0) return gapped;
|
|
723
|
+
const left = Math.floor(room / 2);
|
|
724
|
+
return `${paint(options.styler, repeatTo(fill, left))}${gapped}${paint(options.styler, repeatTo(fill, room - left))}`;
|
|
725
|
+
}
|
|
726
|
+
/**
|
|
727
|
+
* Render `content` framed in box-drawing characters, optionally captioned, width-aware so
|
|
728
|
+
* styled content stays aligned inside the frame. Pure: same {@link BoxOptions} → same string.
|
|
729
|
+
*
|
|
730
|
+
* @remarks
|
|
731
|
+
* - **Lines.** `content` is split on `\n`; each line is padded (left-aligned) to the inner
|
|
732
|
+
* width by {@link align} — measured on VISIBLE width, so a styled line never breaks the
|
|
733
|
+
* right edge. The inner width is the widest line's visible width (or `width − borders −
|
|
734
|
+
* 2·padding` when an explicit `width` is given and is wider), plus `padding` blank cells
|
|
735
|
+
* inside each {@link BorderChars.vertical} edge.
|
|
736
|
+
* - **Title.** An optional `title` is embedded in the TOP border (` title `), the remaining
|
|
737
|
+
* top edge drawn as fill; a title wider than the inner width widens the box to fit it.
|
|
738
|
+
* - **Border + styling.** The {@link BorderStyle} (`options.border`, default
|
|
739
|
+
* {@link DEFAULT_BORDER}) selects the glyph set from {@link BORDER_CHARS}; `options.styler`
|
|
740
|
+
* colors the frame + title when given (content cells are written as supplied).
|
|
741
|
+
* - **Multi-line result.** Returns the box as `\n`-joined rows (top, one row per content line,
|
|
742
|
+
* bottom) with no trailing newline.
|
|
743
|
+
*
|
|
744
|
+
* @param options - See {@link BoxOptions}
|
|
745
|
+
* @returns The framed box (multiple lines joined by `\n`)
|
|
746
|
+
*/
|
|
747
|
+
function renderBox(options) {
|
|
748
|
+
const chars = BORDER_CHARS[options.border ?? "single"];
|
|
749
|
+
const padding = Math.max(0, Math.trunc(options.padding ?? 1));
|
|
750
|
+
const styler = options.styler;
|
|
751
|
+
const lines = options.content.split("\n");
|
|
752
|
+
const titleRoom = options.title === void 0 ? 0 : width(options.title) + 2 + 1 - padding * 2;
|
|
753
|
+
const budget = options.width === void 0 ? 0 : options.width - 2 - padding * 2;
|
|
754
|
+
const inner = lines.reduce((max, line) => Math.max(max, width(line)), Math.max(0, titleRoom, budget));
|
|
755
|
+
const gutter = " ".repeat(padding);
|
|
756
|
+
const bar = paint(styler, chars.vertical);
|
|
757
|
+
const boxTop = () => {
|
|
758
|
+
const span = inner + padding * 2;
|
|
759
|
+
if (options.title === void 0) return paint(styler, `${chars.topLeft}${repeatTo(chars.horizontal, span)}${chars.topRight}`);
|
|
760
|
+
const caption = ` ${options.title} `;
|
|
761
|
+
const room = span - width(caption);
|
|
762
|
+
const lead = paint(styler, repeatTo(chars.horizontal, 1));
|
|
763
|
+
const rest = room - 1 <= 0 ? "" : paint(styler, repeatTo(chars.horizontal, room - 1));
|
|
764
|
+
return `${paint(styler, chars.topLeft)}${lead}${paint(styler, caption)}${rest}${paint(styler, chars.topRight)}`;
|
|
765
|
+
};
|
|
766
|
+
const top = boxTop();
|
|
767
|
+
const bottom = paint(styler, `${chars.bottomLeft}${repeatTo(chars.horizontal, inner + padding * 2)}${chars.bottomRight}`);
|
|
768
|
+
return [
|
|
769
|
+
top,
|
|
770
|
+
...lines.map((line) => `${bar}${gutter}${align(line, inner)}${gutter}${bar}`),
|
|
771
|
+
bottom
|
|
772
|
+
].join("\n");
|
|
773
|
+
}
|
|
774
|
+
/**
|
|
775
|
+
* Render a bordered grid of `columns` + `rows` with per-column alignment and width-aware
|
|
776
|
+
* column sizing. Pure: same {@link TableOptions} → same string.
|
|
777
|
+
*
|
|
778
|
+
* @remarks
|
|
779
|
+
* - **Column sizing — visible width.** Each column is sized to the widest VISIBLE width
|
|
780
|
+
* ({@link width}) among its header label and its cells, so an already-styled cell never
|
|
781
|
+
* breaks the column (its escape codes don't count toward the width).
|
|
782
|
+
* - **Ragged rows.** A row shorter than the column count is padded with empty cells; a longer
|
|
783
|
+
* row is truncated to the column count — a ragged input never throws.
|
|
784
|
+
* - **Alignment.** Each cell is positioned by its column's {@link ColumnSpec.align} (default
|
|
785
|
+
* {@link DEFAULT_ALIGN}) via {@link align}.
|
|
786
|
+
* - **Frame.** The {@link BorderStyle} (`options.border`, default {@link DEFAULT_BORDER})
|
|
787
|
+
* draws the outer frame, the header rule (a `teeRight … cross … teeLeft` line), and the
|
|
788
|
+
* `vertical` column separators; `options.styler` colors the frame + header labels when
|
|
789
|
+
* given. Returns the table as `\n`-joined rows (top, header, rule, one row per data row,
|
|
790
|
+
* bottom), no trailing newline.
|
|
791
|
+
*
|
|
792
|
+
* @param options - See {@link TableOptions}
|
|
793
|
+
* @returns The rendered table (multiple lines joined by `\n`)
|
|
794
|
+
*/
|
|
795
|
+
function renderTable(options) {
|
|
796
|
+
const chars = BORDER_CHARS[options.border ?? "single"];
|
|
797
|
+
const styler = options.styler;
|
|
798
|
+
const columns = options.columns;
|
|
799
|
+
const widths = columns.map((column, index) => options.rows.reduce((max, row) => Math.max(max, width(cellAt(row, index))), width(column.label)));
|
|
800
|
+
const aligns = columns.map((column) => column.align ?? "left");
|
|
801
|
+
const tableRow = (cells) => {
|
|
802
|
+
const bar = paint(styler, chars.vertical);
|
|
803
|
+
return `${bar}${cells.map((cell, index) => ` ${align(cell, widths[index] ?? width(cell), aligns[index] ?? "left")} `).join(bar)}${bar}`;
|
|
804
|
+
};
|
|
805
|
+
const tableEdge = (left, mid, right) => {
|
|
806
|
+
const segments = widths.map((columnWidth) => repeatTo(chars.horizontal, columnWidth + 2));
|
|
807
|
+
return paint(styler, `${left}${segments.join(mid)}${right}`);
|
|
808
|
+
};
|
|
809
|
+
const header = tableRow(columns.map((column) => paint(styler, column.label)));
|
|
810
|
+
const body = options.rows.map((row) => tableRow(columns.map((_column, index) => cellAt(row, index))));
|
|
811
|
+
return [
|
|
812
|
+
tableEdge(chars.topLeft, chars.teeDown, chars.topRight),
|
|
813
|
+
header,
|
|
814
|
+
tableEdge(chars.teeRight, chars.cross, chars.teeLeft),
|
|
815
|
+
...body,
|
|
816
|
+
tableEdge(chars.bottomLeft, chars.teeUp, chars.bottomRight)
|
|
817
|
+
].join("\n");
|
|
818
|
+
}
|
|
819
|
+
/**
|
|
820
|
+
* Render a nested {@link TreeNode} tree with box-drawing connectors. Pure: same
|
|
821
|
+
* {@link TreeOptions} → same string.
|
|
822
|
+
*
|
|
823
|
+
* @remarks
|
|
824
|
+
* The `root` label is the unindented first line; its descendants are drawn beneath it with
|
|
825
|
+
* {@link TREE_CHARS} — `├─ ` before each child but the last, `└─ ` before the last, and the
|
|
826
|
+
* carried prefix using `│ ` under an ancestor that still has later siblings or ` ` under a
|
|
827
|
+
* last ancestor (so the guides line up exactly under the branch they descend from). Node
|
|
828
|
+
* labels are written as given (an already-styled label is honored); `options.styler` colors
|
|
829
|
+
* the connectors when supplied. Returns the tree as `\n`-joined lines, no trailing newline.
|
|
830
|
+
*
|
|
831
|
+
* @param options - See {@link TreeOptions}
|
|
832
|
+
* @returns The rendered tree (multiple lines joined by `\n`)
|
|
833
|
+
*
|
|
834
|
+
* @example
|
|
835
|
+
* ```ts
|
|
836
|
+
* renderTree({ root: { label: 'root', children: [{ label: 'a' }, { label: 'b' }] } })
|
|
837
|
+
* // root
|
|
838
|
+
* // ├─ a
|
|
839
|
+
* // └─ b
|
|
840
|
+
* ```
|
|
841
|
+
*/
|
|
842
|
+
function renderTree(options) {
|
|
843
|
+
return [options.root.label, ...renderTreeChildren(options.root.children ?? [], "", options.styler)].join("\n");
|
|
844
|
+
}
|
|
845
|
+
/**
|
|
846
|
+
* Render the connector-prefixed lines for a {@link TreeNode} list — the recursive core
|
|
847
|
+
* behind {@link renderTree}. Each child is drawn as `prefix` + its connector (`├─ ` for
|
|
848
|
+
* any but the last, `└─ ` for the last) + its label, with its own descendants recursed
|
|
849
|
+
* beneath under the carried guide (`│ ` under a non-last node, ` ` under the last).
|
|
850
|
+
*
|
|
851
|
+
* @remarks
|
|
852
|
+
* A centralized, exported recursion branch (AGENTS §5) so it is directly testable and
|
|
853
|
+
* reusable outside {@link renderTree}'s top-level `root.label` framing.
|
|
854
|
+
*
|
|
855
|
+
* @param nodes - The sibling {@link TreeNode}s to render at this depth
|
|
856
|
+
* @param prefix - The guide/gap string carried in from the ancestor chain (`''` at the root)
|
|
857
|
+
* @param styler - The {@link StylerInterface} connectors are colored through, when supplied
|
|
858
|
+
* @returns The rendered lines for `nodes` and all their descendants
|
|
859
|
+
*
|
|
860
|
+
* @example
|
|
861
|
+
* ```ts
|
|
862
|
+
* renderTreeChildren([{ label: 'a' }, { label: 'b' }], '')
|
|
863
|
+
* // ['├─ a', '└─ b']
|
|
864
|
+
* ```
|
|
865
|
+
*/
|
|
866
|
+
function renderTreeChildren(nodes, prefix, styler) {
|
|
867
|
+
const lines = [];
|
|
868
|
+
nodes.forEach((node, index) => {
|
|
869
|
+
const last = index === nodes.length - 1;
|
|
870
|
+
lines.push(`${prefix}${paint(styler, last ? TREE_CHARS.corner : TREE_CHARS.branch)}${node.label}`);
|
|
871
|
+
const carry = `${prefix}${paint(styler, last ? TREE_CHARS.gap : TREE_CHARS.guide)}`;
|
|
872
|
+
lines.push(...renderTreeChildren(node.children ?? [], carry, styler));
|
|
873
|
+
});
|
|
874
|
+
return lines;
|
|
875
|
+
}
|
|
876
|
+
/**
|
|
877
|
+
* Stringify ONE captured console argument into a line fragment — the per-argument rule behind
|
|
878
|
+
* {@link formatArgs}: an `Error` → `name: message`, a plain object / array → circular-safe JSON,
|
|
879
|
+
* anything else (string, number, boolean, `null`, `undefined`, symbol, function) → `String(value)`.
|
|
880
|
+
*
|
|
881
|
+
* @remarks
|
|
882
|
+
* - **Total + never throws.** Like a guard (§14), this never throws on adversarial input — a value
|
|
883
|
+
* carrying a circular reference, a `BigInt`, or a throwing `toJSON` is rendered, not raised. The
|
|
884
|
+
* `JSON.stringify` runs with a circular-guard replacer (a seen-set drops a back-reference as
|
|
885
|
+
* `'[Circular]'`); should `JSON.stringify` still throw (e.g. a `BigInt`), the value falls back to
|
|
886
|
+
* `String(value)`. So a `Capture` can never crash the program whose `console.*` it intercepts.
|
|
887
|
+
* - **`Error` first.** An `Error` renders as `name: message` (e.g. `TypeError: bad`) — the useful
|
|
888
|
+
* one-line form, since `JSON.stringify(error)` is `{}` (its fields are non-enumerable).
|
|
889
|
+
* - **Objects → JSON.** A non-null `object` (including an array) is `JSON.stringify`d; a primitive
|
|
890
|
+
* (or `null` / `undefined` / `function` / `symbol`) goes through `String`.
|
|
891
|
+
*
|
|
892
|
+
* @param value - One console argument (any value)
|
|
893
|
+
* @returns The argument's one-line string form
|
|
894
|
+
*
|
|
895
|
+
* @example
|
|
896
|
+
* ```ts
|
|
897
|
+
* stringifyValue('hi') // 'hi'
|
|
898
|
+
* stringifyValue({ a: 1 }) // '{"a":1}'
|
|
899
|
+
* stringifyValue(new TypeError('bad')) // 'TypeError: bad'
|
|
900
|
+
* const cycle: Record<string, unknown> = {}
|
|
901
|
+
* cycle.self = cycle
|
|
902
|
+
* stringifyValue(cycle) // '{"self":"[Circular]"}'
|
|
903
|
+
* ```
|
|
904
|
+
*/
|
|
905
|
+
function stringifyValue(value) {
|
|
906
|
+
if (value instanceof Error) return `${value.name}: ${value.message}`;
|
|
907
|
+
if (value === null || typeof value !== "object") return String(value);
|
|
908
|
+
const seen = /* @__PURE__ */ new WeakSet();
|
|
909
|
+
try {
|
|
910
|
+
return JSON.stringify(value, (_key, nested) => {
|
|
911
|
+
if (nested !== null && typeof nested === "object") {
|
|
912
|
+
if (seen.has(nested)) return "[Circular]";
|
|
913
|
+
seen.add(nested);
|
|
914
|
+
}
|
|
915
|
+
return nested;
|
|
916
|
+
});
|
|
917
|
+
} catch {
|
|
918
|
+
return String(value);
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
/**
|
|
922
|
+
* Stringify a captured `console.*` argument list into ONE line — the text of a {@link
|
|
923
|
+
* import('./types.js').CapturedMessage}. Each argument is rendered by {@link stringifyValue} and
|
|
924
|
+
* the parts are space-joined, mirroring how a console concatenates its arguments.
|
|
925
|
+
*
|
|
926
|
+
* @remarks
|
|
927
|
+
* Total and never throws (it composes {@link stringifyValue}, which is total) — a `Capture` builds
|
|
928
|
+
* every message through this, so intercepting `console.*` can never crash the underlying program.
|
|
929
|
+
* An empty argument list yields `''` (an empty `console.log()` is captured as a blank line).
|
|
930
|
+
*
|
|
931
|
+
* @param args - The arguments a `console.*` method was called with
|
|
932
|
+
* @returns The arguments stringified and space-joined into one line
|
|
933
|
+
*
|
|
934
|
+
* @example
|
|
935
|
+
* ```ts
|
|
936
|
+
* formatArgs(['count', 3, { ok: true }]) // 'count 3 {"ok":true}'
|
|
937
|
+
* formatArgs([]) // ''
|
|
938
|
+
* ```
|
|
939
|
+
*/
|
|
940
|
+
function formatArgs(args) {
|
|
941
|
+
return args.map(stringifyValue).join(" ");
|
|
942
|
+
}
|
|
943
|
+
/**
|
|
944
|
+
* Render a determinate progress bar string — a filled / empty glyph track followed by the percentage
|
|
945
|
+
* and the `(current/total)` count (`█████░░░░░ 50% (5/10)`). Pure: same {@link ProgressBarOptions} →
|
|
946
|
+
* same string. The animation-layer sibling of the C-c `render*` renderers (box / table / tree /
|
|
947
|
+
* separator), shared so a {@link import('./types.js').ProgressInterface} and any direct caller draw
|
|
948
|
+
* the ONE bar — never a second, hand-rolled one (AGENTS §5; scsr shipped three).
|
|
949
|
+
*
|
|
950
|
+
* @remarks
|
|
951
|
+
* - **Fill fraction, clamped.** The filled cell count is `round((current / total) · width)` with
|
|
952
|
+
* `current` clamped to `[0, total]`, so an overrun never over-fills and a negative never under-fills.
|
|
953
|
+
* A `total <= 0` renders a FULL track (there is nothing to fill toward — the work is trivially done).
|
|
954
|
+
* - **Width-aware track.** The filled run is `fill` tiled to the filled cell count and the empty run
|
|
955
|
+
* `empty` tiled to the remainder, each via {@link repeatTo} — so the TRACK is exactly `width` VISIBLE
|
|
956
|
+
* columns even for a multi-cell glyph (its escape codes / extra cells never break the width).
|
|
957
|
+
* - **Styling.** `options.styler` colors the FILLED run only (the empty run + the trailing
|
|
958
|
+
* `percent (count)` label stay plain), through {@link paint}; the layout is identical with or
|
|
959
|
+
* without color, since the track is measured on visible width.
|
|
960
|
+
* - **Label.** The percentage is the rounded `current / total` (e.g. `50%`); the count is the CLAMPED
|
|
961
|
+
* `current` over `total` (`(5/10)`), a single space separating the track, the percent, and the count.
|
|
962
|
+
*
|
|
963
|
+
* @param options - See {@link ProgressBarOptions}
|
|
964
|
+
* @returns The rendered bar line (no trailing newline)
|
|
965
|
+
*
|
|
966
|
+
* @example
|
|
967
|
+
* ```ts
|
|
968
|
+
* renderBar({ current: 5, total: 10, width: 10 }) // '█████░░░░░ 50% (5/10)'
|
|
969
|
+
* renderBar({ current: 10, total: 10, width: 4 }) // '████ 100% (10/10)'
|
|
970
|
+
* ```
|
|
971
|
+
*/
|
|
972
|
+
function renderBar(options) {
|
|
973
|
+
const track = options.width ?? 30;
|
|
974
|
+
const fill = options.fill ?? "█";
|
|
975
|
+
const empty = options.empty ?? "░";
|
|
976
|
+
const current = options.total <= 0 ? 0 : Math.max(0, Math.min(options.total, options.current));
|
|
977
|
+
const fraction = options.total <= 0 ? 1 : current / options.total;
|
|
978
|
+
const filledCells = Math.round(fraction * track);
|
|
979
|
+
return `${`${paint(options.styler, repeatTo(fill, filledCells))}${repeatTo(empty, track - filledCells)}`} ${Math.round(fraction * 100)}% (${current}/${options.total})`;
|
|
980
|
+
}
|
|
981
|
+
//#endregion
|
|
982
|
+
//#region src/core/ANSIRenderer.ts
|
|
983
|
+
/**
|
|
984
|
+
* The cross-environment default {@link RendererInterface} — renders style DATA as ANSI
|
|
985
|
+
* SGR escape codes, exactly as `Scheduler` is the `setTimeout` default for its seam. It
|
|
986
|
+
* is the single styling output the whole console / terminal system uses in a terminal;
|
|
987
|
+
* the browser `%c` / CSS renderer (the C-f branch) implements the SAME contract over
|
|
988
|
+
* the SAME {@link Style}, so retargeting changes the renderer, never the style model.
|
|
989
|
+
*
|
|
990
|
+
* @remarks
|
|
991
|
+
* - **Style is DATA in, SGR string out.** It reads the style's `foreground` /
|
|
992
|
+
* `background` / `attributes` and emits one `ESC[…m` sequence whose parameters are the
|
|
993
|
+
* mapped SGR numbers (foreground 30–37 / 90–97, background 40–47 / 100–107, attributes
|
|
994
|
+
* 1 / 2 / 3 / 4 / 7 / 9), followed by `text`, terminated by the reset `ESC[0m`.
|
|
995
|
+
* - **Multiple attributes compose** — their codes join with `;` in a single sequence
|
|
996
|
+
* (`ESC[1;4;31m` for bold + underline + red), so one open and one reset wrap the run.
|
|
997
|
+
* - **`default` and unset colors emit no code** — a `default` (or absent) `foreground` /
|
|
998
|
+
* `background` leaves the terminal's own ink.
|
|
999
|
+
* - **The empty style and the empty string pass through** — when there is nothing to
|
|
1000
|
+
* apply (no colors, no attributes) or `text` is `''`, `text` is returned VERBATIM with
|
|
1001
|
+
* no escape codes, so an unstyled render never injects a stray reset.
|
|
1002
|
+
* - **Stateless and event-free** — no fields, no events; safe to share one instance.
|
|
1003
|
+
*/
|
|
1004
|
+
var ANSIRenderer = class {
|
|
1005
|
+
/**
|
|
1006
|
+
* Wrap `text` in the SGR codes for `style`. Returns `text` unchanged when the style
|
|
1007
|
+
* is empty or `text` is `''`.
|
|
1008
|
+
*/
|
|
1009
|
+
render(style, text) {
|
|
1010
|
+
if (text === "") return text;
|
|
1011
|
+
const codes = this.#codes(style);
|
|
1012
|
+
if (codes.length === 0) return text;
|
|
1013
|
+
return `${CSI}${codes.join(";")}m${text}${RESET}`;
|
|
1014
|
+
}
|
|
1015
|
+
#codes(style) {
|
|
1016
|
+
const codes = [];
|
|
1017
|
+
for (const attribute of style.attributes) codes.push(ATTRIBUTE_CODES[attribute]);
|
|
1018
|
+
if (style.foreground !== void 0 && style.foreground !== "default") codes.push(FOREGROUND_CODES[style.foreground]);
|
|
1019
|
+
if (style.background !== void 0 && style.background !== "default") codes.push(BACKGROUND_CODES[style.background]);
|
|
1020
|
+
return codes;
|
|
1021
|
+
}
|
|
1022
|
+
};
|
|
1023
|
+
//#endregion
|
|
1024
|
+
//#region src/core/Styler.ts
|
|
1025
|
+
/**
|
|
1026
|
+
* The fluent, composable styler — the consumer-facing API over the style engine. It
|
|
1027
|
+
* builds a {@link Style} (style as DATA) and renders it through an injected
|
|
1028
|
+
* {@link RendererInterface} (the ANSI default, or a browser `%c` renderer at C-f). Each
|
|
1029
|
+
* color / attribute accessor is immutable copy-on-write: it returns a NEW styler's
|
|
1030
|
+
* surface with the token added, so `styler.red.bold('hi')` composes without mutating,
|
|
1031
|
+
* and a base styler is freely reusable.
|
|
1032
|
+
*
|
|
1033
|
+
* @remarks
|
|
1034
|
+
* - **Callable surface.** A `Styler` is not itself callable; its {@link surface} getter
|
|
1035
|
+
* returns the {@link StylerInterface} — a render FUNCTION carrying the chainable
|
|
1036
|
+
* accessors. The accessors are installed as LAZY getters (`Object.defineProperties`),
|
|
1037
|
+
* so a chain materializes only the stylers it actually walks — never the full tree —
|
|
1038
|
+
* and the recursion terminates. The factory returns that surface; this class is the
|
|
1039
|
+
* engine behind it.
|
|
1040
|
+
* - **Immutable.** `#foreground` and `#attribute` return a fresh `Styler` (the style is
|
|
1041
|
+
* rebuilt, never mutated). A later color of the same channel WINS (last write); a
|
|
1042
|
+
* repeated attribute is idempotent (de-duplicated, order preserved).
|
|
1043
|
+
* - **`enabled` switch.** When `false`, the render function returns text VERBATIM — no
|
|
1044
|
+
* renderer call, no escape codes (for a non-TTY / `NO_COLOR` / piped output).
|
|
1045
|
+
* - **Event-free** — a pure styling primitive (AGENTS §13), like `Scheduler`.
|
|
1046
|
+
*/
|
|
1047
|
+
var Styler = class Styler {
|
|
1048
|
+
#renderer;
|
|
1049
|
+
#enabled;
|
|
1050
|
+
#style;
|
|
1051
|
+
constructor(renderer, enabled, style) {
|
|
1052
|
+
this.#renderer = renderer;
|
|
1053
|
+
this.#enabled = enabled;
|
|
1054
|
+
this.#style = style;
|
|
1055
|
+
}
|
|
1056
|
+
/** The accumulated style DATA — the empty style on a base styler. */
|
|
1057
|
+
get style() {
|
|
1058
|
+
return this.#style;
|
|
1059
|
+
}
|
|
1060
|
+
/** Whether styling is applied; when `false`, the surface returns text unchanged. */
|
|
1061
|
+
get enabled() {
|
|
1062
|
+
return this.#enabled;
|
|
1063
|
+
}
|
|
1064
|
+
/**
|
|
1065
|
+
* The fluent {@link StylerInterface} value — a render function (`text => string`) with
|
|
1066
|
+
* `style`, `enabled`, and every {@link Color} / {@link Attribute} as a LAZY accessor
|
|
1067
|
+
* (each computes the next styler's surface only when read). This is what consumers
|
|
1068
|
+
* hold and call.
|
|
1069
|
+
*
|
|
1070
|
+
* @remarks
|
|
1071
|
+
* The accessors are defined as getters (not eagerly-merged values), so accessing one
|
|
1072
|
+
* builds exactly one child styler — the tree is never fully materialized and the
|
|
1073
|
+
* construction terminates. The assembled function is then narrowed to
|
|
1074
|
+
* {@link StylerInterface} through {@link #isSurface} (a real structural check), so no
|
|
1075
|
+
* type assertion is used (AGENTS §1 / §14 — narrow, never assert).
|
|
1076
|
+
*/
|
|
1077
|
+
get surface() {
|
|
1078
|
+
const render = (text) => this.#enabled ? this.#renderer.render(this.#style, text) : text;
|
|
1079
|
+
const descriptors = {
|
|
1080
|
+
style: {
|
|
1081
|
+
value: this.#style,
|
|
1082
|
+
enumerable: true
|
|
1083
|
+
},
|
|
1084
|
+
enabled: {
|
|
1085
|
+
value: this.#enabled,
|
|
1086
|
+
enumerable: true
|
|
1087
|
+
}
|
|
1088
|
+
};
|
|
1089
|
+
for (const color of COLORS) descriptors[color] = {
|
|
1090
|
+
get: () => this.#foreground(color).surface,
|
|
1091
|
+
enumerable: true
|
|
1092
|
+
};
|
|
1093
|
+
for (const attribute of ATTRIBUTES) descriptors[attribute] = {
|
|
1094
|
+
get: () => this.#attribute(attribute).surface,
|
|
1095
|
+
enumerable: true
|
|
1096
|
+
};
|
|
1097
|
+
const surface = Object.defineProperties(render, descriptors);
|
|
1098
|
+
if (this.#isSurface(surface)) return surface;
|
|
1099
|
+
throw new ConsoleError("INVARIANT", "console: styler surface construction is incomplete");
|
|
1100
|
+
}
|
|
1101
|
+
#isSurface(value) {
|
|
1102
|
+
return typeof value === "function" && "style" in value && "enabled" in value && "red" in value && "bold" in value;
|
|
1103
|
+
}
|
|
1104
|
+
#foreground(color) {
|
|
1105
|
+
return new Styler(this.#renderer, this.#enabled, Object.freeze({
|
|
1106
|
+
...this.#style,
|
|
1107
|
+
foreground: color
|
|
1108
|
+
}));
|
|
1109
|
+
}
|
|
1110
|
+
#attribute(attribute) {
|
|
1111
|
+
if (this.#style.attributes.includes(attribute)) return this;
|
|
1112
|
+
return new Styler(this.#renderer, this.#enabled, Object.freeze({
|
|
1113
|
+
...this.#style,
|
|
1114
|
+
attributes: Object.freeze([...this.#style.attributes, attribute])
|
|
1115
|
+
}));
|
|
1116
|
+
}
|
|
1117
|
+
};
|
|
1118
|
+
//#endregion
|
|
1119
|
+
//#region src/core/Capture.ts
|
|
1120
|
+
/**
|
|
1121
|
+
* An observable console interceptor (AGENTS §13) — it takes control of the global `console.*` on
|
|
1122
|
+
* the READ side. While `active`, every configured `console.x` call is captured as a frozen
|
|
1123
|
+
* {@link CapturedMessage}, buffered (total + by level, bounded), emitted on `capture`, and — per
|
|
1124
|
+
* options — mirrored to the real console and/or forwarded to a {@link SinkInterface}.
|
|
1125
|
+
*
|
|
1126
|
+
* @remarks
|
|
1127
|
+
* - **Snapshot-at-start (the no-capture-loop principle).** `start()` snapshots the CURRENT
|
|
1128
|
+
* `console[level]` for each configured {@link CaptureLevel}, then installs the wrappers. The
|
|
1129
|
+
* mirror writes through that snapshot — so our OWN console sink output (the Logger / Reporter,
|
|
1130
|
+
* which snapshot the real `console` at creation) is never recaptured: `Capture` catches
|
|
1131
|
+
* THIRD-PARTY `console.*`, not our writes. Create your loggers BEFORE installing a capture.
|
|
1132
|
+
* - **Idempotent + PROCESS-GLOBAL + NON-REENTRANT.** `start()` while already `active` is a no-op
|
|
1133
|
+
* (never double-patches); `stop()` while inactive is a no-op. It patches the ONE global
|
|
1134
|
+
* `console`, so at most ONE capture may be active at a time — running two concurrently
|
|
1135
|
+
* interleaves their buffers and clobbers each other's restore.
|
|
1136
|
+
* - **Bounded buffers.** `messages()` / `messages(level)` — the total buffer and each by-level
|
|
1137
|
+
* bucket are each capped at `limit`
|
|
1138
|
+
* (oldest dropped first), never unbounded — the same retention precedent as {@link Logger}.
|
|
1139
|
+
* - **Lifecycle (§10).** `start` / `stop` toggle interception (emitting `start` / `stop`);
|
|
1140
|
+
* `destroy()` stops (restoring `console`) then destroys the emitter.
|
|
1141
|
+
*
|
|
1142
|
+
* @example
|
|
1143
|
+
* ```ts
|
|
1144
|
+
* const capture = new Capture({ levels: ['warn', 'error'], mirror: true })
|
|
1145
|
+
* capture.start()
|
|
1146
|
+
* console.warn('third-party noise') // captured AND mirrored to the real console
|
|
1147
|
+
* capture.messages('warn') // [{ level: 'warn', text: 'third-party noise', time: … }]
|
|
1148
|
+
* capture.stop() // console.warn restored
|
|
1149
|
+
* ```
|
|
1150
|
+
*/
|
|
1151
|
+
var Capture = class {
|
|
1152
|
+
#emitter;
|
|
1153
|
+
#levels;
|
|
1154
|
+
#mirror;
|
|
1155
|
+
#sink;
|
|
1156
|
+
#limit;
|
|
1157
|
+
#messages = [];
|
|
1158
|
+
#buckets = /* @__PURE__ */ new Map();
|
|
1159
|
+
#originals = /* @__PURE__ */ new Map();
|
|
1160
|
+
#active = false;
|
|
1161
|
+
constructor(options) {
|
|
1162
|
+
this.#emitter = new Emitter({
|
|
1163
|
+
on: options?.on,
|
|
1164
|
+
error: options?.error
|
|
1165
|
+
});
|
|
1166
|
+
this.#levels = options?.levels ?? DEFAULT_CAPTURE_LEVELS;
|
|
1167
|
+
this.#mirror = options?.mirror ?? false;
|
|
1168
|
+
this.#sink = options?.sink;
|
|
1169
|
+
this.#limit = options?.limit ?? 1e3;
|
|
1170
|
+
for (const level of this.#levels) this.#buckets.set(level, []);
|
|
1171
|
+
}
|
|
1172
|
+
get emitter() {
|
|
1173
|
+
return this.#emitter;
|
|
1174
|
+
}
|
|
1175
|
+
get active() {
|
|
1176
|
+
return this.#active;
|
|
1177
|
+
}
|
|
1178
|
+
start() {
|
|
1179
|
+
if (this.#active) return;
|
|
1180
|
+
this.#active = true;
|
|
1181
|
+
const target = console;
|
|
1182
|
+
for (const level of this.#levels) {
|
|
1183
|
+
const original = target[level];
|
|
1184
|
+
this.#originals.set(level, original);
|
|
1185
|
+
const mirror = original.bind(console);
|
|
1186
|
+
target[level] = (...args) => this.#intercept(level, args, mirror);
|
|
1187
|
+
}
|
|
1188
|
+
this.#emitter.emit("start");
|
|
1189
|
+
}
|
|
1190
|
+
stop() {
|
|
1191
|
+
if (!this.#active) return;
|
|
1192
|
+
this.#active = false;
|
|
1193
|
+
const target = console;
|
|
1194
|
+
for (const [level, original] of this.#originals) target[level] = original;
|
|
1195
|
+
this.#originals.clear();
|
|
1196
|
+
this.#emitter.emit("stop");
|
|
1197
|
+
}
|
|
1198
|
+
messages(level) {
|
|
1199
|
+
if (level === void 0) return [...this.#messages];
|
|
1200
|
+
return [...this.#buckets.get(level) ?? []];
|
|
1201
|
+
}
|
|
1202
|
+
clear() {
|
|
1203
|
+
this.#messages.length = 0;
|
|
1204
|
+
for (const bucket of this.#buckets.values()) bucket.length = 0;
|
|
1205
|
+
}
|
|
1206
|
+
destroy() {
|
|
1207
|
+
this.stop();
|
|
1208
|
+
this.#emitter.destroy();
|
|
1209
|
+
}
|
|
1210
|
+
#intercept(level, args, mirror) {
|
|
1211
|
+
const message = this.#capture(level, args);
|
|
1212
|
+
this.#retain(message);
|
|
1213
|
+
this.#emitter.emit("capture", message);
|
|
1214
|
+
if (this.#mirror) mirror(...args);
|
|
1215
|
+
if (this.#sink !== void 0) try {
|
|
1216
|
+
this.#sink.write(message.text, CAPTURE_LEVEL_MAP[level]);
|
|
1217
|
+
} catch {}
|
|
1218
|
+
}
|
|
1219
|
+
#capture(level, args) {
|
|
1220
|
+
return Object.freeze({
|
|
1221
|
+
level,
|
|
1222
|
+
text: formatArgs(args),
|
|
1223
|
+
time: Date.now()
|
|
1224
|
+
});
|
|
1225
|
+
}
|
|
1226
|
+
#retain(message) {
|
|
1227
|
+
this.#push(this.#messages, message);
|
|
1228
|
+
const bucket = this.#buckets.get(message.level);
|
|
1229
|
+
if (bucket !== void 0) this.#push(bucket, message);
|
|
1230
|
+
}
|
|
1231
|
+
#push(buffer, message) {
|
|
1232
|
+
buffer.push(message);
|
|
1233
|
+
if (buffer.length > this.#limit) buffer.shift();
|
|
1234
|
+
}
|
|
1235
|
+
};
|
|
1236
|
+
//#endregion
|
|
1237
|
+
//#region src/core/LoggerManager.ts
|
|
1238
|
+
/**
|
|
1239
|
+
* An event-free registry of named {@link Logger}s plus a convenience fan-out — the §9
|
|
1240
|
+
* manager over the logging layer (a registry, never observable itself; each {@link Logger}
|
|
1241
|
+
* owns its own `emitter`).
|
|
1242
|
+
*
|
|
1243
|
+
* @remarks
|
|
1244
|
+
* - **Registry (§9).** Loggers live in an insertion-ordered `Map` keyed by `name`.
|
|
1245
|
+
* `register(name, options?)` mints a {@link Logger} named `name` — the manager's default
|
|
1246
|
+
* `level` / `sink` / `styler` / `limit` / `silent` flow in unless `options` OVERRIDES them
|
|
1247
|
+
* (`name` is always the registry key, so any `options.name` is ignored) — stores it (a
|
|
1248
|
+
* re-`register` of the same name OVERWRITES, last write wins), and returns it. `count` is
|
|
1249
|
+
* the map size, `logger(name)` looks one up, `loggers()` lists them in insertion order.
|
|
1250
|
+
* - **Removal (§9.2).** `remove()` clears ALL, `remove(name)` drops ONE (`true` if present),
|
|
1251
|
+
* `remove(names)` drops a batch (`true` if any was removed). `clear()` empties the registry.
|
|
1252
|
+
* (Removal does NOT `destroy` the returned loggers — a caller still holding one keeps using
|
|
1253
|
+
* it; the manager simply stops tracking it.)
|
|
1254
|
+
* - **Fan-out.** `debug` / `info` / `warn` / `error(message, data?)` forward the one call to
|
|
1255
|
+
* EVERY registered logger; each gates / emits / writes per its own `level` and `sink`. A
|
|
1256
|
+
* fan-out over an empty registry is a no-op.
|
|
1257
|
+
* - **Event-free.** No emitter, no events — the manager is a pure registry; observability is
|
|
1258
|
+
* per-{@link Logger}.
|
|
1259
|
+
*
|
|
1260
|
+
* @example
|
|
1261
|
+
* ```ts
|
|
1262
|
+
* const manager = new LoggerManager({ level: 'warn' })
|
|
1263
|
+
* manager.register('http') // inherits the `warn` default
|
|
1264
|
+
* manager.register('db', { level: 'debug' }) // overrides to `debug`
|
|
1265
|
+
* manager.warn('slow', { ms: 900 }) // fans out to both loggers
|
|
1266
|
+
* manager.count // 2
|
|
1267
|
+
* ```
|
|
1268
|
+
*/
|
|
1269
|
+
var LoggerManager = class {
|
|
1270
|
+
#loggers = /* @__PURE__ */ new Map();
|
|
1271
|
+
#level;
|
|
1272
|
+
#sink;
|
|
1273
|
+
#styler;
|
|
1274
|
+
#limit;
|
|
1275
|
+
#silent;
|
|
1276
|
+
constructor(options) {
|
|
1277
|
+
this.#level = options?.level;
|
|
1278
|
+
this.#sink = options?.sink;
|
|
1279
|
+
this.#styler = options?.styler;
|
|
1280
|
+
this.#limit = options?.limit;
|
|
1281
|
+
this.#silent = options?.silent;
|
|
1282
|
+
}
|
|
1283
|
+
get count() {
|
|
1284
|
+
return this.#loggers.size;
|
|
1285
|
+
}
|
|
1286
|
+
register(name, options) {
|
|
1287
|
+
const logger = new Logger({
|
|
1288
|
+
level: this.#level,
|
|
1289
|
+
sink: this.#sink,
|
|
1290
|
+
styler: this.#styler,
|
|
1291
|
+
limit: this.#limit,
|
|
1292
|
+
silent: this.#silent,
|
|
1293
|
+
...options,
|
|
1294
|
+
name
|
|
1295
|
+
});
|
|
1296
|
+
this.#loggers.set(name, logger);
|
|
1297
|
+
return logger;
|
|
1298
|
+
}
|
|
1299
|
+
logger(name) {
|
|
1300
|
+
return this.#loggers.get(name);
|
|
1301
|
+
}
|
|
1302
|
+
loggers() {
|
|
1303
|
+
return [...this.#loggers.values()];
|
|
1304
|
+
}
|
|
1305
|
+
debug(message, data) {
|
|
1306
|
+
for (const logger of this.#loggers.values()) logger.debug(message, data);
|
|
1307
|
+
}
|
|
1308
|
+
info(message, data) {
|
|
1309
|
+
for (const logger of this.#loggers.values()) logger.info(message, data);
|
|
1310
|
+
}
|
|
1311
|
+
warn(message, data) {
|
|
1312
|
+
for (const logger of this.#loggers.values()) logger.warn(message, data);
|
|
1313
|
+
}
|
|
1314
|
+
error(message, data) {
|
|
1315
|
+
for (const logger of this.#loggers.values()) logger.error(message, data);
|
|
1316
|
+
}
|
|
1317
|
+
remove(names) {
|
|
1318
|
+
if (names === void 0) {
|
|
1319
|
+
this.#loggers.clear();
|
|
1320
|
+
return;
|
|
1321
|
+
}
|
|
1322
|
+
if (isArray(names)) {
|
|
1323
|
+
let removed = false;
|
|
1324
|
+
for (const name of names) if (this.#loggers.delete(name)) removed = true;
|
|
1325
|
+
return removed;
|
|
1326
|
+
}
|
|
1327
|
+
return this.#loggers.delete(names);
|
|
1328
|
+
}
|
|
1329
|
+
clear() {
|
|
1330
|
+
this.#loggers.clear();
|
|
1331
|
+
}
|
|
1332
|
+
};
|
|
1333
|
+
//#endregion
|
|
1334
|
+
//#region src/core/Progress.ts
|
|
1335
|
+
/**
|
|
1336
|
+
* An update-driven, observable progress bar (AGENTS §13) — {@link update} recomputes the bar via
|
|
1337
|
+
* {@link renderBar}, writes `\r` + bar to its {@link SinkInterface}, and emits the `{ current, total }`
|
|
1338
|
+
* on `update`. The leading `\r` is what an overwrite-capable sink (the C-g TTY sink) redraws on; a
|
|
1339
|
+
* plain sink (C-f) degrades to a fresh, non-overwriting line — the line-OVERWRITE is the SINK's job.
|
|
1340
|
+
* UNIVERSAL — the one {@link StylerInterface} + the one {@link SinkInterface}, no `node:*`, no
|
|
1341
|
+
* `process.stdout`. NO self-timer (unlike {@link import('./Spinner.js').Spinner}) — the caller drives it.
|
|
1342
|
+
*
|
|
1343
|
+
* @remarks
|
|
1344
|
+
* - **Update-driven.** Each {@link update} clamps `current` to `[0, total]`, renders the bar (filled
|
|
1345
|
+
* to `current / total`, with the trailing `percent (current/total)` + message) via {@link renderBar},
|
|
1346
|
+
* emits `update`, and writes `'\r' + bar`. Progress advances only when the caller reports it.
|
|
1347
|
+
* - **Outcome lines.** {@link complete} renders a FULL bar (`current = total`) + message, terminated by
|
|
1348
|
+
* a newline, emits a final `update` then `complete`, and marks `completed`. {@link failure} renders the
|
|
1349
|
+
* bar at its CURRENT fill + message + newline and routes to the sink's error stream (no `complete` —
|
|
1350
|
+
* the work did not finish). Both are terminal: a later {@link update} is ignored once `active` is false.
|
|
1351
|
+
* - **Bounded.** `current` is always clamped to `[0, total]`; {@link completed} reports whether
|
|
1352
|
+
* {@link complete} has run; {@link active} is `true` until a {@link complete} / {@link failure}.
|
|
1353
|
+
* - **Lifecycle (§10).** {@link destroy} destroys the emitter (there is no timer to clear).
|
|
1354
|
+
*
|
|
1355
|
+
* @example
|
|
1356
|
+
* ```ts
|
|
1357
|
+
* const progress = new Progress({ total: 100, message: 'downloading' })
|
|
1358
|
+
* progress.update(40) // ████████████░░░░░░░░░░░░░░░░░░ 40% (40/100) downloading
|
|
1359
|
+
* progress.update(80, 'almost there')
|
|
1360
|
+
* progress.complete('done') // a full bar, committed with a newline
|
|
1361
|
+
* ```
|
|
1362
|
+
*/
|
|
1363
|
+
var Progress = class {
|
|
1364
|
+
#emitter;
|
|
1365
|
+
#total;
|
|
1366
|
+
#width;
|
|
1367
|
+
#sink;
|
|
1368
|
+
#styler;
|
|
1369
|
+
#message;
|
|
1370
|
+
#current = 0;
|
|
1371
|
+
#active = true;
|
|
1372
|
+
#completed = false;
|
|
1373
|
+
constructor(options) {
|
|
1374
|
+
this.#emitter = new Emitter({
|
|
1375
|
+
on: options.on,
|
|
1376
|
+
error: options.error
|
|
1377
|
+
});
|
|
1378
|
+
this.#total = options.total;
|
|
1379
|
+
this.#width = options.width ?? 30;
|
|
1380
|
+
this.#sink = options.sink ?? createConsoleSink();
|
|
1381
|
+
this.#styler = options.styler ?? createStyler();
|
|
1382
|
+
this.#message = options.message ?? "";
|
|
1383
|
+
}
|
|
1384
|
+
get emitter() {
|
|
1385
|
+
return this.#emitter;
|
|
1386
|
+
}
|
|
1387
|
+
get active() {
|
|
1388
|
+
return this.#active;
|
|
1389
|
+
}
|
|
1390
|
+
get completed() {
|
|
1391
|
+
return this.#completed;
|
|
1392
|
+
}
|
|
1393
|
+
get current() {
|
|
1394
|
+
return this.#current;
|
|
1395
|
+
}
|
|
1396
|
+
get total() {
|
|
1397
|
+
return this.#total;
|
|
1398
|
+
}
|
|
1399
|
+
update(current, message) {
|
|
1400
|
+
if (!this.#active) return;
|
|
1401
|
+
this.#advance(current, message);
|
|
1402
|
+
this.#paint(false);
|
|
1403
|
+
}
|
|
1404
|
+
complete(message) {
|
|
1405
|
+
if (!this.#active) return;
|
|
1406
|
+
this.#advance(this.#total, message);
|
|
1407
|
+
this.#active = false;
|
|
1408
|
+
this.#completed = true;
|
|
1409
|
+
this.#paint(true);
|
|
1410
|
+
this.#emitter.emit("complete");
|
|
1411
|
+
}
|
|
1412
|
+
failure(message) {
|
|
1413
|
+
if (!this.#active) return;
|
|
1414
|
+
this.#advance(this.#current, message);
|
|
1415
|
+
this.#active = false;
|
|
1416
|
+
this.#paint(true, "error");
|
|
1417
|
+
}
|
|
1418
|
+
destroy() {
|
|
1419
|
+
this.#emitter.destroy();
|
|
1420
|
+
}
|
|
1421
|
+
#advance(current, message) {
|
|
1422
|
+
this.#current = Math.max(0, Math.min(this.#total, current));
|
|
1423
|
+
if (message !== void 0) this.#message = message;
|
|
1424
|
+
this.#emitter.emit("update", {
|
|
1425
|
+
current: this.#current,
|
|
1426
|
+
total: this.#total
|
|
1427
|
+
});
|
|
1428
|
+
}
|
|
1429
|
+
#paint(final, level) {
|
|
1430
|
+
const bar = renderBar({
|
|
1431
|
+
current: this.#current,
|
|
1432
|
+
total: this.#total,
|
|
1433
|
+
width: this.#width,
|
|
1434
|
+
styler: this.#styler.cyan
|
|
1435
|
+
});
|
|
1436
|
+
const line = this.#message === "" ? bar : `${bar} ${this.#message}`;
|
|
1437
|
+
this.#sink.write(`\r${line}${final ? "\n" : ""}`, level);
|
|
1438
|
+
}
|
|
1439
|
+
};
|
|
1440
|
+
//#endregion
|
|
1441
|
+
//#region src/core/Reporter.ts
|
|
1442
|
+
/**
|
|
1443
|
+
* A lean, event-free narrative reporter (AGENTS §13) — the composable verb set for human /
|
|
1444
|
+
* build-run output. Each verb FORMATS its line through the shared {@link StylerInterface} and
|
|
1445
|
+
* the pure layout renderers ({@link renderSeparator} / {@link renderBox} / {@link renderTable}
|
|
1446
|
+
* / {@link renderTree}) and WRITES it to a {@link SinkInterface} — the SAME styler + sink
|
|
1447
|
+
* substrate the logger uses, never a second colorizer.
|
|
1448
|
+
*
|
|
1449
|
+
* @remarks
|
|
1450
|
+
* - **A SMALL set, not a grab-bag.** `section` / `step` / `timing` / `status` / `table` /
|
|
1451
|
+
* `tree` / `box` / `line` / `blank`. No spinner / bar (the animation chunk), no buffering /
|
|
1452
|
+
* capture (the capture chunk), no level retention (the logger). Just format + write.
|
|
1453
|
+
* - **`status` is a narrative OUTCOME, not a log level.** Its {@link StatusLevel} (`success` /
|
|
1454
|
+
* `error` / `warn` / `info`) is distinct from {@link import('./types.js').LogLevel}: an icon
|
|
1455
|
+
* ({@link STATUS_ICONS}) + a color ({@link STATUS_COLORS}), with `error` routed to the sink's
|
|
1456
|
+
* error stream (the `level` hint forwarded to {@link SinkInterface.write}) — there is no
|
|
1457
|
+
* gating and no severity ordering.
|
|
1458
|
+
* - **Width-aware.** `section` (and a `box` with no explicit `width`) lay out to the reporter's
|
|
1459
|
+
* `#width`; the renderers measure on VISIBLE width (ANSI-aware), so styled content aligns.
|
|
1460
|
+
* - **Event-free (§13).** No `#emitter` — a pure formatting front-end with no observable
|
|
1461
|
+
* lifecycle (like the renderers and `Scheduler`). It is reusable and holds no per-call state.
|
|
1462
|
+
*
|
|
1463
|
+
* @example
|
|
1464
|
+
* ```ts
|
|
1465
|
+
* const reporter = new Reporter()
|
|
1466
|
+
* reporter.section('Build')
|
|
1467
|
+
* reporter.step('compiling', { index: 1, total: 3 }) // [1/3] compiling
|
|
1468
|
+
* reporter.timing('bundle', 1234) // bundle … 1.23s
|
|
1469
|
+
* reporter.status('success', 'done') // ✔ done
|
|
1470
|
+
* ```
|
|
1471
|
+
*/
|
|
1472
|
+
var Reporter = class {
|
|
1473
|
+
#sink;
|
|
1474
|
+
#styler;
|
|
1475
|
+
#width;
|
|
1476
|
+
constructor(options) {
|
|
1477
|
+
this.#sink = options?.sink ?? createConsoleSink();
|
|
1478
|
+
this.#styler = options?.styler ?? createStyler();
|
|
1479
|
+
this.#width = options?.width ?? 80;
|
|
1480
|
+
}
|
|
1481
|
+
section(title) {
|
|
1482
|
+
this.#sink.write(renderSeparator({
|
|
1483
|
+
title,
|
|
1484
|
+
width: this.#width,
|
|
1485
|
+
styler: this.#styler.dim
|
|
1486
|
+
}));
|
|
1487
|
+
}
|
|
1488
|
+
step(message, position) {
|
|
1489
|
+
const prefix = position === void 0 ? "" : `${this.#styler.cyan(`[${position.index}/${position.total}]`)} `;
|
|
1490
|
+
this.#sink.write(`${prefix}${message}`);
|
|
1491
|
+
}
|
|
1492
|
+
timing(label, ms) {
|
|
1493
|
+
this.#sink.write(`${label} ${this.#styler.dim(`… ${formatDuration(ms)}`)}`);
|
|
1494
|
+
}
|
|
1495
|
+
status(level, message) {
|
|
1496
|
+
const color = this.#styler[STATUS_COLORS[level]];
|
|
1497
|
+
const line = `${color(STATUS_ICONS[level])} ${color(message)}`;
|
|
1498
|
+
this.#sink.write(line, level === "error" ? "error" : void 0);
|
|
1499
|
+
}
|
|
1500
|
+
table(options) {
|
|
1501
|
+
this.#sink.write(renderTable({
|
|
1502
|
+
styler: this.#styler.dim,
|
|
1503
|
+
...options
|
|
1504
|
+
}));
|
|
1505
|
+
}
|
|
1506
|
+
tree(options) {
|
|
1507
|
+
this.#sink.write(renderTree({
|
|
1508
|
+
styler: this.#styler.dim,
|
|
1509
|
+
...options
|
|
1510
|
+
}));
|
|
1511
|
+
}
|
|
1512
|
+
box(options) {
|
|
1513
|
+
this.#sink.write(renderBox({
|
|
1514
|
+
width: this.#width,
|
|
1515
|
+
styler: this.#styler.dim,
|
|
1516
|
+
...options
|
|
1517
|
+
}));
|
|
1518
|
+
}
|
|
1519
|
+
line(text) {
|
|
1520
|
+
this.#sink.write(text);
|
|
1521
|
+
}
|
|
1522
|
+
blank(count = 1) {
|
|
1523
|
+
for (let index = 0; index < count; index += 1) this.#sink.write("");
|
|
1524
|
+
}
|
|
1525
|
+
};
|
|
1526
|
+
//#endregion
|
|
1527
|
+
//#region src/core/Spinner.ts
|
|
1528
|
+
/**
|
|
1529
|
+
* A self-driving, observable activity spinner (AGENTS §13) — a glyph cycle that advances on a
|
|
1530
|
+
* periodic timer, writing each `\r` + frame line to its {@link SinkInterface} and emitting it on
|
|
1531
|
+
* `frame`. The leading `\r` is what an overwrite-capable sink (the C-g TTY sink) redraws on; a plain
|
|
1532
|
+
* sink (C-f) degrades to a fresh, non-overwriting line — the line-OVERWRITE is the SINK's job, never
|
|
1533
|
+
* the spinner's. UNIVERSAL — `setInterval` + the one {@link StylerInterface} + the one
|
|
1534
|
+
* {@link SinkInterface}, no `node:*`, no `process.stdout`.
|
|
1535
|
+
*
|
|
1536
|
+
* @remarks
|
|
1537
|
+
* - **Self-driving but deterministically testable.** `start()` arms a `setInterval` that calls
|
|
1538
|
+
* {@link tick} each `interval`; each {@link tick} builds the styled `glyph + message` line for the
|
|
1539
|
+
* current frame, emits it on `frame`, writes `'\r' + line` to the sink, then advances the frame
|
|
1540
|
+
* index (wrapping). A test drives frames by calling {@link tick} directly (NO real clock) and proves
|
|
1541
|
+
* the timer arms / clears with fake timers.
|
|
1542
|
+
* - **Leak-free timer.** The interval is ALWAYS cleared on {@link success} / {@link failure} /
|
|
1543
|
+
* {@link stop} / {@link destroy} — `#handle` is the single source of `active`, set on arm and unset
|
|
1544
|
+
* on clear, so a spinner never leaks a running interval.
|
|
1545
|
+
* - **Idempotent `start`.** A {@link start} while already `active` is a no-op (it never arms a second
|
|
1546
|
+
* timer).
|
|
1547
|
+
* - **Outcome lines.** {@link success} / {@link failure} clear the timer then write + emit a FINAL line —
|
|
1548
|
+
* the {@link STATUS_ICONS} `✔` / `✖` (colored via {@link STATUS_COLORS}) + the message — terminated
|
|
1549
|
+
* by a newline (the activity is over; the line is committed, not overwritten). {@link failure} routes to
|
|
1550
|
+
* the sink's error stream.
|
|
1551
|
+
* - **Lifecycle (§10).** {@link stop} clears the timer and LEAVES the current line; {@link destroy}
|
|
1552
|
+
* stops then destroys the emitter. {@link update} swaps the message and re-renders immediately when
|
|
1553
|
+
* `active`.
|
|
1554
|
+
*
|
|
1555
|
+
* @example
|
|
1556
|
+
* ```ts
|
|
1557
|
+
* const spinner = new Spinner({ message: 'building' })
|
|
1558
|
+
* spinner.start() // arms the timer, paints the first frame to the sink
|
|
1559
|
+
* spinner.update('bundling') // message changes, re-rendered at once
|
|
1560
|
+
* spinner.success('built in 1.2s') // ✔ built in 1.2s — timer cleared, line committed
|
|
1561
|
+
* ```
|
|
1562
|
+
*/
|
|
1563
|
+
var Spinner = class {
|
|
1564
|
+
#emitter;
|
|
1565
|
+
#frames;
|
|
1566
|
+
#interval;
|
|
1567
|
+
#sink;
|
|
1568
|
+
#styler;
|
|
1569
|
+
#message;
|
|
1570
|
+
#handle;
|
|
1571
|
+
#index = 0;
|
|
1572
|
+
constructor(options) {
|
|
1573
|
+
this.#emitter = new Emitter({
|
|
1574
|
+
on: options?.on,
|
|
1575
|
+
error: options?.error
|
|
1576
|
+
});
|
|
1577
|
+
const frames = options?.frames ?? SPINNER_FRAMES;
|
|
1578
|
+
this.#frames = frames.length === 0 ? SPINNER_FRAMES : frames;
|
|
1579
|
+
this.#interval = options?.interval ?? 80;
|
|
1580
|
+
this.#sink = options?.sink ?? createConsoleSink();
|
|
1581
|
+
this.#styler = options?.styler ?? createStyler();
|
|
1582
|
+
this.#message = options?.message ?? "";
|
|
1583
|
+
}
|
|
1584
|
+
get emitter() {
|
|
1585
|
+
return this.#emitter;
|
|
1586
|
+
}
|
|
1587
|
+
get active() {
|
|
1588
|
+
return this.#handle !== void 0;
|
|
1589
|
+
}
|
|
1590
|
+
get message() {
|
|
1591
|
+
return this.#message;
|
|
1592
|
+
}
|
|
1593
|
+
start() {
|
|
1594
|
+
if (this.#handle !== void 0) return;
|
|
1595
|
+
this.#handle = setInterval(() => this.tick(), this.#interval);
|
|
1596
|
+
this.#emitter.emit("start");
|
|
1597
|
+
this.tick();
|
|
1598
|
+
}
|
|
1599
|
+
tick() {
|
|
1600
|
+
this.#paint(this.#line());
|
|
1601
|
+
this.#index = (this.#index + 1) % this.#frames.length;
|
|
1602
|
+
}
|
|
1603
|
+
update(message) {
|
|
1604
|
+
this.#message = message;
|
|
1605
|
+
if (this.#handle !== void 0) this.#paint(this.#line());
|
|
1606
|
+
}
|
|
1607
|
+
success(message) {
|
|
1608
|
+
this.#finish("success", message);
|
|
1609
|
+
}
|
|
1610
|
+
failure(message) {
|
|
1611
|
+
this.#finish("error", message);
|
|
1612
|
+
}
|
|
1613
|
+
stop() {
|
|
1614
|
+
if (this.#handle === void 0) return;
|
|
1615
|
+
clearInterval(this.#handle);
|
|
1616
|
+
this.#handle = void 0;
|
|
1617
|
+
this.#emitter.emit("stop");
|
|
1618
|
+
}
|
|
1619
|
+
destroy() {
|
|
1620
|
+
this.stop();
|
|
1621
|
+
this.#emitter.destroy();
|
|
1622
|
+
}
|
|
1623
|
+
#finish(level, message) {
|
|
1624
|
+
this.stop();
|
|
1625
|
+
const text = message ?? this.#message;
|
|
1626
|
+
if (message !== void 0) this.#message = message;
|
|
1627
|
+
const color = this.#styler[STATUS_COLORS[level]];
|
|
1628
|
+
const line = `${color(STATUS_ICONS[level])} ${color(text)}`;
|
|
1629
|
+
this.#emitter.emit("frame", line);
|
|
1630
|
+
this.#sink.write(`\r${line}\n`, level === "error" ? "error" : void 0);
|
|
1631
|
+
}
|
|
1632
|
+
#line() {
|
|
1633
|
+
const glyph = this.#styler.cyan(this.#frames[this.#index] ?? "");
|
|
1634
|
+
return this.#message === "" ? glyph : `${glyph} ${this.#message}`;
|
|
1635
|
+
}
|
|
1636
|
+
#paint(line) {
|
|
1637
|
+
this.#emitter.emit("frame", line);
|
|
1638
|
+
this.#sink.write(`\r${line}`);
|
|
1639
|
+
}
|
|
1640
|
+
};
|
|
1641
|
+
//#endregion
|
|
1642
|
+
//#region src/core/factories.ts
|
|
1643
|
+
/**
|
|
1644
|
+
* Create the cross-environment default {@link RendererInterface} — the ANSI / SGR
|
|
1645
|
+
* renderer that turns style DATA into terminal escape codes. The default behind
|
|
1646
|
+
* {@link createStyler}; construct one directly to render a {@link import('./types.js').Style}
|
|
1647
|
+
* without the fluent surface, or to share one instance across stylers.
|
|
1648
|
+
*
|
|
1649
|
+
* @returns A stateless ANSI {@link RendererInterface}
|
|
1650
|
+
*
|
|
1651
|
+
* @example
|
|
1652
|
+
* ```ts
|
|
1653
|
+
* import { createANSIRenderer } from '@src/core'
|
|
1654
|
+
*
|
|
1655
|
+
* const renderer = createANSIRenderer()
|
|
1656
|
+
* renderer.render({ foreground: 'red', attributes: ['bold'] }, 'alert') // '\x1b[1;31malert\x1b[0m'
|
|
1657
|
+
* ```
|
|
1658
|
+
*/
|
|
1659
|
+
function createANSIRenderer() {
|
|
1660
|
+
return new ANSIRenderer();
|
|
1661
|
+
}
|
|
1662
|
+
/**
|
|
1663
|
+
* Create the fluent, composable {@link StylerInterface} — the consumer-facing styling
|
|
1664
|
+
* API. It builds a {@link import('./types.js').Style} under the hood and renders it
|
|
1665
|
+
* through a {@link RendererInterface} (the ANSI default), so `styler.red.bold('hi')`
|
|
1666
|
+
* yields styled text. Chains are immutable, so a base styler is freely reusable.
|
|
1667
|
+
*
|
|
1668
|
+
* @param options - See {@link StylerOptions}
|
|
1669
|
+
* @returns A base {@link StylerInterface}
|
|
1670
|
+
*
|
|
1671
|
+
* @remarks
|
|
1672
|
+
* - `options.renderer` swaps the output target without touching the style model — pass a
|
|
1673
|
+
* browser `%c` / CSS renderer (the C-f branch) to retarget; defaults to the ANSI
|
|
1674
|
+
* renderer (the cross-environment default).
|
|
1675
|
+
* - `options.enabled` is the no-color switch: when `false`, the styler returns text
|
|
1676
|
+
* VERBATIM (for a non-TTY, `NO_COLOR`, or piped output); defaults to `true`.
|
|
1677
|
+
*
|
|
1678
|
+
* @example
|
|
1679
|
+
* ```ts
|
|
1680
|
+
* import { createStyler } from '@src/core'
|
|
1681
|
+
*
|
|
1682
|
+
* const style = createStyler()
|
|
1683
|
+
* style.red.bold('error') // bold red
|
|
1684
|
+
* style.red(style.underline('link')) // composes either way
|
|
1685
|
+
*
|
|
1686
|
+
* // Disable for a non-TTY — every call returns its text unchanged.
|
|
1687
|
+
* const plain = createStyler({ enabled: false })
|
|
1688
|
+
* plain.green('ok') // 'ok'
|
|
1689
|
+
* ```
|
|
1690
|
+
*/
|
|
1691
|
+
function createStyler(options) {
|
|
1692
|
+
return new Styler(options?.renderer ?? new ANSIRenderer(), options?.enabled ?? true, EMPTY_STYLE).surface;
|
|
1693
|
+
}
|
|
1694
|
+
/**
|
|
1695
|
+
* Create the default {@link SinkInterface} — a console sink that routes by level and writes
|
|
1696
|
+
* through the `console` methods SNAPSHOTTED at creation. The default output target behind
|
|
1697
|
+
* {@link createLogger}.
|
|
1698
|
+
*
|
|
1699
|
+
* @returns A console {@link SinkInterface}
|
|
1700
|
+
*
|
|
1701
|
+
* @remarks
|
|
1702
|
+
* - **Snapshotted — no capture loop.** It captures `console.log` / `console.warn` /
|
|
1703
|
+
* `console.error` AT CALL TIME and writes through those references. So when a later
|
|
1704
|
+
* `Capture` (C-d) PATCHES `console.*`, this sink still reaches the REAL streams — the
|
|
1705
|
+
* writer and the capturer never feed each other (the no-capture-loop principle). Create
|
|
1706
|
+
* the sink (or the logger) BEFORE installing a capture for this to hold.
|
|
1707
|
+
* - **Routes by level.** `error` → the snapshotted `console.error`, `warn` →
|
|
1708
|
+
* `console.warn`, every other level → `console.log`. The `level` is supplied by the
|
|
1709
|
+
* logger; an omitted `level` goes to `console.log`.
|
|
1710
|
+
*
|
|
1711
|
+
* @example
|
|
1712
|
+
* ```ts
|
|
1713
|
+
* import { createConsoleSink } from '@src/core'
|
|
1714
|
+
*
|
|
1715
|
+
* const sink = createConsoleSink() // snapshots console.* now
|
|
1716
|
+
* sink.write('boom', 'error') // → the real console.error, even after a later console patch
|
|
1717
|
+
* ```
|
|
1718
|
+
*/
|
|
1719
|
+
function createConsoleSink() {
|
|
1720
|
+
const log = console.log.bind(console);
|
|
1721
|
+
const warn = console.warn.bind(console);
|
|
1722
|
+
const error = console.error.bind(console);
|
|
1723
|
+
return { write(text, level) {
|
|
1724
|
+
if (level === "error") {
|
|
1725
|
+
error(text);
|
|
1726
|
+
return;
|
|
1727
|
+
}
|
|
1728
|
+
if (level === "warn") {
|
|
1729
|
+
warn(text);
|
|
1730
|
+
return;
|
|
1731
|
+
}
|
|
1732
|
+
log(text);
|
|
1733
|
+
} };
|
|
1734
|
+
}
|
|
1735
|
+
/**
|
|
1736
|
+
* Create an observable, leveled {@link LoggerInterface} — the entry point into structured
|
|
1737
|
+
* logging. Each `debug` / `info` / `warn` / `error` call builds a frozen
|
|
1738
|
+
* {@link import('./types.js').LogRecord}, gates it by severity, retains a bounded tail,
|
|
1739
|
+
* ALWAYS emits it on `entry` (the transport seam), and — unless `silent` — writes a styled
|
|
1740
|
+
* line to its sink.
|
|
1741
|
+
*
|
|
1742
|
+
* @param options - See {@link LoggerOptions}
|
|
1743
|
+
* @returns A {@link LoggerInterface}
|
|
1744
|
+
*
|
|
1745
|
+
* @remarks
|
|
1746
|
+
* - **Record + event = transport (§13).** Subscribe `logger.emitter.on('entry', …)` to tee
|
|
1747
|
+
* records to a file / JSON / remote transport; the event fires for every accepted record,
|
|
1748
|
+
* even when `silent` (silence suppresses only the SINK WRITE).
|
|
1749
|
+
* - **Bounded retention.** `entries()` returns the recent records, capped at `options.limit`
|
|
1750
|
+
* (default {@link DEFAULT_LOG_LIMIT}); never unbounded.
|
|
1751
|
+
* - **Sink + styler defaults.** `options.sink` defaults to {@link createConsoleSink} (the
|
|
1752
|
+
* snapshotted, level-routing console sink); `options.styler` to {@link createStyler} (ANSI).
|
|
1753
|
+
* Styling is orthogonal to level — a level only chooses a label color.
|
|
1754
|
+
*
|
|
1755
|
+
* @example
|
|
1756
|
+
* ```ts
|
|
1757
|
+
* import { createLogger } from '@src/core'
|
|
1758
|
+
*
|
|
1759
|
+
* const logger = createLogger({ name: 'http', level: 'info' })
|
|
1760
|
+
* logger.info('request', { method: 'GET', path: '/' })
|
|
1761
|
+
* logger.debug('verbose') // dropped — below the info threshold
|
|
1762
|
+
* ```
|
|
1763
|
+
*/
|
|
1764
|
+
function createLogger(options) {
|
|
1765
|
+
return new Logger(options);
|
|
1766
|
+
}
|
|
1767
|
+
/**
|
|
1768
|
+
* Create an event-free {@link LoggerManagerInterface} — a §9 registry of named loggers plus
|
|
1769
|
+
* a convenience fan-out. It mints + stores {@link LoggerInterface}s keyed by name (its
|
|
1770
|
+
* defaults flowing into each), looks them up, removes them, and broadcasts a one-off log to
|
|
1771
|
+
* every registered logger.
|
|
1772
|
+
*
|
|
1773
|
+
* @param options - See {@link LoggerManagerOptions}
|
|
1774
|
+
* @returns A {@link LoggerManagerInterface}
|
|
1775
|
+
*
|
|
1776
|
+
* @remarks
|
|
1777
|
+
* - **Defaults flow in.** `options.level` / `sink` / `styler` / `limit` / `silent` are the
|
|
1778
|
+
* defaults flowed into every `register`ed logger unless that call's options override them.
|
|
1779
|
+
* - **Event-free.** The manager carries NO emitter (each registered logger owns its own
|
|
1780
|
+
* observable `emitter`) — it is a pure registry.
|
|
1781
|
+
*
|
|
1782
|
+
* @example
|
|
1783
|
+
* ```ts
|
|
1784
|
+
* import { createLoggerManager } from '@src/core'
|
|
1785
|
+
*
|
|
1786
|
+
* const loggers = createLoggerManager({ level: 'warn' })
|
|
1787
|
+
* loggers.register('http')
|
|
1788
|
+
* loggers.register('db', { level: 'debug' }) // overrides the default
|
|
1789
|
+
* loggers.warn('slow', { ms: 900 }) // fans out to both
|
|
1790
|
+
* ```
|
|
1791
|
+
*/
|
|
1792
|
+
function createLoggerManager(options) {
|
|
1793
|
+
return new LoggerManager(options);
|
|
1794
|
+
}
|
|
1795
|
+
/**
|
|
1796
|
+
* Create a lean, event-free {@link ReporterInterface} — the entry point into narrative
|
|
1797
|
+
* reporting. Each verb (`section` / `step` / `timing` / `status` / `table` / `tree` / `box` /
|
|
1798
|
+
* `line` / `blank`) formats through the shared styler + the pure layout renderers and writes to
|
|
1799
|
+
* the sink — human / build-run narration over the SAME substrate the logger uses.
|
|
1800
|
+
*
|
|
1801
|
+
* @param options - See {@link ReporterOptions}
|
|
1802
|
+
* @returns A {@link ReporterInterface}
|
|
1803
|
+
*
|
|
1804
|
+
* @remarks
|
|
1805
|
+
* - **One styler, one sink.** `options.styler` defaults to {@link createStyler} (ANSI) and
|
|
1806
|
+
* `options.sink` to {@link createConsoleSink} (the snapshotted, level-routing console sink) —
|
|
1807
|
+
* no second colorizer. A `status('error', …)` routes to the sink's error stream.
|
|
1808
|
+
* - **Width-aware.** `options.width` (default {@link DEFAULT_WIDTH}) sizes `section` and a
|
|
1809
|
+
* `box` with no explicit width; the renderers align on VISIBLE width so styled content keeps
|
|
1810
|
+
* its columns.
|
|
1811
|
+
* - **Event-free (§13).** The reporter carries no emitter — a pure formatting front-end, like
|
|
1812
|
+
* the renderers and `Scheduler`. Reach for a {@link createLogger} when you need observable,
|
|
1813
|
+
* leveled, transportable records instead.
|
|
1814
|
+
*
|
|
1815
|
+
* @example
|
|
1816
|
+
* ```ts
|
|
1817
|
+
* import { createReporter } from '@src/core'
|
|
1818
|
+
*
|
|
1819
|
+
* const reporter = createReporter()
|
|
1820
|
+
* reporter.section('Build')
|
|
1821
|
+
* reporter.step('bundling', { index: 2, total: 5 }) // [2/5] bundling
|
|
1822
|
+
* reporter.status('success', 'built in 1.2s') // ✔ built in 1.2s
|
|
1823
|
+
*
|
|
1824
|
+
* // Disable color (a non-TTY) — every line is plain.
|
|
1825
|
+
* const plain = createReporter({ styler: createStyler({ enabled: false }) })
|
|
1826
|
+
* ```
|
|
1827
|
+
*/
|
|
1828
|
+
function createReporter(options) {
|
|
1829
|
+
return new Reporter(options);
|
|
1830
|
+
}
|
|
1831
|
+
/**
|
|
1832
|
+
* Create an observable {@link CaptureInterface} — console interception on the READ side. While
|
|
1833
|
+
* `active`, every configured `console.*` call is captured as a frozen
|
|
1834
|
+
* {@link import('./types.js').CapturedMessage}, buffered (total + by level, bounded), emitted on
|
|
1835
|
+
* `capture`, and — per options — mirrored to the real console and/or forwarded to a
|
|
1836
|
+
* {@link SinkInterface}.
|
|
1837
|
+
*
|
|
1838
|
+
* @param options - See {@link CaptureOptions}
|
|
1839
|
+
* @returns A {@link CaptureInterface} (inactive until `start()`)
|
|
1840
|
+
*
|
|
1841
|
+
* @remarks
|
|
1842
|
+
* - **Snapshot-at-start — no capture loop.** `start()` snapshots the CURRENT `console[level]` per
|
|
1843
|
+
* configured level, then patches; the mirror writes through that snapshot. Our OWN console sink
|
|
1844
|
+
* output (the Logger / Reporter, which snapshot `console` at creation) is never recaptured —
|
|
1845
|
+
* `Capture` catches THIRD-PARTY `console.*`, not our writes. Create your loggers FIRST.
|
|
1846
|
+
* - **PROCESS-GLOBAL + NON-REENTRANT.** It patches the one global `console`, so at most ONE
|
|
1847
|
+
* capture may be active at a time; two concurrent captures interleave and clobber each other's
|
|
1848
|
+
* restore. Prefer {@link withCapture} for a scoped, self-restoring capture.
|
|
1849
|
+
* - **Bounded.** `options.limit` (default {@link import('./constants.js').DEFAULT_CAPTURE_LIMIT})
|
|
1850
|
+
* caps both the total buffer and each by-level bucket; never unbounded.
|
|
1851
|
+
*
|
|
1852
|
+
* @example
|
|
1853
|
+
* ```ts
|
|
1854
|
+
* import { createCapture } from '@src/core'
|
|
1855
|
+
*
|
|
1856
|
+
* const capture = createCapture({ levels: ['warn', 'error'] })
|
|
1857
|
+
* capture.start()
|
|
1858
|
+
* console.error('boom') // captured, NOT mirrored (mirror defaults to false)
|
|
1859
|
+
* capture.messages('error') // [{ level: 'error', text: 'boom', time: … }]
|
|
1860
|
+
* capture.stop()
|
|
1861
|
+
* ```
|
|
1862
|
+
*/
|
|
1863
|
+
function createCapture(options) {
|
|
1864
|
+
return new Capture(options);
|
|
1865
|
+
}
|
|
1866
|
+
/**
|
|
1867
|
+
* Run `fn` with the global `console.*` captured for its duration, returning the function's `value`
|
|
1868
|
+
* plus the {@link import('./types.js').CapturedMessage}s it logged — the scoped, self-restoring
|
|
1869
|
+
* ergonomic form of {@link createCapture}.
|
|
1870
|
+
*
|
|
1871
|
+
* @param fn - The function to run under capture; may be sync (returns `T`) or async (returns
|
|
1872
|
+
* `Promise<T>`)
|
|
1873
|
+
* @param options - See {@link CaptureOptions} (`levels` / `mirror` / `sink` / `limit` / `on` /
|
|
1874
|
+
* `error`); the capture is started for the duration of `fn` regardless
|
|
1875
|
+
* @returns For a sync `fn`, a {@link CaptureResult}`<T>` (`{ value, messages }`); for an async
|
|
1876
|
+
* `fn`, a `Promise<CaptureResult<T>>` (awaited, then console restored)
|
|
1877
|
+
*
|
|
1878
|
+
* @remarks
|
|
1879
|
+
* - **Always restores.** `start()` runs before `fn`; `stop()` runs in a `finally`, so `console` is
|
|
1880
|
+
* restored even if `fn` throws / rejects (the throw / rejection still propagates). The capture
|
|
1881
|
+
* is local — created, used, and destroyed within the call.
|
|
1882
|
+
* - **Sync vs async.** A `fn` returning a `Promise` is detected and AWAITED before `stop()`, so
|
|
1883
|
+
* captures during the async work are included; a plain `fn` stops synchronously. The return type
|
|
1884
|
+
* follows `fn`'s (overloaded).
|
|
1885
|
+
* - **PROCESS-GLOBAL caveat.** Like {@link createCapture}, this patches the one global `console`.
|
|
1886
|
+
* Concurrent `withCapture` calls (or a `withCapture` around other capturing code) INTERLEAVE —
|
|
1887
|
+
* each captures every `console.*` call in flight, and the inner `stop()` restores whatever the
|
|
1888
|
+
* outer had installed. Use it for sequential, scoped capture, not overlapping captures.
|
|
1889
|
+
*
|
|
1890
|
+
* @example
|
|
1891
|
+
* ```ts
|
|
1892
|
+
* import { withCapture } from '@src/core'
|
|
1893
|
+
*
|
|
1894
|
+
* const { value, messages } = withCapture(() => {
|
|
1895
|
+
* console.log('working')
|
|
1896
|
+
* return 42
|
|
1897
|
+
* })
|
|
1898
|
+
* value // 42
|
|
1899
|
+
* messages.map((m) => m.text) // ['working']
|
|
1900
|
+
*
|
|
1901
|
+
* // Async — awaited before console is restored.
|
|
1902
|
+
* const out = await withCapture(async () => {
|
|
1903
|
+
* console.warn('async noise')
|
|
1904
|
+
* return 'done'
|
|
1905
|
+
* })
|
|
1906
|
+
* out.value // 'done'
|
|
1907
|
+
* ```
|
|
1908
|
+
*/
|
|
1909
|
+
function withCapture(fn, options) {
|
|
1910
|
+
const capture = new Capture(options);
|
|
1911
|
+
capture.start();
|
|
1912
|
+
const settle = (value) => {
|
|
1913
|
+
const messages = capture.messages();
|
|
1914
|
+
capture.destroy();
|
|
1915
|
+
return {
|
|
1916
|
+
value,
|
|
1917
|
+
messages
|
|
1918
|
+
};
|
|
1919
|
+
};
|
|
1920
|
+
try {
|
|
1921
|
+
const result = fn();
|
|
1922
|
+
if (result instanceof Promise) return result.then((value) => settle(value), (error) => {
|
|
1923
|
+
capture.destroy();
|
|
1924
|
+
throw error;
|
|
1925
|
+
});
|
|
1926
|
+
return settle(result);
|
|
1927
|
+
} catch (error) {
|
|
1928
|
+
capture.destroy();
|
|
1929
|
+
throw error;
|
|
1930
|
+
}
|
|
1931
|
+
}
|
|
1932
|
+
/**
|
|
1933
|
+
* Create a self-driving, observable {@link SpinnerInterface} — a live activity spinner. `start()`
|
|
1934
|
+
* arms a periodic timer that advances a glyph cycle, writing each `\r` + frame line to its sink and
|
|
1935
|
+
* emitting it on `frame`; `success` / `failure` commit a final `✔` / `✖` line. The leading `\r` is the
|
|
1936
|
+
* sink's to redraw on — a TTY sink (C-g) overwrites for a smooth animation, a plain sink (C-f)
|
|
1937
|
+
* degrades to a fresh line.
|
|
1938
|
+
*
|
|
1939
|
+
* @param options - See {@link SpinnerOptions}
|
|
1940
|
+
* @returns A {@link SpinnerInterface} (inactive until `start()`)
|
|
1941
|
+
*
|
|
1942
|
+
* @remarks
|
|
1943
|
+
* - **Universal + leak-free.** Built on `setInterval` + the one styler + the one sink (no `node:*`,
|
|
1944
|
+
* no `process.stdout`); the timer is ALWAYS cleared on `success` / `failure` / `stop` / `destroy`, so
|
|
1945
|
+
* it never leaks. `start()` is idempotent (no second timer while `active`).
|
|
1946
|
+
* - **Observable (§13).** Subscribe `spinner.emitter.on('frame', …)` to mirror the animation without
|
|
1947
|
+
* a terminal; `start` / `stop` bracket the timer lifecycle. `options.sink` defaults to
|
|
1948
|
+
* {@link createConsoleSink}, `options.styler` to {@link createStyler} (ANSI).
|
|
1949
|
+
*
|
|
1950
|
+
* @example
|
|
1951
|
+
* ```ts
|
|
1952
|
+
* import { createSpinner } from '@src/core'
|
|
1953
|
+
*
|
|
1954
|
+
* const spinner = createSpinner({ message: 'building' })
|
|
1955
|
+
* spinner.start()
|
|
1956
|
+
* spinner.success('built in 1.2s') // ✔ built in 1.2s — timer cleared, line committed
|
|
1957
|
+
* ```
|
|
1958
|
+
*/
|
|
1959
|
+
function createSpinner(options) {
|
|
1960
|
+
return new Spinner(options);
|
|
1961
|
+
}
|
|
1962
|
+
/**
|
|
1963
|
+
* Create an update-driven, observable {@link ProgressInterface} — a live progress bar. Each
|
|
1964
|
+
* `update(current)` recomputes the bar, writes `\r` + bar to its sink, and emits `{ current, total }`
|
|
1965
|
+
* on `update`; `complete` / `failure` commit a final line. The leading `\r` is the sink's to redraw on —
|
|
1966
|
+
* a TTY sink (C-g) overwrites, a plain sink (C-f) degrades to a fresh line. NO self-timer — the caller
|
|
1967
|
+
* drives the bar.
|
|
1968
|
+
*
|
|
1969
|
+
* @param options - See {@link ProgressOptions} (`total` is required)
|
|
1970
|
+
* @returns A {@link ProgressInterface}
|
|
1971
|
+
*
|
|
1972
|
+
* @remarks
|
|
1973
|
+
* - **Universal + update-driven.** Built on the one styler + the one sink (no `node:*`, no
|
|
1974
|
+
* `process.stdout`); progress advances only when the caller reports it. `current` is always clamped
|
|
1975
|
+
* to `[0, total]`. `options.sink` defaults to {@link createConsoleSink}, `options.styler` to
|
|
1976
|
+
* {@link createStyler} (ANSI).
|
|
1977
|
+
* - **Observable (§13).** Subscribe `progress.emitter.on('update', …)` to mirror progress without a
|
|
1978
|
+
* terminal; `complete` signals a successful finish.
|
|
1979
|
+
*
|
|
1980
|
+
* @example
|
|
1981
|
+
* ```ts
|
|
1982
|
+
* import { createProgress } from '@src/core'
|
|
1983
|
+
*
|
|
1984
|
+
* const progress = createProgress({ total: 100, message: 'downloading' })
|
|
1985
|
+
* progress.update(40)
|
|
1986
|
+
* progress.complete('done')
|
|
1987
|
+
* ```
|
|
1988
|
+
*/
|
|
1989
|
+
function createProgress(options) {
|
|
1990
|
+
return new Progress(options);
|
|
1991
|
+
}
|
|
1992
|
+
//#endregion
|
|
1993
|
+
//#region src/core/Logger.ts
|
|
1994
|
+
/**
|
|
1995
|
+
* An observable, leveled logger (AGENTS §13) — the entry point into the structured-logging
|
|
1996
|
+
* pipeline. Each `debug` / `info` / `warn` / `error` call builds a frozen {@link LogRecord},
|
|
1997
|
+
* gates it by severity, retains a bounded tail of accepted records, ALWAYS emits it on
|
|
1998
|
+
* `entry` (the transport seam), and — unless `silent` — formats it into a styled line and
|
|
1999
|
+
* writes it to its {@link SinkInterface}.
|
|
2000
|
+
*
|
|
2001
|
+
* @remarks
|
|
2002
|
+
* - **Record + event = transport (§13).** An accepted record is frozen and emitted on
|
|
2003
|
+
* `entry` BEFORE anything else observable — every file / JSON / remote transport rides
|
|
2004
|
+
* `emitter.on('entry')`. The event fires even when `silent`: silence suppresses only the
|
|
2005
|
+
* SINK WRITE, never the record or the event, so transports keep flowing.
|
|
2006
|
+
* - **Leveled gate.** A record whose {@link LogLevel} is below the logger's `level` threshold
|
|
2007
|
+
* is dropped ENTIRELY — no record built past the level check, no event, no retention, no
|
|
2008
|
+
* write (see {@link meetsLevel}).
|
|
2009
|
+
* - **Bounded retention.** Accepted records accrue in a ring capped at `limit` (default
|
|
2010
|
+
* {@link DEFAULT_LOG_LIMIT}); the oldest is dropped when full. `entries()` returns a copy,
|
|
2011
|
+
* oldest first; `clear()` empties it. NEVER unbounded (scsr's leak).
|
|
2012
|
+
* - **Styled write, orthogonal to level.** The line ({@link formatRecord}) is colored through
|
|
2013
|
+
* the injected `styler` (the ANSI default, or a browser `%c` styler at C-f) — a level only
|
|
2014
|
+
* chooses a label color; styling is not a level. A disabled styler yields a plain line.
|
|
2015
|
+
* - **Snapshotted sink.** The default {@link createConsoleSink} writes to the `console`
|
|
2016
|
+
* methods captured at creation, so a later `Capture` patching `console` can't loop the
|
|
2017
|
+
* sink's output back into itself.
|
|
2018
|
+
*
|
|
2019
|
+
* @example
|
|
2020
|
+
* ```ts
|
|
2021
|
+
* const logger = new Logger({ name: 'http', level: 'info' })
|
|
2022
|
+
* logger.emitter.on('entry', (record) => archive(record)) // transport hook
|
|
2023
|
+
* logger.info('request', { method: 'GET', path: '/' }) // styled line to the console sink
|
|
2024
|
+
* logger.debug('verbose') // dropped — below the `info` threshold
|
|
2025
|
+
* logger.entries() // [the info record]
|
|
2026
|
+
* ```
|
|
2027
|
+
*/
|
|
2028
|
+
var Logger = class {
|
|
2029
|
+
#emitter;
|
|
2030
|
+
#level;
|
|
2031
|
+
#name;
|
|
2032
|
+
#sink;
|
|
2033
|
+
#styler;
|
|
2034
|
+
#limit;
|
|
2035
|
+
#silent;
|
|
2036
|
+
#entries = [];
|
|
2037
|
+
constructor(options) {
|
|
2038
|
+
this.#emitter = new Emitter({
|
|
2039
|
+
on: options?.on,
|
|
2040
|
+
error: options?.error
|
|
2041
|
+
});
|
|
2042
|
+
this.#level = options?.level ?? "info";
|
|
2043
|
+
this.#name = options?.name;
|
|
2044
|
+
this.#sink = options?.sink ?? createConsoleSink();
|
|
2045
|
+
this.#styler = options?.styler ?? createStyler();
|
|
2046
|
+
this.#limit = options?.limit ?? 1e3;
|
|
2047
|
+
this.#silent = options?.silent ?? false;
|
|
2048
|
+
}
|
|
2049
|
+
get emitter() {
|
|
2050
|
+
return this.#emitter;
|
|
2051
|
+
}
|
|
2052
|
+
get level() {
|
|
2053
|
+
return this.#level;
|
|
2054
|
+
}
|
|
2055
|
+
get name() {
|
|
2056
|
+
return this.#name;
|
|
2057
|
+
}
|
|
2058
|
+
debug(message, data) {
|
|
2059
|
+
this.#log("debug", message, data);
|
|
2060
|
+
}
|
|
2061
|
+
info(message, data) {
|
|
2062
|
+
this.#log("info", message, data);
|
|
2063
|
+
}
|
|
2064
|
+
warn(message, data) {
|
|
2065
|
+
this.#log("warn", message, data);
|
|
2066
|
+
}
|
|
2067
|
+
error(message, data) {
|
|
2068
|
+
this.#log("error", message, data);
|
|
2069
|
+
}
|
|
2070
|
+
entries() {
|
|
2071
|
+
return [...this.#entries];
|
|
2072
|
+
}
|
|
2073
|
+
clear() {
|
|
2074
|
+
this.#entries.length = 0;
|
|
2075
|
+
}
|
|
2076
|
+
destroy() {
|
|
2077
|
+
this.#entries.length = 0;
|
|
2078
|
+
this.#emitter.destroy();
|
|
2079
|
+
}
|
|
2080
|
+
#log(level, message, data) {
|
|
2081
|
+
if (!meetsLevel(this.#level, level)) return;
|
|
2082
|
+
const record = this.#record(level, message, data);
|
|
2083
|
+
this.#retain(record);
|
|
2084
|
+
this.#emitter.emit("entry", record);
|
|
2085
|
+
if (this.#silent) return;
|
|
2086
|
+
this.#sink.write(formatRecord(record, this.#styler), level);
|
|
2087
|
+
}
|
|
2088
|
+
#record(level, message, data) {
|
|
2089
|
+
return Object.freeze({
|
|
2090
|
+
level,
|
|
2091
|
+
message,
|
|
2092
|
+
time: Date.now(),
|
|
2093
|
+
...this.#name === void 0 ? {} : { name: this.#name },
|
|
2094
|
+
...data === void 0 ? {} : { data: Object.freeze({ ...data }) }
|
|
2095
|
+
});
|
|
2096
|
+
}
|
|
2097
|
+
#retain(record) {
|
|
2098
|
+
this.#entries.push(record);
|
|
2099
|
+
if (this.#entries.length > this.#limit) this.#entries.shift();
|
|
2100
|
+
}
|
|
2101
|
+
};
|
|
2102
|
+
//#endregion
|
|
2103
|
+
export { ANSIRenderer, ANSI_PATTERN, ATTRIBUTES, ATTRIBUTE_CODES, BACKGROUND_CODES, BAR_EMPTY, BAR_FILL, BEL, BORDER_CHARS, CAPTURE_LEVELS, CAPTURE_LEVEL_MAP, COLORS, CONTROL_PATTERN, CSI, Capture, ConsoleError, DEFAULT_ALIGN, DEFAULT_BAR_WIDTH, DEFAULT_BORDER, DEFAULT_CAPTURE_LEVELS, DEFAULT_CAPTURE_LIMIT, DEFAULT_LOG_LEVEL, DEFAULT_LOG_LIMIT, DEFAULT_PADDING, DEFAULT_SPINNER_INTERVAL, DEFAULT_WIDTH, EMPTY_STYLE, ESC, FOREGROUND_CODES, LEVELS, LEVEL_COLORS, LEVEL_SEVERITY, Logger, LoggerManager, Progress, RESET, RESET_CODE, Reporter, SECOND_MS, SEPARATOR_FILL, SEPARATOR_TITLE_GAP, SPINNER_FRAMES, STATUS_COLORS, STATUS_ICONS, STATUS_LEVELS, Spinner, Styler, TREE_CHARS, align, cellAt, createANSIRenderer, createCapture, createConsoleSink, createLogger, createLoggerManager, createProgress, createReporter, createSpinner, createStyler, formatArgs, formatDuration, formatRecord, formatTime, isConsoleError, meetsLevel, paint, renderBar, renderBox, renderSeparator, renderTable, renderTree, renderTreeChildren, repeatTo, stringifyValue, strip, stripControls, width, withCapture };
|
|
2104
|
+
|
|
2105
|
+
//# sourceMappingURL=index.js.map
|