@kjanat/dreamcli 2.5.0 → 3.0.0-rc.2

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 (160) hide show
  1. package/CHANGELOG.md +153 -1
  2. package/README.md +9 -2
  3. package/dist/core/cli/dispatch.mjs +214 -1
  4. package/dist/core/cli/help-links.mjs +41 -1
  5. package/dist/core/cli/index.d.mts +109 -16
  6. package/dist/core/cli/index.mjs +901 -1
  7. package/dist/core/cli/planner.d.mts +27 -5
  8. package/dist/core/cli/planner.mjs +300 -1
  9. package/dist/core/cli/plugin.mjs +41 -1
  10. package/dist/core/cli/propagate.mjs +57 -1
  11. package/dist/core/cli/root-help.d.mts +16 -2
  12. package/dist/core/cli/root-help.mjs +208 -6
  13. package/dist/core/cli/root-surface.d.mts +18 -3
  14. package/dist/core/cli/root-surface.mjs +27 -1
  15. package/dist/core/cli/runtime-preflight.d.mts +16 -1
  16. package/dist/core/cli/runtime-preflight.mjs +168 -1
  17. package/dist/core/completion/index.d.mts +32 -1
  18. package/dist/core/completion/index.mjs +90 -1
  19. package/dist/core/completion/shells/bash.mjs +304 -3
  20. package/dist/core/completion/shells/fish.mjs +159 -2
  21. package/dist/core/completion/shells/powershell.mjs +353 -2
  22. package/dist/core/completion/shells/shared.d.mts +10 -0
  23. package/dist/core/completion/shells/shared.mjs +154 -1
  24. package/dist/core/completion/shells/zsh.mjs +244 -2
  25. package/dist/core/config/index.mjs +246 -1
  26. package/dist/core/config/package-json.mjs +385 -3
  27. package/dist/core/errors/index.mjs +87 -1
  28. package/dist/core/execution/index.mjs +189 -1
  29. package/dist/core/help/ansi.mjs +122 -2
  30. package/dist/core/help/index.d.mts +45 -1
  31. package/dist/core/help/index.mjs +329 -7
  32. package/dist/core/json-schema/index.mjs +487 -9
  33. package/dist/core/json-schema/meta-descriptions.generated.d.mts +38 -38
  34. package/dist/core/json-schema/meta-descriptions.generated.mjs +93 -28
  35. package/dist/core/output/activity.mjs +452 -1
  36. package/dist/core/output/bind.mjs +56 -1
  37. package/dist/core/output/contracts.mjs +57 -1
  38. package/dist/core/output/display-value.mjs +32 -1
  39. package/dist/core/output/index.d.mts +21 -0
  40. package/dist/core/output/index.mjs +442 -2
  41. package/dist/core/output/renderers.mjs +46 -1
  42. package/dist/core/output/writer.mjs +12 -1
  43. package/dist/core/parse/index.d.mts +15 -1
  44. package/dist/core/parse/index.mjs +555 -1
  45. package/dist/core/prompt/index.d.mts +11 -4
  46. package/dist/core/prompt/index.mjs +348 -6
  47. package/dist/core/resolve/args.mjs +105 -1
  48. package/dist/core/resolve/coerce.mjs +279 -1
  49. package/dist/core/resolve/config.mjs +19 -1
  50. package/dist/core/resolve/errors.mjs +140 -2
  51. package/dist/core/resolve/flags.mjs +196 -1
  52. package/dist/core/resolve/index.mjs +85 -1
  53. package/dist/core/resolve/property.d.mts +2 -1
  54. package/dist/core/resolve/property.mjs +45 -1
  55. package/dist/core/schema/arg.d.mts +90 -10
  56. package/dist/core/schema/arg.mjs +463 -1
  57. package/dist/core/schema/command.d.mts +21 -1
  58. package/dist/core/schema/command.mjs +712 -1
  59. package/dist/core/schema/flag.d.mts +92 -2
  60. package/dist/core/schema/flag.mjs +453 -1
  61. package/dist/core/schema/index.d.mts +2 -1
  62. package/dist/core/schema/middleware.mjs +41 -1
  63. package/dist/core/schema/number-constraints.d.mts +96 -0
  64. package/dist/core/schema/number-constraints.mjs +60 -0
  65. package/dist/core/schema/prompt.d.mts +15 -0
  66. package/dist/core/schema/run.d.mts +4 -4
  67. package/dist/core/schema-dsl/runtime.mjs +271 -2
  68. package/dist/core/schema-dsl/to-json-schema.mjs +74 -1
  69. package/dist/core/testkit/index.d.mts +9 -5
  70. package/dist/core/testkit/index.mjs +83 -1
  71. package/dist/index.d.mts +3 -1
  72. package/dist/index.mjs +22 -1
  73. package/dist/runtime/adapter.mjs +82 -1
  74. package/dist/runtime/auto.mjs +46 -1
  75. package/dist/runtime/bun.mjs +28 -1
  76. package/dist/runtime/deno.mjs +217 -2
  77. package/dist/runtime/detect.mjs +45 -1
  78. package/dist/runtime/node.mjs +169 -2
  79. package/dist/runtime/paths.mjs +48 -1
  80. package/dist/runtime.mjs +7 -1
  81. package/dist/strings.mjs +22 -1
  82. package/dist/testkit.mjs +5 -1
  83. package/dist/version.mjs +7 -1
  84. package/examples/basic.ts +5 -1
  85. package/examples/gh/package.json +2 -7
  86. package/examples/pwsh-demo/package.json +1 -7
  87. package/examples/pwsh-demo/src/main.test.ts +1 -4
  88. package/examples/pwsh-demo/src/main.ts +14 -4
  89. package/examples/transport-launcher.ts +85 -0
  90. package/package.json +23 -41
  91. package/dist/runtime/support.d.mts +0 -42
  92. package/dist/runtime/support.mjs +0 -1
  93. package/src/core/cli/dispatch.ts +0 -349
  94. package/src/core/cli/help-links.ts +0 -82
  95. package/src/core/cli/index.ts +0 -1413
  96. package/src/core/cli/planner.ts +0 -487
  97. package/src/core/cli/plugin.ts +0 -117
  98. package/src/core/cli/propagate.ts +0 -97
  99. package/src/core/cli/root-help.ts +0 -252
  100. package/src/core/cli/root-surface.ts +0 -74
  101. package/src/core/cli/runtime-preflight.ts +0 -438
  102. package/src/core/completion/index.ts +0 -88
  103. package/src/core/completion/shells/bash.ts +0 -459
  104. package/src/core/completion/shells/fish.ts +0 -259
  105. package/src/core/completion/shells/powershell.ts +0 -439
  106. package/src/core/completion/shells/shared.ts +0 -283
  107. package/src/core/completion/shells/zsh.ts +0 -381
  108. package/src/core/config/index.ts +0 -417
  109. package/src/core/config/package-json.ts +0 -560
  110. package/src/core/errors/index.ts +0 -193
  111. package/src/core/execution/index.ts +0 -268
  112. package/src/core/help/ansi.ts +0 -144
  113. package/src/core/help/index.ts +0 -516
  114. package/src/core/json-schema/index.ts +0 -891
  115. package/src/core/json-schema/meta-descriptions.generated.ts +0 -185
  116. package/src/core/output/activity.ts +0 -575
  117. package/src/core/output/bind.ts +0 -59
  118. package/src/core/output/contracts.ts +0 -194
  119. package/src/core/output/display-value.ts +0 -48
  120. package/src/core/output/index.ts +0 -704
  121. package/src/core/output/renderers.ts +0 -125
  122. package/src/core/output/writer.ts +0 -46
  123. package/src/core/parse/index.ts +0 -681
  124. package/src/core/prompt/index.ts +0 -583
  125. package/src/core/resolve/args.ts +0 -144
  126. package/src/core/resolve/coerce.ts +0 -432
  127. package/src/core/resolve/config.ts +0 -26
  128. package/src/core/resolve/contracts.ts +0 -135
  129. package/src/core/resolve/errors.ts +0 -227
  130. package/src/core/resolve/flags.ts +0 -255
  131. package/src/core/resolve/index.ts +0 -108
  132. package/src/core/resolve/property.ts +0 -99
  133. package/src/core/schema/activity.ts +0 -240
  134. package/src/core/schema/arg.ts +0 -719
  135. package/src/core/schema/command.ts +0 -1498
  136. package/src/core/schema/flag.ts +0 -801
  137. package/src/core/schema/index.ts +0 -91
  138. package/src/core/schema/middleware.ts +0 -171
  139. package/src/core/schema/prompt.ts +0 -156
  140. package/src/core/schema/run.ts +0 -198
  141. package/src/core/schema-dsl/index.ts +0 -109
  142. package/src/core/schema-dsl/parse.ts +0 -262
  143. package/src/core/schema-dsl/runtime.ts +0 -609
  144. package/src/core/schema-dsl/to-json-schema.ts +0 -102
  145. package/src/core/testkit/index.ts +0 -123
  146. package/src/index.ts +0 -179
  147. package/src/runtime/adapter.ts +0 -303
  148. package/src/runtime/auto.ts +0 -110
  149. package/src/runtime/bun.ts +0 -55
  150. package/src/runtime/deno.ts +0 -369
  151. package/src/runtime/detect.ts +0 -105
  152. package/src/runtime/index.ts +0 -21
  153. package/src/runtime/node-builtins.d.ts +0 -27
  154. package/src/runtime/node.ts +0 -300
  155. package/src/runtime/paths.ts +0 -64
  156. package/src/runtime/support.ts +0 -135
  157. package/src/runtime.ts +0 -31
  158. package/src/strings.ts +0 -34
  159. package/src/testkit.ts +0 -25
  160. package/src/version.ts +0 -20
@@ -1,193 +0,0 @@
1
- /**
2
- * Structured error types for DreamCLI.
3
- *
4
- * Base {@linkcode CLIError} carries stable code, exit code, suggestion, and structured
5
- * details. {@linkcode ParseError} and {@linkcode ValidationError} derive from it with
6
- * category-appropriate defaults.
7
- *
8
- * @module dreamcli/core/errors
9
- */
10
-
11
- // --- Error codes — discriminated string union per category
12
-
13
- /** Codes emitted during argv parsing. */
14
- export type ParseErrorCode =
15
- | 'UNKNOWN_FLAG'
16
- | 'UNKNOWN_COMMAND'
17
- | 'MISSING_VALUE'
18
- | 'INVALID_VALUE'
19
- | 'INVALID_SCHEMA'
20
- | 'UNEXPECTED_POSITIONAL';
21
-
22
- /** Codes emitted during post-parse validation / resolution. */
23
- export type ValidationErrorCode =
24
- | 'REQUIRED_FLAG'
25
- | 'REQUIRED_ARG'
26
- | 'INVALID_ENUM'
27
- | 'TYPE_MISMATCH'
28
- | 'CONSTRAINT_VIOLATED';
29
-
30
- /** Any framework error code (extensible via `string & {}`). */
31
- // deno-lint-ignore ban-types
32
- export type ErrorCode = ParseErrorCode | ValidationErrorCode | (string & {});
33
-
34
- // --- Options bag for CLIError construction
35
-
36
- /** Options accepted by the `CLIError` constructor. */
37
- export interface CLIErrorOptions {
38
- /** Stable machine-readable identifier (e.g. `"UNKNOWN_FLAG"`). */
39
- readonly code: ErrorCode;
40
- /**
41
- * Process exit code.
42
- * @defaultValue `1`
43
- */
44
- readonly exitCode?: number;
45
- /** One-liner actionable hint shown to the user. */
46
- readonly suggest?: string;
47
- /** Arbitrary structured payload (serialised in `--json` mode). */
48
- readonly details?: Readonly<Record<string, unknown>>;
49
- /** Original error, if this wraps another. */
50
- readonly cause?: unknown;
51
- }
52
-
53
- // --- CLIError — base structured error
54
-
55
- /**
56
- * Base structured error for DreamCLI.
57
- *
58
- * Every error surfaced by the framework extends this class, ensuring a
59
- * consistent shape for rendering (TTY pretty-print, `--json`, test assertions).
60
- */
61
- export class CLIError extends Error {
62
- /** Error class name, always `'CLIError'` for the base class. @override */
63
- override readonly name: string = 'CLIError';
64
-
65
- /** Stable machine-readable identifier. */
66
- readonly code: ErrorCode;
67
-
68
- /** Process exit code (defaults to `1`). */
69
- readonly exitCode: number;
70
-
71
- /** One-liner actionable hint. */
72
- readonly suggest: string | undefined;
73
-
74
- /** Structured payload for machine output. */
75
- readonly details: Readonly<Record<string, unknown>> | undefined;
76
-
77
- /** Create a structured CLI error from a human message and machine-readable options. */
78
- constructor(message: string, options: CLIErrorOptions) {
79
- super(message, options.cause !== undefined ? { cause: options.cause } : undefined);
80
- this.code = options.code;
81
- this.exitCode = options.exitCode ?? 1;
82
- this.suggest = options.suggest;
83
- this.details = options.details;
84
- }
85
-
86
- /**
87
- * Serialise to a plain object suitable for JSON output.
88
- * @sealed
89
- */
90
- toJSON(): CLIErrorJSON {
91
- return {
92
- name: this.name,
93
- code: this.code,
94
- message: this.message,
95
- exitCode: this.exitCode,
96
- ...(this.suggest !== undefined && { suggest: this.suggest }),
97
- ...(this.details !== undefined && { details: this.details }),
98
- };
99
- }
100
- }
101
-
102
- /** Shape returned by {@linkcode CLIError}.toJSON(). */
103
- export interface CLIErrorJSON {
104
- /** Error class name (e.g. `'CLIError'`, `'ParseError'`). */
105
- readonly name: string;
106
- /** Stable machine-readable identifier for programmatic matching. */
107
- readonly code: ErrorCode;
108
- /** Human-readable description of what went wrong. */
109
- readonly message: string;
110
- /** Process exit code associated with this error. */
111
- readonly exitCode: number;
112
- /** Actionable hint shown to the user, when available. */
113
- readonly suggest?: string;
114
- /** Structured payload for machine consumers, when available. */
115
- readonly details?: Readonly<Record<string, unknown>>;
116
- }
117
-
118
- // --- ParseError — argv parsing failures
119
-
120
- /** Options for {@linkcode ParseError}. Code is narrowed to parse-specific codes. */
121
- export interface ParseErrorOptions extends Omit<CLIErrorOptions, 'code' | 'exitCode'> {
122
- /** Parse-category error code (e.g. `'UNKNOWN_FLAG'`, `'MISSING_VALUE'`). */
123
- readonly code: ParseErrorCode;
124
- /**
125
- * Process exit code for parse failures.
126
- * @defaultValue `2`
127
- */
128
- readonly exitCode?: number;
129
- }
130
-
131
- /**
132
- * Error thrown when argv tokenization / parsing fails.
133
- *
134
- * Exit code defaults to `2` (standard for CLI usage errors).
135
- */
136
- export class ParseError extends CLIError {
137
- /** Always `'ParseError'`. @override */
138
- override readonly name = 'ParseError' as const;
139
- /** Narrowed to parse-category codes. */
140
- declare readonly code: ParseErrorCode;
141
-
142
- /** Create a parse error with exit code defaulting to `2`. */
143
- constructor(message: string, options: ParseErrorOptions) {
144
- super(message, { ...options, exitCode: options.exitCode ?? 2 });
145
- }
146
- }
147
-
148
- // --- ValidationError — post-parse validation / resolution failures
149
-
150
- /** Options for {@linkcode ValidationError}. Code is narrowed to validation-specific codes. */
151
- export interface ValidationErrorOptions extends Omit<CLIErrorOptions, 'code' | 'exitCode'> {
152
- /** Validation-category error code (e.g. `'REQUIRED_FLAG'`, `'INVALID_ENUM'`). */
153
- readonly code: ValidationErrorCode;
154
- /**
155
- * Process exit code for validation failures.
156
- * @defaultValue `2`
157
- */
158
- readonly exitCode?: number;
159
- }
160
-
161
- /**
162
- * Error thrown when resolved values fail validation constraints.
163
- *
164
- * Exit code defaults to `2` (standard for CLI usage errors).
165
- */
166
- export class ValidationError extends CLIError {
167
- /** Always `'ValidationError'`. @override */
168
- override readonly name = 'ValidationError' as const;
169
- /** Narrowed to validation-category codes. */
170
- declare readonly code: ValidationErrorCode;
171
-
172
- /** Create a validation error with exit code defaulting to `2`. */
173
- constructor(message: string, options: ValidationErrorOptions) {
174
- super(message, { ...options, exitCode: options.exitCode ?? 2 });
175
- }
176
- }
177
-
178
- // --- Type guard utilities
179
-
180
- /** Narrows an unknown value to `CLIError`. */
181
- export function isCLIError(value: unknown): value is CLIError {
182
- return value instanceof CLIError;
183
- }
184
-
185
- /** Narrows an unknown value to `ParseError`. */
186
- export function isParseError(value: unknown): value is ParseError {
187
- return value instanceof ParseError;
188
- }
189
-
190
- /** Narrows an unknown value to `ValidationError`. */
191
- export function isValidationError(value: unknown): value is ValidationError {
192
- return value instanceof ValidationError;
193
- }
@@ -1,268 +0,0 @@
1
- /**
2
- * Shared command execution seam.
3
- *
4
- * Centralizes the parse -> resolve -> plugin -> handler pipeline so CLI and
5
- * testkit can converge on one owned execution path during the re-foundation.
6
- *
7
- * @module dreamcli/core/execution
8
- * @internal
9
- */
10
-
11
- import type {
12
- BeforeParseParams,
13
- CLIPlugin,
14
- ResolvedCommandParams,
15
- } from '#internals/core/cli/plugin.ts';
16
- import { CLIError } from '#internals/core/errors/index.ts';
17
- import { formatHelp } from '#internals/core/help/index.ts';
18
- import type { CapturedOutput } from '#internals/core/output/index.ts';
19
- import {
20
- clearRequestedExitCode,
21
- getRequestedExitCode,
22
- } from '#internals/core/output/index.ts';
23
- import { includesBeforeSeparator, parse } from '#internals/core/parse/index.ts';
24
- import { createTestPrompter } from '#internals/core/prompt/index.ts';
25
- import type { DeprecationWarning, ResolveOptions } from '#internals/core/resolve/index.ts';
26
- import { resolve } from '#internals/core/resolve/index.ts';
27
- import type {
28
- CommandMeta,
29
- CommandSchema,
30
- Out,
31
- RunnableCommand,
32
- } from '#internals/core/schema/command.ts';
33
- import type { RunOptions, RunResult } from '#internals/core/schema/run.ts';
34
-
35
- /**
36
- * Explicit executor input for a single command invocation.
37
- * @internal
38
- */
39
- interface CommandExecutionRequest {
40
- /** The command instance whose handler will be invoked. */
41
- readonly command: RunnableCommand;
42
- /** Raw argument tokens to parse (excluding the program name). */
43
- readonly argv: readonly string[];
44
- /** Output channel for handler and error rendering. */
45
- readonly out: Out;
46
- /** Frozen schema definition (flags, args, metadata) for parsing and resolution. */
47
- readonly schema: CommandSchema;
48
- /** Runtime metadata (binary name, version) propagated to the handler. */
49
- readonly meta: CommandMeta;
50
- /** Optional overrides for env, config, prompter, plugins, and JSON mode. */
51
- readonly options?: RunOptions;
52
- }
53
-
54
- /**
55
- * Minimal executor result before output buffers are assembled into `RunResult`.
56
- * @internal
57
- */
58
- interface CommandExecutionResult {
59
- /** Process exit code (`0` on success, error-specific otherwise). */
60
- readonly exitCode: number;
61
- /** The structured error if the command failed, `undefined` on success. */
62
- readonly error: CLIError | undefined;
63
- }
64
-
65
- /**
66
- * Run the full parse -> resolve -> plugin -> handler pipeline for one command.
67
- *
68
- * Handles `--help` short-circuit, plugin lifecycle hooks, deprecation warnings,
69
- * and error wrapping. Both CLI dispatch and testkit `runCommand` converge here.
70
- * @internal
71
- */
72
- async function executeCommand(request: CommandExecutionRequest): Promise<CommandExecutionResult> {
73
- const { argv, command, meta, options, out, schema } = request;
74
- clearRequestedExitCode(out);
75
-
76
- try {
77
- if (includesBeforeSeparator(argv, '--help') || includesBeforeSeparator(argv, '-h')) {
78
- const helpText = formatHelp(schema, options?.help);
79
- out.log(helpText);
80
- return { exitCode: 0, error: undefined };
81
- }
82
-
83
- const handler = command.handler;
84
- if (handler === undefined) {
85
- const error = new CLIError(`Command '${command.schema.name}' has no action handler`, {
86
- code: 'NO_ACTION',
87
- suggest: `Add an .action() handler to the '${command.schema.name}' command`,
88
- });
89
- out.error(error.message);
90
- return { exitCode: 1, error };
91
- }
92
-
93
- await runBeforeParseHooks(options?.plugins, {
94
- argv,
95
- command: schema,
96
- meta,
97
- out,
98
- });
99
-
100
- const parsed = parse(schema, argv);
101
-
102
- const effectivePrompter =
103
- options?.prompter ??
104
- (options?.answers !== undefined ? createTestPrompter(options.answers) : undefined);
105
- const resolveOptions: ResolveOptions = {
106
- ...(options?.stdinData !== undefined ? { stdinData: options.stdinData } : {}),
107
- ...(options?.env !== undefined ? { env: options.env } : {}),
108
- ...(options?.config !== undefined ? { config: options.config } : {}),
109
- ...(effectivePrompter !== undefined ? { prompter: effectivePrompter } : {}),
110
- };
111
- const resolved = await resolve(schema, parsed, resolveOptions);
112
- const resolvedParams: ResolvedCommandParams = {
113
- args: resolved.args,
114
- flags: resolved.flags,
115
- deprecations: resolved.deprecations,
116
- command: schema,
117
- meta,
118
- out,
119
- };
120
-
121
- await runResolvedHooks(options?.plugins, 'afterResolve', resolvedParams);
122
-
123
- for (const deprecation of resolved.deprecations) {
124
- out.warn(formatDeprecation(deprecation));
125
- }
126
-
127
- await runResolvedHooks(options?.plugins, 'beforeAction', resolvedParams);
128
- await executeWithExecutionSteps(command, handler, resolved.flags, resolved.args, out, meta);
129
- await runResolvedHooks(options?.plugins, 'afterAction', resolvedParams);
130
-
131
- return { exitCode: getRequestedExitCode(out) ?? 0, error: undefined };
132
- } catch (error: unknown) {
133
- if (error instanceof CLIError) {
134
- if (options?.jsonMode === true) {
135
- out.json({ error: error.toJSON() });
136
- } else {
137
- out.error(error.message);
138
- if (error.suggest !== undefined) {
139
- out.error(`Suggestion: ${error.suggest}`);
140
- }
141
- }
142
- return { exitCode: error.exitCode, error };
143
- }
144
-
145
- const message = error instanceof Error ? error.message : String(error);
146
- const wrapped = new CLIError(`Unexpected error: ${message}`, {
147
- code: 'UNEXPECTED_ERROR',
148
- cause: error,
149
- });
150
- if (options?.jsonMode === true) {
151
- out.json({ error: wrapped.toJSON() });
152
- } else {
153
- out.error(wrapped.message);
154
- }
155
- return { exitCode: 1, error: wrapped };
156
- } finally {
157
- out.stopActive();
158
- clearRequestedExitCode(out);
159
- }
160
- }
161
-
162
- type ResolvedHookName = Exclude<keyof CLIPlugin['hooks'], 'beforeParse'>;
163
-
164
- async function runBeforeParseHooks(
165
- plugins: readonly CLIPlugin[] | undefined,
166
- params: BeforeParseParams,
167
- ): Promise<void> {
168
- if (plugins === undefined) return;
169
- for (const current of plugins) {
170
- const hook = current.hooks.beforeParse;
171
- if (hook !== undefined) await hook(params);
172
- }
173
- }
174
-
175
- async function runResolvedHooks(
176
- plugins: readonly CLIPlugin[] | undefined,
177
- hookName: ResolvedHookName,
178
- params: ResolvedCommandParams,
179
- ): Promise<void> {
180
- if (plugins === undefined) return;
181
- for (const current of plugins) {
182
- const hook = current.hooks[hookName];
183
- if (hook !== undefined) await hook(params);
184
- }
185
- }
186
-
187
- async function executeWithExecutionSteps(
188
- command: RunnableCommand,
189
- handler: NonNullable<RunnableCommand['handler']>,
190
- flags: Readonly<Record<string, unknown>>,
191
- args: Readonly<Record<string, unknown>>,
192
- out: Out,
193
- meta: CommandMeta,
194
- ): Promise<void> {
195
- const steps = command._executionSteps;
196
-
197
- type ChainFn = (ctx: Readonly<Record<string, unknown>>) => Promise<void>;
198
-
199
- let chain: ChainFn = async (ctx) => {
200
- await handler({ flags, args, ctx, out, meta });
201
- };
202
-
203
- for (let i = steps.length - 1; i >= 0; i--) {
204
- const step = steps[i];
205
- if (step === undefined) continue;
206
- const downstream = chain;
207
- switch (step.kind) {
208
- case 'derive':
209
- chain = async (ctx) => {
210
- const additions = await step.handler({ args, flags, ctx, out, meta });
211
- if (additions === undefined) {
212
- await downstream(ctx);
213
- return;
214
- }
215
- if (typeof additions !== 'object' || additions === null || Array.isArray(additions)) {
216
- throw new CLIError('derive() must return an object or undefined', {
217
- code: 'INVALID_BUILDER_STATE',
218
- suggest:
219
- 'Return an object to add context, or return nothing for validation-only derive handlers',
220
- });
221
- }
222
- await downstream({ ...ctx, ...additions });
223
- };
224
- break;
225
- case 'middleware':
226
- chain = async (ctx) => {
227
- await step.handler({
228
- args,
229
- flags,
230
- ctx,
231
- out,
232
- meta,
233
- next: async (additions) => {
234
- await downstream({ ...ctx, ...additions });
235
- },
236
- });
237
- };
238
- break;
239
- }
240
- }
241
-
242
- await chain({});
243
- }
244
-
245
- /**
246
- * Assemble a {@linkcode CommandExecutionResult} and captured output buffers into a public `RunResult`.
247
- * @internal
248
- */
249
- function buildRunResult(result: CommandExecutionResult, captured: CapturedOutput): RunResult {
250
- return {
251
- exitCode: result.exitCode,
252
- stdout: captured.stdout,
253
- stderr: captured.stderr,
254
- activity: captured.activity,
255
- error: result.error,
256
- };
257
- }
258
-
259
- function formatDeprecation(deprecation: DeprecationWarning): string {
260
- const entity =
261
- deprecation.kind === 'flag' ? `flag --${deprecation.name}` : `argument <${deprecation.name}>`;
262
- return typeof deprecation.message === 'string'
263
- ? `Warning: ${entity} is deprecated: ${deprecation.message}`
264
- : `Warning: ${entity} is deprecated`;
265
- }
266
-
267
- export type { CommandExecutionRequest, CommandExecutionResult };
268
- export { buildRunResult, executeCommand };
@@ -1,144 +0,0 @@
1
- /**
2
- * ANSI/OSC-aware text helpers for help formatting.
3
- *
4
- * Terminal escape sequences (SGR colors, OSC 8 hyperlinks) occupy zero
5
- * columns when rendered, so width math must measure the *visible* text.
6
- * {@linkcode visibleWidth} strips escapes before counting, and the shared
7
- * {@linkcode padEnd}/{@linkcode wrapText} helpers build on it so aligned
8
- * tables and wrapped lines stay intact when escapes are present.
9
- *
10
- * @module dreamcli/core/help/ansi
11
- */
12
-
13
- // --- Escape stripping
14
-
15
- /**
16
- * Matches ANSI escape sequences: CSI (e.g. SGR color codes like `\x1b[31m`)
17
- * and OSC (e.g. OSC 8 hyperlinks), with both BEL and ST terminators.
18
- *
19
- * @internal
20
- */
21
- // biome-ignore lint/suspicious/noControlCharactersInRegex: matching terminal escape sequences requires control characters
22
- const ANSI_PATTERN = /\u001B(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001B]*(?:\u0007|\u001B\\))/g;
23
-
24
- /**
25
- * Remove ANSI CSI and OSC escape sequences from `text`.
26
- *
27
- * @param text - Text possibly containing terminal escapes.
28
- * @returns The text with all escape sequences removed.
29
- */
30
- function stripAnsi(text: string): string {
31
- return text.replace(ANSI_PATTERN, '');
32
- }
33
-
34
- /**
35
- * Measure the visible column width of `text`, ignoring ANSI/OSC escapes.
36
- *
37
- * Escape sequences (SGR colors, OSC 8 hyperlinks) occupy zero columns when
38
- * rendered, so `.length` overcounts whenever they are present. Help
39
- * formatting uses this for padding and wrapping; exported for custom help
40
- * renderers that mix colors or links into aligned output.
41
- *
42
- * @param text - Text possibly containing terminal escapes.
43
- * @returns Number of visible characters.
44
- *
45
- * @example
46
- * ```ts
47
- * visibleWidth('plain'); // 5
48
- * visibleWidth(osc8('https://x.dev', 'x')); // 1
49
- * ```
50
- */
51
- function visibleWidth(text: string): number {
52
- return stripAnsi(text).length;
53
- }
54
-
55
- // --- OSC 8 hyperlinks
56
-
57
- const OSC = '\u001B]';
58
- const BEL = '\u0007';
59
-
60
- /**
61
- * Wrap `text` in an [OSC 8 hyperlink](https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda)
62
- * pointing at `url`.
63
- *
64
- * Supporting terminals render `text` as a clickable link; non-supporting
65
- * terminals ignore the escape sequence and show plain text. Combine with
66
- * {@linkcode visibleWidth}-aware formatting when embedding links in aligned
67
- * output.
68
- *
69
- * @param url - Link target (string or `URL` instance).
70
- * @param text - Visible link text.
71
- * @returns The OSC 8 escape sequence wrapping `text`.
72
- *
73
- * @example
74
- * ```ts
75
- * cli('mycli').version(osc8('https://github.com/me/mycli/releases/tag/v1.0.0', '1.0.0'));
76
- * ```
77
- */
78
- function osc8(url: string | URL, text: string): string {
79
- const href = url instanceof URL ? url.href : url;
80
- return `${OSC}8;;${href}${BEL}${text}${OSC}8;;${BEL}`;
81
- }
82
-
83
- // --- Width-aware padding and wrapping
84
-
85
- /**
86
- * Pad `text` to `length` visible columns with trailing spaces.
87
- *
88
- * @param text - The string to pad (may contain ANSI/OSC escapes).
89
- * @param length - Target visible width in columns.
90
- * @returns The padded string, unchanged if already at or beyond `length`.
91
- */
92
- function padEnd(text: string, length: number): string {
93
- const visible = visibleWidth(text);
94
- if (visible >= length) return text;
95
- return text + ' '.repeat(length - visible);
96
- }
97
-
98
- /**
99
- * Wrap text to `width`, preserving leading indent on continuation lines.
100
- *
101
- * Line lengths are measured with {@linkcode visibleWidth}, so embedded
102
- * ANSI/OSC escapes do not trigger premature wrapping.
103
- *
104
- * @param text - The text to wrap.
105
- * @param width - Maximum line width in columns.
106
- * @param indent - Number of leading spaces for continuation lines.
107
- * @returns The wrapped string with newlines inserted as needed.
108
- */
109
- function wrapText(text: string, width: number, indent: number): string {
110
- if (visibleWidth(text) + indent <= width) return text;
111
-
112
- const maxLen = width - indent;
113
- if (maxLen <= 0) return text;
114
-
115
- const words = text.split(' ');
116
- const lines: string[] = [];
117
- let current = '';
118
- let currentWidth = 0;
119
-
120
- for (const word of words) {
121
- const wordWidth = visibleWidth(word);
122
- if (current.length === 0) {
123
- current = word;
124
- currentWidth = wordWidth;
125
- } else if (currentWidth + 1 + wordWidth <= maxLen) {
126
- current += ` ${word}`;
127
- currentWidth += 1 + wordWidth;
128
- } else {
129
- lines.push(current);
130
- current = word;
131
- currentWidth = wordWidth;
132
- }
133
- }
134
- if (current.length > 0) {
135
- lines.push(current);
136
- }
137
-
138
- const pad = ' '.repeat(indent);
139
- return lines.map((line, i) => (i === 0 ? line : `${pad}${line}`)).join('\n');
140
- }
141
-
142
- // --- Exports
143
-
144
- export { osc8, padEnd, stripAnsi, visibleWidth, wrapText };