@hydranium/protocol 1.0.0-next.8 → 1.0.0-next.86

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 (124) hide show
  1. package/README.md +35 -1
  2. package/lib/client/data-connection.d.ts +114 -0
  3. package/lib/client/data-connection.d.ts.map +1 -0
  4. package/lib/client/data-connection.js +128 -0
  5. package/lib/client/data-connection.js.map +1 -0
  6. package/lib/client/data-events.d.ts +9 -1
  7. package/lib/client/data-events.d.ts.map +1 -1
  8. package/lib/client/data-events.js +14 -0
  9. package/lib/client/data-events.js.map +1 -1
  10. package/lib/client/data-port.d.ts +17 -22
  11. package/lib/client/data-port.d.ts.map +1 -1
  12. package/lib/client/data-session.d.ts +95 -78
  13. package/lib/client/data-session.d.ts.map +1 -1
  14. package/lib/client/data-session.js +115 -108
  15. package/lib/client/data-session.js.map +1 -1
  16. package/lib/client/index.d.ts +10 -7
  17. package/lib/client/index.d.ts.map +1 -1
  18. package/lib/client/index.js +10 -7
  19. package/lib/client/index.js.map +1 -1
  20. package/lib/client/message-relay.d.ts +8 -2
  21. package/lib/client/message-relay.d.ts.map +1 -1
  22. package/lib/client/message-relay.js +10 -4
  23. package/lib/client/message-relay.js.map +1 -1
  24. package/lib/client/rpc-connection.d.ts +139 -0
  25. package/lib/client/rpc-connection.d.ts.map +1 -0
  26. package/lib/client/rpc-connection.js +171 -0
  27. package/lib/client/rpc-connection.js.map +1 -0
  28. package/lib/client-ids.d.ts +41 -0
  29. package/lib/client-ids.d.ts.map +1 -0
  30. package/lib/client-ids.js +44 -0
  31. package/lib/client-ids.js.map +1 -0
  32. package/lib/data/data-protocol-methods.d.ts +2 -2
  33. package/lib/data/data-protocol-methods.d.ts.map +1 -1
  34. package/lib/data/data-protocol-methods.js +6 -1
  35. package/lib/data/data-protocol-methods.js.map +1 -1
  36. package/lib/data/data-server-protocol.d.ts +35 -2
  37. package/lib/data/data-server-protocol.d.ts.map +1 -1
  38. package/lib/data/events.d.ts +70 -3
  39. package/lib/data/events.d.ts.map +1 -1
  40. package/lib/errors.d.ts +28 -11
  41. package/lib/errors.d.ts.map +1 -1
  42. package/lib/errors.js +35 -17
  43. package/lib/errors.js.map +1 -1
  44. package/lib/index.d.ts +2 -0
  45. package/lib/index.d.ts.map +1 -1
  46. package/lib/index.js +5 -0
  47. package/lib/index.js.map +1 -1
  48. package/lib/messages/index.d.ts +28 -0
  49. package/lib/messages/index.d.ts.map +1 -0
  50. package/lib/messages/index.js +52 -0
  51. package/lib/messages/index.js.map +1 -0
  52. package/lib/messages/primitives.d.ts +141 -0
  53. package/lib/messages/primitives.d.ts.map +1 -0
  54. package/lib/messages/primitives.js +138 -0
  55. package/lib/messages/primitives.js.map +1 -0
  56. package/lib/model-server.d.ts +27 -10
  57. package/lib/model-server.d.ts.map +1 -1
  58. package/lib/model-server.js +4 -2
  59. package/lib/model-server.js.map +1 -1
  60. package/lib/model-service/args.d.ts +14 -13
  61. package/lib/model-service/args.d.ts.map +1 -1
  62. package/lib/model-service/based-on.d.ts +55 -0
  63. package/lib/model-service/based-on.d.ts.map +1 -0
  64. package/lib/model-service/based-on.js +34 -0
  65. package/lib/model-service/based-on.js.map +1 -0
  66. package/lib/model-service/index.d.ts +1 -0
  67. package/lib/model-service/index.d.ts.map +1 -1
  68. package/lib/model-service/index.js +1 -0
  69. package/lib/model-service/index.js.map +1 -1
  70. package/lib/rpc/bind-rpc-methods.d.ts +29 -3
  71. package/lib/rpc/bind-rpc-methods.d.ts.map +1 -1
  72. package/lib/rpc/bind-rpc-methods.js +22 -3
  73. package/lib/rpc/bind-rpc-methods.js.map +1 -1
  74. package/lib/rpc/create-rpc-proxy.d.ts +7 -0
  75. package/lib/rpc/create-rpc-proxy.d.ts.map +1 -1
  76. package/lib/rpc/create-rpc-proxy.js +6 -1
  77. package/lib/rpc/create-rpc-proxy.js.map +1 -1
  78. package/lib/testing/catalogue-audit.d.ts +80 -0
  79. package/lib/testing/catalogue-audit.d.ts.map +1 -0
  80. package/lib/testing/catalogue-audit.js +94 -0
  81. package/lib/testing/catalogue-audit.js.map +1 -0
  82. package/lib/testing/data-doubles.d.ts +11 -12
  83. package/lib/testing/data-doubles.d.ts.map +1 -1
  84. package/lib/testing/data-doubles.js +14 -5
  85. package/lib/testing/data-doubles.js.map +1 -1
  86. package/lib/testing/index.d.ts +1 -0
  87. package/lib/testing/index.d.ts.map +1 -1
  88. package/lib/testing/index.js +4 -1
  89. package/lib/testing/index.js.map +1 -1
  90. package/lib/transfer-diagnostic.d.ts +33 -0
  91. package/lib/transfer-diagnostic.d.ts.map +1 -1
  92. package/lib/transfer-diagnostic.js +23 -0
  93. package/lib/transfer-diagnostic.js.map +1 -1
  94. package/lib/transfer-document.d.ts +15 -5
  95. package/lib/transfer-document.d.ts.map +1 -1
  96. package/lib/transfer-document.js +14 -1
  97. package/lib/transfer-document.js.map +1 -1
  98. package/package.json +11 -2
  99. package/src/client/data-connection.ts +181 -0
  100. package/src/client/data-events.ts +24 -1
  101. package/src/client/data-port.ts +17 -23
  102. package/src/client/data-session.ts +172 -131
  103. package/src/client/index.ts +10 -7
  104. package/src/client/message-relay.ts +28 -6
  105. package/src/client/rpc-connection.ts +230 -0
  106. package/src/client-ids.ts +45 -0
  107. package/src/data/data-protocol-methods.ts +6 -3
  108. package/src/data/data-server-protocol.ts +46 -2
  109. package/src/data/events.ts +74 -3
  110. package/src/errors.ts +41 -19
  111. package/src/index.ts +5 -0
  112. package/src/messages/index.ts +35 -0
  113. package/src/messages/primitives.ts +215 -0
  114. package/src/model-server.ts +30 -11
  115. package/src/model-service/args.ts +15 -13
  116. package/src/model-service/based-on.ts +60 -0
  117. package/src/model-service/index.ts +1 -0
  118. package/src/rpc/bind-rpc-methods.ts +49 -4
  119. package/src/rpc/create-rpc-proxy.ts +14 -1
  120. package/src/testing/catalogue-audit.ts +111 -0
  121. package/src/testing/data-doubles.ts +33 -17
  122. package/src/testing/index.ts +4 -1
  123. package/src/transfer-diagnostic.ts +40 -0
  124. package/src/transfer-document.ts +22 -6
@@ -0,0 +1,215 @@
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 { ResponseError } from 'vscode-jsonrpc';
11
+
12
+ /**
13
+ * The framework externalizes user-facing strings and SELECTS no locale: it
14
+ * relays the one its client declared and renders with whatever templates the
15
+ * adopter installed, defaulting to its English. Every such string carries a
16
+ * stable code beside that English, and exactly one side renders it — the side
17
+ * that knows the reading user's language.
18
+ *
19
+ * Which side that is depends on the message, not on the package. A server
20
+ * message is rendered by the server, at the one seam every carrier passes
21
+ * through, in the locale it was handed at init. A message the client tier raises
22
+ * is rendered there, because those fire when the server is unreachable. Nothing
23
+ * is rendered twice: two renders of one sentence are two authorities over it,
24
+ * and they diverge on the first reword.
25
+ *
26
+ * Codes are `hydranium/<unscoped-package>/<name>`. The package segment locates
27
+ * the declaration, so a message is declared in the package that raises it and a
28
+ * code never names a package it does not live in. `.` and `:` are forbidden in a
29
+ * segment: they are i18next's default key and namespace separators, where either
30
+ * silently becomes a nested lookup that misses.
31
+ */
32
+ export type MessageParams = Readonly<Record<string, string | number>>;
33
+
34
+ type Placeholder<S extends string> = S extends `${string}{${infer Name}}${infer Rest}` ? Name | Placeholder<Rest> : never;
35
+
36
+ export type ParamsOf<S extends string> = [Placeholder<S>] extends [never]
37
+ ? Record<never, never>
38
+ : Readonly<Record<Placeholder<S>, string | number>>;
39
+
40
+ /** Required exactly when the text has placeholders, absent when it does not. */
41
+ export type ParamsArg<S extends string> = [Placeholder<S>] extends [never] ? [] : [params: ParamsOf<S>];
42
+
43
+ /**
44
+ * Rejects a text argument already widened to `string`. Load-bearing rather than
45
+ * defensive: the whole compile-time guarantee is conditional on `S` inferring a
46
+ * literal, and for a concatenated or pre-widened text the placeholder set
47
+ * silently becomes empty, `format()` accepts no arguments, and the missing
48
+ * substitution surfaces only at runtime.
49
+ */
50
+ export type LiteralText<S extends string> = string extends S ? never : S;
51
+
52
+ export interface MessageDefinition<S extends string> {
53
+ readonly code: string;
54
+ readonly text: S;
55
+ format(...args: ParamsArg<S>): string;
56
+ }
57
+
58
+ /**
59
+ * Declare a message. Placeholder names are inferred from `text` rather than
60
+ * declared again in a type argument: a second spelling of every name is the
61
+ * repetition that drifts, since adding a placeholder to the sentence and not to
62
+ * the type compiles.
63
+ */
64
+ export function defineMessage<S extends string>(code: string, text: LiteralText<S>): MessageDefinition<S> {
65
+ const literal = text as S;
66
+ return { code, text: literal, format: (...args) => interpolate(literal, args[0] ?? {}) };
67
+ }
68
+
69
+ const PLACEHOLDER = /\{([^}]+)\}/g;
70
+
71
+ /**
72
+ * Substitute `{name}` tokens, leaving an unfilled token in place.
73
+ *
74
+ * It must not throw. This runs over an adopter's translation as well as our own
75
+ * text, so a typo in a foreign catalogue has to degrade to a slightly wrong
76
+ * sentence rather than raise inside a toast render. Re-scanning the result to
77
+ * detect an unfilled token is what an earlier form did, and it cannot work:
78
+ * `String.replace` does not rescan replacement text, so the check could not tell
79
+ * an unfilled placeholder from user data shaped like one — an element literally
80
+ * named `{separator}` crashed at the authoring site.
81
+ */
82
+ export function interpolate(template: string, params: MessageParams): string {
83
+ // Indexed rather than `key in params`: a hand-built or version-skewed
84
+ // identity can arrive with no params at all, and `in` throws on a non-object
85
+ // where a lookup degrades.
86
+ const lookup = params as Record<string, string | number | undefined> | undefined;
87
+ return template.replace(PLACEHOLDER, (match, key: string) => {
88
+ const value = lookup?.[key];
89
+ return value === undefined ? match : String(value);
90
+ });
91
+ }
92
+
93
+ export interface MessageIdentity {
94
+ readonly code: string;
95
+ readonly params: MessageParams;
96
+ }
97
+
98
+ /**
99
+ * Envelope for a protocol `data` field. Namespaced under one key so it co-exists
100
+ * with a carrier's own `data` conventions rather than occupying `data` itself.
101
+ */
102
+ export interface HydraniumMessageData {
103
+ readonly hydranium: MessageIdentity;
104
+ }
105
+
106
+ /** An identity plus its resolved English — everything a renderer needs, on any carrier. */
107
+ export interface ResolvedMessage extends MessageIdentity {
108
+ readonly text: string;
109
+ }
110
+
111
+ export function messageData<S extends string>(message: MessageDefinition<S>, ...args: ParamsArg<S>): HydraniumMessageData {
112
+ return { hydranium: { code: message.code, params: args[0] ?? {} } };
113
+ }
114
+
115
+ /**
116
+ * Identity plus resolved English, for a hand-off carrying a value rather than a
117
+ * protocol field. The result is structured-clone safe, so it survives a process
118
+ * hop where one intervenes and costs nothing where none does.
119
+ */
120
+ export function resolve<S extends string>(message: MessageDefinition<S>, ...args: ParamsArg<S>): ResolvedMessage {
121
+ return { code: message.code, text: message.format(...args), params: args[0] ?? {} };
122
+ }
123
+
124
+ /**
125
+ * Validates every field {@link MessageIdentity} declares, `params` included.
126
+ * A guard over foreign input that checks only `code` while declaring `params`
127
+ * non-optional hands `undefined` to the renderer, which fails with the worst
128
+ * polarity available: invisible in English, crashing only once a translation is
129
+ * loaded.
130
+ */
131
+ export function hasMessageIdentity(data: unknown): data is HydraniumMessageData {
132
+ if (typeof data !== 'object' || data === null || Array.isArray(data) || !('hydranium' in data)) {
133
+ return false;
134
+ }
135
+ const identity = (data as { hydranium: unknown }).hydranium;
136
+ if (typeof identity !== 'object' || identity === null || Array.isArray(identity)) {
137
+ return false;
138
+ }
139
+ const candidate = identity as Partial<MessageIdentity>;
140
+ return typeof candidate.code === 'string' && typeof candidate.params === 'object' && candidate.params !== null;
141
+ }
142
+
143
+ /**
144
+ * A type alias rather than a subclass. Only `code`, `message` and `data` cross
145
+ * the wire, so a subclass buys nothing there: `instanceof` does not survive
146
+ * reconstruction, and the subclass costs an `Object.setPrototypeOf` in every
147
+ * constructor purely to undo what `ResponseError`'s own constructor does.
148
+ */
149
+ export type HydraniumResponseError = ResponseError<HydraniumMessageData>;
150
+
151
+ /**
152
+ * The numeric `code` and the message's catalogue code are unrelated and both are
153
+ * needed: `ResponseError.code` is an `integer`, so it cannot hold a
154
+ * `hydranium/…` key, and it is what a caller switches on after reconstruction.
155
+ */
156
+ export function messageError<S extends string>(
157
+ code: number,
158
+ message: MessageDefinition<S>,
159
+ ...params: ParamsArg<S>
160
+ ): HydraniumResponseError {
161
+ return new ResponseError(code, message.format(...params), messageData(message, ...params));
162
+ }
163
+
164
+ /**
165
+ * Render on the side that knows the reading user's locale. `translations` is
166
+ * whatever flat `code → template` map the host exposes; omitting it is how an
167
+ * adopter without i18n opts out, and yields the English.
168
+ */
169
+ export function renderFrameworkMessage(message: ResolvedMessage, translations?: Record<string, string>): string {
170
+ const template = translations?.[message.code];
171
+ return template ? interpolate(template, message.params) : message.text;
172
+ }
173
+
174
+ export function resolvedFromResponseError(error: ResponseError<unknown>): ResolvedMessage | undefined {
175
+ return hasMessageIdentity(error.data) ? { ...error.data.hydranium, text: error.message } : undefined;
176
+ }
177
+
178
+ /**
179
+ * The detail half of a `{detail}` placeholder. A technical error string is safe
180
+ * to pass as a parameter for the same reason a number is: it is not itself
181
+ * translatable text, so it needs no code of its own. A PROSE fragment is not,
182
+ * and must become one code per value instead.
183
+ */
184
+ export function describeError(error: unknown): string {
185
+ return error instanceof Error ? error.message : String(error);
186
+ }
187
+
188
+ /**
189
+ * Recognises a declaration among a barrel's exports. The `format` check is what
190
+ * discriminates: a `code` + `text` pair alone admits any object that happens to
191
+ * carry both.
192
+ */
193
+ export function isMessageDeclaration(value: unknown): value is MessageDefinition<string> {
194
+ const candidate = value as { code?: unknown; text?: unknown; format?: unknown } | null;
195
+ return (
196
+ typeof candidate === 'object' &&
197
+ candidate !== null &&
198
+ typeof candidate.code === 'string' &&
199
+ typeof candidate.text === 'string' &&
200
+ typeof candidate.format === 'function'
201
+ );
202
+ }
203
+
204
+ /**
205
+ * Every declaration a `./messages` barrel exports.
206
+ *
207
+ * A caller cannot get there with `Object.values(barrel).filter(isMessageDeclaration)`:
208
+ * a barrel's value type is a union of its declarations AND its functions, and
209
+ * `filter` will not narrow a function type down to a `MessageDefinition`, so the
210
+ * result stays the union and reading `.code` off it does not compile. Taking the
211
+ * barrel as an opaque object is what makes the one-liner work.
212
+ */
213
+ export function collectMessages(barrel: object): MessageDefinition<string>[] {
214
+ return (Object.values(barrel) as unknown[]).filter(isMessageDeclaration);
215
+ }
@@ -64,8 +64,8 @@ export interface CloseModelArgs extends TransferClientArgs {}
64
64
  export interface TransferUpdatedEvent<TDocument> {
65
65
  document: TDocument;
66
66
  sourceClientId: string;
67
- /** See `ModelDocumentUpdateReason` in `./data/events` for the canonical reason set + semantics. */
68
- reason: 'changed' | 'deleted' | 'rebuilt' | 'saved';
67
+ /** See `TransferDocumentUpdateReason` in `./data/events` for the canonical reason set + semantics. */
68
+ reason: 'changed' | 'rebuilt' | 'saved';
69
69
  }
70
70
 
71
71
  export interface TransferSavedEvent<TDocument> {
@@ -147,10 +147,10 @@ export function isElementSource(object: unknown): object is ElementSource {
147
147
  /** An element of a document that does not yet exist on disk — used during element creation flows. */
148
148
  export interface SyntheticSource {
149
149
  /**
150
- * The document the element would belong to. That document must already be
151
- * LOADED — the default resolution takes its parse root as the synthetic
152
- * node's container and answers `undefined` when it is not, so a URI for a
153
- * file that exists on disk but was never opened resolves to nothing.
150
+ * The document the element would belong to. It need not be loaded, or
151
+ * exist — an unloaded URI materialises a transient empty document, so a
152
+ * folder is a valid anchor. A URI that IS loaded contributes that
153
+ * document's parse root as the container, putting its contents in scope.
154
154
  */
155
155
  uri: string;
156
156
  /**
@@ -159,6 +159,16 @@ export interface SyntheticSource {
159
159
  * it is what scoping filters candidates against.
160
160
  */
161
161
  type: string;
162
+ /**
163
+ * The grammar the element will belong to, as a language id.
164
+ *
165
+ * Optional because `uri` and `type` each answer on their own when
166
+ * unambiguous. Set it when neither is: a URI naming no file carries no
167
+ * extension to route on, and a `type` two grammars can produce identifies
168
+ * neither. Unset, such a source reaches the server's own policy, which
169
+ * answers the same way for every caller.
170
+ */
171
+ language?: string;
162
172
  }
163
173
 
164
174
  export function isSyntheticSource(object: unknown): object is SyntheticSource {
@@ -183,8 +193,10 @@ export namespace ReferenceSource {
183
193
  export function element(name: string, type?: string): ElementSource {
184
194
  return { name, type };
185
195
  }
186
- export function synthetic(uri: string, type: string): SyntheticSource {
187
- return { uri, type };
196
+ export function synthetic(uri: string, type: string, language?: string): SyntheticSource {
197
+ // The key is omitted rather than set to `undefined`, so a source built
198
+ // without a language stays deep-equal to the two-argument form.
199
+ return language === undefined ? { uri, type } : { uri, type, language };
188
200
  }
189
201
  }
190
202
 
@@ -457,9 +469,10 @@ export interface FindNextNameArgs {
457
469
  */
458
470
  uri: string;
459
471
  /**
460
- * The AST `$type` of the element being named. Collisions are only looked for
461
- * among elements of that same type, so the returned name may still be taken
462
- * by an element of another type.
472
+ * The AST `$type` of the element being named. Collisions are looked for
473
+ * among elements of that type and of any subtype of it, so a supertype
474
+ * names a uniqueness scope its concrete types share; the returned name may
475
+ * still be taken by an element outside that hierarchy.
463
476
  */
464
477
  type: string;
465
478
  /**
@@ -476,4 +489,10 @@ export interface FindNextNameArgs {
476
489
  * See {@link NameTier} for what each tier covers.
477
490
  */
478
491
  tier?: NameTier;
492
+ /**
493
+ * The grammar to name under, routed as {@link SyntheticSource.language} —
494
+ * this call builds one. A caller that sets it there must set it here, or
495
+ * candidates and the name it proposes come from different grammars.
496
+ */
497
+ language?: string;
479
498
  }
@@ -19,6 +19,8 @@
19
19
  * resolves.
20
20
  */
21
21
 
22
+ import type { BasedOn } from './based-on';
23
+
22
24
  /** Identifies a client-document binding. Every facade operation carries these fields. */
23
25
  export interface TransferClientArgs {
24
26
  /** Document URI. */
@@ -39,15 +41,16 @@ export interface TransferUpdateArgs<T> extends TransferClientArgs {
39
41
  /** Structured model root or its serialised textual form. */
40
42
  model: T | string;
41
43
  /**
42
- * Optional based-on version: the text-document version this update
43
- * was authored against. When set, the server compares against its
44
- * current text-document version for `uri` and throws
45
- * `ConflictError` on mismatch. Omit to opt out of the gate — mirrors
46
- * LSP's `OptionalVersionedTextDocumentIdentifier` posture, intended
47
- * for headless / CLI / batch tooling without a meaningful based-on
48
- * version.
44
+ * What this update was authored against. A `SnapshotVersion` is compared
45
+ * against the server's current text-document version for `uri` and throws
46
+ * `ConflictError` on mismatch; `'anything'` writes unconditionally.
47
+ *
48
+ * **Required so that an ungated write is a decision rather than an
49
+ * omission.** An optional gate is indistinguishable from a forgotten one at
50
+ * the call site, and a file of twenty writes hides the one that lost the
51
+ * field. Nothing else here can see that, since the defect is an absence.
49
52
  */
50
- baseVersion?: number;
53
+ basedOn: BasedOn;
51
54
  }
52
55
 
53
56
  /**
@@ -58,10 +61,9 @@ export interface TransferSaveArgs<T> extends TransferClientArgs {
58
61
  /** Structured model root or its serialised textual form. */
59
62
  model: T | string;
60
63
  /**
61
- * Optional based-on version — same semantics as
62
- * {@link TransferUpdateArgs.baseVersion}. `save` delegates the gating
63
- * check to its inner `update`, so this field threads through to the
64
- * same `ConflictError` site.
64
+ * Same semantics and same requirement as {@link TransferUpdateArgs.basedOn}.
65
+ * `save` delegates the gating check to its inner `update`, so this field
66
+ * threads through to the same `ConflictError` site.
65
67
  */
66
- baseVersion?: number;
68
+ basedOn: BasedOn;
67
69
  }
@@ -0,0 +1,60 @@
1
+ /********************************************************************************
2
+ * Copyright (c) 2026 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
+ declare const snapshotMarker: unique symbol;
11
+
12
+ /**
13
+ * A text-document version that came out of a SNAPSHOT read: a document
14
+ * envelope's `version`, which cannot move once the envelope exists.
15
+ *
16
+ * A plain number at runtime, usable anywhere a number is, and it travels the
17
+ * wire as one. The marker exists only so the compiler can tell it apart from a
18
+ * version read off a LIVE document, which is the same number type and is the
19
+ * defect the conflict gate exists to prevent: read at write time it is whatever
20
+ * the server is at now, which is the number the gate is about to compare it
21
+ * against, so the gate passes unconditionally and a concurrent edit is
22
+ * overwritten with nothing logged.
23
+ */
24
+ export type SnapshotVersion = number & { readonly [snapshotMarker]: true };
25
+
26
+ /**
27
+ * What a write declares it was based on: a version from a snapshot read, or
28
+ * `'anything'`.
29
+ *
30
+ * `'anything'` is a precondition that always holds — the write accepts whatever
31
+ * the server currently has, and therefore overwrites it. It is the honest
32
+ * answer wherever the write was authored against no particular server version,
33
+ * and a lie anywhere a reader handed the writer a document. The field carrying
34
+ * it is required, so an ungated write is a word someone chose rather than a
35
+ * field someone forgot.
36
+ */
37
+ export type BasedOn = SnapshotVersion | 'anything';
38
+
39
+ /**
40
+ * Whether `basedOn` names a version, and so arms the gate.
41
+ *
42
+ * Branch on this rather than on `basedOn !== 'anything'`, which reads as "not
43
+ * based on anything" — the opposite of what the branch tests.
44
+ */
45
+ export function isSnapshotVersion(basedOn: BasedOn): basedOn is SnapshotVersion {
46
+ return typeof basedOn === 'number';
47
+ }
48
+
49
+ /**
50
+ * Mark a version as having come from a snapshot read.
51
+ *
52
+ * **For the envelope constructors, not for callers.** Every door that builds a
53
+ * document envelope applies it on the way in, so anything a read returns
54
+ * already carries it and a writer never needs this. A caller reaching for it is
55
+ * asserting a provenance the compiler was about to deny — the read-late defect
56
+ * written out where a reviewer can see it.
57
+ */
58
+ export function asSnapshotVersion(version: number): SnapshotVersion {
59
+ return version as SnapshotVersion;
60
+ }
@@ -13,4 +13,5 @@
13
13
  // protocol can structurally agree on the lifecycle shape.
14
14
 
15
15
  export * from './args';
16
+ export * from './based-on';
16
17
  export * from './reference-candidate';
@@ -7,7 +7,7 @@
7
7
  * SPDX-License-Identifier: MIT
8
8
  ********************************************************************************/
9
9
 
10
- import type { MessageConnection } from 'vscode-jsonrpc';
10
+ import { ResponseError, type MessageConnection } from 'vscode-jsonrpc';
11
11
  import type { LatencyCollector } from '../latency-collector';
12
12
  import { type Disposable, DisposableCollection } from '../util';
13
13
  import { defaultIsNotification } from './create-rpc-proxy';
@@ -70,6 +70,36 @@ export interface BindRpcMethodsOptions {
70
70
  * Requests and notifications are both timed. Absent by default (no overhead).
71
71
  */
72
72
  readonly latency?: LatencyCollector;
73
+
74
+ /**
75
+ * Produce the `message` an outgoing rejection carries, so a user-facing
76
+ * error is rendered by the side that knows the reading user's language.
77
+ * Applied at this one chokepoint, which is what covers a caller's
78
+ * additional methods as well as the framework's own.
79
+ *
80
+ * Only a `ResponseError` is routed through it — a plain `Error` carries no
81
+ * identity to render from, and rewriting its message would relabel a
82
+ * developer-facing failure as a translated one. The rejection is
83
+ * RECONSTRUCTED rather than mutated, because the thrown value may be a
84
+ * shared constant; nothing is lost, since only `code`, `message` and `data`
85
+ * cross the wire and `instanceof` does not survive reconstruction anyway.
86
+ *
87
+ * Notifications are not covered, and "they have no reply channel" is only
88
+ * half the reason — a notification's own PAYLOAD can carry prose. What makes
89
+ * this sound is where that prose comes from: the only user-facing text on
90
+ * the data head's client surface is the diagnostics riding the
91
+ * document-updated and document-saved events, and those are read off
92
+ * `LangiumDocument.diagnostics`, which the document builder has already
93
+ * rendered at `Validated`. So they arrive rendered rather than escaping
94
+ * unrendered. A notification that ever carries prose of its OWN needs its
95
+ * own render at the raise site, as GLSP's actions do.
96
+ */
97
+ readonly renderErrorMessage?: (error: ResponseError<unknown>) => string;
98
+ }
99
+
100
+ /** The rejection to throw in place of `err`, with its message rendered. */
101
+ function renderRejection(err: unknown, render: (error: ResponseError<unknown>) => string): unknown {
102
+ return err instanceof ResponseError ? new ResponseError(err.code, render(err), err.data) : err;
73
103
  }
74
104
 
75
105
  /**
@@ -91,8 +121,10 @@ export interface BindRpcMethodsOptions {
91
121
  *
92
122
  * Errors thrown synchronously from a request handler — or surfaced as a
93
123
  * rejected promise — propagate back to the caller through vscode-jsonrpc's
94
- * standard error envelope. Errors from a notification handler cannot, and are
95
- * routed to {@link BindRpcMethodsOptions.onNotificationError} instead.
124
+ * standard error envelope, with the message rendered when
125
+ * {@link BindRpcMethodsOptions.renderErrorMessage} is supplied. Errors from a
126
+ * notification handler cannot propagate, and are routed to
127
+ * {@link BindRpcMethodsOptions.onNotificationError} instead.
96
128
  *
97
129
  * Accepts either a ready connection or a `Promise<MessageConnection>` —
98
130
  * registrations queue until the connection resolves, then attach. The
@@ -154,7 +186,20 @@ export function bindRpcMethods<T extends object>(
154
186
  })
155
187
  );
156
188
  } else {
157
- disposables.push(resolved.onRequest(wireName, async (params: unknown) => dispatch(params)));
189
+ const render = options.renderErrorMessage;
190
+ disposables.push(
191
+ resolved.onRequest(wireName, async (params: unknown) => {
192
+ if (!render) {
193
+ return dispatch(params);
194
+ }
195
+ try {
196
+ // Awaited inside the try, or a rejected promise escapes it.
197
+ return await dispatch(params);
198
+ } catch (err: unknown) {
199
+ throw renderRejection(err, render);
200
+ }
201
+ })
202
+ );
158
203
  }
159
204
  }
160
205
  };
@@ -136,6 +136,14 @@ export interface CreateRpcProxyOptions<TLocal extends object = never> {
136
136
  * `bindRpcMethods` call) still capture per-method latency. Absent by default.
137
137
  */
138
138
  readonly latency?: BindRpcMethodsOptions['latency'];
139
+
140
+ /**
141
+ * Forwarded to the inbound {@link localTarget} binding: renders the message
142
+ * an outgoing rejection carries. Only the inbound direction has rejections
143
+ * to render — the outbound proxy is this side making requests, and a
144
+ * rejection it receives was rendered by whoever answered.
145
+ */
146
+ readonly renderErrorMessage?: BindRpcMethodsOptions['renderErrorMessage'];
139
147
  }
140
148
 
141
149
  /**
@@ -225,7 +233,12 @@ export function createRpcProxy<T extends object, TLocal extends object = never>(
225
233
  // connection; see `localTarget` for why no `Disposable` is surfaced.
226
234
  const { localTarget, localMethods } = options;
227
235
  if (localTarget && localMethods && localMethods.length > 0) {
228
- const binding = bindRpcMethods(connection, localTarget, localMethods, { methodNamespace, isNotification, latency: options.latency });
236
+ const binding = bindRpcMethods(connection, localTarget, localMethods, {
237
+ methodNamespace,
238
+ isNotification,
239
+ latency: options.latency,
240
+ renderErrorMessage: options.renderErrorMessage
241
+ });
229
242
  resolvedConnection.then(conn => conn.onClose(() => binding.dispose())).catch(() => undefined);
230
243
  }
231
244
 
@@ -0,0 +1,111 @@
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 { collectMessages } from '../messages/primitives';
11
+
12
+ /**
13
+ * Audit a translation catalogue against the codes that actually exist.
14
+ *
15
+ * **The one failure mode a catalogue has, and the only one nothing else
16
+ * catches.** A key naming no declared code falls back to the English — which is
17
+ * byte-identical to a deliberate omission, so a typo is invisible at runtime and
18
+ * indistinguishable from the partial-catalogue behaviour every adopter relies
19
+ * on. Nothing on the render path can tell them apart, `theia nls-extract`
20
+ * reports what the SOURCE declares rather than whether a catalogue matches it,
21
+ * and the framework's own gates see only the framework's own files.
22
+ *
23
+ * Shipped as test support rather than as a runtime check on purpose: an
24
+ * orphaned key is an authoring mistake, and failing a server boot over one would
25
+ * take a running product down for a cosmetic defect.
26
+ */
27
+
28
+ /**
29
+ * Flatten a nested catalogue into the `/`-joined keys a message code is spelled
30
+ * with, dropping `_`-prefixed keys as notes to a human reader.
31
+ *
32
+ * Nesting is a HOST convention, not the framework's: Theia flattens a nested
33
+ * catalogue by joining keys with `/`, which is the separator a code already
34
+ * uses, so an adopter on that host writes the file nested and one handed
35
+ * straight to a `DefaultMessageRenderer` writes it flat. Both end up here.
36
+ *
37
+ * `_`-prefixed keys are dropped by PREFIX rather than by matching one literal
38
+ * name, so a second note added to a file cannot silently become a catalogue
39
+ * entry. A code is three `/`-separated segments, so no real entry can begin
40
+ * with `_`.
41
+ */
42
+ export function flattenCatalogue(catalogue: Record<string, unknown>, prefix = ''): Record<string, string> {
43
+ const flat: Record<string, string> = {};
44
+ for (const [key, value] of Object.entries(catalogue)) {
45
+ if (key.startsWith('_')) {
46
+ continue;
47
+ }
48
+ const joined = prefix ? `${prefix}/${key}` : key;
49
+ if (typeof value === 'string') {
50
+ flat[joined] = value;
51
+ } else if (typeof value === 'object' && value !== null) {
52
+ Object.assign(flat, flattenCatalogue(value as Record<string, unknown>, joined));
53
+ }
54
+ }
55
+ return flat;
56
+ }
57
+
58
+ /** Options for {@link findUndeclaredCodes}. */
59
+ export interface CatalogueAuditOptions {
60
+ /**
61
+ * Key prefixes to skip, for entries whose codes are NOT declared through a
62
+ * `defineMessage` barrel.
63
+ *
64
+ * The real case is a host's own mechanism: Theia's `nls.localize` takes its
65
+ * key as an inline literal at the call site, so those keys exist only in
66
+ * source text and no barrel can enumerate them. Keep this as narrow as the
67
+ * host layer actually is — exempting a namespace is exempting every typo in
68
+ * it, which is what this function exists to find.
69
+ */
70
+ readonly exemptPrefixes?: readonly string[];
71
+ }
72
+
73
+ /**
74
+ * Every catalogue key that names no code any of `barrels` declares.
75
+ *
76
+ * Barrels are taken as opaque objects and read with {@link collectMessages},
77
+ * which is what lets a caller pass a `import * as messages` namespace directly:
78
+ * a barrel's value type is a union of its declarations AND its functions, and
79
+ * filtering that union will not narrow to a `MessageDefinition`.
80
+ *
81
+ * Returns the offending keys rather than a boolean, so a failing assertion names
82
+ * WHICH key is wrong — a count says only that something is.
83
+ */
84
+ export function findUndeclaredCodes(
85
+ catalogueKeys: readonly string[],
86
+ barrels: readonly object[],
87
+ options: CatalogueAuditOptions = {}
88
+ ): string[] {
89
+ const declared = new Set(barrels.flatMap(barrel => collectMessages(barrel).map(message => message.code)));
90
+ const exempt = options.exemptPrefixes ?? [];
91
+ return catalogueKeys.filter(key => !exempt.some(prefix => key.startsWith(prefix)) && !declared.has(key));
92
+ }
93
+
94
+ /**
95
+ * Keys present in more than one catalogue — the shape a split catalogue rots
96
+ * into.
97
+ *
98
+ * Exactly one side renders a given message, so two catalogues holding one code
99
+ * are two authorities over one sentence and they diverge on the first reword.
100
+ * Nothing at runtime notices: both sides render, and whichever ran last wins on
101
+ * its own surface.
102
+ *
103
+ * Takes the key sets rather than a boolean answer for the same reason as
104
+ * {@link findUndeclaredCodes}, and reports NOTHING when a set is empty — an
105
+ * empty catalogue shares no key with anything, so a caller must assert
106
+ * non-emptiness separately or a failed read passes this vacuously.
107
+ */
108
+ export function findSharedCodes(first: readonly string[], second: readonly string[]): string[] {
109
+ const other = new Set(second);
110
+ return first.filter(key => other.has(key));
111
+ }