@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,123 @@
1
+ /**
2
+ * Test harness: command.run() with injected state, output capture.
3
+ *
4
+ * Provides {@linkcode runCommand()} — the in-process test harness wrapper over DreamCLI's
5
+ * shared executor.\
6
+ * It wires capture output and standalone command metadata,
7
+ * then returns a structured {@linkcode RunResult} with exitCode and captured output.
8
+ *
9
+ * This keeps command tests process-free without testkit owning the canonical pipeline:
10
+ *
11
+ * ```text
12
+ * parse -> resolve -> execute
13
+ * ```
14
+ * @module dreamcli/core/testkit
15
+ */
16
+
17
+ import { buildRunResult, executeCommand } from '#internals/core/execution/index.ts';
18
+ import type { CapturedOutput } from '#internals/core/output/index.ts';
19
+ import { createCaptureOutput } from '#internals/core/output/index.ts';
20
+ import type { CommandMeta, Out, RunnableCommand } from '#internals/core/schema/command.ts';
21
+ import type { RunOptions, RunResult } from '#internals/core/schema/run.ts';
22
+
23
+ // RunOptions and RunResult are defined in schema/run.ts so the execution
24
+ // contract is shared by schema, CLI dispatch, and testkit. Re-exported here
25
+ // for public testkit continuity.
26
+
27
+ // --- Core execution pipeline
28
+
29
+ /**
30
+ * Run a command builder against the given argv with injected options.
31
+ *
32
+ * This is the testkit wrapper around the shared executor:
33
+ * 1. Create or reuse capture output
34
+ * 2. Build standalone schema/meta defaults when CLI dispatch did not
35
+ * 3. Delegate parse -> resolve -> execute to the shared executor
36
+ * 4. Return the structured result with captured buffers
37
+ *
38
+ * Errors are normalized by the shared executor into structured {@linkcode RunResult}s
39
+ * with appropriate exit codes. The function never throws.
40
+ *
41
+ * @param cmd - The command builder (must have an action handler)
42
+ * @param argv - Raw argv strings (NOT including the command name itself)
43
+ * @param options - Injectable runtime state
44
+ * @returns Structured run result with exit code and captured output
45
+ */
46
+ async function runCommand(
47
+ cmd: RunnableCommand,
48
+ argv: readonly string[],
49
+ options?: RunOptions,
50
+ ): Promise<RunResult> {
51
+ let out: Out;
52
+ let captured: CapturedOutput;
53
+ if (options?.out !== undefined) {
54
+ out = options.out;
55
+ captured = options.captured ?? { stdout: [], stderr: [], activity: [] };
56
+ } else {
57
+ const captureOptions = {
58
+ ...(options?.verbosity !== undefined ? { verbosity: options.verbosity } : {}),
59
+ ...(options?.jsonMode !== undefined ? { jsonMode: options.jsonMode } : {}),
60
+ ...(options?.isTTY !== undefined ? { isTTY: options.isTTY } : {}),
61
+ };
62
+ [out, captured] = createCaptureOutput(
63
+ Object.keys(captureOptions).length > 0 ? captureOptions : undefined,
64
+ );
65
+ }
66
+
67
+ // Use merged schema (with propagated flags) when provided by dispatch layer,
68
+ // otherwise fall back to the command's own schema.
69
+ const schema = options?.mergedSchema ?? cmd.schema;
70
+ const meta: CommandMeta = options?.meta ?? {
71
+ name: schema.name,
72
+ bin: options?.help?.binName ?? schema.name,
73
+ version: undefined,
74
+ command: schema.name,
75
+ };
76
+
77
+ const result = await executeCommand({
78
+ command: cmd,
79
+ argv,
80
+ out,
81
+ schema,
82
+ meta,
83
+ ...(options !== undefined ? { options } : {}),
84
+ });
85
+
86
+ return buildRunResult(result, captured);
87
+ }
88
+
89
+ // --- Exports
90
+
91
+ /**
92
+ * Options for {@linkcode runCommand} — process-free command execution.
93
+ *
94
+ * Every field is optional. Inject env, config, prompt answers, and
95
+ * output capture without touching process state.
96
+ *
97
+ * @example
98
+ * ```ts
99
+ * const result = await runCommand(cmd, ['--verbose'], {
100
+ * env: { LOG_LEVEL: 'debug' },
101
+ * config: { theme: 'dark' },
102
+ * });
103
+ * ```
104
+ */
105
+ /**
106
+ * Structured result from {@linkcode runCommand}.
107
+ *
108
+ * Contains the exit code, captured stdout/stderr output, recorded
109
+ * {@linkcode ActivityEvent | activity events}, and an `error` field
110
+ * that is `undefined` on success and a {@linkcode CLIError} on failure.
111
+ *
112
+ * @example
113
+ * ```ts
114
+ * const result = await runCommand(greetCmd, ['World']);
115
+ *
116
+ * expect(result.exitCode).toBe(0);
117
+ * expect(result.stdout).toContain('Hello, World!');
118
+ * expect(result.error).toBeUndefined();
119
+ * ```
120
+ */
121
+ export type { RunOptions, RunResult };
122
+
123
+ export { runCommand };
package/src/index.ts ADDED
@@ -0,0 +1,170 @@
1
+ /**
2
+ * DreamCLI — Schema-first, fully typed TypeScript CLI framework.
3
+ *
4
+ * Start here for most applications:
5
+ * - {@link cli} to define a program
6
+ * - {@link command} to define commands and groups
7
+ * - {@link flag} and {@link arg} to describe inputs
8
+ *
9
+ * This root entrypoint also re-exports lower-level building blocks such as
10
+ * parsing, resolution, config discovery, and help formatting. Those are useful
11
+ * for advanced integrations, custom tooling, or focused tests, but they are
12
+ * not the typical starting point for application code.
13
+ *
14
+ * Test utilities (runCommand, createCaptureOutput, createTestPrompter, etc.)
15
+ * are available from `@kjanat/dreamcli/testkit`. Runtime adapters (createAdapter,
16
+ * RuntimeAdapter, etc.) are available from `@kjanat/dreamcli/runtime`.
17
+ *
18
+ * @module @kjanat/dreamcli
19
+ */
20
+
21
+ export type {
22
+ BeforeParseParams,
23
+ CLIOptions,
24
+ CLIPlugin,
25
+ CLIPluginHooks,
26
+ CLIRunOptions,
27
+ CLISchema,
28
+ ConfigSettings,
29
+ PackageJsonSettings,
30
+ PluginCommandContext,
31
+ ResolvedCommandParams,
32
+ } from './core/cli/index.ts';
33
+ export { CLIBuilder, cli, plugin } from './core/cli/index.ts';
34
+ export type { CompletionOptions, Shell } from './core/completion/index.ts';
35
+ export {
36
+ generateBashCompletion,
37
+ generateCompletion,
38
+ generateFishCompletion,
39
+ generatePowerShellCompletion,
40
+ generateZshCompletion,
41
+ SHELLS,
42
+ } from './core/completion/index.ts';
43
+ export type {
44
+ ConfigAdapter,
45
+ ConfigDiscoveryOptions,
46
+ ConfigDiscoveryResult,
47
+ ConfigFound,
48
+ ConfigNotFound,
49
+ FormatLoader,
50
+ PackageJsonAdapter,
51
+ PackageJsonData,
52
+ } from './core/config/index.ts';
53
+ export {
54
+ buildConfigSearchPaths,
55
+ configFormat,
56
+ discoverConfig,
57
+ discoverPackageJson,
58
+ inferCliName,
59
+ } from './core/config/index.ts';
60
+ export type {
61
+ CLIErrorJSON,
62
+ CLIErrorOptions,
63
+ ErrorCode,
64
+ ParseErrorCode,
65
+ ParseErrorOptions,
66
+ ValidationErrorCode,
67
+ ValidationErrorOptions,
68
+ } from './core/errors/index.ts';
69
+ export {
70
+ CLIError,
71
+ isCLIError,
72
+ isParseError,
73
+ isValidationError,
74
+ ParseError,
75
+ ValidationError,
76
+ } from './core/errors/index.ts';
77
+ export type { HelpOptions } from './core/help/index.ts';
78
+ export { formatHelp } from './core/help/index.ts';
79
+ export type { JsonSchemaOptions } from './core/json-schema/index.ts';
80
+ export {
81
+ definitionMetaSchema,
82
+ generateInputSchema,
83
+ generateSchema,
84
+ } from './core/json-schema/index.ts';
85
+ export type { OutputOptions, Verbosity, WriteFn } from './core/output/index.ts';
86
+ export { createOutput } from './core/output/index.ts';
87
+ export type { ParseResult, Token } from './core/parse/index.ts';
88
+ export { parse, tokenize } from './core/parse/index.ts';
89
+ export type {
90
+ PromptEngine,
91
+ ReadFn,
92
+ ResolvedMultiselectPromptConfig,
93
+ ResolvedPromptConfig,
94
+ ResolvedSelectPromptConfig,
95
+ } from './core/prompt/index.ts';
96
+ export { createTerminalPrompter, resolvePromptConfig } from './core/prompt/index.ts';
97
+ export type { DeprecationWarning, ResolveOptions, ResolveResult } from './core/resolve/index.ts';
98
+ export { resolve } from './core/resolve/index.ts';
99
+ export type {
100
+ ActionHandler,
101
+ ActionParams,
102
+ ActivityEvent,
103
+ AnyCommandBuilder,
104
+ ArgConfig,
105
+ ArgFactory,
106
+ ArgKind,
107
+ ArgParseFn,
108
+ ArgPresence,
109
+ ArgSchema,
110
+ CommandArgEntry,
111
+ CommandConfig,
112
+ CommandExample,
113
+ CommandMeta,
114
+ CommandSchema,
115
+ ConfirmPromptConfig,
116
+ DeriveHandler,
117
+ DeriveParams,
118
+ Fallback,
119
+ FlagConfig,
120
+ FlagFactory,
121
+ FlagKind,
122
+ FlagParseFn,
123
+ FlagPresence,
124
+ FlagSchema,
125
+ InferArg,
126
+ InferArgs,
127
+ InferFlag,
128
+ InferFlags,
129
+ InputPromptConfig,
130
+ InteractiveParams,
131
+ InteractiveResolver,
132
+ InteractiveResult,
133
+ Middleware,
134
+ MiddlewareHandler,
135
+ MiddlewareParams,
136
+ MultiselectPromptConfig,
137
+ Out,
138
+ ProgressHandle,
139
+ ProgressOptions,
140
+ PromptConfig,
141
+ PromptConfigBase,
142
+ PromptKind,
143
+ PromptResult,
144
+ ResolvedArgValue,
145
+ ResolvedValue,
146
+ RunResult,
147
+ SelectChoice,
148
+ SelectPromptConfig,
149
+ SpinnerHandle,
150
+ SpinnerOptions,
151
+ TableColumn,
152
+ TableFormat,
153
+ TableOptions,
154
+ TableStream,
155
+ WithArgPresence,
156
+ WithPresence,
157
+ WithVariadic,
158
+ } from './core/schema/index.ts';
159
+ export {
160
+ ArgBuilder,
161
+ arg,
162
+ CommandBuilder,
163
+ command,
164
+ createArgSchema,
165
+ createSchema,
166
+ FlagBuilder,
167
+ flag,
168
+ group,
169
+ middleware,
170
+ } from './core/schema/index.ts';
@@ -0,0 +1,303 @@
1
+ /**
2
+ * Runtime adapter interface. Core never imports runtime-specific modules directly;
3
+ * all platform-dependent behavior flows through this contract.
4
+ *
5
+ * The adapter abstracts the minimal set of platform-dependent operations:
6
+ * argv/env access, I/O streams, TTY detection, working directory, and
7
+ * process exit. Concrete implementations exist for Node, Bun, and Deno.
8
+ *
9
+ * @module @kjanat/dreamcli/runtime/adapter
10
+ */
11
+
12
+ import type { WriteFn } from '#internals/core/output/index.ts';
13
+ import type { ReadFn } from '#internals/core/prompt/index.ts';
14
+
15
+ // --- Runtime adapter interface — the single platform abstraction boundary
16
+
17
+ /**
18
+ * Runtime adapter interface.
19
+ *
20
+ * Defines the minimal contract between the platform-agnostic core and
21
+ * the host runtime (Node.js, Bun, Deno). Every platform-dependent
22
+ * operation flows through this interface — the core never calls
23
+ * `process.*`, `Deno.*`, or `Bun.*` directly.
24
+ *
25
+ * Adapters are designed to be:
26
+ * - **Immutable in shape:** all properties are readonly
27
+ * - **Minimal:** only the operations the framework actually needs
28
+ * - **Testable:** easily stubbed in tests via {@linkcode createTestAdapter | createTestAdapter()}
29
+ *
30
+ * @example
31
+ * ```ts
32
+ * // Production: auto-detected
33
+ * cli('mycli').run(); // uses Node/Bun/Deno adapter
34
+ *
35
+ * // Test: explicit adapter
36
+ * cli('mycli').run({ adapter: createTestAdapter({ argv: ['deploy'] }) });
37
+ * ```
38
+ */
39
+ interface RuntimeAdapter {
40
+ /** Raw argv array (including binary + script path, e.g. `['node', 'cli.js', 'deploy']`). */
41
+ readonly argv: readonly string[];
42
+
43
+ /**
44
+ * Environment variables.
45
+ * Values are `string | undefined` — mirrors Node's `process.env` semantics.
46
+ */
47
+ readonly env: Readonly<Record<string, string | undefined>>;
48
+
49
+ /** Current working directory (absolute path). */
50
+ readonly cwd: string;
51
+
52
+ /** Writer for stdout. Framework routes `out.log`/`out.info` through this. */
53
+ readonly stdout: WriteFn;
54
+
55
+ /** Writer for stderr. Framework routes `out.warn`/`out.error` through this. */
56
+ readonly stderr: WriteFn;
57
+
58
+ /**
59
+ * Line reader for stdin. Used by the prompt engine for interactive input.
60
+ *
61
+ * Returns `null` on EOF (Ctrl+D on Unix, Ctrl+Z on Windows),
62
+ * indicating the user closed the input stream (treated as cancel).
63
+ */
64
+ readonly stdin: ReadFn;
65
+
66
+ /**
67
+ * Read all of stdin as a single string (for piped data).
68
+ *
69
+ * Returns the full stdin contents when data is piped (`stdinIsTTY` is
70
+ * false), or `null` when stdin is a TTY (no piped data available).
71
+ *
72
+ * Used by the resolve chain for args with `.stdin()` configured.
73
+ * Unlike {@link stdin} (which reads one line for prompts), this
74
+ * consumes the entire stream to EOF.
75
+ *
76
+ * @returns Full stdin contents as a string, or `null` if stdin is a TTY.
77
+ */
78
+ readonly readStdin: () => Promise<string | null>;
79
+
80
+ /** Whether stdout is connected to a TTY. */
81
+ readonly isTTY: boolean;
82
+
83
+ /** Whether stdin is connected to a TTY (used for prompt gating). */
84
+ readonly stdinIsTTY: boolean;
85
+
86
+ /**
87
+ * Exit the process with the given code.
88
+ * Must not return (divergent function).
89
+ */
90
+ readonly exit: (code: number) => never;
91
+
92
+ // --- Filesystem primitives (config file discovery) ---
93
+
94
+ /**
95
+ * Read a file as UTF-8 text.
96
+ *
97
+ * Returns file contents on success, `null` if the file does not exist
98
+ * (ENOENT/NotFound). Throws on other I/O errors (permission denied,
99
+ * is-directory, etc.) — those indicate unexpected failures, not
100
+ * "try the next path".
101
+ *
102
+ * Used by config file discovery to probe multiple candidate paths.
103
+ */
104
+ readonly readFile: (path: string) => Promise<string | null>;
105
+
106
+ /**
107
+ * User home directory (absolute path).
108
+ *
109
+ * - Node/Bun: derived from `HOME` / `USERPROFILE` env
110
+ * - Deno: `Deno.env.get('HOME')` / `Deno.env.get('USERPROFILE')`
111
+ */
112
+ readonly homedir: string;
113
+
114
+ /**
115
+ * Platform-specific user configuration directory (absolute path).
116
+ *
117
+ * - Unix: `$XDG_CONFIG_HOME` or `~/.config`
118
+ * - Windows: `%APPDATA%` or `~\AppData\Roaming`
119
+ *
120
+ * Config discovery appends the app-specific subdirectory.
121
+ */
122
+ readonly configDir: string;
123
+ }
124
+
125
+ // --- Test adapter — injectable stub for testing
126
+
127
+ /**
128
+ * Options for creating a test adapter.
129
+ *
130
+ * All fields are optional — sensible defaults are applied for testing
131
+ * scenarios (empty argv, empty env, noop stdout/stderr, non-TTY, exit
132
+ * throws instead of killing the process).
133
+ */
134
+ interface TestAdapterOptions {
135
+ /** Raw argv (defaults to `['node', 'test']`). */
136
+ readonly argv?: readonly string[];
137
+
138
+ /** Environment variables (defaults to `{}`). */
139
+ readonly env?: Readonly<Record<string, string | undefined>>;
140
+
141
+ /** Working directory (defaults to `'/test'`). */
142
+ readonly cwd?: string;
143
+
144
+ /** Stdout writer (defaults to noop). */
145
+ readonly stdout?: WriteFn;
146
+
147
+ /** Stderr writer (defaults to noop). */
148
+ readonly stderr?: WriteFn;
149
+
150
+ /**
151
+ * Stdin line reader (defaults to returning `null` — immediate EOF).
152
+ *
153
+ * Use a custom {@linkcode ReadFn} to simulate user input in tests.
154
+ */
155
+ readonly stdin?: ReadFn;
156
+
157
+ /**
158
+ * Piped stdin data for testing args with `.stdin()` configured.
159
+ *
160
+ * When provided and `stdinIsTTY` is `false`, `readStdin()` returns this
161
+ * string once, then `null` on subsequent reads. When absent, or when
162
+ * `stdinIsTTY` is `true`, `readStdin()` returns `null`.
163
+ *
164
+ * @example
165
+ * ```ts
166
+ * createTestAdapter({
167
+ * stdinData: '{"key": "value"}',
168
+ * })
169
+ * ```
170
+ */
171
+ readonly stdinData?: string;
172
+
173
+ /** TTY flag for stdout (defaults to `false`). */
174
+ readonly isTTY?: boolean;
175
+
176
+ /** TTY flag for stdin (defaults to `false`). */
177
+ readonly stdinIsTTY?: boolean;
178
+
179
+ /**
180
+ * Exit function (defaults to throwing {@linkcode ExitError}).
181
+ * The default throw-based exit allows tests to catch the exit code.
182
+ */
183
+ readonly exit?: (code: number) => never;
184
+
185
+ // --- Filesystem stubs ---
186
+
187
+ /**
188
+ * File reader stub (defaults to returning `null` — all files not found).
189
+ *
190
+ * Supply a custom function to simulate a virtual filesystem in tests:
191
+ * ```ts
192
+ * createTestAdapter({
193
+ * readFile: (path) => Promise.resolve(
194
+ * path === '/home/test/.config/myapp/config.json'
195
+ * ? '{"region":"eu"}'
196
+ * : null
197
+ * ),
198
+ * })
199
+ * ```
200
+ */
201
+ readonly readFile?: (path: string) => Promise<string | null>;
202
+
203
+ /** Home directory (defaults to `'/home/test'`). */
204
+ readonly homedir?: string;
205
+
206
+ /** Config directory (defaults to `'/home/test/.config'`). */
207
+ readonly configDir?: string;
208
+ }
209
+
210
+ /**
211
+ * Error thrown by adapter implementations that model process exit as an
212
+ * exception instead of terminating immediately.
213
+ *
214
+ * Runtime and CLI dispatch layers can catch this to perform real process
215
+ * termination, while tests can assert on exit codes without killing the
216
+ * runner:
217
+ *
218
+ * ```ts
219
+ * try {
220
+ * await cli.run({ adapter: createTestAdapter() });
221
+ * } catch (e) {
222
+ * if (e instanceof ExitError) expect(e.code).toBe(0);
223
+ * }
224
+ * ```
225
+ */
226
+ class ExitError extends Error {
227
+ /** Error name — always `'ExitError'` for `instanceof` checks. */
228
+ override readonly name = 'ExitError';
229
+
230
+ /** The exit code passed to `exit()`. */
231
+ readonly code: number;
232
+
233
+ /** Create an ExitError for the given process exit code. */
234
+ constructor(code: number) {
235
+ super(`Process exited with code ${code}`);
236
+ this.code = code;
237
+ }
238
+ }
239
+
240
+ /** Noop writer — silently discards output. */
241
+ const noopWrite: WriteFn = () => {};
242
+
243
+ /** Noop reader — returns `null` (EOF) immediately. */
244
+ const eofRead: ReadFn = () => Promise.resolve(null);
245
+
246
+ /** Noop file reader — returns `null` (not found) for all paths. */
247
+ const noopReadFile: (path: string) => Promise<string | null> = () => Promise.resolve(null);
248
+
249
+ /**
250
+ * Create a test runtime adapter with injectable process state.
251
+ *
252
+ * Use this in `@kjanat/dreamcli/testkit` tests when you need to simulate argv,
253
+ * environment variables, TTY state, stdin, or config-file reads without
254
+ * touching the host process.
255
+ *
256
+ * @param options - Optional overrides for any adapter field.
257
+ * @returns A {@linkcode RuntimeAdapter} suitable for test scenarios.
258
+ *
259
+ * @example
260
+ * ```ts
261
+ * const adapter = createTestAdapter({
262
+ * argv: ['node', 'cli.js', 'deploy', '--force'],
263
+ * env: { DEPLOY_REGION: 'us' },
264
+ * });
265
+ *
266
+ * const result = await cli('mycli').run({ adapter });
267
+ * ```
268
+ */
269
+ function createTestAdapter(options?: TestAdapterOptions): RuntimeAdapter {
270
+ const stdinIsTTY = options?.stdinIsTTY ?? false;
271
+ let stdinData = !stdinIsTTY ? options?.stdinData : undefined;
272
+ return {
273
+ argv: options?.argv ?? ['node', 'test'],
274
+ env: options?.env ?? {},
275
+ cwd: options?.cwd ?? '/test',
276
+ stdout: options?.stdout ?? noopWrite,
277
+ stderr: options?.stderr ?? noopWrite,
278
+ stdin: options?.stdin ?? eofRead,
279
+ readStdin: () => {
280
+ if (stdinData === undefined) {
281
+ return Promise.resolve(null);
282
+ }
283
+ const result = stdinData;
284
+ stdinData = undefined;
285
+ return Promise.resolve(result);
286
+ },
287
+ isTTY: options?.isTTY ?? false,
288
+ stdinIsTTY,
289
+ exit:
290
+ options?.exit ??
291
+ ((code: number): never => {
292
+ throw new ExitError(code);
293
+ }),
294
+ readFile: options?.readFile ?? noopReadFile,
295
+ homedir: options?.homedir ?? '/home/test',
296
+ configDir: options?.configDir ?? '/home/test/.config',
297
+ };
298
+ }
299
+
300
+ // --- Exports
301
+
302
+ export type { RuntimeAdapter, TestAdapterOptions };
303
+ export { createTestAdapter, ExitError };
@@ -0,0 +1,110 @@
1
+ /**
2
+ * Auto-detecting adapter factory.
3
+ *
4
+ * Uses {@link detectRuntime} to identify the current runtime and
5
+ * creates the appropriate {@link RuntimeAdapter}. Falls back to the
6
+ * Node adapter for unknown runtimes (safest default — most runtimes
7
+ * provide a Node-compatible `process` global).
8
+ *
9
+ * @module @kjanat/dreamcli/runtime/auto
10
+ */
11
+
12
+ import type { RuntimeAdapter } from './adapter.ts';
13
+ import { createBunAdapter } from './bun.ts';
14
+ import type { DenoNamespace } from './deno.ts';
15
+ import { createDenoAdapter } from './deno.ts';
16
+ import type { GlobalForDetect } from './detect.ts';
17
+ import { detectRuntime } from './detect.ts';
18
+ import { createNodeAdapter } from './node.ts';
19
+ import { assertRuntimeVersionSupported } from './support.ts';
20
+
21
+ function detectRuntimeVersion(
22
+ runtime: ReturnType<typeof detectRuntime>,
23
+ globals: GlobalForDetect,
24
+ ): string | undefined {
25
+ switch (runtime) {
26
+ case 'bun':
27
+ return globals.Bun?.version;
28
+ case 'deno':
29
+ return globals.Deno?.version?.deno;
30
+ case 'node':
31
+ return globals.process?.versions?.node;
32
+ case 'unknown':
33
+ return undefined;
34
+ default: {
35
+ const _exhaustive: never = runtime;
36
+ return _exhaustive;
37
+ }
38
+ }
39
+ }
40
+
41
+ function isDenoNamespace(value: unknown): value is DenoNamespace {
42
+ if (typeof value !== 'object' || value === null) return false;
43
+
44
+ const candidate = value as Partial<DenoNamespace>;
45
+ return (
46
+ Array.isArray(candidate.args) &&
47
+ typeof candidate.cwd === 'function' &&
48
+ typeof candidate.exit === 'function' &&
49
+ typeof candidate.readTextFile === 'function' &&
50
+ typeof candidate.env?.get === 'function' &&
51
+ typeof candidate.env.toObject === 'function' &&
52
+ typeof candidate.stdout?.writeSync === 'function' &&
53
+ typeof candidate.stdout.isTerminal === 'function' &&
54
+ typeof candidate.stderr?.writeSync === 'function' &&
55
+ typeof candidate.stdin?.isTerminal === 'function' &&
56
+ typeof candidate.stdin?.readable?.getReader === 'function'
57
+ );
58
+ }
59
+
60
+ function getInjectedDenoNamespace(globals: GlobalForDetect): DenoNamespace | undefined {
61
+ const candidate = (globals as { readonly Deno?: unknown }).Deno;
62
+ return isDenoNamespace(candidate) ? candidate : undefined;
63
+ }
64
+
65
+ // --- Auto-adapter factory
66
+
67
+ /**
68
+ * Create a runtime adapter for the current environment.
69
+ *
70
+ * Detection order follows {@link detectRuntime}: Bun → Deno → Node → unknown.
71
+ * Unknown runtimes fall back to the Node adapter because most JS runtimes
72
+ * expose a Node-compatible `process` global.
73
+ *
74
+ * @param globals - Override `globalThis` for testing. Production callers
75
+ * should omit this parameter.
76
+ * @returns A {@linkcode RuntimeAdapter} for the detected runtime.
77
+ *
78
+ * @example
79
+ * ```ts
80
+ * import { cli } from '@kjanat/dreamcli';
81
+ *
82
+ * // Auto-detects Node/Bun/Deno and creates the right adapter
83
+ * cli('mycli').run(); // uses createAdapter() internally
84
+ * ```
85
+ */
86
+ function createAdapter(globals?: GlobalForDetect): RuntimeAdapter {
87
+ const runtimeGlobals = globals ?? globalThis;
88
+ const runtime = detectRuntime(runtimeGlobals);
89
+ if (runtime !== 'unknown') {
90
+ assertRuntimeVersionSupported(runtime, detectRuntimeVersion(runtime, runtimeGlobals));
91
+ }
92
+
93
+ switch (runtime) {
94
+ case 'bun':
95
+ return createBunAdapter();
96
+ case 'deno':
97
+ return createDenoAdapter(getInjectedDenoNamespace(runtimeGlobals));
98
+ case 'node':
99
+ case 'unknown':
100
+ return createNodeAdapter();
101
+ default: {
102
+ const _exhaustive: never = runtime;
103
+ return _exhaustive;
104
+ }
105
+ }
106
+ }
107
+
108
+ // --- Exports
109
+
110
+ export { createAdapter };