@hydranium/cli 1.0.0-next.24 → 1.0.0-next.241

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 (179) hide show
  1. package/README.md +39 -18
  2. package/bin/hydranium-cli.js +13 -0
  3. package/lib/cli-version.js.map +1 -1
  4. package/lib/cli.js +0 -0
  5. package/lib/commands/analyze-heap-args.js.map +1 -1
  6. package/lib/commands/analyze-heap.d.ts +3 -0
  7. package/lib/commands/analyze-heap.d.ts.map +1 -1
  8. package/lib/commands/analyze-heap.js +2 -1
  9. package/lib/commands/analyze-heap.js.map +1 -1
  10. package/lib/commands/ast-ground-truth-args.d.ts +3 -2
  11. package/lib/commands/ast-ground-truth-args.d.ts.map +1 -1
  12. package/lib/commands/ast-ground-truth-args.js +11 -9
  13. package/lib/commands/ast-ground-truth-args.js.map +1 -1
  14. package/lib/commands/ast-ground-truth.js +1 -1
  15. package/lib/commands/ast-ground-truth.js.map +1 -1
  16. package/lib/commands/generate-ast-builder.d.ts +49 -0
  17. package/lib/commands/generate-ast-builder.d.ts.map +1 -0
  18. package/lib/commands/generate-ast-builder.js +200 -0
  19. package/lib/commands/generate-ast-builder.js.map +1 -0
  20. package/lib/commands/generate-transfer-model-args.d.ts.map +1 -1
  21. package/lib/commands/generate-transfer-model-args.js +11 -1
  22. package/lib/commands/generate-transfer-model-args.js.map +1 -1
  23. package/lib/commands/generate-transfer-model-config.d.ts.map +1 -1
  24. package/lib/commands/generate-transfer-model-config.js +3 -1
  25. package/lib/commands/generate-transfer-model-config.js.map +1 -1
  26. package/lib/commands/generate-transfer-model.d.ts +9 -0
  27. package/lib/commands/generate-transfer-model.d.ts.map +1 -1
  28. package/lib/commands/generate-transfer-model.js +16 -3
  29. package/lib/commands/generate-transfer-model.js.map +1 -1
  30. package/lib/commands/harness-args.d.ts +37 -42
  31. package/lib/commands/harness-args.d.ts.map +1 -1
  32. package/lib/commands/harness-args.js +65 -25
  33. package/lib/commands/harness-args.js.map +1 -1
  34. package/lib/commands/headless-harness.d.ts +37 -20
  35. package/lib/commands/headless-harness.d.ts.map +1 -1
  36. package/lib/commands/headless-harness.js +68 -17
  37. package/lib/commands/headless-harness.js.map +1 -1
  38. package/lib/commands/init-args.js +6 -6
  39. package/lib/commands/init-args.js.map +1 -1
  40. package/lib/commands/init-prompt.d.ts.map +1 -1
  41. package/lib/commands/init-templates.d.ts +8 -10
  42. package/lib/commands/init-templates.d.ts.map +1 -1
  43. package/lib/commands/init-templates.js +245 -140
  44. package/lib/commands/init-templates.js.map +1 -1
  45. package/lib/commands/init-wizard.js +4 -4
  46. package/lib/commands/init-wizard.js.map +1 -1
  47. package/lib/commands/init-workspace.d.ts +13 -3
  48. package/lib/commands/init-workspace.d.ts.map +1 -1
  49. package/lib/commands/init-workspace.js +21 -6
  50. package/lib/commands/init-workspace.js.map +1 -1
  51. package/lib/commands/init.d.ts +16 -10
  52. package/lib/commands/init.d.ts.map +1 -1
  53. package/lib/commands/init.js +17 -15
  54. package/lib/commands/init.js.map +1 -1
  55. package/lib/commands/lint-grammar-args.d.ts +3 -2
  56. package/lib/commands/lint-grammar-args.d.ts.map +1 -1
  57. package/lib/commands/lint-grammar-args.js +13 -10
  58. package/lib/commands/lint-grammar-args.js.map +1 -1
  59. package/lib/commands/lint-grammar-report.js.map +1 -1
  60. package/lib/commands/lint-grammar.js +1 -1
  61. package/lib/commands/lint-grammar.js.map +1 -1
  62. package/lib/commands/measure-memory-args.d.ts +3 -2
  63. package/lib/commands/measure-memory-args.d.ts.map +1 -1
  64. package/lib/commands/measure-memory-args.js +20 -10
  65. package/lib/commands/measure-memory-args.js.map +1 -1
  66. package/lib/commands/measure-memory-driver.js +3 -2
  67. package/lib/commands/measure-memory-driver.js.map +1 -1
  68. package/lib/commands/measure-memory.js +1 -1
  69. package/lib/commands/measure-memory.js.map +1 -1
  70. package/lib/commands/model-docs-args.d.ts +4 -3
  71. package/lib/commands/model-docs-args.d.ts.map +1 -1
  72. package/lib/commands/model-docs-args.js +12 -10
  73. package/lib/commands/model-docs-args.js.map +1 -1
  74. package/lib/commands/model-docs.js +1 -1
  75. package/lib/commands/model-docs.js.map +1 -1
  76. package/lib/commands/projects-args.d.ts.map +1 -1
  77. package/lib/commands/projects-args.js +5 -5
  78. package/lib/commands/projects-args.js.map +1 -1
  79. package/lib/commands/projects.d.ts +3 -4
  80. package/lib/commands/projects.d.ts.map +1 -1
  81. package/lib/commands/projects.js +2 -2
  82. package/lib/commands/projects.js.map +1 -1
  83. package/lib/commands/query-args.d.ts.map +1 -1
  84. package/lib/commands/query-args.js +5 -5
  85. package/lib/commands/query-args.js.map +1 -1
  86. package/lib/commands/query.d.ts +3 -4
  87. package/lib/commands/query.d.ts.map +1 -1
  88. package/lib/commands/query.js +2 -2
  89. package/lib/commands/query.js.map +1 -1
  90. package/lib/commands/reflect-args.d.ts +3 -2
  91. package/lib/commands/reflect-args.d.ts.map +1 -1
  92. package/lib/commands/reflect-args.js +13 -10
  93. package/lib/commands/reflect-args.js.map +1 -1
  94. package/lib/commands/reflect-report.js.map +1 -1
  95. package/lib/commands/reflect.js +1 -1
  96. package/lib/commands/reflect.js.map +1 -1
  97. package/lib/commands/save-args.d.ts.map +1 -1
  98. package/lib/commands/save-args.js +6 -4
  99. package/lib/commands/save-args.js.map +1 -1
  100. package/lib/commands/save.d.ts +8 -4
  101. package/lib/commands/save.d.ts.map +1 -1
  102. package/lib/commands/save.js +31 -6
  103. package/lib/commands/save.js.map +1 -1
  104. package/lib/commands/validate-args.d.ts +3 -2
  105. package/lib/commands/validate-args.d.ts.map +1 -1
  106. package/lib/commands/validate-args.js +13 -10
  107. package/lib/commands/validate-args.js.map +1 -1
  108. package/lib/commands/validate-report.js.map +1 -1
  109. package/lib/commands/validate.js +1 -1
  110. package/lib/commands/validate.js.map +1 -1
  111. package/lib/commands/watch-args.d.ts.map +1 -1
  112. package/lib/commands/watch-args.js +6 -4
  113. package/lib/commands/watch-args.js.map +1 -1
  114. package/lib/commands/watch.d.ts +3 -4
  115. package/lib/commands/watch.d.ts.map +1 -1
  116. package/lib/commands/watch.js +20 -2
  117. package/lib/commands/watch.js.map +1 -1
  118. package/lib/driver-heap.d.ts +52 -0
  119. package/lib/driver-heap.d.ts.map +1 -0
  120. package/lib/driver-heap.js +51 -0
  121. package/lib/driver-heap.js.map +1 -0
  122. package/lib/index.d.ts +1 -0
  123. package/lib/index.d.ts.map +1 -1
  124. package/lib/index.js +1 -0
  125. package/lib/index.js.map +1 -1
  126. package/lib/log-level.d.ts +21 -11
  127. package/lib/log-level.d.ts.map +1 -1
  128. package/lib/log-level.js +25 -14
  129. package/lib/log-level.js.map +1 -1
  130. package/lib/spawn-data-server.d.ts +6 -1
  131. package/lib/spawn-data-server.d.ts.map +1 -1
  132. package/lib/spawn-data-server.js +2 -1
  133. package/lib/spawn-data-server.js.map +1 -1
  134. package/lib/stderr-connection-logger.d.ts +12 -0
  135. package/lib/stderr-connection-logger.d.ts.map +1 -0
  136. package/lib/stderr-connection-logger.js +16 -0
  137. package/lib/stderr-connection-logger.js.map +1 -0
  138. package/lib/testing/echo-server.js +8 -1
  139. package/lib/testing/echo-server.js.map +1 -1
  140. package/package.json +39 -39
  141. package/src/commands/analyze-heap.ts +4 -1
  142. package/src/commands/ast-ground-truth-args.ts +15 -12
  143. package/src/commands/ast-ground-truth.ts +1 -1
  144. package/src/commands/generate-ast-builder.ts +246 -0
  145. package/src/commands/generate-transfer-model-args.ts +11 -1
  146. package/src/commands/generate-transfer-model-config.ts +3 -1
  147. package/src/commands/generate-transfer-model.ts +25 -3
  148. package/src/commands/harness-args.ts +73 -28
  149. package/src/commands/headless-harness.ts +86 -26
  150. package/src/commands/init-args.ts +6 -6
  151. package/src/commands/init-templates.ts +255 -142
  152. package/src/commands/init-wizard.ts +4 -4
  153. package/src/commands/init-workspace.ts +31 -7
  154. package/src/commands/init.ts +36 -26
  155. package/src/commands/lint-grammar-args.ts +17 -13
  156. package/src/commands/lint-grammar.ts +1 -1
  157. package/src/commands/measure-memory-args.ts +25 -13
  158. package/src/commands/measure-memory-driver.ts +3 -2
  159. package/src/commands/measure-memory.ts +1 -1
  160. package/src/commands/model-docs-args.ts +16 -13
  161. package/src/commands/model-docs.ts +1 -1
  162. package/src/commands/projects-args.ts +5 -4
  163. package/src/commands/projects.ts +4 -6
  164. package/src/commands/query-args.ts +5 -4
  165. package/src/commands/query.ts +4 -6
  166. package/src/commands/reflect-args.ts +17 -13
  167. package/src/commands/reflect.ts +1 -1
  168. package/src/commands/save-args.ts +6 -3
  169. package/src/commands/save.ts +49 -10
  170. package/src/commands/validate-args.ts +17 -13
  171. package/src/commands/validate.ts +1 -1
  172. package/src/commands/watch-args.ts +6 -3
  173. package/src/commands/watch.ts +28 -7
  174. package/src/driver-heap.ts +65 -0
  175. package/src/index.ts +1 -0
  176. package/src/log-level.ts +42 -14
  177. package/src/spawn-data-server.ts +14 -2
  178. package/src/stderr-connection-logger.ts +18 -0
  179. package/src/testing/echo-server.ts +10 -2
@@ -7,9 +7,9 @@
7
7
  * SPDX-License-Identifier: MIT
8
8
  ********************************************************************************/
9
9
 
10
- import type { LogThreshold, TransferElement } from '@hydranium/protocol';
10
+ import type { TransferElement } from '@hydranium/protocol';
11
11
  import type { DataServerProtocol } from '@hydranium/protocol/data';
12
- import { logLevelEnv } from '../log-level.js';
12
+ import { logEnv, type LogOptions } from '../log-level.js';
13
13
  import { withDataServer } from '../spawn-data-server.js';
14
14
 
15
15
  /**
@@ -22,12 +22,10 @@ import { withDataServer } from '../spawn-data-server.js';
22
22
  * Test-only `__proxyForTest` bypasses the spawn for unit tests; the
23
23
  * production CLI never passes it.
24
24
  */
25
- export interface QueryCommandOptions {
25
+ export interface QueryCommandOptions extends LogOptions {
26
26
  readonly serverCommand: string;
27
27
  readonly serverArgs?: readonly string[];
28
28
  readonly cwd?: string;
29
- /** Log threshold for the spawned server, set on its `HYDRANIUM_LOG_LEVEL` env. */
30
- readonly logLevel?: LogThreshold;
31
29
  readonly uri: string;
32
30
  readonly write?: (line: string) => void;
33
31
  readonly __proxyForTest?: DataServerProtocol<TransferElement>;
@@ -48,7 +46,7 @@ export async function runQuery(options: QueryCommandOptions): Promise<void> {
48
46
  command: options.serverCommand,
49
47
  args: options.serverArgs,
50
48
  cwd: options.cwd,
51
- env: options.logLevel ? logLevelEnv(options.logLevel) : undefined
49
+ env: logEnv(options)
52
50
  },
53
51
  async server => {
54
52
  const doc = await server.getModelDocument({ uri: options.uri, includeDiagnostics: true });
@@ -9,34 +9,36 @@
9
9
 
10
10
  import {
11
11
  exitWithUsage,
12
+ HARNESS_VALUE_FLAGS,
12
13
  helpRequested,
13
- LOG_LEVEL_FLAG,
14
- logLevelHelpLine,
15
- logLevelOption,
14
+ importHelpLines,
15
+ LOG_VALUE_FLAGS,
16
+ logHelpLines,
17
+ logOptions,
16
18
  parseHarnessArgs,
17
19
  printHelp,
18
- SERVICES_FLAG,
19
20
  type UsageError
20
21
  } from './harness-args.js';
21
22
  import { OUT_FILE_FLAG } from './headless-harness.js';
22
23
  import { runReflect, type ReflectCommandOptions } from './reflect.js';
23
24
 
24
- const VALUE_FLAGS = [OUT_FILE_FLAG, LOG_LEVEL_FLAG] as const;
25
+ const VALUE_FLAGS = [OUT_FILE_FLAG, ...LOG_VALUE_FLAGS] as const;
25
26
  const BOOL_FLAGS = ['--json'] as const;
26
27
 
27
28
  /**
28
29
  * Every flag `reflect` accepts, derived from the sets the parser is handed so
29
- * the list cannot claim a flag the parser would reject. `--services` is consumed
30
- * by the shared harness parser itself, so it is in neither set.
30
+ * the list cannot claim a flag the parser would reject.
31
+ * {@link HARNESS_VALUE_FLAGS} are consumed by the shared harness parser itself,
32
+ * so they are in neither set.
31
33
  */
32
- export const REFLECT_FLAGS: readonly string[] = [SERVICES_FLAG, ...VALUE_FLAGS, ...BOOL_FLAGS];
34
+ export const REFLECT_FLAGS: readonly string[] = [...HARNESS_VALUE_FLAGS, ...VALUE_FLAGS, ...BOOL_FLAGS];
33
35
 
34
36
  /** The subset that takes a value, so `--help` in a value position reads as data. */
35
- export const REFLECT_VALUE_FLAGS: readonly string[] = [SERVICES_FLAG, ...VALUE_FLAGS];
37
+ export const REFLECT_VALUE_FLAGS: readonly string[] = [...HARNESS_VALUE_FLAGS, ...VALUE_FLAGS];
36
38
 
37
39
  /** The `--help` text, as data, held to {@link REFLECT_FLAGS} by a test. */
38
40
  export const REFLECT_HELP: readonly string[] = [
39
- 'Usage: hydranium-cli reflect --services <module> [--json] [--out-file <file>] [--log-level <lvl>]',
41
+ 'Usage: hydranium-cli reflect --services <module> [--import <specifier>]... [--json] [--out-file <file>] [--log-level <lvl>] [--log-file <file>] [--log-file-level <lvl>]',
40
42
  '',
41
43
  "Dump a head's grammar/AST reflection — the type hierarchy, each language's",
42
44
  'terminals and entry rule, and every cross-reference target. Read-only: no',
@@ -46,23 +48,25 @@ export const REFLECT_HELP: readonly string[] = [
46
48
  '',
47
49
  'Options:',
48
50
  ' --services <module> ESM module exporting `createServices(): { shared }` (required).',
51
+ ...importHelpLines(22),
49
52
  ' --json Emit the raw JSON reflection instead of the Markdown report.',
50
53
  ' --out-file <file> Write the report to this file instead of stdout. Written',
51
54
  ' only once the report exists, unlike a shell redirection,',
52
55
  ' which truncates the file before the head is even booted.',
53
- logLevelHelpLine(22)
56
+ ...logHelpLines(22)
54
57
  ];
55
58
 
56
59
  export function parseReflectArgs(args: string[], onError: UsageError = exitWithUsage): ReflectCommandOptions {
57
- const { servicesModule, options } = parseHarnessArgs(args, 'reflect', VALUE_FLAGS, BOOL_FLAGS, {
60
+ const { servicesModule, imports, options } = parseHarnessArgs(args, 'reflect', VALUE_FLAGS, BOOL_FLAGS, {
58
61
  requireWorkspace: false,
59
62
  onError
60
63
  });
61
64
  return {
62
65
  servicesModule,
66
+ imports,
63
67
  json: options['--json'] === 'true',
64
68
  outFile: options[OUT_FILE_FLAG],
65
- logLevel: logLevelOption(options[LOG_LEVEL_FLAG])
69
+ ...logOptions(options)
66
70
  };
67
71
  }
68
72
 
@@ -47,5 +47,5 @@ export function buildReflectDriverArgs(options: ReflectCommandOptions): string[]
47
47
  * the binary language-agnostic.
48
48
  */
49
49
  export function runReflect(options: ReflectCommandOptions): Promise<void> {
50
- return runDriverChild(['--max-old-space-size=8192', DRIVER, ...buildReflectDriverArgs(options)], options);
50
+ return runDriverChild([DRIVER, ...buildReflectDriverArgs(options)], options);
51
51
  }
@@ -11,6 +11,7 @@ import {
11
11
  assertRequired,
12
12
  exitWithUsage,
13
13
  helpRequested,
14
+ logHelpLines,
14
15
  parseFlagOptions,
15
16
  parseServerSpawnOptions,
16
17
  printHelp,
@@ -36,7 +37,7 @@ export const SAVE_VALUE_FLAGS: readonly string[] = SAVE_FLAGS;
36
37
 
37
38
  /** The `--help` text, as data, held to {@link SAVE_FLAGS} by a test. */
38
39
  export const SAVE_HELP: readonly string[] = [
39
- 'Usage: hydranium-cli save --server "<cmd>..." --uri <uri> --content <text|@file> [--client-id <id>] [--cwd <dir>] [--log-level <level>]',
40
+ 'Usage: hydranium-cli save --server "<cmd>..." --uri <uri> --content <text|@file> [--client-id <id>] [--cwd <dir>] [--log-level <lvl>] [--log-file <file>] [--log-file-level <lvl>]',
40
41
  '',
41
42
  'Update the document at `<uri>` with `<content>` and persist via saveModelDocument.',
42
43
  'Output is the post-save envelope as a single JSON line.',
@@ -48,17 +49,19 @@ export const SAVE_HELP: readonly string[] = [
48
49
  ' (escape with `\\@` for literal `@`-leading content).',
49
50
  ' --client-id <id> clientId for authorship attribution. Default: hydranium-cli.',
50
51
  ' --cwd <dir> Working directory for the spawned child. Default: cwd.',
51
- ' --log-level <lvl> Log threshold for the spawned server (off|error|warn|info|debug|trace).'
52
+ ...logHelpLines(22, 'the spawned server')
52
53
  ];
53
54
 
54
55
  export function parseSaveArgs(args: string[], onError: UsageError = exitWithUsage): SaveCommandOptions {
55
- const { serverCommand, serverArgs, cwd, logLevel, extra } = parseServerSpawnOptions(args, 'save', onError);
56
+ const { serverCommand, serverArgs, cwd, logLevel, logFile, logFileLevel, extra } = parseServerSpawnOptions(args, 'save', onError);
56
57
  const { uri, content, clientId } = parseFlagOptions(extra, 'save', OWN_FLAGS, onError);
57
58
  return {
58
59
  serverCommand,
59
60
  serverArgs,
60
61
  cwd,
61
62
  logLevel,
63
+ logFile,
64
+ logFileLevel,
62
65
  uri: assertRequired(uri, '--uri', 'save', onError),
63
66
  content: assertRequired(content, '--content', 'save', onError),
64
67
  clientId
@@ -7,10 +7,10 @@
7
7
  * SPDX-License-Identifier: MIT
8
8
  ********************************************************************************/
9
9
 
10
- import type { LogThreshold, TransferElement } from '@hydranium/protocol';
10
+ import type { TransferElement } from '@hydranium/protocol';
11
11
  import type { DataServerProtocol } from '@hydranium/protocol/data';
12
12
  import * as fs from 'node:fs/promises';
13
- import { logLevelEnv } from '../log-level.js';
13
+ import { logEnv, type LogOptions } from '../log-level.js';
14
14
  import { withDataServer } from '../spawn-data-server.js';
15
15
 
16
16
  /**
@@ -23,13 +23,16 @@ import { withDataServer } from '../spawn-data-server.js';
23
23
  *
24
24
  * `clientId` defaults to `'hydranium-cli'` — adopters wanting a richer
25
25
  * identity (per-user, per-script) override.
26
+ *
27
+ * The command saves as a client session under `clientId`: it registers the
28
+ * session, creates the document from the content when there is no file,
29
+ * opens it otherwise, saves, and ends the session, which leaves nothing open
30
+ * behind it.
26
31
  */
27
- export interface SaveCommandOptions {
32
+ export interface SaveCommandOptions extends LogOptions {
28
33
  readonly serverCommand: string;
29
34
  readonly serverArgs?: readonly string[];
30
35
  readonly cwd?: string;
31
- /** Log threshold for the spawned server, set on its `HYDRANIUM_LOG_LEVEL` env. */
32
- readonly logLevel?: LogThreshold;
33
36
  readonly uri: string;
34
37
  /** Literal content text, or `@<path>` to read from a file. */
35
38
  readonly content: string;
@@ -46,8 +49,7 @@ export async function runSave(options: SaveCommandOptions): Promise<void> {
46
49
  const model = await resolveContent(options.content, options.__readFileForTest);
47
50
 
48
51
  if (options.__proxyForTest) {
49
- const doc = await options.__proxyForTest.saveModelDocument({ uri: options.uri, clientId, model });
50
- write(`${JSON.stringify(doc)}\n`);
52
+ write(`${JSON.stringify(await saveOpened(options.__proxyForTest, options.uri, clientId, model))}\n`);
51
53
  return;
52
54
  }
53
55
 
@@ -56,15 +58,52 @@ export async function runSave(options: SaveCommandOptions): Promise<void> {
56
58
  command: options.serverCommand,
57
59
  args: options.serverArgs,
58
60
  cwd: options.cwd,
59
- env: options.logLevel ? logLevelEnv(options.logLevel) : undefined
61
+ env: logEnv(options)
60
62
  },
61
63
  async server => {
62
- const doc = await server.saveModelDocument({ uri: options.uri, clientId, model });
63
- write(`${JSON.stringify(doc)}\n`);
64
+ write(`${JSON.stringify(await saveOpened(server, options.uri, clientId, model))}\n`);
64
65
  }
65
66
  );
66
67
  }
67
68
 
69
+ /**
70
+ * Save `model` to `uri` as the session `clientId`, and end the session whether
71
+ * the save succeeded or not. An end that fails after a failed save is
72
+ * swallowed: the save's error is the one the user needs.
73
+ */
74
+ async function saveOpened(
75
+ server: Pick<
76
+ DataServerProtocol<TransferElement>,
77
+ 'createSession' | 'openModelDocument' | 'createModelDocument' | 'saveModelDocument' | 'closeSession'
78
+ >,
79
+ uri: string,
80
+ clientId: string,
81
+ model: string
82
+ ): Promise<unknown> {
83
+ await server.createSession({ clientId, label: 'hydranium-cli' });
84
+ let saved: unknown;
85
+ try {
86
+ // The server creates a document only when it finds no file and no
87
+ // client has it open; anything else is opened. An open that fails
88
+ // reports why the create failed too, since that may be the real cause.
89
+ await server.createModelDocument({ uri, clientId, text: model }).catch((created: unknown) =>
90
+ server.openModelDocument({ uri, clientId }).catch((opened: unknown) => {
91
+ throw new Error(`Cannot save ${uri}: ${describe(opened)} (creating it failed first: ${describe(created)})`, { cause: created });
92
+ })
93
+ );
94
+ saved = await server.saveModelDocument({ uri, clientId, model, baseVersion: 'any' });
95
+ } catch (error: unknown) {
96
+ await server.closeSession({ clientId }).catch(() => undefined);
97
+ throw error;
98
+ }
99
+ await server.closeSession({ clientId });
100
+ return saved;
101
+ }
102
+
103
+ function describe(error: unknown): string {
104
+ return error instanceof Error ? error.message : String(error);
105
+ }
106
+
68
107
  /**
69
108
  * Resolve the `--content` argument to its textual form. The `@<path>`
70
109
  * prefix reads from a file (parses as UTF-8); anything else is taken
@@ -9,34 +9,36 @@
9
9
 
10
10
  import {
11
11
  exitWithUsage,
12
+ HARNESS_VALUE_FLAGS,
12
13
  helpRequested,
13
- LOG_LEVEL_FLAG,
14
- logLevelHelpLine,
15
- logLevelOption,
14
+ importHelpLines,
15
+ LOG_VALUE_FLAGS,
16
+ logHelpLines,
17
+ logOptions,
16
18
  parseHarnessArgs,
17
19
  printHelp,
18
- SERVICES_FLAG,
19
20
  type UsageError
20
21
  } from './harness-args.js';
21
22
  import { OUT_FILE_FLAG } from './headless-harness.js';
22
23
  import { runValidate, type ValidateCommandOptions } from './validate.js';
23
24
 
24
- const VALUE_FLAGS = [OUT_FILE_FLAG, LOG_LEVEL_FLAG] as const;
25
+ const VALUE_FLAGS = [OUT_FILE_FLAG, ...LOG_VALUE_FLAGS] as const;
25
26
  const BOOL_FLAGS = ['--strict', '--json'] as const;
26
27
 
27
28
  /**
28
29
  * Every flag `validate` accepts, derived from the sets the parser is handed so
29
- * the list cannot claim a flag the parser would reject. `--services` is consumed
30
- * by the shared harness parser itself, so it is in neither set.
30
+ * the list cannot claim a flag the parser would reject.
31
+ * {@link HARNESS_VALUE_FLAGS} are consumed by the shared harness parser itself,
32
+ * so they are in neither set.
31
33
  */
32
- export const VALIDATE_FLAGS: readonly string[] = [SERVICES_FLAG, ...VALUE_FLAGS, ...BOOL_FLAGS];
34
+ export const VALIDATE_FLAGS: readonly string[] = [...HARNESS_VALUE_FLAGS, ...VALUE_FLAGS, ...BOOL_FLAGS];
33
35
 
34
36
  /** The subset that takes a value, so `--help` in a value position reads as data. */
35
- export const VALIDATE_VALUE_FLAGS: readonly string[] = [SERVICES_FLAG, ...VALUE_FLAGS];
37
+ export const VALIDATE_VALUE_FLAGS: readonly string[] = [...HARNESS_VALUE_FLAGS, ...VALUE_FLAGS];
36
38
 
37
39
  /** The `--help` text, as data, held to {@link VALIDATE_FLAGS} by a test. */
38
40
  export const VALIDATE_HELP: readonly string[] = [
39
- 'Usage: hydranium-cli validate --services <module> <workspace> [--strict] [--json] [--out-file <file>] [--log-level <lvl>]',
41
+ 'Usage: hydranium-cli validate --services <module> [--import <specifier>]... <workspace> [--strict] [--json] [--out-file <file>] [--log-level <lvl>] [--log-file <file>] [--log-file-level <lvl>]',
40
42
  '',
41
43
  'Build a workspace headlessly and report its validation diagnostics — a CI gate:',
42
44
  'the process exits non-zero when any error is found. `<module>` is an ESM module',
@@ -45,6 +47,7 @@ export const VALIDATE_HELP: readonly string[] = [
45
47
  '',
46
48
  'Options:',
47
49
  ' --services <module> ESM module exporting `createServices(): { shared }` (required).',
50
+ ...importHelpLines(22),
48
51
  ' <workspace> Workspace root (path or file URI) to validate (required).',
49
52
  ' --strict Also fail (non-zero exit) on warnings, not only errors.',
50
53
  ' --json Emit the raw JSON result instead of the human report.',
@@ -52,18 +55,19 @@ export const VALIDATE_HELP: readonly string[] = [
52
55
  ' still decides the exit code, and the file is written only',
53
56
  ' once the report exists, unlike a shell redirection, which',
54
57
  ' truncates the file before the workspace is even built.',
55
- logLevelHelpLine(22)
58
+ ...logHelpLines(22)
56
59
  ];
57
60
 
58
61
  export function parseValidateArgs(args: string[], onError: UsageError = exitWithUsage): ValidateCommandOptions {
59
- const { servicesModule, workspace, options } = parseHarnessArgs(args, 'validate', VALUE_FLAGS, BOOL_FLAGS, { onError });
62
+ const { servicesModule, imports, workspace, options } = parseHarnessArgs(args, 'validate', VALUE_FLAGS, BOOL_FLAGS, { onError });
60
63
  return {
61
64
  servicesModule,
65
+ imports,
62
66
  workspace,
63
67
  strict: options['--strict'] === 'true',
64
68
  json: options['--json'] === 'true',
65
69
  outFile: options[OUT_FILE_FLAG],
66
- logLevel: logLevelOption(options[LOG_LEVEL_FLAG])
70
+ ...logOptions(options)
67
71
  };
68
72
  }
69
73
 
@@ -54,5 +54,5 @@ export function buildValidateDriverArgs(options: ValidateCommandOptions): string
54
54
  * The child's exit code propagates to this process so shells and CI see the gate.
55
55
  */
56
56
  export function runValidate(options: ValidateCommandOptions): Promise<void> {
57
- return runDriverChild(['--max-old-space-size=8192', DRIVER, ...buildValidateDriverArgs(options)], options);
57
+ return runDriverChild([DRIVER, ...buildValidateDriverArgs(options)], options);
58
58
  }
@@ -11,6 +11,7 @@ import {
11
11
  assertRequired,
12
12
  exitWithUsage,
13
13
  helpRequested,
14
+ logHelpLines,
14
15
  parseFlagOptions,
15
16
  parseServerSpawnOptions,
16
17
  printHelp,
@@ -35,7 +36,7 @@ export const WATCH_VALUE_FLAGS: readonly string[] = WATCH_FLAGS;
35
36
 
36
37
  /** The `--help` text, as data, held to {@link WATCH_FLAGS} by a test. */
37
38
  export const WATCH_HELP: readonly string[] = [
38
- 'Usage: hydranium-cli watch --server "<cmd>..." --uri <uri> [--client-id <id>] [--cwd <dir>] [--log-level <level>]',
39
+ 'Usage: hydranium-cli watch --server "<cmd>..." --uri <uri> [--client-id <id>] [--cwd <dir>] [--log-level <lvl>] [--log-file <file>] [--log-file-level <lvl>]',
39
40
  '',
40
41
  'Subscribe to document updates at `<uri>` and print events as newline-delimited',
41
42
  'JSON. Long-running — exits cleanly on SIGINT (Ctrl-C).',
@@ -45,18 +46,20 @@ export const WATCH_HELP: readonly string[] = [
45
46
  ' --uri <uri> Document URI (required).',
46
47
  ' --client-id <id> Subscriber identity. Default: hydranium-cli.',
47
48
  ' --cwd <dir> Working directory for the spawned child. Default: cwd.',
48
- ' --log-level <lvl> Log threshold for the spawned server (off|error|warn|info|debug|trace).'
49
+ ...logHelpLines(22, 'the spawned server')
49
50
  ];
50
51
 
51
52
  /** Parse the argv; the abort signal is the entry point's to supply, not the command line's. */
52
53
  export function parseWatchArgs(args: string[], onError: UsageError = exitWithUsage): WatchCommandOptions {
53
- const { serverCommand, serverArgs, cwd, logLevel, extra } = parseServerSpawnOptions(args, 'watch', onError);
54
+ const { serverCommand, serverArgs, cwd, logLevel, logFile, logFileLevel, extra } = parseServerSpawnOptions(args, 'watch', onError);
54
55
  const { uri, clientId } = parseFlagOptions(extra, 'watch', OWN_FLAGS, onError);
55
56
  return {
56
57
  serverCommand,
57
58
  serverArgs,
58
59
  cwd,
59
60
  logLevel,
61
+ logFile,
62
+ logFileLevel,
60
63
  uri: assertRequired(uri, '--uri', 'watch', onError),
61
64
  clientId
62
65
  };
@@ -7,9 +7,14 @@
7
7
  * SPDX-License-Identifier: MIT
8
8
  ********************************************************************************/
9
9
 
10
- import type { LogThreshold, TransferElement } from '@hydranium/protocol';
11
- import type { DataClientProtocol, DataServerProtocol, TransferDocumentUpdatedEvent } from '@hydranium/protocol/data';
12
- import { logLevelEnv } from '../log-level.js';
10
+ import type { TransferElement } from '@hydranium/protocol';
11
+ import type {
12
+ DataClientProtocol,
13
+ DataServerProtocol,
14
+ TransferDocumentDeletedEvent,
15
+ TransferDocumentUpdatedEvent
16
+ } from '@hydranium/protocol/data';
17
+ import { logEnv, type LogOptions } from '../log-level.js';
13
18
  import { spawnDataServer } from '../spawn-data-server.js';
14
19
 
15
20
  /**
@@ -22,12 +27,10 @@ import { spawnDataServer } from '../spawn-data-server.js';
22
27
  * — production CLI wires SIGINT directly. `__handleForTest` bypasses
23
28
  * the spawn step for unit tests.
24
29
  */
25
- export interface WatchCommandOptions {
30
+ export interface WatchCommandOptions extends LogOptions {
26
31
  readonly serverCommand: string;
27
32
  readonly serverArgs?: readonly string[];
28
33
  readonly cwd?: string;
29
- /** Log threshold for the spawned server, set on its `HYDRANIUM_LOG_LEVEL` env. */
30
- readonly logLevel?: LogThreshold;
31
34
  readonly uri: string;
32
35
  readonly clientId?: string;
33
36
  readonly write?: (line: string) => void;
@@ -132,6 +135,24 @@ export async function runWatch(options: WatchCommandOptions): Promise<void> {
132
135
  onDocumentSaved(): void {
133
136
  // Persistence is out of band for the per-URI update view.
134
137
  },
138
+ onDocumentDirtyChanged(): void {
139
+ // Out of band for the per-URI update view, as persistence is.
140
+ },
141
+ onDocumentDeleted(event: TransferDocumentDeletedEvent): void {
142
+ // In band, unlike the two neighbours: this is the end of the stream
143
+ // the view exists to show, and a consumer that never hears it waits
144
+ // forever for an update that cannot come. The line carries no
145
+ // `document`, so a reader must switch on shape rather than assume one.
146
+ if (event.uri !== options.uri) {
147
+ return;
148
+ }
149
+ write(`${JSON.stringify(event)}\n`);
150
+ },
151
+ onDocumentsBuilt(): void {
152
+ // Out of band for a per-URI view by construction: this notification
153
+ // carries only documents nobody watches, and this command watches the
154
+ // one URI it was given.
155
+ },
135
156
  onProjectsChanged(): void {
136
157
  // Project lifecycle is out of band for the per-URI update view.
137
158
  }
@@ -146,7 +167,7 @@ export async function runWatch(options: WatchCommandOptions): Promise<void> {
146
167
  command: options.serverCommand,
147
168
  args: options.serverArgs,
148
169
  cwd: options.cwd,
149
- env: options.logLevel ? logLevelEnv(options.logLevel) : undefined
170
+ env: logEnv(options)
150
171
  },
151
172
  localClient
152
173
  );
@@ -0,0 +1,65 @@
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 { heapCeilingArgs } from '@hydranium/core/node';
11
+
12
+ /**
13
+ * Heap ceiling in MiB for a driver child on a machine with no cgroup limit.
14
+ *
15
+ * The subcommands that spawn one build a whole workspace in that child —
16
+ * `measure-memory` deliberately so, `analyze-heap` loads an entire heap
17
+ * snapshot — so the default Node would pick from physical RAM is too low for
18
+ * the workspaces these are pointed at.
19
+ */
20
+ export const DRIVER_HEAP_MB = 8192;
21
+
22
+ /** Environment variable an operator raises or lowers {@link driverHeapArgs} with. */
23
+ export const DRIVER_HEAP_ENV = 'HYDRANIUM_CLI_MAX_OLD_SPACE_MB';
24
+
25
+ /**
26
+ * Smallest ceiling {@link DRIVER_HEAP_ENV} may state. A driver child builds a
27
+ * whole workspace, so a value this far below the default is a unit mistake
28
+ * rather than a deliberate squeeze.
29
+ */
30
+ export const MIN_DRIVER_HEAP_MB = 256;
31
+
32
+ /**
33
+ * A cgroup reading, so a caller — in practice a test — can decide the ceiling
34
+ * instead of inheriting the machine's. Omitted fields fall back to this
35
+ * process's own reading.
36
+ */
37
+ export interface HeapReading {
38
+ readonly constrained?: number;
39
+ readonly total?: number;
40
+ }
41
+
42
+ /**
43
+ * The `execArgv` prefix every driver child is spawned under.
44
+ *
45
+ * Inside a container this is EMPTY on purpose. {@link DRIVER_HEAP_MB} is sized
46
+ * for a workstation, and handing it to a process under a smaller cgroup limit
47
+ * is worse than handing it nothing: V8 has no reason to collect hard below a
48
+ * ceiling it will never reach, so the kernel OOM-kills the container first and
49
+ * the failure arrives as a signal against the whole cgroup rather than as a
50
+ * heap error the parent can attribute. Left to itself, Node sizes the heap from
51
+ * the limit instead.
52
+ *
53
+ * That trades away the ability to use a LARGE container's memory, since Node's
54
+ * derived default is a fraction of the limit — which is what {@link DRIVER_HEAP_ENV}
55
+ * is for. An operator who states a number has decided, so it wins in a
56
+ * container too.
57
+ */
58
+ export function driverHeapArgs(reading: HeapReading = {}): string[] {
59
+ return heapCeilingArgs({
60
+ desktopDefaultMb: DRIVER_HEAP_MB,
61
+ envValue: process.env[DRIVER_HEAP_ENV],
62
+ minMb: MIN_DRIVER_HEAP_MB,
63
+ ...reading
64
+ });
65
+ }
package/src/index.ts CHANGED
@@ -7,6 +7,7 @@
7
7
  * SPDX-License-Identifier: MIT
8
8
  ********************************************************************************/
9
9
 
10
+ export * from './commands/generate-ast-builder.js';
10
11
  export * from './commands/generate-transfer-model.js';
11
12
  export * from './commands/projects.js';
12
13
  export * from './commands/query.js';
package/src/log-level.ts CHANGED
@@ -7,29 +7,47 @@
7
7
  * SPDX-License-Identifier: MIT
8
8
  ********************************************************************************/
9
9
 
10
- import { DEFAULT_LOG_LEVEL_ENV, LEVEL_ORDER, parseLogLevel, type LogThreshold } from '@hydranium/protocol';
10
+ import {
11
+ DEFAULT_LOG_FILE_ENV,
12
+ DEFAULT_LOG_FILE_LEVEL_ENV,
13
+ DEFAULT_LOG_LEVEL_ENV,
14
+ LEVEL_ORDER,
15
+ parseLogLevel,
16
+ type LogThreshold
17
+ } from '@hydranium/protocol';
18
+
19
+ /** The log flags every subcommand takes, as the env {@link logEnv} hands its child. */
20
+ export interface LogOptions {
21
+ /** Threshold for the client sink; the server's log-level setting replaces it. */
22
+ readonly logLevel?: LogThreshold;
23
+ /** File the server tees its log to; `{workspace}` expands once it is known. */
24
+ readonly logFile?: string;
25
+ /** The file's own threshold, which the log-level setting does not change. */
26
+ readonly logFileLevel?: LogThreshold;
27
+ }
11
28
 
12
29
  /**
13
- * Validate a raw `--log-level` argument into a {@link LogThreshold}. Throws on
14
- * an unrecognised value so the CLI's top-level `catch` surfaces a clean error
15
- * and exits non-zero (mirroring how the other option parsers fail fast). Use
16
- * for the argv-supplied value; the resolved threshold is handed to
17
- * {@link logLevelEnv} to target the spawned server.
30
+ * Validate a raw `--log-level` / `--log-file-level` argument into a
31
+ * {@link LogThreshold}. Throws on an unrecognised value so the CLI's top-level
32
+ * `catch` surfaces a clean error and exits non-zero (mirroring how the other
33
+ * option parsers fail fast). Use for the argv-supplied value; the resolved
34
+ * threshold is handed to {@link logEnv} to target the spawned server.
18
35
  */
19
- export function parseLogLevelOption(raw: string): LogThreshold {
36
+ export function parseLogLevelOption(raw: string, flag = '--log-level'): LogThreshold {
20
37
  const level = parseLogLevel(raw);
21
38
  if (!level) {
22
- throw new Error(`Invalid --log-level: ${raw} (expected one of: ${Object.keys(LEVEL_ORDER).join(', ')})`);
39
+ throw new Error(`Invalid ${flag}: ${raw} (expected one of: ${Object.keys(LEVEL_ORDER).join(', ')})`);
23
40
  }
24
41
  return level;
25
42
  }
26
43
 
27
44
  /**
28
45
  * Build the environment override that targets *only the spawned server's* log
29
- * threshold. Passed to `spawnDataServer` as `env`, it sets the same
30
- * `HYDRANIUM_LOG_LEVEL` variable the server reads at startup — the CLI's own
31
- * logging is unaffected, unlike an ambient `HYDRANIUM_LOG_LEVEL=…` that the
32
- * child would inherit alongside the parent. The server owns *how* log level
46
+ * configuration, or `undefined` when no log flag was given. Passed to
47
+ * `spawnDataServer` as `env`, it sets the same `HYDRANIUM_LOG_LEVEL` /
48
+ * `HYDRANIUM_LOG_FILE` / `HYDRANIUM_LOG_FILE_LEVEL` variables the server reads
49
+ * at startup — the CLI's own logging is unaffected, unlike ambient variables
50
+ * that the child would inherit alongside the parent. The server owns *how* log level
33
51
  * works; this only routes the CLI's request onto the channel it already reads.
34
52
  *
35
53
  * **The variable is read by `LspLogger`'s constructor**, which is bound on the
@@ -44,6 +62,16 @@ export function parseLogLevelOption(raw: string): LogThreshold {
44
62
  * not go to stdout: that is the JSON-RPC channel, so a log line there would
45
63
  * corrupt the very request this flag was set to diagnose.
46
64
  */
47
- export function logLevelEnv(level: LogThreshold): Record<string, string> {
48
- return { [DEFAULT_LOG_LEVEL_ENV]: level };
65
+ export function logEnv(options: LogOptions): Record<string, string> | undefined {
66
+ const env: Record<string, string> = {};
67
+ if (options.logLevel !== undefined) {
68
+ env[DEFAULT_LOG_LEVEL_ENV] = options.logLevel;
69
+ }
70
+ if (options.logFile !== undefined) {
71
+ env[DEFAULT_LOG_FILE_ENV] = options.logFile;
72
+ }
73
+ if (options.logFileLevel !== undefined) {
74
+ env[DEFAULT_LOG_FILE_LEVEL_ENV] = options.logFileLevel;
75
+ }
76
+ return Object.keys(env).length > 0 ? env : undefined;
49
77
  }
@@ -15,7 +15,14 @@ import {
15
15
  type DataServerProtocol
16
16
  } from '@hydranium/protocol/data';
17
17
  import { type ChildProcess, spawn } from 'node:child_process';
18
- import { StreamMessageReader, StreamMessageWriter, createMessageConnection, type MessageConnection } from 'vscode-jsonrpc/node';
18
+ import {
19
+ StreamMessageReader,
20
+ StreamMessageWriter,
21
+ createMessageConnection,
22
+ type Logger as ConnectionLogger,
23
+ type MessageConnection
24
+ } from 'vscode-jsonrpc/node';
25
+ import { STDERR_CONNECTION_LOGGER } from './stderr-connection-logger.js';
19
26
 
20
27
  /**
21
28
  * Options for {@link spawnDataServer}. `command` is the binary or script
@@ -49,6 +56,11 @@ export interface SpawnDataServerOptions {
49
56
  * scripted use; set to `'pipe'` to capture for assertion in tests.
50
57
  */
51
58
  readonly stderr?: 'inherit' | 'ignore' | 'pipe';
59
+ /**
60
+ * Where the connection to the child logs its protocol faults, such as a
61
+ * response that matches no request. Default: this process's stderr.
62
+ */
63
+ readonly logger?: ConnectionLogger;
52
64
  }
53
65
 
54
66
  /**
@@ -143,7 +155,7 @@ export function spawnDataServer<TTransfer extends TransferElement, TDiagnostic e
143
155
 
144
156
  const reader = new StreamMessageReader(child.stdout);
145
157
  const writer = new StreamMessageWriter(child.stdin);
146
- const connection = createMessageConnection(reader, writer);
158
+ const connection = createMessageConnection(reader, writer, options.logger ?? STDERR_CONNECTION_LOGGER);
147
159
  // Consume transport error / close so a child that dies mid-stream (its stdout
148
160
  // closing, a write landing on a torn-down stdin) is observed here rather than
149
161
  // escaping as an unhandled error — the death is reported via `whenTerminated`.