@hydranium/protocol 1.0.0-next.28 → 1.0.0-next.281

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 (254) hide show
  1. package/README.md +44 -49
  2. package/lib/abstract-logger.d.ts +5 -0
  3. package/lib/abstract-logger.d.ts.map +1 -1
  4. package/lib/abstract-logger.js +7 -0
  5. package/lib/abstract-logger.js.map +1 -1
  6. package/lib/client/data-connection.d.ts +248 -0
  7. package/lib/client/data-connection.d.ts.map +1 -0
  8. package/lib/client/data-connection.js +439 -0
  9. package/lib/client/data-connection.js.map +1 -0
  10. package/lib/client/data-events.d.ts +13 -1
  11. package/lib/client/data-events.d.ts.map +1 -1
  12. package/lib/client/data-events.js +21 -0
  13. package/lib/client/data-events.js.map +1 -1
  14. package/lib/client/data-port.d.ts +34 -24
  15. package/lib/client/data-port.d.ts.map +1 -1
  16. package/lib/client/data-session.d.ts +606 -89
  17. package/lib/client/data-session.d.ts.map +1 -1
  18. package/lib/client/data-session.js +1015 -114
  19. package/lib/client/data-session.js.map +1 -1
  20. package/lib/client/index.d.ts +14 -9
  21. package/lib/client/index.d.ts.map +1 -1
  22. package/lib/client/index.js +14 -9
  23. package/lib/client/index.js.map +1 -1
  24. package/lib/client/message-relay.d.ts +4 -4
  25. package/lib/client/message-relay.js +4 -4
  26. package/lib/client/message-relay.js.map +1 -1
  27. package/lib/client/post-message-transport.d.ts +64 -3
  28. package/lib/client/post-message-transport.d.ts.map +1 -1
  29. package/lib/client/post-message-transport.js +175 -1
  30. package/lib/client/post-message-transport.js.map +1 -1
  31. package/lib/client/rpc-connection.d.ts +157 -0
  32. package/lib/client/rpc-connection.d.ts.map +1 -0
  33. package/lib/client/rpc-connection.js +214 -0
  34. package/lib/client/rpc-connection.js.map +1 -0
  35. package/lib/client-ids.d.ts +45 -0
  36. package/lib/client-ids.d.ts.map +1 -0
  37. package/lib/client-ids.js +48 -0
  38. package/lib/client-ids.js.map +1 -0
  39. package/lib/clock.d.ts +50 -10
  40. package/lib/clock.d.ts.map +1 -1
  41. package/lib/clock.js +36 -1
  42. package/lib/clock.js.map +1 -1
  43. package/lib/console-logger.d.ts +23 -0
  44. package/lib/console-logger.d.ts.map +1 -0
  45. package/lib/console-logger.js +39 -0
  46. package/lib/console-logger.js.map +1 -0
  47. package/lib/data/data-protocol-methods.d.ts +4 -4
  48. package/lib/data/data-protocol-methods.d.ts.map +1 -1
  49. package/lib/data/data-protocol-methods.js +13 -1
  50. package/lib/data/data-protocol-methods.js.map +1 -1
  51. package/lib/data/data-server-protocol.d.ts +146 -41
  52. package/lib/data/data-server-protocol.d.ts.map +1 -1
  53. package/lib/data/events.d.ts +124 -21
  54. package/lib/data/events.d.ts.map +1 -1
  55. package/lib/data/requests.d.ts +71 -11
  56. package/lib/data/requests.d.ts.map +1 -1
  57. package/lib/debouncer.d.ts +3 -3
  58. package/lib/debouncer.d.ts.map +1 -1
  59. package/lib/debouncer.js +6 -9
  60. package/lib/debouncer.js.map +1 -1
  61. package/lib/errors.d.ts +178 -30
  62. package/lib/errors.d.ts.map +1 -1
  63. package/lib/errors.js +263 -32
  64. package/lib/errors.js.map +1 -1
  65. package/lib/glsp-request-model-args.d.ts +16 -0
  66. package/lib/glsp-request-model-args.d.ts.map +1 -0
  67. package/lib/glsp-request-model-args.js +19 -0
  68. package/lib/glsp-request-model-args.js.map +1 -0
  69. package/lib/glsp-save-model-actions.d.ts +50 -0
  70. package/lib/glsp-save-model-actions.d.ts.map +1 -0
  71. package/lib/glsp-save-model-actions.js +28 -0
  72. package/lib/glsp-save-model-actions.js.map +1 -0
  73. package/lib/index.d.ts +6 -0
  74. package/lib/index.d.ts.map +1 -1
  75. package/lib/index.js +6 -0
  76. package/lib/index.js.map +1 -1
  77. package/lib/latency-collector.d.ts +8 -4
  78. package/lib/latency-collector.d.ts.map +1 -1
  79. package/lib/latency-collector.js.map +1 -1
  80. package/lib/logger.d.ts +27 -6
  81. package/lib/logger.d.ts.map +1 -1
  82. package/lib/logger.js +31 -3
  83. package/lib/logger.js.map +1 -1
  84. package/lib/messages/index.d.ts +4 -2
  85. package/lib/messages/index.d.ts.map +1 -1
  86. package/lib/messages/index.js +14 -4
  87. package/lib/messages/index.js.map +1 -1
  88. package/lib/messages/primitives.d.ts +71 -10
  89. package/lib/messages/primitives.d.ts.map +1 -1
  90. package/lib/messages/primitives.js +55 -3
  91. package/lib/messages/primitives.js.map +1 -1
  92. package/lib/model-server.d.ts +60 -13
  93. package/lib/model-server.d.ts.map +1 -1
  94. package/lib/model-server.js +4 -2
  95. package/lib/model-server.js.map +1 -1
  96. package/lib/model-service/base-version.d.ts +64 -0
  97. package/lib/model-service/base-version.d.ts.map +1 -0
  98. package/lib/model-service/base-version.js +43 -0
  99. package/lib/model-service/base-version.js.map +1 -0
  100. package/lib/model-service/index.d.ts +1 -1
  101. package/lib/model-service/index.d.ts.map +1 -1
  102. package/lib/model-service/index.js +4 -5
  103. package/lib/model-service/index.js.map +1 -1
  104. package/lib/model-service/reference-candidate.d.ts +5 -3
  105. package/lib/model-service/reference-candidate.d.ts.map +1 -1
  106. package/lib/{model-service/args.js → node/index.d.ts} +2 -3
  107. package/lib/node/index.d.ts.map +1 -0
  108. package/lib/node/index.js +29 -0
  109. package/lib/node/index.js.map +1 -0
  110. package/lib/node/process-memory.d.ts +66 -0
  111. package/lib/node/process-memory.d.ts.map +1 -0
  112. package/lib/node/process-memory.js +291 -0
  113. package/lib/node/process-memory.js.map +1 -0
  114. package/lib/noop-logger.d.ts.map +1 -1
  115. package/lib/noop-logger.js.map +1 -1
  116. package/lib/observable-value.js.map +1 -1
  117. package/lib/patch-merge.d.ts +63 -35
  118. package/lib/patch-merge.d.ts.map +1 -1
  119. package/lib/patch-merge.js +171 -25
  120. package/lib/patch-merge.js.map +1 -1
  121. package/lib/profile-session.d.ts +8 -4
  122. package/lib/profile-session.d.ts.map +1 -1
  123. package/lib/profile-session.js.map +1 -1
  124. package/lib/project.d.ts +4 -1
  125. package/lib/project.d.ts.map +1 -1
  126. package/lib/project.js.map +1 -1
  127. package/lib/random-uuid.d.ts +14 -0
  128. package/lib/random-uuid.d.ts.map +1 -0
  129. package/lib/random-uuid.js +24 -0
  130. package/lib/random-uuid.js.map +1 -0
  131. package/lib/reconcile-write.d.ts +67 -0
  132. package/lib/reconcile-write.d.ts.map +1 -0
  133. package/lib/reconcile-write.js +69 -0
  134. package/lib/reconcile-write.js.map +1 -0
  135. package/lib/rpc/bind-rpc-methods.d.ts +33 -3
  136. package/lib/rpc/bind-rpc-methods.d.ts.map +1 -1
  137. package/lib/rpc/bind-rpc-methods.js +32 -3
  138. package/lib/rpc/bind-rpc-methods.js.map +1 -1
  139. package/lib/rpc/create-rpc-proxy.d.ts +10 -0
  140. package/lib/rpc/create-rpc-proxy.d.ts.map +1 -1
  141. package/lib/rpc/create-rpc-proxy.js +12 -2
  142. package/lib/rpc/create-rpc-proxy.js.map +1 -1
  143. package/lib/rpc/index.d.ts +1 -0
  144. package/lib/rpc/index.d.ts.map +1 -1
  145. package/lib/rpc/index.js +1 -0
  146. package/lib/rpc/index.js.map +1 -1
  147. package/lib/rpc/send-by-method-name.d.ts +76 -0
  148. package/lib/rpc/send-by-method-name.d.ts.map +1 -0
  149. package/lib/rpc/send-by-method-name.js +120 -0
  150. package/lib/rpc/send-by-method-name.js.map +1 -0
  151. package/lib/rpc/wire-prefix.js.map +1 -1
  152. package/lib/testing/catalogue-audit.d.ts +80 -0
  153. package/lib/testing/catalogue-audit.d.ts.map +1 -0
  154. package/lib/testing/catalogue-audit.js +94 -0
  155. package/lib/testing/catalogue-audit.js.map +1 -0
  156. package/lib/testing/data-doubles.d.ts +41 -12
  157. package/lib/testing/data-doubles.d.ts.map +1 -1
  158. package/lib/testing/data-doubles.js +56 -8
  159. package/lib/testing/data-doubles.js.map +1 -1
  160. package/lib/testing/fake-clock.d.ts +17 -2
  161. package/lib/testing/fake-clock.d.ts.map +1 -1
  162. package/lib/testing/fake-clock.js +61 -46
  163. package/lib/testing/fake-clock.js.map +1 -1
  164. package/lib/testing/index.d.ts +1 -0
  165. package/lib/testing/index.d.ts.map +1 -1
  166. package/lib/testing/index.js +5 -2
  167. package/lib/testing/index.js.map +1 -1
  168. package/lib/testing/node/duplex-connection.d.ts.map +1 -1
  169. package/lib/testing/node/duplex-connection.js +3 -2
  170. package/lib/testing/node/duplex-connection.js.map +1 -1
  171. package/lib/testing/node/duplex-stream.js.map +1 -1
  172. package/lib/testing/node/index.d.ts +1 -0
  173. package/lib/testing/node/index.d.ts.map +1 -1
  174. package/lib/testing/node/index.js +2 -2
  175. package/lib/testing/node/index.js.map +1 -1
  176. package/lib/testing/node/message-port-pair.d.ts +25 -0
  177. package/lib/testing/node/message-port-pair.d.ts.map +1 -0
  178. package/lib/testing/node/message-port-pair.js +26 -0
  179. package/lib/testing/node/message-port-pair.js.map +1 -0
  180. package/lib/testing/wait-for.d.ts +3 -2
  181. package/lib/testing/wait-for.d.ts.map +1 -1
  182. package/lib/testing/wait-for.js +40 -10
  183. package/lib/testing/wait-for.js.map +1 -1
  184. package/lib/tracer.d.ts.map +1 -1
  185. package/lib/tracer.js +5 -9
  186. package/lib/tracer.js.map +1 -1
  187. package/lib/transfer-diagnostic.js.map +1 -1
  188. package/lib/transfer-document.d.ts +70 -32
  189. package/lib/transfer-document.d.ts.map +1 -1
  190. package/lib/transfer-document.js +17 -9
  191. package/lib/transfer-document.js.map +1 -1
  192. package/lib/uri.d.ts.map +1 -1
  193. package/lib/uri.js.map +1 -1
  194. package/lib/util.d.ts +8 -2
  195. package/lib/util.d.ts.map +1 -1
  196. package/lib/util.js +32 -4
  197. package/lib/util.js.map +1 -1
  198. package/package.json +24 -40
  199. package/src/abstract-logger.ts +8 -0
  200. package/src/client/data-connection.ts +535 -0
  201. package/src/client/data-events.ts +33 -1
  202. package/src/client/data-port.ts +36 -25
  203. package/src/client/data-session.ts +1285 -136
  204. package/src/client/index.ts +14 -9
  205. package/src/client/message-relay.ts +4 -4
  206. package/src/client/post-message-transport.ts +219 -4
  207. package/src/client/rpc-connection.ts +281 -0
  208. package/src/client-ids.ts +49 -0
  209. package/src/clock.ts +68 -10
  210. package/src/console-logger.ts +39 -0
  211. package/src/data/data-protocol-methods.ts +14 -4
  212. package/src/data/data-server-protocol.ts +173 -41
  213. package/src/data/events.ts +130 -21
  214. package/src/data/requests.ts +77 -11
  215. package/src/debouncer.ts +7 -10
  216. package/src/errors.ts +312 -40
  217. package/src/glsp-request-model-args.ts +16 -0
  218. package/src/glsp-save-model-actions.ts +59 -0
  219. package/src/index.ts +6 -0
  220. package/src/latency-collector.ts +8 -3
  221. package/src/logger.ts +33 -7
  222. package/src/messages/index.ts +4 -2
  223. package/src/messages/primitives.ts +102 -10
  224. package/src/model-server.ts +64 -19
  225. package/src/model-service/base-version.ts +72 -0
  226. package/src/model-service/index.ts +4 -5
  227. package/src/model-service/reference-candidate.ts +5 -3
  228. package/src/node/index.ts +14 -0
  229. package/src/node/process-memory.ts +299 -0
  230. package/src/patch-merge.ts +230 -45
  231. package/src/profile-session.ts +9 -4
  232. package/src/project.ts +4 -1
  233. package/src/random-uuid.ts +21 -0
  234. package/src/reconcile-write.ts +128 -0
  235. package/src/rpc/README.md +6 -6
  236. package/src/rpc/bind-rpc-methods.ts +59 -4
  237. package/src/rpc/create-rpc-proxy.ts +20 -2
  238. package/src/rpc/index.ts +1 -0
  239. package/src/rpc/send-by-method-name.ts +140 -0
  240. package/src/testing/catalogue-audit.ts +111 -0
  241. package/src/testing/data-doubles.ts +141 -19
  242. package/src/testing/fake-clock.ts +76 -48
  243. package/src/testing/index.ts +5 -2
  244. package/src/testing/node/duplex-connection.ts +3 -2
  245. package/src/testing/node/index.ts +2 -2
  246. package/src/testing/node/message-port-pair.ts +40 -0
  247. package/src/testing/wait-for.ts +38 -11
  248. package/src/tracer.ts +5 -9
  249. package/src/transfer-document.ts +87 -34
  250. package/src/util.ts +33 -6
  251. package/lib/model-service/args.d.ts +0 -64
  252. package/lib/model-service/args.d.ts.map +0 -1
  253. package/lib/model-service/args.js.map +0 -1
  254. package/src/model-service/args.ts +0 -67
package/src/errors.ts CHANGED
@@ -9,62 +9,92 @@
9
9
 
10
10
  import { ResponseError } from 'vscode-jsonrpc';
11
11
  import { defineMessage, type HydraniumMessageData, messageData } from './messages/primitives';
12
+ import { asModelVersion, type ModelVersion, type TextVersion } from './model-service/base-version';
13
+
14
+ /*
15
+ * Every error here is a typed error: a caller reacts to it, so it has a class,
16
+ * a JSON-RPC code and an `is*` guard, and an English message. A typed error
17
+ * also carries a message identity where the framework can write an end-user
18
+ * sentence that needs no context. A URI may stay in that sentence; a client id
19
+ * or a raw version stays out of it, worded or left to `data`.
20
+ *
21
+ * An error nothing reacts to does not belong here: it stays a plain `Error`, or
22
+ * a named subclass without a code, at its throw site, since a code and a guard
23
+ * are public API that no caller would use.
24
+ */
12
25
 
13
26
  /**
14
- * The catalogue declaration behind {@link ConflictError}'s sentence.
27
+ * The catalogue declaration behind {@link ConflictError}'s sentence. It words
28
+ * the version mismatch rather than stating it: the two numbers mean nothing to
29
+ * an end user, and they stay in {@link ConflictErrorData}.
15
30
  *
16
31
  * Its English must keep containing {@link CONFLICT_ERROR_MESSAGE_MARKER}: the
17
32
  * marker is tier 3 of {@link isConflictError}'s ladder, and it matches on text.
18
33
  * That tier only ever works untranslated, which is why it is the last resort
19
34
  * behind the numeric code rather than the primary check.
20
35
  */
21
- export const STALE_BASED_UPDATE = defineMessage(
22
- 'hydranium/protocol/stale-based-update',
23
- 'Stale-based update for {uri}: expected v{expected}, server is at v{actual}'
36
+ export const STALE_BASE_VERSION_UPDATE = defineMessage(
37
+ 'hydranium/protocol/stale-base-version-update',
38
+ 'The edit to {uri} was not applied: it was made to an older version of the document.'
24
39
  );
25
40
 
26
41
  /**
27
- * Application-specific JSON-RPC error code for {@link ConflictError}.
28
- * Outside the reserved range (-32768 .. -32000) per JSON-RPC 2.0.
42
+ * Every JSON-RPC error code the framework raises, from any package, keyed by
43
+ * the error it identifies.
44
+ *
45
+ * The framework reserves the block 42000 to 42999 for these, and an adopter's
46
+ * own codes stay outside it: after an RPC a guard matches on the code alone, so
47
+ * an adopter's error carrying one of these reads as the framework's. A new code
48
+ * takes the next unused number in the block, whichever package raises it, and
49
+ * is declared here, where tests hold every code distinct and inside the block.
50
+ * The block sits clear of the range JSON-RPC 2.0 reserves for itself, -32768
51
+ * to -32000.
52
+ */
53
+ export const HYDRANIUM_ERROR_CODES = {
54
+ conflict: 42001,
55
+ noActiveProfile: 42002,
56
+ referenceSettleTimeout: 42003,
57
+ sessionClosed: 42004,
58
+ documentNotOpen: 42005,
59
+ duplicateClientId: 42006,
60
+ reservedClientId: 42007
61
+ } as const;
62
+
63
+ /**
64
+ * JSON-RPC error code for {@link ConflictError}.
29
65
  *
30
66
  * The code is the load-bearing identifier across realm boundaries —
31
67
  * `code` is a first-class field on the JSON-RPC error envelope and
32
68
  * survives wire reconstruction; the custom `Error` subclass name does
33
69
  * not.
34
70
  */
35
- export const CONFLICT_ERROR_CODE = 1001;
71
+ export const CONFLICT_ERROR_CODE = HYDRANIUM_ERROR_CODES.conflict;
36
72
 
37
- /**
38
- * Structured payload carried in {@link ConflictError.data}, and the only place
39
- * a post-RPC caller can read the version mismatch from.
40
- */
73
+ /** Structured payload carried in {@link ConflictError.data}. */
41
74
  export interface ConflictErrorData extends HydraniumMessageData {
42
75
  readonly uri: string;
43
- /** The based-on version the caller authored against. */
44
- readonly expected: number;
76
+ /** The base version the caller authored against. */
77
+ readonly baseVersion: ModelVersion;
45
78
  /** The server's current text-document version at the time of the throw. */
46
- readonly actual: number;
79
+ readonly actualVersion: TextVersion;
47
80
  }
48
81
 
49
82
  /**
50
- * Thrown by `ModelService.update` / `ModelService.save` when the caller-
51
- * supplied based-on version no longer matches the server's current text-
83
+ * Thrown by a client session's `update` / `save` when the caller-
84
+ * supplied base version no longer matches the server's current text-
52
85
  * document version for the same URI — i.e. the snapshot the caller
53
86
  * authored against has been superseded by an intervening edit.
54
87
  *
55
88
  * Extends vscode-jsonrpc's {@link ResponseError} so the typed
56
89
  * {@link ConflictErrorData} payload rides on the standard JSON-RPC
57
90
  * error envelope (`code`, `message`, `data`) — all three fields are
58
- * preserved by RPC reconstruction. Adopters that catch the error on
59
- * the receiving side of an RPC call read the version mismatch from
60
- * `err.data` (the instance is reconstructed as a generic
61
- * `ResponseError`, so subclass getters / fields do not survive).
91
+ * preserved by RPC reconstruction. `createRpcProxy` revives it into
92
+ * this class on the receiving side; a path that does not leaves a
93
+ * plain `ResponseError`, readable through `err.data` only.
62
94
  *
63
- * Detection is opt-in via the optional `baseVersion` field on
64
- * `TransferUpdateArgs` / `TransferSaveArgs`; callers that omit the field get
65
- * no gating. This mirrors LSP's `OptionalVersionedTextDocumentIdentifier`
66
- * posture, so headless / CLI / batch tooling with no meaningful based-on
67
- * version can opt out explicitly.
95
+ * Detection is driven by the required `baseVersion` field of every write
96
+ * request; a caller with no meaningful base version passes
97
+ * `'any'` and gets no gating.
68
98
  *
69
99
  * Three reasonable adopter recovery strategies:
70
100
  *
@@ -78,18 +108,23 @@ export interface ConflictErrorData extends HydraniumMessageData {
78
108
  * No auto-retry or auto-merge ships by default.
79
109
  */
80
110
  export class ConflictError extends ResponseError<ConflictErrorData> {
81
- constructor(uri: string, expected: number, actual: number) {
82
- const params = { uri, expected, actual };
111
+ constructor(uri: string, baseVersion: ModelVersion, actualVersion: TextVersion) {
83
112
  // The identity rides alongside the typed payload rather than replacing
84
- // it: this class's getters and `isConflictError`'s name check are surface
85
- // an adopter may bind, so the payload widens rather than changing shape.
86
- super(CONFLICT_ERROR_CODE, STALE_BASED_UPDATE.format(params), { ...params, ...messageData(STALE_BASED_UPDATE, params) });
113
+ // it: `isConflictError`'s name check is surface an adopter may bind, so
114
+ // adding the identity widens the payload rather than reshaping it.
115
+ super(CONFLICT_ERROR_CODE, STALE_BASE_VERSION_UPDATE.format({ uri }), {
116
+ uri,
117
+ baseVersion,
118
+ actualVersion,
119
+ ...messageData(STALE_BASE_VERSION_UPDATE, { uri })
120
+ });
87
121
  this.name = 'ConflictError';
88
122
  // ResponseError's constructor calls `Object.setPrototypeOf(this,
89
123
  // ResponseError.prototype)` to keep its own prototype chain intact across
90
124
  // transpilation targets; that resets us to ResponseError, hiding the
91
125
  // ConflictError-specific getters. Restore the prototype here so
92
- // `err.uri` / `.expected` / `.actual` resolve through this class.
126
+ // `err.uri` / `.baseVersion` / `.actualVersion` resolve through this
127
+ // class.
93
128
  Object.setPrototypeOf(this, ConflictError.prototype);
94
129
  }
95
130
 
@@ -97,19 +132,255 @@ export class ConflictError extends ResponseError<ConflictErrorData> {
97
132
  return this.data!.uri;
98
133
  }
99
134
 
100
- get expected(): number {
101
- return this.data!.expected;
135
+ /**
136
+ * The base version the caller authored against.
137
+ *
138
+ * Must not be renamed to `expected`, nor its sibling to `actual`: a test
139
+ * reporter reads an error carrying both as an assertion failure, and
140
+ * vitest's formatter then ASSIGNS to them, which throws on an accessor and
141
+ * replaces the real failure with a `TypeError`.
142
+ */
143
+ get baseVersion(): ModelVersion {
144
+ return this.data!.baseVersion;
145
+ }
146
+
147
+ /** The server's version at the time of the throw. Not `actual` — see {@link baseVersion}. */
148
+ get actualVersion(): TextVersion {
149
+ return this.data!.actualVersion;
150
+ }
151
+ }
152
+
153
+ /**
154
+ * JSON-RPC code for {@link SessionClosedError}, beside {@link CONFLICT_ERROR_CODE}
155
+ * and for the same reason: the code survives reconstruction, the class does not.
156
+ */
157
+ export const SESSION_CLOSED_ERROR_CODE = HYDRANIUM_ERROR_CODES.sessionClosed;
158
+ /** JSON-RPC code for {@link DocumentNotOpenError}. */
159
+ export const DOCUMENT_NOT_OPEN_ERROR_CODE = HYDRANIUM_ERROR_CODES.documentNotOpen;
160
+ /** JSON-RPC code for {@link DuplicateClientIdError}. */
161
+ export const DUPLICATE_CLIENT_ID_ERROR_CODE = HYDRANIUM_ERROR_CODES.duplicateClientId;
162
+ /** JSON-RPC code for {@link ReservedClientIdError}. */
163
+ export const RESERVED_CLIENT_ID_ERROR_CODE = HYDRANIUM_ERROR_CODES.reservedClientId;
164
+
165
+ /**
166
+ * The catalogue declaration behind {@link SessionClosedError}'s default
167
+ * sentence. It names no client id: the sentence can reach an end user, and the
168
+ * id stays in {@link SessionClosedErrorData.clientId} for whoever needs it.
169
+ */
170
+ export const SESSION_CLOSED = defineMessage('hydranium/protocol/session-closed', 'The editing session has ended.');
171
+
172
+ /** Structured payload carried in {@link SessionClosedError.data}. */
173
+ export interface SessionClosedErrorData extends HydraniumMessageData {
174
+ readonly clientId: string;
175
+ }
176
+
177
+ /**
178
+ * Thrown by every call on a client session after it ended, and by an open that
179
+ * was still in flight when its session ended: by the server for its sessions,
180
+ * and by a client-side `DataSession` once disposed, so a caller handles both
181
+ * the same way. A caller recognises it with {@link isSessionClosedError}, never
182
+ * by its sentence.
183
+ */
184
+ export class SessionClosedError extends ResponseError<SessionClosedErrorData> {
185
+ /**
186
+ * `message` replaces the default English, for a caller that knows more than
187
+ * that the session is gone. The identity stays {@link SESSION_CLOSED}'s, so a
188
+ * translating renderer renders the catalogue sentence in its place.
189
+ */
190
+ constructor(clientId: string, message = SESSION_CLOSED.format()) {
191
+ super(SESSION_CLOSED_ERROR_CODE, message, { clientId, ...messageData(SESSION_CLOSED) });
192
+ this.name = 'SessionClosedError';
193
+ // `ResponseError` resets the prototype to its own; see `ConflictError`.
194
+ Object.setPrototypeOf(this, SessionClosedError.prototype);
195
+ }
196
+
197
+ get clientId(): string {
198
+ return this.data!.clientId;
102
199
  }
200
+ }
201
+
202
+ /**
203
+ * The catalogue declaration behind {@link DocumentNotOpenError}'s sentence. The
204
+ * client id stays in {@link DocumentNotOpenErrorData.clientId}.
205
+ */
206
+ export const DOCUMENT_NOT_OPEN = defineMessage(
207
+ 'hydranium/protocol/document-not-open',
208
+ 'The document {uri} is not open in this editing session.'
209
+ );
210
+
211
+ /** Structured payload carried in {@link DocumentNotOpenError.data}. */
212
+ export interface DocumentNotOpenErrorData extends HydraniumMessageData {
213
+ readonly uri: string;
214
+ readonly clientId: string;
215
+ }
103
216
 
104
- get actual(): number {
105
- return this.data!.actual;
217
+ /**
218
+ * Thrown when a client session writes a document it does not have open.
219
+ *
220
+ * A session writes only what it has open, so this is the answer both to a write
221
+ * that never opened and to one whose open was closed underneath it — by the
222
+ * session itself, or by the document being deleted.
223
+ */
224
+ export class DocumentNotOpenError extends ResponseError<DocumentNotOpenErrorData> {
225
+ constructor(uri: string, clientId: string) {
226
+ super(DOCUMENT_NOT_OPEN_ERROR_CODE, DOCUMENT_NOT_OPEN.format({ uri }), {
227
+ uri,
228
+ clientId,
229
+ ...messageData(DOCUMENT_NOT_OPEN, { uri })
230
+ });
231
+ this.name = 'DocumentNotOpenError';
232
+ Object.setPrototypeOf(this, DocumentNotOpenError.prototype);
233
+ }
234
+
235
+ get uri(): string {
236
+ return this.data!.uri;
106
237
  }
238
+
239
+ get clientId(): string {
240
+ return this.data!.clientId;
241
+ }
242
+ }
243
+
244
+ /**
245
+ * The catalogue declaration behind {@link DuplicateClientIdError}'s sentence.
246
+ * The client id stays in {@link DuplicateClientIdErrorData.clientId}.
247
+ */
248
+ export const DUPLICATE_CLIENT_ID = defineMessage(
249
+ 'hydranium/protocol/duplicate-client-id',
250
+ 'Could not start an editing session: its identifier is still in use by another editor.'
251
+ );
252
+
253
+ /** Structured payload carried in {@link DuplicateClientIdError.data}. */
254
+ export interface DuplicateClientIdErrorData extends HydraniumMessageData {
255
+ readonly clientId: string;
256
+ }
257
+
258
+ /**
259
+ * Thrown when a client session is started under an id that is already live in
260
+ * the process. The id frees up once its holder ends or closes its last
261
+ * document, so a caller may retry.
262
+ *
263
+ * Ids are unique process-wide because the id is also the author label on every
264
+ * version and the key a client recognises its own echoes by; two participants
265
+ * sharing one would each take the other's writes for their own.
266
+ */
267
+ export class DuplicateClientIdError extends ResponseError<DuplicateClientIdErrorData> {
268
+ constructor(clientId: string) {
269
+ super(DUPLICATE_CLIENT_ID_ERROR_CODE, DUPLICATE_CLIENT_ID.format(), { clientId, ...messageData(DUPLICATE_CLIENT_ID) });
270
+ this.name = 'DuplicateClientIdError';
271
+ Object.setPrototypeOf(this, DuplicateClientIdError.prototype);
272
+ }
273
+
274
+ get clientId(): string {
275
+ return this.data!.clientId;
276
+ }
277
+ }
278
+
279
+ /**
280
+ * Thrown when a client session is started under an id the framework reserves
281
+ * for one of its own participants. A reserved id never frees up, so a caller
282
+ * that retries on {@link DuplicateClientIdError} stops on this one.
283
+ *
284
+ * It carries no message identity: a host that picks a reserved id has a bug,
285
+ * and no sentence addressed to an end user is true for it.
286
+ */
287
+ export class ReservedClientIdError extends ResponseError<{ readonly clientId: string }> {
288
+ constructor(clientId: string) {
289
+ super(RESERVED_CLIENT_ID_ERROR_CODE, `Client id ${clientId} is reserved for a framework participant`, { clientId });
290
+ this.name = 'ReservedClientIdError';
291
+ Object.setPrototypeOf(this, ReservedClientIdError.prototype);
292
+ }
293
+
294
+ get clientId(): string {
295
+ return this.data!.clientId;
296
+ }
297
+ }
298
+
299
+ /**
300
+ * Rebuilds one typed error from the `data` that crossed the wire, or
301
+ * `undefined` when `data` lacks the fields the class reads.
302
+ */
303
+ type ProtocolErrorReviver = (data: Readonly<Record<string, unknown>>) => ResponseError<unknown> | undefined;
304
+
305
+ /** One entry per typed error class, keyed by its code; a class without one reaches a caller as a plain `ResponseError`. */
306
+ const PROTOCOL_ERROR_REVIVERS: ReadonlyMap<number, ProtocolErrorReviver> = new Map<number, ProtocolErrorReviver>([
307
+ [
308
+ CONFLICT_ERROR_CODE,
309
+ ({ uri, baseVersion, actualVersion }) =>
310
+ typeof uri === 'string' && typeof baseVersion === 'number' && typeof actualVersion === 'number'
311
+ ? new ConflictError(uri, asModelVersion(baseVersion), actualVersion)
312
+ : undefined
313
+ ],
314
+ [SESSION_CLOSED_ERROR_CODE, ({ clientId }) => (typeof clientId === 'string' ? new SessionClosedError(clientId) : undefined)],
315
+ [
316
+ DOCUMENT_NOT_OPEN_ERROR_CODE,
317
+ ({ uri, clientId }) => (typeof uri === 'string' && typeof clientId === 'string' ? new DocumentNotOpenError(uri, clientId) : undefined)
318
+ ],
319
+ [DUPLICATE_CLIENT_ID_ERROR_CODE, ({ clientId }) => (typeof clientId === 'string' ? new DuplicateClientIdError(clientId) : undefined)],
320
+ [RESERVED_CLIENT_ID_ERROR_CODE, ({ clientId }) => (typeof clientId === 'string' ? new ReservedClientIdError(clientId) : undefined)]
321
+ ]);
322
+
323
+ /**
324
+ * Whether `error` is a `ResponseError` from any copy of `vscode-jsonrpc`. An
325
+ * install holds several copies, and `instanceof` recognises only its own. An
326
+ * error that merely carries an integer `code` has no `toJson`, and is not one.
327
+ */
328
+ export function isResponseError(error: unknown): error is ResponseError<unknown> {
329
+ return (
330
+ error instanceof Error && 'code' in error && Number.isInteger(error.code) && 'toJson' in error && typeof error.toJson === 'function'
331
+ );
332
+ }
333
+
334
+ /**
335
+ * `error` as an instance of the typed error class its code names, with its
336
+ * message, data and stack kept, or `error` itself when its code names none or
337
+ * its data lacks the fields that class reads.
338
+ * An RPC reconstructs every rejection as a plain `ResponseError`, which has
339
+ * none of the class getters.
340
+ */
341
+ export function reviveProtocolError(error: unknown): unknown {
342
+ if (!isResponseError(error) || error.data === null || typeof error.data !== 'object') {
343
+ return error;
344
+ }
345
+ const revived = PROTOCOL_ERROR_REVIVERS.get(error.code)?.({ ...error.data });
346
+ if (!revived) {
347
+ return error;
348
+ }
349
+ return Object.assign(revived, { message: error.message, data: error.data, stack: error.stack });
350
+ }
351
+
352
+ /**
353
+ * Whether `error` is a {@link SessionClosedError}: by name in-process, by code
354
+ * when it arrives as a plain `ResponseError`, through a path that does not
355
+ * {@link reviveProtocolError revive} it.
356
+ */
357
+ export function isSessionClosedError(error: unknown): error is SessionClosedError {
358
+ return hasErrorIdentity(error, 'SessionClosedError', SESSION_CLOSED_ERROR_CODE);
359
+ }
360
+
361
+ /** Whether `error` is a {@link DocumentNotOpenError}; see {@link isSessionClosedError}. */
362
+ export function isDocumentNotOpenError(error: unknown): error is DocumentNotOpenError {
363
+ return hasErrorIdentity(error, 'DocumentNotOpenError', DOCUMENT_NOT_OPEN_ERROR_CODE);
364
+ }
365
+
366
+ /** Whether `error` is a {@link DuplicateClientIdError}; see {@link isSessionClosedError}. */
367
+ export function isDuplicateClientIdError(error: unknown): error is DuplicateClientIdError {
368
+ return hasErrorIdentity(error, 'DuplicateClientIdError', DUPLICATE_CLIENT_ID_ERROR_CODE);
369
+ }
370
+
371
+ /** Whether `error` is a {@link ReservedClientIdError}; see {@link isSessionClosedError}. */
372
+ export function isReservedClientIdError(error: unknown): error is ReservedClientIdError {
373
+ return hasErrorIdentity(error, 'ReservedClientIdError', RESERVED_CLIENT_ID_ERROR_CODE);
374
+ }
375
+
376
+ function hasErrorIdentity(error: unknown, name: string, code: number): boolean {
377
+ return error instanceof Error && (error.name === name || (error as Partial<ResponseError<unknown>>).code === code);
107
378
  }
108
379
 
109
380
  /** Marker substring present in every {@link ConflictError} message, used by
110
381
  * {@link isConflictError} as a fallback when a transport re-wraps the error
111
382
  * and drops the JSON-RPC code. */
112
- const CONFLICT_ERROR_MESSAGE_MARKER = 'Stale-based update for ';
383
+ const CONFLICT_ERROR_MESSAGE_MARKER = ': it was made to an older version of the document';
113
384
 
114
385
  /**
115
386
  * Type guard for {@link ConflictError}. Detection ladder:
@@ -120,11 +391,12 @@ const CONFLICT_ERROR_MESSAGE_MARKER = 'Stale-based update for ';
120
391
  * canonical wire-side check; the JSON-RPC `code` field is preserved
121
392
  * across reconstruction, so any adopter catching after an RPC call
122
393
  * hits this branch.
123
- * 3. `error.message.includes('Stale-based update for ')` — fallback
124
- * for transports that re-wrap the message and drop the code (rare).
394
+ * 3. `error.message` contains the marker {@link STALE_BASE_VERSION_UPDATE}'s
395
+ * English carries — fallback for transports that re-wrap the message
396
+ * and drop the code (rare).
125
397
  *
126
- * `instanceof ConflictError` alone would silently return `false` on the
127
- * reconstructed shape, so callers do not use it.
398
+ * `instanceof ConflictError` alone returns `false` on a rejection that was
399
+ * not {@link reviveProtocolError revived}, so callers do not use it.
128
400
  */
129
401
  export function isConflictError(error: unknown): error is ConflictError {
130
402
  if (!(error instanceof Error)) {
@@ -0,0 +1,16 @@
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 `RequestModelAction` option carrying a diagram's resume token. A load
12
+ * whose token matches the one the live session under its client id was started
13
+ * with takes that session over, so a diagram that reconnects or reloads keeps
14
+ * its unsaved text; without it, the id held by another session is refused.
15
+ */
16
+ export const RESUME_TOKEN_ARG = 'hydraniumResumeToken';
@@ -0,0 +1,59 @@
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
+ // Declared field by field rather than extending GLSP's action types: this
11
+ // package carries no GLSP dependency, and both GLSP heads already depend on it.
12
+ // The fields are GLSP's own, so both actions are assignable to GLSP's
13
+ // `RequestAction` and `ResponseAction`.
14
+
15
+ /**
16
+ * A save of a diagram's model that the server answers, with a
17
+ * {@link ModelSavedAction} once the save has finished or a GLSP
18
+ * `RejectAction` when it fails.
19
+ *
20
+ * It carries what GLSP's `SaveModelAction` carries, and the server saves it the
21
+ * same way. GLSP's `SaveModelAction` is not answered: the server's only
22
+ * reply is a dirty-state change, which the client drops when the dirty flag
23
+ * does not change, so a client cannot tell which save an answer belongs to or
24
+ * whether a save failed.
25
+ */
26
+ export interface RequestSaveModelAction {
27
+ kind: typeof RequestSaveModelAction.KIND;
28
+ /** The id the response echoes as its `responseId`. Empty until the dispatcher assigns one. */
29
+ requestId: string;
30
+ /** How long the receiver waits for its own handler, in milliseconds. */
31
+ timeout?: number;
32
+ /** The file to save to, as in GLSP's `SaveModelAction`; absent saves to the diagram's source. */
33
+ fileUri?: string;
34
+ /** GLSP's typing marker for the response. Never set. */
35
+ readonly _?: ModelSavedAction;
36
+ }
37
+
38
+ export namespace RequestSaveModelAction {
39
+ export const KIND = 'hydraniumRequestSaveModel';
40
+
41
+ export function create(options: { fileUri?: string; requestId?: string } = {}): RequestSaveModelAction {
42
+ return { kind: KIND, requestId: '', ...options };
43
+ }
44
+ }
45
+
46
+ /** The server's answer to a {@link RequestSaveModelAction} that saved. */
47
+ export interface ModelSavedAction {
48
+ kind: typeof ModelSavedAction.KIND;
49
+ /** The `requestId` of the save this answers. The server's dispatcher sets it. */
50
+ responseId: string;
51
+ }
52
+
53
+ export namespace ModelSavedAction {
54
+ export const KIND = 'hydraniumModelSaved';
55
+
56
+ export function create(options: { responseId?: string } = {}): ModelSavedAction {
57
+ return { kind: KIND, responseId: '', ...options };
58
+ }
59
+ }
package/src/index.ts CHANGED
@@ -15,11 +15,15 @@
15
15
  // every production bundle that imports the root.
16
16
 
17
17
  export * from './abstract-logger';
18
+ export * from './console-logger';
18
19
  export * from './client';
20
+ export * from './client-ids';
19
21
  export * from './clock';
20
22
  export * from './data';
21
23
  export * from './browser-runtime';
22
24
  export * from './debouncer';
25
+ export * from './glsp-request-model-args';
26
+ export * from './glsp-save-model-actions';
23
27
  export * from './errors';
24
28
  export * from './host-diagnostics';
25
29
  export * from './logger';
@@ -29,6 +33,7 @@ export * from './latency-collector';
29
33
  // the modules that raise them.
30
34
  export * from './messages/primitives';
31
35
  export * from './patch-merge';
36
+ export * from './reconcile-write';
32
37
  export * from './noop-logger';
33
38
  export * from './observable-value';
34
39
  export * from './profile-session';
@@ -40,6 +45,7 @@ export * from './model-service';
40
45
  export * from './transfer-document';
41
46
  export * from './model-server';
42
47
  export * from './project';
48
+ export * from './random-uuid';
43
49
  export * from './rpc';
44
50
  export * from './uri';
45
51
  export * from './util';
@@ -87,8 +87,13 @@ export interface LatencyReport {
87
87
  */
88
88
  export type LatencyRetention = { readonly kind: 'keep-all' } | { readonly kind: 'ring-buffer'; readonly maxSamplesPerMethod: number };
89
89
 
90
- /** Per-method state: retained samples (bounded in ring-buffer mode) plus lifetime totals. */
91
- interface MethodAccumulator {
90
+ /**
91
+ * Per-method state: retained samples (bounded in ring-buffer mode) plus lifetime
92
+ * totals. The mutable tally behind {@link MethodLatency}, which is the derived
93
+ * report row. Held by the `protected` {@link LatencyCollector.durations}, so a
94
+ * subclass recording its own samples has to name it.
95
+ */
96
+ export interface MethodLatencyTally {
92
97
  /** Retained durations for percentile estimation; capped in ring-buffer mode. Order is irrelevant (report sorts). */
93
98
  readonly samples: number[];
94
99
  /** Next slot to overwrite once the ring buffer is full (ring-buffer mode only). */
@@ -119,7 +124,7 @@ function percentile(sortedAscending: readonly number[], percent: number): number
119
124
  * deterministic on a fake clock.
120
125
  */
121
126
  export class LatencyCollector {
122
- protected readonly durations = new Map<string, MethodAccumulator>();
127
+ protected readonly durations = new Map<string, MethodLatencyTally>();
123
128
  protected window: Stopwatch;
124
129
 
125
130
  constructor(
package/src/logger.ts CHANGED
@@ -24,6 +24,7 @@ export const LEVEL_LABELS: Record<LogLevel, string> = {
24
24
  /** Module-global threshold; shared by every `AbstractLogger` instance so derived child
25
25
  * loggers pick up live updates without each having to subscribe to a configuration source. */
26
26
  let currentLevel: LogThreshold = 'info';
27
+ let fileLevel: LogThreshold | undefined;
27
28
 
28
29
  /**
29
30
  * Cross-side public logger contract. Every consumer of the framework — browser
@@ -38,15 +39,15 @@ let currentLevel: LogThreshold = 'info';
38
39
  * and every `for` / `sub` / `with` derivation preserves the implementation type.
39
40
  */
40
41
  export interface Logger {
41
- /** Log a message at error level. */
42
+ /** Requested work failed; logged once, by the code that ends the failure, not by one that rethrows it. */
42
43
  error(message?: string, ...args: unknown[]): this;
43
- /** Log a message at warn level. */
44
+ /** An anomaly that was handled, or work declined by design, such as a conflict or a cap; a clean run logs none. */
44
45
  warn(message?: string, ...args: unknown[]): this;
45
- /** Log a message at info level. */
46
+ /** A milestone the person running the server would recognise without knowing the internals. */
46
47
  info(message?: string, ...args: unknown[]): this;
47
- /** Log a message at debug level. */
48
+ /** Diagnosis; its level decides whether the line is built, never which code runs. */
48
49
  debug(message?: string, ...args: unknown[]): this;
49
- /** High-volume diagnostic lines, only emitted at the `'trace'` threshold. */
50
+ /** High-volume diagnosis, emitted only at the `'trace'` threshold; as for `debug`, no code runs only for it. */
50
51
  trace(message?: string, ...args: unknown[]): this;
51
52
  /** Log a message at info-level threshold with a `Log` label (rather than `Info`). */
52
53
  log(message?: string, ...args: unknown[]): this;
@@ -93,12 +94,32 @@ export namespace Logger {
93
94
  return currentLevel;
94
95
  }
95
96
  /**
96
- * Whether a message at `level` would be emitted at the current threshold.
97
+ * Set the log file's own threshold, which {@link setLevel} does not move;
98
+ * `undefined` makes the file follow {@link getLevel}. A file sink compares
99
+ * against `getFileLevel() ?? getLevel()`, every other sink against
100
+ * {@link getLevel}.
101
+ *
102
+ * Set it through the file sink's own configuration, which clears it with
103
+ * the file: set here with no file configured, it widens
104
+ * {@link isLevelEnabled} for lines nothing writes.
105
+ */
106
+ export function setFileLevel(level: LogThreshold | undefined): void {
107
+ fileLevel = level;
108
+ }
109
+ /** Read the log file's own threshold, `undefined` while it follows {@link getLevel}. */
110
+ export function getFileLevel(): LogThreshold | undefined {
111
+ return fileLevel;
112
+ }
113
+ /**
114
+ * Whether any sink takes a message at `level`: the more verbose of
115
+ * {@link getLevel} and {@link getFileLevel} decides. A sink that admits less
116
+ * re-checks its own threshold before writing.
117
+ *
97
118
  * Use to guard expensive log-line construction:
98
119
  * `if (Logger.isLevelEnabled('trace')) logger.trace(buildPayload())`.
99
120
  */
100
121
  export function isLevelEnabled(level: LogLevel): boolean {
101
- return LEVEL_ORDER[level] <= LEVEL_ORDER[currentLevel];
122
+ return LEVEL_ORDER[level] <= Math.max(LEVEL_ORDER[currentLevel], fileLevel ? LEVEL_ORDER[fileLevel] : 0);
102
123
  }
103
124
  /**
104
125
  * Whether a message at `threshold` would be emitted: `false` for `'off'`,
@@ -136,6 +157,11 @@ export function parseLogLevel(value: unknown): LogThreshold | undefined {
136
157
  export const DEFAULT_LOG_LEVEL_ENV = 'HYDRANIUM_LOG_LEVEL';
137
158
  /** Env var the server reads its log file-tee target from. See {@link DEFAULT_LOG_LEVEL_ENV}. */
138
159
  export const DEFAULT_LOG_FILE_ENV = 'HYDRANIUM_LOG_FILE';
160
+ /**
161
+ * Env var the server reads the file tee's own threshold from, which the LSP
162
+ * log-level setting does not change. See {@link Logger.setFileLevel}.
163
+ */
164
+ export const DEFAULT_LOG_FILE_LEVEL_ENV = 'HYDRANIUM_LOG_FILE_LEVEL';
139
165
 
140
166
  /**
141
167
  * Human-readable formatting helpers used in log lines and diagnostic output.
@@ -25,8 +25,10 @@
25
25
 
26
26
  export * from './primitives';
27
27
 
28
- export { STALE_BASED_UPDATE } from '../errors';
29
- export { DATA_SERVER_CONNECT_FAILED, DATA_SERVER_NOT_READY } from '../client/data-session';
28
+ export { DOCUMENT_NOT_OPEN, DUPLICATE_CLIENT_ID, SESSION_CLOSED, STALE_BASE_VERSION_UPDATE } from '../errors';
29
+ export { DATA_CONNECTION_SESSION_RESTORE_FAILED, DATA_CONNECTION_WATCH_RESTORE_FAILED } from '../client/data-connection';
30
+ export { DATA_SERVER_CONNECT_FAILED, DATA_SERVER_NOT_READY } from '../client/rpc-connection';
31
+ export { DATA_SESSION_ANSWER_WITHOUT_MODEL, DATA_SESSION_RESTORE_FAILED, DATA_SESSION_UNSAVED_LOST } from '../client/data-session';
30
32
  export {
31
33
  RELAY_REPLAY_FAILED,
32
34
  RELAY_TRANSPORT_OPEN_FAILED,