@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
package/dist/index.d.mts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { ActivityEvent, Fallback, ProgressHandle, ProgressOptions, SpinnerHandle, SpinnerOptions, TableColumn, TableFormat, TableOptions, TableStream } from "./core/schema/activity.mjs";
2
+ import { NumberConstraintViolation, NumberConstraints } from "./core/schema/number-constraints.mjs";
2
3
  import { ArgBuilder, ArgConfig, ArgFactory, ArgKind, ArgParseFn, ArgPresence, ArgSchema, InferArg, InferArgs, ResolvedArgValue, WithArgPresence, WithVariadic, arg, createArgSchema } from "./core/schema/arg.mjs";
3
4
  import { ConfirmPromptConfig, InputPromptConfig, MultiselectPromptConfig, PromptConfig, PromptConfigBase, PromptKind, PromptResult, SelectChoice, SelectPromptConfig } from "./core/schema/prompt.mjs";
4
5
  import { FlagBuilder, FlagConfig, FlagFactory, FlagKind, FlagParseFn, FlagPresence, FlagSchema, InferFlag, InferFlags, ResolvedValue, WithPresence, createSchema, flag } from "./core/schema/flag.mjs";
@@ -27,4 +28,5 @@ import { SHELLS, Shell, generateCompletion } from "./core/completion/index.mjs";
27
28
  import { ConfigAdapter, ConfigDiscoveryOptions, ConfigDiscoveryResult, ConfigFound, ConfigNotFound, FormatLoader, buildConfigSearchPaths, configFormat, discoverConfig } from "./core/config/index.mjs";
28
29
  import { CLIBuilder, CLIOptions, CLIRunOptions, CLISchema, ConfigSettings, InferNameOption, ManifestPresetSettings, ManifestSettings, PackageJsonSettings, ResolvedManifestSettings, cli } from "./core/cli/index.mjs";
29
30
  import { JsonSchemaOptions, definitionMetaSchema, generateInputSchema, generateSchema } from "./core/json-schema/index.mjs";
30
- export { type ActionHandler, type ActionParams, type ActivityEvent, type AnyCommandBuilder, ArgBuilder, type ArgConfig, type ArgFactory, type ArgKind, type ArgParseFn, type ArgPresence, type ArgSchema, type BeforeParseParams, CLIBuilder, CLIError, type CLIErrorJSON, type CLIErrorOptions, type CLIOptions, type CLIPlugin, type CLIPluginHooks, type CLIRunOptions, type CLISchema, type CommandArgEntry, CommandBuilder, type CommandConfig, type CommandExample, type CommandMeta, type CommandSchema, type CompletionOptions, type ConfigAdapter, type ConfigDiscoveryOptions, type ConfigDiscoveryResult, type ConfigFound, type ConfigNotFound, type ConfigSettings, type ConfirmPromptConfig, type DeprecationWarning, type DeriveHandler, type DeriveParams, type ErrorCode, type Fallback, FlagBuilder, type FlagConfig, type FlagFactory, type FlagKind, type FlagParseFn, type FlagPresence, type FlagSchema, type FormatLoader, type HelpLinks, type HelpOptions, type InferArg, type InferArgs, type InferFlag, type InferFlags, type InferNameOption, type InputPromptConfig, type InteractiveParams, type InteractiveResolver, type InteractiveResult, type JsonSchemaOptions, type ManifestDiscoveryOptions, type ManifestPresetSettings, type ManifestSettings, type Middleware, type MiddlewareHandler, type MiddlewareParams, type MultiselectPromptConfig, type Out, type OutputOptions, type PackageJsonAdapter, type PackageJsonData, type PackageJsonSettings, type PackageRepository, ParseError, type ParseErrorCode, type ParseErrorOptions, type ParseResult, type PluginCommandContext, type ProgressHandle, type ProgressOptions, type PromptConfig, type PromptConfigBase, type PromptEngine, type PromptKind, type PromptResult, type ReadFn, type ResolveOptions, type ResolveResult, type ResolvedArgValue, type ResolvedCommandParams, type ResolvedManifestSettings, type ResolvedMultiselectPromptConfig, type ResolvedPromptConfig, type ResolvedSelectPromptConfig, type ResolvedValue, type RunResult, SHELLS, type SelectChoice, type SelectPromptConfig, type Shell, type SpinnerHandle, type SpinnerOptions, type TableColumn, type TableFormat, type TableOptions, type TableStream, type Token, ValidationError, type ValidationErrorCode, type ValidationErrorOptions, type Verbosity, type WithArgPresence, type WithPresence, type WithVariadic, type WriteFn, arg, buildConfigSearchPaths, cli, command, configFormat, createArgSchema, createOutput, createSchema, createTerminalPrompter, definitionMetaSchema, discoverConfig, discoverManifest, discoverPackageJson, flag, formatHelp, generateBashCompletion, generateCompletion, generateFishCompletion, generateInputSchema, generatePowerShellCompletion, generateSchema, generateZshCompletion, group, inferCliName, isCLIError, isParseError, isValidationError, middleware, osc8, packageRepositoryUrl, parse, plugin, resolve, resolvePromptConfig, tokenize, visibleWidth };
31
+ import { Colors } from "ansispeck";
32
+ export { type ActionHandler, type ActionParams, type ActivityEvent, type AnyCommandBuilder, ArgBuilder, type ArgConfig, type ArgFactory, type ArgKind, type ArgParseFn, type ArgPresence, type ArgSchema, type BeforeParseParams, CLIBuilder, CLIError, type CLIErrorJSON, type CLIErrorOptions, type CLIOptions, type CLIPlugin, type CLIPluginHooks, type CLIRunOptions, type CLISchema, type Colors, type CommandArgEntry, CommandBuilder, type CommandConfig, type CommandExample, type CommandMeta, type CommandSchema, type CompletionOptions, type ConfigAdapter, type ConfigDiscoveryOptions, type ConfigDiscoveryResult, type ConfigFound, type ConfigNotFound, type ConfigSettings, type ConfirmPromptConfig, type DeprecationWarning, type DeriveHandler, type DeriveParams, type ErrorCode, type Fallback, FlagBuilder, type FlagConfig, type FlagFactory, type FlagKind, type FlagParseFn, type FlagPresence, type FlagSchema, type FormatLoader, type HelpLinks, type HelpOptions, type InferArg, type InferArgs, type InferFlag, type InferFlags, type InferNameOption, type InputPromptConfig, type InteractiveParams, type InteractiveResolver, type InteractiveResult, type JsonSchemaOptions, type ManifestDiscoveryOptions, type ManifestPresetSettings, type ManifestSettings, type Middleware, type MiddlewareHandler, type MiddlewareParams, type MultiselectPromptConfig, type NumberConstraintViolation, type NumberConstraints, type Out, type OutputOptions, type PackageJsonAdapter, type PackageJsonData, type PackageJsonSettings, type PackageRepository, ParseError, type ParseErrorCode, type ParseErrorOptions, type ParseResult, type PluginCommandContext, type ProgressHandle, type ProgressOptions, type PromptConfig, type PromptConfigBase, type PromptEngine, type PromptKind, type PromptResult, type ReadFn, type ResolveOptions, type ResolveResult, type ResolvedArgValue, type ResolvedCommandParams, type ResolvedManifestSettings, type ResolvedMultiselectPromptConfig, type ResolvedPromptConfig, type ResolvedSelectPromptConfig, type ResolvedValue, type RunResult, SHELLS, type SelectChoice, type SelectPromptConfig, type Shell, type SpinnerHandle, type SpinnerOptions, type TableColumn, type TableFormat, type TableOptions, type TableStream, type Token, ValidationError, type ValidationErrorCode, type ValidationErrorOptions, type Verbosity, type WithArgPresence, type WithPresence, type WithVariadic, type WriteFn, arg, buildConfigSearchPaths, cli, command, configFormat, createArgSchema, createOutput, createSchema, createTerminalPrompter, definitionMetaSchema, discoverConfig, discoverManifest, discoverPackageJson, flag, formatHelp, generateBashCompletion, generateCompletion, generateFishCompletion, generateInputSchema, generatePowerShellCompletion, generateSchema, generateZshCompletion, group, inferCliName, isCLIError, isParseError, isValidationError, middleware, osc8, packageRepositoryUrl, parse, plugin, resolve, resolvePromptConfig, tokenize, visibleWidth };
package/dist/index.mjs CHANGED
@@ -1 +1,22 @@
1
- import{FlagBuilder as e,createSchema as t,flag as n}from"./core/schema/flag.mjs";import{generateBashCompletion as r}from"./core/completion/shells/bash.mjs";import{generateFishCompletion as i}from"./core/completion/shells/fish.mjs";import{generatePowerShellCompletion as a}from"./core/completion/shells/powershell.mjs";import{CLIError as o,ParseError as s,ValidationError as c,isCLIError as l,isParseError as u,isValidationError as d}from"./core/errors/index.mjs";import{generateZshCompletion as f}from"./core/completion/shells/zsh.mjs";import{SHELLS as p,generateCompletion as m}from"./core/completion/index.mjs";import{osc8 as h,visibleWidth as g}from"./core/help/ansi.mjs";import{formatHelp as _}from"./core/help/index.mjs";import{createOutput as v}from"./core/output/index.mjs";import{parse as y,tokenize as b}from"./core/parse/index.mjs";import{createTerminalPrompter as x,resolvePromptConfig as S}from"./core/prompt/index.mjs";import{resolve as C}from"./core/resolve/index.mjs";import{ArgBuilder as w,arg as T,createArgSchema as E}from"./core/schema/arg.mjs";import{CommandBuilder as D,command as O,group as k}from"./core/schema/command.mjs";import{discoverManifest as A,discoverPackageJson as j,inferCliName as M,packageRepositoryUrl as N}from"./core/config/package-json.mjs";import{plugin as P}from"./core/cli/plugin.mjs";import{buildConfigSearchPaths as F,configFormat as I,discoverConfig as L}from"./core/config/index.mjs";import{CLIBuilder as R,cli as z}from"./core/cli/index.mjs";import{definitionMetaSchema as B,generateInputSchema as V,generateSchema as H}from"./core/json-schema/index.mjs";import{middleware as U}from"./core/schema/middleware.mjs";export{w as ArgBuilder,R as CLIBuilder,o as CLIError,D as CommandBuilder,e as FlagBuilder,s as ParseError,p as SHELLS,c as ValidationError,T as arg,F as buildConfigSearchPaths,z as cli,O as command,I as configFormat,E as createArgSchema,v as createOutput,t as createSchema,x as createTerminalPrompter,B as definitionMetaSchema,L as discoverConfig,A as discoverManifest,j as discoverPackageJson,n as flag,_ as formatHelp,r as generateBashCompletion,m as generateCompletion,i as generateFishCompletion,V as generateInputSchema,a as generatePowerShellCompletion,H as generateSchema,f as generateZshCompletion,k as group,M as inferCliName,l as isCLIError,u as isParseError,d as isValidationError,U as middleware,h as osc8,N as packageRepositoryUrl,y as parse,P as plugin,C as resolve,S as resolvePromptConfig,b as tokenize,g as visibleWidth};
1
+ import { FlagBuilder, createSchema, flag } from "./core/schema/flag.mjs";
2
+ import { generateBashCompletion } from "./core/completion/shells/bash.mjs";
3
+ import { generateFishCompletion } from "./core/completion/shells/fish.mjs";
4
+ import { generatePowerShellCompletion } from "./core/completion/shells/powershell.mjs";
5
+ import { CLIError, ParseError, ValidationError, isCLIError, isParseError, isValidationError } from "./core/errors/index.mjs";
6
+ import { generateZshCompletion } from "./core/completion/shells/zsh.mjs";
7
+ import { SHELLS, generateCompletion } from "./core/completion/index.mjs";
8
+ import { osc8, visibleWidth } from "./core/help/ansi.mjs";
9
+ import { formatHelp } from "./core/help/index.mjs";
10
+ import { createOutput } from "./core/output/index.mjs";
11
+ import { ArgBuilder, arg, createArgSchema } from "./core/schema/arg.mjs";
12
+ import { CommandBuilder, command, group } from "./core/schema/command.mjs";
13
+ import { middleware } from "./core/schema/middleware.mjs";
14
+ import { parse, tokenize } from "./core/parse/index.mjs";
15
+ import { createTerminalPrompter, resolvePromptConfig } from "./core/prompt/index.mjs";
16
+ import { resolve } from "./core/resolve/index.mjs";
17
+ import { discoverManifest, discoverPackageJson, inferCliName, packageRepositoryUrl } from "./core/config/package-json.mjs";
18
+ import { plugin } from "./core/cli/plugin.mjs";
19
+ import { buildConfigSearchPaths, configFormat, discoverConfig } from "./core/config/index.mjs";
20
+ import { CLIBuilder, cli } from "./core/cli/index.mjs";
21
+ import { definitionMetaSchema, generateInputSchema, generateSchema } from "./core/json-schema/index.mjs";
22
+ export { ArgBuilder, CLIBuilder, CLIError, CommandBuilder, FlagBuilder, ParseError, SHELLS, ValidationError, arg, buildConfigSearchPaths, cli, command, configFormat, createArgSchema, createOutput, createSchema, createTerminalPrompter, definitionMetaSchema, discoverConfig, discoverManifest, discoverPackageJson, flag, formatHelp, generateBashCompletion, generateCompletion, generateFishCompletion, generateInputSchema, generatePowerShellCompletion, generateSchema, generateZshCompletion, group, inferCliName, isCLIError, isParseError, isValidationError, middleware, osc8, packageRepositoryUrl, parse, plugin, resolve, resolvePromptConfig, tokenize, visibleWidth };
@@ -1 +1,82 @@
1
- var e=class extends Error{name=`ExitError`;code;constructor(e){super(`Process exited with code ${e}`),this.code=e}};const t=()=>{},n=()=>Promise.resolve(null),r=()=>Promise.resolve(null);function i(i){let a=i?.stdinIsTTY??!1,o=a?void 0:i?.stdinData;return{argv:i?.argv??[`node`,`test`],env:i?.env??{},cwd:i?.cwd??`/test`,stdout:i?.stdout??t,stderr:i?.stderr??t,stdin:i?.stdin??n,readStdin:()=>{if(o===void 0)return Promise.resolve(null);let e=o;return o=void 0,Promise.resolve(e)},isTTY:i?.isTTY??!1,stdinIsTTY:a,exit:i?.exit??(t=>{throw new e(t)}),readFile:i?.readFile??r,homedir:i?.homedir??`/home/test`,configDir:i?.configDir??`/home/test/.config`}}export{e as ExitError,i as createTestAdapter};
1
+ //#region src/runtime/adapter.ts
2
+ /**
3
+ * Error thrown by adapter implementations that model process exit as an
4
+ * exception instead of terminating immediately.
5
+ *
6
+ * Runtime and CLI dispatch layers can catch this to perform real process
7
+ * termination, while tests can assert on exit codes without killing the
8
+ * runner:
9
+ *
10
+ * ```ts
11
+ * try {
12
+ * await cli.run({ adapter: createTestAdapter() });
13
+ * } catch (e) {
14
+ * if (e instanceof ExitError) expect(e.code).toBe(0);
15
+ * }
16
+ * ```
17
+ */
18
+ var ExitError = class extends Error {
19
+ /** Error name — always `'ExitError'` for `instanceof` checks. */
20
+ name = "ExitError";
21
+ /** The exit code passed to `exit()`. */
22
+ code;
23
+ /** Create an ExitError for the given process exit code. */
24
+ constructor(code) {
25
+ super(`Process exited with code ${code}`);
26
+ this.code = code;
27
+ }
28
+ };
29
+ /** Noop writer — silently discards output. */
30
+ const noopWrite = () => {};
31
+ /** Noop reader — returns `null` (EOF) immediately. */
32
+ const eofRead = () => Promise.resolve(null);
33
+ /** Noop file reader — returns `null` (not found) for all paths. */
34
+ const noopReadFile = () => Promise.resolve(null);
35
+ /**
36
+ * Create a test runtime adapter with injectable process state.
37
+ *
38
+ * Use this in `@kjanat/dreamcli/testkit` tests when you need to simulate argv,
39
+ * environment variables, TTY state, stdin, or config-file reads without
40
+ * touching the host process.
41
+ *
42
+ * @param options - Optional overrides for any adapter field.
43
+ * @returns A {@linkcode RuntimeAdapter} suitable for test scenarios.
44
+ *
45
+ * @example
46
+ * ```ts
47
+ * const adapter = createTestAdapter({
48
+ * argv: ['node', 'cli.js', 'deploy', '--force'],
49
+ * env: { DEPLOY_REGION: 'us' },
50
+ * });
51
+ *
52
+ * const result = await cli('mycli').run({ adapter });
53
+ * ```
54
+ */
55
+ function createTestAdapter(options) {
56
+ const stdinIsTTY = options?.stdinIsTTY ?? false;
57
+ let stdinData = !stdinIsTTY ? options?.stdinData : void 0;
58
+ return {
59
+ argv: options?.argv ?? ["node", "test"],
60
+ env: options?.env ?? {},
61
+ cwd: options?.cwd ?? "/test",
62
+ stdout: options?.stdout ?? noopWrite,
63
+ stderr: options?.stderr ?? noopWrite,
64
+ stdin: options?.stdin ?? eofRead,
65
+ readStdin: () => {
66
+ if (stdinData === void 0) return Promise.resolve(null);
67
+ const result = stdinData;
68
+ stdinData = void 0;
69
+ return Promise.resolve(result);
70
+ },
71
+ isTTY: options?.isTTY ?? false,
72
+ stdinIsTTY,
73
+ exit: options?.exit ?? ((code) => {
74
+ throw new ExitError(code);
75
+ }),
76
+ readFile: options?.readFile ?? noopReadFile,
77
+ homedir: options?.homedir ?? "/home/test",
78
+ configDir: options?.configDir ?? "/home/test/.config"
79
+ };
80
+ }
81
+ //#endregion
82
+ export { ExitError, createTestAdapter };
@@ -1 +1,46 @@
1
- import{assertRuntimeVersionSupported as e}from"./support.mjs";import{createNodeAdapter as t}from"./node.mjs";import{createBunAdapter as n}from"./bun.mjs";import{createDenoAdapter as r}from"./deno.mjs";import{detectRuntime as i}from"./detect.mjs";function a(e,t){switch(e){case`bun`:return t.Bun?.version;case`deno`:return t.Deno?.version?.deno;case`node`:return t.process?.versions?.node;case`unknown`:return;default:return e}}function o(e){if(typeof e!=`object`||!e)return!1;let t=e;return Array.isArray(t.args)&&typeof t.cwd==`function`&&typeof t.exit==`function`&&typeof t.readTextFile==`function`&&typeof t.env?.get==`function`&&typeof t.env.toObject==`function`&&typeof t.stdout?.writeSync==`function`&&typeof t.stdout.isTerminal==`function`&&typeof t.stderr?.writeSync==`function`&&typeof t.stdin?.isTerminal==`function`&&typeof t.stdin?.readable?.getReader==`function`}function s(e){let t=e.Deno;return o(t)?t:void 0}function c(o){let c=o??globalThis,l=i(c);switch(l!==`unknown`&&e(l,a(l,c)),l){case`bun`:return n();case`deno`:return r(s(c));case`node`:case`unknown`:return t();default:return l}}export{c as createAdapter};
1
+ import { createNodeAdapter } from "./node.mjs";
2
+ import { createBunAdapter } from "./bun.mjs";
3
+ import { createDenoAdapter } from "./deno.mjs";
4
+ import { detectRuntime } from "./detect.mjs";
5
+ //#region src/runtime/auto.ts
6
+ function isDenoNamespace(value) {
7
+ if (typeof value !== "object" || value === null) return false;
8
+ const candidate = value;
9
+ return Array.isArray(candidate.args) && typeof candidate.cwd === "function" && typeof candidate.exit === "function" && typeof candidate.readTextFile === "function" && typeof candidate.env?.get === "function" && typeof candidate.env.toObject === "function" && typeof candidate.stdout?.writeSync === "function" && typeof candidate.stdout.isTerminal === "function" && typeof candidate.stderr?.writeSync === "function" && typeof candidate.stdin?.isTerminal === "function" && typeof candidate.stdin?.readable?.getReader === "function";
10
+ }
11
+ function getInjectedDenoNamespace(globals) {
12
+ const candidate = globals.Deno;
13
+ return isDenoNamespace(candidate) ? candidate : void 0;
14
+ }
15
+ /**
16
+ * Create a runtime adapter for the current environment.
17
+ *
18
+ * Detection order follows {@link detectRuntime}: Bun → Deno → Node → unknown.
19
+ * Unknown runtimes fall back to the Node adapter because most JS runtimes
20
+ * expose a Node-compatible `process` global.
21
+ *
22
+ * @param globals - Override `globalThis` for testing. Production callers
23
+ * should omit this parameter.
24
+ * @returns A {@linkcode RuntimeAdapter} for the detected runtime.
25
+ *
26
+ * @example
27
+ * ```ts
28
+ * import { cli } from '@kjanat/dreamcli';
29
+ *
30
+ * // Auto-detects Node/Bun/Deno and creates the right adapter
31
+ * cli('mycli').run(); // uses createAdapter() internally
32
+ * ```
33
+ */
34
+ function createAdapter(globals) {
35
+ const runtimeGlobals = globals ?? globalThis;
36
+ const runtime = detectRuntime(runtimeGlobals);
37
+ switch (runtime) {
38
+ case "bun": return createBunAdapter();
39
+ case "deno": return createDenoAdapter(getInjectedDenoNamespace(runtimeGlobals));
40
+ case "node":
41
+ case "unknown": return createNodeAdapter();
42
+ default: return runtime;
43
+ }
44
+ }
45
+ //#endregion
46
+ export { createAdapter };
@@ -1 +1,28 @@
1
- import{assertRuntimeVersionSupported as e}from"./support.mjs";import{createNodeAdapter as t}from"./node.mjs";function n(e){return e?.versions?.bun===void 0?globalThis.Bun?.version:e.versions.bun}function r(r){return e(`bun`,n(r)),t(r)}export{r as createBunAdapter};
1
+ import { createNodeAdapter } from "./node.mjs";
2
+ //#region src/runtime/bun.ts
3
+ /**
4
+ * Create a runtime adapter backed by Bun's Node-compatible `process` global.
5
+ *
6
+ * Bun exposes `globalThis.process` with the same shape as Node.js, so this
7
+ * delegates entirely to {@link createNodeAdapter}. If Bun-specific optimizations
8
+ * are needed in the future (e.g. `Bun.write` for I/O), they can be layered
9
+ * here without changing the public API.
10
+ *
11
+ * @param proc - Override the process object (useful for testing the adapter itself).
12
+ * @returns A {@linkcode RuntimeAdapter} backed by Bun's process state.
13
+ *
14
+ * @example
15
+ * ```ts
16
+ * import { cli } from '@kjanat/dreamcli';
17
+ * import { createBunAdapter } from '@kjanat/dreamcli/runtime';
18
+ *
19
+ * cli('mycli')
20
+ * .command(deploy)
21
+ * .run({ adapter: createBunAdapter() });
22
+ * ```
23
+ */
24
+ function createBunAdapter(proc) {
25
+ return createNodeAdapter(proc);
26
+ }
27
+ //#endregion
28
+ export { createBunAdapter };
@@ -1,2 +1,217 @@
1
- import{resolveConfigDirectory as e,resolveHomeDirectory as t}from"./paths.mjs";import{assertRuntimeVersionSupported as n}from"./support.mjs";function r(e,t){if(typeof e!=`object`||!e||!(`name`in e))return!1;let n=e;return typeof n.name==`string`&&n.name===t}function i(e){try{return e.env.toObject()}catch(e){if(r(e,`PermissionDenied`))return{};throw e}}function a(e){try{return e.cwd()}catch(e){if(r(e,`PermissionDenied`))return`/`;throw e}}function o(e){let t=e??s();n(`deno`,t.version?.deno);let o=new TextEncoder,f=[`deno`,`run`,...t.args],p=i(t),m=a(t),h=e=>{t.stdout.writeSync(o.encode(e))},g=e=>{t.stderr.writeSync(o.encode(e))},_=l(t),v=async e=>{try{return await t.readTextFile(e)}catch(e){if(r(e,`NotFound`)||r(e,`PermissionDenied`))return null;throw e}},y=u(p,t.build.os===`windows`),b=d(p,y,t.build.os===`windows`),x=t.stdin.isTerminal();return{argv:f,env:p,cwd:m,stdout:h,stderr:g,stdin:_,readStdin:()=>c(t,x),isTTY:t.stdout.isTerminal(),stdinIsTTY:x,exit:e=>t.exit(e),readFile:v,homedir:y,configDir:b}}function s(){return globalThis.Deno}async function c(e,t){if(t)return null;let n=e.stdin.readable.getReader(),r=new TextDecoder,i=[];try{for(;;){let{value:e,done:t}=await n.read();if(t){i.push(r.decode());break}i.push(r.decode(e,{stream:!0}))}}finally{n.releaseLock()}return i.join(``)}function l(e){let t=new TextDecoder,n=``,r=!1;return async()=>{let i=e.stdin.readable.getReader();try{for(;;){let e=n.indexOf(`
2
- `);if(e!==-1){let t=n.slice(0,e).replace(/\r$/,``);return n=n.slice(e+1),t}if(r){if(n.length===0)return null;let e=n;return n=``,e}let{value:a,done:o}=await i.read();if(o){n+=t.decode(),r=!0;continue}n+=t.decode(a,{stream:!0})}}finally{i.releaseLock()}}}function u(e,n){return t(e,n)}function d(t,n,r){return e(t,r,n)}export{o as createDenoAdapter};
1
+ import { resolveConfigDirectory, resolveHomeDirectory } from "./paths.mjs";
2
+ //#region src/runtime/deno.ts
3
+ /**
4
+ * Detect whether an unknown thrown value is a Deno error by name.
5
+ *
6
+ * @internal
7
+ */
8
+ function isDenoErrorNamed(err, name) {
9
+ if (typeof err !== "object" || err === null || !("name" in err)) return false;
10
+ const candidate = err;
11
+ return typeof candidate.name === "string" && candidate.name === name;
12
+ }
13
+ /**
14
+ * Safely read all environment variables. Returns empty object if
15
+ * `--allow-env` permission is not granted.
16
+ *
17
+ * @internal
18
+ */
19
+ function safeEnvToObject(deno) {
20
+ try {
21
+ return deno.env.toObject();
22
+ } catch (err) {
23
+ if (isDenoErrorNamed(err, "PermissionDenied")) return {};
24
+ throw err;
25
+ }
26
+ }
27
+ /**
28
+ * Safely get the current working directory. Returns `/` if the cwd is
29
+ * inaccessible due to missing permissions.
30
+ *
31
+ * @internal
32
+ */
33
+ function safeCwd(deno) {
34
+ try {
35
+ return deno.cwd();
36
+ } catch (err) {
37
+ if (isDenoErrorNamed(err, "PermissionDenied")) return "/";
38
+ throw err;
39
+ }
40
+ }
41
+ /**
42
+ * Create a runtime adapter backed by the Deno namespace.
43
+ *
44
+ * Reads `Deno.args`, `Deno.env`, `Deno.cwd()`, and wraps Deno's stream-based
45
+ * I/O into the {@linkcode WriteFn}/{@linkcode ReadFn} functions expected by the framework.
46
+ *
47
+ * Unlike Node/Bun, Deno strips the binary and script path from `Deno.args`.
48
+ * The adapter prepends synthetic entries (`['deno', 'run']`) so the argv
49
+ * shape matches the {@linkcode RuntimeAdapter} contract (binary + script + user args).
50
+ *
51
+ * @param ns - Override the Deno namespace (useful for testing the adapter itself).
52
+ * @returns A {@linkcode RuntimeAdapter} backed by Deno's namespace APIs.
53
+ *
54
+ * @example
55
+ * ```ts
56
+ * import { cli } from '@kjanat/dreamcli';
57
+ * import { createDenoAdapter } from '@kjanat/dreamcli/runtime';
58
+ *
59
+ * cli('mycli')
60
+ * .command(deploy)
61
+ * .run({ adapter: createDenoAdapter() });
62
+ * ```
63
+ */
64
+ function createDenoAdapter(ns) {
65
+ const d = ns ?? getDenoNamespace();
66
+ const encoder = new TextEncoder();
67
+ const argv = [
68
+ "deno",
69
+ "run",
70
+ ...d.args
71
+ ];
72
+ const env = safeEnvToObject(d);
73
+ const cwd = safeCwd(d);
74
+ const stdoutWrite = (data) => {
75
+ d.stdout.writeSync(encoder.encode(data));
76
+ };
77
+ const stderrWrite = (data) => {
78
+ d.stderr.writeSync(encoder.encode(data));
79
+ };
80
+ const stdinRead = createDenoReadLine(d);
81
+ const readFile = async (path) => {
82
+ try {
83
+ return await d.readTextFile(path);
84
+ } catch (err) {
85
+ if (isDenoErrorNamed(err, "NotFound")) return null;
86
+ if (isDenoErrorNamed(err, "PermissionDenied")) return null;
87
+ throw err;
88
+ }
89
+ };
90
+ const homedir = resolveDenoHomedir(env, d.build.os === "windows");
91
+ const configDir = resolveDenoConfigDir(env, homedir, d.build.os === "windows");
92
+ const stdinIsTTY = d.stdin.isTerminal();
93
+ return {
94
+ argv,
95
+ env,
96
+ cwd,
97
+ stdout: stdoutWrite,
98
+ stderr: stderrWrite,
99
+ stdin: stdinRead,
100
+ readStdin: () => readDenoStdinAll(d, stdinIsTTY),
101
+ isTTY: d.stdout.isTerminal(),
102
+ stdinIsTTY,
103
+ exit: (code) => d.exit(code),
104
+ readFile,
105
+ homedir,
106
+ configDir
107
+ };
108
+ }
109
+ /**
110
+ * Access the global `Deno` namespace.
111
+ *
112
+ * Cast through `unknown` to avoid TypeScript errors when Deno types
113
+ * aren't installed. Safe because this adapter is only used on Deno
114
+ * where `globalThis.Deno` is always defined.
115
+ *
116
+ * @internal
117
+ */
118
+ function getDenoNamespace() {
119
+ return globalThis.Deno;
120
+ }
121
+ /**
122
+ * Read all of stdin as a single string (for piped data).
123
+ *
124
+ * Returns `null` immediately if stdin is a TTY — the user is typing
125
+ * interactively, so there's no piped data to consume. When stdin is
126
+ * piped, collects all chunks via the `ReadableStream` until EOF and
127
+ * returns the decoded string, which may be empty for an empty pipe.
128
+ *
129
+ * @internal
130
+ */
131
+ async function readDenoStdinAll(deno, stdinIsTTY) {
132
+ if (stdinIsTTY) return null;
133
+ const reader = deno.stdin.readable.getReader();
134
+ const decoder = new TextDecoder();
135
+ const chunks = [];
136
+ try {
137
+ for (;;) {
138
+ const { value, done } = await reader.read();
139
+ if (done) {
140
+ chunks.push(decoder.decode());
141
+ break;
142
+ }
143
+ chunks.push(decoder.decode(value, { stream: true }));
144
+ }
145
+ } finally {
146
+ reader.releaseLock();
147
+ }
148
+ return chunks.join("");
149
+ }
150
+ /**
151
+ * Read a single line from Deno's stdin.
152
+ *
153
+ * Uses the `ReadableStream` API with a manual buffer to read until
154
+ * a newline character is found. Returns `null` on EOF.
155
+ *
156
+ * This is intentionally simple — the terminal prompter handles retries
157
+ * and validation.
158
+ *
159
+ * @internal
160
+ */
161
+ function createDenoReadLine(deno) {
162
+ const decoder = new TextDecoder();
163
+ let buffer = "";
164
+ let done = false;
165
+ return async () => {
166
+ const reader = deno.stdin.readable.getReader();
167
+ try {
168
+ for (;;) {
169
+ const newlineIndex = buffer.indexOf("\n");
170
+ if (newlineIndex !== -1) {
171
+ const line = buffer.slice(0, newlineIndex).replace(/\r$/, "");
172
+ buffer = buffer.slice(newlineIndex + 1);
173
+ return line;
174
+ }
175
+ if (done) {
176
+ if (buffer.length === 0) return null;
177
+ const line = buffer;
178
+ buffer = "";
179
+ return line;
180
+ }
181
+ const { value, done: readDone } = await reader.read();
182
+ if (readDone) {
183
+ buffer += decoder.decode();
184
+ done = true;
185
+ continue;
186
+ }
187
+ buffer += decoder.decode(value, { stream: true });
188
+ }
189
+ } finally {
190
+ reader.releaseLock();
191
+ }
192
+ };
193
+ }
194
+ /**
195
+ * Resolve the user's home directory from environment variables.
196
+ *
197
+ * Deno doesn't expose `os.homedir()` without `--allow-sys`, so we derive
198
+ * it from env vars — same approach as the Node adapter.
199
+ *
200
+ * @internal
201
+ */
202
+ function resolveDenoHomedir(env, isWindows) {
203
+ return resolveHomeDirectory(env, isWindows);
204
+ }
205
+ /**
206
+ * Resolve the platform-specific user configuration directory.
207
+ *
208
+ * Uses `Deno.build.os` for platform detection, then applies the same fallback
209
+ * chain as the Node adapter.
210
+ *
211
+ * @internal
212
+ */
213
+ function resolveDenoConfigDir(env, homedir, isWindows) {
214
+ return resolveConfigDirectory(env, isWindows, homedir);
215
+ }
216
+ //#endregion
217
+ export { createDenoAdapter };
@@ -1 +1,45 @@
1
- const e=[`node`,`bun`,`deno`,`unknown`];function t(e){let t=e??globalThis;return typeof t.Bun?.version==`string`?`bun`:typeof t.Deno?.version?.deno==`string`?`deno`:typeof t.process?.versions?.node==`string`?`node`:`unknown`}export{e as RUNTIMES,t as detectRuntime};
1
+ //#region src/runtime/detect.ts
2
+ /**
3
+ * All known runtime values as a readonly tuple.
4
+ *
5
+ * Useful for validation, iteration, and exhaustiveness checks.
6
+ *
7
+ * @example
8
+ * ```ts
9
+ * if (RUNTIMES.includes(value)) {
10
+ * // value is a valid Runtime
11
+ * }
12
+ * ```
13
+ */
14
+ const RUNTIMES = [
15
+ "node",
16
+ "bun",
17
+ "deno",
18
+ "unknown"
19
+ ];
20
+ /**
21
+ * Detect the current JavaScript runtime.
22
+ *
23
+ * Uses `globalThis` feature detection to identify the host runtime.
24
+ * Detection order is significant: Bun is checked before Node because
25
+ * Bun exposes a Node-compatible `process` global.
26
+ *
27
+ * @param globals - Override `globalThis` for testing. Production callers
28
+ * should omit this parameter.
29
+ * @returns The detected {@link Runtime} identifier.
30
+ *
31
+ * @example
32
+ * ```ts
33
+ * const rt = detectRuntime();
34
+ * // rt === 'node' | 'bun' | 'deno' | 'unknown'
35
+ * ```
36
+ */
37
+ function detectRuntime(globals) {
38
+ const g = globals ?? globalThis;
39
+ if (typeof g.Bun?.version === "string") return "bun";
40
+ if (typeof g.Deno?.version?.deno === "string") return "deno";
41
+ if (typeof g.process?.versions?.node === "string") return "node";
42
+ return "unknown";
43
+ }
44
+ //#endregion
45
+ export { RUNTIMES, detectRuntime };
@@ -1,2 +1,169 @@
1
- import{resolveConfigDirectory as e,resolveHomeDirectory as t}from"./paths.mjs";import{assertRuntimeVersionSupported as n}from"./support.mjs";function r(){return globalThis.process}function i(e){return typeof e!=`object`||!e||!(`code`in e)?!1:typeof e.code==`string`}function a(e,n){return t(e,n===`win32`)}function o(t,n,r){return e(t,n===`win32`,r)}function s(e){if(e.versions?.bun!==void 0){n(`bun`,e.versions.bun);return}n(`node`,e.versions?.node)}function c(e){let t=e??r();s(t);let n=e=>{t.stdout.write(e)},c=e=>{t.stderr.write(e)},d=u(t),f=async e=>{let t=await import(`node:fs/promises`);try{return await t.readFile(e,`utf8`)}catch(e){if(i(e)&&e.code===`ENOENT`)return null;throw e}},p=a(t.env,t.platform),m=o(t.env,t.platform,p),h=t.stdin.isTTY===!0;return{argv:t.argv,env:t.env,cwd:t.cwd(),stdout:n,stderr:c,stdin:d,readStdin:()=>l(t,h),isTTY:t.stdout.isTTY===!0,stdinIsTTY:h,exit:e=>t.exit(e),readFile:f,homedir:p,configDir:m}}async function l(e,t){if(t)return null;let n=[],r=new TextDecoder;for await(let t of e.stdin)n.push(r.decode(t,{stream:!0}));return n.push(r.decode()),n.join(``)}function u(e){let t=e.stdin[Symbol.asyncIterator](),n=new TextDecoder,r=``,i=!1;return async()=>{for(;;){let e=r.indexOf(`
2
- `);if(e!==-1){let t=r.slice(0,e).replace(/\r$/,``);return r=r.slice(e+1),t}if(i){if(r.length===0)return null;let e=r;return r=``,e}let a=await t.next();if(a.done){r+=n.decode(),i=!0;continue}r+=n.decode(a.value,{stream:!0})}}}export{c as createNodeAdapter};
1
+ import { resolveConfigDirectory, resolveHomeDirectory } from "./paths.mjs";
2
+ //#region src/runtime/node.ts
3
+ /**
4
+ * Access the global `process` object without importing `@types/node`.
5
+ *
6
+ * Cast through `unknown` to avoid TypeScript errors when `@types/node`
7
+ * isn't installed. Safe because this adapter is only used on Node/Bun
8
+ * where `globalThis.process` is always defined.
9
+ *
10
+ * @internal
11
+ */
12
+ function getNodeProcess() {
13
+ return globalThis.process;
14
+ }
15
+ /**
16
+ * Detect whether an unknown thrown value is a Node.js system error
17
+ * with a string `code` property (e.g. `'ENOENT'`, `'EACCES'`).
18
+ *
19
+ * @internal
20
+ */
21
+ function isNodeSystemError(err) {
22
+ if (typeof err !== "object" || err === null || !("code" in err)) return false;
23
+ return typeof err.code === "string";
24
+ }
25
+ /**
26
+ * Resolve the user's home directory from environment variables.
27
+ *
28
+ * **Windows** (`win32`): `USERPROFILE` → `HOMEDRIVE`+`HOMEPATH` (both required) → `HOME` → `C:\`
29
+ * **Unix**: `HOME` → `/`
30
+ *
31
+ * `HOMEPATH` alone is never used — it is a relative fragment (e.g. `\Users\alice`) that only
32
+ * makes sense when combined with `HOMEDRIVE` (e.g. `C:`). Using `HOMEPATH` without `HOMEDRIVE`
33
+ * could resolve against the working drive, producing an incorrect path.
34
+ *
35
+ * We avoid importing `node:os` to keep the factory synchronous and
36
+ * to maintain the pattern of deriving everything from the process object.
37
+ *
38
+ * @internal
39
+ */
40
+ function resolveHomedir(env, platform) {
41
+ return resolveHomeDirectory(env, platform === "win32");
42
+ }
43
+ /**
44
+ * Resolve the platform-specific user configuration directory.
45
+ *
46
+ * - Unix: `$XDG_CONFIG_HOME` (if set), otherwise `~/.config`
47
+ * - Windows: `%APPDATA%` (if set), otherwise `~\AppData\Roaming`
48
+ *
49
+ * @internal
50
+ */
51
+ function resolveConfigDir(env, platform, homedir) {
52
+ return resolveConfigDirectory(env, platform === "win32", homedir);
53
+ }
54
+ /**
55
+ * Create a runtime adapter backed by Node.js `process` globals.
56
+ *
57
+ * Reads `process.argv`, `process.env`, `process.cwd()`, and wraps
58
+ * `process.stdout.write`/`process.stderr.write` as {@linkcode WriteFn} functions.
59
+ *
60
+ * Also works on Bun, which provides a Node-compatible `process` global.
61
+ *
62
+ * @param proc - Override the process object (useful for testing the adapter itself).
63
+ * @returns A {@linkcode RuntimeAdapter} backed by Node.js process state.
64
+ *
65
+ * @example
66
+ * ```ts
67
+ * import { cli } from '@kjanat/dreamcli';
68
+ * import { createNodeAdapter } from '@kjanat/dreamcli/runtime/node';
69
+ *
70
+ * cli('mycli')
71
+ * .command(deploy)
72
+ * .run({ adapter: createNodeAdapter() });
73
+ * ```
74
+ */
75
+ function createNodeAdapter(proc) {
76
+ const p = proc ?? getNodeProcess();
77
+ const stdoutWrite = (data) => {
78
+ p.stdout.write(data);
79
+ };
80
+ const stderrWrite = (data) => {
81
+ p.stderr.write(data);
82
+ };
83
+ const stdinRead = createNodeReadLine(p);
84
+ const readFile = async (path) => {
85
+ const fs = await import("node:fs/promises");
86
+ try {
87
+ return await fs.readFile(path, "utf8");
88
+ } catch (err) {
89
+ if (isNodeSystemError(err) && err.code === "ENOENT") return null;
90
+ throw err;
91
+ }
92
+ };
93
+ const homedir = resolveHomedir(p.env, p.platform);
94
+ const configDir = resolveConfigDir(p.env, p.platform, homedir);
95
+ const stdinIsTTY = p.stdin.isTTY === true;
96
+ return {
97
+ argv: p.argv,
98
+ env: p.env,
99
+ cwd: p.cwd(),
100
+ stdout: stdoutWrite,
101
+ stderr: stderrWrite,
102
+ stdin: stdinRead,
103
+ readStdin: () => readNodeStdinAll(p, stdinIsTTY),
104
+ isTTY: p.stdout.isTTY === true,
105
+ stdinIsTTY,
106
+ exit: (code) => p.exit(code),
107
+ readFile,
108
+ homedir,
109
+ configDir
110
+ };
111
+ }
112
+ /**
113
+ * Read all of stdin as a single string (for piped data).
114
+ *
115
+ * Returns `null` immediately if stdin is a TTY — the user is typing
116
+ * interactively, so there's no piped data to consume. When stdin is
117
+ * piped, collects all chunks via the async iterator until EOF and
118
+ * returns the decoded string, which may be empty for an empty pipe.
119
+ *
120
+ * @internal
121
+ */
122
+ async function readNodeStdinAll(proc, stdinIsTTY) {
123
+ if (stdinIsTTY) return null;
124
+ const chunks = [];
125
+ const decoder = new TextDecoder();
126
+ for await (const chunk of proc.stdin) chunks.push(decoder.decode(chunk, { stream: true }));
127
+ chunks.push(decoder.decode());
128
+ return chunks.join("");
129
+ }
130
+ /**
131
+ * Read a single line from Node's stdin via its async iterator.
132
+ *
133
+ * Iterates stdin chunks manually (without `for-await` to avoid calling
134
+ * `iterator.return()` which would close the stream). Returns `null`
135
+ * on EOF.
136
+ *
137
+ * @internal
138
+ */
139
+ function createNodeReadLine(proc) {
140
+ const iter = proc.stdin[Symbol.asyncIterator]();
141
+ const decoder = new TextDecoder();
142
+ let buffer = "";
143
+ let done = false;
144
+ return async () => {
145
+ for (;;) {
146
+ const nlIndex = buffer.indexOf("\n");
147
+ if (nlIndex !== -1) {
148
+ const line = buffer.slice(0, nlIndex).replace(/\r$/, "");
149
+ buffer = buffer.slice(nlIndex + 1);
150
+ return line;
151
+ }
152
+ if (done) {
153
+ if (buffer.length === 0) return null;
154
+ const line = buffer;
155
+ buffer = "";
156
+ return line;
157
+ }
158
+ const result = await iter.next();
159
+ if (result.done) {
160
+ buffer += decoder.decode();
161
+ done = true;
162
+ continue;
163
+ }
164
+ buffer += decoder.decode(result.value, { stream: true });
165
+ }
166
+ };
167
+ }
168
+ //#endregion
169
+ export { createNodeAdapter };