@kjanat/dreamcli 2.5.0 → 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 (202) hide show
  1. package/CHANGELOG.md +344 -1
  2. package/README.md +9 -2
  3. package/dist/core/cli/dispatch.d.mts +6 -5
  4. package/dist/core/cli/dispatch.mjs +205 -1
  5. package/dist/core/cli/help-links.d.mts +0 -1
  6. package/dist/core/cli/help-links.mjs +41 -1
  7. package/dist/core/cli/index.d.mts +185 -19
  8. package/dist/core/cli/index.mjs +945 -1
  9. package/dist/core/cli/planner.d.mts +32 -6
  10. package/dist/core/cli/planner.mjs +300 -1
  11. package/dist/core/cli/plugin.d.mts +1 -1
  12. package/dist/core/cli/plugin.mjs +41 -1
  13. package/dist/core/cli/propagate.d.mts +1 -1
  14. package/dist/core/cli/propagate.mjs +57 -1
  15. package/dist/core/cli/root-help.d.mts +18 -3
  16. package/dist/core/cli/root-help.mjs +226 -6
  17. package/dist/core/cli/root-surface.d.mts +30 -4
  18. package/dist/core/cli/root-surface.mjs +28 -1
  19. package/dist/core/cli/runtime-preflight.d.mts +30 -3
  20. package/dist/core/cli/runtime-preflight.mjs +169 -1
  21. package/dist/core/completion/index.d.mts +32 -2
  22. package/dist/core/completion/index.mjs +90 -1
  23. package/dist/core/completion/shells/bash.d.mts +0 -1
  24. package/dist/core/completion/shells/bash.mjs +308 -3
  25. package/dist/core/completion/shells/fish.d.mts +0 -1
  26. package/dist/core/completion/shells/fish.mjs +162 -2
  27. package/dist/core/completion/shells/powershell.d.mts +0 -1
  28. package/dist/core/completion/shells/powershell.mjs +358 -2
  29. package/dist/core/completion/shells/shared.d.mts +23 -2
  30. package/dist/core/completion/shells/shared.mjs +176 -1
  31. package/dist/core/completion/shells/zsh.d.mts +0 -1
  32. package/dist/core/completion/shells/zsh.mjs +251 -2
  33. package/dist/core/config/index.d.mts +2 -3
  34. package/dist/core/config/index.mjs +246 -1
  35. package/dist/core/config/package-json.d.mts +27 -4
  36. package/dist/core/config/package-json.mjs +386 -3
  37. package/dist/core/errors/index.d.mts +3 -3
  38. package/dist/core/errors/index.mjs +87 -1
  39. package/dist/core/execution/index.d.mts +0 -1
  40. package/dist/core/execution/index.mjs +201 -1
  41. package/dist/core/help/ansi.d.mts +11 -5
  42. package/dist/core/help/ansi.mjs +121 -2
  43. package/dist/core/help/index.d.mts +65 -2
  44. package/dist/core/help/index.mjs +341 -7
  45. package/dist/core/help/theme.d.mts +68 -0
  46. package/dist/core/help/theme.mjs +46 -0
  47. package/dist/core/json-schema/index.d.mts +15 -2
  48. package/dist/core/json-schema/index.mjs +536 -12
  49. package/dist/core/json-schema/meta-descriptions.generated.d.mts +22 -5
  50. package/dist/core/json-schema/meta-descriptions.generated.mjs +102 -28
  51. package/dist/core/output/activity.d.mts +0 -1
  52. package/dist/core/output/activity.mjs +452 -1
  53. package/dist/core/output/bind.mjs +56 -1
  54. package/dist/core/output/contracts.d.mts +4 -5
  55. package/dist/core/output/contracts.mjs +57 -1
  56. package/dist/core/output/display-value.mjs +32 -1
  57. package/dist/core/output/index.d.mts +21 -1
  58. package/dist/core/output/index.mjs +442 -2
  59. package/dist/core/output/renderers.d.mts +0 -1
  60. package/dist/core/output/renderers.mjs +46 -1
  61. package/dist/core/output/writer.mjs +12 -1
  62. package/dist/core/parse/index.d.mts +54 -7
  63. package/dist/core/parse/index.mjs +727 -1
  64. package/dist/core/prompt/index.d.mts +12 -4
  65. package/dist/core/prompt/index.mjs +348 -6
  66. package/dist/core/resolve/args.d.mts +1 -1
  67. package/dist/core/resolve/args.mjs +105 -1
  68. package/dist/core/resolve/coerce.d.mts +1 -1
  69. package/dist/core/resolve/coerce.mjs +336 -1
  70. package/dist/core/resolve/config.mjs +19 -1
  71. package/dist/core/resolve/contracts.d.mts +9 -4
  72. package/dist/core/resolve/errors.d.mts +0 -1
  73. package/dist/core/resolve/errors.mjs +140 -2
  74. package/dist/core/resolve/flags.d.mts +7 -2
  75. package/dist/core/resolve/flags.mjs +251 -1
  76. package/dist/core/resolve/index.d.mts +2 -2
  77. package/dist/core/resolve/index.mjs +85 -1
  78. package/dist/core/resolve/property.d.mts +6 -2
  79. package/dist/core/resolve/property.mjs +53 -1
  80. package/dist/core/schema/activity.d.mts +31 -11
  81. package/dist/core/schema/arg.d.mts +92 -13
  82. package/dist/core/schema/arg.mjs +463 -1
  83. package/dist/core/schema/command.d.mts +29 -7
  84. package/dist/core/schema/command.mjs +726 -1
  85. package/dist/core/schema/flag.d.mts +577 -21
  86. package/dist/core/schema/flag.mjs +705 -1
  87. package/dist/core/schema/index.d.mts +5 -2
  88. package/dist/core/schema/middleware.d.mts +4 -3
  89. package/dist/core/schema/middleware.mjs +41 -1
  90. package/dist/core/schema/number-constraints.d.mts +96 -0
  91. package/dist/core/schema/number-constraints.mjs +60 -0
  92. package/dist/core/schema/prompt.d.mts +21 -3
  93. package/dist/core/schema/run.d.mts +24 -5
  94. package/dist/core/schema/string-constraints.d.mts +97 -0
  95. package/dist/core/schema/string-constraints.mjs +69 -0
  96. package/dist/core/schema/value-parsers.d.mts +78 -0
  97. package/dist/core/schema/value-parsers.mjs +142 -0
  98. package/dist/core/schema-dsl/runtime.mjs +271 -2
  99. package/dist/core/schema-dsl/to-json-schema.d.mts +0 -1
  100. package/dist/core/schema-dsl/to-json-schema.mjs +74 -1
  101. package/dist/core/testkit/index.d.mts +9 -36
  102. package/dist/core/testkit/index.mjs +83 -1
  103. package/dist/index.d.mts +12 -6
  104. package/dist/index.mjs +22 -1
  105. package/dist/runtime/adapter.d.mts +38 -2
  106. package/dist/runtime/adapter.mjs +87 -1
  107. package/dist/runtime/auto.d.mts +2 -3
  108. package/dist/runtime/auto.mjs +45 -1
  109. package/dist/runtime/deno.d.mts +24 -5
  110. package/dist/runtime/deno.mjs +262 -2
  111. package/dist/runtime/detect.mjs +45 -1
  112. package/dist/runtime/index.d.mts +3 -4
  113. package/dist/runtime/node.d.mts +8 -2
  114. package/dist/runtime/node.mjs +220 -2
  115. package/dist/runtime/paths.mjs +48 -1
  116. package/dist/runtime.d.mts +4 -4
  117. package/dist/runtime.mjs +6 -1
  118. package/dist/strings.mjs +22 -1
  119. package/dist/testkit.d.mts +1 -0
  120. package/dist/testkit.mjs +5 -1
  121. package/dist/version.d.mts +7 -3
  122. package/dist/version.mjs +7 -1
  123. package/dreamcli.schema.json +36 -7
  124. package/examples/basic.ts +5 -1
  125. package/examples/gh/package.json +2 -7
  126. package/examples/pwsh-demo/package.json +1 -7
  127. package/examples/pwsh-demo/src/main.test.ts +1 -4
  128. package/examples/pwsh-demo/src/main.ts +14 -4
  129. package/examples/transport-launcher.ts +85 -0
  130. package/package.json +43 -49
  131. package/dist/runtime/bun.d.mts +0 -28
  132. package/dist/runtime/bun.mjs +0 -1
  133. package/dist/runtime/support.d.mts +0 -42
  134. package/dist/runtime/support.mjs +0 -1
  135. package/src/core/cli/dispatch.ts +0 -349
  136. package/src/core/cli/help-links.ts +0 -82
  137. package/src/core/cli/index.ts +0 -1413
  138. package/src/core/cli/planner.ts +0 -487
  139. package/src/core/cli/plugin.ts +0 -117
  140. package/src/core/cli/propagate.ts +0 -97
  141. package/src/core/cli/root-help.ts +0 -252
  142. package/src/core/cli/root-surface.ts +0 -74
  143. package/src/core/cli/runtime-preflight.ts +0 -438
  144. package/src/core/completion/index.ts +0 -88
  145. package/src/core/completion/shells/bash.ts +0 -459
  146. package/src/core/completion/shells/fish.ts +0 -259
  147. package/src/core/completion/shells/powershell.ts +0 -439
  148. package/src/core/completion/shells/shared.ts +0 -283
  149. package/src/core/completion/shells/zsh.ts +0 -381
  150. package/src/core/config/index.ts +0 -417
  151. package/src/core/config/package-json.ts +0 -560
  152. package/src/core/errors/index.ts +0 -193
  153. package/src/core/execution/index.ts +0 -268
  154. package/src/core/help/ansi.ts +0 -144
  155. package/src/core/help/index.ts +0 -516
  156. package/src/core/json-schema/index.ts +0 -891
  157. package/src/core/json-schema/meta-descriptions.generated.ts +0 -185
  158. package/src/core/output/activity.ts +0 -575
  159. package/src/core/output/bind.ts +0 -59
  160. package/src/core/output/contracts.ts +0 -194
  161. package/src/core/output/display-value.ts +0 -48
  162. package/src/core/output/index.ts +0 -704
  163. package/src/core/output/renderers.ts +0 -125
  164. package/src/core/output/writer.ts +0 -46
  165. package/src/core/parse/index.ts +0 -681
  166. package/src/core/prompt/index.ts +0 -583
  167. package/src/core/resolve/args.ts +0 -144
  168. package/src/core/resolve/coerce.ts +0 -432
  169. package/src/core/resolve/config.ts +0 -26
  170. package/src/core/resolve/contracts.ts +0 -135
  171. package/src/core/resolve/errors.ts +0 -227
  172. package/src/core/resolve/flags.ts +0 -255
  173. package/src/core/resolve/index.ts +0 -108
  174. package/src/core/resolve/property.ts +0 -99
  175. package/src/core/schema/activity.ts +0 -240
  176. package/src/core/schema/arg.ts +0 -719
  177. package/src/core/schema/command.ts +0 -1498
  178. package/src/core/schema/flag.ts +0 -801
  179. package/src/core/schema/index.ts +0 -91
  180. package/src/core/schema/middleware.ts +0 -171
  181. package/src/core/schema/prompt.ts +0 -156
  182. package/src/core/schema/run.ts +0 -198
  183. package/src/core/schema-dsl/index.ts +0 -109
  184. package/src/core/schema-dsl/parse.ts +0 -262
  185. package/src/core/schema-dsl/runtime.ts +0 -609
  186. package/src/core/schema-dsl/to-json-schema.ts +0 -102
  187. package/src/core/testkit/index.ts +0 -123
  188. package/src/index.ts +0 -179
  189. package/src/runtime/adapter.ts +0 -303
  190. package/src/runtime/auto.ts +0 -110
  191. package/src/runtime/bun.ts +0 -55
  192. package/src/runtime/deno.ts +0 -369
  193. package/src/runtime/detect.ts +0 -105
  194. package/src/runtime/index.ts +0 -21
  195. package/src/runtime/node-builtins.d.ts +0 -27
  196. package/src/runtime/node.ts +0 -300
  197. package/src/runtime/paths.ts +0 -64
  198. package/src/runtime/support.ts +0 -135
  199. package/src/runtime.ts +0 -31
  200. package/src/strings.ts +0 -34
  201. package/src/testkit.ts +0 -25
  202. package/src/version.ts +0 -20
@@ -1,609 +0,0 @@
1
- /**
2
- * Runtime schema string parser.
3
- *
4
- * Parses the same string literals as the compile-time {@link Parse} type,
5
- * producing a runtime AST ({@link SchemaNode}) that mirrors the inferred
6
- * TypeScript type. The AST can drive JSON Schema generation, validation,
7
- * and introspection — all from the same source string.
8
- *
9
- * Grammar (matches the type-level parser in `parse.ts`):
10
- * ```
11
- * value = union
12
- * union = postfix ('|' postfix)*
13
- * postfix = primary ('[]')*
14
- * primary = object | record | ref | literal | IDENT
15
- * object = '{' properties '}'
16
- * properties = (property ';')* property? ';'?
17
- * property = IDENT '?'? ':' value
18
- * record = 'Record' '<' value ',' value '>'
19
- * ref = '@' IDENT
20
- * literal = "'" CHARS "'"
21
- * ```
22
- *
23
- * @module dreamcli/core/schema-dsl/runtime
24
- */
25
-
26
- // === AST node types (discriminated union) ===
27
-
28
- /** Discriminated union of all schema AST nodes. */
29
- type SchemaNode =
30
- | StringNode
31
- | NumberNode
32
- | IntegerNode
33
- | BooleanNode
34
- | LiteralTrueNode
35
- | LiteralFalseNode
36
- | LiteralNullNode
37
- | LiteralStringNode
38
- | LiteralUndefinedNode
39
- | UnknownNode
40
- | NeverNode
41
- | ArrayNode
42
- | ObjectNode
43
- | UnionNode
44
- | RefNode
45
- | RecordNode;
46
-
47
- /** String primitive. */
48
- interface StringNode {
49
- /** Identifies this node as a string type. */
50
- readonly kind: 'string';
51
- }
52
-
53
- /** Number primitive. */
54
- interface NumberNode {
55
- /** Identifies this node as a number type. */
56
- readonly kind: 'number';
57
- }
58
-
59
- /** Integer primitive (maps to `number` in TS, `integer` in JSON Schema). */
60
- interface IntegerNode {
61
- /** Identifies this node as an integer type. */
62
- readonly kind: 'integer';
63
- }
64
-
65
- /** Boolean primitive. */
66
- interface BooleanNode {
67
- /** Identifies this node as a boolean type. */
68
- readonly kind: 'boolean';
69
- }
70
-
71
- /** Literal `true`. */
72
- interface LiteralTrueNode {
73
- /** Identifies this node as the literal `true` value. */
74
- readonly kind: 'true';
75
- }
76
-
77
- /** Literal `false`. */
78
- interface LiteralFalseNode {
79
- /** Identifies this node as the literal `false` value. */
80
- readonly kind: 'false';
81
- }
82
-
83
- /** Literal `null`. */
84
- interface LiteralNullNode {
85
- /** Identifies this node as the literal `null` value. */
86
- readonly kind: 'null';
87
- }
88
-
89
- /** String literal value (e.g. `'confirm'`). */
90
- interface LiteralStringNode {
91
- /** Identifies this node as a string literal. */
92
- readonly kind: 'literal';
93
- /** The exact string value this literal represents. */
94
- readonly value: string;
95
- }
96
-
97
- /** Literal `undefined`. */
98
- interface LiteralUndefinedNode {
99
- /** Identifies this node as the literal `undefined` value. */
100
- readonly kind: 'undefined';
101
- }
102
-
103
- /** The `unknown` top type. */
104
- interface UnknownNode {
105
- /** Identifies this node as the `unknown` top type. */
106
- readonly kind: 'unknown';
107
- }
108
-
109
- /** The `never` bottom type. */
110
- interface NeverNode {
111
- /** Identifies this node as the `never` bottom type. */
112
- readonly kind: 'never';
113
- }
114
-
115
- /** Array of element type. */
116
- interface ArrayNode {
117
- /** Identifies this node as an array type. */
118
- readonly kind: 'array';
119
- /** The type of each array element. */
120
- readonly element: SchemaNode;
121
- }
122
-
123
- /** Object with named properties. */
124
- interface ObjectNode {
125
- /** Identifies this node as an object type. */
126
- readonly kind: 'object';
127
- /** Named properties keyed by field name. */
128
- readonly properties: Readonly<Record<string, PropertyNode>>;
129
- }
130
-
131
- /** Union of two or more member types. */
132
- interface UnionNode {
133
- /** Identifies this node as a union type. */
134
- readonly kind: 'union';
135
- /** The constituent types of this union. */
136
- readonly members: readonly SchemaNode[];
137
- }
138
-
139
- /** Reference to a named definition (e.g. `@flag` → `$ref: '#/$defs/flag'`). */
140
- interface RefNode {
141
- /** Identifies this node as a `$ref` reference. */
142
- readonly kind: 'ref';
143
- /** Name of the referenced definition (without the `@` prefix). */
144
- readonly target: string;
145
- }
146
-
147
- /** Record/dictionary type (e.g. `Record<string, @flag>`). */
148
- interface RecordNode {
149
- /** Identifies this node as a record/dictionary type. */
150
- readonly kind: 'record';
151
- /** The type of each record value (keys are always strings). */
152
- readonly value: SchemaNode;
153
- }
154
-
155
- /** A named property with optionality flag. */
156
- interface PropertyNode {
157
- /** Whether the property is optional (`?` suffix in the schema DSL). */
158
- readonly optional: boolean;
159
- /** The property's value type. */
160
- readonly schema: SchemaNode;
161
- }
162
-
163
- // === Tokenizer ===
164
-
165
- /** Token kind discriminator. */
166
- type TokenKind =
167
- | 'ident'
168
- | 'string_literal'
169
- | 'ref'
170
- | 'lbrace'
171
- | 'rbrace'
172
- | 'lbracket'
173
- | 'rbracket'
174
- | 'langle'
175
- | 'rangle'
176
- | 'comma'
177
- | 'colon'
178
- | 'semicolon'
179
- | 'question'
180
- | 'pipe';
181
-
182
- /** A single token from the schema string. */
183
- interface Token {
184
- readonly kind: TokenKind;
185
- readonly value: string;
186
- }
187
-
188
- /** Map single characters to their token kinds. */
189
- const SINGLE_CHAR_TOKENS: Readonly<Record<string, TokenKind>> = {
190
- '{': 'lbrace',
191
- '}': 'rbrace',
192
- '[': 'lbracket',
193
- ']': 'rbracket',
194
- '<': 'langle',
195
- '>': 'rangle',
196
- ',': 'comma',
197
- ':': 'colon',
198
- ';': 'semicolon',
199
- '?': 'question',
200
- '|': 'pipe',
201
- };
202
-
203
- /** Whitespace characters to skip. */
204
- function isWhitespace(c: string): boolean {
205
- return c === ' ' || c === '\n' || c === '\t' || c === '\r';
206
- }
207
-
208
- /** Identifier-valid characters (a-z, A-Z, 0-9, _, $). */
209
- function isIdentChar(c: string): boolean {
210
- return (
211
- (c >= 'a' && c <= 'z') ||
212
- (c >= 'A' && c <= 'Z') ||
213
- (c >= '0' && c <= '9') ||
214
- c === '_' ||
215
- c === '$'
216
- );
217
- }
218
-
219
- /** Identifier start characters (a-z, A-Z, _, $). */
220
- function isIdentStart(c: string): boolean {
221
- return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c === '_' || c === '$';
222
- }
223
-
224
- /**
225
- * Tokenize a schema source string.
226
- *
227
- * Produces a flat array of tokens: identifiers (`string`, `number`, etc.),
228
- * punctuation (`{`, `}`, `[`, `]`, `:`, `;`, `?`, `|`), and skips
229
- * whitespace. Throws on unrecognized characters.
230
- */
231
- function tokenize(source: string): Token[] {
232
- const tokens: Token[] = [];
233
- let i = 0;
234
-
235
- while (i < source.length) {
236
- const c = source[i] ?? '';
237
-
238
- if (isWhitespace(c)) {
239
- i++;
240
- continue;
241
- }
242
-
243
- const singleKind = SINGLE_CHAR_TOKENS[c];
244
- if (singleKind !== undefined) {
245
- tokens.push({ kind: singleKind, value: c });
246
- i++;
247
- continue;
248
- }
249
-
250
- // String literal: 'foo'
251
- if (c === "'") {
252
- let lit = '';
253
- i++; // skip opening quote
254
- while (i < source.length && source[i] !== "'") {
255
- lit += source[i];
256
- i++;
257
- }
258
- if (i >= source.length) throw new SyntaxError('Unterminated string literal');
259
- i++; // skip closing quote
260
- tokens.push({ kind: 'string_literal', value: lit });
261
- continue;
262
- }
263
-
264
- // Reference: @name
265
- if (c === '@') {
266
- i++; // skip @
267
- let ref = '';
268
- while (i < source.length) {
269
- const ch = source[i] ?? '';
270
- if (!isIdentChar(ch)) break;
271
- ref += ch;
272
- i++;
273
- }
274
- if (ref.length === 0)
275
- throw new SyntaxError(`Expected identifier after '@' at position ${String(i)}`);
276
- tokens.push({ kind: 'ref', value: ref });
277
- continue;
278
- }
279
-
280
- if (isIdentStart(c)) {
281
- let ident = '';
282
- while (i < source.length) {
283
- const ch = source[i] ?? '';
284
- if (!isIdentChar(ch)) break;
285
- ident += ch;
286
- i++;
287
- }
288
- tokens.push({ kind: 'ident', value: ident });
289
- continue;
290
- }
291
-
292
- throw new SyntaxError(`Unexpected character '${c}' at position ${String(i)}`);
293
- }
294
-
295
- return tokens;
296
- }
297
-
298
- // === Primitive lookup ===
299
-
300
- /** Primitive type names recognized by the parser. */
301
- const PRIMITIVES: ReadonlySet<string> = new Set([
302
- 'string',
303
- 'number',
304
- 'integer',
305
- 'boolean',
306
- 'true',
307
- 'false',
308
- 'null',
309
- 'undefined',
310
- 'unknown',
311
- 'never',
312
- ]);
313
-
314
- /** Map a primitive name to its AST node. */
315
- function primitiveNode(name: string): SchemaNode {
316
- switch (name) {
317
- case 'string':
318
- return { kind: 'string' };
319
- case 'number':
320
- return { kind: 'number' };
321
- case 'integer':
322
- return { kind: 'integer' };
323
- case 'boolean':
324
- return { kind: 'boolean' };
325
- case 'true':
326
- return { kind: 'true' };
327
- case 'false':
328
- return { kind: 'false' };
329
- case 'null':
330
- return { kind: 'null' };
331
- case 'undefined':
332
- return { kind: 'undefined' };
333
- case 'unknown':
334
- return { kind: 'unknown' };
335
- case 'never':
336
- return { kind: 'never' };
337
- default:
338
- throw new SyntaxError(`Unknown type '${name}'`);
339
- }
340
- }
341
-
342
- // === Recursive descent parser ===
343
-
344
- /**
345
- * Parse a token stream into a {@link SchemaNode} AST.
346
- *
347
- * Implements the grammar documented at the module level using standard
348
- * recursive descent. Each grammar rule maps to one `parse*` method.
349
- */
350
- class SchemaParser {
351
- private pos = 0;
352
-
353
- constructor(private readonly tokens: readonly Token[]) {}
354
-
355
- /** Parse the full token stream, asserting all tokens are consumed. */
356
- parseRoot(): SchemaNode {
357
- const result = this.parseValue();
358
- if (this.pos < this.tokens.length) {
359
- const leftover = this.peek();
360
- throw new SyntaxError(
361
- `Unexpected token '${leftover?.value ?? '?'}' at position ${String(this.pos)}`,
362
- );
363
- }
364
- return result;
365
- }
366
-
367
- // --- Grammar rules ---
368
-
369
- /** value = union */
370
- private parseValue(): SchemaNode {
371
- return this.parseUnion();
372
- }
373
-
374
- /** union = postfix ('|' postfix)* */
375
- private parseUnion(): SchemaNode {
376
- const first = this.parsePostfix();
377
-
378
- if (!this.check('pipe')) return first;
379
-
380
- const members: SchemaNode[] = [first];
381
- while (this.match('pipe')) {
382
- members.push(this.parsePostfix());
383
- }
384
- return { kind: 'union', members };
385
- }
386
-
387
- /** postfix = primary ('[]')* */
388
- private parsePostfix(): SchemaNode {
389
- let node = this.parsePrimary();
390
-
391
- while (this.check('lbracket') && this.checkAt(this.pos + 1, 'rbracket')) {
392
- this.advance(); // [
393
- this.advance(); // ]
394
- node = { kind: 'array', element: node };
395
- }
396
-
397
- return node;
398
- }
399
-
400
- /** primary = object | record | ref | literal | IDENT */
401
- private parsePrimary(): SchemaNode {
402
- if (this.check('lbrace')) {
403
- return this.parseObject();
404
- }
405
-
406
- if (this.check('string_literal')) {
407
- const token = this.advance();
408
- return { kind: 'literal', value: token.value };
409
- }
410
-
411
- if (this.check('ref')) {
412
- const token = this.advance();
413
- return { kind: 'ref', target: token.value };
414
- }
415
-
416
- const name = this.expectIdent();
417
-
418
- // Record<K, V>
419
- if (name === 'Record') {
420
- this.expect('langle');
421
- const keySchema = this.parseValue();
422
- if (keySchema.kind !== 'string') {
423
- throw new SyntaxError(
424
- "Record key type must be 'string' because JSON object keys are always strings",
425
- );
426
- }
427
- this.expect('comma');
428
- const valueSchema = this.parseValue();
429
- this.expect('rangle');
430
- return { kind: 'record', value: valueSchema };
431
- }
432
-
433
- if (!PRIMITIVES.has(name)) {
434
- throw new SyntaxError(`Unknown type '${name}' at position ${String(this.pos - 1)}`);
435
- }
436
- return primitiveNode(name);
437
- }
438
-
439
- /** object = '{' properties '}' */
440
- private parseObject(): ObjectNode {
441
- this.expect('lbrace');
442
-
443
- const properties: Record<string, PropertyNode> = {};
444
-
445
- while (!this.check('rbrace')) {
446
- const name = this.expectIdent();
447
- if (Object.hasOwn(properties, name)) {
448
- throw new SyntaxError(`Duplicate property '${name}' at position ${String(this.pos - 1)}`);
449
- }
450
- const optional = this.match('question');
451
- this.expect('colon');
452
- const schema = this.parseValue();
453
-
454
- properties[name] = { optional, schema };
455
-
456
- this.match('semicolon'); // optional trailing semicolon
457
- }
458
-
459
- this.expect('rbrace');
460
- return { kind: 'object', properties };
461
- }
462
-
463
- // --- Token helpers ---
464
-
465
- private peek(): Token | undefined {
466
- return this.tokens[this.pos];
467
- }
468
-
469
- private check(kind: TokenKind): boolean {
470
- return this.peek()?.kind === kind;
471
- }
472
-
473
- private checkAt(pos: number, kind: TokenKind): boolean {
474
- return this.tokens[pos]?.kind === kind;
475
- }
476
-
477
- private advance(): Token {
478
- const token = this.tokens[this.pos];
479
- if (token === undefined) {
480
- throw new SyntaxError('Unexpected end of input');
481
- }
482
- this.pos++;
483
- return token;
484
- }
485
-
486
- private match(kind: TokenKind): boolean {
487
- if (this.check(kind)) {
488
- this.pos++;
489
- return true;
490
- }
491
- return false;
492
- }
493
-
494
- private expect(kind: TokenKind): Token {
495
- if (!this.check(kind)) {
496
- const got = this.peek();
497
- throw new SyntaxError(
498
- got
499
- ? `Expected '${kind}' but got '${got.kind}' ('${got.value}') at position ${String(this.pos)}`
500
- : `Expected '${kind}' but reached end of input`,
501
- );
502
- }
503
- return this.advance();
504
- }
505
-
506
- private expectIdent(): string {
507
- return this.expect('ident').value;
508
- }
509
- }
510
-
511
- /**
512
- * Parse a schema source string into a runtime AST.
513
- *
514
- * @param source - Schema string (e.g. `"{ name: string; age: number }"`).
515
- * @returns The root {@link SchemaNode}.
516
- * @throws {@link SyntaxError} on malformed input.
517
- */
518
- function parseSchema(source: string): SchemaNode {
519
- const tokens = tokenize(source);
520
- return new SchemaParser(tokens).parseRoot();
521
- }
522
-
523
- // === Validation ===
524
-
525
- function isRecord(value: unknown): value is Readonly<Record<string, unknown>> {
526
- return typeof value === 'object' && value !== null && !Array.isArray(value);
527
- }
528
-
529
- /**
530
- * Validate that `input` conforms to the given AST node.
531
- *
532
- * @param node - The schema AST to validate against.
533
- * @param input - The value to check.
534
- * @returns `true` if the value matches the schema.
535
- */
536
- function validateNode(node: SchemaNode, input: unknown): boolean {
537
- switch (node.kind) {
538
- case 'string':
539
- return typeof input === 'string';
540
- case 'number':
541
- return typeof input === 'number';
542
- case 'integer':
543
- return typeof input === 'number' && Number.isInteger(input);
544
- case 'boolean':
545
- return typeof input === 'boolean';
546
- case 'true':
547
- return input === true;
548
- case 'false':
549
- return input === false;
550
- case 'null':
551
- return input === null;
552
- case 'literal':
553
- return input === node.value;
554
- case 'undefined':
555
- return input === undefined;
556
- case 'unknown':
557
- return true;
558
- case 'never':
559
- return false;
560
- case 'ref':
561
- return false; // fail closed until refs can be resolved against a definition map
562
- case 'array':
563
- return Array.isArray(input) && input.every((el) => validateNode(node.element, el));
564
- case 'object': {
565
- if (!isRecord(input)) return false;
566
- for (const key of Object.keys(input)) {
567
- if (!Object.hasOwn(node.properties, key)) return false;
568
- }
569
- for (const [key, prop] of Object.entries(node.properties)) {
570
- if (!Object.hasOwn(input, key)) {
571
- if (!prop.optional) return false;
572
- continue;
573
- }
574
- if (!validateNode(prop.schema, input[key])) return false;
575
- }
576
- return true;
577
- }
578
- case 'record': {
579
- if (!isRecord(input)) return false;
580
- return Object.values(input).every((v) => validateNode(node.value, v));
581
- }
582
- case 'union':
583
- return node.members.some((member) => validateNode(member, input));
584
- }
585
- }
586
-
587
- // === Exports ===
588
-
589
- export type {
590
- ArrayNode,
591
- BooleanNode,
592
- IntegerNode,
593
- LiteralFalseNode,
594
- LiteralNullNode,
595
- LiteralStringNode,
596
- LiteralTrueNode,
597
- LiteralUndefinedNode,
598
- NeverNode,
599
- NumberNode,
600
- ObjectNode,
601
- PropertyNode,
602
- RecordNode,
603
- RefNode,
604
- SchemaNode,
605
- StringNode,
606
- UnionNode,
607
- UnknownNode,
608
- };
609
- export { parseSchema, validateNode };
@@ -1,102 +0,0 @@
1
- /**
2
- * Convert schema DSL AST nodes to JSON Schema (draft 2020-12) fragments.
3
- *
4
- * This bridges the schema DSL and JSON Schema generation: define a shape
5
- * once as a DSL string, parse it to an AST, then convert to JSON Schema
6
- * properties — no manual override maps or probe fixtures needed.
7
- *
8
- * @module dreamcli/core/schema-dsl/to-json-schema
9
- */
10
-
11
- import type { SchemaNode } from './runtime.ts';
12
-
13
- /**
14
- * Convert a {@link SchemaNode} AST node to a JSON Schema fragment.
15
- *
16
- * Mapping:
17
- * - `string` → `{ type: 'string' }`
18
- * - `number` → `{ type: 'number' }`
19
- * - `integer` → `{ type: 'integer' }`
20
- * - `boolean` → `{ type: 'boolean' }`
21
- * - `true` → `{ const: true }`
22
- * - `false` → `{ const: false }`
23
- * - `null` → `{ type: 'null' }`
24
- * - `undefined` → throws (JSON Schema has no `undefined` type)
25
- * - `unknown` → `{}` (accepts any value)
26
- * - `never` → `{ not: {} }` (rejects all values)
27
- * - `'literal'` → `{ const: 'literal' }`
28
- * - `@ref` → `{ $ref: '#/$defs/ref' }`
29
- * - `T[]` → `{ type: 'array', items: convert(T) }`
30
- * - `Record<K,V>` → `{ type: 'object', additionalProperties: convert(V) }`
31
- * - `{...}` → `{ type: 'object', properties: ..., required: [...] }`
32
- * - `A | B` → `{ enum: [...] }` if all literals, else `{ oneOf: [...] }`
33
- *
34
- * @param node - The AST node to convert.
35
- * @returns A plain JSON Schema fragment.
36
- */
37
- function nodeToJsonSchema(node: SchemaNode): Record<string, unknown> {
38
- switch (node.kind) {
39
- case 'string':
40
- return { type: 'string' };
41
- case 'number':
42
- return { type: 'number' };
43
- case 'integer':
44
- return { type: 'integer' };
45
- case 'boolean':
46
- return { type: 'boolean' };
47
- case 'true':
48
- return { const: true };
49
- case 'false':
50
- return { const: false };
51
- case 'null':
52
- return { type: 'null' };
53
- case 'literal':
54
- return { const: node.value };
55
- case 'undefined':
56
- throw new Error(
57
- "Cannot convert 'undefined' type to JSON Schema; model optionality at the parent level",
58
- );
59
- case 'unknown':
60
- return {};
61
- case 'never':
62
- return { not: {} };
63
- case 'ref':
64
- return { $ref: `#/$defs/${node.target}` };
65
- case 'array':
66
- return { type: 'array', items: nodeToJsonSchema(node.element) };
67
- case 'record':
68
- return { type: 'object', additionalProperties: nodeToJsonSchema(node.value) };
69
- case 'object': {
70
- const properties: Record<string, Record<string, unknown>> = {};
71
- const required: string[] = [];
72
- for (const [key, prop] of Object.entries(node.properties)) {
73
- properties[key] = nodeToJsonSchema(prop.schema);
74
- if (!prop.optional) required.push(key);
75
- }
76
- const result: Record<string, unknown> = {
77
- type: 'object',
78
- additionalProperties: false,
79
- properties,
80
- };
81
- if (required.length > 0) result.required = required;
82
- return result;
83
- }
84
- case 'union': {
85
- // Union of all string literals → { enum: [...] }
86
- const literalValues: string[] = [];
87
- let allLiteral = true;
88
- for (const member of node.members) {
89
- if (member.kind === 'literal') {
90
- literalValues.push(member.value);
91
- } else {
92
- allLiteral = false;
93
- }
94
- }
95
- if (allLiteral) return { enum: literalValues };
96
- // Mixed union → oneOf
97
- return { oneOf: node.members.map(nodeToJsonSchema) };
98
- }
99
- }
100
- }
101
-
102
- export { nodeToJsonSchema };