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