@hydranium/protocol 1.0.0-next.18 → 1.0.0-next.181

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 (193) hide show
  1. package/README.md +35 -1
  2. package/lib/abstract-logger.d.ts.map +1 -1
  3. package/lib/abstract-logger.js.map +1 -1
  4. package/lib/client/data-connection.d.ts +157 -0
  5. package/lib/client/data-connection.d.ts.map +1 -0
  6. package/lib/client/data-connection.js +236 -0
  7. package/lib/client/data-connection.js.map +1 -0
  8. package/lib/client/data-events.d.ts +13 -1
  9. package/lib/client/data-events.d.ts.map +1 -1
  10. package/lib/client/data-events.js +21 -0
  11. package/lib/client/data-events.js.map +1 -1
  12. package/lib/client/data-port.d.ts +25 -23
  13. package/lib/client/data-port.d.ts.map +1 -1
  14. package/lib/client/data-session.d.ts +440 -78
  15. package/lib/client/data-session.d.ts.map +1 -1
  16. package/lib/client/data-session.js +697 -106
  17. package/lib/client/data-session.js.map +1 -1
  18. package/lib/client/index.d.ts +13 -8
  19. package/lib/client/index.d.ts.map +1 -1
  20. package/lib/client/index.js +13 -8
  21. package/lib/client/index.js.map +1 -1
  22. package/lib/client/message-relay.d.ts +9 -3
  23. package/lib/client/message-relay.d.ts.map +1 -1
  24. package/lib/client/message-relay.js +11 -5
  25. package/lib/client/message-relay.js.map +1 -1
  26. package/lib/client/post-message-transport.d.ts +64 -3
  27. package/lib/client/post-message-transport.d.ts.map +1 -1
  28. package/lib/client/post-message-transport.js +175 -1
  29. package/lib/client/post-message-transport.js.map +1 -1
  30. package/lib/client/rpc-connection.d.ts +149 -0
  31. package/lib/client/rpc-connection.d.ts.map +1 -0
  32. package/lib/client/rpc-connection.js +202 -0
  33. package/lib/client/rpc-connection.js.map +1 -0
  34. package/lib/client-ids.d.ts +45 -0
  35. package/lib/client-ids.d.ts.map +1 -0
  36. package/lib/client-ids.js +48 -0
  37. package/lib/client-ids.js.map +1 -0
  38. package/lib/clock.d.ts +38 -0
  39. package/lib/clock.d.ts.map +1 -1
  40. package/lib/clock.js +36 -1
  41. package/lib/clock.js.map +1 -1
  42. package/lib/data/data-protocol-methods.d.ts +4 -4
  43. package/lib/data/data-protocol-methods.d.ts.map +1 -1
  44. package/lib/data/data-protocol-methods.js +11 -1
  45. package/lib/data/data-protocol-methods.js.map +1 -1
  46. package/lib/data/data-server-protocol.d.ts +111 -31
  47. package/lib/data/data-server-protocol.d.ts.map +1 -1
  48. package/lib/data/events.d.ts +103 -14
  49. package/lib/data/events.d.ts.map +1 -1
  50. package/lib/data/requests.d.ts +67 -11
  51. package/lib/data/requests.d.ts.map +1 -1
  52. package/lib/debouncer.d.ts.map +1 -1
  53. package/lib/debouncer.js.map +1 -1
  54. package/lib/errors.d.ts +163 -17
  55. package/lib/errors.d.ts.map +1 -1
  56. package/lib/errors.js +219 -22
  57. package/lib/errors.js.map +1 -1
  58. package/lib/glsp-save-model-actions.d.ts +50 -0
  59. package/lib/glsp-save-model-actions.d.ts.map +1 -0
  60. package/lib/glsp-save-model-actions.js +28 -0
  61. package/lib/glsp-save-model-actions.js.map +1 -0
  62. package/lib/index.d.ts +3 -0
  63. package/lib/index.d.ts.map +1 -1
  64. package/lib/index.js +6 -0
  65. package/lib/index.js.map +1 -1
  66. package/lib/latency-collector.d.ts +8 -4
  67. package/lib/latency-collector.d.ts.map +1 -1
  68. package/lib/latency-collector.js.map +1 -1
  69. package/lib/logger.js.map +1 -1
  70. package/lib/messages/index.d.ts +29 -0
  71. package/lib/messages/index.d.ts.map +1 -0
  72. package/lib/messages/index.js +58 -0
  73. package/lib/messages/index.js.map +1 -0
  74. package/lib/messages/primitives.d.ts +188 -0
  75. package/lib/messages/primitives.d.ts.map +1 -0
  76. package/lib/messages/primitives.js +161 -0
  77. package/lib/messages/primitives.js.map +1 -0
  78. package/lib/model-server.d.ts +60 -13
  79. package/lib/model-server.d.ts.map +1 -1
  80. package/lib/model-server.js +4 -2
  81. package/lib/model-server.js.map +1 -1
  82. package/lib/model-service/based-on.d.ts +57 -0
  83. package/lib/model-service/based-on.d.ts.map +1 -0
  84. package/lib/model-service/based-on.js +37 -0
  85. package/lib/model-service/based-on.js.map +1 -0
  86. package/lib/model-service/index.d.ts +1 -1
  87. package/lib/model-service/index.d.ts.map +1 -1
  88. package/lib/model-service/index.js +4 -5
  89. package/lib/model-service/index.js.map +1 -1
  90. package/lib/noop-logger.d.ts.map +1 -1
  91. package/lib/noop-logger.js.map +1 -1
  92. package/lib/observable-value.js.map +1 -1
  93. package/lib/patch-merge.d.ts +28 -27
  94. package/lib/patch-merge.d.ts.map +1 -1
  95. package/lib/patch-merge.js +66 -22
  96. package/lib/patch-merge.js.map +1 -1
  97. package/lib/profile-session.d.ts +8 -4
  98. package/lib/profile-session.d.ts.map +1 -1
  99. package/lib/profile-session.js.map +1 -1
  100. package/lib/rpc/bind-rpc-methods.d.ts +29 -3
  101. package/lib/rpc/bind-rpc-methods.d.ts.map +1 -1
  102. package/lib/rpc/bind-rpc-methods.js +22 -3
  103. package/lib/rpc/bind-rpc-methods.js.map +1 -1
  104. package/lib/rpc/create-rpc-proxy.d.ts +7 -0
  105. package/lib/rpc/create-rpc-proxy.d.ts.map +1 -1
  106. package/lib/rpc/create-rpc-proxy.js +6 -1
  107. package/lib/rpc/create-rpc-proxy.js.map +1 -1
  108. package/lib/rpc/wire-prefix.js.map +1 -1
  109. package/lib/testing/catalogue-audit.d.ts +80 -0
  110. package/lib/testing/catalogue-audit.d.ts.map +1 -0
  111. package/lib/testing/catalogue-audit.js +94 -0
  112. package/lib/testing/catalogue-audit.js.map +1 -0
  113. package/lib/testing/data-doubles.d.ts +13 -12
  114. package/lib/testing/data-doubles.d.ts.map +1 -1
  115. package/lib/testing/data-doubles.js +19 -5
  116. package/lib/testing/data-doubles.js.map +1 -1
  117. package/lib/testing/fake-clock.d.ts +9 -1
  118. package/lib/testing/fake-clock.d.ts.map +1 -1
  119. package/lib/testing/fake-clock.js +54 -45
  120. package/lib/testing/fake-clock.js.map +1 -1
  121. package/lib/testing/index.d.ts +1 -0
  122. package/lib/testing/index.d.ts.map +1 -1
  123. package/lib/testing/index.js +4 -1
  124. package/lib/testing/index.js.map +1 -1
  125. package/lib/testing/node/duplex-connection.js.map +1 -1
  126. package/lib/testing/node/duplex-stream.js.map +1 -1
  127. package/lib/testing/node/index.d.ts +1 -0
  128. package/lib/testing/node/index.d.ts.map +1 -1
  129. package/lib/testing/node/index.js +2 -2
  130. package/lib/testing/node/index.js.map +1 -1
  131. package/lib/testing/node/message-port-pair.d.ts +25 -0
  132. package/lib/testing/node/message-port-pair.d.ts.map +1 -0
  133. package/lib/testing/node/message-port-pair.js +26 -0
  134. package/lib/testing/node/message-port-pair.js.map +1 -0
  135. package/lib/testing/wait-for.js.map +1 -1
  136. package/lib/tracer.d.ts.map +1 -1
  137. package/lib/tracer.js.map +1 -1
  138. package/lib/transfer-diagnostic.d.ts +33 -0
  139. package/lib/transfer-diagnostic.d.ts.map +1 -1
  140. package/lib/transfer-diagnostic.js +23 -0
  141. package/lib/transfer-diagnostic.js.map +1 -1
  142. package/lib/transfer-document.d.ts +34 -5
  143. package/lib/transfer-document.d.ts.map +1 -1
  144. package/lib/transfer-document.js +14 -1
  145. package/lib/transfer-document.js.map +1 -1
  146. package/lib/uri.d.ts.map +1 -1
  147. package/lib/uri.js.map +1 -1
  148. package/lib/util.d.ts +8 -0
  149. package/lib/util.d.ts.map +1 -1
  150. package/lib/util.js +32 -0
  151. package/lib/util.js.map +1 -1
  152. package/package.json +27 -18
  153. package/src/client/data-connection.ts +314 -0
  154. package/src/client/data-events.ts +33 -1
  155. package/src/client/data-port.ts +26 -24
  156. package/src/client/data-session.ts +881 -123
  157. package/src/client/index.ts +13 -8
  158. package/src/client/message-relay.ts +29 -7
  159. package/src/client/post-message-transport.ts +219 -4
  160. package/src/client/rpc-connection.ts +268 -0
  161. package/src/client-ids.ts +49 -0
  162. package/src/clock.ts +56 -0
  163. package/src/data/data-protocol-methods.ts +11 -3
  164. package/src/data/data-server-protocol.ts +132 -31
  165. package/src/data/events.ts +109 -14
  166. package/src/data/requests.ts +71 -11
  167. package/src/errors.ts +259 -24
  168. package/src/glsp-save-model-actions.ts +59 -0
  169. package/src/index.ts +6 -0
  170. package/src/latency-collector.ts +8 -3
  171. package/src/messages/index.ts +36 -0
  172. package/src/messages/primitives.ts +271 -0
  173. package/src/model-server.ts +63 -18
  174. package/src/model-service/based-on.ts +63 -0
  175. package/src/model-service/index.ts +4 -5
  176. package/src/patch-merge.ts +90 -37
  177. package/src/profile-session.ts +9 -4
  178. package/src/rpc/bind-rpc-methods.ts +49 -4
  179. package/src/rpc/create-rpc-proxy.ts +14 -1
  180. package/src/testing/catalogue-audit.ts +111 -0
  181. package/src/testing/data-doubles.ts +42 -17
  182. package/src/testing/fake-clock.ts +62 -47
  183. package/src/testing/index.ts +4 -1
  184. package/src/testing/node/index.ts +2 -2
  185. package/src/testing/node/message-port-pair.ts +40 -0
  186. package/src/transfer-diagnostic.ts +40 -0
  187. package/src/transfer-document.ts +41 -6
  188. package/src/util.ts +33 -0
  189. package/lib/model-service/args.d.ts +0 -64
  190. package/lib/model-service/args.d.ts.map +0 -1
  191. package/lib/model-service/args.js +0 -11
  192. package/lib/model-service/args.js.map +0 -1
  193. package/src/model-service/args.ts +0 -67
@@ -7,34 +7,43 @@
7
7
  * SPDX-License-Identifier: MIT
8
8
  ********************************************************************************/
9
9
 
10
- import { applyPatch, compare, deepClone, getValueByPointer, type Operation as JsonPatchOperation } from 'fast-json-patch';
10
+ import {
11
+ _areEquals,
12
+ applyPatch,
13
+ compare,
14
+ deepClone,
15
+ getValueByPointer,
16
+ type Operation as JsonPatchOperation,
17
+ unescapePathComponent
18
+ } from 'fast-json-patch';
11
19
 
12
20
  /**
13
- * Augment a user-intent JSON patch (computed `baseline → attempted`) with
21
+ * Augment a user-intent JSON patch (computed `base → ours`) with
14
22
  * `test` ops so a strict `applyPatch` against freshly-fetched server state
15
23
  * fails loudly when a foreign writer changed a path the user also changed.
16
24
  *
17
25
  * `fast-json-patch`'s `validateOperation: true` validates op structure and
18
26
  * path resolvability but NOT the pre-existing value — a plain `replace` /
19
27
  * `remove` silently overwrites whatever the foreign writer put there. For each
20
- * `replace` / `remove` op we prepend a `test` op carrying the baseline value at
28
+ * `replace` / `remove` op we prepend a `test` op carrying the base value at
21
29
  * that path, so a same-path divergence becomes a `TEST_OPERATION_FAILED` throw.
22
30
  * The caller treats that as a real field-level conflict (drop + refetch) rather
23
31
  * than silently clobbering the foreign edit.
24
32
  *
25
- * `add` ops are left unguarded: the path is new, so there is no baseline value
26
- * to test against, and add-vs-add overlaps are out of scope for this floor.
33
+ * `add` ops get no `test` op: the path is new, so there is no base value
34
+ * to test. {@link reconcileByPatchReplay} checks them against theirs
35
+ * instead; a caller applying this patch itself does not get that check.
27
36
  *
28
37
  * Used behind the framework's `ConflictError` contract by every reconcile
29
38
  * path — the GLSP recording command's undo/redo and forward-write, via
30
39
  * {@link ReconcilingConflictResolver}, and an adopter's form-widget save — so
31
40
  * they share one collision-detection rule.
32
41
  */
33
- export function augmentWithTestOps(baseline: object, userPatch: ReadonlyArray<JsonPatchOperation>): JsonPatchOperation[] {
42
+ export function augmentWithTestOps(base: object, userPatch: ReadonlyArray<JsonPatchOperation>): JsonPatchOperation[] {
34
43
  const augmented: JsonPatchOperation[] = [];
35
44
  for (const op of userPatch) {
36
45
  if (op.op === 'replace' || op.op === 'remove') {
37
- augmented.push({ op: 'test', path: op.path, value: getValueByPointer(baseline, op.path) });
46
+ augmented.push({ op: 'test', path: op.path, value: getValueByPointer(base, op.path) });
38
47
  }
39
48
  augmented.push(op);
40
49
  }
@@ -42,39 +51,38 @@ export function augmentWithTestOps(baseline: object, userPatch: ReadonlyArray<Js
42
51
  }
43
52
 
44
53
  /**
45
- * Outcome of {@link reconcileByPatchReplay}. The caller persists / re-baselines
46
- * on `merged`, drops + surfaces the `fresh` root on `conflict`, and decides its
47
- * own fallback (e.g. force-retry) on `no-op` / `unavailable`.
54
+ * Outcome of {@link reconcileByPatchReplay}. The caller persists `merged` and
55
+ * takes it as the new base, drops + surfaces the `theirs` root on `conflict`, and
56
+ * decides its own fallback (e.g. force-retry) on `no-op` / `unavailable`.
48
57
  */
49
58
  export type ReconcileOutcome<T> =
50
59
  | {
51
60
  /** The replay succeeded: the foreign writer touched no path the user did. */
52
61
  status: 'merged';
53
62
  /**
54
- * A fresh root built on the refetched server state, carrying both
55
- * intents. It is NOT the caller's `attempted` root — re-baseline on
56
- * this value, or the next write diffs against state the server never
57
- * had.
63
+ * A new root built on theirs, carrying both intents. It is NOT the
64
+ * caller's `ours` root — take this value as the new base, or the next
65
+ * write diffs against state the server never had.
58
66
  */
59
67
  merged: T;
60
68
  }
61
69
  | {
62
70
  /**
63
- * The user's root already equalled the baseline, so the version gate
71
+ * The user's root already equalled the base, so the version gate
64
72
  * fired on drift that changed nothing. No refetch was performed and
65
73
  * there is nothing to persist — retrying the same write reproduces it.
66
74
  */
67
75
  status: 'no-op';
68
76
  }
69
77
  | {
70
- /** A guarded `test` op tripped: user and foreign writer touched one path. */
78
+ /** User and foreign writer changed one path, or both added the same element or key. */
71
79
  status: 'conflict';
72
80
  /**
73
81
  * The server's current root, refetched and unmodified — the user's
74
82
  * intent was NOT applied to it. Surface it and drop the write; treating
75
83
  * it as a merge result silently discards what the user typed.
76
84
  */
77
- fresh: T;
85
+ theirs: T;
78
86
  }
79
87
  | {
80
88
  /**
@@ -87,39 +95,84 @@ export type ReconcileOutcome<T> =
87
95
 
88
96
  /**
89
97
  * Shared three-way reconcile for a `ConflictError`: diff the user's intent
90
- * (`baseline → attempted`), refetch the server's current root, and replay the
98
+ * (`base → ours`), refetch the server's current root (theirs), and replay the
91
99
  * intent on top under strict, {@link augmentWithTestOps}-guarded `applyPatch`.
92
100
  *
93
- * - `no-op` — the user's root equals the baseline, so the gate fired on a
101
+ * - `no-op` — the user's root equals the base, so the gate fired on a
94
102
  * benign version drift; nothing to replay (refetch is skipped).
95
103
  * - `unavailable` — the refetch produced nothing; caller falls back.
96
104
  * - `merged` — the foreign writer touched only paths the user did not; the
97
105
  * merged root carries both intents.
98
- * - `conflict` — a same-path divergence tripped a `test` op; caller drops the
99
- * write and surfaces `fresh`.
106
+ * - `conflict` — a same-path divergence tripped a `test` op, or an `add`
107
+ * collides with one the foreign writer made; caller drops the write and
108
+ * surfaces `theirs`.
100
109
  *
101
110
  * I/O is the caller's: `refetch` supplies the current root, and applying the
102
- * `merged` result (update vs save, re-baseline, UI refresh) stays at the call
111
+ * `merged` result (update vs save, new base, UI refresh) stays at the call
103
112
  * site so form and GLSP paths keep their own persistence semantics.
104
113
  */
105
114
  export async function reconcileByPatchReplay<T extends object>(
106
- baseline: T,
107
- attempted: T,
115
+ base: T,
116
+ ours: T,
108
117
  refetch: () => Promise<T | undefined>
109
118
  ): Promise<ReconcileOutcome<T>> {
110
- const userPatch = compare(baseline, attempted);
119
+ const userPatch = compare(base, ours);
111
120
  if (userPatch.length === 0) {
112
121
  return { status: 'no-op' };
113
122
  }
114
- const fresh = await refetch();
115
- if (!fresh) {
123
+ const theirs = await refetch();
124
+ if (!theirs) {
116
125
  return { status: 'unavailable' };
117
126
  }
127
+ if (addsCollide(base, theirs, userPatch)) {
128
+ return { status: 'conflict', theirs };
129
+ }
118
130
  try {
119
- const merged = applyPatch(deepClone(fresh), augmentWithTestOps(baseline, userPatch), true).newDocument;
131
+ const merged = applyPatch(deepClone(theirs), augmentWithTestOps(base, userPatch), true).newDocument;
120
132
  return { status: 'merged', merged };
121
133
  } catch {
122
- return { status: 'conflict', fresh };
134
+ return { status: 'conflict', theirs };
135
+ }
136
+ }
137
+
138
+ /**
139
+ * Whether an `add` of `userPatch` collides with one the foreign writer made:
140
+ * it inserts a value into an array that `theirs` holds more often than
141
+ * `base` did, or it adds an object key that `theirs` already holds.
142
+ *
143
+ * Replayed, the first inserts the value a second time and the second replaces
144
+ * the foreign value. Identical values conflict rather than being skipped:
145
+ * skipping drops one of two additions that merely happen to be equal.
146
+ */
147
+ function addsCollide(base: object, theirs: object, userPatch: readonly JsonPatchOperation[]): boolean {
148
+ // Through JSON, as `compare` clones the add values: an undefined-valued key
149
+ // in `theirs` would otherwise make an equal element count as another.
150
+ const comparable = JSON.parse(JSON.stringify(theirs)) as object;
151
+ return userPatch.some(op => {
152
+ if (op.op !== 'add') {
153
+ return false;
154
+ }
155
+ const cut = op.path.lastIndexOf('/');
156
+ const before = valueAt(base, op.path.slice(0, cut));
157
+ const now = valueAt(comparable, op.path.slice(0, cut));
158
+ if (Array.isArray(before)) {
159
+ return Array.isArray(now) && occurrences(now, op.value) > occurrences(before, op.value);
160
+ }
161
+ return typeof now === 'object' && now !== null && Object.hasOwn(now, unescapePathComponent(op.path.slice(cut + 1)));
162
+ });
163
+ }
164
+
165
+ /** How many elements of `array` deeply equal `value`, whatever their key order. */
166
+ function occurrences(array: readonly unknown[], value: unknown): number {
167
+ return array.filter(element => _areEquals(element, value)).length;
168
+ }
169
+
170
+ /** The value at `pointer`, or `undefined` when a step of it is missing. */
171
+ function valueAt(document: object, pointer: string): unknown {
172
+ try {
173
+ return getValueByPointer(document, pointer);
174
+ } catch {
175
+ return undefined;
123
176
  }
124
177
  }
125
178
 
@@ -132,12 +185,12 @@ export async function reconcileByPatchReplay<T extends object>(
132
185
  */
133
186
  export interface ConflictResolver {
134
187
  /**
135
- * Reconcile the user's `baseline → attempted` intent against the current
136
- * server state (`refetch`), returning a {@link ReconcileOutcome} the caller
188
+ * Reconcile the user's `base → ours` intent against the current
189
+ * server state (theirs, from `refetch`), returning a {@link ReconcileOutcome} the caller
137
190
  * acts on (persist `merged`, drop on `conflict`, fall back on `no-op` /
138
191
  * `unavailable`).
139
192
  */
140
- resolve<T extends object>(baseline: T, attempted: T, refetch: () => Promise<T | undefined>): Promise<ReconcileOutcome<T>>;
193
+ resolve<T extends object>(base: T, ours: T, refetch: () => Promise<T | undefined>): Promise<ReconcileOutcome<T>>;
141
194
  }
142
195
 
143
196
  /**
@@ -147,19 +200,19 @@ export interface ConflictResolver {
147
200
  * clobbered.
148
201
  */
149
202
  export class ReconcilingConflictResolver implements ConflictResolver {
150
- resolve<T extends object>(baseline: T, attempted: T, refetch: () => Promise<T | undefined>): Promise<ReconcileOutcome<T>> {
151
- return reconcileByPatchReplay(baseline, attempted, refetch);
203
+ resolve<T extends object>(base: T, ours: T, refetch: () => Promise<T | undefined>): Promise<ReconcileOutcome<T>> {
204
+ return reconcileByPatchReplay(base, ours, refetch);
152
205
  }
153
206
  }
154
207
 
155
208
  /**
156
- * Last-writer-wins {@link ConflictResolver}: always reports the `attempted`
209
+ * Last-writer-wins {@link ConflictResolver}: always reports the `ours`
157
210
  * state as merged, without refetching or guarding. Suitable for single-client
158
211
  * tools or always-regenerated artifacts where a concurrent foreign edit may be
159
212
  * overwritten. A foreign edit to any field is clobbered.
160
213
  */
161
214
  export class ForceConflictResolver implements ConflictResolver {
162
- async resolve<T extends object>(_baseline: T, attempted: T, _refetch: () => Promise<T | undefined>): Promise<ReconcileOutcome<T>> {
163
- return { status: 'merged', merged: attempted };
215
+ async resolve<T extends object>(_base: T, ours: T, _refetch: () => Promise<T | undefined>): Promise<ReconcileOutcome<T>> {
216
+ return { status: 'merged', merged: ours };
164
217
  }
165
218
  }
@@ -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
 
@@ -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
+ }
@@ -34,7 +34,15 @@
34
34
  import { Emitter, type MessageConnection } from 'vscode-jsonrpc';
35
35
  import type { DataPort } from '../client/data-port';
36
36
  import type { DataClientProtocol } from '../data/data-server-protocol';
37
- import type { ProjectsChangedEvent, TransferDocumentSavedEvent, TransferDocumentUpdatedEvent } from '../data/events';
37
+ import type {
38
+ ProjectsChangedEvent,
39
+ TransferDocumentDeletedEvent,
40
+ TransferDocumentDirtyChangedEvent,
41
+ TransferDocumentSavedEvent,
42
+ TransferDocumentsBuiltEvent,
43
+ TransferDocumentUpdatedEvent
44
+ } from '../data/events';
45
+ import type { ResolvedMessage } from '../messages/primitives';
38
46
  import type { Project } from '../project';
39
47
  import type { TransferDiagnostic } from '../transfer-diagnostic';
40
48
  import type { TransferElement } from '../transfer-element';
@@ -51,13 +59,6 @@ export interface FakeDataPortOptions {
51
59
  * which the consumer surfaces through {@link FakeDataPort.reported}.
52
60
  */
53
61
  connect(): MessageConnection | Promise<MessageConnection>;
54
- /**
55
- * Stable client identity. Defaults to `'fake-data-port'`, which avoids the
56
- * three sentinels the framework reserves (`'language-client'`, `'unknown'`,
57
- * `'revert-on-close'`); override it when a test needs two distinguishable
58
- * clients on one server.
59
- */
60
- clientId?: string;
61
62
  }
62
63
 
63
64
  /** A {@link DataPort} that records what passed through it. */
@@ -73,10 +74,11 @@ export interface FakeDataPort extends DataPort {
73
74
  /**
74
75
  * Every {@link DataPort.reportError} call, in order. Read from outside: this
75
76
  * is the only place a transport failure surfaces, so a test for the failure
76
- * path asserts on the `context` string here rather than on a rejection that
77
- * the consumer may legitimately swallow.
77
+ * path asserts here rather than on a rejection the consumer may legitimately
78
+ * swallow. Prefer asserting on `message.code`, which is stable, over
79
+ * `message.text`, which is the English default and may be reworded.
78
80
  */
79
- readonly reported: readonly { readonly error: unknown; readonly context: string }[];
81
+ readonly reported: readonly { readonly error: unknown; readonly message: ResolvedMessage }[];
80
82
  /**
81
83
  * Fire {@link DataPort.onDispose} — the host tearing the transport down, a
82
84
  * language-server restart being the case that forces the event to exist.
@@ -96,10 +98,9 @@ export interface FakeDataPort extends DataPort {
96
98
  */
97
99
  export function makeFakeDataPort(options: FakeDataPortOptions): FakeDataPort {
98
100
  const connections: MessageConnection[] = [];
99
- const reported: { error: unknown; context: string }[] = [];
101
+ const reported: { error: unknown; message: ResolvedMessage }[] = [];
100
102
  const disposeEmitter = new Emitter<void>();
101
103
  return {
102
- clientId: options.clientId ?? 'fake-data-port',
103
104
  connections,
104
105
  reported,
105
106
  onDispose: disposeEmitter.event,
@@ -108,8 +109,8 @@ export function makeFakeDataPort(options: FakeDataPortOptions): FakeDataPort {
108
109
  connections.push(connection);
109
110
  return connection;
110
111
  },
111
- reportError(error: unknown, context: string): void {
112
- reported.push({ error, context });
112
+ reportError(error: unknown, message: ResolvedMessage): void {
113
+ reported.push({ error, message });
113
114
  },
114
115
  fireDispose(): void {
115
116
  disposeEmitter.fire(undefined);
@@ -132,6 +133,12 @@ export interface CapturingDataClient<
132
133
  readonly updates: TransferDocumentUpdatedEvent<TTransfer, TDiagnostic>[];
133
134
  /** Every `onDocumentSaved` event, in arrival order. */
134
135
  readonly saves: TransferDocumentSavedEvent<TTransfer, TDiagnostic>[];
136
+ /** Every `onDocumentDirtyChanged` event, in arrival order. */
137
+ readonly dirtyChanges: TransferDocumentDirtyChangedEvent[];
138
+ /** Every `onDocumentDeleted` event, in arrival order. */
139
+ readonly deletions: TransferDocumentDeletedEvent[];
140
+ /** Every `onDocumentsBuilt` event, in arrival order. */
141
+ readonly builds: TransferDocumentsBuiltEvent[];
135
142
  /** Every `onProjectsChanged` event, in arrival order. */
136
143
  readonly projectsChanges: ProjectsChangedEvent<TProject>[];
137
144
  }
@@ -139,7 +146,7 @@ export interface CapturingDataClient<
139
146
  /**
140
147
  * A {@link DataClientProtocol} that records every notification it receives.
141
148
  *
142
- * Recording ALL THREE channels even when a suite reads one is deliberate: an
149
+ * Recording EVERY channel even when a suite reads one is deliberate: an
143
150
  * event delivered on the wrong channel is a real defect of the data head, and a
144
151
  * double that drops the other two turns it into silence on the one being
145
152
  * watched.
@@ -156,6 +163,9 @@ export function makeCapturingDataClient<
156
163
  >(overrides: Partial<DataClientProtocol<TTransfer, TDiagnostic, TProject>> = {}): CapturingDataClient<TTransfer, TDiagnostic, TProject> {
157
164
  const updates: TransferDocumentUpdatedEvent<TTransfer, TDiagnostic>[] = [];
158
165
  const saves: TransferDocumentSavedEvent<TTransfer, TDiagnostic>[] = [];
166
+ const dirtyChanges: TransferDocumentDirtyChangedEvent[] = [];
167
+ const deletions: TransferDocumentDeletedEvent[] = [];
168
+ const builds: TransferDocumentsBuiltEvent[] = [];
159
169
  const projectsChanges: ProjectsChangedEvent<TProject>[] = [];
160
170
  const client: DataClientProtocol<TTransfer, TDiagnostic, TProject> = {
161
171
  onDocumentUpdated:
@@ -168,11 +178,26 @@ export function makeCapturingDataClient<
168
178
  (event => {
169
179
  saves.push(event);
170
180
  }),
181
+ onDocumentDirtyChanged:
182
+ overrides.onDocumentDirtyChanged ??
183
+ (event => {
184
+ dirtyChanges.push(event);
185
+ }),
186
+ onDocumentDeleted:
187
+ overrides.onDocumentDeleted ??
188
+ (event => {
189
+ deletions.push(event);
190
+ }),
191
+ onDocumentsBuilt:
192
+ overrides.onDocumentsBuilt ??
193
+ (event => {
194
+ builds.push(event);
195
+ }),
171
196
  onProjectsChanged:
172
197
  overrides.onProjectsChanged ??
173
198
  (event => {
174
199
  projectsChanges.push(event);
175
200
  })
176
201
  };
177
- return { client, updates, saves, projectsChanges };
202
+ return { client, updates, saves, dirtyChanges, deletions, builds, projectsChanges };
178
203
  }