@hydranium/cli 1.0.0-next.30 → 1.0.0-next.300

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 (222) hide show
  1. package/README.md +75 -204
  2. package/bin/hydranium-cli.js +13 -0
  3. package/heap-analysis/heap/core/load.mjs +2 -2
  4. package/lib/cli-version.js.map +1 -1
  5. package/lib/cli.js +7 -2
  6. package/lib/cli.js.map +1 -1
  7. package/lib/commands/analyze-heap-args.js.map +1 -1
  8. package/lib/commands/analyze-heap.d.ts +3 -0
  9. package/lib/commands/analyze-heap.d.ts.map +1 -1
  10. package/lib/commands/analyze-heap.js +2 -1
  11. package/lib/commands/analyze-heap.js.map +1 -1
  12. package/lib/commands/ast-ground-truth-args.d.ts +3 -2
  13. package/lib/commands/ast-ground-truth-args.d.ts.map +1 -1
  14. package/lib/commands/ast-ground-truth-args.js +11 -9
  15. package/lib/commands/ast-ground-truth-args.js.map +1 -1
  16. package/lib/commands/ast-ground-truth-driver.js +2 -1
  17. package/lib/commands/ast-ground-truth-driver.js.map +1 -1
  18. package/lib/commands/ast-ground-truth.js +1 -1
  19. package/lib/commands/ast-ground-truth.js.map +1 -1
  20. package/lib/commands/client-session.d.ts +17 -0
  21. package/lib/commands/client-session.d.ts.map +1 -0
  22. package/lib/commands/client-session.js +27 -0
  23. package/lib/commands/client-session.js.map +1 -0
  24. package/lib/commands/create-args.d.ts +17 -0
  25. package/lib/commands/create-args.d.ts.map +1 -0
  26. package/lib/commands/create-args.js +53 -0
  27. package/lib/commands/create-args.js.map +1 -0
  28. package/lib/commands/create.d.ts +38 -0
  29. package/lib/commands/create.d.ts.map +1 -0
  30. package/lib/commands/create.js +43 -0
  31. package/lib/commands/create.js.map +1 -0
  32. package/lib/commands/delete-args.d.ts +17 -0
  33. package/lib/commands/delete-args.d.ts.map +1 -0
  34. package/lib/commands/delete-args.js +49 -0
  35. package/lib/commands/delete-args.js.map +1 -0
  36. package/lib/commands/delete.d.ts +30 -0
  37. package/lib/commands/delete.d.ts.map +1 -0
  38. package/lib/commands/delete.js +32 -0
  39. package/lib/commands/delete.js.map +1 -0
  40. package/lib/commands/generate-ast-builder.d.ts +49 -0
  41. package/lib/commands/generate-ast-builder.d.ts.map +1 -0
  42. package/lib/commands/generate-ast-builder.js +200 -0
  43. package/lib/commands/generate-ast-builder.js.map +1 -0
  44. package/lib/commands/generate-transfer-model-args.d.ts.map +1 -1
  45. package/lib/commands/generate-transfer-model-args.js +11 -1
  46. package/lib/commands/generate-transfer-model-args.js.map +1 -1
  47. package/lib/commands/generate-transfer-model-config.d.ts.map +1 -1
  48. package/lib/commands/generate-transfer-model-config.js +6 -3
  49. package/lib/commands/generate-transfer-model-config.js.map +1 -1
  50. package/lib/commands/generate-transfer-model.d.ts +9 -0
  51. package/lib/commands/generate-transfer-model.d.ts.map +1 -1
  52. package/lib/commands/generate-transfer-model.js +18 -4
  53. package/lib/commands/generate-transfer-model.js.map +1 -1
  54. package/lib/commands/harness-args.d.ts +44 -42
  55. package/lib/commands/harness-args.d.ts.map +1 -1
  56. package/lib/commands/harness-args.js +109 -27
  57. package/lib/commands/harness-args.js.map +1 -1
  58. package/lib/commands/headless-harness.d.ts +37 -20
  59. package/lib/commands/headless-harness.d.ts.map +1 -1
  60. package/lib/commands/headless-harness.js +68 -17
  61. package/lib/commands/headless-harness.js.map +1 -1
  62. package/lib/commands/init-args.js +6 -6
  63. package/lib/commands/init-args.js.map +1 -1
  64. package/lib/commands/init-prompt.d.ts.map +1 -1
  65. package/lib/commands/init-templates.d.ts +8 -10
  66. package/lib/commands/init-templates.d.ts.map +1 -1
  67. package/lib/commands/init-templates.js +261 -167
  68. package/lib/commands/init-templates.js.map +1 -1
  69. package/lib/commands/init-wizard.js +4 -4
  70. package/lib/commands/init-wizard.js.map +1 -1
  71. package/lib/commands/init-workspace.d.ts +13 -3
  72. package/lib/commands/init-workspace.d.ts.map +1 -1
  73. package/lib/commands/init-workspace.js +21 -6
  74. package/lib/commands/init-workspace.js.map +1 -1
  75. package/lib/commands/init.d.ts +16 -10
  76. package/lib/commands/init.d.ts.map +1 -1
  77. package/lib/commands/init.js +17 -15
  78. package/lib/commands/init.js.map +1 -1
  79. package/lib/commands/lint-grammar-args.d.ts +3 -2
  80. package/lib/commands/lint-grammar-args.d.ts.map +1 -1
  81. package/lib/commands/lint-grammar-args.js +13 -10
  82. package/lib/commands/lint-grammar-args.js.map +1 -1
  83. package/lib/commands/lint-grammar-driver.js +2 -1
  84. package/lib/commands/lint-grammar-driver.js.map +1 -1
  85. package/lib/commands/lint-grammar-report.js.map +1 -1
  86. package/lib/commands/lint-grammar.js +1 -1
  87. package/lib/commands/lint-grammar.js.map +1 -1
  88. package/lib/commands/measure-memory-args.d.ts +3 -2
  89. package/lib/commands/measure-memory-args.d.ts.map +1 -1
  90. package/lib/commands/measure-memory-args.js +22 -11
  91. package/lib/commands/measure-memory-args.js.map +1 -1
  92. package/lib/commands/measure-memory-driver.js +5 -3
  93. package/lib/commands/measure-memory-driver.js.map +1 -1
  94. package/lib/commands/measure-memory.js +1 -1
  95. package/lib/commands/measure-memory.js.map +1 -1
  96. package/lib/commands/model-docs-args.d.ts +4 -3
  97. package/lib/commands/model-docs-args.d.ts.map +1 -1
  98. package/lib/commands/model-docs-args.js +12 -10
  99. package/lib/commands/model-docs-args.js.map +1 -1
  100. package/lib/commands/model-docs-driver.js +2 -1
  101. package/lib/commands/model-docs-driver.js.map +1 -1
  102. package/lib/commands/model-docs.js +1 -1
  103. package/lib/commands/model-docs.js.map +1 -1
  104. package/lib/commands/projects-args.d.ts.map +1 -1
  105. package/lib/commands/projects-args.js +5 -5
  106. package/lib/commands/projects-args.js.map +1 -1
  107. package/lib/commands/projects.d.ts +3 -4
  108. package/lib/commands/projects.d.ts.map +1 -1
  109. package/lib/commands/projects.js +2 -2
  110. package/lib/commands/projects.js.map +1 -1
  111. package/lib/commands/query-args.d.ts.map +1 -1
  112. package/lib/commands/query-args.js +5 -5
  113. package/lib/commands/query-args.js.map +1 -1
  114. package/lib/commands/query.d.ts +3 -4
  115. package/lib/commands/query.d.ts.map +1 -1
  116. package/lib/commands/query.js +2 -2
  117. package/lib/commands/query.js.map +1 -1
  118. package/lib/commands/reflect-args.d.ts +3 -2
  119. package/lib/commands/reflect-args.d.ts.map +1 -1
  120. package/lib/commands/reflect-args.js +13 -10
  121. package/lib/commands/reflect-args.js.map +1 -1
  122. package/lib/commands/reflect-driver.js +2 -1
  123. package/lib/commands/reflect-driver.js.map +1 -1
  124. package/lib/commands/reflect-report.js.map +1 -1
  125. package/lib/commands/reflect.js +1 -1
  126. package/lib/commands/reflect.js.map +1 -1
  127. package/lib/commands/save-args.d.ts.map +1 -1
  128. package/lib/commands/save-args.js +7 -4
  129. package/lib/commands/save-args.js.map +1 -1
  130. package/lib/commands/save.d.ts +8 -4
  131. package/lib/commands/save.d.ts.map +1 -1
  132. package/lib/commands/save.js +12 -23
  133. package/lib/commands/save.js.map +1 -1
  134. package/lib/commands/validate-args.d.ts +3 -2
  135. package/lib/commands/validate-args.d.ts.map +1 -1
  136. package/lib/commands/validate-args.js +13 -10
  137. package/lib/commands/validate-args.js.map +1 -1
  138. package/lib/commands/validate-driver.js +2 -1
  139. package/lib/commands/validate-driver.js.map +1 -1
  140. package/lib/commands/validate-report.js.map +1 -1
  141. package/lib/commands/validate.js +1 -1
  142. package/lib/commands/validate.js.map +1 -1
  143. package/lib/commands/watch-args.d.ts.map +1 -1
  144. package/lib/commands/watch-args.js +6 -4
  145. package/lib/commands/watch-args.js.map +1 -1
  146. package/lib/commands/watch.d.ts +3 -4
  147. package/lib/commands/watch.d.ts.map +1 -1
  148. package/lib/commands/watch.js +20 -2
  149. package/lib/commands/watch.js.map +1 -1
  150. package/lib/driver-heap.d.ts +52 -0
  151. package/lib/driver-heap.d.ts.map +1 -0
  152. package/lib/driver-heap.js +51 -0
  153. package/lib/driver-heap.js.map +1 -0
  154. package/lib/index.d.ts +3 -0
  155. package/lib/index.d.ts.map +1 -1
  156. package/lib/index.js +3 -0
  157. package/lib/index.js.map +1 -1
  158. package/lib/log-level.d.ts +21 -11
  159. package/lib/log-level.d.ts.map +1 -1
  160. package/lib/log-level.js +25 -14
  161. package/lib/log-level.js.map +1 -1
  162. package/lib/spawn-data-server.d.ts +9 -4
  163. package/lib/spawn-data-server.d.ts.map +1 -1
  164. package/lib/spawn-data-server.js +5 -4
  165. package/lib/spawn-data-server.js.map +1 -1
  166. package/lib/stderr-connection-logger.d.ts +12 -0
  167. package/lib/stderr-connection-logger.d.ts.map +1 -0
  168. package/lib/stderr-connection-logger.js +16 -0
  169. package/lib/stderr-connection-logger.js.map +1 -0
  170. package/lib/testing/echo-server.js +9 -1
  171. package/lib/testing/echo-server.js.map +1 -1
  172. package/package.json +50 -39
  173. package/src/cli.ts +7 -2
  174. package/src/commands/analyze-heap.ts +4 -1
  175. package/src/commands/ast-ground-truth-args.ts +15 -12
  176. package/src/commands/ast-ground-truth-driver.ts +2 -1
  177. package/src/commands/ast-ground-truth.ts +1 -1
  178. package/src/commands/client-session.ts +33 -0
  179. package/src/commands/create-args.ts +68 -0
  180. package/src/commands/create.ts +83 -0
  181. package/src/commands/delete-args.ts +64 -0
  182. package/src/commands/delete.ts +61 -0
  183. package/src/commands/generate-ast-builder.ts +246 -0
  184. package/src/commands/generate-transfer-model-args.ts +11 -1
  185. package/src/commands/generate-transfer-model-config.ts +6 -3
  186. package/src/commands/generate-transfer-model.ts +27 -4
  187. package/src/commands/harness-args.ts +99 -31
  188. package/src/commands/headless-harness.ts +86 -26
  189. package/src/commands/init-args.ts +6 -6
  190. package/src/commands/init-templates.ts +272 -169
  191. package/src/commands/init-wizard.ts +4 -4
  192. package/src/commands/init-workspace.ts +31 -7
  193. package/src/commands/init.ts +36 -26
  194. package/src/commands/lint-grammar-args.ts +17 -13
  195. package/src/commands/lint-grammar-driver.ts +2 -1
  196. package/src/commands/lint-grammar.ts +1 -1
  197. package/src/commands/measure-memory-args.ts +27 -14
  198. package/src/commands/measure-memory-driver.ts +5 -3
  199. package/src/commands/measure-memory.ts +1 -1
  200. package/src/commands/model-docs-args.ts +16 -13
  201. package/src/commands/model-docs-driver.ts +2 -1
  202. package/src/commands/model-docs.ts +1 -1
  203. package/src/commands/projects-args.ts +5 -4
  204. package/src/commands/projects.ts +4 -6
  205. package/src/commands/query-args.ts +5 -4
  206. package/src/commands/query.ts +4 -6
  207. package/src/commands/reflect-args.ts +17 -13
  208. package/src/commands/reflect-driver.ts +2 -1
  209. package/src/commands/reflect.ts +1 -1
  210. package/src/commands/save-args.ts +7 -3
  211. package/src/commands/save.ts +24 -27
  212. package/src/commands/validate-args.ts +17 -13
  213. package/src/commands/validate-driver.ts +2 -1
  214. package/src/commands/validate.ts +1 -1
  215. package/src/commands/watch-args.ts +6 -3
  216. package/src/commands/watch.ts +28 -7
  217. package/src/driver-heap.ts +65 -0
  218. package/src/index.ts +3 -0
  219. package/src/log-level.ts +42 -14
  220. package/src/spawn-data-server.ts +17 -5
  221. package/src/stderr-connection-logger.ts +18 -0
  222. package/src/testing/echo-server.ts +11 -2
@@ -0,0 +1,246 @@
1
+ /********************************************************************************
2
+ * Copyright (c) 2026 CrossBreeze, EclipseSource and others.
3
+ *
4
+ * This program and the accompanying materials are made available under the
5
+ * terms of the MIT License which is available in the project root.
6
+ *
7
+ * SPDX-License-Identifier: MIT
8
+ ********************************************************************************/
9
+
10
+ import * as fs from 'fs';
11
+ import * as path from 'path';
12
+ import type { SourceFile } from 'ts-morph';
13
+
14
+ /** Inputs for {@link emitAstBuilder}, resolved by the transfer-model command. */
15
+ export interface EmitAstBuilderOptions {
16
+ /** Destination path for the generated builder module. */
17
+ outFile: string;
18
+ /** Path to the Langium-generated AST file the builder imports from. */
19
+ astFile: string;
20
+ /** Language id derived from the `<LanguageId>AstReflection` class name. */
21
+ languageId: string;
22
+ /** Header line naming the command that regenerates the file. */
23
+ regenCommand: string;
24
+ }
25
+
26
+ /**
27
+ * A single `makeAstNodeBuilder` binding the generator emits.
28
+ *
29
+ * `typeMap` is the type expression handed to the generic — the whole-project
30
+ * alias for the merged binding, `<Namespace>.AstType` for a narrowed one.
31
+ */
32
+ interface BuilderBinding {
33
+ exportName: string;
34
+ typeMap: string;
35
+ /** Grammar this binding is narrowed to; absent on the merged binding. */
36
+ namespace?: string;
37
+ }
38
+
39
+ /**
40
+ * Langium declares this type alias inside each language's namespace in a
41
+ * multi-language project. Its presence is what marks a namespace as a grammar's
42
+ * type registry rather than an incidental one.
43
+ */
44
+ const NAMESPACED_AST_TYPE_NAME = 'AstType';
45
+
46
+ /** Export name of the merged, whole-project binding. */
47
+ const MERGED_EXPORT_NAME = 'astNode';
48
+
49
+ /**
50
+ * Emit a module binding {@link makeAstNodeBuilder} to a project's reflection,
51
+ * once per grammar plus once across all of them.
52
+ *
53
+ * **The binding is boilerplate with exactly one degree of freedom** — the type
54
+ * map — so hand-writing it buys nothing and goes stale the moment a grammar is
55
+ * added. Generating it is also the only way a narrowed binding can exist at all:
56
+ * the per-grammar type maps live in namespaces Langium emits only on its
57
+ * multi-language path, so a single-grammar project gets the merged binding alone
58
+ * and there is nothing to narrow.
59
+ *
60
+ * **A narrowed binding is only as narrow as its grammar's import closure.**
61
+ * Langium's per-grammar `AstType` lists everything REACHABLE from that grammar,
62
+ * so where one grammar imports all the others its map equals the project's and
63
+ * its binding checks nothing the merged one does not. The emitted doc says so at
64
+ * each declaration rather than promising a guarantee the type map cannot give.
65
+ *
66
+ * Answers `false` when the AST source declares no whole-project type alias,
67
+ * which means the file did not come from `langium generate` and the caller
68
+ * should report rather than write a module that cannot compile.
69
+ */
70
+ export function emitAstBuilder(astSource: SourceFile, options: EmitAstBuilderOptions): boolean {
71
+ const content = buildAstBuilderSource(astSource, options);
72
+ if (content === undefined) {
73
+ return false;
74
+ }
75
+
76
+ fs.mkdirSync(path.dirname(options.outFile), { recursive: true });
77
+ if (fs.existsSync(options.outFile) && fs.readFileSync(options.outFile, 'utf-8') === content) {
78
+ console.log('AST builder is up to date.');
79
+ return true;
80
+ }
81
+ fs.writeFileSync(options.outFile, content, 'utf-8');
82
+ console.log(`Generated: ${options.outFile}`);
83
+ return true;
84
+ }
85
+
86
+ /**
87
+ * The module text {@link emitAstBuilder} would write, or `undefined` when the
88
+ * AST source declares no whole-project type alias. Pure over its inputs, so the
89
+ * emitted shape is testable without touching a filesystem.
90
+ */
91
+ export function buildAstBuilderSource(astSource: SourceFile, options: EmitAstBuilderOptions): string | undefined {
92
+ const mergedTypeMap = `${options.languageId}AstType`;
93
+ if (!astSource.getTypeAlias(mergedTypeMap)) {
94
+ return undefined;
95
+ }
96
+
97
+ const bindings: BuilderBinding[] = [{ exportName: MERGED_EXPORT_NAME, typeMap: mergedTypeMap }];
98
+ for (const namespace of findGrammarNamespaces(astSource)) {
99
+ bindings.push({
100
+ exportName: builderExportName(namespace),
101
+ typeMap: `${namespace}.${NAMESPACED_AST_TYPE_NAME}`,
102
+ namespace
103
+ });
104
+ }
105
+ assertDistinctExportNames(bindings);
106
+
107
+ return renderAstBuilder(bindings, {
108
+ reflectionName: findReflectionConstName(astSource, options.languageId),
109
+ importPath: relativeImportPath(options.outFile, options.astFile),
110
+ regenCommand: options.regenCommand
111
+ });
112
+ }
113
+
114
+ /**
115
+ * Namespaces that carry a grammar's type registry, in declaration order.
116
+ *
117
+ * Keyed on the nested `AstType` alias rather than on the namespace being
118
+ * exported, because an adopter's augmentation can add namespaces to the same
119
+ * file for unrelated reasons and only the ones Langium emits per grammar have
120
+ * a type map to bind.
121
+ */
122
+ function findGrammarNamespaces(astSource: SourceFile): string[] {
123
+ const names: string[] = [];
124
+ for (const module of astSource.getModules()) {
125
+ const name = module.getName();
126
+ if (name && module.getTypeAlias(NAMESPACED_AST_TYPE_NAME)) {
127
+ names.push(name);
128
+ }
129
+ }
130
+ return names;
131
+ }
132
+
133
+ /**
134
+ * `Domain` → `domainNode`. Lower-cases the leading character only, so a grammar
135
+ * named `OrderFlow` reads as `orderFlowNode` rather than losing its word break.
136
+ */
137
+ function builderExportName(namespace: string): string {
138
+ return `${namespace.charAt(0).toLowerCase()}${namespace.slice(1)}Node`;
139
+ }
140
+
141
+ /**
142
+ * Two grammars whose names differ only in their leading character collapse to
143
+ * one export. Emitting anyway would silently drop a binding, so fail with both
144
+ * names rather than leave the caller to discover it at compile time.
145
+ */
146
+ function assertDistinctExportNames(bindings: readonly BuilderBinding[]): void {
147
+ const seen = new Map<string, string>();
148
+ for (const binding of bindings) {
149
+ const previous = seen.get(binding.exportName);
150
+ if (previous !== undefined) {
151
+ throw new Error(
152
+ `Cannot emit the AST builder: grammars '${previous}' and '${binding.namespace}' both map to the export ` +
153
+ `'${binding.exportName}'. Rename one grammar so the generated bindings stay distinct.`
154
+ );
155
+ }
156
+ seen.set(binding.exportName, binding.namespace ?? MERGED_EXPORT_NAME);
157
+ }
158
+ }
159
+
160
+ /**
161
+ * Name of the const holding the project's reflection instance.
162
+ *
163
+ * Langium emits `export const reflection = new <LanguageId>AstReflection()`, but
164
+ * the const is located by its initializer rather than by that name so a renamed
165
+ * export still resolves. Falls back to the emitted default when no declaration
166
+ * matches, which keeps the output compiling against a stock Langium file.
167
+ */
168
+ function findReflectionConstName(astSource: SourceFile, languageId: string): string {
169
+ const reflectionClass = `${languageId}AstReflection`;
170
+ for (const declaration of astSource.getVariableDeclarations()) {
171
+ if (declaration.getInitializer()?.getText().replace(/\s/g, '') === `new${reflectionClass}()`) {
172
+ return declaration.getName();
173
+ }
174
+ }
175
+ return 'reflection';
176
+ }
177
+
178
+ /**
179
+ * Module specifier for the AST file as seen from the generated module's own
180
+ * directory. Emitted with a `.js` extension and posix separators because the
181
+ * output is ESM TypeScript, where the specifier names the compiled sibling.
182
+ */
183
+ function relativeImportPath(outFile: string, astFile: string): string {
184
+ const relative = path.relative(path.dirname(path.resolve(outFile)), path.resolve(astFile));
185
+ const posix = relative.split(path.sep).join('/').replace(/\.ts$/, '.js');
186
+ return posix.startsWith('.') ? posix : `./${posix}`;
187
+ }
188
+
189
+ function renderAstBuilder(
190
+ bindings: readonly BuilderBinding[],
191
+ context: { reflectionName: string; importPath: string; regenCommand: string }
192
+ ): string {
193
+ const imported = [context.reflectionName, ...bindings.map(binding => `type ${binding.namespace ?? binding.typeMap}`)];
194
+ const out: string[] = [];
195
+
196
+ out.push('/******************************************************************************');
197
+ out.push(' * Generated from the Langium AST — DO NOT EDIT MANUALLY!');
198
+ out.push(` * ${context.regenCommand}`);
199
+ out.push(' ******************************************************************************/');
200
+ out.push('');
201
+ out.push('/* eslint-disable */');
202
+ out.push('');
203
+ out.push("import { makeAstNodeBuilder } from '@hydranium/core';");
204
+ out.push(`import { ${imported.join(', ')} } from '${context.importPath}';`);
205
+ out.push('');
206
+
207
+ // A single-grammar project has nothing to narrow to, so the merged binding is
208
+ // simply THE binding there and must not point at a sibling that was not emitted.
209
+ const narrowed = bindings.some(binding => binding.namespace !== undefined);
210
+ const guarantee = [
211
+ ' * Mandatory fields are a type error at the call site, and grammar-declared',
212
+ ' * containment arrays are materialised from reflection metadata, so a built',
213
+ ' * node carries `[]` where a cast literal would leave `undefined`.'
214
+ ];
215
+
216
+ for (const binding of bindings) {
217
+ out.push('/**');
218
+ if (binding.namespace !== undefined) {
219
+ out.push(` * AST-node factory narrowed to the '${binding.namespace}' grammar.`);
220
+ out.push(' *');
221
+ out.push(' * Narrowed by grammar REACHABILITY, not by ownership: a grammar that');
222
+ out.push(" * imports another sees that one's types too, so this binding is only as");
223
+ out.push(` * narrow as '${binding.namespace}'s import closure. Where that closure is the`);
224
+ out.push(' * whole project, it accepts exactly what the merged binding does and the');
225
+ out.push(' * choice is documentation rather than a check.');
226
+ out.push(' *');
227
+ out.push(...guarantee);
228
+ } else if (narrowed) {
229
+ out.push(' * AST-node factory spanning every grammar in this project.');
230
+ out.push(' *');
231
+ out.push(' * Prefer the narrowed binding matching the grammar the call site works in:');
232
+ out.push(" * it rejects a type outside that grammar's import closure, which this one");
233
+ out.push(' * accepts from anywhere. Reach for this one where a call site genuinely');
234
+ out.push(' * spans grammars.');
235
+ } else {
236
+ out.push(" * AST-node factory for this project's grammar.");
237
+ out.push(' *');
238
+ out.push(...guarantee);
239
+ }
240
+ out.push(' */');
241
+ out.push(`export const ${binding.exportName} = makeAstNodeBuilder<${binding.typeMap}>(${context.reflectionName});`);
242
+ out.push('');
243
+ }
244
+
245
+ return out.join('\n');
246
+ }
@@ -29,6 +29,7 @@ export const GENERATE_TRANSFER_MODEL_FLAGS: readonly string[] = [
29
29
  '--ast-file',
30
30
  '--augmentation-file',
31
31
  '--out-file',
32
+ '--ast-builder-file',
32
33
  '--element-type-name',
33
34
  '--terminals-name',
34
35
  '--terminals-source-name',
@@ -48,7 +49,8 @@ export const GENERATE_TRANSFER_MODEL_VALUE_FLAGS: readonly string[] = GENERATE_T
48
49
  export const GENERATE_TRANSFER_MODEL_HELP: readonly string[] = [
49
50
  'Usage: hydranium-cli generate-transfer-model [options]',
50
51
  '',
51
- 'Generate a serializable transfer-model TypeScript file from a Langium AST. The',
52
+ 'Generate a serializable transfer-model TypeScript file from a Langium AST, and',
53
+ 'optionally an AST-node builder module bound to the same reflection. The',
52
54
  'required inputs (--ast-file / --augmentation-file / --out-file) may instead come',
53
55
  'from a --config JSON file, and --ast-file can be auto-discovered from a Langium',
54
56
  "config's `out` directory. Precedence, highest first: explicit flags, then the",
@@ -67,6 +69,11 @@ export const GENERATE_TRANSFER_MODEL_HELP: readonly string[] = [
67
69
  ' directory: it treats that directory as exclusively',
68
70
  ' its own, so every `langium generate` reports this',
69
71
  ' file as unexpected and offers to delete it.',
72
+ ' --ast-builder-file <path> Also emit an AST-node builder module here: one',
73
+ ' makeAstNodeBuilder binding per grammar, plus one',
74
+ ' spanning all of them. Omit if nothing constructs',
75
+ ' AST nodes. Same restriction as --out-file: keep it',
76
+ " out of langium-cli's own `out` directory.",
70
77
  ' --element-type-name <name> Base element type name in output. Default: TransferElement.',
71
78
  ' --terminals-name <name> Terminals const name in output. Default: ModelTerminals.',
72
79
  ' --terminals-source-name <n> Source-side terminals variable name. Default: <LanguageId>Terminals.',
@@ -120,6 +127,9 @@ export function parseGenerateOptions(args: string[], onError: UsageError = exitW
120
127
  case '--out-file':
121
128
  flags.outFile = next();
122
129
  break;
130
+ case '--ast-builder-file':
131
+ flags.astBuilderFile = next();
132
+ break;
123
133
  case '--element-type-name':
124
134
  flags.elementTypeName = next();
125
135
  break;
@@ -9,10 +9,11 @@
9
9
 
10
10
  import * as fs from 'node:fs';
11
11
  import * as path from 'node:path';
12
+ import { describeError } from '@hydranium/protocol';
12
13
  import type { GenerateTransferModelOptions } from './generate-transfer-model.js';
13
14
 
14
15
  /** Path-valued option keys — resolved relative to a config/langium-config file's directory. */
15
- const PATH_KEYS = ['astFile', 'augmentationFile', 'outFile'] as const;
16
+ const PATH_KEYS = ['astFile', 'augmentationFile', 'outFile', 'astBuilderFile'] as const;
16
17
 
17
18
  /** Resolve `value` against `baseDir` when it is relative; absolute paths pass through. */
18
19
  function resolveAgainst(baseDir: string, value: string): string {
@@ -31,7 +32,7 @@ export function loadTransferModelConfig(configPath: string): Partial<GenerateTra
31
32
  try {
32
33
  raw = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
33
34
  } catch (error: unknown) {
34
- throw new Error(`Cannot read transfer-model config '${configPath}': ${error instanceof Error ? error.message : String(error)}`);
35
+ throw new Error(`Cannot read transfer-model config '${configPath}': ${describeError(error)}`);
35
36
  }
36
37
  if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {
37
38
  throw new Error(`Transfer-model config '${configPath}' must be a JSON object.`);
@@ -43,6 +44,7 @@ export function loadTransferModelConfig(configPath: string): Partial<GenerateTra
43
44
  'astFile',
44
45
  'augmentationFile',
45
46
  'outFile',
47
+ 'astBuilderFile',
46
48
  'elementTypeName',
47
49
  'terminalsName',
48
50
  'terminalsSourceName',
@@ -74,7 +76,7 @@ export function deriveAstFileFromLangiumConfig(langiumConfigPath: string): strin
74
76
  try {
75
77
  raw = JSON.parse(fs.readFileSync(langiumConfigPath, 'utf-8'));
76
78
  } catch (error: unknown) {
77
- throw new Error(`Cannot read langium-config '${langiumConfigPath}': ${error instanceof Error ? error.message : String(error)}`);
79
+ throw new Error(`Cannot read langium-config '${langiumConfigPath}': ${describeError(error)}`);
78
80
  }
79
81
  const out = (raw as { out?: unknown })?.out;
80
82
  if (typeof out !== 'string') {
@@ -118,6 +120,7 @@ export function mergeTransferModelOptions(...sources: Array<Partial<GenerateTran
118
120
  astFile: astFile!,
119
121
  augmentationFile: augmentationFile!,
120
122
  outFile: outFile!,
123
+ astBuilderFile: pick('astBuilderFile'),
121
124
  elementTypeName: pick('elementTypeName'),
122
125
  terminalsName: pick('terminalsName'),
123
126
  terminalsSourceName: pick('terminalsSourceName'),
@@ -9,6 +9,7 @@
9
9
 
10
10
  import * as fs from 'fs';
11
11
  import * as path from 'path';
12
+ import { emitAstBuilder } from './generate-ast-builder.js';
12
13
  import {
13
14
  type Node,
14
15
  type ObjectLiteralExpression,
@@ -18,6 +19,7 @@ import {
18
19
  type InterfaceDeclaration,
19
20
  type SourceFile
20
21
  } from 'ts-morph';
22
+ import { describeError } from '@hydranium/protocol';
21
23
 
22
24
  /**
23
25
  * Options for the transfer-model generator.
@@ -35,6 +37,15 @@ export interface GenerateTransferModelOptions {
35
37
  augmentationFile: string;
36
38
  /** Destination path for the generated transfer model. */
37
39
  outFile: string;
40
+ /**
41
+ * Destination for a generated AST-node builder module. Omitted by consumers
42
+ * that construct no AST nodes; the transfer model is emitted either way.
43
+ *
44
+ * Emitted from this command rather than its own because the AST source is
45
+ * already parsed here, and because a consumer that regenerates one artefact
46
+ * and not the other has the two disagreeing about the same grammar.
47
+ */
48
+ astBuilderFile?: string;
38
49
  /** Name used for the base element type in the output. Defaults to `TransferElement`. */
39
50
  elementTypeName?: string;
40
51
  /** Name used for the terminal-patterns const in the output. Defaults to `ModelTerminals`. */
@@ -99,7 +110,7 @@ export function watchTransferModel(options: GenerateTransferModelOptions, contex
99
110
  try {
100
111
  generateTransferModel(options);
101
112
  } catch (error: unknown) {
102
- console.error(`Transfer-model generation failed: ${error instanceof Error ? error.message : String(error)}`);
113
+ console.error(`Transfer-model generation failed: ${describeError(error)}`);
103
114
  }
104
115
  };
105
116
  runSafely();
@@ -396,10 +407,22 @@ export function generateTransferModel(options: GenerateTransferModelOptions): vo
396
407
  fs.mkdirSync(path.dirname(options.outFile), { recursive: true });
397
408
  if (fs.existsSync(options.outFile) && fs.readFileSync(options.outFile, 'utf-8') === content) {
398
409
  console.log('Transfer model is up to date.');
399
- return;
410
+ } else {
411
+ fs.writeFileSync(options.outFile, content, 'utf-8');
412
+ console.log(`Generated: ${options.outFile}`);
413
+ }
414
+
415
+ if (options.astBuilderFile !== undefined) {
416
+ const emitted = emitAstBuilder(astSource, {
417
+ outFile: options.astBuilderFile,
418
+ astFile: options.astFile,
419
+ languageId,
420
+ regenCommand
421
+ });
422
+ if (!emitted) {
423
+ console.warn(`Warning: no '${languageId}AstType' alias in ${options.astFile}; skipping the AST builder.`);
424
+ }
400
425
  }
401
- fs.writeFileSync(options.outFile, content, 'utf-8');
402
- console.log(`Generated: ${options.outFile}`);
403
426
  }
404
427
 
405
428
  // ---------------------------------------------------------------------------
@@ -31,11 +31,12 @@
31
31
  * parser rejects is an invocation that fails for no visible reason.
32
32
  */
33
33
 
34
- import type { LogThreshold } from '@hydranium/protocol';
34
+ import { describeError, type LogThreshold } from '@hydranium/protocol';
35
35
  import { statSync } from 'node:fs';
36
+ import * as fs from 'node:fs/promises';
36
37
  import * as path from 'node:path';
37
38
  import { fileURLToPath } from 'node:url';
38
- import { parseLogLevelOption } from '../log-level.js';
39
+ import { type LogOptions, parseLogLevelOption } from '../log-level.js';
39
40
 
40
41
  /**
41
42
  * How a parser reports a usage problem. It never returns, so a parser can treat
@@ -56,9 +57,18 @@ export function exitWithUsage(message: string): never {
56
57
  process.exit(2);
57
58
  }
58
59
 
59
- /** The value flag {@link parseHarnessArgs} consumes itself, before any the subcommand declares. */
60
+ /** Names the head's services module; every harness subcommand requires it. */
60
61
  export const SERVICES_FLAG = '--services';
61
62
 
63
+ /**
64
+ * Registers a loader in the driver child that imports the head. The child is a
65
+ * fresh `node`, so a loader registered on the CLI's own process never reaches it.
66
+ */
67
+ export const IMPORT_FLAG = '--import';
68
+
69
+ /** The value flags {@link parseHarnessArgs} consumes itself, before any the subcommand declares. */
70
+ export const HARNESS_VALUE_FLAGS = [SERVICES_FLAG, IMPORT_FLAG] as const;
71
+
62
72
  /**
63
73
  * The one spelling of the log threshold, shared by both subcommand families.
64
74
  *
@@ -68,33 +78,68 @@ export const SERVICES_FLAG = '--services';
68
78
  * on which command a caller happened to reach for.
69
79
  */
70
80
  export const LOG_LEVEL_FLAG = '--log-level';
81
+ export const LOG_FILE_FLAG = '--log-file';
82
+ export const LOG_FILE_LEVEL_FLAG = '--log-file-level';
83
+
84
+ /** The log flags every subcommand takes, read by {@link logOptions}. */
85
+ export const LOG_VALUE_FLAGS = [LOG_LEVEL_FLAG, LOG_FILE_FLAG, LOG_FILE_LEVEL_FLAG] as const;
71
86
 
72
87
  /** The value flags {@link parseServerSpawnOptions} consumes itself. */
73
- export const SERVER_SPAWN_VALUE_FLAGS: readonly string[] = ['--server', '--cwd', LOG_LEVEL_FLAG];
88
+ export const SERVER_SPAWN_VALUE_FLAGS: readonly string[] = ['--server', '--cwd', ...LOG_VALUE_FLAGS];
74
89
 
75
90
  /**
76
- * The `--help` line every subcommand describes {@link LOG_LEVEL_FLAG} with.
91
+ * The `--help` lines every subcommand describes {@link LOG_VALUE_FLAGS} with.
77
92
  *
78
93
  * Shared text, per-command padding: `command-args.test.ts` compares the flags a
79
94
  * help block DESCRIBES against the flags the parser accepts, and it recognises a
80
- * description by the two-space indent — so the line has to be a real option entry
95
+ * description by the two-space indent — so each line has to be a real option entry
81
96
  * in each block, and the column each block aligns its descriptions at is the
82
- * block's own.
97
+ * block's own. A flag too wide for that column takes its description on the
98
+ * next line, at the column.
83
99
  */
84
- export function logLevelHelpLine(padTo: number): string {
85
- return ` ${`${LOG_LEVEL_FLAG} <lvl>`.padEnd(padTo)}Log threshold for the head this boots (off|error|warn|info|debug|trace).`;
100
+ export function logHelpLines(padTo: number, head = 'the head this boots'): string[] {
101
+ return [
102
+ helpLine(`${LOG_LEVEL_FLAG} <lvl>`, `Log threshold for ${head} (off|error|warn|info|debug|trace).`, padTo),
103
+ helpLine(
104
+ `${LOG_FILE_FLAG} <file>`,
105
+ `Also write ${head}'s log to <file>; {workspace} expands to the workspace, {pid} to the process id.`,
106
+ padTo
107
+ ),
108
+ helpLine(`${LOG_FILE_LEVEL_FLAG} <lvl>`, `Threshold for that file, which the log-level setting does not change.`, padTo)
109
+ ].flat();
110
+ }
111
+
112
+ /** The `--help` lines every `--services` subcommand describes {@link IMPORT_FLAG} with, aligned as {@link logHelpLines}. */
113
+ export function importHelpLines(padTo: number): string[] {
114
+ return helpLine(`${IMPORT_FLAG} <specifier>`, 'Loader to register before importing <module>, e.g. tsx (repeatable).', padTo);
115
+ }
116
+
117
+ function helpLine(flag: string, text: string, padTo: number): string[] {
118
+ return flag.length < padTo - 1 ? [` ${flag.padEnd(padTo)}${text}`] : [` ${flag}`, `${' '.repeat(padTo + 2)}${text}`];
86
119
  }
87
120
 
88
121
  /**
89
- * Narrow a raw {@link LOG_LEVEL_FLAG} value that {@link parseHarnessArgs}
90
- * collected, leaving an absent flag absent.
122
+ * Narrow the raw {@link LOG_VALUE_FLAGS} values a parser collected, leaving
123
+ * absent flags absent.
124
+ *
125
+ * `--log-file` resolves against the caller's directory: the child may run
126
+ * elsewhere (`--cwd`), and a relative path would land the log there.
91
127
  *
92
128
  * Throws rather than reaching `onError`, matching {@link parseServerSpawnOptions}:
93
129
  * the level vocabulary belongs to the protocol package, which reports it, and the
94
130
  * entry point's catch turns that into the same message-and-exit.
95
131
  */
96
- export function logLevelOption(value: string | undefined): LogThreshold | undefined {
97
- return value === undefined ? undefined : parseLogLevelOption(value);
132
+ export function logOptions(options: Readonly<Record<string, string | undefined>>): LogOptions {
133
+ const level = (flag: string): LogThreshold | undefined => {
134
+ const value = options[flag];
135
+ return value === undefined ? undefined : parseLogLevelOption(value, flag);
136
+ };
137
+ const logFile = options[LOG_FILE_FLAG];
138
+ return {
139
+ logLevel: level(LOG_LEVEL_FLAG),
140
+ logFile: logFile === undefined ? undefined : path.resolve(logFile),
141
+ logFileLevel: level(LOG_FILE_LEVEL_FLAG)
142
+ };
98
143
  }
99
144
 
100
145
  /**
@@ -134,6 +179,8 @@ export function printHelp(lines: readonly string[]): void {
134
179
  /** What {@link parseHarnessArgs} recovered from an argv. */
135
180
  export interface ParsedHarnessArgs {
136
181
  servicesModule: string;
182
+ /** The {@link IMPORT_FLAG} values in the order given, absent when there were none. */
183
+ imports?: string[];
137
184
  /**
138
185
  * An absolute directory path, resolved by {@link resolveWorkspaceArgument} and
139
186
  * checked to exist. `''` when the subcommand declared `requireWorkspace: false`.
@@ -163,12 +210,12 @@ export interface HarnessArgsConfig {
163
210
 
164
211
  /**
165
212
  * Shared parser for the headless-harness subcommands. Consumes the required
166
- * `--services <module>` value flag and a single positional `<workspace>`, plus
167
- * the `valueFlags` (each takes a value) and `boolFlags` (presence-only, recorded
168
- * as `'true'`) the subcommand recognises. Unknown flags or a missing
169
- * `--services`/`<workspace>` are usage errors, and so is a `<workspace>` that
170
- * reaches no directory — see {@link resolveWorkspaceArgument} for why that cannot
171
- * be left to the run.
213
+ * `--services <module>` value flag, the repeatable `--import <specifier>` and a
214
+ * single positional `<workspace>`, plus the `valueFlags` (each takes a value)
215
+ * and `boolFlags` (presence-only, recorded as `'true'`) the subcommand
216
+ * recognises. Unknown flags or a missing `--services`/`<workspace>` are usage
217
+ * errors, and so is a `<workspace>` that reaches no directory — see
218
+ * {@link resolveWorkspaceArgument} for why that cannot be left to the run.
172
219
  */
173
220
  export function parseHarnessArgs(
174
221
  args: string[],
@@ -185,6 +232,7 @@ export function parseHarnessArgs(
185
232
  const options: Record<string, string | undefined> = {};
186
233
  const values: Record<string, string[]> = {};
187
234
  let servicesModule: string | undefined;
235
+ let imports: string[] | undefined;
188
236
  let workspace: string | undefined;
189
237
  for (let index = 0; index < args.length; index += 1) {
190
238
  const flag = args[index];
@@ -196,8 +244,10 @@ export function parseHarnessArgs(
196
244
  index += 1;
197
245
  return value;
198
246
  };
199
- if (flag === '--services') {
247
+ if (flag === SERVICES_FLAG) {
200
248
  servicesModule = next();
249
+ } else if (flag === IMPORT_FLAG) {
250
+ (imports ??= []).push(next());
201
251
  } else if (boolSet.has(flag)) {
202
252
  options[flag] = 'true';
203
253
  } else if (repeatableSet.has(flag)) {
@@ -213,7 +263,8 @@ export function parseHarnessArgs(
213
263
  }
214
264
  }
215
265
  return {
216
- servicesModule: assertRequired(servicesModule, '--services', commandName, onError),
266
+ servicesModule: assertRequired(servicesModule, SERVICES_FLAG, commandName, onError),
267
+ imports,
217
268
  workspace: requireWorkspace
218
269
  ? resolveWorkspaceArgument(assertRequired(workspace, '<workspace>', commandName, onError), commandName, onError)
219
270
  : (workspace ?? ''),
@@ -257,7 +308,7 @@ export function resolveWorkspaceArgument(workspace: string, commandName: string,
257
308
  try {
258
309
  stats = statSync(resolved, { throwIfNoEntry: false });
259
310
  } catch (err: unknown) {
260
- const detail = err instanceof Error ? err.message : String(err);
311
+ const detail = describeError(err);
261
312
  onError(`<workspace> is not reachable: '${workspace}' resolved to ${resolved} (${detail}) ${help}`);
262
313
  }
263
314
  if (stats === undefined) {
@@ -276,7 +327,7 @@ function toWorkspacePath(workspace: string, commandName: string, onError: UsageE
276
327
  try {
277
328
  return fileURLToPath(workspace);
278
329
  } catch (err: unknown) {
279
- const detail = err instanceof Error ? err.message : String(err);
330
+ const detail = describeError(err);
280
331
  onError(`<workspace> is not a usable file URI: '${workspace}' (${detail}) (hydranium-cli ${commandName} --help)`);
281
332
  }
282
333
  }
@@ -336,11 +387,10 @@ function kebabToCamel(name: string): string {
336
387
  }
337
388
 
338
389
  /** What {@link parseServerSpawnOptions} recovered from an argv. */
339
- export interface SpawnOptions {
390
+ export interface SpawnOptions extends LogOptions {
340
391
  serverCommand: string;
341
392
  serverArgs: string[];
342
393
  cwd?: string;
343
- logLevel?: LogThreshold;
344
394
  /** The tokens this parser did not claim, for the subcommand's own options. */
345
395
  extra: string[];
346
396
  }
@@ -363,10 +413,10 @@ function isRelativePathToken(token: string, isCommand: boolean): boolean {
363
413
 
364
414
  /**
365
415
  * Shared option parser for subcommands that spawn a data-server child. Consumes
366
- * `--server` / `--cwd` / `--log-level` and returns the surviving tokens as
416
+ * `--server` / `--cwd` / the {@link LOG_VALUE_FLAGS} and returns the surviving tokens as
367
417
  * `extra` for {@link parseFlagOptions} to finish.
368
418
  *
369
- * An unrecognised `--log-level` value throws rather than reaching `onError`: the
419
+ * An unrecognised log level value throws rather than reaching `onError`: the
370
420
  * level vocabulary belongs to the protocol package, which reports it, and the
371
421
  * entry point's catch turns that into the same message-and-exit.
372
422
  *
@@ -383,7 +433,7 @@ function isRelativePathToken(token: string, isCommand: boolean): boolean {
383
433
  export function parseServerSpawnOptions(args: string[], commandName: string, onError: UsageError = exitWithUsage): SpawnOptions {
384
434
  let serverSpec: string | undefined;
385
435
  let cwd: string | undefined;
386
- let logLevel: LogThreshold | undefined;
436
+ const logFlags: Record<string, string> = {};
387
437
  const extra: string[] = [];
388
438
  for (let index = 0; index < args.length; index += 1) {
389
439
  const flag = args[index];
@@ -399,8 +449,8 @@ export function parseServerSpawnOptions(args: string[], commandName: string, onE
399
449
  serverSpec = claim();
400
450
  } else if (flag === '--cwd') {
401
451
  cwd = claim();
402
- } else if (flag === LOG_LEVEL_FLAG) {
403
- logLevel = parseLogLevelOption(claim());
452
+ } else if ((LOG_VALUE_FLAGS as readonly string[]).includes(flag)) {
453
+ logFlags[flag] = claim();
404
454
  } else {
405
455
  extra.push(flag);
406
456
  }
@@ -425,5 +475,23 @@ export function parseServerSpawnOptions(args: string[], commandName: string, onE
425
475
  );
426
476
  }
427
477
  }
428
- return { serverCommand, serverArgs, cwd, logLevel, extra };
478
+ return { serverCommand, serverArgs, cwd, ...logOptions(logFlags), extra };
479
+ }
480
+
481
+ /**
482
+ * Resolve the `--content` argument to its textual form. The `@<path>`
483
+ * prefix reads from a file (parses as UTF-8); anything else is taken
484
+ * literally. The leading `@` can be escaped as `\@` for content that
485
+ * legitimately starts with `@`.
486
+ */
487
+ export async function resolveContent(content: string, readFile?: (path: string) => Promise<string>): Promise<string> {
488
+ if (content.startsWith('@')) {
489
+ const file = content.slice(1);
490
+ const reader = readFile ?? ((target: string) => fs.readFile(target, 'utf8'));
491
+ return reader(file);
492
+ }
493
+ if (content.startsWith('\\@')) {
494
+ return content.slice(1);
495
+ }
496
+ return content;
429
497
  }