@kjanat/dreamcli 0.0.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/CHANGELOG.md +667 -0
  2. package/LICENSE +22 -0
  3. package/README.md +370 -0
  4. package/dist/adapter-B37d9oia.mjs +1 -0
  5. package/dist/adapter-CCSh5juX.cjs +1 -0
  6. package/dist/adapter-DIwO-q7K.d.mts +3447 -0
  7. package/dist/adapter-DQnxxLiE.d.cts +3447 -0
  8. package/dist/auto-5cjZaF9V.mjs +3 -0
  9. package/dist/auto-B0eSgoDw.cjs +3 -0
  10. package/dist/index.cjs +10 -0
  11. package/dist/index.d.cts +920 -0
  12. package/dist/index.d.mts +920 -0
  13. package/dist/index.mjs +10 -0
  14. package/dist/runtime.cjs +1 -0
  15. package/dist/runtime.d.cts +253 -0
  16. package/dist/runtime.d.mts +253 -0
  17. package/dist/runtime.mjs +1 -0
  18. package/dist/testkit-CEDYPvhF.mjs +14 -0
  19. package/dist/testkit-ClIKijxC.cjs +14 -0
  20. package/dist/testkit.cjs +1 -0
  21. package/dist/testkit.d.cts +25 -0
  22. package/dist/testkit.d.mts +25 -0
  23. package/dist/testkit.mjs +1 -0
  24. package/examples/basic.ts +33 -0
  25. package/examples/gh/package.json +48 -0
  26. package/examples/gh/src/commands/auth.ts +66 -0
  27. package/examples/gh/src/commands/issue.ts +120 -0
  28. package/examples/gh/src/commands/pr.ts +125 -0
  29. package/examples/gh/src/data/issues.yaml +5 -0
  30. package/examples/gh/src/data/issues.yaml.d.ts +17 -0
  31. package/examples/gh/src/data/pull-requests.yaml +7 -0
  32. package/examples/gh/src/data/pull-requests.yaml.d.ts +18 -0
  33. package/examples/gh/src/lib/auth.ts +37 -0
  34. package/examples/gh/src/lib/utils.ts +17 -0
  35. package/examples/gh/src/main.test.ts +306 -0
  36. package/examples/gh/src/main.ts +38 -0
  37. package/examples/gh/tsconfig.json +37 -0
  38. package/examples/interactive.ts +66 -0
  39. package/examples/json-mode.ts +93 -0
  40. package/examples/middleware.ts +71 -0
  41. package/examples/multi-command.ts +66 -0
  42. package/examples/spinner-progress.ts +49 -0
  43. package/examples/testing.ts +145 -0
  44. package/examples/tsconfig.json +17 -0
  45. package/package.json +123 -2
  46. package/src/core/cli/AGENTS.md +72 -0
  47. package/src/core/cli/dispatch.ts +282 -0
  48. package/src/core/cli/index.ts +1425 -0
  49. package/src/core/cli/plugin.ts +111 -0
  50. package/src/core/cli/propagate.ts +97 -0
  51. package/src/core/cli/root-help.ts +269 -0
  52. package/src/core/cli/root-surface.ts +74 -0
  53. package/src/core/completion/AGENTS.md +72 -0
  54. package/src/core/completion/completion-test-helpers.ts +48 -0
  55. package/src/core/completion/index.ts +82 -0
  56. package/src/core/completion/shells/bash.ts +456 -0
  57. package/src/core/completion/shells/fish.ts +24 -0
  58. package/src/core/completion/shells/powershell.ts +24 -0
  59. package/src/core/completion/shells/shared.ts +283 -0
  60. package/src/core/completion/shells/zsh.ts +376 -0
  61. package/src/core/config/index.ts +404 -0
  62. package/src/core/config/package-json.ts +216 -0
  63. package/src/core/errors/index.ts +178 -0
  64. package/src/core/help/index.ts +559 -0
  65. package/src/core/json-schema/index.ts +705 -0
  66. package/src/core/output/AGENTS.md +69 -0
  67. package/src/core/output/activity.ts +568 -0
  68. package/src/core/output/display-value.ts +48 -0
  69. package/src/core/output/index.ts +704 -0
  70. package/src/core/output/writer.ts +46 -0
  71. package/src/core/parse/index.ts +643 -0
  72. package/src/core/prompt/index.ts +566 -0
  73. package/src/core/resolve/AGENTS.md +69 -0
  74. package/src/core/resolve/index.ts +1331 -0
  75. package/src/core/schema/AGENTS.md +61 -0
  76. package/src/core/schema/activity.ts +237 -0
  77. package/src/core/schema/arg.ts +707 -0
  78. package/src/core/schema/command.ts +1263 -0
  79. package/src/core/schema/flag.ts +651 -0
  80. package/src/core/schema/index.ts +82 -0
  81. package/src/core/schema/middleware.ts +171 -0
  82. package/src/core/schema/prompt.ts +148 -0
  83. package/src/core/schema/run.ts +187 -0
  84. package/src/core/testkit/AGENTS.md +55 -0
  85. package/src/core/testkit/index.ts +365 -0
  86. package/src/index.ts +164 -0
  87. package/src/runtime/AGENTS.md +74 -0
  88. package/src/runtime/adapter.ts +300 -0
  89. package/src/runtime/auto.ts +110 -0
  90. package/src/runtime/bun.ts +55 -0
  91. package/src/runtime/deno.ts +355 -0
  92. package/src/runtime/detect.ts +102 -0
  93. package/src/runtime/index.ts +21 -0
  94. package/src/runtime/node-builtins.d.ts +23 -0
  95. package/src/runtime/node.ts +278 -0
  96. package/src/runtime/paths.ts +56 -0
  97. package/src/runtime/support.ts +119 -0
  98. package/src/runtime/test-helpers.ts +40 -0
  99. package/src/runtime.ts +31 -0
  100. package/src/testkit.ts +23 -0
  101. package/src/version.ts +20 -0
@@ -0,0 +1,69 @@
1
+ # output — OutputChannel, spinner/progress, TTY rendering
2
+
3
+ Three files: `writer.ts` (leaf, ~30 lines), `activity.ts` (handle classes, ~581 lines), `index.ts`
4
+ (OutputChannel + factories, ~570 lines).
5
+
6
+ Dependency graph (no cycles): `writer.ts` ← `activity.ts` ← `index.ts` → `writer.ts`.
7
+
8
+ ## KEY TYPES
9
+
10
+ | Symbol | Visibility | Role |
11
+ | ----------------------- | ----------- | ------------------------------------------------ |
12
+ | `createOutput()` | **Public** | Factory → `Out` interface (mode-dispatched) |
13
+ | `createCaptureOutput()` | **Public** | Factory → `Out` + `CapturedOutput` (for testkit) |
14
+ | `OutputChannel` | `@internal` | Concrete class implementing `Out` |
15
+ | `CaptureOutputChannel` | `@internal` | Subclass capturing output + activity events |
16
+
17
+ ## OUTPUT MODES
18
+
19
+ | Mode | `out.log` | `out.json` | Spinner/Progress |
20
+ | ------- | ---------- | ---------- | ---------------- |
21
+ | Normal | → stdout | → stdout | TTY handles |
22
+ | JSON | → stderr | → stdout | Noop handles |
23
+ | Quiet | suppressed | → stdout | Noop handles |
24
+ | Non-TTY | → stdout | → stdout | Static handles |
25
+ | Capture | → array | → array | Capture handles |
26
+
27
+ ## ACTIVITY HANDLES
28
+
29
+ Four handle tiers per activity type (spinner + progress):
30
+
31
+ | Handle class | When used | Behavior |
32
+ | ---------------------- | ---------- | --------------------------------------------- |
33
+ | `noopSpinnerHandle` | JSON/quiet | Silent, all methods no-op |
34
+ | `StaticSpinnerHandle` | non-TTY | Writes start/succeed/fail as plain text lines |
35
+ | `TTYSpinnerHandle` | TTY | Braille animation, cursor control, erase line |
36
+ | `CaptureSpinnerHandle` | testkit | Records `ActivityEvent[]` for assertions |
37
+
38
+ Same pattern for `*ProgressHandle` (bar rendering, percentage, indeterminate pulse).
39
+
40
+ Active handle tracking: only one spinner/progress at a time per `OutputChannel`. Starting a new one
41
+ implicitly stops the previous. `stopActive()` public method for explicit cleanup.
42
+
43
+ All activity handle output (static and TTY) routes to **stderr** — stdout reserved for data.
44
+
45
+ ## AMBIENT DECLARATIONS
46
+
47
+ `setInterval`/`clearInterval` declared as ambient functions in `activity.ts` (not from
48
+ `@types/node`) — zero-dep library targeting ES2022 without DOM or Node lib typings.
49
+
50
+ ## TEST FILES (6)
51
+
52
+ | File | Tests | Focus |
53
+ | ---------------------------------- | ----: | ----------------------------------------------------- |
54
+ | `output.test.ts` | 49 | Core OutputChannel: log/warn/error, modes |
55
+ | `output-tty.test.ts` | 20 | TTY-specific rendering, color, formatting |
56
+ | `output-table.test.ts` | 16 | Table output in various modes |
57
+ | `output-spinner.test.ts` | 45 | Spinner handles: noop/static/TTY/capture, fake timers |
58
+ | `output-progress.test.ts` | 40 | Progress handles: noop/static/TTY/capture, fake timer |
59
+ | `output-activity-dispatch.test.ts` | 32 | OutputChannel wiring: mode dispatch, overlap, testkit |
60
+
61
+ ## GOTCHAS
62
+
63
+ - Imports `schema/activity.ts` directly for activity types, `schema/command.ts` for `Out` — bypasses
64
+ barrel to avoid circular dep
65
+ - `writer.ts` is a leaf: `WriteFn` type + `writeLine` helper. Shared by `index.ts` and `activity.ts`
66
+ - Terminal escape sequences (`HIDE_CURSOR`, `ERASE_LINE`, etc.) are `@internal` constants in
67
+ `activity.ts`
68
+ - Spinner/progress tests use `vi.useFakeTimers()` inline with `try/finally`
69
+ - `ActivityEvent` has 10 variants (including `progress:increment` distinct from `progress:update`)
@@ -0,0 +1,568 @@
1
+ /**
2
+ * Activity handle implementations — spinner and progress bar.
3
+ *
4
+ * Four tiers per activity type:
5
+ * - **Noop** — silent, all methods no-op (jsonMode / non-TTY silent)
6
+ * - **Static** — plain text at lifecycle boundaries (non-TTY, fallback='static')
7
+ * - **TTY** — animated ANSI rendering (braille spinner, bar with percentage)
8
+ * - **Capture** — records `ActivityEvent[]` for testkit assertion
9
+ *
10
+ * Extracted from `index.ts` to keep the main OutputChannel file focused on
11
+ * the `Out` implementation. Depends only on `writer.ts` (leaf) and
12
+ * `schema/command.ts` (types).
13
+ *
14
+ * @module dreamcli/core/output/activity
15
+ * @internal
16
+ */
17
+
18
+ import type {
19
+ ActivityEvent,
20
+ ProgressHandle,
21
+ ProgressOptions,
22
+ SpinnerHandle,
23
+ } from '#internals/core/schema/activity.ts';
24
+ import type { WriteFn } from './writer.ts';
25
+ import { writeLine } from './writer.ts';
26
+
27
+ // --- Timer globals — minimal declarations for setInterval/clearInterval.
28
+ //
29
+ // The project targets ES2022 without DOM or Node lib typings. Timer APIs
30
+ // are universally available across Node, Bun, Deno, and browsers, but the
31
+ // type checker doesn't know about them. Declaring the subset we need here
32
+ // avoids adding `@types/node` as a dependency.
33
+
34
+ declare function setInterval(callback: () => void, ms: number): unknown;
35
+ declare function clearInterval(handle: unknown): void;
36
+
37
+ // --- Noop activity handles — silent mode (non-TTY, fallback='silent')
38
+
39
+ /**
40
+ * Noop spinner handle singleton.
41
+ *
42
+ * All methods are no-ops. Used when spinners should produce no output
43
+ * at all — `jsonMode`, or non-TTY with `fallback: 'silent'` (default).
44
+ *
45
+ * @internal
46
+ */
47
+ const noopSpinnerHandle: SpinnerHandle = {
48
+ update() {},
49
+ succeed() {},
50
+ fail() {},
51
+ stop() {},
52
+ wrap<T>(promise: Promise<T>): Promise<T> {
53
+ return promise;
54
+ },
55
+ };
56
+
57
+ /**
58
+ * Noop progress handle singleton.
59
+ *
60
+ * All methods are no-ops. Used when progress bars should produce no
61
+ * output at all — `jsonMode`, or non-TTY with `fallback: 'silent'`.
62
+ *
63
+ * @internal
64
+ */
65
+ const noopProgressHandle: ProgressHandle = {
66
+ increment() {},
67
+ update() {},
68
+ done() {},
69
+ fail() {},
70
+ };
71
+
72
+ // --- Static activity handles — plain text mode (non-TTY, fallback='static')
73
+
74
+ /**
75
+ * Static spinner handle — emits plain text at lifecycle boundaries.
76
+ *
77
+ * Used in non-TTY environments with `fallback: 'static'`. No animation,
78
+ * no ANSI codes. Emits text on start and terminal events only.
79
+ *
80
+ * Terminal methods are idempotent — calling after stop is a no-op.
81
+ *
82
+ * @internal
83
+ */
84
+ class StaticSpinnerHandle implements SpinnerHandle {
85
+ /** Whether the handle has been stopped (terminal state reached). */
86
+ private stopped = false;
87
+
88
+ constructor(
89
+ text: string,
90
+ private readonly write: WriteFn,
91
+ ) {
92
+ writeLine(write, text);
93
+ }
94
+
95
+ update(_text: string): void {
96
+ // Static mode — no update output (no terminal to overwrite).
97
+ }
98
+
99
+ succeed(text?: string): void {
100
+ if (this.stopped) return;
101
+ this.stopped = true;
102
+ if (text !== undefined) {
103
+ writeLine(this.write, text);
104
+ }
105
+ }
106
+
107
+ fail(text?: string): void {
108
+ if (this.stopped) return;
109
+ this.stopped = true;
110
+ if (text !== undefined) {
111
+ writeLine(this.write, text);
112
+ }
113
+ }
114
+
115
+ stop(): void {
116
+ if (this.stopped) return;
117
+ this.stopped = true;
118
+ }
119
+
120
+ async wrap<T>(
121
+ promise: Promise<T>,
122
+ options?: { readonly succeed?: string; readonly fail?: string },
123
+ ): Promise<T> {
124
+ try {
125
+ const value = await promise;
126
+ this.succeed(options?.succeed);
127
+ return value;
128
+ } catch (error: unknown) {
129
+ this.fail(options?.fail);
130
+ throw error;
131
+ }
132
+ }
133
+ }
134
+
135
+ /**
136
+ * Static progress handle — emits plain text at lifecycle boundaries.
137
+ *
138
+ * Used in non-TTY environments with `fallback: 'static'`. No animation,
139
+ * no progress bar rendering. Emits label on start, text on done/fail.
140
+ *
141
+ * Terminal methods are idempotent — calling after stop is a no-op.
142
+ *
143
+ * @internal
144
+ */
145
+ class StaticProgressHandle implements ProgressHandle {
146
+ /** Whether the handle has been stopped (terminal state reached). */
147
+ private stopped = false;
148
+
149
+ constructor(
150
+ label: string | undefined,
151
+ private readonly write: WriteFn,
152
+ ) {
153
+ if (label !== undefined) {
154
+ writeLine(write, label);
155
+ }
156
+ }
157
+
158
+ increment(_n?: number): void {
159
+ // Static mode — no incremental output.
160
+ }
161
+
162
+ update(_value: number): void {
163
+ // Static mode — no incremental output.
164
+ }
165
+
166
+ done(text?: string): void {
167
+ if (this.stopped) return;
168
+ this.stopped = true;
169
+ if (text !== undefined) {
170
+ writeLine(this.write, text);
171
+ }
172
+ }
173
+
174
+ fail(text?: string): void {
175
+ if (this.stopped) return;
176
+ this.stopped = true;
177
+ if (text !== undefined) {
178
+ writeLine(this.write, text);
179
+ }
180
+ }
181
+ }
182
+
183
+ // --- ANSI escape sequences
184
+
185
+ /** Hide the terminal cursor. @internal */
186
+ const HIDE_CURSOR = '\x1b[?25l';
187
+
188
+ /** Show the terminal cursor. @internal */
189
+ const SHOW_CURSOR = '\x1b[?25h';
190
+
191
+ /** Erase the entire current line. @internal */
192
+ const ERASE_LINE = '\x1b[2K';
193
+
194
+ /**
195
+ * Braille-dot spinner frames.
196
+ *
197
+ * Provides smooth animation across most terminal emulators. The 10-frame
198
+ * sequence completes a full rotation of the braille clock pattern.
199
+ *
200
+ * @internal
201
+ */
202
+ const SPINNER_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'] as const;
203
+
204
+ /** @internal */ const SPINNER_INTERVAL_MS = 80;
205
+
206
+ /** Success symbol for terminal output. @internal */
207
+ const CHECK = '✓';
208
+
209
+ /** Failure symbol for terminal output. @internal */
210
+ const CROSS = '✗';
211
+
212
+ /** Filled segment of a progress bar. @internal */
213
+ const BAR_FILLED = '█';
214
+
215
+ /** Empty segment of a progress bar. @internal */
216
+ const BAR_EMPTY = '░';
217
+
218
+ /** Width of the progress bar in characters. @internal */
219
+ const BAR_WIDTH = 20;
220
+
221
+ /** Pulse width for indeterminate progress (number of filled segments). @internal */
222
+ const PULSE_WIDTH = 3;
223
+
224
+ /** Animation interval for indeterminate progress pulse (ms). @internal */
225
+ const PULSE_INTERVAL_MS = 80;
226
+
227
+ // --- TTY activity handles — animated mode (isTTY && !jsonMode)
228
+
229
+ /**
230
+ * TTY spinner handle — animated braille frames with ANSI line overwrite.
231
+ *
232
+ * Used in TTY environments (non-JSON mode). Renders a spinning indicator
233
+ * with configurable text, using `\r` + erase-line to overwrite in place.
234
+ * Hides the cursor during animation and restores it on any terminal method.
235
+ *
236
+ * Terminal methods (`succeed`, `fail`, `stop`) are idempotent — calling any
237
+ * of them after the handle is already stopped is a no-op.
238
+ *
239
+ * **Note:** If the process exits abnormally (e.g. `SIGKILL`) while a spinner
240
+ * is active, the cursor may remain hidden. Use {@link SpinnerHandle.wrap} to
241
+ * ensure cleanup on both success and failure paths.
242
+ *
243
+ * @internal
244
+ */
245
+ class TTYSpinnerHandle implements SpinnerHandle {
246
+ /** Whether the handle has been stopped (terminal state reached). */
247
+ private stopped = false;
248
+ /** Animation timer handle — cleared on any terminal method. */
249
+ private timer: unknown;
250
+ /** Current position in the braille frame sequence. */
251
+ private frameIndex = 0;
252
+ /** Current spinner text (mutable via `update()`). */
253
+ private text: string;
254
+
255
+ constructor(
256
+ text: string,
257
+ private readonly write: WriteFn,
258
+ ) {
259
+ this.text = text;
260
+ write(HIDE_CURSOR);
261
+ this.render();
262
+ this.timer = setInterval(() => {
263
+ this.frameIndex = (this.frameIndex + 1) % SPINNER_FRAMES.length;
264
+ this.render();
265
+ }, SPINNER_INTERVAL_MS);
266
+ }
267
+
268
+ /** Render the current frame + text, overwriting the current line. */
269
+ private render(): void {
270
+ const frame = SPINNER_FRAMES[this.frameIndex] ?? SPINNER_FRAMES[0];
271
+ this.write(`\r${ERASE_LINE}${frame} ${this.text}`);
272
+ }
273
+
274
+ /** Clear the animation timer, erase the line, and restore the cursor. */
275
+ private cleanup(): void {
276
+ if (this.timer !== undefined) {
277
+ clearInterval(this.timer);
278
+ this.timer = undefined;
279
+ }
280
+ this.write(`\r${ERASE_LINE}${SHOW_CURSOR}`);
281
+ }
282
+
283
+ update(text: string): void {
284
+ if (this.stopped) return;
285
+ this.text = text;
286
+ // Render immediately so the text change is visible before the next frame.
287
+ this.render();
288
+ }
289
+
290
+ succeed(text?: string): void {
291
+ if (this.stopped) return;
292
+ this.stopped = true;
293
+ this.cleanup();
294
+ if (text !== undefined) {
295
+ writeLine(this.write, `${CHECK} ${text}`);
296
+ }
297
+ }
298
+
299
+ fail(text?: string): void {
300
+ if (this.stopped) return;
301
+ this.stopped = true;
302
+ this.cleanup();
303
+ if (text !== undefined) {
304
+ writeLine(this.write, `${CROSS} ${text}`);
305
+ }
306
+ }
307
+
308
+ stop(): void {
309
+ if (this.stopped) return;
310
+ this.stopped = true;
311
+ this.cleanup();
312
+ }
313
+
314
+ async wrap<T>(
315
+ promise: Promise<T>,
316
+ options?: { readonly succeed?: string; readonly fail?: string },
317
+ ): Promise<T> {
318
+ try {
319
+ const value = await promise;
320
+ this.succeed(options?.succeed);
321
+ return value;
322
+ } catch (error: unknown) {
323
+ this.fail(options?.fail);
324
+ throw error;
325
+ }
326
+ }
327
+ }
328
+
329
+ /**
330
+ * TTY progress handle — bar rendering with ANSI line overwrite.
331
+ *
332
+ * Supports two modes:
333
+ * - **Determinate** (`total` provided) — renders `[████░░░░░░] 40% label`,
334
+ * re-rendered on each `increment()` / `update()` call. No timer.
335
+ * - **Indeterminate** (`total` omitted) — renders a pulsing highlight that
336
+ * bounces across the bar via `setInterval`.
337
+ *
338
+ * Terminal methods (`done`, `fail`) are idempotent — calling any of them
339
+ * after the handle is already stopped is a no-op.
340
+ *
341
+ * @internal
342
+ */
343
+ class TTYProgressHandle implements ProgressHandle {
344
+ /** Whether the handle has been stopped (terminal state reached). */
345
+ private stopped = false;
346
+ /** Animation timer for indeterminate mode — `undefined` in determinate mode. */
347
+ private timer: unknown;
348
+ /** Current progress value (units completed). */
349
+ private current = 0;
350
+ /** Total units of work (`undefined` = indeterminate mode). */
351
+ private readonly total: number | undefined;
352
+ /** Label displayed alongside the bar. */
353
+ private readonly label: string;
354
+ /** Pulse position for indeterminate animation (bouncing highlight). */
355
+ private pulsePos = 0;
356
+ /** Pulse direction: 1 = forward, -1 = backward (for bounce). */
357
+ private pulseDir: 1 | -1 = 1;
358
+
359
+ constructor(
360
+ opts: ProgressOptions,
361
+ private readonly write: WriteFn,
362
+ ) {
363
+ this.total = opts.total;
364
+ this.label = opts.label ?? '';
365
+ write(HIDE_CURSOR);
366
+ this.render();
367
+
368
+ // Only start animation timer for indeterminate mode.
369
+ if (this.total === undefined) {
370
+ this.timer = setInterval(() => {
371
+ this.advancePulse();
372
+ this.render();
373
+ }, PULSE_INTERVAL_MS);
374
+ }
375
+ }
376
+
377
+ /** Advance the indeterminate pulse position with bounce logic. */
378
+ private advancePulse(): void {
379
+ this.pulsePos += this.pulseDir;
380
+ // Bounce at boundaries: when the rightmost lit segment would exceed the bar.
381
+ if (this.pulsePos + PULSE_WIDTH > BAR_WIDTH) {
382
+ this.pulseDir = -1;
383
+ this.pulsePos = BAR_WIDTH - PULSE_WIDTH;
384
+ } else if (this.pulsePos < 0) {
385
+ this.pulseDir = 1;
386
+ this.pulsePos = 0;
387
+ }
388
+ }
389
+
390
+ /** Render the progress bar, overwriting the current line. */
391
+ private render(): void {
392
+ const bar =
393
+ this.total !== undefined ? this.renderDeterminate(this.total) : this.renderIndeterminate();
394
+ const suffix = this.label.length > 0 ? ` ${this.label}` : '';
395
+ this.write(`\r${ERASE_LINE}${bar}${suffix}`);
396
+ }
397
+
398
+ /** Render a determinate bar: `[████░░░░░░] 40%`. */
399
+ private renderDeterminate(total: number): string {
400
+ const ratio = total > 0 ? Math.max(0, Math.min(this.current / total, 1)) : 0;
401
+ const filled = Math.round(ratio * BAR_WIDTH);
402
+ const empty = BAR_WIDTH - filled;
403
+ const pct = Math.round(ratio * 100);
404
+ return `[${BAR_FILLED.repeat(filled)}${BAR_EMPTY.repeat(empty)}] ${String(pct)}%`;
405
+ }
406
+
407
+ /** Render an indeterminate bar: pulsing highlight bouncing across empty segments. */
408
+ private renderIndeterminate(): string {
409
+ let bar = '';
410
+ for (let i = 0; i < BAR_WIDTH; i++) {
411
+ bar += i >= this.pulsePos && i < this.pulsePos + PULSE_WIDTH ? BAR_FILLED : BAR_EMPTY;
412
+ }
413
+ return `[${bar}]`;
414
+ }
415
+
416
+ /** Clear the animation timer, erase the line, and restore the cursor. */
417
+ private cleanup(): void {
418
+ if (this.timer !== undefined) {
419
+ clearInterval(this.timer);
420
+ this.timer = undefined;
421
+ }
422
+ this.write(`\r${ERASE_LINE}${SHOW_CURSOR}`);
423
+ }
424
+
425
+ increment(n?: number): void {
426
+ if (this.stopped) return;
427
+ this.current += n ?? 1;
428
+ this.render();
429
+ }
430
+
431
+ update(value: number): void {
432
+ if (this.stopped) return;
433
+ this.current = value;
434
+ this.render();
435
+ }
436
+
437
+ done(text?: string): void {
438
+ if (this.stopped) return;
439
+ this.stopped = true;
440
+ this.cleanup();
441
+ if (text !== undefined) {
442
+ writeLine(this.write, `${CHECK} ${text}`);
443
+ }
444
+ }
445
+
446
+ fail(text?: string): void {
447
+ if (this.stopped) return;
448
+ this.stopped = true;
449
+ this.cleanup();
450
+ if (text !== undefined) {
451
+ writeLine(this.write, `${CROSS} ${text}`);
452
+ }
453
+ }
454
+ }
455
+
456
+ // --- Capture activity handles — testkit recording mode
457
+
458
+ /**
459
+ * Spinner handle that records lifecycle events to a shared `ActivityEvent[]`.
460
+ *
461
+ * Used by `createCaptureOutput()` so testkit can assert on spinner behaviour
462
+ * without polluting stdout/stderr arrays. Terminal methods are idempotent.
463
+ *
464
+ * @internal
465
+ */
466
+ class CaptureSpinnerHandle implements SpinnerHandle {
467
+ /** Whether the handle has been stopped (terminal state reached). */
468
+ private stopped = false;
469
+
470
+ constructor(
471
+ text: string,
472
+ private readonly events: ActivityEvent[],
473
+ ) {
474
+ events.push({ type: 'spinner:start', text });
475
+ }
476
+
477
+ update(text: string): void {
478
+ if (this.stopped) return;
479
+ this.events.push({ type: 'spinner:update', text });
480
+ }
481
+
482
+ succeed(text?: string): void {
483
+ if (this.stopped) return;
484
+ this.stopped = true;
485
+ this.events.push({ type: 'spinner:succeed', text: text ?? '' });
486
+ }
487
+
488
+ fail(text?: string): void {
489
+ if (this.stopped) return;
490
+ this.stopped = true;
491
+ this.events.push({ type: 'spinner:fail', text: text ?? '' });
492
+ }
493
+
494
+ stop(): void {
495
+ if (this.stopped) return;
496
+ this.stopped = true;
497
+ this.events.push({ type: 'spinner:stop' });
498
+ }
499
+
500
+ async wrap<T>(
501
+ promise: Promise<T>,
502
+ options?: { readonly succeed?: string; readonly fail?: string },
503
+ ): Promise<T> {
504
+ try {
505
+ const value = await promise;
506
+ this.succeed(options?.succeed);
507
+ return value;
508
+ } catch (error: unknown) {
509
+ this.fail(options?.fail);
510
+ throw error;
511
+ }
512
+ }
513
+ }
514
+
515
+ /**
516
+ * Progress handle that records lifecycle events to a shared `ActivityEvent[]`.
517
+ *
518
+ * Used by `createCaptureOutput()` so testkit can assert on progress behaviour
519
+ * without polluting stdout/stderr arrays. Terminal methods are idempotent.
520
+ *
521
+ * @internal
522
+ */
523
+ class CaptureProgressHandle implements ProgressHandle {
524
+ /** Whether the handle has been stopped (terminal state reached). */
525
+ private stopped = false;
526
+
527
+ constructor(
528
+ opts: ProgressOptions,
529
+ private readonly events: ActivityEvent[],
530
+ ) {
531
+ events.push({ type: 'progress:start', label: opts.label ?? '', total: opts.total });
532
+ }
533
+
534
+ increment(n?: number): void {
535
+ if (this.stopped) return;
536
+ this.events.push({ type: 'progress:increment', delta: n ?? 1 });
537
+ }
538
+
539
+ update(value: number): void {
540
+ if (this.stopped) return;
541
+ this.events.push({ type: 'progress:update', value });
542
+ }
543
+
544
+ done(text?: string): void {
545
+ if (this.stopped) return;
546
+ this.stopped = true;
547
+ this.events.push({ type: 'progress:done', text });
548
+ }
549
+
550
+ fail(text?: string): void {
551
+ if (this.stopped) return;
552
+ this.stopped = true;
553
+ this.events.push({ type: 'progress:fail', text });
554
+ }
555
+ }
556
+
557
+ // --- Exports
558
+
559
+ export {
560
+ CaptureProgressHandle,
561
+ CaptureSpinnerHandle,
562
+ noopProgressHandle,
563
+ noopSpinnerHandle,
564
+ StaticProgressHandle,
565
+ StaticSpinnerHandle,
566
+ TTYProgressHandle,
567
+ TTYSpinnerHandle,
568
+ };
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Shared runtime-value formatting for human-readable output.
3
+ *
4
+ * Used by help text and table rendering so default values and structured cells
5
+ * stringify consistently across the CLI surface.
6
+ *
7
+ * @module dreamcli/core/output/display-value
8
+ * @internal
9
+ */
10
+
11
+ /**
12
+ * Format an unknown runtime value for human-readable output.
13
+ *
14
+ * @param value - The value to format (any type).
15
+ * @returns A string representation suitable for table cells and help text.
16
+ */
17
+ function formatDisplayValue(value: unknown): string {
18
+ if (value === null || value === undefined) return '';
19
+
20
+ if (
21
+ typeof value === 'string' ||
22
+ typeof value === 'number' ||
23
+ typeof value === 'boolean' ||
24
+ typeof value === 'bigint' ||
25
+ typeof value === 'symbol'
26
+ ) {
27
+ return String(value);
28
+ }
29
+
30
+ if (value instanceof Date) {
31
+ if (Number.isNaN(value.getTime())) {
32
+ return 'Invalid Date';
33
+ }
34
+ return value.toISOString();
35
+ }
36
+
37
+ if (typeof value === 'function') {
38
+ return value.name.length > 0 ? `[Function: ${value.name}]` : '[Function]';
39
+ }
40
+
41
+ try {
42
+ return JSON.stringify(value) ?? '[unserializable]';
43
+ } catch {
44
+ return '[unserializable]';
45
+ }
46
+ }
47
+
48
+ export { formatDisplayValue };