@hydranium/core 1.0.0-next.31 → 1.0.0-next.32

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 (92) hide show
  1. package/lib/documents/hydranium-text-documents.d.ts.map +1 -1
  2. package/lib/documents/hydranium-text-documents.js +12 -1
  3. package/lib/documents/hydranium-text-documents.js.map +1 -1
  4. package/lib/index.d.ts +1 -0
  5. package/lib/index.d.ts.map +1 -1
  6. package/lib/index.js +1 -0
  7. package/lib/index.js.map +1 -1
  8. package/lib/langium/bootstrap.d.ts.map +1 -1
  9. package/lib/langium/bootstrap.js +8 -1
  10. package/lib/langium/bootstrap.js.map +1 -1
  11. package/lib/langium/document-builder/document-builder.d.ts +33 -1
  12. package/lib/langium/document-builder/document-builder.d.ts.map +1 -1
  13. package/lib/langium/document-builder/document-builder.js +68 -2
  14. package/lib/langium/document-builder/document-builder.js.map +1 -1
  15. package/lib/langium/model-service/model-service.d.ts +26 -0
  16. package/lib/langium/model-service/model-service.d.ts.map +1 -1
  17. package/lib/langium/model-service/model-service.js +31 -3
  18. package/lib/langium/model-service/model-service.js.map +1 -1
  19. package/lib/langium/module.d.ts +20 -0
  20. package/lib/langium/module.d.ts.map +1 -1
  21. package/lib/langium/module.js +4 -0
  22. package/lib/langium/module.js.map +1 -1
  23. package/lib/langium/naming/name-provider.d.ts +10 -0
  24. package/lib/langium/naming/name-provider.d.ts.map +1 -1
  25. package/lib/langium/naming/name-provider.js.map +1 -1
  26. package/lib/langium/naming/name-separator-validation.d.ts +23 -1
  27. package/lib/langium/naming/name-separator-validation.d.ts.map +1 -1
  28. package/lib/langium/naming/name-separator-validation.js +22 -0
  29. package/lib/langium/naming/name-separator-validation.js.map +1 -1
  30. package/lib/langium/shared-services.d.ts +13 -2
  31. package/lib/langium/shared-services.d.ts.map +1 -1
  32. package/lib/langium/shared-services.js.map +1 -1
  33. package/lib/langium/validation/document-validator.d.ts +66 -1
  34. package/lib/langium/validation/document-validator.d.ts.map +1 -1
  35. package/lib/langium/validation/document-validator.js +101 -1
  36. package/lib/langium/validation/document-validator.js.map +1 -1
  37. package/lib/langium/workspace/hydranium-workspace-manager.d.ts +11 -1
  38. package/lib/langium/workspace/hydranium-workspace-manager.d.ts.map +1 -1
  39. package/lib/langium/workspace/hydranium-workspace-manager.js +15 -0
  40. package/lib/langium/workspace/hydranium-workspace-manager.js.map +1 -1
  41. package/lib/langium/workspace/initialize-workspace.d.ts +22 -2
  42. package/lib/langium/workspace/initialize-workspace.d.ts.map +1 -1
  43. package/lib/langium/workspace/initialize-workspace.js +13 -5
  44. package/lib/langium/workspace/initialize-workspace.js.map +1 -1
  45. package/lib/locale/index.d.ts +10 -0
  46. package/lib/locale/index.d.ts.map +1 -0
  47. package/lib/locale/index.js +10 -0
  48. package/lib/locale/index.js.map +1 -0
  49. package/lib/locale/server-locale.d.ts +49 -0
  50. package/lib/locale/server-locale.d.ts.map +1 -0
  51. package/lib/locale/server-locale.js +51 -0
  52. package/lib/locale/server-locale.js.map +1 -0
  53. package/lib/messages/carriers.d.ts +7 -6
  54. package/lib/messages/carriers.d.ts.map +1 -1
  55. package/lib/messages/carriers.js +8 -7
  56. package/lib/messages/carriers.js.map +1 -1
  57. package/lib/messages/index.d.ts +3 -0
  58. package/lib/messages/index.d.ts.map +1 -1
  59. package/lib/messages/index.js +3 -0
  60. package/lib/messages/index.js.map +1 -1
  61. package/lib/messages/renderer.d.ts +117 -0
  62. package/lib/messages/renderer.d.ts.map +1 -0
  63. package/lib/messages/renderer.js +159 -0
  64. package/lib/messages/renderer.js.map +1 -0
  65. package/lib/testing/make-noop-shared-services.d.ts +14 -0
  66. package/lib/testing/make-noop-shared-services.d.ts.map +1 -1
  67. package/lib/testing/make-noop-shared-services.js +28 -2
  68. package/lib/testing/make-noop-shared-services.js.map +1 -1
  69. package/lib/testing/make-test-services.d.ts +27 -0
  70. package/lib/testing/make-test-services.d.ts.map +1 -1
  71. package/lib/testing/make-test-services.js +17 -1
  72. package/lib/testing/make-test-services.js.map +1 -1
  73. package/package.json +5 -5
  74. package/src/documents/hydranium-text-documents.ts +12 -1
  75. package/src/index.ts +1 -0
  76. package/src/langium/bootstrap.ts +8 -1
  77. package/src/langium/document-builder/document-builder.ts +70 -2
  78. package/src/langium/model-service/model-service.ts +33 -2
  79. package/src/langium/module.ts +22 -0
  80. package/src/langium/naming/name-provider.ts +10 -0
  81. package/src/langium/naming/name-separator-validation.ts +25 -3
  82. package/src/langium/shared-services.ts +13 -2
  83. package/src/langium/validation/document-validator.ts +117 -1
  84. package/src/langium/workspace/hydranium-workspace-manager.ts +18 -1
  85. package/src/langium/workspace/initialize-workspace.ts +34 -5
  86. package/src/locale/index.ts +10 -0
  87. package/src/locale/server-locale.ts +61 -0
  88. package/src/messages/carriers.ts +8 -8
  89. package/src/messages/index.ts +3 -0
  90. package/src/messages/renderer.ts +184 -0
  91. package/src/testing/make-noop-shared-services.ts +50 -2
  92. package/src/testing/make-test-services.ts +43 -1
@@ -73,7 +73,14 @@ const EXPECTED_SHARED_SLOTS: readonly ExpectedSlot[] = [
73
73
  side: 'shared',
74
74
  path: 'workspace.BuildPipelineIntegration',
75
75
  get: services => nested(services, 'workspace', 'BuildPipelineIntegration')
76
- }
76
+ },
77
+ // Unbound, this fails where the cause is least visible: the render pass runs
78
+ // inside the `Validated` phase, so a `TypeError` there propagates out of
79
+ // `notifyDocumentPhase` and the document reaches `Validated` with Langium's
80
+ // publisher never invoked — the client receives no diagnostics for the file
81
+ // and the stack names the document builder.
82
+ { side: 'shared', path: 'MessageRenderer', get: services => nested(services, 'MessageRenderer') },
83
+ { side: 'shared', path: 'ServerLocale', get: services => nested(services, 'ServerLocale') }
77
84
  ];
78
85
 
79
86
  /**
@@ -21,8 +21,12 @@ import {
21
21
  interruptAndCheck,
22
22
  isOperationCancelled
23
23
  } from '@hydranium/langium';
24
- import { CancellationToken, type Diagnostic } from 'vscode-languageserver-protocol';
24
+ // `Diagnostic` as a VALUE: `renderDiagnostics` needs its `getMessageString`
25
+ // namespace helper to read the `string | MarkupContent` union without
26
+ // restating it.
27
+ import { CancellationToken, Diagnostic } from 'vscode-languageserver-protocol';
25
28
  import { type LogNameOptions } from '../diagnostics/logger.js';
29
+ import type { ServerMessageRenderer } from '../../messages/renderer.js';
26
30
  import { CST_REHYDRATION_RESET_STATE, isCstShed } from '../residency/cst-residency-service.js';
27
31
  import { type ExtendedServiceRegistry } from '../service-registry.js';
28
32
  import { type ServerSharedServicesMinimal } from '../shared-services.js';
@@ -119,7 +123,9 @@ export interface DocumentBuilderOptions extends LogNameOptions {
119
123
  * - **In-place rebuild helpers** — {@link reparse} and
120
124
  * {@link reparseAndRelink} — for a build-phase listener that mutated a
121
125
  * document's AST and must reconcile it within the same build.
122
- * - **Diagnostic dedupe** at `Validated` ({@link dedupeDiagnostics}).
126
+ * - **Diagnostic dedupe** at `Validated` ({@link dedupeDiagnostics}), followed
127
+ * by the **one server-side message render** every head inherits
128
+ * ({@link renderDiagnostics}).
123
129
  * - **Build sessions** ({@link BuildSession}): each `update` / `build` call is
124
130
  * one correlated unit carrying an id, a trigger label, a start time and
125
131
  * cancellation lineage, so every line of a rebuild reads as belonging to it
@@ -152,6 +158,7 @@ export class HydraniumDocumentBuilder extends DefaultDocumentBuilder {
152
158
  protected readonly phaseDetailMs: ObservableValue<number>;
153
159
  protected readonly uriPolicy: DocumentUriPolicy;
154
160
  protected readonly clock: Clock;
161
+ protected readonly messageRenderer: ServerMessageRenderer;
155
162
  /** Narrower handle on the same registry as the inherited `serviceRegistry`, for {@link ExtendedServiceRegistry.registrations}. */
156
163
  protected readonly languageRegistry: ExtendedServiceRegistry;
157
164
  protected languageFileExtensions: string[] = [];
@@ -184,6 +191,7 @@ export class HydraniumDocumentBuilder extends DefaultDocumentBuilder {
184
191
  this.languageRegistry = services.ServiceRegistry;
185
192
  this.uriPolicy = services.workspace.DocumentUriPolicy;
186
193
  this.clock = services.Clock;
194
+ this.messageRenderer = services.MessageRenderer;
187
195
  this.tracer = services.Tracer.for(options.logName ?? 'DocumentBuilder').trace('instantiated');
188
196
  this.logLevel = options.logLevel ?? 'debug';
189
197
  this.loggedPhases = options.loggedPhases ?? DEFAULT_LOGGED_PHASES;
@@ -893,8 +901,12 @@ export class HydraniumDocumentBuilder extends DefaultDocumentBuilder {
893
901
  // build settling inside that window therefore appends after this call has
894
902
  // already deduped, and the appended duplicate is published by the listener
895
903
  // of the build that deduped. Only `serializeBuilds` closes the window.
904
+ //
905
+ // Dedupe before rendering: rendering is deterministic, so it cannot
906
+ // change which entries are structurally equal, and fewer survive to render.
896
907
  if (state === DocumentState.Validated) {
897
908
  this.dedupeDiagnostics(document);
909
+ this.renderDiagnostics(document);
898
910
  }
899
911
  if (this.logLevel === 'off') {
900
912
  return super.notifyDocumentPhase(document, state, cancelToken);
@@ -1070,6 +1082,62 @@ export class HydraniumDocumentBuilder extends DefaultDocumentBuilder {
1070
1082
  }
1071
1083
  }
1072
1084
 
1085
+ /**
1086
+ * Render every diagnostic on `document` through the bound message renderer,
1087
+ * in ONE pass over the finished list.
1088
+ *
1089
+ * All three heads read `document.diagnostics` — the LSP publish,
1090
+ * `TransferEncoder.toTransferDiagnostic` and the GLSP validation path — so
1091
+ * one pass here is what keeps the render from happening per head. It is also
1092
+ * the only placement that covers lexer and parser errors, which Langium
1093
+ * pushes onto the document without routing them through `toDiagnostic`.
1094
+ *
1095
+ * Running here rather than from a `Validated` phase listener needs no
1096
+ * ordering assumption: Langium publishes from `addDiagnosticsHandler`, a free
1097
+ * function it registers as such a listener, which can only be outrun.
1098
+ *
1099
+ * **It inherits {@link dedupeDiagnostics}'s window, and therefore the same
1100
+ * precondition.** A build settling inside the listener window appends
1101
+ * diagnostics this pass never saw, and the publisher of the build that
1102
+ * rendered sends them — unrendered. `ModelServiceOptions.serializeBuilds`
1103
+ * closes it and defaults to `true`, so "every diagnostic is rendered" holds
1104
+ * by default and is an opt-out rather than a guarantee. Opting out accepts
1105
+ * unrendered diagnostics on exactly the terms it already accepts duplicates.
1106
+ *
1107
+ * Entries are REPLACED rather than mutated: `sendDiagnostics` passes the
1108
+ * array by reference and serialises later, so an in-place message mutation
1109
+ * reaches the wire even when it runs after the publisher — which would make
1110
+ * a test for the ordering pass in either state.
1111
+ */
1112
+ protected renderDiagnostics(document: LangiumDocument): void {
1113
+ const diagnostics = document.diagnostics;
1114
+ if (!diagnostics || diagnostics.length === 0) {
1115
+ return;
1116
+ }
1117
+ let changed = false;
1118
+ // No try/catch: `renderDiagnostic` carries a no-throw contract, because an
1119
+ // error escaping this phase strands the document at `Validated` with
1120
+ // Langium's publisher never invoked.
1121
+ const rendered = diagnostics.map(diagnostic => {
1122
+ const text = this.messageRenderer.renderDiagnostic(diagnostic);
1123
+ // Against the message's STRING FORM, not the field. `renderDiagnostic`
1124
+ // answers a `string` by contract, while `Diagnostic.message` is
1125
+ // `string | MarkupContent` since LSP 3.17 — so comparing the answer
1126
+ // against the field never matches for a markup message, and a pass
1127
+ // that replaced on mismatch flattened every un-identified markup
1128
+ // diagnostic to its own plain text. That is silent data loss on the
1129
+ // path whose whole job is to leave such entries alone.
1130
+ if (text === Diagnostic.getMessageString(diagnostic)) {
1131
+ return diagnostic;
1132
+ }
1133
+ changed = true;
1134
+ return { ...diagnostic, message: text };
1135
+ });
1136
+ if (changed) {
1137
+ document.diagnostics = rendered;
1138
+ }
1139
+ }
1140
+
1073
1141
  // ============================================================
1074
1142
  // Internal helpers
1075
1143
  // ============================================================
@@ -11,6 +11,7 @@ import {
11
11
  type CanonicalUri,
12
12
  type CloseModelArgs,
13
13
  ConflictError,
14
+ defineMessage,
14
15
  Logger,
15
16
  type MaybeObservableValue,
16
17
  type MaybePromise,
@@ -34,6 +35,23 @@ import { labelPhaseListener } from '../document-builder/labeled-phase-listener.j
34
35
  import { LANGUAGE_CLIENT_ID } from '../../documents/client-ids.js';
35
36
  import { type ServerSharedServices } from '../module.js';
36
37
 
38
+ /**
39
+ * The undo-stack entry for a server-authored write pushed to the editor.
40
+ *
41
+ * **A user-facing LABEL, not a log string**, which is easy to miss because it
42
+ * travels as an options field rather than as a message: LSP specifies
43
+ * `ApplyWorkspaceEditParams.label` as "presented in the user interface for
44
+ * example on an undo stack to undo the workspace edit". So a user who edits
45
+ * through a form or drags a diagram node reads this in their editor's undo menu
46
+ * — which is why it is rendered like any other message the server sends rather
47
+ * than left as the English literal it was.
48
+ *
49
+ * Parameterless deliberately. The obvious improvement is to name the document,
50
+ * and it is the wrong one: an undo menu is already grouped under the file, so
51
+ * the URI would be noise in the one place it is redundant.
52
+ */
53
+ export const MODEL_UPDATE_EDIT = defineMessage('hydranium/core/model-update-edit', 'Update Model');
54
+
37
55
  /** Max time {@link ModelService.settleSave} waits for the build to settle and the sync chain to drain. */
38
56
  const SAVE_SETTLE_TIMEOUT_MS = 10_000;
39
57
 
@@ -878,13 +896,26 @@ export class ModelService<
878
896
  this.syncChains.set(uri, chain);
879
897
  }
880
898
 
899
+ /**
900
+ * The undo-stack label for a server-authored write, in the locale the server
901
+ * was handed at init.
902
+ *
903
+ * One method rather than the literal at each `applyEdit`, because the two
904
+ * call sites are the same edit — a push and its full-replace retry — and an
905
+ * undo menu showing two different words for one operation would read as two
906
+ * operations.
907
+ */
908
+ protected editLabel(): string {
909
+ return this.services.MessageRenderer.renderMessage(MODEL_UPDATE_EDIT);
910
+ }
911
+
881
912
  protected async drainSyncQueue(uri: string): Promise<void> {
882
913
  const uriLogger = this.tracer.withUri(uri);
883
914
  while (this.pendingSync.has(uri)) {
884
915
  const text = this.pendingSync.get(uri)!;
885
916
  this.pendingSync.delete(uri);
886
917
  try {
887
- let result = await this.services.workspace.TextDocuments.applyEditToLanguageClient(uri, text, { label: 'Update Model' });
918
+ let result = await this.services.workspace.TextDocuments.applyEditToLanguageClient(uri, text, { label: this.editLabel() });
888
919
  if (result?.applied === false && !this.pendingSync.has(uri)) {
889
920
  // The push is addressed at the client's LAST DECLARED VERSION, so a
890
921
  // rejection normally means the client's buffer moved while the
@@ -905,7 +936,7 @@ export class ModelService<
905
936
  // queued — best-effort, since a settle arriving later simply pushes
906
937
  // after this and still wins.
907
938
  uriLogger.warn(`Language client rejected applyEdit at its declared version — re-pushing a full replace`);
908
- result = await this.services.workspace.TextDocuments.applyEditToLanguageClient(uri, text, { label: 'Update Model' });
939
+ result = await this.services.workspace.TextDocuments.applyEditToLanguageClient(uri, text, { label: this.editLabel() });
909
940
  if (result?.applied === false) {
910
941
  uriLogger.warn(`Language client rejected the full-replace retry too — client content is stale`);
911
942
  }
@@ -8,6 +8,8 @@
8
8
  ********************************************************************************/
9
9
 
10
10
  import { type Clock, type Logger, type Project, type Tracer, type TransferDiagnostic, NoopLogger, SystemClock } from '@hydranium/protocol';
11
+ import { ServerLocale } from '../locale/server-locale.js';
12
+ import { ServerMessageRenderer } from '../messages/renderer.js';
11
13
  import { ServerTracer } from './diagnostics/server-tracer.js';
12
14
  import { HydraniumLangiumProfiler } from './diagnostics/hydranium-langium-profiler.js';
13
15
  import { type AstNode, type Module } from '@hydranium/langium';
@@ -92,6 +94,24 @@ export interface ServerAddedSharedServices<TProject extends Project = Project> {
92
94
  * plain `DefaultTracer` with their own `MemoryReader`.
93
95
  */
94
96
  Tracer: Tracer;
97
+ /**
98
+ * Renders each user-facing message once, before the server sends it — so
99
+ * every message is rendered by the side that knows the reading user's
100
+ * language. All three heads inherit one diagnostics pass, which is what
101
+ * makes this the single slot an adopter with i18n rebinds; the same binding
102
+ * serves framework codes and their own `defineMessage` codes alike.
103
+ *
104
+ * The framework ships English only and selects no locale, so the default
105
+ * returns every sentence unchanged. Adopters subclass and override
106
+ * `translationsFor`.
107
+ */
108
+ MessageRenderer: ServerMessageRenderer;
109
+ /**
110
+ * The locale an init handed the server, for whoever renders in it. Held
111
+ * apart from the renderer so replacing the renderer cannot drop locale
112
+ * handling.
113
+ */
114
+ ServerLocale: ServerLocale;
95
115
  /**
96
116
  * LSP-bound slots layered on top of Langium's `LangiumSharedLSPServices`.
97
117
  * The framework contributes a single string slot here —
@@ -334,6 +354,8 @@ export function createServerSharedModule(
334
354
  ServiceRegistry: services => new ExtendedServiceRegistry<ServerLanguageServices>(services),
335
355
  Logger: () => new NoopLogger(),
336
356
  Tracer: services => new ServerTracer(services.Logger, services.Clock),
357
+ ServerLocale: services => new ServerLocale(services),
358
+ MessageRenderer: services => new ServerMessageRenderer(services),
337
359
  // Bind Langium's per-grammar-rule / per-`$type` parse/link/validate
338
360
  // profiler (the data the framework's own `Tracer`/`ProfileSession` passes
339
361
  // cannot produce), routed through our `Logger` and debug-gated. At the
@@ -59,6 +59,16 @@ export interface NameProviderOptions {
59
59
  * an `id` field) override explicitly; the explicit override at
60
60
  * the adopter side documents the grammar's convention rather than
61
61
  * burying it in a framework default.
62
+ *
63
+ * **The override is not optional where `name` is a display LABEL rather
64
+ * than an identifier**, and getting it wrong is quiet at first and then
65
+ * loud. A `name=STRING` holding `"Order.Line"` is legitimate content, but
66
+ * the default reads it as the identifier: `getName` composes a qualified
67
+ * name whose segments cannot be told apart from the label's own dots, and
68
+ * `nameSeparatorCheck` reports `hydranium/core/separator-in-name` on every
69
+ * such node. That diagnostic then names the wrong remedy — it asks for a
70
+ * different character, when the fix is to point this option at the property
71
+ * that really is the identifier.
62
72
  */
63
73
  readonly nameProperties?: readonly string[];
64
74
  }
@@ -10,14 +10,36 @@
10
10
  import { type AstNode, type ValidationAcceptor, type ValidationChecks } from '@hydranium/langium';
11
11
  import { defineMessage } from '@hydranium/protocol';
12
12
  import { acceptMessage } from '../../messages/carriers.js';
13
+ import { type ServerLanguageServices } from '../language-module.js';
14
+ import { type ValidationCheckContribution, type ValidationCheckRegistry } from '../validation/validation-contribution.js';
15
+ import type { NameProvider } from './name-provider.js';
13
16
 
17
+ /**
18
+ * A name value that collides with the qualified-name separator.
19
+ *
20
+ * **The sentence addresses a MODELLER, and the remedy it names is theirs**:
21
+ * where `name` really is the identifier, a different character is the fix and
22
+ * the only one available to whoever is typing.
23
+ *
24
+ * **The adopter-facing failure is a different one, and this message cannot
25
+ * carry it.** With `nameProperties` left at its default `['name']` over a
26
+ * grammar where `name` is a display LABEL — a `STRING` legitimately holding
27
+ * `"Order.Line"` — this fires on every dotted label at once, and "use a
28
+ * different character" is then advice nobody can act on: the content is
29
+ * correct and the configuration is not. A burst of this diagnostic across
30
+ * unrelated nodes is that misconfiguration, not a naming problem, and the fix
31
+ * is `nameProperties`. Widening the sentence to say both was rejected: a
32
+ * modeller cannot act on a DI option, and naming one in an editor squiggle
33
+ * teaches the wrong audience.
34
+ *
35
+ * Unreachable from a grammar whose identifier charset excludes the separator,
36
+ * which is every example here and the reference adopter — so it reads as dead
37
+ * and is not: it guards the configuration, not the content.
38
+ */
14
39
  export const SEPARATOR_IN_NAME = defineMessage(
15
40
  'hydranium/core/separator-in-name',
16
41
  "Name '{name}' contains the configured name separator '{separator}', which is reserved for qualified-name composition — use a different character."
17
42
  );
18
- import { type ServerLanguageServices } from '../language-module.js';
19
- import { type ValidationCheckContribution, type ValidationCheckRegistry } from '../validation/validation-contribution.js';
20
- import type { NameProvider } from './name-provider.js';
21
43
 
22
44
  /**
23
45
  * Per-node validation check: flag name-bearing AST nodes whose name
@@ -9,6 +9,8 @@
9
9
 
10
10
  import type { Clock, Logger, Project, Tracer } from '@hydranium/protocol';
11
11
  import type { LangiumSharedCoreServices } from '@hydranium/langium';
12
+ import type { ServerLocale } from '../locale/server-locale.js';
13
+ import type { ServerMessageRenderer } from '../messages/renderer.js';
12
14
  import type { SelfSaveRegistry } from '../documents/self-save-registry.js';
13
15
  import type { WritableFileSystemProvider } from '../documents/ast-document-manager.js';
14
16
  import type { HydraniumDocumentRegistry } from './workspace/langium-documents.js';
@@ -28,8 +30,9 @@ import type { AdditionalDocumentContribution } from './workspace/additional-docu
28
30
  * framework additions that other framework services consume: the dedicated
29
31
  * {@link Clock}, {@link Logger} and {@link Tracer} top-level slots (injectable
30
32
  * time source, emission-only logger, and the measure-and-emit tracer composed
31
- * from the other two), the {@link AdditionalDocumentContribution} group, an
32
- * {@link ExtendedServiceRegistry}, and on `workspace` a writable file-system
33
+ * from the other two), the {@link AdditionalDocumentContribution} group, the
34
+ * {@link ServerMessageRenderer} and the {@link ServerLocale} it renders in,
35
+ * an {@link ExtendedServiceRegistry}, and on `workspace` a writable file-system
33
36
  * provider plus {@link HydraniumWorkspaceManager}, {@link ProjectManager},
34
37
  * {@link SelfSaveRegistry}, {@link BuildPipelineIntegration},
35
38
  * {@link BuildPhasePassService}, {@link CstResidencyService} and
@@ -58,6 +61,14 @@ export interface ServerSharedServicesMinimal<TProject extends Project = Project>
58
61
  * adopters deep-merge contributions that seed built-in / stdlib documents.
59
62
  */
60
63
  additionalDocuments: Record<string, AdditionalDocumentContribution>;
64
+ /**
65
+ * Renders each user-facing message once, before the server sends it. On the
66
+ * shared tier with no workspace dependency, because all three heads'
67
+ * messages pass through it.
68
+ */
69
+ MessageRenderer: ServerMessageRenderer;
70
+ /** The locale an init handed the server, for whoever renders in it. */
71
+ ServerLocale: ServerLocale;
61
72
  /**
62
73
  * Narrows Langium's base `ServiceRegistry` slot to the framework impl the
63
74
  * framework always binds, so the abstaining lookups — `getServicesFor`
@@ -7,10 +7,20 @@
7
7
  * SPDX-License-Identifier: MIT
8
8
  ********************************************************************************/
9
9
 
10
- import { type LogThreshold, type MaybeObservableValue, ObservableValue, type Tracer, TransferDiagnostic } from '@hydranium/protocol';
10
+ import {
11
+ defineMessage,
12
+ describeError,
13
+ messageData,
14
+ type LogThreshold,
15
+ type MaybeObservableValue,
16
+ ObservableValue,
17
+ type Tracer,
18
+ TransferDiagnostic
19
+ } from '@hydranium/protocol';
11
20
  import {
12
21
  type AstNode,
13
22
  type AstNodeLocator,
23
+ type AstReflection,
14
24
  DefaultDocumentValidator,
15
25
  type DiagnosticInfo,
16
26
  type LangiumDocument,
@@ -48,6 +58,26 @@ export interface TransferLspDiagnostic extends Diagnostic {
48
58
  property?: string;
49
59
  }
50
60
 
61
+ /**
62
+ * A reference resolved to nothing.
63
+ *
64
+ * **The English is byte-identical to Langium's `DefaultLinker.createLinkingError`
65
+ * sentence, and must stay so.** The identity is attached to a diagnostic Langium
66
+ * already worded, so a divergence here would silently change the text every
67
+ * adopter without a catalogue sees. {@link HydraniumDocumentValidator.processLinkingErrors}
68
+ * attaches it only when the two match exactly, which is also what keeps an
69
+ * adopter's own reworded linking error from being mislabelled as this one.
70
+ *
71
+ * It exists because this is the most-seen validation error in any language built
72
+ * on the framework, and Langium puts its own code in `data.code` rather than on
73
+ * `Diagnostic.code` — so without a framework identity every adopter wanting to
74
+ * render it has to special-case Langium's shape.
75
+ */
76
+ export const UNRESOLVED_REFERENCE = defineMessage(
77
+ 'hydranium/core/unresolved-reference',
78
+ "Could not resolve reference to {referenceType} named '{refText}'."
79
+ );
80
+
51
81
  export interface DocumentValidatorOptions extends LogNameOptions {
52
82
  /**
53
83
  * Level at which the `validateDocument` timing line is emitted, or `'off'`
@@ -94,6 +124,7 @@ export interface DocumentValidatorOptions extends LogNameOptions {
94
124
  export class HydraniumDocumentValidator extends DefaultDocumentValidator {
95
125
  protected readonly tracer: Tracer;
96
126
  protected readonly astNodeLocator: AstNodeLocator;
127
+ protected readonly reflection: AstReflection;
97
128
  protected readonly logLevel: ObservableValue<LogThreshold>;
98
129
  protected readonly logAfterMs: ObservableValue<number>;
99
130
  protected readonly validateVirtualDocuments: ObservableValue<boolean>;
@@ -103,6 +134,7 @@ export class HydraniumDocumentValidator extends DefaultDocumentValidator {
103
134
  super(services);
104
135
  this.tracer = services.shared.Tracer.for(options.logName ?? 'DocumentValidator').trace('instantiated');
105
136
  this.astNodeLocator = services.workspace.AstNodeLocator;
137
+ this.reflection = services.shared.AstReflection;
106
138
  this.logLevel = ObservableValue.from(options.logLevel ?? 'debug');
107
139
  this.logAfterMs = ObservableValue.from(options.logAfterMs ?? 20);
108
140
  this.validateVirtualDocuments = ObservableValue.from(options.validateVirtualDocuments ?? false);
@@ -157,6 +189,90 @@ export class HydraniumDocumentValidator extends DefaultDocumentValidator {
157
189
  return !this.validateSyntheticNodes.value && isSyntheticNode(node);
158
190
  }
159
191
 
192
+ /**
193
+ * Langium's linking-error pass, plus the framework identity on each
194
+ * diagnostic it produced.
195
+ *
196
+ * Langium puts its own `linking-error` marker in `data.code` and leaves
197
+ * `Diagnostic.code` unset, so nothing identifies the message on a surface
198
+ * that drops `data` — which is every editor surface. This adds the framework
199
+ * identity to both `code` and `data.hydranium` while LEAVING `data.code` in
200
+ * place: `stopAfterLinkingErrors` and Langium's code-action dispatch both
201
+ * read it.
202
+ *
203
+ * **The identity is attached only when the message is the one
204
+ * {@link UNRESOLVED_REFERENCE} renders.** Two other sentences reach this
205
+ * list: the linker's exception form, raised when resolution itself throws,
206
+ * and whatever an adopter overriding `createLinkingError` chose. Labelling
207
+ * either would make a catalogue render the wrong sentence — and for the
208
+ * exception form it would discard the underlying cause. Comparing against
209
+ * the locally rendered English is what discriminates; there is no structural
210
+ * field that does.
211
+ */
212
+ protected override processLinkingErrors(document: LangiumDocument, diagnostics: Diagnostic[], options: ValidationOptions): void {
213
+ const from = diagnostics.length;
214
+ super.processLinkingErrors(document, diagnostics, options);
215
+ for (let index = from; index < diagnostics.length; index++) {
216
+ diagnostics[index] = this.identifyLinkingError(diagnostics[index]);
217
+ }
218
+ }
219
+
220
+ /**
221
+ * Add the {@link UNRESOLVED_REFERENCE} identity to one linking diagnostic,
222
+ * or return it untouched when its message is not the sentence that identity
223
+ * renders.
224
+ *
225
+ * `refText` comes from the `data` Langium populated; `referenceType` is not
226
+ * in it, so it is recovered the same way `createLinkingError` produced it —
227
+ * through the reflection, from the container type and property.
228
+ */
229
+ protected identifyLinkingError(diagnostic: Diagnostic): Diagnostic {
230
+ const data = diagnostic.data as { code?: unknown; refText?: unknown; containerType?: unknown; property?: unknown } | undefined;
231
+ if (typeof data?.refText !== 'string' || typeof data.containerType !== 'string' || typeof data.property !== 'string') {
232
+ return diagnostic;
233
+ }
234
+ const referenceType = this.referenceTypeOf(data.containerType, data.property, data.refText);
235
+ if (referenceType === undefined) {
236
+ return diagnostic;
237
+ }
238
+ const params = { referenceType, refText: data.refText };
239
+ if (diagnostic.message !== UNRESOLVED_REFERENCE.format(params)) {
240
+ return diagnostic;
241
+ }
242
+ // Merged OVER Langium's data rather than replacing it, so `data.code`
243
+ // survives for the readers that switch on it.
244
+ return { ...diagnostic, code: UNRESOLVED_REFERENCE.code, data: { ...data, ...messageData(UNRESOLVED_REFERENCE, params) } };
245
+ }
246
+
247
+ /**
248
+ * The declared target type of the reference this diagnostic came from, or
249
+ * `undefined` when the reflection cannot name one.
250
+ *
251
+ * **The lookup can throw, and that is the reason this is a method rather
252
+ * than an inline call.** `AbstractAstReflection.getReferenceType` raises on
253
+ * an unknown container `$type` and on a property that is not a reference —
254
+ * and the linking error whose type it cannot name is the one most likely to
255
+ * reach here, because `DefaultLinker` catches its OWN failed lookup and
256
+ * turns it into the exception-form message. Rethrowing would take
257
+ * `validateDocument` with it, since Langium wraps `processLinkingErrors` in
258
+ * no try: a diagnostic Langium degraded gracefully would become a failed
259
+ * build. Declining is also the right answer on the merits — a reference
260
+ * whose type cannot be named is not the message
261
+ * {@link UNRESOLVED_REFERENCE} claims.
262
+ */
263
+ protected referenceTypeOf(containerType: string, property: string, refText: string): string | undefined {
264
+ try {
265
+ return this.reflection.getReferenceType({
266
+ container: { $type: containerType } as AstNode,
267
+ property,
268
+ reference: { $refText: refText }
269
+ } as Parameters<AstReflection['getReferenceType']>[0]);
270
+ } catch (err: unknown) {
271
+ this.tracer.debug(`cannot name the reference type for ${containerType}.${property}: ${describeError(err)}`);
272
+ return undefined;
273
+ }
274
+ }
275
+
160
276
  protected override toDiagnostic<N extends AstNode>(
161
277
  severity: ValidationSeverity,
162
278
  message: string,
@@ -9,9 +9,10 @@
9
9
 
10
10
  import { Deferred, type Logger, type Tracer } from '@hydranium/protocol';
11
11
  import { DefaultWorkspaceManager, DocumentState, type LangiumDocument, UriUtils, type URI } from '@hydranium/langium';
12
- import { type CancellationToken } from 'vscode-languageserver';
12
+ import { type CancellationToken, type InitializeParams } from 'vscode-languageserver';
13
13
  import type { WorkspaceFolder } from 'vscode-languageserver-types';
14
14
  import { type LogNameOptions, resolveLogFilePlaceholder, toLogFileWorkspaceToken } from '../diagnostics/logger.js';
15
+ import type { ServerLocale } from '../../locale/server-locale.js';
15
16
  import type { ProjectChangeEvent } from '../project/project-change-event.js';
16
17
  import type { ProjectManager } from '../project/project-manager.js';
17
18
  import type { ServerSharedServicesMinimal } from '../shared-services.js';
@@ -156,6 +157,8 @@ export class HydraniumWorkspaceManager extends DefaultWorkspaceManager {
156
157
  readonly workspaceInitialized: Promise<unknown> = this.workspaceInitializedDeferred.promise;
157
158
 
158
159
  protected readonly uriPolicy: DocumentUriPolicy;
160
+ /** Handed the client's locale at init; read by whoever renders in it. */
161
+ protected readonly serverLocale: ServerLocale;
159
162
  protected readonly writableFileSystemProvider: WritableFileSystemProvider;
160
163
  protected readonly additionalDocuments: Record<string, AdditionalDocumentContribution>;
161
164
  /** Registry consulted by {@link warnIfUnroutable} to check a seeded document routes. */
@@ -166,6 +169,7 @@ export class HydraniumWorkspaceManager extends DefaultWorkspaceManager {
166
169
  this.projectManager = services.workspace.ProjectManager;
167
170
  this.projectManager.onProjectsChanged(event => this.onProjectsChanged(event));
168
171
  this.uriPolicy = services.workspace.DocumentUriPolicy;
172
+ this.serverLocale = services.ServerLocale;
169
173
  this.writableFileSystemProvider = services.workspace.FileSystemProvider;
170
174
  this.additionalDocuments = services.additionalDocuments;
171
175
  this.languageRegistry = services.ServiceRegistry;
@@ -360,6 +364,19 @@ export class HydraniumWorkspaceManager extends DefaultWorkspaceManager {
360
364
  }
361
365
  }
362
366
 
367
+ /**
368
+ * Forward the locale the client declared, then Langium's own read of the
369
+ * params. `DefaultWorkspaceManager.initialize` reads `workspaceFolders`
370
+ * alone, so `params.locale` would otherwise be discarded — and this is the
371
+ * only place it arrives, which the headless init seams route through too.
372
+ */
373
+ override initialize(params: InitializeParams): void {
374
+ if (params.locale) {
375
+ this.serverLocale.accept(params.locale);
376
+ }
377
+ super.initialize(params);
378
+ }
379
+
363
380
  /**
364
381
  * Override of Langium's workspace setup to resolve / reject
365
382
  * {@link workspaceInitializedDeferred} once setup completes. Adopters with
@@ -18,6 +18,25 @@ import type { ServerSharedServicesMinimal } from '../shared-services.js';
18
18
  /** A workspace folder root accepted by the headless init seams: a filesystem path or a {@link URI}. */
19
19
  export type WorkspaceFolderInput = string | URI;
20
20
 
21
+ /**
22
+ * Options for the headless init seams.
23
+ *
24
+ * **Optional, and the parameter is optional too**, so that no existing caller
25
+ * has to change to gain a field it does not set.
26
+ */
27
+ export interface ProgrammaticInitOptions {
28
+ /**
29
+ * The locale to render user-facing server messages in — the headless
30
+ * equivalent of LSP `initialize`'s `locale`, for a head with no LSP
31
+ * connection (`startStdioServer`, the CLI subcommands, a test harness).
32
+ *
33
+ * Omitted means no locale, which the default renderer resolves as the
34
+ * framework's English. That is the correct answer for a headless tool: it
35
+ * has no reading user to have a language.
36
+ */
37
+ readonly locale?: string;
38
+ }
39
+
21
40
  /**
22
41
  * Normalize the seam's flexible folder argument to LSP {@link WorkspaceFolder}s.
23
42
  * A `string` is resolved to an absolute filesystem path and wrapped as a
@@ -58,17 +77,25 @@ function toWorkspaceFolders(folders: WorkspaceFolderInput | ReadonlyArray<Worksp
58
77
  *
59
78
  * @param services the shared services tree the workspace manager lives on
60
79
  * @param folders one or more workspace roots (filesystem paths or URIs)
80
+ * @param options the message locale, when the caller has one
61
81
  */
62
82
  export async function initializeWorkspaceProgrammatically(
63
83
  services: ServerSharedServicesMinimal,
64
- folders: WorkspaceFolderInput | ReadonlyArray<WorkspaceFolderInput>
84
+ folders: WorkspaceFolderInput | ReadonlyArray<WorkspaceFolderInput>,
85
+ options: ProgrammaticInitOptions = {}
65
86
  ): Promise<void> {
66
87
  const workspaceFolders = toWorkspaceFolders(folders);
67
88
  const manager = services.workspace.WorkspaceManager;
68
- // `initialize` records the folders (DefaultWorkspaceManager reads only this
89
+ // `locale` goes through the synthesized params rather than a direct
90
+ // `acceptLocale` call, so this seam and a real LSP `initialize` reach the
91
+ // slot by the SAME path — an adopter overriding the capture in
92
+ // `HydraniumWorkspaceManager.initialize` is honoured headlessly too, which a
93
+ // second write site here would silently bypass.
94
+ //
95
+ // `initialize` records the folders (DefaultWorkspaceManager reads only that
69
96
  // field); `initialized` runs `mutex.write(initializeWorkspace)` and resolves
70
97
  // once discovery + the init build settle, so awaiting it is the ready gate.
71
- manager.initialize({ workspaceFolders } as InitializeParams);
98
+ manager.initialize({ workspaceFolders, locale: options.locale } as InitializeParams);
72
99
  await manager.initialized({} as InitializedParams);
73
100
  }
74
101
 
@@ -91,12 +118,14 @@ export async function initializeWorkspaceProgrammatically(
91
118
  *
92
119
  * @param services the shared services tree the workspace manager lives on
93
120
  * @param folders one or more workspace roots (filesystem paths or URIs)
121
+ * @param options the message locale, when the caller has one
94
122
  */
95
123
  export async function buildWorkspaceProgrammatically(
96
124
  services: ServerSharedServicesMinimal,
97
- folders: WorkspaceFolderInput | ReadonlyArray<WorkspaceFolderInput>
125
+ folders: WorkspaceFolderInput | ReadonlyArray<WorkspaceFolderInput>,
126
+ options: ProgrammaticInitOptions = {}
98
127
  ): Promise<void> {
99
- await initializeWorkspaceProgrammatically(services, folders);
128
+ await initializeWorkspaceProgrammatically(services, folders, options);
100
129
  const documents = services.workspace.LangiumDocuments.all.toArray();
101
130
  await services.workspace.DocumentBuilder.build(documents, { validation: true });
102
131
  }
@@ -0,0 +1,10 @@
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
+ export * from './server-locale.js';