@hydranium/cli 1.0.0-next.8 → 1.0.0-next.85

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 (77) hide show
  1. package/README.md +14 -0
  2. package/lib/commands/analyze-heap.d.ts +3 -0
  3. package/lib/commands/analyze-heap.d.ts.map +1 -1
  4. package/lib/commands/analyze-heap.js +2 -1
  5. package/lib/commands/analyze-heap.js.map +1 -1
  6. package/lib/commands/ast-ground-truth.js +1 -1
  7. package/lib/commands/ast-ground-truth.js.map +1 -1
  8. package/lib/commands/generate-ast-builder.d.ts +49 -0
  9. package/lib/commands/generate-ast-builder.d.ts.map +1 -0
  10. package/lib/commands/generate-ast-builder.js +200 -0
  11. package/lib/commands/generate-ast-builder.js.map +1 -0
  12. package/lib/commands/generate-transfer-model-args.d.ts.map +1 -1
  13. package/lib/commands/generate-transfer-model-args.js +11 -1
  14. package/lib/commands/generate-transfer-model-args.js.map +1 -1
  15. package/lib/commands/generate-transfer-model-config.d.ts.map +1 -1
  16. package/lib/commands/generate-transfer-model-config.js +3 -1
  17. package/lib/commands/generate-transfer-model-config.js.map +1 -1
  18. package/lib/commands/generate-transfer-model.d.ts +9 -0
  19. package/lib/commands/generate-transfer-model.d.ts.map +1 -1
  20. package/lib/commands/generate-transfer-model.js +16 -3
  21. package/lib/commands/generate-transfer-model.js.map +1 -1
  22. package/lib/commands/headless-harness.d.ts +18 -3
  23. package/lib/commands/headless-harness.d.ts.map +1 -1
  24. package/lib/commands/headless-harness.js +12 -4
  25. package/lib/commands/headless-harness.js.map +1 -1
  26. package/lib/commands/init-templates.d.ts +0 -9
  27. package/lib/commands/init-templates.d.ts.map +1 -1
  28. package/lib/commands/init-templates.js +49 -35
  29. package/lib/commands/init-templates.js.map +1 -1
  30. package/lib/commands/init.d.ts.map +1 -1
  31. package/lib/commands/init.js +2 -6
  32. package/lib/commands/init.js.map +1 -1
  33. package/lib/commands/lint-grammar.js +1 -1
  34. package/lib/commands/lint-grammar.js.map +1 -1
  35. package/lib/commands/measure-memory-driver.js +3 -2
  36. package/lib/commands/measure-memory-driver.js.map +1 -1
  37. package/lib/commands/measure-memory.js +1 -1
  38. package/lib/commands/measure-memory.js.map +1 -1
  39. package/lib/commands/model-docs.js +1 -1
  40. package/lib/commands/model-docs.js.map +1 -1
  41. package/lib/commands/reflect.js +1 -1
  42. package/lib/commands/reflect.js.map +1 -1
  43. package/lib/commands/save.js +2 -2
  44. package/lib/commands/save.js.map +1 -1
  45. package/lib/commands/validate.js +1 -1
  46. package/lib/commands/validate.js.map +1 -1
  47. package/lib/commands/watch.d.ts.map +1 -1
  48. package/lib/commands/watch.js +15 -0
  49. package/lib/commands/watch.js.map +1 -1
  50. package/lib/driver-heap.d.ts +52 -0
  51. package/lib/driver-heap.d.ts.map +1 -0
  52. package/lib/driver-heap.js +51 -0
  53. package/lib/driver-heap.js.map +1 -0
  54. package/lib/index.d.ts +1 -0
  55. package/lib/index.d.ts.map +1 -1
  56. package/lib/index.js +1 -0
  57. package/lib/index.js.map +1 -1
  58. package/package.json +11 -10
  59. package/src/commands/analyze-heap.ts +4 -1
  60. package/src/commands/ast-ground-truth.ts +1 -1
  61. package/src/commands/generate-ast-builder.ts +246 -0
  62. package/src/commands/generate-transfer-model-args.ts +11 -1
  63. package/src/commands/generate-transfer-model-config.ts +3 -1
  64. package/src/commands/generate-transfer-model.ts +25 -3
  65. package/src/commands/headless-harness.ts +22 -4
  66. package/src/commands/init-templates.ts +49 -36
  67. package/src/commands/init.ts +2 -8
  68. package/src/commands/lint-grammar.ts +1 -1
  69. package/src/commands/measure-memory-driver.ts +3 -2
  70. package/src/commands/measure-memory.ts +1 -1
  71. package/src/commands/model-docs.ts +1 -1
  72. package/src/commands/reflect.ts +1 -1
  73. package/src/commands/save.ts +2 -2
  74. package/src/commands/validate.ts +1 -1
  75. package/src/commands/watch.ts +21 -1
  76. package/src/driver-heap.ts +65 -0
  77. package/src/index.ts +1 -0
@@ -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;
@@ -12,7 +12,7 @@ import * as path from 'node:path';
12
12
  import type { GenerateTransferModelOptions } from './generate-transfer-model.js';
13
13
 
14
14
  /** Path-valued option keys — resolved relative to a config/langium-config file's directory. */
15
- const PATH_KEYS = ['astFile', 'augmentationFile', 'outFile'] as const;
15
+ const PATH_KEYS = ['astFile', 'augmentationFile', 'outFile', 'astBuilderFile'] as const;
16
16
 
17
17
  /** Resolve `value` against `baseDir` when it is relative; absolute paths pass through. */
18
18
  function resolveAgainst(baseDir: string, value: string): string {
@@ -43,6 +43,7 @@ export function loadTransferModelConfig(configPath: string): Partial<GenerateTra
43
43
  'astFile',
44
44
  'augmentationFile',
45
45
  'outFile',
46
+ 'astBuilderFile',
46
47
  'elementTypeName',
47
48
  'terminalsName',
48
49
  'terminalsSourceName',
@@ -118,6 +119,7 @@ export function mergeTransferModelOptions(...sources: Array<Partial<GenerateTran
118
119
  astFile: astFile!,
119
120
  augmentationFile: augmentationFile!,
120
121
  outFile: outFile!,
122
+ astBuilderFile: pick('astBuilderFile'),
121
123
  elementTypeName: pick('elementTypeName'),
122
124
  terminalsName: pick('terminalsName'),
123
125
  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,
@@ -35,6 +36,15 @@ export interface GenerateTransferModelOptions {
35
36
  augmentationFile: string;
36
37
  /** Destination path for the generated transfer model. */
37
38
  outFile: string;
39
+ /**
40
+ * Destination for a generated AST-node builder module. Omitted by consumers
41
+ * that construct no AST nodes; the transfer model is emitted either way.
42
+ *
43
+ * Emitted from this command rather than its own because the AST source is
44
+ * already parsed here, and because a consumer that regenerates one artefact
45
+ * and not the other has the two disagreeing about the same grammar.
46
+ */
47
+ astBuilderFile?: string;
38
48
  /** Name used for the base element type in the output. Defaults to `TransferElement`. */
39
49
  elementTypeName?: string;
40
50
  /** Name used for the terminal-patterns const in the output. Defaults to `ModelTerminals`. */
@@ -396,10 +406,22 @@ export function generateTransferModel(options: GenerateTransferModelOptions): vo
396
406
  fs.mkdirSync(path.dirname(options.outFile), { recursive: true });
397
407
  if (fs.existsSync(options.outFile) && fs.readFileSync(options.outFile, 'utf-8') === content) {
398
408
  console.log('Transfer model is up to date.');
399
- return;
409
+ } else {
410
+ fs.writeFileSync(options.outFile, content, 'utf-8');
411
+ console.log(`Generated: ${options.outFile}`);
412
+ }
413
+
414
+ if (options.astBuilderFile !== undefined) {
415
+ const emitted = emitAstBuilder(astSource, {
416
+ outFile: options.astBuilderFile,
417
+ astFile: options.astFile,
418
+ languageId,
419
+ regenCommand
420
+ });
421
+ if (!emitted) {
422
+ console.warn(`Warning: no '${languageId}AstType' alias in ${options.astFile}; skipping the AST builder.`);
423
+ }
400
424
  }
401
- fs.writeFileSync(options.outFile, content, 'utf-8');
402
- console.log(`Generated: ${options.outFile}`);
403
425
  }
404
426
 
405
427
  // ---------------------------------------------------------------------------
@@ -14,6 +14,7 @@ import { statSync, writeFileSync } from 'node:fs';
14
14
  import { createRequire } from 'node:module';
15
15
  import * as path from 'node:path';
16
16
  import { pathToFileURL } from 'node:url';
17
+ import { driverHeapArgs, type HeapReading } from '../driver-heap.js';
17
18
  import { logLevelEnv } from '../log-level.js';
18
19
  import { SERVICES_FLAG } from './harness-args.js';
19
20
 
@@ -47,9 +48,10 @@ export interface HeadlessContext {
47
48
  * ZERO-ARG `createServices(): { shared }`. `hydranium-cli` is language-agnostic
48
49
  * and cannot statically import a head's `create<Lang>Services`, so the dynamic
49
50
  * import is the seam that keeps the binary head-neutral. Resolving the harness
50
- * from the head's graph (via `createRequire` rooted at the head module) means the
51
- * CLI itself needs no `@hydranium/core` dependency the head always has it — and
52
- * guarantees the harness runs against the SAME core copy as `createServices`.
51
+ * from the head's graph (via `createRequire` rooted at the head module) rather
52
+ * than from the CLI's guarantees it runs against the SAME core copy as
53
+ * `createServices`, which a second copy of the module would break even where
54
+ * both resolve.
53
55
  *
54
56
  * Throws a clear error when the path names no file, and when the export is
55
57
  * missing or not a function.
@@ -139,6 +141,13 @@ export interface DriverSpawnOptions {
139
141
  readonly logLevel?: LogThreshold;
140
142
  /** Test-only: capture the node argv and env instead of spawning the real child. */
141
143
  readonly __spawnForTest?: SpawnDriverChild;
144
+ /**
145
+ * Test-only: decide the heap ceiling from a stated cgroup reading rather
146
+ * than the machine's. Without it an argv assertion means one thing on a
147
+ * workstation and nothing at all under a memory limit, so a suite that
148
+ * asserts the ceiling is present passes vacuously in a container.
149
+ */
150
+ readonly __heapReadingForTest?: HeapReading;
142
151
  }
143
152
 
144
153
  /**
@@ -155,10 +164,19 @@ export interface DriverSpawnOptions {
155
164
  * A head that binds a logger of its own decides for itself whether the flag means
156
165
  * anything, which is the intended seam: the CLI is language-agnostic and cannot
157
166
  * reach past `createServices`.
167
+ *
168
+ * **The heap ceiling is prepended HERE rather than passed by each subcommand.**
169
+ * Every caller wants the same answer to the same question, and the answer is not
170
+ * a constant — see {@link driverHeapArgs}. A literal at the call site is a place
171
+ * the container case can be missed, and the caller that misses it takes the whole
172
+ * cgroup down with it rather than failing on its own.
158
173
  */
159
174
  export async function runDriverChild(execArgs: string[], options: DriverSpawnOptions): Promise<void> {
160
175
  const spawnChild = options.__spawnForTest ?? spawnNodeChild;
161
- const code = await spawnChild(execArgs, options.logLevel === undefined ? undefined : logLevelEnv(options.logLevel));
176
+ const code = await spawnChild(
177
+ [...driverHeapArgs(options.__heapReadingForTest), ...execArgs],
178
+ options.logLevel === undefined ? undefined : logLevelEnv(options.logLevel)
179
+ );
162
180
  if (code) {
163
181
  process.exitCode = code;
164
182
  }
@@ -82,16 +82,6 @@ export interface InitTemplate {
82
82
  content: string;
83
83
  }
84
84
 
85
- /**
86
- * The version every framework package carries before the first release.
87
- *
88
- * A scaffold made by a CLI still at this version pins a range the registry
89
- * cannot serve, so the emitted README keeps its yalc note and `init` keeps its
90
- * install warning while — and only while — it holds: from a published CLI the
91
- * derived pins resolve and either note would be false as printed.
92
- */
93
- export const UNPUBLISHED_FRAMEWORK_VERSION = '0.0.0';
94
-
95
85
  /**
96
86
  * The version `init` pins every `@hydranium/*` dependency at: the scaffolding
97
87
  * CLI's own.
@@ -310,9 +300,9 @@ __BIN__ },
310
300
  ],
311
301
  "scripts": {
312
302
  "build": "npm run generate && tsc",
313
- "clean": "rimraf lib syntaxes src/language-server/generated src/language-server/generated-transfer tsconfig.tsbuildinfo",
303
+ "clean": "rimraf lib syntaxes src/language-server/generated src/language-server/generated-hydranium tsconfig.tsbuildinfo",
314
304
  "generate": "npm run langium:generate && npm run generate:transfer-model",
315
- "generate:transfer-model": "hydranium-cli generate-transfer-model --ast-file src/language-server/generated/ast.ts --augmentation-file src/language-server/ast.ts --out-file src/language-server/generated-transfer/transfer-model.ts --element-type-name __NAME__Element --terminals-name __NAME__Terminals --regen-command \\"Run: __NPM_RUN__ generate:transfer-model\\"",
305
+ "generate:transfer-model": "hydranium-cli generate-transfer-model --ast-file src/language-server/generated/ast.ts --augmentation-file src/language-server/ast.ts --out-file src/language-server/generated-hydranium/transfer-model.ts --ast-builder-file src/language-server/generated-hydranium/ast-builder.ts --element-type-name __NAME__Element --terminals-name __NAME__Terminals --regen-command \\"Run: __NPM_RUN__ generate:transfer-model\\"",
316
306
  "langium:generate": "langium generate",
317
307
  "langium:watch": "langium generate --watch",
318
308
  __LINT__ "start": "node lib/main.js --stdio",
@@ -439,6 +429,11 @@ const TSCONFIG_COMPILER_OPTIONS: ReadonlyArray<readonly [string, JsonValue]> = [
439
429
  ['outDir', 'lib'],
440
430
  ['strict', true],
441
431
  ['esModuleInterop', true],
432
+ // A server that renders its own user-facing messages loads a catalogue, and
433
+ // a catalogue is JSON. Without this the import does not resolve at all, and
434
+ // without the `include` glob below a composite project rejects it with
435
+ // TS6307 naming neither cause.
436
+ ['resolveJsonModule', true],
442
437
  ['skipLibCheck', true],
443
438
  ['declaration', true],
444
439
  ['experimentalDecorators', true],
@@ -480,7 +475,7 @@ function tsconfigJson(composition: InitComposition): string {
480
475
  ];
481
476
  const extendsLine = workspace?.baseTsconfig === undefined ? '' : ` "extends": "${workspace.baseTsconfig}",\n`;
482
477
  const body = options.map(([key, value]) => ` "${key}": ${JSON.stringify(value)}`).join(',\n');
483
- return `{\n${extendsLine} "compilerOptions": {\n${body}\n },\n "include": ["src"]\n}\n`;
478
+ return `{\n${extendsLine} "compilerOptions": {\n${body}\n },\n "include": ["src", "src/**/*.json"]\n}\n`;
484
479
  }
485
480
 
486
481
  // `isolatedModules` is what makes this check agree with the transform that
@@ -498,7 +493,7 @@ const TSCONFIG_TEST = `{
498
493
  "isolatedModules": true,
499
494
  "types": ["node"]
500
495
  },
501
- "include": ["src", "test"]
496
+ "include": ["src", "test", "src/**/*.json"]
502
497
  }
503
498
  `;
504
499
 
@@ -708,13 +703,35 @@ export type __NAME__Services = LangiumServices &
708
703
  LspServerAddedServices & {
709
704
  shared: __NAME__SharedServices;
710
705
  };
706
+
707
+ /** What a host or a test may vary about this composition. */
708
+ export interface __NAME__Options {
709
+ /**
710
+ * Shared modules layered in after the framework's own bindings.
711
+ *
712
+ * The framework constructs most shared services with no options —
713
+ * \`DocumentBuilder: services => new HydraniumDocumentBuilder(services)\` — so
714
+ * rebinding the slot is the only way to boot one configured differently, and
715
+ * a factory that hard-codes its composition leaves a test nowhere to do it.
716
+ * That is what this is for: pass a module binding \`workspace.DocumentBuilder\`
717
+ * to exercise a builder option, or to substitute a subclass.
718
+ *
719
+ * Composed LAST, after \`__NAME__SharedModule\`, so it wins over every other
720
+ * tier including this file's own bindings — which is what makes it usable for
721
+ * a slot the adopter overrides. Production code should not reach for it.
722
+ */
723
+ readonly extraSharedModules?: ReadonlyArray<Module<__NAME__SharedServices, DeepPartial<__NAME__SharedServices>>>;
724
+ }
711
725
  ${configurationRoot}
712
726
  ${sharedModule}
713
727
 
714
728
  ${languageModules}
715
729
 
716
730
  /** Compose the Langium DI tree for __NAME__ — returns the shared + language services. */
717
- export function create__NAME__Services(context: Partial<ServerModuleContext> = EmptyFileSystem): {
731
+ export function create__NAME__Services(
732
+ context: Partial<ServerModuleContext> = EmptyFileSystem,
733
+ options: __NAME__Options = {}
734
+ ): {
718
735
  shared: __NAME__SharedServices;
719
736
  ${returnType}
720
737
  } {
@@ -724,7 +741,8 @@ ${returnType}
724
741
  sharedModules: {
725
742
  generated: __NAME__GeneratedSharedModule,
726
743
  adopter: __NAME__SharedModule,
727
- extra: [createLspServerSharedModule(fullContext)]
744
+ extra: [createLspServerSharedModule(fullContext)],
745
+ overrides: options.extraSharedModules
728
746
  },
729
747
  languageModules: {
730
748
  generated: ${primary.grammar}GeneratedModule,
@@ -980,7 +998,7 @@ import { startGlspServer } from '@hydranium/glsp-server/node';
980
998
  // \`TransferElement\` structurally, so naming the AST type here compiles fine and
981
999
  // silently tells every typed client that a reference is a resolvable object
982
1000
  // rather than a name.
983
- ${importList(roots, './language-server/generated-transfer/transfer-model.js', columns, true)}
1001
+ ${importList(roots, './language-server/generated-hydranium/transfer-model.js', columns, true)}
984
1002
  `
985
1003
  : '';
986
1004
 
@@ -1063,7 +1081,13 @@ void glspServer;
1063
1081
  // than a library entry — import \`./index.js\` instead to compose the language.
1064
1082
 
1065
1083
  ${reflectImport}${glspImports}${importList(coreNodeSymbols, '@hydranium/core/node', columns)}
1066
- ${data ? "import { DataServer } from '@hydranium/data-server';\n" : ''}import { startLanguageServer } from '@hydranium/langium/lsp';
1084
+ ${data ? "import { DataServer } from '@hydranium/data-server';\n" : ''}// The framework's entry point, NOT Langium's \`@hydranium/langium/lsp\` one. It is
1085
+ // signature-compatible and delegates straight through; what it adds first is
1086
+ // \`assertLspHeadComposed\`, which fails the start if the LSP head's SHARED module
1087
+ // was never composed. Reaching for Langium's is the natural mistake and it is
1088
+ // silent: the server boots, links and completes, while echo suppression, the
1089
+ // didChangeContent debounce and the last-client-close rebuild are all inert.
1090
+ import { startLanguageServer } from '@hydranium/core/lsp';
1067
1091
  import { ProposedFeatures, createConnection } from 'vscode-languageserver/node';
1068
1092
  ${diagramImports}${transferImports}import { create__NAME__Services } from './language-server/__PROJECT_ID__-module.js';
1069
1093
  ${portCommands === '' ? '' : '\n' + portCommands}
@@ -1117,7 +1141,7 @@ function dataServerMainFile(composition: InitComposition): string {
1117
1141
  ${importList(['NodeFileSystem', 'startStdioServer'], '@hydranium/core/node', columns)}
1118
1142
  import { DataServer } from '@hydranium/data-server';
1119
1143
  // The TRANSFER root${plural}, not the AST one${plural} — same reasoning as \`main.ts\`.
1120
- ${importList(roots, './language-server/generated-transfer/transfer-model.js', columns, true)}
1144
+ ${importList(roots, './language-server/generated-hydranium/transfer-model.js', columns, true)}
1121
1145
  import { create__NAME__Services } from './language-server/__PROJECT_ID__-module.js';
1122
1146
 
1123
1147
  const { shared } = create__NAME__Services({ ...NodeFileSystem });
@@ -1247,7 +1271,7 @@ function serializationTest(composition: InitComposition): string {
1247
1271
  import { parseHelper } from '@hydranium/core/testing';
1248
1272
  import { describe, expect, it } from 'vitest';
1249
1273
  ${importList(astTypes, '../src/language-server/ast.js', columns, true)}
1250
- ${importList(transferTypes, '../src/language-server/generated-transfer/transfer-model.js', columns, true)}
1274
+ ${importList(transferTypes, '../src/language-server/generated-hydranium/transfer-model.js', columns, true)}
1251
1275
  import { createServices } from '../src/services.js';
1252
1276
 
1253
1277
  ${composition.grammars.map(grammar => render(SERIALIZATION_SUITE, composition, grammar)).join('\n\n')}
@@ -1416,20 +1440,6 @@ function readme(composition: InitComposition): string {
1416
1440
  '',
1417
1441
  '## Getting started',
1418
1442
  '',
1419
- // Conditional on the pin this scaffold actually carries — see
1420
- // `UNPUBLISHED_FRAMEWORK_VERSION`.
1421
- ...(composition.frameworkVersion === UNPUBLISHED_FRAMEWORK_VERSION
1422
- ? [
1423
- '> **Pre-publish note.** `@hydranium/*` is not on npm yet, so the `0.0.0`',
1424
- '> pins below are placeholders and `npm install` will fail with a 404 until',
1425
- '> the framework is released. Until then, supply the packages from a local',
1426
- '> framework checkout with [yalc](https://github.com/wclr/yalc) — a plain',
1427
- '> `file:` path or `npm link` is not enough, because the framework packages',
1428
- '> depend on each other by version and npm would try to fetch those from the',
1429
- '> registry too.',
1430
- ''
1431
- ]
1432
- : []),
1433
1443
  '```bash',
1434
1444
  'npm install',
1435
1445
  'npm run langium:generate # generate the AST from the grammar',
@@ -1633,8 +1643,11 @@ export class __GRAMMAR__GlspState extends FullTextHydraniumGlspState<__ENTRY_RUL
1633
1643
 
1634
1644
  const storage = `// Source-model storage for the __GRAMMAR__ diagram, inheriting both framework
1635
1645
  // defaults: \`loadSourceModel\` (open + settle + \`setSourceRoot\`) and
1636
- // \`saveSourceModel\` (through \`ModelService.save\` the per-URI \`Serializer\`
1637
- // the multi-client text store → \`WritableFileSystemProvider\`).
1646
+ // \`saveSourceModel\` (flush the store's text for the primary and every tracked
1647
+ // secondary through \`AstDocumentManager.save\` → \`WritableFileSystemProvider\`).
1648
+ //
1649
+ // No serializer runs on the save path — a save persists what the diagram's
1650
+ // operations already wrote to the store.
1638
1651
  //
1639
1652
  // The subclass exists so a bespoke load or save has a stable place to land.
1640
1653
 
@@ -9,7 +9,7 @@
9
9
 
10
10
  import * as fs from 'node:fs';
11
11
  import * as path from 'node:path';
12
- import { buildInitTemplates, readFrameworkVersion, UNPUBLISHED_FRAMEWORK_VERSION } from './init-templates.js';
12
+ import { buildInitTemplates, readFrameworkVersion } from './init-templates.js';
13
13
  import { createNodeWorkspaceProbe, detectWorkspace, type JsonValue, type WorkspaceProbe } from './init-workspace.js';
14
14
 
15
15
  /**
@@ -536,13 +536,7 @@ export function runInit(options: InitCommandOptions): void {
536
536
  write('\n');
537
537
  write('Next steps:\n');
538
538
  write(` cd ${options.targetDir}\n`);
539
- // The warning is conditional on the pins this scaffold actually carries — see
540
- // `UNPUBLISHED_FRAMEWORK_VERSION`.
541
- write(
542
- composition.frameworkVersion === UNPUBLISHED_FRAMEWORK_VERSION
543
- ? ' npm install # 404s until @hydranium/* is published — see README\n'
544
- : ' npm install\n'
545
- );
539
+ write(' npm install\n');
546
540
  write(' npm run build # langium generate + tsc\n');
547
541
  write(' npm test # the scaffolded DI-composition test\n');
548
542
  // `npx`, not a bare invocation: `@hydranium/cli` is a devDependency of the
@@ -53,5 +53,5 @@ export function buildLintGrammarDriverArgs(options: LintGrammarCommandOptions):
53
53
  * `createServices` module, keeping the binary language-agnostic.
54
54
  */
55
55
  export function runLintGrammar(options: LintGrammarCommandOptions): Promise<void> {
56
- return runDriverChild(['--max-old-space-size=8192', DRIVER, ...buildLintGrammarDriverArgs(options)], options);
56
+ return runDriverChild([DRIVER, ...buildLintGrammarDriverArgs(options)], options);
57
57
  }
@@ -9,8 +9,9 @@
9
9
 
10
10
  /*
11
11
  * Spawned child of the `measure-memory` subcommand. Launched by the parent with
12
- * `node --expose-gc --max-old-space-size=8192 <this> --services <module> <workspace> ...`
13
- * so the underlying harness gets post-GC readings. It dynamic-imports the head's
12
+ * `node [heap ceiling] --expose-gc <this> --services <module> <workspace> ...`
13
+ * so the underlying harness gets post-GC readings. The ceiling is whatever
14
+ * `driverHeapArgs` decides, which is nothing at all inside a container. It dynamic-imports the head's
14
15
  * services module and runs the framework's `measureModelMemory`, streaming the
15
16
  * baseline / after-build / churn lines to stdout. Never imported — only spawned.
16
17
  */
@@ -139,5 +139,5 @@ export function buildDriverArgs(options: MeasureMemoryCommandOptions): string[]
139
139
  * module and reports the baseline / after-build / churn lines on stdout.
140
140
  */
141
141
  export function runMeasureMemory(options: MeasureMemoryCommandOptions): Promise<void> {
142
- return runDriverChild(['--expose-gc', '--max-old-space-size=8192', DRIVER, ...buildDriverArgs(options)], options);
142
+ return runDriverChild(['--expose-gc', DRIVER, ...buildDriverArgs(options)], options);
143
143
  }
@@ -44,5 +44,5 @@ export function buildModelDocsDriverArgs(options: ModelDocsCommandOptions): stri
44
44
  * module, keeping the binary language-agnostic.
45
45
  */
46
46
  export function runModelDocs(options: ModelDocsCommandOptions): Promise<void> {
47
- return runDriverChild(['--max-old-space-size=8192', DRIVER, ...buildModelDocsDriverArgs(options)], options);
47
+ return runDriverChild([DRIVER, ...buildModelDocsDriverArgs(options)], options);
48
48
  }