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

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 +227 -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,910 +0,0 @@
1
- /**
2
- * JSON Schema generation from CLI schemas.
3
- *
4
- * Two complementary functions:
5
- *
6
- * - {@link generateSchema} — definition metadata describing the CLI tree
7
- * (commands, flags, args, types, constraints) for tooling and documentation.
8
- *
9
- * - {@link generateInputSchema} — JSON Schema (draft 2020-12) for validating
10
- * CLI input as a JSON object, useful for config file validation and IDE
11
- * autocompletion.
12
- *
13
- * @module dreamcli/core/json-schema
14
- */
15
-
16
- import type { CLISchema } from '#internals/core/cli/index.ts';
17
- import { getFlagAliasNames } from '#internals/core/schema/flag.ts';
18
- import type {
19
- ArgSchema,
20
- CommandArgEntry,
21
- CommandExample,
22
- CommandSchema,
23
- FlagSchema,
24
- PromptConfig,
25
- SelectChoice,
26
- } from '#internals/core/schema/index.ts';
27
- import { parseSchema } from '#internals/core/schema-dsl/runtime.ts';
28
- import { nodeToJsonSchema } from '#internals/core/schema-dsl/to-json-schema.ts';
29
- import { definitionMetaSchemaDescriptions } from './meta-descriptions.generated.ts';
30
-
31
- // --- Options
32
-
33
- /**
34
- * Options for JSON Schema generation.
35
- *
36
- * Both {@link generateSchema} and {@link generateInputSchema} accept these
37
- * options to control which parts of the CLI schema are included in the output.
38
- */
39
- interface JsonSchemaOptions {
40
- /**
41
- * Include commands marked as hidden.
42
- *
43
- * When `true` (default), hidden commands appear in the output with
44
- * `hidden: true` (definition schema) or as valid branches (input schema).
45
- * When `false`, hidden commands and their entire subtrees are excluded.
46
- *
47
- * @defaultValue `true`
48
- */
49
- readonly includeHidden?: boolean;
50
-
51
- /**
52
- * Include prompt configuration on flags.
53
- *
54
- * When `false`, prompt configs are omitted even if defined on flags.
55
- * Useful for producing a schema focused on the non-interactive CLI
56
- * surface only.
57
- *
58
- * Only affects {@link generateSchema} output — prompt configs are never
59
- * included in {@link generateInputSchema} output.
60
- *
61
- * @defaultValue `true`
62
- */
63
- readonly includePrompts?: boolean;
64
- }
65
-
66
- /** Internal resolved options with defaults applied. */
67
- interface ResolvedOptions {
68
- readonly includeHidden: boolean;
69
- readonly includePrompts: boolean;
70
- }
71
-
72
- /**
73
- * Apply defaults to optional {@link JsonSchemaOptions}.
74
- *
75
- * @param options - User-supplied schema generation options, or `undefined` for all defaults.
76
- * @returns Fully resolved options with defaults applied.
77
- */
78
- function resolveOptions(options: JsonSchemaOptions | undefined): ResolvedOptions {
79
- return {
80
- includeHidden: options?.includeHidden ?? true,
81
- includePrompts: options?.includePrompts ?? true,
82
- };
83
- }
84
-
85
- // --- Constants
86
-
87
- /**
88
- * `$schema` URL for definition documents.
89
- *
90
- * Resolves via the actual file path on the CDN (`dreamcli.schema.json`).
91
- * For offline or local-first workflows, use
92
- * `./node_modules/@kjanat/dreamcli/dreamcli.schema.json`.
93
- */
94
- const DEFINITION_SCHEMA_URL = 'https://cdn.jsdelivr.net/npm/@kjanat/dreamcli/dreamcli.schema.json';
95
-
96
- /** Meta-schema URL for JSON Schema draft 2020-12 (input validation). */
97
- const JSON_SCHEMA_DRAFT = 'https://json-schema.org/draft/2020-12/schema';
98
-
99
- function isRecord(value: unknown): value is Record<string, unknown> {
100
- return typeof value === 'object' && value !== null && !Array.isArray(value);
101
- }
102
-
103
- // === Definition schema — generateSchema()
104
-
105
- /**
106
- * Generate a definition metadata document describing the CLI's structure.
107
- *
108
- * Walks the full command tree and produces a plain JSON-serializable object
109
- * representing all commands, subcommands, flags, args, and metadata.
110
- * Non-serializable runtime values (parse functions, middleware handlers,
111
- * interactive resolvers) are omitted.
112
- *
113
- * @param schema - The CLI schema from `CLIBuilder.schema`.
114
- * @param options - Generation options.
115
- * @returns A plain object suitable for `JSON.stringify()`.
116
- *
117
- * @example
118
- * ```ts
119
- * const app = cli('myapp').version('1.0.0').command(deploy);
120
- * const definition = generateSchema(app.schema);
121
- * writeFileSync('cli-schema.json', JSON.stringify(definition, null, 2));
122
- * ```
123
- */
124
- function generateSchema(schema: CLISchema, options?: JsonSchemaOptions): Record<string, unknown> {
125
- const opts = resolveOptions(options);
126
-
127
- const result: Record<string, unknown> = {
128
- $schema: DEFINITION_SCHEMA_URL,
129
- name: schema.name,
130
- };
131
-
132
- if (schema.version !== undefined) {
133
- result.version = schema.version;
134
- }
135
- if (schema.description !== undefined) {
136
- result.description = schema.description;
137
- }
138
- if (
139
- schema.defaultCommand !== undefined &&
140
- (opts.includeHidden || !schema.defaultCommand.schema.hidden)
141
- ) {
142
- result.defaultCommand = schema.defaultCommand.schema.name;
143
- }
144
-
145
- result.commands = schema.commands
146
- .filter((cmd) => opts.includeHidden || !cmd.schema.hidden)
147
- .map((cmd) => serializeCommand(cmd.schema, opts));
148
-
149
- return result;
150
- }
151
-
152
- // --- Command serialization
153
-
154
- /**
155
- * Serialize a single {@link CommandSchema} into a plain object.
156
- *
157
- * @param schema - The command schema to serialize.
158
- * @param opts - Resolved generation options (hidden/prompt inclusion).
159
- * @returns JSON-serializable object representing the command.
160
- */
161
- function serializeCommand(schema: CommandSchema, opts: ResolvedOptions): Record<string, unknown> {
162
- const result: Record<string, unknown> = { name: schema.name };
163
-
164
- if (schema.description !== undefined) {
165
- result.description = schema.description;
166
- }
167
- if (schema.aliases.length > 0) {
168
- result.aliases = [...schema.aliases];
169
- }
170
- if (schema.hidden) {
171
- result.hidden = true;
172
- }
173
- if (schema.examples.length > 0) {
174
- result.examples = schema.examples.map(serializeExample);
175
- }
176
-
177
- // Flags — always present (consumers iterate without existence check)
178
- const flags: Record<string, Record<string, unknown>> = {};
179
- for (const [name, flagDef] of Object.entries(schema.flags)) {
180
- flags[name] = serializeFlag(flagDef, opts);
181
- }
182
- result.flags = flags;
183
-
184
- // Args — always present (positional order matters)
185
- result.args = schema.args.map(serializeArgEntry);
186
-
187
- // Subcommands — always present
188
- result.commands = schema.commands
189
- .filter((cmd) => opts.includeHidden || !cmd.hidden)
190
- .map((cmd) => serializeCommand(cmd, opts));
191
-
192
- return result;
193
- }
194
-
195
- // --- Flag serialization
196
-
197
- /**
198
- * Serialize a {@link FlagSchema} into a plain object.
199
- *
200
- * @param schema - The flag schema to serialize.
201
- * @param opts - Resolved generation options (prompt inclusion).
202
- * @returns JSON-serializable object representing the flag.
203
- */
204
- function serializeFlag(schema: FlagSchema, opts: ResolvedOptions): Record<string, unknown> {
205
- const result: Record<string, unknown> = {
206
- kind: schema.kind,
207
- presence: schema.presence,
208
- };
209
-
210
- if (schema.presence === 'defaulted' && isJsonSerializable(schema.defaultValue)) {
211
- result.defaultValue = schema.defaultValue;
212
- }
213
- const visibleAliases = getFlagAliasNames(schema);
214
- if (visibleAliases.length > 0) {
215
- result.aliases = [...visibleAliases];
216
- }
217
- if (schema.envVar !== undefined) {
218
- result.envVar = schema.envVar;
219
- }
220
- if (schema.configPath !== undefined) {
221
- result.configPath = schema.configPath;
222
- }
223
- if (schema.description !== undefined) {
224
- result.description = schema.description;
225
- }
226
- if (schema.enumValues !== undefined) {
227
- result.enumValues = [...schema.enumValues];
228
- }
229
- if (schema.elementSchema !== undefined) {
230
- result.elementSchema = serializeFlag(schema.elementSchema, opts);
231
- }
232
- if (opts.includePrompts && schema.prompt !== undefined) {
233
- result.prompt = serializePrompt(schema.prompt);
234
- }
235
- if (schema.deprecated !== undefined) {
236
- result.deprecated = schema.deprecated;
237
- }
238
- if (schema.propagate) {
239
- result.propagate = true;
240
- }
241
-
242
- return result;
243
- }
244
-
245
- // --- Arg serialization
246
-
247
- /**
248
- * Serialize a {@link CommandArgEntry} into a plain object.
249
- *
250
- * @param entry - The positional arg entry (name + {@link ArgSchema}).
251
- * @returns JSON-serializable object representing the arg.
252
- */
253
- function serializeArgEntry(entry: CommandArgEntry): Record<string, unknown> {
254
- const { name, schema } = entry;
255
- const result: Record<string, unknown> = {
256
- name,
257
- kind: schema.kind,
258
- presence: schema.presence,
259
- };
260
-
261
- if (schema.variadic) {
262
- result.variadic = true;
263
- }
264
- if (schema.stdinMode) {
265
- result.stdinMode = true;
266
- }
267
- if (schema.presence === 'defaulted' && isJsonSerializable(schema.defaultValue)) {
268
- result.defaultValue = schema.defaultValue;
269
- }
270
- if (schema.description !== undefined) {
271
- result.description = schema.description;
272
- }
273
- if (schema.envVar !== undefined) {
274
- result.envVar = schema.envVar;
275
- }
276
- if (schema.enumValues !== undefined) {
277
- result.enumValues = [...schema.enumValues];
278
- }
279
- if (schema.deprecated !== undefined) {
280
- result.deprecated = schema.deprecated;
281
- }
282
-
283
- return result;
284
- }
285
-
286
- // --- Prompt serialization
287
-
288
- /**
289
- * Serialize a {@link PromptConfig} into a plain object.
290
- *
291
- * @param prompt - The prompt configuration to serialize.
292
- * @returns JSON-serializable object representing the prompt.
293
- */
294
- function serializePrompt(prompt: PromptConfig): Record<string, unknown> {
295
- const result: Record<string, unknown> = {
296
- kind: prompt.kind,
297
- message: prompt.message,
298
- };
299
-
300
- switch (prompt.kind) {
301
- case 'input':
302
- if (prompt.placeholder !== undefined) {
303
- result.placeholder = prompt.placeholder;
304
- }
305
- // validate fn omitted — not serializable
306
- break;
307
- case 'select':
308
- if (prompt.choices !== undefined) {
309
- result.choices = prompt.choices.map(serializeChoice);
310
- }
311
- break;
312
- case 'multiselect':
313
- if (prompt.choices !== undefined) {
314
- result.choices = prompt.choices.map(serializeChoice);
315
- }
316
- if (prompt.min !== undefined) {
317
- result.min = prompt.min;
318
- }
319
- if (prompt.max !== undefined) {
320
- result.max = prompt.max;
321
- }
322
- break;
323
- case 'confirm':
324
- break;
325
- }
326
-
327
- return result;
328
- }
329
-
330
- /**
331
- * Serialize a {@link SelectChoice} into a plain object.
332
- *
333
- * @param choice - The select/multiselect choice to serialize.
334
- * @returns JSON-serializable object with value, optional label and description.
335
- */
336
- function serializeChoice(choice: SelectChoice): Record<string, unknown> {
337
- const result: Record<string, unknown> = { value: choice.value };
338
- if (choice.label !== undefined) {
339
- result.label = choice.label;
340
- }
341
- if (choice.description !== undefined) {
342
- result.description = choice.description;
343
- }
344
- return result;
345
- }
346
-
347
- // --- Example serialization
348
-
349
- /**
350
- * Serialize a {@link CommandExample} into a plain object.
351
- *
352
- * @param example - The example to serialize.
353
- * @returns JSON-serializable object with command and optional description.
354
- */
355
- function serializeExample(example: CommandExample): Record<string, unknown> {
356
- const result: Record<string, unknown> = { command: example.command };
357
- if (example.description !== undefined) {
358
- result.description = example.description;
359
- }
360
- return result;
361
- }
362
-
363
- // === Input validation schema — generateInputSchema()
364
-
365
- /**
366
- * Generate a JSON Schema (draft 2020-12) for validating CLI input as JSON.
367
- *
368
- * Accepts either a full {@link CLISchema} (producing a discriminated union
369
- * across all commands) or a single {@link CommandSchema} (producing a flat
370
- * object schema for that command's flags and args).
371
- *
372
- * **Single command** — produces an object schema where flag/arg names are
373
- * properties with appropriate JSON Schema types.
374
- *
375
- * **Multi-command CLI** — produces a `oneOf` discriminated union with a
376
- * `command` property identifying each branch. Nested subcommands use
377
- * dot-delimited paths (e.g. `"deploy.rollback"`).
378
- *
379
- * Only commands with action handlers are included (group commands without
380
- * actions are not directly invocable and are skipped).
381
- *
382
- * @param schema - A CLI schema or a single command schema.
383
- * @param options - Generation options.
384
- * @returns A JSON Schema object suitable for `JSON.stringify()`.
385
- *
386
- * @example
387
- * ```ts
388
- * // Validate a config file against the CLI's input shape
389
- * const inputSchema = generateInputSchema(app.schema);
390
- * writeFileSync('input-schema.json', JSON.stringify(inputSchema, null, 2));
391
- * ```
392
- */
393
- function generateInputSchema(
394
- schema: CLISchema | CommandSchema,
395
- options?: JsonSchemaOptions,
396
- ): Record<string, unknown> {
397
- const opts = resolveOptions(options);
398
-
399
- // Discriminate between a leaf/group command schema and the CLI root schema.
400
- if (isCommandSchema(schema)) {
401
- return {
402
- $schema: JSON_SCHEMA_DRAFT,
403
- ...commandToInputSchema(schema),
404
- };
405
- }
406
-
407
- // CLISchema — collect all invocable commands into branches
408
- const branches: Array<Record<string, unknown>> = [];
409
- for (const cmd of schema.commands) {
410
- if (!opts.includeHidden && cmd.schema.hidden) continue;
411
- collectInputBranches(cmd.schema, '', branches, opts);
412
- }
413
-
414
- // Single branch: emit flat (no oneOf wrapper)
415
- if (branches.length === 1) {
416
- const branch = stripCommandDiscriminator(branches[0] ?? {});
417
- return {
418
- $schema: JSON_SCHEMA_DRAFT,
419
- ...branch,
420
- };
421
- }
422
-
423
- // Multiple branches: discriminated union
424
- if (branches.length > 0) {
425
- const defaultBranchName =
426
- schema.defaultCommand !== undefined &&
427
- (opts.includeHidden || !schema.defaultCommand.schema.hidden)
428
- ? schema.defaultCommand.schema.name
429
- : undefined;
430
- const normalizedBranches =
431
- defaultBranchName !== undefined
432
- ? branches.map((branch) =>
433
- getBranchCommandDiscriminator(branch) === defaultBranchName
434
- ? stripCommandDiscriminator(branch)
435
- : branch,
436
- )
437
- : branches;
438
-
439
- return {
440
- $schema: JSON_SCHEMA_DRAFT,
441
- oneOf: normalizedBranches,
442
- };
443
- }
444
-
445
- // No invocable commands
446
- return {
447
- $schema: JSON_SCHEMA_DRAFT,
448
- type: 'object',
449
- };
450
- }
451
-
452
- // --- Input schema helpers
453
-
454
- /**
455
- * Discriminate between CLISchema and CommandSchema at runtime.
456
- *
457
- * Use a command-only field combination rather than a single shape check:
458
- * command schemas always carry flags, args, middleware, and hasAction, while
459
- * the CLI root schema does not expose that execution surface.
460
- */
461
- function isCommandSchema(schema: CLISchema | CommandSchema): schema is CommandSchema {
462
- return 'flags' in schema && 'args' in schema && 'middleware' in schema && 'hasAction' in schema;
463
- }
464
-
465
- /** Recursively collect input schema branches for all invocable commands. */
466
- function collectInputBranches(
467
- schema: CommandSchema,
468
- prefix: string,
469
- branches: Array<Record<string, unknown>>,
470
- opts: ResolvedOptions,
471
- ): void {
472
- const path = prefix ? `${prefix}.${schema.name}` : schema.name;
473
-
474
- if (schema.hasAction) {
475
- branches.push(commandToInputSchema(schema, path));
476
- }
477
-
478
- for (const sub of schema.commands) {
479
- if (!opts.includeHidden && sub.hidden) continue;
480
- collectInputBranches(sub, path, branches, opts);
481
- }
482
- }
483
-
484
- /**
485
- * Create a JSON Schema object for a single command's flags + args.
486
- *
487
- * When `commandPath` is provided, a `command` const discriminator property
488
- * is added and required (used in multi-command oneOf schemas).
489
- */
490
- function commandToInputSchema(
491
- schema: CommandSchema,
492
- commandPath?: string,
493
- ): Record<string, unknown> {
494
- const properties: Record<string, Record<string, unknown>> = {};
495
- const required: string[] = [];
496
-
497
- // Command discriminator (for multi-command schemas)
498
- if (commandPath !== undefined) {
499
- properties.command = { const: commandPath };
500
- required.push('command');
501
- }
502
-
503
- // Flags → properties
504
- for (const [name, flagDef] of Object.entries(schema.flags)) {
505
- properties[name] = flagToJsonSchemaType(flagDef);
506
- if (flagDef.presence === 'required') {
507
- required.push(name);
508
- }
509
- }
510
-
511
- // Args → properties (by name)
512
- for (const entry of schema.args) {
513
- properties[entry.name] = argToJsonSchemaType(entry.schema);
514
- if (entry.schema.presence === 'required') {
515
- required.push(entry.name);
516
- }
517
- }
518
-
519
- const result: Record<string, unknown> = {
520
- type: 'object',
521
- properties,
522
- additionalProperties: false,
523
- };
524
-
525
- if (required.length > 0) {
526
- result.required = required;
527
- }
528
-
529
- return result;
530
- }
531
-
532
- /** @internal */
533
- function stripCommandDiscriminator(branch: Record<string, unknown>): Record<string, unknown> {
534
- const propertiesValue = branch.properties;
535
- const requiredValue = branch.required;
536
- const properties = isRecord(propertiesValue) ? { ...propertiesValue } : undefined;
537
- const required = Array.isArray(requiredValue)
538
- ? requiredValue.filter((value): value is string => typeof value === 'string')
539
- : undefined;
540
-
541
- if (properties !== undefined) {
542
- delete properties.command;
543
- }
544
-
545
- const cleanedRequired = required?.filter((value) => value !== 'command');
546
- const result: Record<string, unknown> = { ...branch };
547
-
548
- if (properties !== undefined) {
549
- result.properties = properties;
550
- }
551
-
552
- if (cleanedRequired !== undefined && cleanedRequired.length > 0) {
553
- result.required = cleanedRequired;
554
- } else {
555
- delete result.required;
556
- }
557
-
558
- return result;
559
- }
560
-
561
- function getBranchCommandDiscriminator(branch: Record<string, unknown>): string | undefined {
562
- const propertiesValue = branch.properties;
563
- if (!isRecord(propertiesValue)) {
564
- return undefined;
565
- }
566
-
567
- const commandValue = propertiesValue.command;
568
- return isRecord(commandValue) && typeof commandValue.const === 'string'
569
- ? commandValue.const
570
- : undefined;
571
- }
572
-
573
- // --- Type mapping — flags → JSON Schema types
574
-
575
- function flagToJsonSchemaType(schema: FlagSchema): Record<string, unknown> {
576
- const result: Record<string, unknown> = {};
577
-
578
- switch (schema.kind) {
579
- case 'string':
580
- result.type = 'string';
581
- break;
582
- case 'number': {
583
- const constraints = schema.numberConstraints;
584
- result.type = constraints?.int === true ? 'integer' : 'number';
585
- if (constraints?.min !== undefined) {
586
- result.minimum = constraints.min;
587
- }
588
- if (constraints?.max !== undefined) {
589
- result.maximum = constraints.max;
590
- }
591
- break;
592
- }
593
- case 'boolean':
594
- result.type = 'boolean';
595
- break;
596
- case 'enum':
597
- result.type = 'string';
598
- if (schema.enumValues !== undefined) {
599
- result.enum = [...schema.enumValues];
600
- }
601
- break;
602
- case 'array':
603
- result.type = 'array';
604
- if (schema.elementSchema !== undefined) {
605
- result.items = flagToJsonSchemaType(schema.elementSchema);
606
- }
607
- break;
608
- case 'custom':
609
- // Opaque type — no JSON Schema constraint
610
- break;
611
- }
612
-
613
- if (schema.description !== undefined) {
614
- result.description = schema.description;
615
- }
616
- if (schema.presence === 'defaulted' && isJsonSerializable(schema.defaultValue)) {
617
- result.default = schema.defaultValue;
618
- }
619
- if (schema.deprecated !== undefined) {
620
- result.deprecated = schema.deprecated;
621
- }
622
-
623
- return result;
624
- }
625
-
626
- // --- Type mapping — args → JSON Schema types
627
-
628
- function argToJsonSchemaType(schema: ArgSchema): Record<string, unknown> {
629
- const kind = argKindToType(schema);
630
- const result: Record<string, unknown> = schema.variadic
631
- ? { type: 'array', items: kind }
632
- : { ...kind };
633
-
634
- if (schema.description !== undefined) {
635
- result.description = schema.description;
636
- }
637
- if (schema.presence === 'defaulted' && isJsonSerializable(schema.defaultValue)) {
638
- result.default = schema.defaultValue;
639
- }
640
- if (schema.deprecated !== undefined) {
641
- result.deprecated = schema.deprecated;
642
- }
643
-
644
- return result;
645
- }
646
-
647
- /** Map an arg's kind to a JSON Schema type fragment. */
648
- function argKindToType(schema: ArgSchema): Record<string, unknown> {
649
- switch (schema.kind) {
650
- case 'string':
651
- return { type: 'string' };
652
- case 'number': {
653
- const constraints = schema.numberConstraints;
654
- const result: Record<string, unknown> = {
655
- type: constraints?.int === true ? 'integer' : 'number',
656
- };
657
- if (constraints?.min !== undefined) {
658
- result.minimum = constraints.min;
659
- }
660
- if (constraints?.max !== undefined) {
661
- result.maximum = constraints.max;
662
- }
663
- return result;
664
- }
665
- case 'enum': {
666
- const result: Record<string, unknown> = { type: 'string' };
667
- if (schema.enumValues !== undefined) {
668
- result.enum = [...schema.enumValues];
669
- }
670
- return result;
671
- }
672
- case 'custom':
673
- return {};
674
- }
675
- }
676
-
677
- // === Utilities
678
-
679
- /**
680
- * Check whether a value can survive a JSON round-trip.
681
- *
682
- * Returns `false` for functions, symbols, bigints, non-finite numbers, and
683
- * objects containing them. Used to guard default-value inclusion in
684
- * serialized output.
685
- */
686
- function isJsonSerializable(
687
- value: unknown,
688
- seen: WeakSet<object> = new WeakSet<object>(),
689
- ): boolean {
690
- if (value === undefined) return false;
691
- if (value === null) return true;
692
- const t = typeof value;
693
- if (t === 'string' || t === 'boolean') return true;
694
- if (t === 'number') return Number.isFinite(value);
695
- if (t === 'function' || t === 'symbol' || t === 'bigint') return false;
696
- if (Array.isArray(value)) {
697
- if (seen.has(value)) return false;
698
- seen.add(value);
699
- try {
700
- return value.every((entry) => isJsonSerializable(entry, seen));
701
- } finally {
702
- seen.delete(value);
703
- }
704
- }
705
- if (t === 'object') {
706
- const objectValue = value as Record<string, unknown>;
707
- if (!isPlainJsonObject(objectValue)) return false;
708
- if (seen.has(objectValue)) return false;
709
- seen.add(objectValue);
710
- try {
711
- return Object.values(objectValue).every((entry) => isJsonSerializable(entry, seen));
712
- } finally {
713
- seen.delete(objectValue);
714
- }
715
- }
716
- return false;
717
- }
718
-
719
- /**
720
- * Check whether an object is a plain JSON object.
721
- *
722
- * Accepts objects with `Object.prototype` or a null prototype, which are the
723
- * only object shapes that round-trip through JSON as structural objects.
724
- *
725
- * @internal
726
- */
727
- function isPlainJsonObject(value: object): value is Record<string, unknown> {
728
- const proto = Object.getPrototypeOf(value);
729
- return proto === Object.prototype || proto === null;
730
- }
731
-
732
- // === Definition meta-schema — derived from schema DSL definitions
733
-
734
- /** Convert a DSL string to a JSON Schema object definition. */
735
- function def(source: string): Record<string, unknown> {
736
- return nodeToJsonSchema(parseSchema(source));
737
- }
738
-
739
- interface DefinitionMetaSchemaDescriptionNode {
740
- readonly description?: string;
741
- readonly properties?: Readonly<Record<string, DefinitionMetaSchemaDescriptionNode>>;
742
- }
743
-
744
- function withDefinitionDescriptions(
745
- schema: Record<string, unknown>,
746
- descriptions: DefinitionMetaSchemaDescriptionNode,
747
- ): Record<string, unknown> {
748
- const propertiesValue = schema.properties;
749
- const describedProperties =
750
- typeof propertiesValue === 'object' &&
751
- propertiesValue !== null &&
752
- isPlainJsonObject(propertiesValue) &&
753
- descriptions.properties !== undefined
754
- ? Object.fromEntries(
755
- Object.entries(propertiesValue).map(([name, propertySchema]) => {
756
- const propertyDescriptions = descriptions.properties?.[name];
757
- if (
758
- propertyDescriptions === undefined ||
759
- typeof propertySchema !== 'object' ||
760
- propertySchema === null ||
761
- !isPlainJsonObject(propertySchema)
762
- ) {
763
- return [name, propertySchema];
764
- }
765
-
766
- return [name, withDefinitionDescriptions(propertySchema, propertyDescriptions)];
767
- }),
768
- )
769
- : undefined;
770
-
771
- return {
772
- ...schema,
773
- ...(descriptions.description !== undefined ? { description: descriptions.description } : {}),
774
- ...(describedProperties !== undefined ? { properties: describedProperties } : {}),
775
- };
776
- }
777
-
778
- function withDefinitionMetaSchemaDescriptions(
779
- schema: Record<string, unknown>,
780
- descriptions: {
781
- readonly root: DefinitionMetaSchemaDescriptionNode;
782
- readonly defs: Readonly<Record<string, DefinitionMetaSchemaDescriptionNode>>;
783
- },
784
- ): Record<string, unknown> {
785
- const describedRoot = withDefinitionDescriptions(schema, descriptions.root);
786
- const defsValue = describedRoot.$defs;
787
- if (typeof defsValue !== 'object' || defsValue === null || !isPlainJsonObject(defsValue)) {
788
- return describedRoot;
789
- }
790
-
791
- return {
792
- ...describedRoot,
793
- $defs: Object.fromEntries(
794
- Object.entries(defsValue).map(([name, defSchema]) => {
795
- const defDescriptions = descriptions.defs[name];
796
- if (
797
- defDescriptions === undefined ||
798
- typeof defSchema !== 'object' ||
799
- defSchema === null ||
800
- !isPlainJsonObject(defSchema)
801
- ) {
802
- return [name, defSchema];
803
- }
804
-
805
- return [name, withDefinitionDescriptions(defSchema, defDescriptions)];
806
- }),
807
- ),
808
- };
809
- }
810
-
811
- /**
812
- * JSON Schema (draft 2020-12) that validates the output of {@link generateSchema}.
813
- *
814
- * Each `$defs` entry is defined once as a schema DSL string — the DSL
815
- * parser produces a runtime AST, and {@link nodeToJsonSchema} converts
816
- * that AST to a JSON Schema fragment. No probe fixtures, no override
817
- * maps, no manually maintained type definitions.
818
- *
819
- * Hosted at {@link DEFINITION_SCHEMA_URL} for `$schema` resolution. Also
820
- * exported so tooling can validate definition documents without a network
821
- * round-trip.
822
- *
823
- * @example
824
- * ```ts
825
- * import Ajv from 'ajv/dist/2020';
826
- * import { definitionMetaSchema, generateSchema } from '@kjanat/dreamcli';
827
- *
828
- * const ajv = new Ajv();
829
- * const validate = ajv.compile(definitionMetaSchema);
830
- * const valid = validate(generateSchema(myCli.schema));
831
- * ```
832
- */
833
- const definitionMetaSchema: Record<string, unknown> = withDefinitionMetaSchemaDescriptions(
834
- {
835
- $schema: JSON_SCHEMA_DRAFT,
836
- $id: DEFINITION_SCHEMA_URL,
837
- title: '@kjanat/dreamcli definition schema',
838
- description:
839
- 'Describes the structure of a CLI built with dreamcli — commands, flags, args, types, constraints, env bindings, and prompts.',
840
- ...def(`{
841
- $schema: '${DEFINITION_SCHEMA_URL}';
842
- name: string;
843
- version?: string;
844
- description?: string;
845
- defaultCommand?: string;
846
- commands: @command[]
847
- }`),
848
- $defs: {
849
- command: def(`{
850
- name: string;
851
- description?: string;
852
- aliases?: string[];
853
- hidden?: true;
854
- examples?: @example[];
855
- flags: Record<string, @flag>;
856
- args: @arg[];
857
- commands: @command[]
858
- }`),
859
- flag: def(`{
860
- kind: 'string' | 'number' | 'boolean' | 'enum' | 'array' | 'custom';
861
- presence: 'optional' | 'required' | 'defaulted';
862
- defaultValue?: unknown;
863
- aliases?: string[];
864
- envVar?: string;
865
- configPath?: string;
866
- description?: string;
867
- enumValues?: string[];
868
- elementSchema?: @flag;
869
- prompt?: @prompt;
870
- deprecated?: string | true;
871
- propagate?: true
872
- }`),
873
- arg: def(`{
874
- name: string;
875
- kind: 'string' | 'number' | 'enum' | 'custom';
876
- presence: 'required' | 'optional' | 'defaulted';
877
- variadic?: true;
878
- stdinMode?: true;
879
- defaultValue?: unknown;
880
- description?: string;
881
- envVar?: string;
882
- enumValues?: string[];
883
- deprecated?: string | true
884
- }`),
885
- prompt: def(`{
886
- kind: 'confirm' | 'input' | 'select' | 'multiselect';
887
- message: string;
888
- placeholder?: string;
889
- choices?: @choice[];
890
- min?: integer;
891
- max?: integer
892
- }`),
893
- choice: def(`{
894
- value: string;
895
- label?: string;
896
- description?: string
897
- }`),
898
- example: def(`{
899
- command: string;
900
- description?: string
901
- }`),
902
- },
903
- },
904
- definitionMetaSchemaDescriptions,
905
- );
906
-
907
- // === Exports
908
-
909
- export type { JsonSchemaOptions };
910
- export { definitionMetaSchema, generateInputSchema, generateSchema };