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

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 (107) 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/keys/containment.d.ts +64 -0
  16. package/lib/langium/keys/containment.d.ts.map +1 -0
  17. package/lib/langium/keys/containment.js +53 -0
  18. package/lib/langium/keys/containment.js.map +1 -0
  19. package/lib/langium/keys/index.d.ts +1 -0
  20. package/lib/langium/keys/index.d.ts.map +1 -1
  21. package/lib/langium/keys/index.js +1 -0
  22. package/lib/langium/keys/index.js.map +1 -1
  23. package/lib/langium/keys/name-based-key-provider.d.ts +4 -0
  24. package/lib/langium/keys/name-based-key-provider.d.ts.map +1 -1
  25. package/lib/langium/keys/name-based-key-provider.js +4 -0
  26. package/lib/langium/keys/name-based-key-provider.js.map +1 -1
  27. package/lib/langium/model-service/model-service.d.ts +39 -2
  28. package/lib/langium/model-service/model-service.d.ts.map +1 -1
  29. package/lib/langium/model-service/model-service.js +44 -5
  30. package/lib/langium/model-service/model-service.js.map +1 -1
  31. package/lib/langium/module.d.ts +20 -0
  32. package/lib/langium/module.d.ts.map +1 -1
  33. package/lib/langium/module.js +4 -0
  34. package/lib/langium/module.js.map +1 -1
  35. package/lib/langium/naming/name-provider.d.ts +10 -0
  36. package/lib/langium/naming/name-provider.d.ts.map +1 -1
  37. package/lib/langium/naming/name-provider.js.map +1 -1
  38. package/lib/langium/naming/name-separator-validation.d.ts +23 -1
  39. package/lib/langium/naming/name-separator-validation.d.ts.map +1 -1
  40. package/lib/langium/naming/name-separator-validation.js +22 -0
  41. package/lib/langium/naming/name-separator-validation.js.map +1 -1
  42. package/lib/langium/shared-services.d.ts +13 -2
  43. package/lib/langium/shared-services.d.ts.map +1 -1
  44. package/lib/langium/shared-services.js.map +1 -1
  45. package/lib/langium/validation/document-validator.d.ts +128 -2
  46. package/lib/langium/validation/document-validator.d.ts.map +1 -1
  47. package/lib/langium/validation/document-validator.js +211 -4
  48. package/lib/langium/validation/document-validator.js.map +1 -1
  49. package/lib/langium/workspace/hydranium-workspace-manager.d.ts +21 -1
  50. package/lib/langium/workspace/hydranium-workspace-manager.d.ts.map +1 -1
  51. package/lib/langium/workspace/hydranium-workspace-manager.js +28 -0
  52. package/lib/langium/workspace/hydranium-workspace-manager.js.map +1 -1
  53. package/lib/langium/workspace/initialize-workspace.d.ts +22 -2
  54. package/lib/langium/workspace/initialize-workspace.d.ts.map +1 -1
  55. package/lib/langium/workspace/initialize-workspace.js +13 -5
  56. package/lib/langium/workspace/initialize-workspace.js.map +1 -1
  57. package/lib/locale/index.d.ts +10 -0
  58. package/lib/locale/index.d.ts.map +1 -0
  59. package/lib/locale/index.js +10 -0
  60. package/lib/locale/index.js.map +1 -0
  61. package/lib/locale/server-locale.d.ts +59 -0
  62. package/lib/locale/server-locale.d.ts.map +1 -0
  63. package/lib/locale/server-locale.js +61 -0
  64. package/lib/locale/server-locale.js.map +1 -0
  65. package/lib/messages/carriers.d.ts +15 -7
  66. package/lib/messages/carriers.d.ts.map +1 -1
  67. package/lib/messages/carriers.js +19 -8
  68. package/lib/messages/carriers.js.map +1 -1
  69. package/lib/messages/index.d.ts +3 -0
  70. package/lib/messages/index.d.ts.map +1 -1
  71. package/lib/messages/index.js +3 -0
  72. package/lib/messages/index.js.map +1 -1
  73. package/lib/messages/renderer.d.ts +117 -0
  74. package/lib/messages/renderer.d.ts.map +1 -0
  75. package/lib/messages/renderer.js +159 -0
  76. package/lib/messages/renderer.js.map +1 -0
  77. package/lib/testing/make-noop-shared-services.d.ts +14 -0
  78. package/lib/testing/make-noop-shared-services.d.ts.map +1 -1
  79. package/lib/testing/make-noop-shared-services.js +28 -2
  80. package/lib/testing/make-noop-shared-services.js.map +1 -1
  81. package/lib/testing/make-test-services.d.ts +27 -0
  82. package/lib/testing/make-test-services.d.ts.map +1 -1
  83. package/lib/testing/make-test-services.js +17 -1
  84. package/lib/testing/make-test-services.js.map +1 -1
  85. package/package.json +5 -5
  86. package/src/documents/hydranium-text-documents.ts +12 -1
  87. package/src/index.ts +1 -0
  88. package/src/langium/bootstrap.ts +8 -1
  89. package/src/langium/document-builder/document-builder.ts +70 -2
  90. package/src/langium/keys/containment.ts +87 -0
  91. package/src/langium/keys/index.ts +1 -0
  92. package/src/langium/keys/name-based-key-provider.ts +4 -0
  93. package/src/langium/model-service/model-service.ts +46 -4
  94. package/src/langium/module.ts +22 -0
  95. package/src/langium/naming/name-provider.ts +10 -0
  96. package/src/langium/naming/name-separator-validation.ts +25 -3
  97. package/src/langium/shared-services.ts +13 -2
  98. package/src/langium/validation/document-validator.ts +238 -4
  99. package/src/langium/workspace/hydranium-workspace-manager.ts +30 -1
  100. package/src/langium/workspace/initialize-workspace.ts +34 -5
  101. package/src/locale/index.ts +10 -0
  102. package/src/locale/server-locale.ts +71 -0
  103. package/src/messages/carriers.ts +20 -10
  104. package/src/messages/index.ts +3 -0
  105. package/src/messages/renderer.ts +184 -0
  106. package/src/testing/make-noop-shared-services.ts +50 -2
  107. package/src/testing/make-test-services.ts +43 -1
@@ -7,12 +7,23 @@
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,
26
+ DocumentValidator,
16
27
  type LangiumDocument,
17
28
  type LangiumCoreServices,
18
29
  type ValidateSingleNodeOptions,
@@ -20,7 +31,10 @@ import {
20
31
  type ValidationSeverity
21
32
  } from '@hydranium/langium';
22
33
  import type { CancellationToken } from 'vscode-languageserver-protocol';
23
- import type { Diagnostic } from 'vscode-languageserver-types';
34
+ // A VALUE import, for `Diagnostic.getMessageString`: `message` is
35
+ // `string | MarkupContent` in LSP 3.17+, so upstream's own reader is what
36
+ // narrows it rather than a hand-rolled union check here.
37
+ import { Diagnostic } from 'vscode-languageserver-types';
24
38
  import { type LogNameOptions } from '../diagnostics/logger.js';
25
39
  import { isSyntheticNode } from '../workspace/synthetic.js';
26
40
  import { isVirtualUri } from '../workspace/virtual-document.js';
@@ -48,6 +62,71 @@ export interface TransferLspDiagnostic extends Diagnostic {
48
62
  property?: string;
49
63
  }
50
64
 
65
+ /**
66
+ * A reference resolved to nothing.
67
+ *
68
+ * **The English is byte-identical to Langium's `DefaultLinker.createLinkingError`
69
+ * sentence, and must stay so.** The identity is attached to a diagnostic Langium
70
+ * already worded, so a divergence here would silently change the text every
71
+ * adopter without a catalogue sees. {@link HydraniumDocumentValidator.processLinkingErrors}
72
+ * attaches it only when the two match exactly, which is also what keeps an
73
+ * adopter's own reworded linking error from being mislabelled as this one.
74
+ *
75
+ * It exists because this is the most-seen validation error in any language built
76
+ * on the framework, and Langium puts its own code in `data.code` rather than on
77
+ * `Diagnostic.code` — so without a framework identity every adopter wanting to
78
+ * render it has to special-case Langium's shape.
79
+ */
80
+ export const UNRESOLVED_REFERENCE = defineMessage(
81
+ 'hydranium/core/unresolved-reference',
82
+ "Could not resolve reference to {referenceType} named '{refText}'."
83
+ );
84
+
85
+ /**
86
+ * A character no token of the grammar can start with.
87
+ *
88
+ * **The English is byte-identical to CHEVROTAIN's
89
+ * `defaultLexerErrorProvider.buildUnexpectedCharactersMessage`, and must stay
90
+ * so** — one layer further out than {@link UNRESOLVED_REFERENCE}, whose sentence
91
+ * is Langium's. Langium words neither: `processLexingErrors` copies
92
+ * `lexerDiagnostic.message` through untouched, so the text an adopter sees today
93
+ * is produced two dependencies down and is the only thing this identity may
94
+ * claim to be. {@link HydraniumDocumentValidator.identifyLexingError} attaches
95
+ * it only when the two match exactly, which is also what keeps a custom lexer's
96
+ * own diagnostics — Langium admits any of them through `lexerReport` — from
97
+ * being mislabelled as this one.
98
+ *
99
+ * It exists because a lexing error is the FIRST message a user of a new language
100
+ * sees and the one an adopter cannot reach: every other diagnostic worth
101
+ * translating either carries an identity already or is raised by adopter code,
102
+ * while this one arrives with a Langium `data.code` naming a KIND and no
103
+ * parameters at all — so a catalogue had nothing to key on and nothing to
104
+ * interpolate.
105
+ *
106
+ * `skipped` rather than `length`, matching what the sentence says the number
107
+ * means: chevrotain reports how many characters the lexer discarded to recover,
108
+ * which for a single stray character is one and for a run of them is the run.
109
+ */
110
+ export const LEXING_ERROR = defineMessage(
111
+ 'hydranium/core/lexing-error',
112
+ 'unexpected character: ->{character}<- at offset: {offset}, skipped {skipped} characters.'
113
+ );
114
+
115
+ /**
116
+ * Langium's own `data.code` values for a diagnostic that came out of the lexer.
117
+ *
118
+ * All four severities, not just the error one: `lexerReport` admits warnings and
119
+ * below, and a token builder that downgrades a stray character still produces
120
+ * the same sentence. Gating on the error code alone would leave the identity off
121
+ * a message that is word-for-word the one it names.
122
+ */
123
+ const LEXING_CODES: ReadonlySet<unknown> = new Set([
124
+ DocumentValidator.LexingError,
125
+ DocumentValidator.LexingWarning,
126
+ DocumentValidator.LexingInfo,
127
+ DocumentValidator.LexingHint
128
+ ]);
129
+
51
130
  export interface DocumentValidatorOptions extends LogNameOptions {
52
131
  /**
53
132
  * Level at which the `validateDocument` timing line is emitted, or `'off'`
@@ -94,6 +173,7 @@ export interface DocumentValidatorOptions extends LogNameOptions {
94
173
  export class HydraniumDocumentValidator extends DefaultDocumentValidator {
95
174
  protected readonly tracer: Tracer;
96
175
  protected readonly astNodeLocator: AstNodeLocator;
176
+ protected readonly reflection: AstReflection;
97
177
  protected readonly logLevel: ObservableValue<LogThreshold>;
98
178
  protected readonly logAfterMs: ObservableValue<number>;
99
179
  protected readonly validateVirtualDocuments: ObservableValue<boolean>;
@@ -103,6 +183,7 @@ export class HydraniumDocumentValidator extends DefaultDocumentValidator {
103
183
  super(services);
104
184
  this.tracer = services.shared.Tracer.for(options.logName ?? 'DocumentValidator').trace('instantiated');
105
185
  this.astNodeLocator = services.workspace.AstNodeLocator;
186
+ this.reflection = services.shared.AstReflection;
106
187
  this.logLevel = ObservableValue.from(options.logLevel ?? 'debug');
107
188
  this.logAfterMs = ObservableValue.from(options.logAfterMs ?? 20);
108
189
  this.validateVirtualDocuments = ObservableValue.from(options.validateVirtualDocuments ?? false);
@@ -124,16 +205,85 @@ export class HydraniumDocumentValidator extends DefaultDocumentValidator {
124
205
  }
125
206
  const level = this.logLevel.value;
126
207
  if (level === 'off') {
127
- return super.validateDocument(document, options, cancelToken);
208
+ return this.validateAndIdentify(document, options, cancelToken);
128
209
  }
129
210
  // `level` is narrowed to `LogLevel` past the early-return.
130
211
  return this.tracer
131
212
  .withUri(document.uri.toString())
132
- .time('validateDocument', () => super.validateDocument(document, options, cancelToken), level, {
213
+ .time('validateDocument', () => this.validateAndIdentify(document, options, cancelToken), level, {
133
214
  logAfterMs: this.logAfterMs.value
134
215
  });
135
216
  }
136
217
 
218
+ /**
219
+ * Langium's validation pass, plus the framework identity on the lexing
220
+ * diagnostics it produced.
221
+ *
222
+ * **Here rather than in an override of `processLexingErrors`, and the reason
223
+ * is that the seam cannot see what the identity needs.** Langium hands that
224
+ * method a `ParseResult`, which carries the AST and the error lists but not
225
+ * the source text — and the offending CHARACTER is the parameter a
226
+ * translation exists to interpolate. The document does carry it, and this is
227
+ * the innermost point that still holds one. Reconstructing the character by
228
+ * matching it out of the finished sentence was the alternative, and it
229
+ * inverts the direction the rest of this file works in: every other identity
230
+ * here is derived from structured fields and CHECKED against the prose.
231
+ *
232
+ * Inside the timing span rather than around it, so the line accounts for the
233
+ * whole pass.
234
+ */
235
+ protected async validateAndIdentify(
236
+ document: LangiumDocument,
237
+ options?: ValidationOptions,
238
+ cancelToken?: CancellationToken
239
+ ): Promise<Diagnostic[]> {
240
+ const diagnostics = await super.validateDocument(document, options, cancelToken);
241
+ // Mapped in place over the array Langium built, rather than filtered and
242
+ // re-concatenated: the publish order is the diagnostic order and a
243
+ // reordering would move a squiggle's entry in the problems list.
244
+ for (let index = 0; index < diagnostics.length; index++) {
245
+ diagnostics[index] = this.identifyLexingError(document, diagnostics[index]);
246
+ }
247
+ return diagnostics;
248
+ }
249
+
250
+ /**
251
+ * Add the {@link LEXING_ERROR} identity to one diagnostic, or return it
252
+ * untouched when it is not the sentence that identity renders.
253
+ *
254
+ * The parameters come from the diagnostic's own RANGE, not from
255
+ * `parseResult.lexerErrors`. Both hold the same numbers, and the range is the
256
+ * one that needs no assumption about upstream: correlating the two lists
257
+ * would depend on Langium appending one diagnostic per lexer error in order,
258
+ * which is true today and is an internal of the method being wrapped.
259
+ *
260
+ * **The format-and-compare is the whole discriminator, and it validates the
261
+ * reconstruction as well as the identity.** A range that did not round-trip
262
+ * to the offset chevrotain reported would produce a different sentence and be
263
+ * declined, so a wrong parameter set can never be attached to a right-looking
264
+ * message.
265
+ */
266
+ protected identifyLexingError(document: LangiumDocument, diagnostic: Diagnostic): Diagnostic {
267
+ const data = diagnostic.data as { code?: unknown } | undefined;
268
+ if (!LEXING_CODES.has(data?.code)) {
269
+ return diagnostic;
270
+ }
271
+ const text = document.textDocument;
272
+ const offset = text.offsetAt(diagnostic.range.start);
273
+ const params = {
274
+ character: text.getText().charAt(offset),
275
+ offset,
276
+ skipped: text.offsetAt(diagnostic.range.end) - offset
277
+ };
278
+ if (Diagnostic.getMessageString(diagnostic) !== LEXING_ERROR.format(params)) {
279
+ return diagnostic;
280
+ }
281
+ // Merged OVER Langium's data, so `data.code` survives for the readers that
282
+ // switch on it — `stopAfterLexingErrors` is one, and the GLSP head's
283
+ // read-only decision is another.
284
+ return { ...diagnostic, code: LEXING_ERROR.code, data: { ...data, ...messageData(LEXING_ERROR, params) } };
285
+ }
286
+
137
287
  /**
138
288
  * Skip validation for a node **and its children** when
139
289
  * {@link shouldSkipValidation} returns true.
@@ -157,6 +307,90 @@ export class HydraniumDocumentValidator extends DefaultDocumentValidator {
157
307
  return !this.validateSyntheticNodes.value && isSyntheticNode(node);
158
308
  }
159
309
 
310
+ /**
311
+ * Langium's linking-error pass, plus the framework identity on each
312
+ * diagnostic it produced.
313
+ *
314
+ * Langium puts its own `linking-error` marker in `data.code` and leaves
315
+ * `Diagnostic.code` unset, so nothing identifies the message on a surface
316
+ * that drops `data` — which is every editor surface. This adds the framework
317
+ * identity to both `code` and `data.hydranium` while LEAVING `data.code` in
318
+ * place: `stopAfterLinkingErrors` and Langium's code-action dispatch both
319
+ * read it.
320
+ *
321
+ * **The identity is attached only when the message is the one
322
+ * {@link UNRESOLVED_REFERENCE} renders.** Two other sentences reach this
323
+ * list: the linker's exception form, raised when resolution itself throws,
324
+ * and whatever an adopter overriding `createLinkingError` chose. Labelling
325
+ * either would make a catalogue render the wrong sentence — and for the
326
+ * exception form it would discard the underlying cause. Comparing against
327
+ * the locally rendered English is what discriminates; there is no structural
328
+ * field that does.
329
+ */
330
+ protected override processLinkingErrors(document: LangiumDocument, diagnostics: Diagnostic[], options: ValidationOptions): void {
331
+ const from = diagnostics.length;
332
+ super.processLinkingErrors(document, diagnostics, options);
333
+ for (let index = from; index < diagnostics.length; index++) {
334
+ diagnostics[index] = this.identifyLinkingError(diagnostics[index]);
335
+ }
336
+ }
337
+
338
+ /**
339
+ * Add the {@link UNRESOLVED_REFERENCE} identity to one linking diagnostic,
340
+ * or return it untouched when its message is not the sentence that identity
341
+ * renders.
342
+ *
343
+ * `refText` comes from the `data` Langium populated; `referenceType` is not
344
+ * in it, so it is recovered the same way `createLinkingError` produced it —
345
+ * through the reflection, from the container type and property.
346
+ */
347
+ protected identifyLinkingError(diagnostic: Diagnostic): Diagnostic {
348
+ const data = diagnostic.data as { code?: unknown; refText?: unknown; containerType?: unknown; property?: unknown } | undefined;
349
+ if (typeof data?.refText !== 'string' || typeof data.containerType !== 'string' || typeof data.property !== 'string') {
350
+ return diagnostic;
351
+ }
352
+ const referenceType = this.referenceTypeOf(data.containerType, data.property, data.refText);
353
+ if (referenceType === undefined) {
354
+ return diagnostic;
355
+ }
356
+ const params = { referenceType, refText: data.refText };
357
+ if (diagnostic.message !== UNRESOLVED_REFERENCE.format(params)) {
358
+ return diagnostic;
359
+ }
360
+ // Merged OVER Langium's data rather than replacing it, so `data.code`
361
+ // survives for the readers that switch on it.
362
+ return { ...diagnostic, code: UNRESOLVED_REFERENCE.code, data: { ...data, ...messageData(UNRESOLVED_REFERENCE, params) } };
363
+ }
364
+
365
+ /**
366
+ * The declared target type of the reference this diagnostic came from, or
367
+ * `undefined` when the reflection cannot name one.
368
+ *
369
+ * **The lookup can throw, and that is the reason this is a method rather
370
+ * than an inline call.** `AbstractAstReflection.getReferenceType` raises on
371
+ * an unknown container `$type` and on a property that is not a reference —
372
+ * and the linking error whose type it cannot name is the one most likely to
373
+ * reach here, because `DefaultLinker` catches its OWN failed lookup and
374
+ * turns it into the exception-form message. Rethrowing would take
375
+ * `validateDocument` with it, since Langium wraps `processLinkingErrors` in
376
+ * no try: a diagnostic Langium degraded gracefully would become a failed
377
+ * build. Declining is also the right answer on the merits — a reference
378
+ * whose type cannot be named is not the message
379
+ * {@link UNRESOLVED_REFERENCE} claims.
380
+ */
381
+ protected referenceTypeOf(containerType: string, property: string, refText: string): string | undefined {
382
+ try {
383
+ return this.reflection.getReferenceType({
384
+ container: { $type: containerType } as AstNode,
385
+ property,
386
+ reference: { $refText: refText }
387
+ } as Parameters<AstReflection['getReferenceType']>[0]);
388
+ } catch (err: unknown) {
389
+ this.tracer.debug(`cannot name the reference type for ${containerType}.${property}: ${describeError(err)}`);
390
+ return undefined;
391
+ }
392
+ }
393
+
160
394
  protected override toDiagnostic<N extends AstNode>(
161
395
  severity: ValidationSeverity,
162
396
  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,31 @@ 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
+ * **The ABSENT case is reported from here rather than from `ServerLocale`,
374
+ * because this is the only end that can see it.** `accept` is not called
375
+ * when no locale was declared — nor should it be, since `''` is a claim
376
+ * about a language rather than the absence of one — so a log written there
377
+ * covers one of the two outcomes and leaves the other looking like a server
378
+ * that never reached init. Both lines are at `info` for the reason `accept`
379
+ * gives: the framework ships no catalogue, so an undeclared locale and an
380
+ * untranslated code produce the same English and the log is what separates
381
+ * them.
382
+ */
383
+ override initialize(params: InitializeParams): void {
384
+ if (params.locale) {
385
+ this.serverLocale.accept(params.locale);
386
+ } else {
387
+ this.tracer.info("no locale declared at init — rendering messages in the framework's English");
388
+ }
389
+ super.initialize(params);
390
+ }
391
+
363
392
  /**
364
393
  * Override of Langium's workspace setup to resolve / reject
365
394
  * {@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';
@@ -0,0 +1,71 @@
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 type { Tracer } from '@hydranium/protocol';
11
+ import { type LogNameOptions } from '../langium/diagnostics/logger.js';
12
+ import type { ServerSharedServicesMinimal } from '../langium/shared-services.js';
13
+
14
+ /** Construction options for {@link ServerLocale}. */
15
+ export type ServerLocaleOptions = LogNameOptions;
16
+
17
+ /**
18
+ * The locale the server was handed at init, for whoever needs to render in the
19
+ * reading user's language. Held apart from the message renderer that reads it,
20
+ * so replacing the renderer cannot drop locale handling.
21
+ *
22
+ * A plain string in and out. A consumer that must react to a change rather than
23
+ * read the current value wraps this itself — nothing does today, and both real
24
+ * hosts respawn the server on a display-language switch.
25
+ */
26
+ export class ServerLocale {
27
+ protected readonly tracer: Tracer;
28
+ protected current: string | undefined;
29
+
30
+ constructor(services: ServerSharedServicesMinimal, options: ServerLocaleOptions = {}) {
31
+ this.tracer = services.Tracer.for(options.logName ?? 'ServerLocale').trace('instantiated');
32
+ }
33
+
34
+ /** The locale, or `undefined` when no init supplied one — which means the framework's English. */
35
+ get value(): string | undefined {
36
+ return this.current;
37
+ }
38
+
39
+ /**
40
+ * Take the locale an init declared.
41
+ *
42
+ * **One locale per process, and the reason the OTHER heads need none of
43
+ * their own.** The data and GLSP heads publish a port over the LSP
44
+ * connection and are reached by forwarding a socket to it, so they are the
45
+ * same process as the LSP head that was handed this locale — there is no
46
+ * topology in which one of them serves a second frontend. The Theia backend
47
+ * is the case that would break it, and it holds no locale precisely because
48
+ * it serves every frontend at once; nothing there writes here.
49
+ *
50
+ * The framework accepts a locale and never sources one, and neither
51
+ * validates nor normalises the tag: rejecting an unfamiliar one would be
52
+ * selecting a locale.
53
+ *
54
+ * Override to ignore the argument, which is how a host pins a locale it
55
+ * already knows but has no LSP client to declare.
56
+ *
57
+ * **The line is at `info`, which is a deliberate exception to the
58
+ * per-service default.** A locale is written once per process and it is the
59
+ * one setting that silently changes every user-facing sentence the server
60
+ * produces, so a reader trying to explain an unexpected language has nothing
61
+ * else to look at: the framework ships no catalogue, so "no entry for this
62
+ * code" and "no locale declared" both render the English and are
63
+ * indistinguishable in the output. At `debug` the line is below the default
64
+ * threshold and therefore absent from exactly the log someone would be
65
+ * reading.
66
+ */
67
+ accept(locale: string): void {
68
+ this.current = locale;
69
+ this.tracer.info(`rendering messages in locale '${locale}'`);
70
+ }
71
+ }
@@ -16,7 +16,7 @@ import {
16
16
  type ResolvedMessage
17
17
  } from '@hydranium/protocol';
18
18
  import type { AstNode, DiagnosticData, DiagnosticInfo, Properties, ValidationAcceptor } from '@hydranium/langium';
19
- import type { Diagnostic } from 'vscode-languageserver-protocol';
19
+ import { Diagnostic } from 'vscode-languageserver-protocol';
20
20
 
21
21
  /**
22
22
  * Raise a validation diagnostic from a declaration, so the call site never
@@ -29,6 +29,13 @@ import type { Diagnostic } from 'vscode-languageserver-protocol';
29
29
  * be able to request a quick fix. The identity is merged OVER whatever they
30
30
  * pass, which makes the two conventions co-exist rather than compete.
31
31
  *
32
+ * `data` admits adopter-owned keys beside Langium's, which is why the index
33
+ * signature is there rather than a bare `Partial<DiagnosticData>`. Langium's
34
+ * shape is closed, and a diagnostic that carries a COMPANION payload for its own
35
+ * surface to read — the field a form must highlight, say — has nowhere else to
36
+ * put it: an encoder projecting that payload reads `diagnostic.data`, so the
37
+ * narrower type made the identity and the companion mutually exclusive.
38
+ *
32
39
  * The identity lands in both `code` and `data.hydranium` on purpose. `code` is
33
40
  * what survives to the editor surface; Theia's converter drops `data` before the
34
41
  * squiggle, so a parameterised diagnostic falls back to the server's English
@@ -44,25 +51,28 @@ export function acceptMessage<S extends string, N extends AstNode, P extends Pro
44
51
  accept: ValidationAcceptor,
45
52
  severity: 'error' | 'warning' | 'info' | 'hint',
46
53
  message: MessageDefinition<S>,
47
- info: Omit<DiagnosticInfo<N, P>, 'code' | 'data'> & { data?: Partial<DiagnosticData> },
54
+ info: Omit<DiagnosticInfo<N, P>, 'code' | 'data'> & { data?: Partial<DiagnosticData> & Record<string, unknown> },
48
55
  ...params: ParamsArg<S>
49
56
  ): void {
50
- const data: HydraniumMessageData & Partial<DiagnosticData> = { ...info.data, ...messageData(message, ...params) };
57
+ const data: HydraniumMessageData & Partial<DiagnosticData> & Record<string, unknown> = {
58
+ ...info.data,
59
+ ...messageData(message, ...params)
60
+ };
51
61
  accept(severity, message.format(...params), { ...info, code: message.code, data });
52
62
  }
53
63
 
54
64
  /**
55
- * Recover the identity from a published diagnostic, for a surface that renders
56
- * diagnostics itself.
65
+ * Recover the identity from a published diagnostic, for a surface that
66
+ * identifies or renders diagnostics itself.
57
67
  *
58
- * The `MarkupContent` narrowing is not padding: `Diagnostic.message` is
59
- * `string | MarkupContent` in LSP 3.17+ and this does not compile without it.
60
- * Only the string form is a resolved English sentence.
68
+ * `Diagnostic.message` is `string | MarkupContent` in LSP 3.17+, so the text
69
+ * comes from upstream's own `Diagnostic.getMessageString` rather than a
70
+ * hand-rolled narrowing — consuming the library in its style, and one fewer
71
+ * place restating the union.
61
72
  */
62
73
  export function resolvedFromDiagnostic(diagnostic: Diagnostic): ResolvedMessage | undefined {
63
74
  if (!hasMessageIdentity(diagnostic.data)) {
64
75
  return undefined;
65
76
  }
66
- const text = typeof diagnostic.message === 'string' ? diagnostic.message : diagnostic.message.value;
67
- return { ...diagnostic.data.hydranium, text };
77
+ return { ...diagnostic.data.hydranium, text: Diagnostic.getMessageString(diagnostic) };
68
78
  }
@@ -18,7 +18,10 @@
18
18
  */
19
19
 
20
20
  export * from './carriers.js';
21
+ export * from './renderer.js';
21
22
 
23
+ export { MODEL_UPDATE_EDIT } from '../langium/model-service/model-service.js';
22
24
  export { SEPARATOR_IN_NAME } from '../langium/naming/name-separator-validation.js';
25
+ export { LEXING_ERROR, UNRESOLVED_REFERENCE } from '../langium/validation/document-validator.js';
23
26
  export { NO_LOADABLE_CONTENT } from '../langium/workspace/langium-documents.js';
24
27
  export { NO_SUCH_FILE, NO_SUCH_PATH } from '../langium/workspace/in-memory-file-system-provider.js';