@hydranium/protocol 1.0.0-next.10 → 1.0.0-next.103

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 (132) hide show
  1. package/README.md +35 -1
  2. package/lib/client/data-connection.d.ts +152 -0
  3. package/lib/client/data-connection.d.ts.map +1 -0
  4. package/lib/client/data-connection.js +214 -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 +154 -76
  13. package/lib/client/data-session.d.ts.map +1 -1
  14. package/lib/client/data-session.js +194 -109
  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 +143 -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/latency-collector.d.ts +8 -4
  49. package/lib/latency-collector.d.ts.map +1 -1
  50. package/lib/latency-collector.js.map +1 -1
  51. package/lib/messages/index.d.ts +28 -0
  52. package/lib/messages/index.d.ts.map +1 -0
  53. package/lib/messages/index.js +52 -0
  54. package/lib/messages/index.js.map +1 -0
  55. package/lib/messages/primitives.d.ts +141 -0
  56. package/lib/messages/primitives.d.ts.map +1 -0
  57. package/lib/messages/primitives.js +138 -0
  58. package/lib/messages/primitives.js.map +1 -0
  59. package/lib/model-server.d.ts +27 -10
  60. package/lib/model-server.d.ts.map +1 -1
  61. package/lib/model-server.js +4 -2
  62. package/lib/model-server.js.map +1 -1
  63. package/lib/model-service/args.d.ts +14 -13
  64. package/lib/model-service/args.d.ts.map +1 -1
  65. package/lib/model-service/based-on.d.ts +55 -0
  66. package/lib/model-service/based-on.d.ts.map +1 -0
  67. package/lib/model-service/based-on.js +34 -0
  68. package/lib/model-service/based-on.js.map +1 -0
  69. package/lib/model-service/index.d.ts +1 -0
  70. package/lib/model-service/index.d.ts.map +1 -1
  71. package/lib/model-service/index.js +1 -0
  72. package/lib/model-service/index.js.map +1 -1
  73. package/lib/profile-session.d.ts +8 -4
  74. package/lib/profile-session.d.ts.map +1 -1
  75. package/lib/profile-session.js.map +1 -1
  76. package/lib/rpc/bind-rpc-methods.d.ts +29 -3
  77. package/lib/rpc/bind-rpc-methods.d.ts.map +1 -1
  78. package/lib/rpc/bind-rpc-methods.js +22 -3
  79. package/lib/rpc/bind-rpc-methods.js.map +1 -1
  80. package/lib/rpc/create-rpc-proxy.d.ts +7 -0
  81. package/lib/rpc/create-rpc-proxy.d.ts.map +1 -1
  82. package/lib/rpc/create-rpc-proxy.js +6 -1
  83. package/lib/rpc/create-rpc-proxy.js.map +1 -1
  84. package/lib/testing/catalogue-audit.d.ts +80 -0
  85. package/lib/testing/catalogue-audit.d.ts.map +1 -0
  86. package/lib/testing/catalogue-audit.js +94 -0
  87. package/lib/testing/catalogue-audit.js.map +1 -0
  88. package/lib/testing/data-doubles.d.ts +11 -12
  89. package/lib/testing/data-doubles.d.ts.map +1 -1
  90. package/lib/testing/data-doubles.js +14 -5
  91. package/lib/testing/data-doubles.js.map +1 -1
  92. package/lib/testing/index.d.ts +1 -0
  93. package/lib/testing/index.d.ts.map +1 -1
  94. package/lib/testing/index.js +4 -1
  95. package/lib/testing/index.js.map +1 -1
  96. package/lib/transfer-diagnostic.d.ts +33 -0
  97. package/lib/transfer-diagnostic.d.ts.map +1 -1
  98. package/lib/transfer-diagnostic.js +23 -0
  99. package/lib/transfer-diagnostic.js.map +1 -1
  100. package/lib/transfer-document.d.ts +15 -5
  101. package/lib/transfer-document.d.ts.map +1 -1
  102. package/lib/transfer-document.js +14 -1
  103. package/lib/transfer-document.js.map +1 -1
  104. package/package.json +11 -2
  105. package/src/client/data-connection.ts +266 -0
  106. package/src/client/data-events.ts +24 -1
  107. package/src/client/data-port.ts +17 -23
  108. package/src/client/data-session.ts +279 -131
  109. package/src/client/index.ts +10 -7
  110. package/src/client/message-relay.ts +28 -6
  111. package/src/client/rpc-connection.ts +235 -0
  112. package/src/client-ids.ts +45 -0
  113. package/src/data/data-protocol-methods.ts +6 -3
  114. package/src/data/data-server-protocol.ts +46 -2
  115. package/src/data/events.ts +74 -3
  116. package/src/errors.ts +41 -19
  117. package/src/index.ts +5 -0
  118. package/src/latency-collector.ts +8 -3
  119. package/src/messages/index.ts +35 -0
  120. package/src/messages/primitives.ts +215 -0
  121. package/src/model-server.ts +30 -11
  122. package/src/model-service/args.ts +15 -13
  123. package/src/model-service/based-on.ts +60 -0
  124. package/src/model-service/index.ts +1 -0
  125. package/src/profile-session.ts +9 -4
  126. package/src/rpc/bind-rpc-methods.ts +49 -4
  127. package/src/rpc/create-rpc-proxy.ts +14 -1
  128. package/src/testing/catalogue-audit.ts +111 -0
  129. package/src/testing/data-doubles.ts +33 -17
  130. package/src/testing/index.ts +4 -1
  131. package/src/transfer-diagnostic.ts +40 -0
  132. 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';
@@ -62,7 +62,12 @@ export interface ProfileSession {
62
62
  records(): readonly ProfileRecord[];
63
63
  }
64
64
 
65
- interface ScopeFrame {
65
+ /**
66
+ * One in-flight {@link ProfileSession.scope} call. Held on the `protected`
67
+ * {@link DefaultProfileSession.stack} and named by
68
+ * {@link DefaultProfileSession.closeFrame}, so a subclass has to name it too.
69
+ */
70
+ export interface ProfileScopeFrame {
66
71
  readonly id: string;
67
72
  /** Session-stopwatch reading when this scope began. */
68
73
  readonly start: number;
@@ -78,7 +83,7 @@ interface ScopeFrame {
78
83
  export class DefaultProfileSession implements ProfileSession {
79
84
  /** Single monotonic timeline for the whole session; per-scope readings are deltas off it. */
80
85
  protected readonly sessionStopwatch: Stopwatch;
81
- protected readonly stack: ScopeFrame[] = [];
86
+ protected readonly stack: ProfileScopeFrame[] = [];
82
87
  protected readonly entries = new Map<string, number[]>();
83
88
 
84
89
  constructor(
@@ -92,7 +97,7 @@ export class DefaultProfileSession implements ProfileSession {
92
97
  scope<T>(id: string, fn: () => Promise<T>): Promise<T>;
93
98
  scope<T>(id: string, fn: () => T): T;
94
99
  scope<T>(id: string, fn: () => T | Promise<T>): T | Promise<T> {
95
- const frame: ScopeFrame = { id, start: this.sessionStopwatch.elapsedMs, childMs: 0 };
100
+ const frame: ProfileScopeFrame = { id, start: this.sessionStopwatch.elapsedMs, childMs: 0 };
96
101
  this.stack.push(frame);
97
102
  let result: T | Promise<T>;
98
103
  try {
@@ -118,7 +123,7 @@ export class DefaultProfileSession implements ProfileSession {
118
123
  }
119
124
 
120
125
  /** Pop `frame`, charge its full duration to the parent, and record its self-time. */
121
- protected closeFrame(frame: ScopeFrame): void {
126
+ protected closeFrame(frame: ProfileScopeFrame): void {
122
127
  this.stack.pop();
123
128
  const duration = this.sessionStopwatch.elapsedMs - frame.start;
124
129
  const parent = this.stack[this.stack.length - 1];
@@ -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