@hydranium/protocol 1.0.0-next.6 → 1.0.0-next.61

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 (99) hide show
  1. package/README.md +35 -1
  2. package/lib/client/data-connection.d.ts +76 -0
  3. package/lib/client/data-connection.d.ts.map +1 -0
  4. package/lib/client/data-connection.js +73 -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 +16 -21
  11. package/lib/client/data-port.d.ts.map +1 -1
  12. package/lib/client/data-session.d.ts +56 -74
  13. package/lib/client/data-session.d.ts.map +1 -1
  14. package/lib/client/data-session.js +67 -101
  15. package/lib/client/data-session.js.map +1 -1
  16. package/lib/client/index.d.ts +5 -2
  17. package/lib/client/index.d.ts.map +1 -1
  18. package/lib/client/index.js +5 -2
  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 +116 -0
  25. package/lib/client/rpc-connection.d.ts.map +1 -0
  26. package/lib/client/rpc-connection.js +155 -0
  27. package/lib/client/rpc-connection.js.map +1 -0
  28. package/lib/data/data-protocol-methods.d.ts +2 -2
  29. package/lib/data/data-protocol-methods.d.ts.map +1 -1
  30. package/lib/data/data-protocol-methods.js +6 -1
  31. package/lib/data/data-protocol-methods.js.map +1 -1
  32. package/lib/data/data-server-protocol.d.ts +21 -1
  33. package/lib/data/data-server-protocol.d.ts.map +1 -1
  34. package/lib/data/events.d.ts +70 -3
  35. package/lib/data/events.d.ts.map +1 -1
  36. package/lib/errors.d.ts +25 -6
  37. package/lib/errors.d.ts.map +1 -1
  38. package/lib/errors.js +32 -12
  39. package/lib/errors.js.map +1 -1
  40. package/lib/index.d.ts +1 -0
  41. package/lib/index.d.ts.map +1 -1
  42. package/lib/index.js +4 -0
  43. package/lib/index.js.map +1 -1
  44. package/lib/messages/index.d.ts +28 -0
  45. package/lib/messages/index.d.ts.map +1 -0
  46. package/lib/messages/index.js +52 -0
  47. package/lib/messages/index.js.map +1 -0
  48. package/lib/messages/primitives.d.ts +141 -0
  49. package/lib/messages/primitives.d.ts.map +1 -0
  50. package/lib/messages/primitives.js +138 -0
  51. package/lib/messages/primitives.js.map +1 -0
  52. package/lib/model-server.d.ts +2 -2
  53. package/lib/model-server.d.ts.map +1 -1
  54. package/lib/rpc/bind-rpc-methods.d.ts +29 -3
  55. package/lib/rpc/bind-rpc-methods.d.ts.map +1 -1
  56. package/lib/rpc/bind-rpc-methods.js +22 -3
  57. package/lib/rpc/bind-rpc-methods.js.map +1 -1
  58. package/lib/rpc/create-rpc-proxy.d.ts +7 -0
  59. package/lib/rpc/create-rpc-proxy.d.ts.map +1 -1
  60. package/lib/rpc/create-rpc-proxy.js +6 -1
  61. package/lib/rpc/create-rpc-proxy.js.map +1 -1
  62. package/lib/testing/catalogue-audit.d.ts +80 -0
  63. package/lib/testing/catalogue-audit.d.ts.map +1 -0
  64. package/lib/testing/catalogue-audit.js +94 -0
  65. package/lib/testing/catalogue-audit.js.map +1 -0
  66. package/lib/testing/data-doubles.d.ts +11 -12
  67. package/lib/testing/data-doubles.d.ts.map +1 -1
  68. package/lib/testing/data-doubles.js +14 -5
  69. package/lib/testing/data-doubles.js.map +1 -1
  70. package/lib/testing/index.d.ts +1 -0
  71. package/lib/testing/index.d.ts.map +1 -1
  72. package/lib/testing/index.js +4 -1
  73. package/lib/testing/index.js.map +1 -1
  74. package/lib/transfer-diagnostic.d.ts +33 -0
  75. package/lib/transfer-diagnostic.d.ts.map +1 -1
  76. package/lib/transfer-diagnostic.js +23 -0
  77. package/lib/transfer-diagnostic.js.map +1 -1
  78. package/package.json +11 -2
  79. package/src/client/data-connection.ts +114 -0
  80. package/src/client/data-events.ts +24 -1
  81. package/src/client/data-port.ts +16 -22
  82. package/src/client/data-session.ts +86 -124
  83. package/src/client/index.ts +5 -2
  84. package/src/client/message-relay.ts +28 -6
  85. package/src/client/rpc-connection.ts +205 -0
  86. package/src/data/data-protocol-methods.ts +6 -3
  87. package/src/data/data-server-protocol.ts +29 -1
  88. package/src/data/events.ts +74 -3
  89. package/src/errors.ts +38 -14
  90. package/src/index.ts +4 -0
  91. package/src/messages/index.ts +35 -0
  92. package/src/messages/primitives.ts +215 -0
  93. package/src/model-server.ts +2 -2
  94. package/src/rpc/bind-rpc-methods.ts +49 -4
  95. package/src/rpc/create-rpc-proxy.ts +14 -1
  96. package/src/testing/catalogue-audit.ts +111 -0
  97. package/src/testing/data-doubles.ts +33 -17
  98. package/src/testing/index.ts +4 -1
  99. package/src/transfer-diagnostic.ts +40 -0
@@ -13,7 +13,13 @@ import type { Project } from '../project';
13
13
  import type { TransferDocument } from '../transfer-document';
14
14
  import type { CloseModelArgs, FindNextNameArgs, OpenModelArgs, ReferenceContext, ReferenceRequest } from '../model-server';
15
15
  import type { ReferenceCandidate, ReferenceTarget } from '../model-service/reference-candidate';
16
- import type { ProjectsChangedEvent, TransferDocumentSavedEvent, TransferDocumentUpdatedEvent } from './events';
16
+ import type {
17
+ ProjectsChangedEvent,
18
+ TransferDocumentDeletedEvent,
19
+ TransferDocumentSavedEvent,
20
+ TransferDocumentsBuiltEvent,
21
+ TransferDocumentUpdatedEvent
22
+ } from './events';
17
23
  import type {
18
24
  GetModelDocumentArgs,
19
25
  GetProjectForUriArgs,
@@ -262,6 +268,28 @@ export interface DocumentClientProtocol<TTransfer extends TransferElement, TDiag
262
268
  * codepath, not a subscription codepath).
263
269
  */
264
270
  onDocumentSaved(event: TransferDocumentSavedEvent<TTransfer, TDiagnostic>): void;
271
+
272
+ /**
273
+ * Delivered when a document's backing file was removed. Separate from
274
+ * {@link onDocumentUpdated} for the same reason as {@link onDocumentSaved},
275
+ * and more strongly: there is no built state to deliver, and the build-phase
276
+ * path cannot report a deletion at all.
277
+ *
278
+ * Ungated, because on a browser host — where the workspace lives behind the
279
+ * head — no other source can observe a file disappearing. Recipients that
280
+ * only care about their own documents filter by URI.
281
+ */
282
+ onDocumentDeleted(event: TransferDocumentDeletedEvent): void;
283
+
284
+ /**
285
+ * Delivered once per build, naming the documents that reached the
286
+ * subscription phase and that
287
+ * nobody on this connection watches — chiefly the ones rebuilt as a cascade
288
+ * from a dependency's change, which no filesystem watcher can see because
289
+ * their own files did not change. The complement of
290
+ * {@link onDocumentUpdated}; carries URIs and no documents.
291
+ */
292
+ onDocumentsBuilt(event: TransferDocumentsBuiltEvent): void;
265
293
  }
266
294
 
267
295
  /**
@@ -30,10 +30,14 @@ import type { TransferDocument } from '../transfer-document';
30
30
  * from both `onDocumentUpdated` and `onDocumentSaved`. The framework's own
31
31
  * `dispatchPhaseEvent` does NOT emit `'saved'` — saves take the dedicated
32
32
  * `DataClientProtocol.onDocumentSaved` channel.
33
- * - `'deleted'` — the URI appeared in `DocumentBuilder.onUpdate`'s
34
- * `deleted` list. The backing file was removed.
33
+ *
34
+ * Deletion is deliberately NOT a member. An update event carries a built
35
+ * document, which a deleted one has none of, and the phase-driven path that
36
+ * produces these events never runs for a deleted URI — the builder drops the
37
+ * document before deriving the rebuild set. It travels as
38
+ * {@link TransferDocumentDeletedEvent} on its own channel instead.
35
39
  */
36
- export type TransferDocumentUpdateReason = 'changed' | 'rebuilt' | 'saved' | 'deleted';
40
+ export type TransferDocumentUpdateReason = 'changed' | 'rebuilt' | 'saved';
37
41
 
38
42
  /**
39
43
  * Delivered on the data-server when a document's content (or existence)
@@ -91,6 +95,73 @@ export type TransferDocumentSavedListener<
91
95
  TDiagnostic extends TransferDiagnostic = TransferDiagnostic
92
96
  > = (event: TransferDocumentSavedEvent<TTransfer, TDiagnostic>) => void;
93
97
 
98
+ /**
99
+ * Delivered on the data-server when a document's backing file was removed.
100
+ * Carries no document, and cannot: the state a
101
+ * {@link TransferDocumentUpdatedEvent} would have to carry no longer exists by
102
+ * the time anyone can be told. That is also why deletion is not a `reason` on
103
+ * the update stream — `DocumentBuilder.update` drops the document before
104
+ * deriving the rebuild set, so the phase-driven path that produces update
105
+ * events never runs for it.
106
+ *
107
+ * **Delivered for EVERY document, not only watched ones**, unlike
108
+ * `onDocumentUpdated` and `onDocumentSaved`. The test that decides which
109
+ * channels are gated is whether any OTHER source can observe the fact on the
110
+ * least capable host: a browser-hosted client's workspace lives behind the
111
+ * head, so nothing there can see a file disappear, and gating the notification
112
+ * would leave it blind. (A Theia frontend's filesystem watcher would cover it,
113
+ * which is why this is a host argument and not a structure-versus-content one.)
114
+ * A watcher is told about its own document's deletion here too, the update
115
+ * channel being silent for deletions by construction. Filter on {@link uri} if
116
+ * the receiver only cares about documents it opened.
117
+ *
118
+ * A watch survives the deletion, so a file that comes back resumes delivering
119
+ * `onDocumentUpdated` to the same subscribers with no re-subscription. A
120
+ * client that responds by closing its editor releases the watch through
121
+ * `closeModelDocument` as usual.
122
+ */
123
+ export interface TransferDocumentDeletedEvent {
124
+ /** Canonical URI of the removed document, keyed as the subscription is. */
125
+ readonly uri: string;
126
+ }
127
+
128
+ /** Callback shape for `DataClientProtocol.onDocumentDeleted`. */
129
+ export type TransferDocumentDeletedListener = (event: TransferDocumentDeletedEvent) => void;
130
+
131
+ /**
132
+ * Delivered on the data-server once per build, naming the documents that reached
133
+ * the configured subscription phase (`DataServerOptions.subscriptionPhase`,
134
+ * `Validated` by default) and that NO client on the connection is watching. Not
135
+ * the integrity-settled landmark, which is a different point and a different
136
+ * word in this framework.
137
+ *
138
+ * The complement of {@link TransferDocumentUpdatedEvent}, which is gated per
139
+ * URI: together the two cover every document a build touched. This one exists
140
+ * for the case no source outside the server can observe — a document rebuilt
141
+ * because something it DEPENDS ON changed. Its own file never changed, so a
142
+ * filesystem watcher cannot see it, and it has no subscriber, so the update
143
+ * channel does not report it. A consumer showing data derived from such a
144
+ * document (a tree label, a decorator) would otherwise hold a stale value with
145
+ * nothing to invalidate it.
146
+ *
147
+ * Carries URIs and no documents: a recipient re-reads what it displays, through
148
+ * `getModelDocument` or its own request. That keeps the bandwidth property the
149
+ * per-URI subscription exists for, without gating the message.
150
+ *
151
+ * Not sent when the set is empty, which is the normal case while editing — the
152
+ * document being edited is watched by its own editor and therefore excluded.
153
+ * Workspace initialisation sends nothing either: it does not build to the
154
+ * subscription phase. The largest message a workspace can produce is therefore
155
+ * a whole-workspace rebuild at that phase, which is one message of URIs.
156
+ */
157
+ export interface TransferDocumentsBuiltEvent {
158
+ /** Canonical URIs, keyed as subscriptions are. Never empty. */
159
+ readonly uris: readonly string[];
160
+ }
161
+
162
+ /** Callback shape for `DataClientProtocol.onDocumentsBuilt`. */
163
+ export type TransferDocumentsBuiltListener = (event: TransferDocumentsBuiltEvent) => void;
164
+
94
165
  /**
95
166
  * Why a project-change event fired. `added` — the project was newly
96
167
  * registered (descriptor discovered); `updated` — the project's
package/src/errors.ts CHANGED
@@ -8,6 +8,20 @@
8
8
  ********************************************************************************/
9
9
 
10
10
  import { ResponseError } from 'vscode-jsonrpc';
11
+ import { defineMessage, type HydraniumMessageData, messageData } from './messages/primitives';
12
+
13
+ /**
14
+ * The catalogue declaration behind {@link ConflictError}'s sentence.
15
+ *
16
+ * Its English must keep containing {@link CONFLICT_ERROR_MESSAGE_MARKER}: the
17
+ * marker is tier 3 of {@link isConflictError}'s ladder, and it matches on text.
18
+ * That tier only ever works untranslated, which is why it is the last resort
19
+ * behind the numeric code rather than the primary check.
20
+ */
21
+ export const STALE_BASED_UPDATE = defineMessage(
22
+ 'hydranium/protocol/stale-based-update',
23
+ 'Stale-based update for {uri}: expected v{expectedVersion}, server is at v{actualVersion}'
24
+ );
11
25
 
12
26
  /**
13
27
  * Application-specific JSON-RPC error code for {@link ConflictError}.
@@ -24,12 +38,12 @@ export const CONFLICT_ERROR_CODE = 1001;
24
38
  * Structured payload carried in {@link ConflictError.data}, and the only place
25
39
  * a post-RPC caller can read the version mismatch from.
26
40
  */
27
- export interface ConflictErrorData {
41
+ export interface ConflictErrorData extends HydraniumMessageData {
28
42
  readonly uri: string;
29
43
  /** The based-on version the caller authored against. */
30
- readonly expected: number;
44
+ readonly expectedVersion: number;
31
45
  /** The server's current text-document version at the time of the throw. */
32
- readonly actual: number;
46
+ readonly actualVersion: number;
33
47
  }
34
48
 
35
49
  /**
@@ -64,18 +78,19 @@ export interface ConflictErrorData {
64
78
  * No auto-retry or auto-merge ships by default.
65
79
  */
66
80
  export class ConflictError extends ResponseError<ConflictErrorData> {
67
- constructor(uri: string, expected: number, actual: number) {
68
- super(CONFLICT_ERROR_CODE, `Stale-based update for ${uri}: expected v${expected}, server is at v${actual}`, {
69
- uri,
70
- expected,
71
- actual
72
- });
81
+ constructor(uri: string, expectedVersion: number, actualVersion: number) {
82
+ const params = { uri, expectedVersion, actualVersion };
83
+ // The identity rides alongside the typed payload rather than replacing
84
+ // it: `isConflictError`'s name check is surface an adopter may bind, so
85
+ // adding the identity widens the payload rather than reshaping it.
86
+ super(CONFLICT_ERROR_CODE, STALE_BASED_UPDATE.format(params), { ...params, ...messageData(STALE_BASED_UPDATE, params) });
73
87
  this.name = 'ConflictError';
74
88
  // ResponseError's constructor calls `Object.setPrototypeOf(this,
75
89
  // ResponseError.prototype)` to keep its own prototype chain intact across
76
90
  // transpilation targets; that resets us to ResponseError, hiding the
77
91
  // ConflictError-specific getters. Restore the prototype here so
78
- // `err.uri` / `.expected` / `.actual` resolve through this class.
92
+ // `err.uri` / `.expectedVersion` / `.actualVersion` resolve through this
93
+ // class.
79
94
  Object.setPrototypeOf(this, ConflictError.prototype);
80
95
  }
81
96
 
@@ -83,12 +98,21 @@ export class ConflictError extends ResponseError<ConflictErrorData> {
83
98
  return this.data!.uri;
84
99
  }
85
100
 
86
- get expected(): number {
87
- return this.data!.expected;
101
+ /**
102
+ * The based-on version the caller authored against.
103
+ *
104
+ * Must not be renamed to `expected`, nor its sibling to `actual`: a test
105
+ * reporter reads an error carrying both as an assertion failure, and
106
+ * vitest's formatter then ASSIGNS to them, which throws on an accessor and
107
+ * replaces the real failure with a `TypeError`.
108
+ */
109
+ get expectedVersion(): number {
110
+ return this.data!.expectedVersion;
88
111
  }
89
112
 
90
- get actual(): number {
91
- return this.data!.actual;
113
+ /** The server's version at the time of the throw. Not `actual` — see {@link expectedVersion}. */
114
+ get actualVersion(): number {
115
+ return this.data!.actualVersion;
92
116
  }
93
117
  }
94
118
 
package/src/index.ts CHANGED
@@ -24,6 +24,10 @@ export * from './errors';
24
24
  export * from './host-diagnostics';
25
25
  export * from './logger';
26
26
  export * from './latency-collector';
27
+ // The primitives only. The `./messages` subpath additionally enumerates this
28
+ // package's own declarations, which the root barrel already re-exports through
29
+ // the modules that raise them.
30
+ export * from './messages/primitives';
27
31
  export * from './patch-merge';
28
32
  export * from './noop-logger';
29
33
  export * from './observable-value';
@@ -0,0 +1,35 @@
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
+ /**
11
+ * The message-externalization mechanism, plus every user-facing message
12
+ * `@hydranium/protocol` itself raises.
13
+ *
14
+ * Declarations stay beside their call sites and are re-exported here, so this is
15
+ * enumeration rather than centralization: a code's package segment has to name
16
+ * the package that raises it, and a shared module would make that segment a lie
17
+ * for every message in it. Adding a message therefore touches the file that
18
+ * raises it and this list, and nothing else.
19
+ *
20
+ * A barrel makes every code and English default public API, so renaming a code
21
+ * is a breaking change. That was already true — an adopter's catalogue keys on
22
+ * these codes either way — but it is now in the type system rather than implicit.
23
+ * The English is a fallback, not a contract; the code is the contract.
24
+ */
25
+
26
+ export * from './primitives';
27
+
28
+ export { STALE_BASED_UPDATE } from '../errors';
29
+ export { DATA_SERVER_CONNECT_FAILED, DATA_SERVER_NOT_READY } from '../client/rpc-connection';
30
+ export {
31
+ RELAY_REPLAY_FAILED,
32
+ RELAY_TRANSPORT_OPEN_FAILED,
33
+ RELAY_TRANSPORT_READ_FAILED,
34
+ RELAY_TRANSPORT_WRITE_FAILED
35
+ } from '../client/message-relay';
@@ -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> {
@@ -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