incur 0.3.5 → 0.3.6

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 (49) hide show
  1. package/README.md +61 -0
  2. package/dist/Cli.d.ts +15 -0
  3. package/dist/Cli.d.ts.map +1 -1
  4. package/dist/Cli.js +207 -11
  5. package/dist/Cli.js.map +1 -1
  6. package/dist/Filter.js +0 -18
  7. package/dist/Filter.js.map +1 -1
  8. package/dist/Help.d.ts +4 -0
  9. package/dist/Help.d.ts.map +1 -1
  10. package/dist/Help.js +17 -14
  11. package/dist/Help.js.map +1 -1
  12. package/dist/Parser.d.ts +2 -0
  13. package/dist/Parser.d.ts.map +1 -1
  14. package/dist/Parser.js +69 -37
  15. package/dist/Parser.js.map +1 -1
  16. package/dist/bin.d.ts +1 -0
  17. package/dist/bin.d.ts.map +1 -1
  18. package/dist/bin.js +17 -2
  19. package/dist/bin.js.map +1 -1
  20. package/dist/internal/command.d.ts +2 -0
  21. package/dist/internal/command.d.ts.map +1 -1
  22. package/dist/internal/command.js +1 -0
  23. package/dist/internal/command.js.map +1 -1
  24. package/dist/internal/configSchema.d.ts +8 -0
  25. package/dist/internal/configSchema.d.ts.map +1 -0
  26. package/dist/internal/configSchema.js +57 -0
  27. package/dist/internal/configSchema.js.map +1 -0
  28. package/dist/internal/helpers.d.ts +5 -0
  29. package/dist/internal/helpers.d.ts.map +1 -0
  30. package/dist/internal/helpers.js +9 -0
  31. package/dist/internal/helpers.js.map +1 -0
  32. package/examples/npm/.npmrc.json +21 -0
  33. package/examples/npm/config.schema.json +137 -0
  34. package/package.json +1 -1
  35. package/src/Cli.test-d.ts +39 -0
  36. package/src/Cli.test.ts +554 -3
  37. package/src/Cli.ts +266 -11
  38. package/src/Filter.ts +0 -17
  39. package/src/Help.test.ts +66 -0
  40. package/src/Help.ts +20 -13
  41. package/src/Parser.test-d.ts +22 -0
  42. package/src/Parser.test.ts +89 -0
  43. package/src/Parser.ts +86 -35
  44. package/src/bin.ts +21 -2
  45. package/src/e2e.test.ts +1 -1
  46. package/src/internal/command.ts +3 -0
  47. package/src/internal/configSchema.test.ts +193 -0
  48. package/src/internal/configSchema.ts +66 -0
  49. package/src/internal/helpers.ts +9 -0
@@ -252,4 +252,93 @@ describe('parse', () => {
252
252
  expect(result.args).toEqual({ repo: 'myrepo' })
253
253
  expect(result.options).toEqual({ limit: 5 })
254
254
  })
255
+
256
+ test('applies config defaults when argv omits an option', () => {
257
+ const result = Parser.parse([], {
258
+ defaults: { limit: 10 },
259
+ options: z.object({ limit: z.number().default(30) }),
260
+ })
261
+ expect(result.options).toEqual({ limit: 10 })
262
+ })
263
+
264
+ test('argv overrides config defaults', () => {
265
+ const result = Parser.parse(['--limit', '5'], {
266
+ defaults: { limit: 10 },
267
+ options: z.object({ limit: z.number().default(30) }),
268
+ })
269
+ expect(result.options).toEqual({ limit: 5 })
270
+ })
271
+
272
+ test('argv arrays replace config arrays', () => {
273
+ const result = Parser.parse(['--label', 'bug', '--label', 'feature'], {
274
+ defaults: { label: ['ops'] },
275
+ options: z.object({ label: z.array(z.string()).default([]) }),
276
+ })
277
+ expect(result.options).toEqual({ label: ['bug', 'feature'] })
278
+ })
279
+
280
+ test('kebab-case config keys map to camelCase schema names', () => {
281
+ const result = Parser.parse([], {
282
+ defaults: { 'save-dev': true } as any,
283
+ options: z.object({ saveDev: z.boolean().default(false) }),
284
+ })
285
+ expect(result.options).toEqual({ saveDev: true })
286
+ })
287
+
288
+ test('throws ParseError on unknown config option keys', () => {
289
+ expect(() =>
290
+ Parser.parse([], {
291
+ defaults: { missing: true } as any,
292
+ options: z.object({ saveDev: z.boolean().default(false) }),
293
+ }),
294
+ ).toThrow(expect.objectContaining({ name: 'Incur.ParseError' }))
295
+ })
296
+
297
+ test('throws ValidationError for invalid config defaults when argv does not override them', () => {
298
+ expect(() =>
299
+ Parser.parse([], {
300
+ defaults: { limit: 'oops' } as any,
301
+ options: z.object({ limit: z.number() }),
302
+ }),
303
+ ).toThrow(expect.objectContaining({ name: 'Incur.ValidationError' }))
304
+ })
305
+
306
+ test('argv overrides invalid config defaults', () => {
307
+ const result = Parser.parse(['--limit', '5'], {
308
+ defaults: { limit: 'oops' } as any,
309
+ options: z.object({ limit: z.number() }),
310
+ })
311
+ expect(result.options).toEqual({ limit: 5 })
312
+ })
313
+
314
+ test('defaults with no options schema throws on non-empty defaults', () => {
315
+ expect(() =>
316
+ Parser.parse([], {
317
+ defaults: { limit: 10 } as any,
318
+ }),
319
+ ).toThrow(expect.objectContaining({ name: 'Incur.ParseError' }))
320
+ })
321
+
322
+ test('defaults with no options schema and empty defaults is a no-op', () => {
323
+ const result = Parser.parse([], { defaults: {} as any })
324
+ expect(result.options).toEqual({})
325
+ })
326
+
327
+ test('config array defaults are used when argv omits the option', () => {
328
+ const result = Parser.parse([], {
329
+ defaults: { label: ['bug', 'feature'] },
330
+ options: z.object({ label: z.array(z.string()).default([]) }),
331
+ })
332
+ expect(result.options).toEqual({ label: ['bug', 'feature'] })
333
+ })
334
+
335
+ test('refined option schemas validate only the merged winning values', () => {
336
+ const result = Parser.parse(['--min', '1', '--max', '3'], {
337
+ defaults: { min: 'oops' } as any,
338
+ options: z
339
+ .object({ min: z.number(), max: z.number() })
340
+ .refine((value) => value.min < value.max, { message: 'min must be less than max' }),
341
+ })
342
+ expect(result.options).toEqual({ min: 1, max: 3 })
343
+ })
255
344
  })
package/src/Parser.ts CHANGED
@@ -2,29 +2,20 @@ import type { z } from 'zod'
2
2
 
3
3
  import type { FieldError } from './Errors.js'
4
4
  import { ParseError, ValidationError } from './Errors.js'
5
+ import { isRecord, toKebab } from './internal/helpers.js'
5
6
 
6
7
  /** Parses raw argv tokens against Zod schemas for args and options. */
7
8
  export function parse<
8
9
  const args extends z.ZodObject<any> | undefined = undefined,
9
10
  const options extends z.ZodObject<any> | undefined = undefined,
10
11
  >(argv: string[], options: parse.Options<args, options> = {}): parse.ReturnType<args, options> {
11
- const { args: argsSchema, options: optionsSchema, alias } = options
12
+ const { args: argsSchema, options: optionsSchema, alias, defaults } = options
12
13
 
13
- // Build reverse alias map: short char → long name
14
- const aliasToName = new Map<string, string>()
15
- if (alias) for (const [name, short] of Object.entries(alias)) aliasToName.set(short, name)
16
-
17
- // Known option names from schema, plus kebab-case → camelCase map
18
- const knownOptions = new Set(optionsSchema ? Object.keys(optionsSchema.shape) : [])
19
- const kebabToCamel = new Map<string, string>()
20
- for (const name of knownOptions) {
21
- const kebab = name.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)
22
- if (kebab !== name) kebabToCamel.set(kebab, name)
23
- }
14
+ const optionNames = createOptionNames(optionsSchema, alias)
24
15
 
25
16
  // First pass: split argv into positional tokens and raw option values
26
17
  const positionals: string[] = []
27
- const rawOptions: Record<string, unknown> = {}
18
+ const rawArgvOptions: Record<string, unknown> = {}
28
19
 
29
20
  let i = 0
30
21
  while (i < argv.length) {
@@ -32,36 +23,34 @@ export function parse<
32
23
 
33
24
  if (token.startsWith('--no-') && token.length > 5) {
34
25
  // --no-flag negation
35
- const raw = token.slice(5)
36
- const name = kebabToCamel.get(raw) ?? raw
37
- if (!knownOptions.has(name)) throw new ParseError({ message: `Unknown flag: ${token}` })
38
- rawOptions[name] = false
26
+ const name = normalizeOptionName(token.slice(5), optionNames)
27
+ if (!name) throw new ParseError({ message: `Unknown flag: ${token}` })
28
+ rawArgvOptions[name] = false
39
29
  i++
40
30
  } else if (token.startsWith('--')) {
41
31
  const eqIdx = token.indexOf('=')
42
32
  if (eqIdx !== -1) {
43
33
  // --flag=value
44
34
  const raw = token.slice(2, eqIdx)
45
- const name = kebabToCamel.get(raw) ?? raw
46
- if (!knownOptions.has(name)) throw new ParseError({ message: `Unknown flag: --${raw}` })
47
- setOption(rawOptions, name, token.slice(eqIdx + 1), optionsSchema)
35
+ const name = normalizeOptionName(raw, optionNames)
36
+ if (!name) throw new ParseError({ message: `Unknown flag: --${raw}` })
37
+ setOption(rawArgvOptions, name, token.slice(eqIdx + 1), optionsSchema)
48
38
  i++
49
39
  } else {
50
40
  // --flag [value]
51
- const raw = token.slice(2)
52
- const name = kebabToCamel.get(raw) ?? raw
53
- if (!knownOptions.has(name)) throw new ParseError({ message: `Unknown flag: ${token}` })
41
+ const name = normalizeOptionName(token.slice(2), optionNames)
42
+ if (!name) throw new ParseError({ message: `Unknown flag: ${token}` })
54
43
  if (isCountOption(name, optionsSchema)) {
55
- rawOptions[name] = ((rawOptions[name] as number) ?? 0) + 1
44
+ rawArgvOptions[name] = ((rawArgvOptions[name] as number) ?? 0) + 1
56
45
  i++
57
46
  } else if (isBooleanOption(name, optionsSchema)) {
58
- rawOptions[name] = true
47
+ rawArgvOptions[name] = true
59
48
  i++
60
49
  } else {
61
50
  const value = argv[i + 1]
62
51
  if (value === undefined)
63
52
  throw new ParseError({ message: `Missing value for flag: ${token}` })
64
- setOption(rawOptions, name, value, optionsSchema)
53
+ setOption(rawArgvOptions, name, value, optionsSchema)
65
54
  i += 2
66
55
  }
67
56
  }
@@ -70,28 +59,28 @@ export function parse<
70
59
  const chars = token.slice(1)
71
60
  for (let j = 0; j < chars.length; j++) {
72
61
  const short = chars[j]!
73
- const name = aliasToName.get(short)
62
+ const name = optionNames.aliasToName.get(short)
74
63
  if (!name) throw new ParseError({ message: `Unknown flag: -${short}` })
75
64
  const isLast = j === chars.length - 1
76
65
  if (!isLast) {
77
66
  if (isCountOption(name, optionsSchema)) {
78
- rawOptions[name] = ((rawOptions[name] as number) ?? 0) + 1
67
+ rawArgvOptions[name] = ((rawArgvOptions[name] as number) ?? 0) + 1
79
68
  } else if (isBooleanOption(name, optionsSchema)) {
80
- rawOptions[name] = true
69
+ rawArgvOptions[name] = true
81
70
  } else {
82
71
  throw new ParseError({
83
72
  message: `Non-boolean flag -${short} must be last in a stacked alias`,
84
73
  })
85
74
  }
86
75
  } else if (isCountOption(name, optionsSchema)) {
87
- rawOptions[name] = ((rawOptions[name] as number) ?? 0) + 1
76
+ rawArgvOptions[name] = ((rawArgvOptions[name] as number) ?? 0) + 1
88
77
  } else if (isBooleanOption(name, optionsSchema)) {
89
- rawOptions[name] = true
78
+ rawArgvOptions[name] = true
90
79
  } else {
91
80
  const value = argv[i + 1]
92
81
  if (value === undefined)
93
82
  throw new ParseError({ message: `Missing value for flag: -${short}` })
94
- setOption(rawOptions, name, value, optionsSchema)
83
+ setOption(rawArgvOptions, name, value, optionsSchema)
95
84
  i++
96
85
  }
97
86
  }
@@ -117,15 +106,19 @@ export function parse<
117
106
  // Validate args through zod
118
107
  const args = argsSchema ? zodParse(argsSchema, rawArgs) : {}
119
108
 
109
+ const rawDefaults = normalizeOptionDefaults(defaults, optionsSchema, optionNames)
110
+
120
111
  // Coerce raw option values before zod validation
121
112
  if (optionsSchema) {
122
- for (const [name, value] of Object.entries(rawOptions)) {
123
- rawOptions[name] = coerce(value, name, optionsSchema)
113
+ for (const [name, value] of Object.entries(rawArgvOptions)) {
114
+ rawArgvOptions[name] = coerce(value, name, optionsSchema)
124
115
  }
125
116
  }
126
117
 
118
+ const mergedOptions = { ...rawDefaults, ...rawArgvOptions }
119
+
127
120
  // Validate options through zod
128
- const parsedOptions = optionsSchema ? zodParse(optionsSchema, rawOptions) : {}
121
+ const parsedOptions = optionsSchema ? zodParse(optionsSchema, mergedOptions) : {}
129
122
 
130
123
  return { args, options: parsedOptions } as parse.ReturnType<args, options>
131
124
  }
@@ -138,6 +131,8 @@ export declare namespace parse {
138
131
  > = {
139
132
  /** Zod schema for positional arguments. Keys define order. */
140
133
  args?: args
134
+ /** Config-backed option defaults merged before argv parsing. */
135
+ defaults?: options extends z.ZodObject<any> ? Partial<z.input<options>> | undefined : undefined
141
136
  /** Zod schema for named options/flags. */
142
137
  options?: options
143
138
  /** Map of option names to single-char aliases. */
@@ -155,6 +150,62 @@ export declare namespace parse {
155
150
  }
156
151
  }
157
152
 
153
+ type OptionNames = {
154
+ aliasToName: Map<string, string>
155
+ kebabToCamel: Map<string, string>
156
+ knownOptions: Set<string>
157
+ }
158
+
159
+ /** Builds lookup tables for option names and short aliases. */
160
+ function createOptionNames(
161
+ schema: z.ZodObject<any> | undefined,
162
+ alias: Record<string, string> | undefined,
163
+ ): OptionNames {
164
+ const aliasToName = new Map<string, string>()
165
+ if (alias) for (const [name, short] of Object.entries(alias)) aliasToName.set(short, name)
166
+
167
+ const knownOptions = new Set(schema ? Object.keys(schema.shape) : [])
168
+ const kebabToCamel = new Map<string, string>()
169
+ for (const name of knownOptions) {
170
+ const kebab = toKebab(name)
171
+ if (kebab !== name) kebabToCamel.set(kebab, name)
172
+ }
173
+
174
+ return { aliasToName, kebabToCamel, knownOptions }
175
+ }
176
+
177
+ /** Normalizes a long option name, accepting kebab-case aliases for camelCase schema keys. */
178
+ function normalizeOptionName(raw: string, options: OptionNames): string | undefined {
179
+ const name = options.kebabToCamel.get(raw) ?? raw
180
+ return options.knownOptions.has(name) ? name : undefined
181
+ }
182
+
183
+ /** Normalizes config-backed defaults and validates config structure/key names. */
184
+ function normalizeOptionDefaults(
185
+ defaults: unknown,
186
+ schema: z.ZodObject<any> | undefined,
187
+ optionNames: OptionNames,
188
+ ): Record<string, unknown> {
189
+ if (defaults === undefined) return {}
190
+ if (!isRecord(defaults))
191
+ throw new ParseError({
192
+ message: 'Invalid config section: expected an object of option defaults',
193
+ })
194
+ if (!schema) {
195
+ const [first] = Object.keys(defaults)
196
+ if (first) throw new ParseError({ message: `Unknown config option: ${first}` })
197
+ return {}
198
+ }
199
+
200
+ const normalized: Record<string, unknown> = {}
201
+ for (const [rawName, value] of Object.entries(defaults)) {
202
+ const name = normalizeOptionName(rawName, optionNames)
203
+ if (!name) throw new ParseError({ message: `Unknown config option: ${rawName}` })
204
+ normalized[name] = value
205
+ }
206
+ return normalized
207
+ }
208
+
158
209
  /** Unwraps ZodDefault/ZodOptional to get the inner type. */
159
210
  function unwrap(schema: z.ZodType): z.ZodType {
160
211
  let s = schema as any
package/src/bin.ts CHANGED
@@ -1,8 +1,11 @@
1
1
  #!/usr/bin/env node
2
+ import fs from 'node:fs/promises'
2
3
  import path from 'node:path'
3
4
  import { z } from 'zod'
4
5
 
5
6
  import * as Cli from './Cli.js'
7
+ import * as ConfigSchema from './internal/configSchema.js'
8
+ import { importCli } from './internal/utils.js'
6
9
  import * as Typegen from './Typegen.js'
7
10
 
8
11
  const cli = Cli.create('incur', {
@@ -15,6 +18,10 @@ const cli = Cli.create('incur', {
15
18
  }).command('gen', {
16
19
  description: 'Generate type definitions for development.',
17
20
  options: z.object({
21
+ configSchema: z
22
+ .boolean()
23
+ .optional()
24
+ .describe('Generate config JSON Schema (auto-detected by default)'),
18
25
  dir: z.string().optional().describe('Project root directory'),
19
26
  entry: z.string().optional().describe('Entrypoint path (absolute)'),
20
27
  output: z.string().optional().describe('Output path (absolute)'),
@@ -23,8 +30,20 @@ const cli = Cli.create('incur', {
23
30
  const dir = c.options.dir ?? '.'
24
31
  const entry = c.options.entry ?? dir
25
32
  const output = c.options.output ?? path.join(dir, 'incur.generated.ts')
26
- await Typegen.generate(entry, output)
27
- return { dir, entry, output }
33
+
34
+ const cli = await importCli(entry)
35
+ await fs.writeFile(output, Typegen.fromCli(cli))
36
+
37
+ const result: Record<string, unknown> = { dir, entry, output }
38
+
39
+ const configSchema = c.options.configSchema ?? ConfigSchema.hasConfig(cli)
40
+ if (configSchema) {
41
+ const schemaOutput = path.join(path.dirname(output), 'config.schema.json')
42
+ await fs.writeFile(schemaOutput, JSON.stringify(ConfigSchema.fromCli(cli), null, 2) + '\n')
43
+ result.configSchema = schemaOutput
44
+ }
45
+
46
+ return result
28
47
  },
29
48
  })
30
49
 
package/src/e2e.test.ts CHANGED
@@ -2204,7 +2204,7 @@ describe('fetch gateway', () => {
2204
2204
  })
2205
2205
 
2206
2206
  test('query params from --key value', async () => {
2207
- const { output } = await serve(createApp(), ['api', 'users', '--limit', '5'])
2207
+ await serve(createApp(), ['api', 'users', '--limit', '5'])
2208
2208
  const { output: jsonOut } = await serve(createApp(), [
2209
2209
  'api',
2210
2210
  'users',
@@ -71,6 +71,7 @@ export async function execute(command: any, options: execute.Options): Promise<e
71
71
  const parsed = Parser.parse(argv, {
72
72
  alias: command.alias as Record<string, string> | undefined,
73
73
  args: command.args,
74
+ defaults: options.defaults,
74
75
  options: command.options,
75
76
  })
76
77
  args = parsed.args
@@ -269,6 +270,8 @@ export declare namespace execute {
269
270
  agent: boolean
270
271
  /** Raw positional tokens (already separated from flags). For HTTP/MCP, pass `[]`. */
271
272
  argv: string[]
273
+ /** Default option values from config file. */
274
+ defaults?: Record<string, unknown> | undefined
272
275
  /** CLI-level env schema. */
273
276
  env?: z.ZodObject<any> | undefined
274
277
  /** Source for environment variables. Defaults to `process.env`. */
@@ -0,0 +1,193 @@
1
+ import { Cli, z } from 'incur'
2
+
3
+ import * as ConfigSchema from './configSchema.js'
4
+
5
+ describe('fromCli', () => {
6
+ test('generates schema for root options and leaf commands', () => {
7
+ const cli = Cli.create('test', {
8
+ options: z.object({
9
+ verbose: z.boolean().default(false),
10
+ }),
11
+ })
12
+ cli.command('echo', {
13
+ options: z.object({
14
+ prefix: z.string().default(''),
15
+ upper: z.boolean().default(false),
16
+ }),
17
+ run: (c) => c.options,
18
+ })
19
+
20
+ const schema = ConfigSchema.fromCli(cli)
21
+ expect(schema).toMatchInlineSnapshot(`
22
+ {
23
+ "additionalProperties": false,
24
+ "properties": {
25
+ "$schema": {
26
+ "type": "string",
27
+ },
28
+ "commands": {
29
+ "additionalProperties": false,
30
+ "properties": {
31
+ "echo": {
32
+ "additionalProperties": false,
33
+ "properties": {
34
+ "options": {
35
+ "additionalProperties": false,
36
+ "properties": {
37
+ "prefix": {
38
+ "default": "",
39
+ "type": "string",
40
+ },
41
+ "upper": {
42
+ "default": false,
43
+ "type": "boolean",
44
+ },
45
+ },
46
+ "type": "object",
47
+ },
48
+ },
49
+ "type": "object",
50
+ },
51
+ },
52
+ "type": "object",
53
+ },
54
+ "options": {
55
+ "additionalProperties": false,
56
+ "properties": {
57
+ "verbose": {
58
+ "default": false,
59
+ "type": "boolean",
60
+ },
61
+ },
62
+ "type": "object",
63
+ },
64
+ },
65
+ "type": "object",
66
+ }
67
+ `)
68
+ })
69
+
70
+ test('generates schema for nested command groups', () => {
71
+ const project = Cli.create('project')
72
+ project.command('list', {
73
+ options: z.object({
74
+ limit: z.number().default(10),
75
+ label: z.array(z.string()).default([]),
76
+ }),
77
+ run: (c) => c.options,
78
+ })
79
+
80
+ const cli = Cli.create('test')
81
+ cli.command(project)
82
+
83
+ const schema = ConfigSchema.fromCli(cli)
84
+ expect(schema).toMatchInlineSnapshot(`
85
+ {
86
+ "additionalProperties": false,
87
+ "properties": {
88
+ "$schema": {
89
+ "type": "string",
90
+ },
91
+ "commands": {
92
+ "additionalProperties": false,
93
+ "properties": {
94
+ "project": {
95
+ "additionalProperties": false,
96
+ "properties": {
97
+ "commands": {
98
+ "additionalProperties": false,
99
+ "properties": {
100
+ "list": {
101
+ "additionalProperties": false,
102
+ "properties": {
103
+ "options": {
104
+ "additionalProperties": false,
105
+ "properties": {
106
+ "label": {
107
+ "default": [],
108
+ "items": {
109
+ "type": "string",
110
+ },
111
+ "type": "array",
112
+ },
113
+ "limit": {
114
+ "default": 10,
115
+ "type": "number",
116
+ },
117
+ },
118
+ "type": "object",
119
+ },
120
+ },
121
+ "type": "object",
122
+ },
123
+ },
124
+ "type": "object",
125
+ },
126
+ },
127
+ "type": "object",
128
+ },
129
+ },
130
+ "type": "object",
131
+ },
132
+ },
133
+ "type": "object",
134
+ }
135
+ `)
136
+ })
137
+
138
+ test('returns schema with only $schema for cli with no commands', () => {
139
+ const cli = Cli.create('test')
140
+ const schema = ConfigSchema.fromCli(cli)
141
+ expect(schema).toEqual({
142
+ type: 'object',
143
+ additionalProperties: false,
144
+ properties: { $schema: { type: 'string' } },
145
+ })
146
+ })
147
+
148
+ test('skips fetch gateway commands', () => {
149
+ const cli = Cli.create('test')
150
+ cli.command('echo', {
151
+ options: z.object({ prefix: z.string().default('') }),
152
+ run: (c) => c.options,
153
+ })
154
+ cli.command('api', {
155
+ description: 'API gateway',
156
+ fetch: () => new Response('ok'),
157
+ })
158
+
159
+ const schema = ConfigSchema.fromCli(cli)
160
+ const commandKeys = Object.keys((schema as any).properties.commands.properties)
161
+ expect(commandKeys).toEqual(['echo'])
162
+ })
163
+
164
+ test('includes commands without options as empty objects', () => {
165
+ const cli = Cli.create('test')
166
+ cli.command('ping', {
167
+ run: () => 'pong',
168
+ })
169
+
170
+ const schema = ConfigSchema.fromCli(cli)
171
+ expect(schema).toMatchInlineSnapshot(`
172
+ {
173
+ "additionalProperties": false,
174
+ "properties": {
175
+ "$schema": {
176
+ "type": "string",
177
+ },
178
+ "commands": {
179
+ "additionalProperties": false,
180
+ "properties": {
181
+ "ping": {
182
+ "additionalProperties": false,
183
+ "type": "object",
184
+ },
185
+ },
186
+ "type": "object",
187
+ },
188
+ },
189
+ "type": "object",
190
+ }
191
+ `)
192
+ })
193
+ })
@@ -0,0 +1,66 @@
1
+ import fs from 'node:fs/promises'
2
+ import type { z } from 'zod'
3
+
4
+ import * as Cli from '../Cli.js'
5
+ import * as Schema from '../Schema.js'
6
+ import { importCli } from './utils.js'
7
+
8
+ /** Returns `true` if the CLI has `config` enabled on `Cli.create()`. */
9
+ export function hasConfig(cli: Cli.Cli): boolean {
10
+ return Cli.toConfigEnabled.get(cli) === true
11
+ }
12
+
13
+ /** Imports a CLI from `input` (must `export default` a `Cli`), generates the JSON Schema, and writes it to `output`. */
14
+ export async function generate(input: string, output: string): Promise<void> {
15
+ const cli = await importCli(input)
16
+ await fs.writeFile(output, JSON.stringify(fromCli(cli), null, 2) + '\n')
17
+ }
18
+
19
+ /** Generates a JSON Schema describing the config file structure for a CLI. */
20
+ export function fromCli(cli: Cli.Cli): Record<string, unknown> {
21
+ const commands = Cli.toCommands.get(cli)
22
+ if (!commands) return { type: 'object' }
23
+
24
+ const rootOptions = Cli.toRootOptions.get(cli)
25
+ const node = buildNode(commands, rootOptions)
26
+ const properties = (node.properties ?? {}) as Record<string, unknown>
27
+ properties.$schema = { type: 'string' }
28
+ node.properties = properties
29
+ return node
30
+ }
31
+
32
+ /** Builds a JSON Schema node for a command level. */
33
+ function buildNode(
34
+ commands: Map<string, any>,
35
+ options?: z.ZodObject<any>,
36
+ ): Record<string, unknown> {
37
+ const properties: Record<string, unknown> = {}
38
+
39
+ // Add `options` property from the options schema
40
+ if (options) {
41
+ const optSchema = Schema.toJsonSchema(options)
42
+ const props = optSchema.properties as Record<string, unknown> | undefined
43
+ if (props && Object.keys(props).length > 0)
44
+ properties.options = { type: 'object', additionalProperties: false, properties: props }
45
+ }
46
+
47
+ // Add `commands` property with subcommand namespaces
48
+ const commandProps: Record<string, unknown> = {}
49
+ for (const [name, entry] of commands) {
50
+ if ('_group' in entry && entry._group) {
51
+ commandProps[name] = buildNode(entry.commands, undefined)
52
+ } else if (!('_fetch' in entry)) {
53
+ const cmd = entry as { options?: z.ZodObject<any> }
54
+ commandProps[name] = buildNode(new Map(), cmd.options)
55
+ }
56
+ }
57
+ if (Object.keys(commandProps).length > 0)
58
+ properties.commands = { type: 'object', additionalProperties: false, properties: commandProps }
59
+
60
+ const node: Record<string, unknown> = {
61
+ type: 'object',
62
+ additionalProperties: false,
63
+ }
64
+ if (Object.keys(properties).length > 0) node.properties = properties
65
+ return node
66
+ }
@@ -0,0 +1,9 @@
1
+ /** Checks whether a value is a plain object record. */
2
+ export function isRecord(value: unknown): value is Record<string, unknown> {
3
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
4
+ }
5
+
6
+ /** Converts a camelCase string to kebab-case. */
7
+ export function toKebab(value: string): string {
8
+ return value.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)
9
+ }