@kjanat/dreamcli 3.0.0-rc.1 → 3.0.0-rc.11

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 (194) hide show
  1. package/CHANGELOG.md +227 -1
  2. package/dist/core/cli/dispatch.d.mts +6 -5
  3. package/dist/core/cli/dispatch.mjs +205 -1
  4. package/dist/core/cli/help-links.d.mts +0 -1
  5. package/dist/core/cli/help-links.mjs +41 -1
  6. package/dist/core/cli/index.d.mts +81 -8
  7. package/dist/core/cli/index.mjs +945 -1
  8. package/dist/core/cli/planner.d.mts +5 -1
  9. package/dist/core/cli/planner.mjs +300 -1
  10. package/dist/core/cli/plugin.d.mts +1 -1
  11. package/dist/core/cli/plugin.mjs +41 -1
  12. package/dist/core/cli/propagate.d.mts +1 -1
  13. package/dist/core/cli/propagate.mjs +57 -1
  14. package/dist/core/cli/root-help.d.mts +2 -1
  15. package/dist/core/cli/root-help.mjs +226 -4
  16. package/dist/core/cli/root-surface.d.mts +12 -1
  17. package/dist/core/cli/root-surface.mjs +28 -1
  18. package/dist/core/cli/runtime-preflight.d.mts +14 -2
  19. package/dist/core/cli/runtime-preflight.mjs +169 -1
  20. package/dist/core/completion/index.d.mts +0 -1
  21. package/dist/core/completion/index.mjs +90 -1
  22. package/dist/core/completion/shells/bash.d.mts +0 -1
  23. package/dist/core/completion/shells/bash.mjs +308 -3
  24. package/dist/core/completion/shells/fish.d.mts +0 -1
  25. package/dist/core/completion/shells/fish.mjs +162 -2
  26. package/dist/core/completion/shells/powershell.d.mts +0 -1
  27. package/dist/core/completion/shells/powershell.mjs +358 -2
  28. package/dist/core/completion/shells/shared.d.mts +13 -2
  29. package/dist/core/completion/shells/shared.mjs +176 -1
  30. package/dist/core/completion/shells/zsh.d.mts +0 -1
  31. package/dist/core/completion/shells/zsh.mjs +251 -2
  32. package/dist/core/config/index.d.mts +2 -3
  33. package/dist/core/config/index.mjs +246 -1
  34. package/dist/core/config/package-json.d.mts +27 -4
  35. package/dist/core/config/package-json.mjs +386 -3
  36. package/dist/core/errors/index.d.mts +3 -3
  37. package/dist/core/errors/index.mjs +87 -1
  38. package/dist/core/execution/index.d.mts +0 -1
  39. package/dist/core/execution/index.mjs +201 -1
  40. package/dist/core/help/ansi.d.mts +11 -5
  41. package/dist/core/help/ansi.mjs +121 -2
  42. package/dist/core/help/index.d.mts +22 -3
  43. package/dist/core/help/index.mjs +341 -7
  44. package/dist/core/help/theme.d.mts +68 -0
  45. package/dist/core/help/theme.mjs +46 -0
  46. package/dist/core/json-schema/index.d.mts +15 -2
  47. package/dist/core/json-schema/index.mjs +536 -12
  48. package/dist/core/json-schema/meta-descriptions.generated.d.mts +55 -38
  49. package/dist/core/json-schema/meta-descriptions.generated.mjs +102 -28
  50. package/dist/core/output/activity.d.mts +0 -1
  51. package/dist/core/output/activity.mjs +452 -1
  52. package/dist/core/output/bind.mjs +56 -1
  53. package/dist/core/output/contracts.d.mts +4 -5
  54. package/dist/core/output/contracts.mjs +57 -1
  55. package/dist/core/output/display-value.mjs +32 -1
  56. package/dist/core/output/index.d.mts +21 -1
  57. package/dist/core/output/index.mjs +442 -2
  58. package/dist/core/output/renderers.d.mts +0 -1
  59. package/dist/core/output/renderers.mjs +46 -1
  60. package/dist/core/output/writer.mjs +12 -1
  61. package/dist/core/parse/index.d.mts +40 -7
  62. package/dist/core/parse/index.mjs +727 -1
  63. package/dist/core/prompt/index.d.mts +1 -1
  64. package/dist/core/prompt/index.mjs +348 -6
  65. package/dist/core/resolve/args.d.mts +1 -1
  66. package/dist/core/resolve/args.mjs +105 -1
  67. package/dist/core/resolve/coerce.d.mts +1 -1
  68. package/dist/core/resolve/coerce.mjs +336 -1
  69. package/dist/core/resolve/config.mjs +19 -1
  70. package/dist/core/resolve/contracts.d.mts +9 -4
  71. package/dist/core/resolve/errors.d.mts +0 -1
  72. package/dist/core/resolve/errors.mjs +140 -2
  73. package/dist/core/resolve/flags.d.mts +7 -2
  74. package/dist/core/resolve/flags.mjs +251 -1
  75. package/dist/core/resolve/index.d.mts +2 -2
  76. package/dist/core/resolve/index.mjs +85 -1
  77. package/dist/core/resolve/property.d.mts +4 -2
  78. package/dist/core/resolve/property.mjs +53 -1
  79. package/dist/core/schema/activity.d.mts +31 -11
  80. package/dist/core/schema/arg.d.mts +3 -4
  81. package/dist/core/schema/arg.mjs +463 -1
  82. package/dist/core/schema/command.d.mts +26 -6
  83. package/dist/core/schema/command.mjs +726 -1
  84. package/dist/core/schema/flag.d.mts +485 -19
  85. package/dist/core/schema/flag.mjs +705 -1
  86. package/dist/core/schema/index.d.mts +4 -2
  87. package/dist/core/schema/middleware.d.mts +4 -3
  88. package/dist/core/schema/middleware.mjs +41 -1
  89. package/dist/core/schema/number-constraints.mjs +60 -1
  90. package/dist/core/schema/prompt.d.mts +6 -3
  91. package/dist/core/schema/run.d.mts +20 -1
  92. package/dist/core/schema/string-constraints.d.mts +97 -0
  93. package/dist/core/schema/string-constraints.mjs +69 -0
  94. package/dist/core/schema/value-parsers.d.mts +78 -0
  95. package/dist/core/schema/value-parsers.mjs +142 -0
  96. package/dist/core/schema-dsl/runtime.mjs +271 -2
  97. package/dist/core/schema-dsl/to-json-schema.d.mts +0 -1
  98. package/dist/core/schema-dsl/to-json-schema.mjs +74 -1
  99. package/dist/core/testkit/index.d.mts +0 -31
  100. package/dist/core/testkit/index.mjs +83 -1
  101. package/dist/index.d.mts +11 -6
  102. package/dist/index.mjs +22 -1
  103. package/dist/runtime/adapter.d.mts +38 -2
  104. package/dist/runtime/adapter.mjs +87 -1
  105. package/dist/runtime/auto.d.mts +2 -3
  106. package/dist/runtime/auto.mjs +45 -1
  107. package/dist/runtime/deno.d.mts +24 -5
  108. package/dist/runtime/deno.mjs +262 -2
  109. package/dist/runtime/detect.mjs +45 -1
  110. package/dist/runtime/index.d.mts +3 -4
  111. package/dist/runtime/node.d.mts +8 -2
  112. package/dist/runtime/node.mjs +220 -2
  113. package/dist/runtime/paths.mjs +48 -1
  114. package/dist/runtime.d.mts +4 -4
  115. package/dist/runtime.mjs +6 -1
  116. package/dist/strings.mjs +22 -1
  117. package/dist/testkit.d.mts +1 -0
  118. package/dist/testkit.mjs +5 -1
  119. package/dist/version.d.mts +7 -3
  120. package/dist/version.mjs +7 -1
  121. package/dreamcli.schema.json +36 -7
  122. package/package.json +45 -42
  123. package/dist/runtime/bun.d.mts +0 -28
  124. package/dist/runtime/bun.mjs +0 -1
  125. package/src/core/cli/dispatch.ts +0 -355
  126. package/src/core/cli/help-links.ts +0 -82
  127. package/src/core/cli/index.ts +0 -1614
  128. package/src/core/cli/planner.ts +0 -656
  129. package/src/core/cli/plugin.ts +0 -117
  130. package/src/core/cli/propagate.ts +0 -97
  131. package/src/core/cli/root-help.ts +0 -342
  132. package/src/core/cli/root-surface.ts +0 -87
  133. package/src/core/cli/runtime-preflight.ts +0 -456
  134. package/src/core/completion/index.ts +0 -138
  135. package/src/core/completion/shells/bash.ts +0 -459
  136. package/src/core/completion/shells/fish.ts +0 -259
  137. package/src/core/completion/shells/powershell.ts +0 -439
  138. package/src/core/completion/shells/shared.ts +0 -310
  139. package/src/core/completion/shells/zsh.ts +0 -381
  140. package/src/core/config/index.ts +0 -417
  141. package/src/core/config/package-json.ts +0 -560
  142. package/src/core/errors/index.ts +0 -193
  143. package/src/core/execution/index.ts +0 -265
  144. package/src/core/help/ansi.ts +0 -144
  145. package/src/core/help/index.ts +0 -563
  146. package/src/core/json-schema/index.ts +0 -910
  147. package/src/core/json-schema/meta-descriptions.generated.ts +0 -202
  148. package/src/core/output/activity.ts +0 -575
  149. package/src/core/output/bind.ts +0 -59
  150. package/src/core/output/contracts.ts +0 -194
  151. package/src/core/output/display-value.ts +0 -48
  152. package/src/core/output/index.ts +0 -704
  153. package/src/core/output/renderers.ts +0 -125
  154. package/src/core/output/writer.ts +0 -46
  155. package/src/core/parse/index.ts +0 -742
  156. package/src/core/prompt/index.ts +0 -623
  157. package/src/core/resolve/args.ts +0 -144
  158. package/src/core/resolve/coerce.ts +0 -500
  159. package/src/core/resolve/config.ts +0 -26
  160. package/src/core/resolve/contracts.ts +0 -135
  161. package/src/core/resolve/errors.ts +0 -227
  162. package/src/core/resolve/flags.ts +0 -269
  163. package/src/core/resolve/index.ts +0 -108
  164. package/src/core/resolve/property.ts +0 -99
  165. package/src/core/schema/activity.ts +0 -240
  166. package/src/core/schema/arg.ts +0 -841
  167. package/src/core/schema/command.ts +0 -1500
  168. package/src/core/schema/flag.ts +0 -917
  169. package/src/core/schema/index.ts +0 -96
  170. package/src/core/schema/middleware.ts +0 -171
  171. package/src/core/schema/number-constraints.ts +0 -153
  172. package/src/core/schema/prompt.ts +0 -171
  173. package/src/core/schema/run.ts +0 -198
  174. package/src/core/schema-dsl/index.ts +0 -109
  175. package/src/core/schema-dsl/parse.ts +0 -262
  176. package/src/core/schema-dsl/runtime.ts +0 -609
  177. package/src/core/schema-dsl/to-json-schema.ts +0 -102
  178. package/src/core/testkit/index.ts +0 -147
  179. package/src/index.ts +0 -181
  180. package/src/runtime/adapter.ts +0 -303
  181. package/src/runtime/auto.ts +0 -86
  182. package/src/runtime/bun.ts +0 -48
  183. package/src/runtime/deno.ts +0 -367
  184. package/src/runtime/detect.ts +0 -105
  185. package/src/runtime/index.ts +0 -21
  186. package/src/runtime/node-builtins.d.ts +0 -27
  187. package/src/runtime/node.ts +0 -289
  188. package/src/runtime/paths.ts +0 -64
  189. package/src/runtime/support.ts +0 -77
  190. package/src/runtime.ts +0 -31
  191. package/src/schema.ts +0 -16
  192. package/src/strings.ts +0 -34
  193. package/src/testkit.ts +0 -25
  194. package/src/version.ts +0 -20
@@ -1,704 +0,0 @@
1
- /**
2
- * Output channel (out object) for command handlers.
3
- *
4
- * Provides a structured output abstraction that handlers use instead of
5
- * raw `console.log`. The channel respects TTY vs piped contexts and
6
- * supports verbosity levels (quiet mode suppresses `info`).
7
- *
8
- * The {@linkcode Out} interface (the contract handlers depend on) lives in
9
- * `src/core/schema/command.ts`. This module provides the implementation.
10
- *
11
- * @module dreamcli/core/output
12
- */
13
-
14
- import type {
15
- ActivityEvent,
16
- ProgressHandle,
17
- ProgressOptions,
18
- SpinnerHandle,
19
- SpinnerOptions,
20
- TableColumn,
21
- TableOptions,
22
- } from '#internals/core/schema/activity.ts';
23
- import type { Out } from '#internals/core/schema/command.ts';
24
- import {
25
- CaptureProgressHandle,
26
- CaptureSpinnerHandle,
27
- noopProgressHandle,
28
- noopSpinnerHandle,
29
- StaticProgressHandle,
30
- StaticSpinnerHandle,
31
- TTYProgressHandle,
32
- TTYSpinnerHandle,
33
- } from './activity.ts';
34
- import { bindMethods } from './bind.ts';
35
- import type { OutputPolicy, Verbosity } from './contracts.ts';
36
- import {
37
- resolveOutputPolicy,
38
- resolveProgressPolicy,
39
- resolveSpinnerPolicy,
40
- resolveTableFormat,
41
- resolveTableTextStream,
42
- resolveTextStream,
43
- shouldEmitInfo,
44
- } from './contracts.ts';
45
- import { formatDisplayValue } from './display-value.ts';
46
- import {
47
- createProgressHandleFromPolicy,
48
- createSpinnerHandleFromPolicy,
49
- resolveWriterForStream,
50
- } from './renderers.ts';
51
- import type { WriteFn } from './writer.ts';
52
- import { writeLine } from './writer.ts';
53
-
54
- // --- Options
55
-
56
- /**
57
- * Configuration for creating an output channel.
58
- *
59
- * Every field is optional — sensible defaults are applied when omitted.
60
- */
61
- interface OutputOptions {
62
- /**
63
- * Writer for stdout-bound messages (`log`, `info`, `json`).
64
- * Defaults to `process.stdout.write` when running in Node/Bun.
65
- */
66
- readonly stdout?: WriteFn;
67
-
68
- /**
69
- * Writer for stderr-bound messages (`warn`, `error`).
70
- * In JSON mode, `log` and `info` are also redirected here so that
71
- * stdout contains only structured JSON output.
72
- * Defaults to `process.stderr.write` when running in Node/Bun.
73
- */
74
- readonly stderr?: WriteFn;
75
-
76
- /**
77
- * Whether stdout is connected to a TTY.
78
- * When `false`, output may omit ANSI codes and decorations.
79
- * Defaults to `false` (safe default — non-TTY until proven otherwise).
80
- */
81
- readonly isTTY?: boolean;
82
-
83
- /**
84
- * Verbosity level.
85
- * - `'normal'` (default) — emit all messages
86
- * - `'quiet'` — suppress `info` messages
87
- */
88
- readonly verbosity?: Verbosity;
89
-
90
- /**
91
- * Enable JSON output mode.
92
- *
93
- * When `true`, `log` and `info` messages are redirected to stderr
94
- * so that stdout is reserved exclusively for structured `json()` output.
95
- * `warn` and `error` continue to write to stderr as normal.
96
- *
97
- * @defaultValue `false`
98
- */
99
- readonly jsonMode?: boolean;
100
- }
101
-
102
- // --- Resolved options (all fields required, filled from defaults)
103
-
104
- /** Fully resolved output options with no optional fields. */
105
- interface ResolvedOutputOptions {
106
- readonly stdout: WriteFn;
107
- readonly stderr: WriteFn;
108
- readonly isTTY: boolean;
109
- readonly verbosity: Verbosity;
110
- readonly jsonMode: boolean;
111
- }
112
-
113
- /**
114
- * A noop writer used as fallback when no writer is provided and
115
- * platform defaults aren't available. Silently discards output.
116
- */
117
- const noopWrite: WriteFn = () => {};
118
-
119
- const requestedExitCodes = new WeakMap<Out, number>();
120
-
121
- function validateExitCode(code: number): number {
122
- if (!Number.isInteger(code) || code < 0 || code > 255) {
123
- throw new RangeError('Exit code must be an integer from 0 to 255');
124
- }
125
- return code;
126
- }
127
-
128
- function setRequestedExitCode(out: Out, code: number): void {
129
- requestedExitCodes.set(out, validateExitCode(code));
130
- }
131
-
132
- function getRequestedExitCode(out: Out): number | undefined {
133
- return requestedExitCodes.get(out);
134
- }
135
-
136
- function clearRequestedExitCode(out: Out): void {
137
- requestedExitCodes.delete(out);
138
- }
139
-
140
- /** Merge user-supplied options with defaults. */
141
- function resolveOptions(options?: OutputOptions): ResolvedOutputOptions {
142
- return {
143
- stdout: options?.stdout ?? noopWrite,
144
- stderr: options?.stderr ?? noopWrite,
145
- isTTY: options?.isTTY ?? false,
146
- verbosity: options?.verbosity ?? 'normal',
147
- jsonMode: options?.jsonMode ?? false,
148
- };
149
- }
150
-
151
- // --- OutputChannel — the concrete Out implementation
152
-
153
- /**
154
- * Concrete implementation of the {@linkcode Out} interface.
155
- *
156
- * Routes messages to the appropriate writer (stdout vs stderr) and
157
- * respects the configured verbosity level.
158
- *
159
- * Handlers interact with this via the {@linkcode Out} interface — they never see
160
- * {@linkcode OutputChannel} directly, which keeps the coupling minimal.
161
- * Prefer {@link createOutput} unless you are extending the output layer.
162
- *
163
- * @internal
164
- */
165
- class OutputChannel implements Out {
166
- /** @internal Resolved configuration. */
167
- readonly options: ResolvedOutputOptions;
168
-
169
- /** Semantic output policy snapshot shared by routing helpers. */
170
- readonly policy: OutputPolicy;
171
-
172
- /** Whether JSON output mode is active. */
173
- readonly jsonMode: boolean;
174
-
175
- /**
176
- * Whether stdout is connected to a TTY.
177
- *
178
- * When `jsonMode` is active, this reflects the underlying TTY status
179
- * but decorative output should still be suppressed (jsonMode takes
180
- * precedence).
181
- */
182
- readonly isTTY: boolean;
183
-
184
- constructor(options: ResolvedOutputOptions) {
185
- this.options = options;
186
- this.policy = resolveOutputPolicy(options);
187
- this.jsonMode = options.jsonMode;
188
- this.isTTY = options.isTTY;
189
-
190
- // Bind methods to the instance so they keep working when destructured
191
- // off `out` (e.g. `const { log } = out`). Resolves subclass overrides
192
- // (spinner/progress in CaptureOutputChannel) automatically.
193
- bindMethods(this);
194
- }
195
-
196
- /**
197
- * Write to stdout (normal output). Always emitted.
198
- *
199
- * In JSON mode, redirected to stderr so stdout is reserved for
200
- * structured `json()` output only.
201
- */
202
- log(message: string): void {
203
- const writer = resolveWriterForStream(this.options, resolveTextStream(this.policy));
204
- writeLine(writer, message);
205
- }
206
-
207
- /**
208
- * Informational message to stdout.
209
- * Suppressed when verbosity is `'quiet'`.
210
- *
211
- * In JSON mode, redirected to stderr.
212
- */
213
- info(message: string): void {
214
- if (!shouldEmitInfo(this.policy)) return;
215
- const writer = resolveWriterForStream(this.options, resolveTextStream(this.policy));
216
- writeLine(writer, message);
217
- }
218
-
219
- /** Warning to stderr. Always emitted. */
220
- warn(message: string): void {
221
- writeLine(this.options.stderr, message);
222
- }
223
-
224
- /** Error to stderr. Always emitted. */
225
- error(message: string): void {
226
- writeLine(this.options.stderr, message);
227
- }
228
-
229
- /** Request a successful-process exit code without writing error output. */
230
- setExitCode(code: number): void {
231
- setRequestedExitCode(this, code);
232
- }
233
-
234
- /**
235
- * Emit a structured JSON value to stdout.
236
- *
237
- * Serialises `value` with `JSON.stringify` and writes to stdout
238
- * regardless of JSON mode — `json()` always targets stdout.
239
- */
240
- json(value: unknown): void {
241
- writeLine(this.options.stdout, JSON.stringify(value));
242
- }
243
-
244
- /**
245
- * Render tabular data.
246
- *
247
- * Default behavior matches the current output mode:
248
- * - normal mode → text table to stdout
249
- * - jsonMode → JSON array to stdout
250
- *
251
- * Per-call options can force text/json rendering and route text tables to
252
- * stdout or stderr.
253
- */
254
- table<T extends Record<string, unknown>>(rows: readonly T[], options: TableOptions): void;
255
- table<T extends Record<string, unknown>>(
256
- rows: readonly T[],
257
- columns?: readonly TableColumn<T>[],
258
- options?: TableOptions,
259
- ): void;
260
- table<T extends Record<string, unknown>>(
261
- rows: readonly T[],
262
- columnsOrOptions?: readonly TableColumn<T>[] | TableOptions,
263
- options?: TableOptions,
264
- ): void {
265
- const { columns, options: tableOptions } = resolveTableArgs(columnsOrOptions, options);
266
- const format = resolveTableFormat(this.policy, tableOptions);
267
- const resolved = columns ?? inferColumns(rows);
268
-
269
- if (format === 'json') {
270
- this.json(projectTableRows(rows, resolved));
271
- return;
272
- }
273
-
274
- const text = formatTable(rows, resolved);
275
- if (text.length === 0) return;
276
-
277
- writeLine(resolveTextTableWriter(this.options, this.policy, format, tableOptions), text);
278
- }
279
-
280
- // ----- Active handle tracking -----
281
- //
282
- // At most one spinner or progress handle may be active at a time. When a
283
- // new one is created while another is running, the previous one is
284
- // implicitly stopped to avoid garbled terminal output.
285
-
286
- /**
287
- * Cleanup callback for the currently active spinner/progress handle.
288
- *
289
- * Set to `undefined` when no handle is active. The callback calls the
290
- * appropriate terminal method (`.stop()` for spinners, `.done()` for
291
- * progress) on the previous handle.
292
- *
293
- * @internal
294
- */
295
- private activeCleanup: (() => void) | undefined;
296
-
297
- /**
298
- * Stop the currently active spinner/progress handle (if any).
299
- *
300
- * Called internally before creating a new handle to prevent overlap,
301
- * and externally after handler execution to clean up leaked timers.
302
- * Idempotent (safe to call when no handle is active).
303
- */
304
- stopActive(): void {
305
- if (this.activeCleanup !== undefined) {
306
- this.activeCleanup();
307
- this.activeCleanup = undefined;
308
- }
309
- }
310
-
311
- /**
312
- * Create a spinner handle.
313
- *
314
- * Mode dispatch:
315
- * - `jsonMode` → noop (structured output only, spinners suppressed)
316
- * - `isTTY` → animated TTY spinner (braille frames, ANSI overwrite)
317
- * - `!isTTY && fallback: 'static'` → plain text at lifecycle boundaries
318
- * - `!isTTY && fallback: 'silent'` (default) → noop
319
- *
320
- * All activity output (transient frames, terminal messages) routes to
321
- * stderr so stdout remains clean for structured data and piping.
322
- *
323
- * If another spinner or progress handle is active, it is implicitly
324
- * stopped before the new one starts.
325
- *
326
- * @virtual
327
- */
328
- spinner(text: string, options?: SpinnerOptions): SpinnerHandle {
329
- const policy = resolveSpinnerPolicy(this.policy, options?.fallback ?? 'silent');
330
- const rendered = createSpinnerHandleFromPolicy(policy, text, this.options.stderr);
331
-
332
- if (rendered.cleanup === undefined) {
333
- return rendered.handle;
334
- }
335
-
336
- // Stop any active handle before creating a new one.
337
- this.stopActive();
338
- this.activeCleanup = rendered.cleanup;
339
- return rendered.handle;
340
- }
341
-
342
- /**
343
- * Create a progress handle.
344
- *
345
- * Mode dispatch:
346
- * - `jsonMode` → noop (structured output only, progress suppressed)
347
- * - `isTTY` → animated TTY progress bar (determinate or indeterminate)
348
- * - `!isTTY && fallback: 'static'` → plain text at lifecycle boundaries
349
- * - `!isTTY && fallback: 'silent'` (default) → noop
350
- *
351
- * All activity output (transient frames, terminal messages) routes to
352
- * stderr so stdout remains clean for structured data and piping.
353
- *
354
- * If another spinner or progress handle is active, it is implicitly
355
- * stopped before the new one starts.
356
- *
357
- * @virtual
358
- */
359
- progress(opts: ProgressOptions): ProgressHandle {
360
- const policy = resolveProgressPolicy(this.policy, opts.fallback ?? 'silent');
361
- const rendered = createProgressHandleFromPolicy(policy, opts, this.options.stderr);
362
-
363
- if (rendered.cleanup === undefined) {
364
- return rendered.handle;
365
- }
366
-
367
- // Stop any active handle before creating a new one.
368
- this.stopActive();
369
- this.activeCleanup = rendered.cleanup;
370
- return rendered.handle;
371
- }
372
- }
373
-
374
- // --- CaptureOutputChannel — testkit subclass that records activity events
375
-
376
- /**
377
- * Output channel variant that returns capture handles for spinner/progress.
378
- *
379
- * Extends {@linkcode OutputChannel} to override `spinner()` and `progress()`, routing
380
- * activity events into a shared {@linkcode ActivityEvent | ActivityEvent[]} for testkit assertion.
381
- * Text output (log/info/warn/error) is handled by the parent class.
382
- *
383
- * @internal
384
- */
385
- class CaptureOutputChannel extends OutputChannel {
386
- constructor(
387
- options: ResolvedOutputOptions,
388
- private readonly activity: ActivityEvent[],
389
- ) {
390
- super(options);
391
- }
392
-
393
- /**
394
- * Return a {@link CaptureSpinnerHandle} that records events into the activity log.
395
- * @override
396
- */
397
- override spinner(text: string, _options?: SpinnerOptions): SpinnerHandle {
398
- return new CaptureSpinnerHandle(text, this.activity);
399
- }
400
-
401
- /**
402
- * Return a {@link CaptureProgressHandle} that records events into the activity log.
403
- * @override
404
- */
405
- override progress(opts: ProgressOptions): ProgressHandle {
406
- return new CaptureProgressHandle(opts, this.activity);
407
- }
408
- }
409
-
410
- // --- Table formatting
411
-
412
- /**
413
- * Infer column descriptors from the keys of the first row.
414
- *
415
- * When no explicit columns are provided, all keys from the first row
416
- * become columns in insertion order. This is a convenience — callers
417
- * who need stable ordering should provide explicit columns.
418
- *
419
- * @param rows - Data rows to derive columns from.
420
- * @returns Column descriptors, one per key of the first row (empty if `rows` is empty).
421
- */
422
- function inferColumns<T extends Record<string, unknown>>(
423
- rows: readonly T[],
424
- ): readonly TableColumn<T>[] {
425
- const first = rows[0];
426
- if (first === undefined) return [];
427
- return Object.keys(first).map((key) => ({ key: key as keyof T & string }));
428
- }
429
-
430
- /**
431
- * Type guard: is `value` a {@link TableColumn} array (not {@link TableOptions})?
432
- *
433
- * @param value - The ambiguous argument to discriminate.
434
- * @returns `true` when `value` is a column descriptor array.
435
- */
436
- function isTableColumns<T extends Record<string, unknown>>(
437
- value: readonly TableColumn<T>[] | TableOptions | undefined,
438
- ): value is readonly TableColumn<T>[] {
439
- return Array.isArray(value);
440
- }
441
-
442
- /**
443
- * Disambiguate the overloaded `table()` arguments.
444
- *
445
- * @param columnsOrOptions - Either column descriptors or table options (from the 2-arg overload).
446
- * @param options - Explicit table options (from the 3-arg overload).
447
- * @returns Separated `columns` and `options`, each possibly `undefined`.
448
- */
449
- function resolveTableArgs<T extends Record<string, unknown>>(
450
- columnsOrOptions?: readonly TableColumn<T>[] | TableOptions,
451
- options?: TableOptions,
452
- ): {
453
- readonly columns: readonly TableColumn<T>[] | undefined;
454
- readonly options: TableOptions | undefined;
455
- } {
456
- if (options !== undefined) {
457
- return {
458
- columns: isTableColumns(columnsOrOptions) ? columnsOrOptions : undefined,
459
- options,
460
- };
461
- }
462
-
463
- if (isTableColumns(columnsOrOptions)) {
464
- return { columns: columnsOrOptions, options };
465
- }
466
-
467
- return { columns: undefined, options: columnsOrOptions };
468
- }
469
-
470
- /**
471
- * Keep only the keys listed in `columns`, preserving column order.
472
- *
473
- * @param rows - Source data rows.
474
- * @param columns - Column descriptors controlling which keys to retain.
475
- * @returns Projected rows containing only the specified keys.
476
- */
477
- function projectTableRows<T extends Record<string, unknown>>(
478
- rows: readonly T[],
479
- columns: readonly TableColumn<T>[],
480
- ): Record<string, unknown>[] {
481
- return rows.map((row) => Object.fromEntries(columns.map((c) => [c.key, row[c.key]])));
482
- }
483
-
484
- /**
485
- * Determine the concrete table format (`'text'` or `'json'`).
486
- *
487
- * Resolves `'auto'` / `undefined` by falling back to the channel's `jsonMode`.
488
- *
489
- * @param jsonMode - Whether the channel is in JSON output mode.
490
- * @param options - Per-call table options (may specify an explicit format).
491
- * @returns `'text'` or `'json'`.
492
- */
493
- /**
494
- * Pick the {@link WriteFn} for a text-mode table.
495
- *
496
- * Respects `tableOptions.stream` when present; otherwise falls back to
497
- * the channel's default policy-owned text stream.
498
- *
499
- * @param options - Resolved channel options.
500
- * @param format - Resolved table format.
501
- * @param tableOptions - Per-call table options (may specify a stream override).
502
- * @returns The writer to use.
503
- */
504
- function resolveTextTableWriter(
505
- options: ResolvedOutputOptions,
506
- policy: OutputPolicy,
507
- format: 'text' | 'json',
508
- tableOptions?: TableOptions,
509
- ): WriteFn {
510
- if (format === 'json') {
511
- return options.stdout;
512
- }
513
-
514
- return resolveWriterForStream(options, resolveTableTextStream(policy, tableOptions));
515
- }
516
-
517
- /**
518
- * Convert a cell value to a display string.
519
- *
520
- * - `null` / `undefined` → `''`
521
- * - Primitives → `String(value)`
522
- * - Objects / arrays → JSON
523
- *
524
- * @param value - The raw cell value.
525
- * @returns Display string for the cell.
526
- */
527
- function cellToString(value: unknown): string {
528
- return formatDisplayValue(value);
529
- }
530
-
531
- /**
532
- * Format rows as an aligned text table.
533
- *
534
- * Returns the full table string (without trailing newline — the caller
535
- * adds that via `writeLine`). Returns `''` when rows is empty.
536
- *
537
- * Column widths are computed as the max of header and all cell values.
538
- * Cells are left-aligned, padded with spaces. Columns are separated by
539
- * two spaces.
540
- *
541
- * @param rows - Data rows to render.
542
- * @param columns - Column descriptors controlling key, header, and order.
543
- * @returns The formatted table string, or `''` when there is nothing to render.
544
- */
545
- function formatTable<T extends Record<string, unknown>>(
546
- rows: readonly T[],
547
- columns: readonly TableColumn<T>[],
548
- ): string {
549
- if (rows.length === 0 || columns.length === 0) return '';
550
-
551
- const SEPARATOR = ' ';
552
-
553
- // Resolve headers
554
- const headers = columns.map((c) => c.header ?? c.key);
555
-
556
- // Convert all cells to strings
557
- const cellGrid: string[][] = rows.map((row) => columns.map((c) => cellToString(row[c.key])));
558
-
559
- // Compute column widths
560
- const widths: number[] = headers.map((h, i) => {
561
- let max = h.length;
562
- for (const row of cellGrid) {
563
- const cell = row[i];
564
- if (cell !== undefined && cell.length > max) {
565
- max = cell.length;
566
- }
567
- }
568
- return max;
569
- });
570
-
571
- // Build header line
572
- const headerLine = headers.map((h, i) => h.padEnd(widths[i] ?? 0)).join(SEPARATOR);
573
-
574
- // Build separator line (dashes under each column)
575
- const separatorLine = widths.map((w) => '-'.repeat(w)).join(SEPARATOR);
576
-
577
- // Build data lines
578
- const dataLines = cellGrid.map((row) =>
579
- row.map((cell, i) => cell.padEnd(widths[i] ?? 0)).join(SEPARATOR),
580
- );
581
-
582
- return [headerLine, separatorLine, ...dataLines].join('\n');
583
- }
584
-
585
- // --- Factory
586
-
587
- /**
588
- * Create an output channel.
589
- *
590
- * Low-level factory: action handlers already receive `out` automatically from
591
- * `cli()`, `.execute()`, and `runCommand()`. Call `createOutput()` when you
592
- * are embedding DreamCLI primitives into a custom runtime or need a standalone
593
- * output implementation outside the normal command pipeline.
594
- *
595
- * @param options - Optional configuration. When omitted, output is
596
- * discarded (useful for silent test runs). Pass `stdout`/`stderr`
597
- * writers to direct output somewhere useful.
598
- *
599
- * @returns An {@link Out} instance backed by an {@link OutputChannel}.
600
- *
601
- * @example
602
- * ```ts
603
- * // Production (wired by the runtime adapter)
604
- * const out = createOutput({
605
- * stdout: (s) => process.stdout.write(s),
606
- * stderr: (s) => process.stderr.write(s),
607
- * isTTY: process.stdout.isTTY === true,
608
- * });
609
- *
610
- * // Test (capture output)
611
- * const lines: string[] = [];
612
- * const out = createOutput({
613
- * stdout: (s) => lines.push(s),
614
- * stderr: (s) => lines.push(s),
615
- * });
616
- * ```
617
- */
618
- function createOutput(options?: OutputOptions): Out {
619
- return new OutputChannel(resolveOptions(options));
620
- }
621
-
622
- // --- Test helper — captures output into arrays
623
-
624
- /** Captured output from a `createCaptureOutput` instance. */
625
- interface CapturedOutput {
626
- /**
627
- * Lines written to stdout.
628
- *
629
- * In normal mode: `log`, `info`, and `json` output.
630
- * In JSON mode: only `json` output (log/info redirected to stderr).
631
- */
632
- readonly stdout: string[];
633
- /**
634
- * Lines written to stderr.
635
- *
636
- * In normal mode: `warn` and `error` output.
637
- * In JSON mode: `warn`, `error`, `log`, and `info` output.
638
- */
639
- readonly stderr: string[];
640
- /**
641
- * Activity events from spinner and progress handles.
642
- *
643
- * Captured separately from stdout/stderr to allow targeted assertions
644
- * on activity lifecycle without parsing text output. Events are
645
- * recorded in chronological order.
646
- */
647
- readonly activity: ActivityEvent[];
648
- }
649
-
650
- /**
651
- * Create an output channel that captures all output into arrays.
652
- *
653
- * Useful in tests to assert on what a handler wrote without touching
654
- * real I/O.
655
- *
656
- * @param options - Optional {@link OutputOptions} (minus `stdout`/`stderr`,
657
- * which are wired to the capture buffers automatically).
658
- *
659
- * @returns A tuple of `[out, captured]` — the {@link Out} channel and the
660
- * {@link CapturedOutput} buffers.
661
- *
662
- * @example
663
- * ```ts
664
- * const [out, captured] = createCaptureOutput();
665
- * out.log('hello');
666
- * out.warn('danger');
667
- * expect(captured.stdout).toEqual(['hello\n']);
668
- * expect(captured.stderr).toEqual(['danger\n']);
669
- * ```
670
- */
671
- function createCaptureOutput(
672
- options?: Omit<OutputOptions, 'stdout' | 'stderr'>,
673
- ): [out: Out, captured: CapturedOutput] {
674
- const captured: CapturedOutput = { stdout: [], stderr: [], activity: [] };
675
- const resolved = resolveOptions({
676
- ...options,
677
- stdout: (s) => captured.stdout.push(s),
678
- stderr: (s) => captured.stderr.push(s),
679
- });
680
- const out = new CaptureOutputChannel(resolved, captured.activity);
681
- return [out, captured];
682
- }
683
-
684
- // --- Exports
685
-
686
- export type { CapturedOutput, OutputOptions, Verbosity, WriteFn };
687
- export {
688
- CaptureOutputChannel,
689
- CaptureProgressHandle,
690
- CaptureSpinnerHandle,
691
- clearRequestedExitCode,
692
- createCaptureOutput,
693
- createOutput,
694
- getRequestedExitCode,
695
- noopProgressHandle,
696
- noopSpinnerHandle,
697
- OutputChannel,
698
- StaticProgressHandle,
699
- StaticSpinnerHandle,
700
- setRequestedExitCode,
701
- TTYProgressHandle,
702
- TTYSpinnerHandle,
703
- writeLine,
704
- };