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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (194) hide show
  1. package/CHANGELOG.md +217 -1
  2. package/dist/core/cli/dispatch.d.mts +6 -5
  3. package/dist/core/cli/dispatch.mjs +205 -1
  4. package/dist/core/cli/help-links.d.mts +0 -1
  5. package/dist/core/cli/help-links.mjs +41 -1
  6. package/dist/core/cli/index.d.mts +81 -8
  7. package/dist/core/cli/index.mjs +945 -1
  8. package/dist/core/cli/planner.d.mts +5 -1
  9. package/dist/core/cli/planner.mjs +300 -1
  10. package/dist/core/cli/plugin.d.mts +1 -1
  11. package/dist/core/cli/plugin.mjs +41 -1
  12. package/dist/core/cli/propagate.d.mts +1 -1
  13. package/dist/core/cli/propagate.mjs +57 -1
  14. package/dist/core/cli/root-help.d.mts +2 -1
  15. package/dist/core/cli/root-help.mjs +226 -4
  16. package/dist/core/cli/root-surface.d.mts +12 -1
  17. package/dist/core/cli/root-surface.mjs +28 -1
  18. package/dist/core/cli/runtime-preflight.d.mts +14 -2
  19. package/dist/core/cli/runtime-preflight.mjs +169 -1
  20. package/dist/core/completion/index.d.mts +0 -1
  21. package/dist/core/completion/index.mjs +90 -1
  22. package/dist/core/completion/shells/bash.d.mts +0 -1
  23. package/dist/core/completion/shells/bash.mjs +308 -3
  24. package/dist/core/completion/shells/fish.d.mts +0 -1
  25. package/dist/core/completion/shells/fish.mjs +162 -2
  26. package/dist/core/completion/shells/powershell.d.mts +0 -1
  27. package/dist/core/completion/shells/powershell.mjs +358 -2
  28. package/dist/core/completion/shells/shared.d.mts +13 -2
  29. package/dist/core/completion/shells/shared.mjs +176 -1
  30. package/dist/core/completion/shells/zsh.d.mts +0 -1
  31. package/dist/core/completion/shells/zsh.mjs +251 -2
  32. package/dist/core/config/index.d.mts +2 -3
  33. package/dist/core/config/index.mjs +246 -1
  34. package/dist/core/config/package-json.d.mts +27 -4
  35. package/dist/core/config/package-json.mjs +386 -3
  36. package/dist/core/errors/index.d.mts +3 -3
  37. package/dist/core/errors/index.mjs +87 -1
  38. package/dist/core/execution/index.d.mts +0 -1
  39. package/dist/core/execution/index.mjs +201 -1
  40. package/dist/core/help/ansi.d.mts +11 -5
  41. package/dist/core/help/ansi.mjs +121 -2
  42. package/dist/core/help/index.d.mts +22 -3
  43. package/dist/core/help/index.mjs +341 -7
  44. package/dist/core/help/theme.d.mts +68 -0
  45. package/dist/core/help/theme.mjs +46 -0
  46. package/dist/core/json-schema/index.d.mts +15 -2
  47. package/dist/core/json-schema/index.mjs +536 -12
  48. package/dist/core/json-schema/meta-descriptions.generated.d.mts +55 -38
  49. package/dist/core/json-schema/meta-descriptions.generated.mjs +102 -28
  50. package/dist/core/output/activity.d.mts +0 -1
  51. package/dist/core/output/activity.mjs +452 -1
  52. package/dist/core/output/bind.mjs +56 -1
  53. package/dist/core/output/contracts.d.mts +4 -5
  54. package/dist/core/output/contracts.mjs +57 -1
  55. package/dist/core/output/display-value.mjs +32 -1
  56. package/dist/core/output/index.d.mts +21 -1
  57. package/dist/core/output/index.mjs +442 -2
  58. package/dist/core/output/renderers.d.mts +0 -1
  59. package/dist/core/output/renderers.mjs +46 -1
  60. package/dist/core/output/writer.mjs +12 -1
  61. package/dist/core/parse/index.d.mts +40 -7
  62. package/dist/core/parse/index.mjs +727 -1
  63. package/dist/core/prompt/index.d.mts +1 -1
  64. package/dist/core/prompt/index.mjs +348 -6
  65. package/dist/core/resolve/args.d.mts +1 -1
  66. package/dist/core/resolve/args.mjs +105 -1
  67. package/dist/core/resolve/coerce.d.mts +1 -1
  68. package/dist/core/resolve/coerce.mjs +336 -1
  69. package/dist/core/resolve/config.mjs +19 -1
  70. package/dist/core/resolve/contracts.d.mts +9 -4
  71. package/dist/core/resolve/errors.d.mts +0 -1
  72. package/dist/core/resolve/errors.mjs +140 -2
  73. package/dist/core/resolve/flags.d.mts +7 -2
  74. package/dist/core/resolve/flags.mjs +251 -1
  75. package/dist/core/resolve/index.d.mts +2 -2
  76. package/dist/core/resolve/index.mjs +85 -1
  77. package/dist/core/resolve/property.d.mts +4 -2
  78. package/dist/core/resolve/property.mjs +53 -1
  79. package/dist/core/schema/activity.d.mts +31 -11
  80. package/dist/core/schema/arg.d.mts +3 -4
  81. package/dist/core/schema/arg.mjs +463 -1
  82. package/dist/core/schema/command.d.mts +26 -6
  83. package/dist/core/schema/command.mjs +726 -1
  84. package/dist/core/schema/flag.d.mts +485 -19
  85. package/dist/core/schema/flag.mjs +705 -1
  86. package/dist/core/schema/index.d.mts +4 -2
  87. package/dist/core/schema/middleware.d.mts +4 -3
  88. package/dist/core/schema/middleware.mjs +41 -1
  89. package/dist/core/schema/number-constraints.mjs +60 -1
  90. package/dist/core/schema/prompt.d.mts +6 -3
  91. package/dist/core/schema/run.d.mts +20 -1
  92. package/dist/core/schema/string-constraints.d.mts +97 -0
  93. package/dist/core/schema/string-constraints.mjs +69 -0
  94. package/dist/core/schema/value-parsers.d.mts +78 -0
  95. package/dist/core/schema/value-parsers.mjs +142 -0
  96. package/dist/core/schema-dsl/runtime.mjs +271 -2
  97. package/dist/core/schema-dsl/to-json-schema.d.mts +0 -1
  98. package/dist/core/schema-dsl/to-json-schema.mjs +74 -1
  99. package/dist/core/testkit/index.d.mts +0 -31
  100. package/dist/core/testkit/index.mjs +83 -1
  101. package/dist/index.d.mts +11 -6
  102. package/dist/index.mjs +22 -1
  103. package/dist/runtime/adapter.d.mts +38 -2
  104. package/dist/runtime/adapter.mjs +87 -1
  105. package/dist/runtime/auto.d.mts +2 -3
  106. package/dist/runtime/auto.mjs +45 -1
  107. package/dist/runtime/deno.d.mts +24 -5
  108. package/dist/runtime/deno.mjs +262 -2
  109. package/dist/runtime/detect.mjs +45 -1
  110. package/dist/runtime/index.d.mts +3 -4
  111. package/dist/runtime/node.d.mts +8 -2
  112. package/dist/runtime/node.mjs +220 -2
  113. package/dist/runtime/paths.mjs +48 -1
  114. package/dist/runtime.d.mts +4 -4
  115. package/dist/runtime.mjs +6 -1
  116. package/dist/strings.mjs +22 -1
  117. package/dist/testkit.d.mts +1 -0
  118. package/dist/testkit.mjs +5 -1
  119. package/dist/version.d.mts +7 -3
  120. package/dist/version.mjs +7 -1
  121. package/dreamcli.schema.json +36 -7
  122. package/package.json +45 -42
  123. package/dist/runtime/bun.d.mts +0 -28
  124. package/dist/runtime/bun.mjs +0 -1
  125. package/src/core/cli/dispatch.ts +0 -355
  126. package/src/core/cli/help-links.ts +0 -82
  127. package/src/core/cli/index.ts +0 -1614
  128. package/src/core/cli/planner.ts +0 -656
  129. package/src/core/cli/plugin.ts +0 -117
  130. package/src/core/cli/propagate.ts +0 -97
  131. package/src/core/cli/root-help.ts +0 -342
  132. package/src/core/cli/root-surface.ts +0 -87
  133. package/src/core/cli/runtime-preflight.ts +0 -456
  134. package/src/core/completion/index.ts +0 -138
  135. package/src/core/completion/shells/bash.ts +0 -459
  136. package/src/core/completion/shells/fish.ts +0 -259
  137. package/src/core/completion/shells/powershell.ts +0 -439
  138. package/src/core/completion/shells/shared.ts +0 -310
  139. package/src/core/completion/shells/zsh.ts +0 -381
  140. package/src/core/config/index.ts +0 -417
  141. package/src/core/config/package-json.ts +0 -560
  142. package/src/core/errors/index.ts +0 -193
  143. package/src/core/execution/index.ts +0 -265
  144. package/src/core/help/ansi.ts +0 -144
  145. package/src/core/help/index.ts +0 -563
  146. package/src/core/json-schema/index.ts +0 -910
  147. package/src/core/json-schema/meta-descriptions.generated.ts +0 -202
  148. package/src/core/output/activity.ts +0 -575
  149. package/src/core/output/bind.ts +0 -59
  150. package/src/core/output/contracts.ts +0 -194
  151. package/src/core/output/display-value.ts +0 -48
  152. package/src/core/output/index.ts +0 -704
  153. package/src/core/output/renderers.ts +0 -125
  154. package/src/core/output/writer.ts +0 -46
  155. package/src/core/parse/index.ts +0 -742
  156. package/src/core/prompt/index.ts +0 -623
  157. package/src/core/resolve/args.ts +0 -144
  158. package/src/core/resolve/coerce.ts +0 -500
  159. package/src/core/resolve/config.ts +0 -26
  160. package/src/core/resolve/contracts.ts +0 -135
  161. package/src/core/resolve/errors.ts +0 -227
  162. package/src/core/resolve/flags.ts +0 -269
  163. package/src/core/resolve/index.ts +0 -108
  164. package/src/core/resolve/property.ts +0 -99
  165. package/src/core/schema/activity.ts +0 -240
  166. package/src/core/schema/arg.ts +0 -841
  167. package/src/core/schema/command.ts +0 -1500
  168. package/src/core/schema/flag.ts +0 -917
  169. package/src/core/schema/index.ts +0 -96
  170. package/src/core/schema/middleware.ts +0 -171
  171. package/src/core/schema/number-constraints.ts +0 -153
  172. package/src/core/schema/prompt.ts +0 -171
  173. package/src/core/schema/run.ts +0 -198
  174. package/src/core/schema-dsl/index.ts +0 -109
  175. package/src/core/schema-dsl/parse.ts +0 -262
  176. package/src/core/schema-dsl/runtime.ts +0 -609
  177. package/src/core/schema-dsl/to-json-schema.ts +0 -102
  178. package/src/core/testkit/index.ts +0 -147
  179. package/src/index.ts +0 -181
  180. package/src/runtime/adapter.ts +0 -303
  181. package/src/runtime/auto.ts +0 -86
  182. package/src/runtime/bun.ts +0 -48
  183. package/src/runtime/deno.ts +0 -367
  184. package/src/runtime/detect.ts +0 -105
  185. package/src/runtime/index.ts +0 -21
  186. package/src/runtime/node-builtins.d.ts +0 -27
  187. package/src/runtime/node.ts +0 -289
  188. package/src/runtime/paths.ts +0 -64
  189. package/src/runtime/support.ts +0 -77
  190. package/src/runtime.ts +0 -31
  191. package/src/schema.ts +0 -16
  192. package/src/strings.ts +0 -34
  193. package/src/testkit.ts +0 -25
  194. package/src/version.ts +0 -20
@@ -1 +1,726 @@
1
- import{CLIError as e}from"../errors/index.mjs";function t(t,n,r){if(n.stdinMode&&n.variadic)throw new e(`Argument <${t}> cannot be both variadic and stdin-backed`,{code:`INVALID_BUILDER_STATE`,details:{arg:t,stdinMode:!0,variadic:!0},suggest:`Remove .stdin() or .variadic() from this argument`});if(!n.stdinMode)return;let i=r.find(e=>e.schema.stdinMode);if(i!==void 0)throw new e(`Only one stdin argument is allowed; <${i.name}> is already stdin-backed`,{code:`DUPLICATE_STDIN_ARG`,details:{arg:t,existingArg:i.name},suggest:`Keep .stdin() on a single argument per command`})}function n(e,t){return t===`alias`&&e.length===1?`-${e}`:`--${e}`}function r(e){if(e.kind===`canonical`)return`canonical flag ${n(e.name,e.kind)}`;let t=e.name.length===1?`short alias`:`long alias`;return`${e.hidden?`hidden `:``}${t} ${n(e.name,e.kind)}`}function i(e,t){return[{owner:e,name:e,kind:`canonical`,hidden:!1},...t.aliases.map(t=>({owner:e,name:t.name,kind:`alias`,hidden:t.hidden}))]}function a(t,i,a,o){let s=o?.inherited??!1,c=`flag ${n(a.owner,`canonical`)}`,l=`Command '${t}' ${c}`;throw new e(s?`${l} propagates ${r(a)}, which collides with ${r(i)} on flag ${n(i.owner,`canonical`)}`:`Command '${t}' flag ${n(i.owner,`canonical`)} ${r(i)} collides with ${r(a)} on ${c}`,{code:s?`PROPAGATED_FLAG_COLLISION`:`FLAG_NAME_COLLISION`,details:{command:t,flag:i.owner,surface:i.name,surfaceKind:i.kind,hidden:i.hidden,existingFlag:a.owner,existingSurface:a.name,existingSurfaceKind:a.kind,existingHidden:a.hidden,inherited:s}})}function o(e,t){let n=new Map;for(let[r,o]of Object.entries(t))for(let t of i(r,o)){let r=n.get(t.name);r!==void 0&&a(e,t,r),n.set(t.name,t)}}function s(e,t,n){let r=new Map;for(let[e,n]of Object.entries(t))for(let t of i(e,n))r.set(t.name,t);for(let[t,o]of Object.entries(n))for(let n of i(t,o)){let t=r.get(n.name);t!==void 0&&a(e,n,t,{inherited:!0})}}function c(e,t){let n={...e};for(let e of Object.keys(t))delete n[e];for(let[e,r]of Object.entries(t))r.propagate&&(n[e]=r);return n}function l(e,t={}){o(e.name,e.flags);let n={...t};for(let t of Object.keys(e.flags))delete n[t];s(e.name,n,e.flags);let r=c(t,e.flags);for(let t of e.commands)l(t,r)}function u(e){return e}var d=class n{schema;handler;_subcommands;_executionSteps;constructor(e,t,n,r){this.schema=e,this.handler=t,this._subcommands=n??[],this._executionSteps=r??[]}interactive(e){let t=e;return new n({...this.schema,interactive:t},this.handler,this._subcommands,this._executionSteps)}derive(e){let t=e;return new n({...this.schema,hasAction:!1},void 0,this._subcommands,[...this._executionSteps,{kind:`derive`,handler:t}])}middleware(e){return new n({...this.schema,middleware:[...this.schema.middleware,e._handler],hasAction:!1},void 0,this._subcommands,[...this._executionSteps,{kind:`middleware`,handler:e._handler}])}description(e){return new n({...this.schema,description:e},this.handler,this._subcommands,this._executionSteps)}alias(e){return new n({...this.schema,aliases:[...this.schema.aliases,e]},this.handler,this._subcommands,this._executionSteps)}hidden(){return new n({...this.schema,hidden:!0},this.handler,this._subcommands,this._executionSteps)}example(e,t){let r=t===void 0?{command:e}:{command:e,description:t};return new n({...this.schema,examples:[...this.schema.examples,r]},this.handler,this._subcommands,this._executionSteps)}flag(t,r){if(t in this.schema.flags)throw new e(`Command '${this.schema.name}' already defines flag --${t}`,{code:`FLAG_NAME_COLLISION`,details:{command:this.schema.name,flag:t,surface:t,surfaceKind:`canonical`}});let i={...this.schema.flags,[t]:r.schema},a={...this.schema,flags:i,hasAction:!1};return l(a),new n(a,void 0,this._subcommands,this._executionSteps)}arg(e,r){t(e,r.schema,this.schema.args);let i={name:e,schema:r.schema},a=[...this.schema.args,i];return new n({...this.schema,args:a,hasAction:!1},void 0,this._subcommands,this._executionSteps)}command(e){let t={...this.schema,commands:[...this.schema.commands,e.schema]};return l(t),new n(t,this.handler,[...this._subcommands,u(e)],this._executionSteps)}action(e){return new n({...this.schema,hasAction:!0},e,this._subcommands,this._executionSteps)}};function f(e){return new d({name:e,description:void 0,aliases:[],hidden:!1,examples:[],flags:{},args:[],hasAction:!1,interactive:void 0,middleware:[],commands:[]})}function p(e){return f(e)}export{d as CommandBuilder,f as command,p as group};
1
+ import { CLIError } from "../errors/index.mjs";
2
+ import { getFlagNegatedName } from "./flag.mjs";
3
+ //#region src/core/schema/command.ts
4
+ /**
5
+ * Validate a new arg entry against invariants before adding it to the command.
6
+ *
7
+ * @param name - Arg name being registered.
8
+ * @param schema - Runtime descriptor of the arg.
9
+ * @param args - Already-registered arg entries on this command.
10
+ *
11
+ * @throws {@link CLIError} `INVALID_BUILDER_STATE` if both `.stdin()` and `.variadic()` are set.
12
+ * @throws {@link CLIError} `DUPLICATE_STDIN_ARG` if another arg already uses `.stdin()`.
13
+ *
14
+ * @internal
15
+ */
16
+ function validateArgEntry(name, schema, args) {
17
+ if (schema.stdinMode && schema.variadic) throw new CLIError(`Argument <${name}> cannot be both variadic and stdin-backed`, {
18
+ code: "INVALID_BUILDER_STATE",
19
+ details: {
20
+ arg: name,
21
+ stdinMode: true,
22
+ variadic: true
23
+ },
24
+ suggest: "Remove .stdin() or .variadic() from this argument"
25
+ });
26
+ if (!schema.stdinMode) return;
27
+ const existing = args.find((entry) => entry.schema.stdinMode);
28
+ if (existing === void 0) return;
29
+ throw new CLIError(`Only one stdin argument is allowed; <${existing.name}> is already stdin-backed`, {
30
+ code: "DUPLICATE_STDIN_ARG",
31
+ details: {
32
+ arg: name,
33
+ existingArg: existing.name
34
+ },
35
+ suggest: "Keep .stdin() on a single argument per command"
36
+ });
37
+ }
38
+ function formatFlagToken(name, kind) {
39
+ return kind === "alias" && name.length === 1 ? `-${name}` : `--${name}`;
40
+ }
41
+ function describeFlagForm(form) {
42
+ if (form.kind === "canonical") return `canonical flag ${formatFlagToken(form.name, form.kind)}`;
43
+ if (form.kind === "negation") return `${form.hidden ? "hidden " : ""}negated spelling ${formatFlagToken(form.name, form.kind)}`;
44
+ const aliasType = form.name.length === 1 ? "short alias" : "long alias";
45
+ return `${form.hidden ? "hidden " : ""}${aliasType} ${formatFlagToken(form.name, form.kind)}`;
46
+ }
47
+ function listFlagForms(name, schema) {
48
+ const negatedName = getFlagNegatedName(name, schema);
49
+ return [
50
+ {
51
+ owner: name,
52
+ name,
53
+ kind: "canonical",
54
+ hidden: false
55
+ },
56
+ ...schema.aliases.map((alias) => ({
57
+ owner: name,
58
+ name: alias.name,
59
+ kind: "alias",
60
+ hidden: alias.hidden
61
+ })),
62
+ ...negatedName !== void 0 && schema.negation !== void 0 ? [{
63
+ owner: name,
64
+ name: negatedName,
65
+ kind: "negation",
66
+ hidden: schema.negation.hidden
67
+ }] : []
68
+ ];
69
+ }
70
+ function throwFlagCollisionError(commandName, form, existing, options) {
71
+ const inherited = options?.inherited ?? false;
72
+ const existingOwner = `flag ${formatFlagToken(existing.owner, "canonical")}`;
73
+ const subject = `Command '${commandName}' ${existingOwner}`;
74
+ throw new CLIError(inherited ? `${subject} propagates ${describeFlagForm(existing)}, which collides with ${describeFlagForm(form)} on flag ${formatFlagToken(form.owner, "canonical")}` : `Command '${commandName}' flag ${formatFlagToken(form.owner, "canonical")} ${describeFlagForm(form)} collides with ${describeFlagForm(existing)} on ${existingOwner}`, {
75
+ code: inherited ? "PROPAGATED_FLAG_COLLISION" : "FLAG_NAME_COLLISION",
76
+ details: {
77
+ command: commandName,
78
+ flag: form.owner,
79
+ surface: form.name,
80
+ surfaceKind: form.kind,
81
+ hidden: form.hidden,
82
+ existingFlag: existing.owner,
83
+ existingSurface: existing.name,
84
+ existingSurfaceKind: existing.kind,
85
+ existingHidden: existing.hidden,
86
+ inherited
87
+ }
88
+ });
89
+ }
90
+ function validateLocalFlagCollisions(commandName, flags) {
91
+ const seen = /* @__PURE__ */ new Map();
92
+ for (const [name, schema] of Object.entries(flags)) for (const form of listFlagForms(name, schema)) {
93
+ const existing = seen.get(form.name);
94
+ if (existing !== void 0) throwFlagCollisionError(commandName, form, existing);
95
+ seen.set(form.name, form);
96
+ }
97
+ }
98
+ function validateInheritedFlagCollisions(commandName, inherited, local) {
99
+ const inheritedForms = /* @__PURE__ */ new Map();
100
+ for (const [name, schema] of Object.entries(inherited)) for (const form of listFlagForms(name, schema)) inheritedForms.set(form.name, form);
101
+ for (const [name, schema] of Object.entries(local)) for (const form of listFlagForms(name, schema)) {
102
+ const existing = inheritedForms.get(form.name);
103
+ if (existing !== void 0) throwFlagCollisionError(commandName, form, existing, { inherited: true });
104
+ }
105
+ }
106
+ function buildInheritedFlagsForChildren(inherited, local) {
107
+ const next = { ...inherited };
108
+ for (const name of Object.keys(local)) delete next[name];
109
+ for (const [name, schema] of Object.entries(local)) if (schema.propagate) next[name] = schema;
110
+ return next;
111
+ }
112
+ function validateCommandFlagTree(command, inheritedFlags = {}) {
113
+ validateLocalFlagCollisions(command.name, command.flags);
114
+ const visibleInherited = { ...inheritedFlags };
115
+ for (const name of Object.keys(command.flags)) delete visibleInherited[name];
116
+ validateInheritedFlagCollisions(command.name, visibleInherited, command.flags);
117
+ const inheritedForChildren = buildInheritedFlagsForChildren(inheritedFlags, command.flags);
118
+ for (const child of command.commands) validateCommandFlagTree(child, inheritedForChildren);
119
+ }
120
+ /**
121
+ * Erase a typed `CommandBuilder<F, A, C>` to `AnyCommandBuilder` for
122
+ * heterogeneous storage. Centralises the `as unknown as` double-cast
123
+ * required at the type-erasure boundary.
124
+ *
125
+ * @internal
126
+ */
127
+ function eraseBuilder(builder) {
128
+ return builder;
129
+ }
130
+ /**
131
+ * Immutable command schema builder.
132
+ *
133
+ * The type parameters `F` (flags), `A` (args), and `C` (context) are
134
+ * phantom types that accumulate builder types as `.flag()`, `.arg()`,
135
+ * `.derive()`, and `.middleware()` are chained. The `.action()` handler receives
136
+ * fully typed `ActionParams<F, A, C>`.
137
+ *
138
+ * `C` defaults to `Record<string, never>`, making `ctx` property
139
+ * access a type error until derive or middleware extends it.
140
+ *
141
+ * @example
142
+ * ```ts
143
+ * const deploy = command('deploy')
144
+ * .description('Deploy to an environment')
145
+ * .arg('target', arg.string().describe('Deploy target'))
146
+ * .flag('force', flag.boolean().alias('f'))
147
+ * .flag('region', flag.enum(['us', 'eu', 'ap']))
148
+ * .action(async ({ args, flags, out }) => {
149
+ * // args.target: string
150
+ * // flags.force: boolean
151
+ * // flags.region: 'us' | 'eu' | 'ap' | undefined
152
+ * out.log(`Deploying ${args.target}...`);
153
+ * });
154
+ * ```
155
+ */
156
+ var CommandBuilder = class CommandBuilder {
157
+ /** @internal Runtime schema descriptor. */
158
+ schema;
159
+ /** @internal The action handler, if registered (type-erased for covariance). */
160
+ handler;
161
+ /**
162
+ * @internal Nested sub-command builders (type-erased for heterogeneous storage).
163
+ *
164
+ * Stored separately from `schema.commands` because builders carry action
165
+ * handlers and phantom types needed by `eraseCommand()` in the CLI layer.
166
+ * `schema.commands` holds pure `CommandSchema[]` for help/completion.
167
+ */
168
+ _subcommands;
169
+ /**
170
+ * @internal Execution steps in registration order.
171
+ *
172
+ * Distinct from `schema.middleware`: middleware handlers remain in schema
173
+ * for backward compatibility, while derives stay command-local and builder-
174
+ * scoped so future shared/global middleware can compose cleanly.
175
+ */
176
+ _executionSteps;
177
+ /**
178
+ * Create a command builder from a pre-built schema descriptor.
179
+ *
180
+ * @param schema - Runtime command descriptor.
181
+ * @param handler - Action handler, if registered.
182
+ * @param subcommands - Nested sub-command builders (type-erased).
183
+ * @param executionSteps - Derive/middleware steps in registration order.
184
+ */
185
+ constructor(schema, handler, subcommands, executionSteps) {
186
+ this.schema = schema;
187
+ this.handler = handler;
188
+ this._subcommands = subcommands ?? [];
189
+ this._executionSteps = executionSteps ?? [];
190
+ }
191
+ /**
192
+ * Register a command-level interactive resolver for schema-driven prompts.
193
+ *
194
+ * The resolver is called after CLI/env/config resolution with partially
195
+ * resolved flag values. It returns a prompt schema for flags that need
196
+ * interactive input based on the current state.
197
+ *
198
+ * For flags the resolver returns a {@linkcode PromptConfig}, that config is used
199
+ * instead of any per-flag `.prompt()` config. For flags returned as falsy
200
+ * (or not mentioned), per-flag `.prompt()` configs are used as fallback.
201
+ *
202
+ * Commands without `.interactive()` use per-flag prompt configs directly.
203
+ *
204
+ * @example
205
+ * ```ts
206
+ * const deploy = command('deploy')
207
+ * .flag('region', flag.enum(['us', 'eu', 'ap']))
208
+ * .flag('force', flag.boolean())
209
+ * .interactive(({ flags }) => ({
210
+ * region: !flags.region && {
211
+ * kind: 'select',
212
+ * message: 'Select region',
213
+ * },
214
+ * }))
215
+ * .action(({ flags }) => { ... });
216
+ * ```
217
+ *
218
+ * @param resolver - Function receiving partially resolved flags and returning prompt configs.
219
+ * @returns The builder (for chaining).
220
+ */
221
+ interactive(resolver) {
222
+ const erased = resolver;
223
+ return new CommandBuilder({
224
+ ...this.schema,
225
+ interactive: erased
226
+ }, this.handler, this._subcommands, this._executionSteps);
227
+ }
228
+ /**
229
+ * Register a command-scoped typed pre-action handler.
230
+ *
231
+ * Derive runs after full resolution and before the action handler.
232
+ * It receives typed `{ args, flags, ctx, out, meta }` and may either:
233
+ *
234
+ * - return nothing (or `undefined`) for validation-only behavior
235
+ * - return an object to merge additional properties into `ctx`
236
+ *
237
+ * Handlers may be async — the runtime awaits them before continuing.
238
+ *
239
+ * Unlike middleware, derive cannot wrap downstream execution and does not
240
+ * use `next()`. Use {@linkcode middleware} for timing, logging, retries, cleanup,
241
+ * or error-boundary patterns.
242
+ *
243
+ * Adding derive drops the current handler (like `.flag()`, `.arg()`, and
244
+ * `.middleware()`) because the action handler's `ctx` type may change.
245
+ *
246
+ * @example
247
+ * ```ts
248
+ * command('deploy')
249
+ * .flag('token', flag.string().env('AUTH_TOKEN'))
250
+ * .derive(({ flags }) => {
251
+ * if (!flags.token) {
252
+ * throw new CLIError('Not authenticated', {
253
+ * code: 'AUTH_REQUIRED',
254
+ * suggest: 'Run `mycli login` or set AUTH_TOKEN',
255
+ * });
256
+ * }
257
+ * return { token: flags.token };
258
+ * })
259
+ * .action(({ ctx }) => {
260
+ * ctx.token; // string
261
+ * });
262
+ * ```
263
+ *
264
+ * @param handler - Derive function receiving typed args/flags/ctx.
265
+ * @returns The builder (for chaining).
266
+ */
267
+ derive(handler) {
268
+ const erased = handler;
269
+ return new CommandBuilder({
270
+ ...this.schema,
271
+ hasAction: false
272
+ }, void 0, this._subcommands, [...this._executionSteps, {
273
+ kind: "derive",
274
+ handler: erased
275
+ }]);
276
+ }
277
+ /**
278
+ * Register middleware to run before the action handler.
279
+ *
280
+ * Middleware executes in registration order. Each middleware receives
281
+ * `{ args, flags, ctx, out, meta, next }` and must call `next(additions)`
282
+ * to continue the chain. Context additions are merged and become
283
+ * typed downstream.
284
+ *
285
+ * Adding middleware widens `C` via intersection and drops the current
286
+ * handler (like `.flag()` / `.arg()` — the handler's type signature
287
+ * changes when context changes).
288
+ *
289
+ * @example
290
+ * ```ts
291
+ * import { CLIError, command, middleware } from '@kjanat/dreamcli';
292
+ *
293
+ * interface User {
294
+ * id: string;
295
+ * email: string;
296
+ * }
297
+ *
298
+ * async function getCurrentUser(): Promise<User | null> {
299
+ * return { id: 'u_123', email: 'dev@example.com' };
300
+ * }
301
+ *
302
+ * function startTrace(name: string): string {
303
+ * return `trace:${name}`;
304
+ * }
305
+ *
306
+ * // Resolve the current user and expose it as `ctx.user` downstream.
307
+ * const auth = middleware<{ user: User }>(async ({ next }) => {
308
+ * const user = await getCurrentUser();
309
+ * if (!user) {
310
+ * throw new CLIError('Not authenticated', { code: 'AUTH_REQUIRED' });
311
+ * }
312
+ * await next({ user });
313
+ * });
314
+ *
315
+ * // Create a trace id for this command run and expose it as `ctx.traceId`.
316
+ * const telemetry = middleware<{ traceId: string }>(async ({ meta, next }) => {
317
+ * const traceId = startTrace(`${meta.name}.${meta.command}`);
318
+ * await next({ traceId });
319
+ * });
320
+ *
321
+ * command('deploy')
322
+ * .middleware(auth) // C becomes { user: User }
323
+ * .middleware(telemetry) // C becomes { user: User } & { traceId: string }
324
+ * .action(({ ctx }) => {
325
+ * ctx.user; // User — typed
326
+ * ctx.traceId; // string — typed
327
+ * });
328
+ * ```
329
+ *
330
+ * @param m - {@link Middleware} instance created via {@linkcode middleware | middleware()}.
331
+ * Middleware handlers receive `{ args, flags, ctx, out, meta, next }`.
332
+ * @returns The builder (for chaining).
333
+ */
334
+ middleware(m) {
335
+ return new CommandBuilder({
336
+ ...this.schema,
337
+ middleware: [...this.schema.middleware, m._handler],
338
+ hasAction: false
339
+ }, void 0, this._subcommands, [...this._executionSteps, {
340
+ kind: "middleware",
341
+ handler: m._handler
342
+ }]);
343
+ }
344
+ /**
345
+ * Set the command's description for help text.
346
+ *
347
+ * Displayed below the usage line in `--help` output and next to the
348
+ * command name in parent command/group help listings.
349
+ *
350
+ * @param text - One-line description of what the command does.
351
+ *
352
+ * @example
353
+ * ```ts
354
+ * command('deploy')
355
+ * .description('Deploy the application to a target environment')
356
+ * .action(({ out }) => { out.log('deploying...'); });
357
+ *
358
+ * // $ mycli deploy --help
359
+ * // Usage: deploy [flags]
360
+ * //
361
+ * // Deploy the application to a target environment
362
+ * ```
363
+ *
364
+ * @returns The builder (for chaining).
365
+ */
366
+ description(text) {
367
+ return new CommandBuilder({
368
+ ...this.schema,
369
+ description: text
370
+ }, this.handler, this._subcommands, this._executionSteps);
371
+ }
372
+ /**
373
+ * Add an alternative name for this command.
374
+ *
375
+ * Aliases are accepted during dispatch alongside the primary name.
376
+ * Multiple aliases can be chained. Aliases are shown in help output.
377
+ *
378
+ * @param name - Alternative command name (e.g. `'d'` for `deploy`).
379
+ *
380
+ * @example
381
+ * ```ts
382
+ * command('deploy')
383
+ * .alias('d')
384
+ * .alias('push')
385
+ * .action(({ out }) => { out.log('deploying...'); });
386
+ *
387
+ * // All equivalent:
388
+ * // $ mycli deploy
389
+ * // $ mycli d
390
+ * // $ mycli push
391
+ * ```
392
+ *
393
+ * @returns The builder (for chaining).
394
+ */
395
+ alias(name) {
396
+ return new CommandBuilder({
397
+ ...this.schema,
398
+ aliases: [...this.schema.aliases, name]
399
+ }, this.handler, this._subcommands, this._executionSteps);
400
+ }
401
+ /**
402
+ * Hide this command from help listings.
403
+ *
404
+ * The command remains fully functional and dispatchable — it just
405
+ * won't appear in `--help` output or shell completions. Useful for
406
+ * internal/debug commands.
407
+ *
408
+ * @example
409
+ * ```ts
410
+ * command('debug-dump')
411
+ * .hidden()
412
+ * .action(({ out }) => { out.log(JSON.stringify(internalState)); });
413
+ *
414
+ * // $ mycli --help → 'debug-dump' is not listed
415
+ * // $ mycli debug-dump → still works
416
+ * ```
417
+ *
418
+ * @returns The builder (for chaining).
419
+ */
420
+ hidden() {
421
+ return new CommandBuilder({
422
+ ...this.schema,
423
+ hidden: true
424
+ }, this.handler, this._subcommands, this._executionSteps);
425
+ }
426
+ /**
427
+ * Add a usage example to help text.
428
+ *
429
+ * Examples are rendered in the "Examples:" section of `--help` output.
430
+ * Call multiple times to add several examples. Each example shows a
431
+ * shell invocation, optionally with a description.
432
+ *
433
+ * @param cmd - The example command line (without the program name prefix).
434
+ * @param description - Optional one-line explanation of what the example does.
435
+ *
436
+ * @example
437
+ * ```ts
438
+ * command('deploy')
439
+ * .arg('target', arg.string())
440
+ * .flag('force', flag.boolean().alias('f'))
441
+ * .example('deploy production', 'Deploy to production')
442
+ * .example('deploy staging -f', 'Force deploy to staging')
443
+ * .action(({ args, flags }) => { ... });
444
+ *
445
+ * // $ mycli deploy --help
446
+ * // ...
447
+ * // Examples:
448
+ * // deploy production Deploy to production
449
+ * // deploy staging -f Force deploy to staging
450
+ * ```
451
+ *
452
+ * @returns The builder (for chaining).
453
+ */
454
+ example(cmd, description) {
455
+ const entry = description !== void 0 ? {
456
+ command: cmd,
457
+ description
458
+ } : { command: cmd };
459
+ return new CommandBuilder({
460
+ ...this.schema,
461
+ examples: [...this.schema.examples, entry]
462
+ }, this.handler, this._subcommands, this._executionSteps);
463
+ }
464
+ /**
465
+ * Register a named flag on this command.
466
+ *
467
+ * The flag name is added to the type-level `F` map. Duplicate flag names
468
+ * are prevented at the type level via the `Exclude` constraint.
469
+ *
470
+ * The builder controls the flag's type, presence, aliases, env/config
471
+ * bindings, and description. See {@link FlagBuilder} for available modifiers.
472
+ *
473
+ * @param name - Flag name: the `--name` CLI token and the matching key on `flags`
474
+ * in the handler. The name is preserved as-is (no camelCasing); read non-identifier
475
+ * names such as `'dry-run'` with bracket access (`flags['dry-run']`).
476
+ * @param builder - Configured {@linkcode FlagBuilder} from {@linkcode flag | flag.string()},
477
+ * `flag.boolean()`, `flag.number()`, `flag.enum()`, `flag.array()`, or `flag.custom()`.
478
+ *
479
+ * @example
480
+ * ```ts
481
+ * command('serve')
482
+ * .flag('port', flag.number()
483
+ * .alias('p')
484
+ * .env('PORT')
485
+ * .default(3000)
486
+ * .describe('Port to listen on'))
487
+ * .flag('host', flag.string()
488
+ * .env('HOST')
489
+ * .default('localhost')
490
+ * .describe('Bind address'))
491
+ * .flag('verbose', flag.boolean()
492
+ * .alias('v')
493
+ * .describe('Enable verbose logging'))
494
+ * .action(({ flags, out }) => {
495
+ * flags.port; // number
496
+ * flags.host; // string
497
+ * flags.verbose; // boolean
498
+ * out.log(`Listening on ${flags.host}:${flags.port}`);
499
+ * });
500
+ *
501
+ * // $ mycli serve --port 8080 -v
502
+ * // $ PORT=9090 mycli serve
503
+ * ```
504
+ *
505
+ * @returns The builder (for chaining).
506
+ */
507
+ flag(name, builder) {
508
+ if (name in this.schema.flags) throw new CLIError(`Command '${this.schema.name}' already defines flag --${name}`, {
509
+ code: "FLAG_NAME_COLLISION",
510
+ details: {
511
+ command: this.schema.name,
512
+ flag: name,
513
+ surface: name,
514
+ surfaceKind: "canonical"
515
+ }
516
+ });
517
+ const nextFlags = {
518
+ ...this.schema.flags,
519
+ [name]: builder.schema
520
+ };
521
+ const nextSchema = {
522
+ ...this.schema,
523
+ flags: nextFlags,
524
+ hasAction: false
525
+ };
526
+ validateCommandFlagTree(nextSchema);
527
+ return new CommandBuilder(nextSchema, void 0, this._subcommands, this._executionSteps);
528
+ }
529
+ /**
530
+ * Register a named positional argument on this command.
531
+ *
532
+ * Args are ordered by registration — position on the CLI matches the
533
+ * order of `.arg()` calls. The arg name is added to the type-level `A`
534
+ * map. Duplicate arg names are prevented at the type level via the
535
+ * `Exclude` constraint.
536
+ *
537
+ * The builder controls the arg's type, presence, env binding, and
538
+ * description. See {@link ArgBuilder} for available modifiers.
539
+ *
540
+ * @param name - Positional arg name (used in help text and `args.*`).
541
+ * @param builder - Configured {@linkcode ArgBuilder} from `arg.string()`, `arg.number()`,
542
+ * or `arg.custom()`.
543
+ *
544
+ * @example
545
+ * ```ts
546
+ * command('deploy')
547
+ * // Required string arg — first positional
548
+ * .arg('target', arg.string()
549
+ * .env('DEPLOY_TARGET')
550
+ * .describe('Deploy target'))
551
+ * // Optional number arg — second positional
552
+ * .arg('port', arg.number()
553
+ * .env('PORT')
554
+ * .default(3000)
555
+ * .describe('Port number'))
556
+ * .action(({ args }) => {
557
+ * args.target; // string
558
+ * args.port; // number
559
+ * });
560
+ *
561
+ * // Usage: deploy [flags] <target> [port]
562
+ * // $ mycli deploy production 8080
563
+ * // $ DEPLOY_TARGET=staging mycli deploy
564
+ * ```
565
+ *
566
+ * @returns The builder (for chaining).
567
+ */
568
+ arg(name, builder) {
569
+ validateArgEntry(name, builder.schema, this.schema.args);
570
+ const entry = {
571
+ name,
572
+ schema: builder.schema
573
+ };
574
+ const nextArgs = [...this.schema.args, entry];
575
+ return new CommandBuilder({
576
+ ...this.schema,
577
+ args: nextArgs,
578
+ hasAction: false
579
+ }, void 0, this._subcommands, this._executionSteps);
580
+ }
581
+ /**
582
+ * Register a nested subcommand on this command.
583
+ *
584
+ * The subcommand's builder is stored in `_subcommands` for the CLI layer's
585
+ * `eraseCommand()` to traverse when building the execution tree. The
586
+ * subcommand's `CommandSchema` is also appended to `schema.commands` for
587
+ * help rendering and completion generation.
588
+ *
589
+ * Does not change `F`, `A`, or `C` — subcommands are type-erased at the
590
+ * parent level (same semantics as `CLIBuilder.command()`). The handler is
591
+ * preserved.
592
+ *
593
+ * @example
594
+ * ```ts
595
+ * const db = group('db')
596
+ * .description('Database operations')
597
+ * .command(migrateCmd)
598
+ * .command(seedCmd);
599
+ * ```
600
+ *
601
+ * @param sub - Child {@link CommandBuilder} to nest under this command.
602
+ * @returns The builder (for chaining).
603
+ */
604
+ command(sub) {
605
+ const nextSchema = {
606
+ ...this.schema,
607
+ commands: [...this.schema.commands, sub.schema]
608
+ };
609
+ validateCommandFlagTree(nextSchema);
610
+ return new CommandBuilder(nextSchema, this.handler, [...this._subcommands, eraseBuilder(sub)], this._executionSteps);
611
+ }
612
+ /**
613
+ * Register the action handler for this command.
614
+ *
615
+ * The handler receives fully typed `{ args, flags, ctx, out, meta }` derived
616
+ * from the accumulated `.flag()`, `.arg()`, `.derive()`, and `.middleware()`
617
+ * definitions.
618
+ *
619
+ * May be synchronous or async. Return values are ignored; command handlers
620
+ * communicate through `out`, thrown errors, and side effects.
621
+ *
622
+ * @param handler - Function receiving `ActionParams<F, A, C>`.
623
+ *
624
+ * @example
625
+ * ```ts
626
+ * // Minimal
627
+ * command('greet')
628
+ * .arg('name', arg.string())
629
+ * .action(({ args, out }) => {
630
+ * out.log(`Hello, ${args.name}!`);
631
+ * });
632
+ * ```
633
+ *
634
+ * @example
635
+ * ```ts
636
+ * // Full params — flags, args, context, output, metadata
637
+ * command('deploy')
638
+ * .arg('target', arg.string().env('DEPLOY_TARGET'))
639
+ * .flag('force', flag.boolean().alias('f'))
640
+ * .flag('region', flag.enum(['us', 'eu', 'ap']).env('REGION'))
641
+ * .middleware(auth)
642
+ * .action(async ({ args, flags, ctx, out, meta }) => {
643
+ * args.target; // string
644
+ * flags.force; // boolean
645
+ * flags.region; // 'us' | 'eu' | 'ap' | undefined
646
+ * ctx.user; // User (from auth middleware)
647
+ * meta.command; // string
648
+ *
649
+ * const spinner = out.spinner('Deploying...');
650
+ * await deploy(args.target, { force: flags.force });
651
+ * spinner.stop();
652
+ * out.log('Done');
653
+ * });
654
+ * ```
655
+ *
656
+ * @returns The builder (for chaining).
657
+ */
658
+ action(handler) {
659
+ return new CommandBuilder({
660
+ ...this.schema,
661
+ hasAction: true
662
+ }, handler, this._subcommands, this._executionSteps);
663
+ }
664
+ };
665
+ /**
666
+ * Create a new command builder.
667
+ *
668
+ * @param name - The command name used for dispatch (e.g. `'deploy'`).
669
+ *
670
+ * @example
671
+ * ```ts
672
+ * import { arg, command, flag } from '@kjanat/dreamcli';
673
+ *
674
+ * const greet = command('greet')
675
+ * .arg('name', arg.string())
676
+ * .flag('loud', flag.boolean())
677
+ * .action(({ args, flags, out }) => {
678
+ * const msg = `Hello, ${args.name}!`;
679
+ * out.log(flags.loud ? msg.toUpperCase() : msg);
680
+ * });
681
+ * ```
682
+ *
683
+ * @returns A fresh {@link CommandBuilder} with empty flags, args, and context.
684
+ */
685
+ function command(name) {
686
+ return new CommandBuilder({
687
+ name,
688
+ description: void 0,
689
+ aliases: [],
690
+ hidden: false,
691
+ examples: [],
692
+ flags: {},
693
+ args: [],
694
+ hasAction: false,
695
+ interactive: void 0,
696
+ middleware: [],
697
+ commands: []
698
+ });
699
+ }
700
+ /**
701
+ * Create a command builder intended for use as a command group.
702
+ *
703
+ * Semantically identical to {@linkcode command | command()} — a group is simply a command that
704
+ * has subcommands registered via `.command()`. The separate factory
705
+ * communicates intent: groups organise subcommands, leaf commands have actions.
706
+ *
707
+ * A group may also have its own `.action()` (e.g. `git remote` lists remotes
708
+ * when invoked without a subcommand, but dispatches to `git remote add`, etc.).
709
+ *
710
+ * @param name - The group name used for dispatch (e.g. `'db'`).
711
+ *
712
+ * @example
713
+ * ```ts
714
+ * const db = group('db')
715
+ * .description('Database operations')
716
+ * .command(migrateCmd)
717
+ * .command(seedCmd);
718
+ * ```
719
+ *
720
+ * @returns A fresh {@link CommandBuilder} with empty flags, args, and context.
721
+ */
722
+ function group(name) {
723
+ return command(name);
724
+ }
725
+ //#endregion
726
+ export { CommandBuilder, command, group };