@hydranium/protocol 1.0.0-next.23 → 1.0.0-next.230

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 (246) hide show
  1. package/README.md +40 -3
  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 +236 -0
  7. package/lib/client/data-connection.d.ts.map +1 -0
  8. package/lib/client/data-connection.js +404 -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 +27 -22
  15. package/lib/client/data-port.d.ts.map +1 -1
  16. package/lib/client/data-session.d.ts +473 -81
  17. package/lib/client/data-session.d.ts.map +1 -1
  18. package/lib/client/data-session.js +743 -108
  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 +9 -3
  25. package/lib/client/message-relay.d.ts.map +1 -1
  26. package/lib/client/message-relay.js +11 -5
  27. package/lib/client/message-relay.js.map +1 -1
  28. package/lib/client/post-message-transport.d.ts +64 -3
  29. package/lib/client/post-message-transport.d.ts.map +1 -1
  30. package/lib/client/post-message-transport.js +175 -1
  31. package/lib/client/post-message-transport.js.map +1 -1
  32. package/lib/client/rpc-connection.d.ts +157 -0
  33. package/lib/client/rpc-connection.d.ts.map +1 -0
  34. package/lib/client/rpc-connection.js +214 -0
  35. package/lib/client/rpc-connection.js.map +1 -0
  36. package/lib/client-ids.d.ts +45 -0
  37. package/lib/client-ids.d.ts.map +1 -0
  38. package/lib/client-ids.js +48 -0
  39. package/lib/client-ids.js.map +1 -0
  40. package/lib/clock.d.ts +38 -0
  41. package/lib/clock.d.ts.map +1 -1
  42. package/lib/clock.js +36 -1
  43. package/lib/clock.js.map +1 -1
  44. package/lib/console-logger.d.ts +23 -0
  45. package/lib/console-logger.d.ts.map +1 -0
  46. package/lib/console-logger.js +39 -0
  47. package/lib/console-logger.js.map +1 -0
  48. package/lib/data/data-protocol-methods.d.ts +4 -4
  49. package/lib/data/data-protocol-methods.d.ts.map +1 -1
  50. package/lib/data/data-protocol-methods.js +12 -1
  51. package/lib/data/data-protocol-methods.js.map +1 -1
  52. package/lib/data/data-server-protocol.d.ts +132 -41
  53. package/lib/data/data-server-protocol.d.ts.map +1 -1
  54. package/lib/data/events.d.ts +117 -21
  55. package/lib/data/events.d.ts.map +1 -1
  56. package/lib/data/requests.d.ts +69 -11
  57. package/lib/data/requests.d.ts.map +1 -1
  58. package/lib/debouncer.d.ts.map +1 -1
  59. package/lib/debouncer.js.map +1 -1
  60. package/lib/errors.d.ts +187 -29
  61. package/lib/errors.d.ts.map +1 -1
  62. package/lib/errors.js +270 -29
  63. package/lib/errors.js.map +1 -1
  64. package/lib/glsp-request-model-args.d.ts +16 -0
  65. package/lib/glsp-request-model-args.d.ts.map +1 -0
  66. package/lib/glsp-request-model-args.js +19 -0
  67. package/lib/glsp-request-model-args.js.map +1 -0
  68. package/lib/glsp-save-model-actions.d.ts +50 -0
  69. package/lib/glsp-save-model-actions.d.ts.map +1 -0
  70. package/lib/glsp-save-model-actions.js +28 -0
  71. package/lib/glsp-save-model-actions.js.map +1 -0
  72. package/lib/index.d.ts +7 -0
  73. package/lib/index.d.ts.map +1 -1
  74. package/lib/index.js +10 -0
  75. package/lib/index.js.map +1 -1
  76. package/lib/latency-collector.d.ts +8 -4
  77. package/lib/latency-collector.d.ts.map +1 -1
  78. package/lib/latency-collector.js.map +1 -1
  79. package/lib/logger.d.ts +22 -1
  80. package/lib/logger.d.ts.map +1 -1
  81. package/lib/logger.js +31 -3
  82. package/lib/logger.js.map +1 -1
  83. package/lib/messages/index.d.ts +30 -0
  84. package/lib/messages/index.d.ts.map +1 -0
  85. package/lib/messages/index.js +62 -0
  86. package/lib/messages/index.js.map +1 -0
  87. package/lib/messages/primitives.d.ts +188 -0
  88. package/lib/messages/primitives.d.ts.map +1 -0
  89. package/lib/messages/primitives.js +161 -0
  90. package/lib/messages/primitives.js.map +1 -0
  91. package/lib/model-server.d.ts +60 -13
  92. package/lib/model-server.d.ts.map +1 -1
  93. package/lib/model-server.js +4 -2
  94. package/lib/model-server.js.map +1 -1
  95. package/lib/model-service/base-version.d.ts +64 -0
  96. package/lib/model-service/base-version.d.ts.map +1 -0
  97. package/lib/model-service/base-version.js +43 -0
  98. package/lib/model-service/base-version.js.map +1 -0
  99. package/lib/model-service/index.d.ts +1 -1
  100. package/lib/model-service/index.d.ts.map +1 -1
  101. package/lib/model-service/index.js +4 -5
  102. package/lib/model-service/index.js.map +1 -1
  103. package/lib/model-service/reference-candidate.d.ts +5 -3
  104. package/lib/model-service/reference-candidate.d.ts.map +1 -1
  105. package/lib/{model-service/args.js → node/index.d.ts} +2 -3
  106. package/lib/node/index.d.ts.map +1 -0
  107. package/lib/node/index.js +29 -0
  108. package/lib/node/index.js.map +1 -0
  109. package/lib/node/process-memory.d.ts +66 -0
  110. package/lib/node/process-memory.d.ts.map +1 -0
  111. package/lib/node/process-memory.js +291 -0
  112. package/lib/node/process-memory.js.map +1 -0
  113. package/lib/noop-logger.d.ts.map +1 -1
  114. package/lib/noop-logger.js.map +1 -1
  115. package/lib/observable-value.js.map +1 -1
  116. package/lib/patch-merge.d.ts +35 -32
  117. package/lib/patch-merge.d.ts.map +1 -1
  118. package/lib/patch-merge.js +67 -23
  119. package/lib/patch-merge.js.map +1 -1
  120. package/lib/profile-session.d.ts +8 -4
  121. package/lib/profile-session.d.ts.map +1 -1
  122. package/lib/profile-session.js.map +1 -1
  123. package/lib/random-uuid.d.ts +14 -0
  124. package/lib/random-uuid.d.ts.map +1 -0
  125. package/lib/random-uuid.js +24 -0
  126. package/lib/random-uuid.js.map +1 -0
  127. package/lib/reconcile-write.d.ts +65 -0
  128. package/lib/reconcile-write.d.ts.map +1 -0
  129. package/lib/reconcile-write.js +67 -0
  130. package/lib/reconcile-write.js.map +1 -0
  131. package/lib/rpc/bind-rpc-methods.d.ts +33 -3
  132. package/lib/rpc/bind-rpc-methods.d.ts.map +1 -1
  133. package/lib/rpc/bind-rpc-methods.js +32 -3
  134. package/lib/rpc/bind-rpc-methods.js.map +1 -1
  135. package/lib/rpc/create-rpc-proxy.d.ts +10 -0
  136. package/lib/rpc/create-rpc-proxy.d.ts.map +1 -1
  137. package/lib/rpc/create-rpc-proxy.js +12 -2
  138. package/lib/rpc/create-rpc-proxy.js.map +1 -1
  139. package/lib/rpc/index.d.ts +1 -0
  140. package/lib/rpc/index.d.ts.map +1 -1
  141. package/lib/rpc/index.js +1 -0
  142. package/lib/rpc/index.js.map +1 -1
  143. package/lib/rpc/send-by-method-name.d.ts +76 -0
  144. package/lib/rpc/send-by-method-name.d.ts.map +1 -0
  145. package/lib/rpc/send-by-method-name.js +120 -0
  146. package/lib/rpc/send-by-method-name.js.map +1 -0
  147. package/lib/rpc/wire-prefix.js.map +1 -1
  148. package/lib/testing/catalogue-audit.d.ts +80 -0
  149. package/lib/testing/catalogue-audit.d.ts.map +1 -0
  150. package/lib/testing/catalogue-audit.js +94 -0
  151. package/lib/testing/catalogue-audit.js.map +1 -0
  152. package/lib/testing/data-doubles.d.ts +42 -15
  153. package/lib/testing/data-doubles.d.ts.map +1 -1
  154. package/lib/testing/data-doubles.js +58 -10
  155. package/lib/testing/data-doubles.js.map +1 -1
  156. package/lib/testing/fake-clock.d.ts +9 -1
  157. package/lib/testing/fake-clock.d.ts.map +1 -1
  158. package/lib/testing/fake-clock.js +54 -45
  159. package/lib/testing/fake-clock.js.map +1 -1
  160. package/lib/testing/index.d.ts +1 -0
  161. package/lib/testing/index.d.ts.map +1 -1
  162. package/lib/testing/index.js +5 -2
  163. package/lib/testing/index.js.map +1 -1
  164. package/lib/testing/node/duplex-connection.d.ts.map +1 -1
  165. package/lib/testing/node/duplex-connection.js +3 -2
  166. package/lib/testing/node/duplex-connection.js.map +1 -1
  167. package/lib/testing/node/duplex-stream.js.map +1 -1
  168. package/lib/testing/node/index.d.ts +1 -0
  169. package/lib/testing/node/index.d.ts.map +1 -1
  170. package/lib/testing/node/index.js +2 -2
  171. package/lib/testing/node/index.js.map +1 -1
  172. package/lib/testing/node/message-port-pair.d.ts +25 -0
  173. package/lib/testing/node/message-port-pair.d.ts.map +1 -0
  174. package/lib/testing/node/message-port-pair.js +26 -0
  175. package/lib/testing/node/message-port-pair.js.map +1 -0
  176. package/lib/testing/wait-for.js.map +1 -1
  177. package/lib/tracer.d.ts.map +1 -1
  178. package/lib/tracer.js.map +1 -1
  179. package/lib/transfer-diagnostic.d.ts +33 -0
  180. package/lib/transfer-diagnostic.d.ts.map +1 -1
  181. package/lib/transfer-diagnostic.js +23 -0
  182. package/lib/transfer-diagnostic.js.map +1 -1
  183. package/lib/transfer-document.d.ts +70 -32
  184. package/lib/transfer-document.d.ts.map +1 -1
  185. package/lib/transfer-document.js +17 -9
  186. package/lib/transfer-document.js.map +1 -1
  187. package/lib/uri.d.ts.map +1 -1
  188. package/lib/uri.js.map +1 -1
  189. package/lib/util.d.ts +8 -0
  190. package/lib/util.d.ts.map +1 -1
  191. package/lib/util.js +32 -0
  192. package/lib/util.js.map +1 -1
  193. package/package.json +29 -37
  194. package/src/abstract-logger.ts +8 -0
  195. package/src/client/data-connection.ts +502 -0
  196. package/src/client/data-events.ts +33 -1
  197. package/src/client/data-port.ts +29 -23
  198. package/src/client/data-session.ts +951 -126
  199. package/src/client/index.ts +14 -9
  200. package/src/client/message-relay.ts +29 -7
  201. package/src/client/post-message-transport.ts +219 -4
  202. package/src/client/rpc-connection.ts +281 -0
  203. package/src/client-ids.ts +49 -0
  204. package/src/clock.ts +56 -0
  205. package/src/console-logger.ts +39 -0
  206. package/src/data/data-protocol-methods.ts +13 -4
  207. package/src/data/data-server-protocol.ts +157 -41
  208. package/src/data/events.ts +123 -21
  209. package/src/data/requests.ts +74 -11
  210. package/src/errors.ts +322 -36
  211. package/src/glsp-request-model-args.ts +16 -0
  212. package/src/glsp-save-model-actions.ts +59 -0
  213. package/src/index.ts +10 -0
  214. package/src/latency-collector.ts +8 -3
  215. package/src/logger.ts +28 -2
  216. package/src/messages/index.ts +37 -0
  217. package/src/messages/primitives.ts +271 -0
  218. package/src/model-server.ts +63 -18
  219. package/src/model-service/base-version.ts +72 -0
  220. package/src/model-service/index.ts +4 -5
  221. package/src/model-service/reference-candidate.ts +5 -3
  222. package/src/node/index.ts +14 -0
  223. package/src/node/process-memory.ts +299 -0
  224. package/src/patch-merge.ts +97 -42
  225. package/src/profile-session.ts +9 -4
  226. package/src/random-uuid.ts +21 -0
  227. package/src/reconcile-write.ts +124 -0
  228. package/src/rpc/README.md +4 -5
  229. package/src/rpc/bind-rpc-methods.ts +59 -4
  230. package/src/rpc/create-rpc-proxy.ts +20 -2
  231. package/src/rpc/index.ts +1 -0
  232. package/src/rpc/send-by-method-name.ts +140 -0
  233. package/src/testing/catalogue-audit.ts +111 -0
  234. package/src/testing/data-doubles.ts +145 -25
  235. package/src/testing/fake-clock.ts +62 -47
  236. package/src/testing/index.ts +5 -2
  237. package/src/testing/node/duplex-connection.ts +3 -2
  238. package/src/testing/node/index.ts +2 -2
  239. package/src/testing/node/message-port-pair.ts +40 -0
  240. package/src/transfer-diagnostic.ts +40 -0
  241. package/src/transfer-document.ts +87 -34
  242. package/src/util.ts +33 -0
  243. package/lib/model-service/args.d.ts +0 -64
  244. package/lib/model-service/args.d.ts.map +0 -1
  245. package/lib/model-service/args.js.map +0 -1
  246. package/src/model-service/args.ts +0 -67
@@ -0,0 +1,502 @@
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 { Disposable, Emitter, type Event } from 'vscode-jsonrpc';
11
+ import { FRAMEWORK_CLIENT_IDS } from '../client-ids';
12
+ import {
13
+ DATA_CLIENT_PROTOCOL_METHODS,
14
+ DATA_SERVER_WIRE_PREFIX,
15
+ type DataClientProtocol,
16
+ type DataServerProtocol,
17
+ type DiagnosticOf,
18
+ type ProjectOf,
19
+ type TransferDocumentDirtyChangedEvent,
20
+ type TransferDocumentUpdatedEvent
21
+ } from '../data';
22
+ import { DuplicateClientIdError, ReservedClientIdError } from '../errors';
23
+ import type { Logger } from '../logger';
24
+ import { defineMessage, describeError, resolve } from '../messages/primitives';
25
+ import { NoopLogger } from '../noop-logger';
26
+ import { randomUuid } from '../random-uuid';
27
+ import type { TransferElement } from '../transfer-element';
28
+ import { DataEvents } from './data-events';
29
+ import type { DataPort } from './data-port';
30
+ import { DataSession, type DataSessionFactory } from './data-session';
31
+ import { RpcConnection, type RpcConnectionGeneration, type RpcConnectionLifecycle } from './rpc-connection';
32
+
33
+ /**
34
+ * A watch {@link DataConnection.watchDocument} keeps could not be sent again to
35
+ * a connection that became ready after a drop; the next one sends it again.
36
+ */
37
+ export const DATA_CONNECTION_WATCH_RESTORE_FAILED = defineMessage(
38
+ 'hydranium/protocol/data-connection-watch-restore-failed',
39
+ 'Could not watch {uri} again after reconnecting to the data server: {detail}'
40
+ );
41
+
42
+ /**
43
+ * A session's restore threw when its connection came back; the connection
44
+ * went on restoring the others.
45
+ */
46
+ export const DATA_CONNECTION_SESSION_RESTORE_FAILED = defineMessage(
47
+ 'hydranium/protocol/data-connection-session-restore-failed',
48
+ 'Could not restore a session after reconnecting to the data server: {detail}'
49
+ );
50
+
51
+ /** Options for {@link DataConnection}. */
52
+ export interface DataConnectionOptions<
53
+ TTransfer extends TransferElement = TransferElement,
54
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
55
+ > extends RpcConnectionLifecycle {
56
+ /**
57
+ * Wire namespace the server is addressed under. Defaults to the
58
+ * framework's {@link DATA_SERVER_WIRE_PREFIX}, which is what an unmodified
59
+ * `DataServer` binds. Override only alongside the server's own
60
+ * `methodNamespace` option — a mismatch turns every request into
61
+ * "Unhandled method" rather than failing at wire-up.
62
+ */
63
+ readonly methodNamespace?: string;
64
+ /** Builds the sessions `createSession` hands out. Defaults to a plain {@link DataSession}. */
65
+ readonly sessionFactory?: DataSessionFactory<TTransfer, TServer>;
66
+ }
67
+
68
+ /** {@link DataConnectionOptions} for a client that does not speak {@link DataClientProtocol}. */
69
+ export interface DataConnectionOptionsWithMethods<
70
+ TClient extends object,
71
+ TTransfer extends TransferElement = TransferElement,
72
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
73
+ > extends DataConnectionOptions<TTransfer, TServer> {
74
+ /**
75
+ * Method names of the client to bind as inbound handlers. Declare it
76
+ * `as const satisfies ReadonlyArray<keyof YourClient & string>` so the list
77
+ * cannot drift from the interface.
78
+ */
79
+ readonly clientMethods: readonly (keyof TClient & string)[];
80
+ }
81
+
82
+ /**
83
+ * Trailing constructor arguments, required only when the client cannot take
84
+ * the framework's default method list.
85
+ *
86
+ * `bindRpcMethods` throws for a name the target does not implement, so a
87
+ * request/response-only client binding the default list fails at wire-up. The
88
+ * conditional turns that into a compile error.
89
+ */
90
+ export type DataConnectionArgs<
91
+ TTransfer extends TransferElement,
92
+ TClient extends object,
93
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
94
+ > =
95
+ TClient extends DataClientProtocol<TTransfer>
96
+ ? [options?: DataConnectionOptions<TTransfer, TServer> & Partial<DataConnectionOptionsWithMethods<TClient, TTransfer, TServer>>]
97
+ : [options: DataConnectionOptionsWithMethods<TClient, TTransfer, TServer>];
98
+
99
+ /**
100
+ * A {@link RpcConnection} to the data head, carrying as many participants as
101
+ * the host has interested parties.
102
+ *
103
+ * Document operations live on the participants rather than here: they carry a
104
+ * `clientId`, which identifies a participant rather than a wire, and the server
105
+ * keys its opens and watches per `(uri, clientId)`. Two parties sharing one
106
+ * identity cannot tell each other's writes from their own echoes.
107
+ * {@link DataConnection.watchDocument} is the exception: it acts as no
108
+ * participant, under an id no session holds, and opens or writes nothing.
109
+ *
110
+ * Generic over the transfer root so this file names no grammar. An adopter
111
+ * binds the concrete root (or the union of them, for a multi-grammar head) at
112
+ * its own edge.
113
+ */
114
+ export class DataConnection<
115
+ TTransfer extends TransferElement,
116
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>,
117
+ TClient extends object = DataClientProtocol<TTransfer>
118
+ > extends RpcConnection<TServer, TClient> {
119
+ protected readonly sessions = new Set<DataSession<TTransfer, TServer>>();
120
+ protected readonly sessionFactory: DataSessionFactory<TTransfer, TServer>;
121
+ protected readonly createSessionEmitter = new Emitter<DataSession<TTransfer, TServer>>();
122
+ /**
123
+ * Fires with each session {@link createSession} starts, before it returns,
124
+ * so a listener sees every session a caller can. A session started before
125
+ * the listener subscribed is in {@link liveSessions}.
126
+ */
127
+ readonly onDidCreateSession: Event<DataSession<TTransfer, TServer>> = this.createSessionEmitter.event;
128
+ /**
129
+ * Per URI, the `dirty` the client was last told, whether a session of this
130
+ * connection has it open or a watch follows it. A session's open or close
131
+ * of the URI forgets it; disposing a watch does not, since a watch knows
132
+ * only the caller's spelling of the URI, not the server's key. A
133
+ * session's restore and a watch sent again after a reconnect tell the
134
+ * client their answer where it differs, a forgotten URI included; see
135
+ * {@link restoreDirty}.
136
+ */
137
+ protected readonly dirtyStates = new Map<string, boolean>();
138
+ /** Backs each session's {@link DataSessionHost.onDidChangeDirty}. */
139
+ protected readonly dirtyChangedEmitter = new Emitter<TransferDocumentDirtyChangedEvent>();
140
+ /** Backs each session's {@link DataSessionHost.onDidUpdateDocument}. */
141
+ protected readonly documentUpdatedEmitter = new Emitter<TransferDocumentUpdatedEvent<TTransfer, DiagnosticOf<TServer>>>();
142
+ /**
143
+ * Per id {@link watchDocument} watches under, the URI it watches, which
144
+ * {@link generationReady} sends again to every later generation until the
145
+ * watch's handle is disposed.
146
+ */
147
+ protected readonly watches = new Map<string, string>();
148
+ /** The port's logger, or one that logs nothing. */
149
+ protected readonly logger: Logger;
150
+ /** Backs {@link onDidReconnect}. */
151
+ protected readonly reconnectEmitter = new Emitter<void>();
152
+ /**
153
+ * Fires on every reconnect: once a connection becomes ready after an
154
+ * earlier one was, and its watches have been sent. The server sends no
155
+ * event for a change made while the connection was down, so a watcher reads
156
+ * its document again on this; a read it sends now reaches the server after
157
+ * its watch.
158
+ */
159
+ readonly onDidReconnect: Event<void> = this.reconnectEmitter.event;
160
+ /** Whether a generation was ready before, which makes the next one a reconnect. */
161
+ protected readyBefore = false;
162
+
163
+ constructor(port: DataPort, client: TClient, ...rest: DataConnectionArgs<TTransfer, TClient, TServer>) {
164
+ const [options = {}] = rest as [
165
+ (DataConnectionOptions<TTransfer, TServer> & Partial<DataConnectionOptionsWithMethods<TClient, TTransfer, TServer>>)?
166
+ ];
167
+ super(port, client, {
168
+ methodNamespace: options.methodNamespace ?? DATA_SERVER_WIRE_PREFIX,
169
+ // The default is reachable only where `TClient` satisfies
170
+ // `DataClientProtocol`, which the constructor's conditional enforces;
171
+ // the compiler cannot carry that through to the generic parameter.
172
+ clientMethods: options.clientMethods ?? (DATA_CLIENT_PROTOCOL_METHODS as unknown as readonly (keyof TClient & string)[]),
173
+ lifecycle: options
174
+ });
175
+ this.sessionFactory =
176
+ options.sessionFactory ?? ((clientId, host, label) => new DataSession<TTransfer, TServer>(clientId, host, label));
177
+ this.logger = (port.logger ?? new NoopLogger()).for('DataConnection');
178
+ }
179
+
180
+ /**
181
+ * The sessions of this connection that have not ended, in the order they
182
+ * started. A session is listed until its `onDidDispose` fires, or until
183
+ * {@link dispose} clears the list.
184
+ */
185
+ get liveSessions(): readonly DataSession<TTransfer, TServer>[] {
186
+ return [...this.sessions];
187
+ }
188
+
189
+ /**
190
+ * Start a participant on this connection, registered with the server under a
191
+ * fresh id, `label` plus `#` plus a random UUID, or under `clientId` when
192
+ * given. Pass a `label` naming the participant; without one it is
193
+ * `session`. Synchronous: the registration is sent at once, and the
194
+ * session's calls wait for it. The server refuses an id live anywhere in
195
+ * its process, and every call of that session then rejects with an error
196
+ * `isDuplicateClientIdError` recognises; an id the server reserves beyond
197
+ * {@link FRAMEWORK_CLIENT_IDS}, such as the integrity author, with one
198
+ * `isReservedClientIdError` recognises. Only the code crosses the wire, so
199
+ * test with those guards rather than `instanceof`.
200
+ *
201
+ * Throws a {@link ReservedClientIdError} for an id in
202
+ * {@link FRAMEWORK_CLIENT_IDS} — those are authors the SERVER emits rather
203
+ * than participants, so a session holding one would read the framework's
204
+ * own broadcasts as its own echoes and drop them — and a
205
+ * {@link DuplicateClientIdError} for an id a live session on this
206
+ * connection already holds.
207
+ */
208
+ createSession(label = 'session', clientId?: string): DataSession<TTransfer, TServer> {
209
+ this.assertLive();
210
+ const id = clientId ?? `${label}#${randomUuid()}`;
211
+ if (FRAMEWORK_CLIENT_IDS.includes(id)) {
212
+ throw new ReservedClientIdError(id);
213
+ }
214
+ if ([...this.sessions].some(session => session.clientId === id)) {
215
+ throw new DuplicateClientIdError(id);
216
+ }
217
+ const session = this.sessionFactory(
218
+ id,
219
+ {
220
+ connected: () => this.connected(),
221
+ reportError: (error, reported) => this.reportError(error, reported),
222
+ restoreDirty: event => this.restoreDirty(event),
223
+ forgetDirty: uri => this.dirtyStates.delete(uri),
224
+ onDidChangeDirty: this.dirtyChangedEmitter.event,
225
+ onDidUpdateDocument: this.documentUpdatedEmitter.event
226
+ },
227
+ label
228
+ );
229
+ this.sessions.add(session);
230
+ // Subscribed before the session is handed out, so the id is free again
231
+ // on this connection by the time any caller's listener runs.
232
+ session.onDidDispose(() => this.sessions.delete(session));
233
+ // A failure reaches the session's own calls, which wait for the same
234
+ // registration; caught here only so it is not also reported unhandled.
235
+ session.connected().catch(() => undefined);
236
+ this.createSessionEmitter.fire(session);
237
+ return session;
238
+ }
239
+
240
+ /**
241
+ * Follow `uri` without opening it: its update events reach this
242
+ * connection's client once this resolves. An open would hold the document
243
+ * for as long as the caller follows it. The watch runs under an id of its
244
+ * own, `label` plus `#` plus a random UUID, and needs no session: a session
245
+ * closing the document would also end its own watch of it. Every later
246
+ * connection that becomes ready gets the watch again. Disposing the handle
247
+ * unwatches.
248
+ */
249
+ async watchDocument(uri: string, label = 'watch'): Promise<Disposable> {
250
+ const clientId = `${label}#${randomUuid()}`;
251
+ const server = await this.connected();
252
+ // Kept only from here: kept during the wait, a generation that became
253
+ // ready meanwhile would send the watch a second time.
254
+ this.watches.set(clientId, uri);
255
+ try {
256
+ await server.watchModelDocument({ uri, clientId });
257
+ } catch (error: unknown) {
258
+ this.watches.delete(clientId);
259
+ throw error;
260
+ }
261
+ this.logger.debug(`Watch ${uri} as ${clientId}`);
262
+ return Disposable.create(() => {
263
+ if (!this.watches.delete(clientId)) {
264
+ return;
265
+ }
266
+ // Without a generation the server dropped the watch with its
267
+ // connection, and one that drops before it is ready drops it too: the
268
+ // unwatch follows no drop to a connection opened only for it.
269
+ const generation = this.generation;
270
+ if (generation) {
271
+ (generation.ready ??= this.awaitReady(generation)).then(
272
+ () => {
273
+ if (this.generation === generation) {
274
+ this.logger.debug(`Unwatch ${uri} as ${clientId}`);
275
+ generation.server.unwatchModelDocument({ uri, clientId }).catch(() => undefined);
276
+ }
277
+ },
278
+ () => undefined
279
+ );
280
+ }
281
+ });
282
+ }
283
+
284
+ /**
285
+ * The client, with its `onDocumentDirtyChanged` passing through
286
+ * {@link deliverDirty} first, so {@link dirtyStates} holds what the server
287
+ * told it, and every session hears it through {@link dirtyChangedEmitter};
288
+ * and with its `onDocumentUpdated` heard by every session through
289
+ * {@link documentUpdatedEmitter} first. Every other bound method forwards
290
+ * to the client unchanged, and one the client lacks stays absent, so the
291
+ * binding still refuses it.
292
+ */
293
+ protected override localTarget(): TClient {
294
+ const client = this.client as unknown as Record<string, unknown>;
295
+ const hearsDirty = typeof client.onDocumentDirtyChanged === 'function';
296
+ const hearsUpdates = typeof client.onDocumentUpdated === 'function';
297
+ if (!hearsDirty && !hearsUpdates) {
298
+ return this.client;
299
+ }
300
+ const target: Record<string, unknown> = {};
301
+ for (const name of this.clientMethods) {
302
+ const method: unknown = client[name];
303
+ if (typeof method === 'function') {
304
+ target[name] = (params: unknown): unknown => (method as (params: unknown) => unknown).call(client, params);
305
+ }
306
+ }
307
+ if (hearsDirty) {
308
+ target.onDocumentDirtyChanged = (event: TransferDocumentDirtyChangedEvent): void => {
309
+ this.dirtyChangedEmitter.fire(event);
310
+ this.deliverDirty(event);
311
+ };
312
+ }
313
+ if (hearsUpdates) {
314
+ const forward = target.onDocumentUpdated as (event: TransferDocumentUpdatedEvent<TTransfer, DiagnosticOf<TServer>>) => void;
315
+ target.onDocumentUpdated = (event: TransferDocumentUpdatedEvent<TTransfer, DiagnosticOf<TServer>>): void => {
316
+ this.documentUpdatedEmitter.fire(event);
317
+ forward(event);
318
+ };
319
+ }
320
+ return target as unknown as TClient;
321
+ }
322
+
323
+ /**
324
+ * Hand a dirty state a restore read to the client, unless it is what
325
+ * {@link dirtyStates} says the client was last told; a URI it holds
326
+ * nothing for counts as different.
327
+ */
328
+ protected restoreDirty(event: TransferDocumentDirtyChangedEvent): void {
329
+ if (this.dirtyStates.get(event.uri) !== (event.text?.dirty ?? false)) {
330
+ this.deliverDirty(event);
331
+ }
332
+ }
333
+
334
+ /** Record `event` in {@link dirtyStates} and hand it to the client. */
335
+ protected deliverDirty(event: TransferDocumentDirtyChangedEvent): void {
336
+ this.dirtyStates.set(event.uri, event.text?.dirty ?? false);
337
+ const client = this.client as unknown as Partial<Pick<DataClientProtocol<TTransfer>, 'onDocumentDirtyChanged'>>;
338
+ client.onDocumentDirtyChanged?.(event);
339
+ }
340
+
341
+ /**
342
+ * After the transport dropped, reconnect on the next macrotask for the
343
+ * sessions with documents open, so they re-watch and follow their documents
344
+ * again without waiting for a call of their own, and connect for what
345
+ * {@link watchDocument} watches, which {@link generationReady} places
346
+ * again; a session with nothing open restores on its next call. Nothing is
347
+ * scheduled once this connection is disposed, which drops its generation
348
+ * too.
349
+ */
350
+ protected override dropGeneration(): void {
351
+ const dropped = this.generation !== undefined;
352
+ super.dropGeneration();
353
+ if (dropped && !this.disposed) {
354
+ setTimeout(() => {
355
+ if (!this.disposed) {
356
+ this.reconnectSessions();
357
+ if (this.watches.size > 0) {
358
+ // One generation, not `connected`, which follows a drop to
359
+ // the next: that drop's own timer asks again whether
360
+ // anything is still kept. A failure is reported by the gate.
361
+ const generation = this.currentGeneration();
362
+ (generation.ready ??= this.awaitReady(generation)).catch(() => undefined);
363
+ }
364
+ }
365
+ }, 0);
366
+ }
367
+ }
368
+
369
+ /**
370
+ * Call `reconnect()` on every session, reporting a throw instead of letting
371
+ * one session's restore stop the others and the watches after them, and,
372
+ * inside the readiness gate, fail the whole generation.
373
+ */
374
+ protected reconnectSessions(): void {
375
+ for (const session of this.sessions) {
376
+ try {
377
+ session.reconnect();
378
+ } catch (error: unknown) {
379
+ // Reported, so it reaches the user on a port without a logger;
380
+ // logged too, since only the log names the session.
381
+ this.reportError(error, resolve(DATA_CONNECTION_SESSION_RESTORE_FAILED, { detail: describeError(error) }));
382
+ this.logger.error(`Could not restore session ${session.clientId}: ${describeError(error)}`);
383
+ }
384
+ }
385
+ }
386
+
387
+ /**
388
+ * Restore what the server lost with an earlier generation, whichever
389
+ * request brought this one up: the documents of sessions that have some
390
+ * open, and every watch {@link watchDocument} keeps.
391
+ */
392
+ protected override generationReady(generation: RpcConnectionGeneration<TServer>): void {
393
+ super.generationReady(generation);
394
+ this.reconnectSessions();
395
+ this.watches.forEach((uri, clientId) => this.watchAgain(generation, clientId, uri));
396
+ if (this.readyBefore) {
397
+ this.reconnectEmitter.fire(undefined);
398
+ }
399
+ this.readyBefore = true;
400
+ }
401
+
402
+ /**
403
+ * Send the watch of `uri` under `clientId` to `generation`, which has just
404
+ * passed its readiness gate. Sent at once rather than after a wait, so no
405
+ * drop can come between choosing the generation and sending. A failure is
406
+ * reported, since no caller waits on it, only while the watch is kept and
407
+ * `generation` is still current: otherwise the next generation sends it
408
+ * again.
409
+ *
410
+ * Once the watch is in place, the document's dirty state is read and goes
411
+ * through {@link restoreDirty}, as a session's restore does: a flip while
412
+ * the connection was down reached no one.
413
+ */
414
+ protected watchAgain(generation: RpcConnectionGeneration<TServer>, clientId: string, uri: string): void {
415
+ generation.server.watchModelDocument({ uri, clientId }).then(
416
+ () => {
417
+ if (!this.watches.has(clientId)) {
418
+ return;
419
+ }
420
+ this.logger.debug(`Watch ${uri} again as ${clientId}`);
421
+ generation.server.getModelDocument({ uri }).then(
422
+ current => {
423
+ if (current.text && this.watches.has(clientId)) {
424
+ try {
425
+ this.restoreDirty({ uri: current.uri, text: current.text });
426
+ } catch {
427
+ // The client's listener failed, not the watch, which stays kept.
428
+ }
429
+ }
430
+ },
431
+ () => undefined
432
+ );
433
+ },
434
+ (error: unknown) => {
435
+ if (!this.watches.has(clientId)) {
436
+ return;
437
+ }
438
+ if (this.generation !== generation) {
439
+ this.logger.debug(`Watch of ${uri} as ${clientId} cut short by a lost connection; the next one sends it again`);
440
+ return;
441
+ }
442
+ this.reportError(error, resolve(DATA_CONNECTION_WATCH_RESTORE_FAILED, { uri, detail: describeError(error) }));
443
+ }
444
+ );
445
+ }
446
+
447
+ /**
448
+ * Sessions are detached rather than disposed: the server ends every session
449
+ * on a connection it sees close, so ending each one first sends requests
450
+ * over a connection this call is about to dispose.
451
+ */
452
+ override dispose(): void {
453
+ for (const session of [...this.sessions]) {
454
+ session.detach();
455
+ }
456
+ // For a factory's session whose `detach` does not fire.
457
+ this.sessions.clear();
458
+ this.watches.clear();
459
+ this.createSessionEmitter.dispose();
460
+ this.reconnectEmitter.dispose();
461
+ this.dirtyChangedEmitter.dispose();
462
+ this.documentUpdatedEmitter.dispose();
463
+ super.dispose();
464
+ }
465
+ }
466
+
467
+ /**
468
+ * A {@link DataConnection} that brings its own {@link DataEvents}, so a host
469
+ * with several interested parties does not have to supply one.
470
+ *
471
+ * **The client slot holds exactly one object, and that is why this exists.**
472
+ * `createRpcProxy` binds a single `localTarget`, and underneath a method name
473
+ * maps to one handler — a second registration replaces the first silently. So a
474
+ * properties panel and a tree cannot both be the client; one fan-out sits in the
475
+ * slot and both subscribe to it.
476
+ *
477
+ * Use {@link DataConnection} directly instead when the client is yours: an
478
+ * adopter service that implements the protocol plus its own methods, a single
479
+ * consumer that IS the client, or a request/response-only client that binds
480
+ * nothing.
481
+ */
482
+ export class DataConnectionWithEvents<
483
+ TTransfer extends TransferElement,
484
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
485
+ > extends DataConnection<TTransfer, TServer, DataEvents<TTransfer, DiagnosticOf<TServer>, ProjectOf<TServer>>> {
486
+ /** Server pushes, fanned out to as many local listeners as the host has. */
487
+ readonly events: DataEvents<TTransfer, DiagnosticOf<TServer>, ProjectOf<TServer>>;
488
+
489
+ constructor(port: DataPort, options?: DataConnectionOptions<TTransfer, TServer>) {
490
+ // Built as a local because `this` is unavailable before `super`, then
491
+ // read back onto the field.
492
+ const events = new DataEvents<TTransfer, DiagnosticOf<TServer>, ProjectOf<TServer>>();
493
+ super(port, events, options);
494
+ this.events = events;
495
+ }
496
+
497
+ /** Disposes the fan-out it created, which no caller else holds. */
498
+ override dispose(): void {
499
+ super.dispose();
500
+ this.events.dispose();
501
+ }
502
+ }
@@ -8,7 +8,15 @@
8
8
  ********************************************************************************/
9
9
 
10
10
  import { Emitter, type Event } from 'vscode-jsonrpc';
11
- import type { DataClientProtocol, ProjectsChangedEvent, TransferDocumentSavedEvent, TransferDocumentUpdatedEvent } from '../data';
11
+ import type {
12
+ DataClientProtocol,
13
+ ProjectsChangedEvent,
14
+ TransferDocumentDeletedEvent,
15
+ TransferDocumentDirtyChangedEvent,
16
+ TransferDocumentSavedEvent,
17
+ TransferDocumentsBuiltEvent,
18
+ TransferDocumentUpdatedEvent
19
+ } from '../data';
12
20
  import type { Project } from '../project';
13
21
  import type { TransferDiagnostic } from '../transfer-diagnostic';
14
22
  import type { TransferElement } from '../transfer-element';
@@ -40,12 +48,21 @@ export class DataEvents<
40
48
  > implements DataClientProtocol<TTransfer, TDiagnostic, TProject> {
41
49
  protected readonly documentUpdatedEmitter = new Emitter<TransferDocumentUpdatedEvent<TTransfer, TDiagnostic>>();
42
50
  protected readonly documentSavedEmitter = new Emitter<TransferDocumentSavedEvent<TTransfer, TDiagnostic>>();
51
+ protected readonly documentDirtyChangedEmitter = new Emitter<TransferDocumentDirtyChangedEvent>();
52
+ protected readonly documentDeletedEmitter = new Emitter<TransferDocumentDeletedEvent>();
53
+ protected readonly documentsBuiltEmitter = new Emitter<TransferDocumentsBuiltEvent>();
43
54
  protected readonly projectsChangedEmitter = new Emitter<ProjectsChangedEvent<TProject>>();
44
55
 
45
56
  /** A build-phase event for a watched document. Carries the originating `sourceClientId`. */
46
57
  readonly onDidUpdateDocument: Event<TransferDocumentUpdatedEvent<TTransfer, TDiagnostic>> = this.documentUpdatedEmitter.event;
47
58
  /** A watched document was persisted to disk. */
48
59
  readonly onDidSaveDocument: Event<TransferDocumentSavedEvent<TTransfer, TDiagnostic>> = this.documentSavedEmitter.event;
60
+ /** A watched document's text started or stopped differing from its file. */
61
+ readonly onDidChangeDocumentDirty: Event<TransferDocumentDirtyChangedEvent> = this.documentDirtyChangedEmitter.event;
62
+ /** A document's backing file was removed, watched or not. Any watch survives. */
63
+ readonly onDidDeleteDocument: Event<TransferDocumentDeletedEvent> = this.documentDeletedEmitter.event;
64
+ /** Documents built that nobody watches — re-read anything derived from them. */
65
+ readonly onDidBuildDocuments: Event<TransferDocumentsBuiltEvent> = this.documentsBuiltEmitter.event;
49
66
  /** The project set changed. */
50
67
  readonly onDidChangeProjects: Event<ProjectsChangedEvent<TProject>> = this.projectsChangedEmitter.event;
51
68
 
@@ -59,6 +76,18 @@ export class DataEvents<
59
76
  this.documentSavedEmitter.fire(event);
60
77
  }
61
78
 
79
+ onDocumentDirtyChanged(event: TransferDocumentDirtyChangedEvent): void {
80
+ this.documentDirtyChangedEmitter.fire(event);
81
+ }
82
+
83
+ onDocumentDeleted(event: TransferDocumentDeletedEvent): void {
84
+ this.documentDeletedEmitter.fire(event);
85
+ }
86
+
87
+ onDocumentsBuilt(event: TransferDocumentsBuiltEvent): void {
88
+ this.documentsBuiltEmitter.fire(event);
89
+ }
90
+
62
91
  onProjectsChanged(event: ProjectsChangedEvent<TProject>): void {
63
92
  this.projectsChangedEmitter.fire(event);
64
93
  }
@@ -66,6 +95,9 @@ export class DataEvents<
66
95
  dispose(): void {
67
96
  this.documentUpdatedEmitter.dispose();
68
97
  this.documentSavedEmitter.dispose();
98
+ this.documentDirtyChangedEmitter.dispose();
99
+ this.documentDeletedEmitter.dispose();
100
+ this.documentsBuiltEmitter.dispose();
69
101
  this.projectsChangedEmitter.dispose();
70
102
  }
71
103
  }
@@ -8,15 +8,21 @@
8
8
  ********************************************************************************/
9
9
 
10
10
  import type { Event, MessageConnection } from 'vscode-jsonrpc';
11
+ import type { Logger } from '../logger';
12
+ import type { ResolvedMessage } from '../messages/primitives';
13
+ import type { RpcConnectionLifecycle } from './rpc-connection';
11
14
 
12
15
  /**
13
16
  * The one thing a host has to supply for the data head: a live JSON-RPC
14
- * connection to the data server, plus the identity and failure sink that go
15
- * with it.
17
+ * connection to the data server, plus the failure sink that goes with it.
16
18
  *
17
- * "Port" in the hexagonal sense — the host implements it, `DataSession`
19
+ * "Port" in the hexagonal sense — the host implements it, `DataConnection`
18
20
  * consumes it, and nothing on either side of the boundary imports the other.
19
21
  *
22
+ * Carries no identity. A `clientId` names a participant, and one transport
23
+ * serves as many as the host has; binding an identity here is what makes two
24
+ * of them share one, so it lives on `DataSession` instead.
25
+ *
20
26
  * **This deliberately does NOT wrap the protocol methods.** `createRpcProxy`
21
27
  * already takes a promise of a connection and produces the whole typed
22
28
  * `DataServerProtocol` surface, so wrapping it would re-derive the framework's
@@ -24,7 +30,7 @@ import type { Event, MessageConnection } from 'vscode-jsonrpc';
24
30
  * method allowlists, which cannot drift. Everything a form or a tree actually
25
31
  * does — the wire contract, the open/watch/update/close sequence, `baseVersion`
26
32
  * conflict handling, echo filtering by `sourceClientId` — is host-invariant and
27
- * lives above this interface. What varies between hosts is exactly the four
33
+ * lives above this interface. What varies between hosts is exactly the
28
34
  * members below.
29
35
  *
30
36
  * **Why the transport hop and not merely the protocol.** In a Theia frontend
@@ -45,22 +51,6 @@ import type { Event, MessageConnection } from 'vscode-jsonrpc';
45
51
  * calls on the promise but never calls `listen` itself.
46
52
  */
47
53
  export interface DataPort {
48
- /**
49
- * Stable identity of this client on the data server, passed as `clientId`
50
- * on every document request.
51
- *
52
- * It has to be stable for the session because it is the echo key: an
53
- * inbound `onDocumentUpdated` carries the originating mutation's
54
- * `clientId` as `sourceClientId`, and a client that cannot recognise its
55
- * own echo treats its own write as a concurrent third-party one. It also
56
- * has to be distinct per client, since it keys the server's per-
57
- * `(uri, clientId)` watch bucket.
58
- *
59
- * Avoid the three values the framework itself uses as sentinels —
60
- * `'language-client'`, `'unknown'` and `'revert-on-close'`.
61
- */
62
- readonly clientId: string;
63
-
64
54
  /**
65
55
  * Open the transport and hand back a listening `MessageConnection`.
66
56
  *
@@ -77,10 +67,19 @@ export interface DataPort {
77
67
  *
78
68
  * It exists because the alternative is worse in both directions: this tier
79
69
  * cannot import a host's UI, and swallowing the error makes a dead
80
- * connection look like an empty model. `context` names what was being
81
- * attempted, not where in the code it happened.
70
+ * connection look like an empty model.
71
+ *
72
+ * `reported` is a complete sentence plus the identity needed to render it in
73
+ * another language. It carries a value rather than using a protocol field
74
+ * because this tier does not know whether a process hop intervenes — in a
75
+ * webview host the render happens across one — and a `ResolvedMessage` is
76
+ * structured-clone safe either way. Render it with `renderFrameworkMessage`;
77
+ * passing no translation map yields the English.
82
78
  */
83
- reportError(error: unknown, context: string): void;
79
+ reportError(error: unknown, reported: ResolvedMessage): void;
80
+
81
+ /** Where a connection over this port logs what it does on its own. Without one it logs nothing. */
82
+ readonly logger?: Logger;
84
83
 
85
84
  /**
86
85
  * Fires when the host tears the transport down and the current connection
@@ -96,4 +95,11 @@ export interface DataPort {
96
95
  * `Disposable` on the *wire* would not be.
97
96
  */
98
97
  readonly onDispose: Event<void>;
98
+
99
+ /**
100
+ * Called for each connection generation, beside the lifecycle the
101
+ * connection's options pass, so a host reporting its connections itself
102
+ * does so without every connection built over it passing this on.
103
+ */
104
+ readonly connectionLifecycle?: RpcConnectionLifecycle;
99
105
  }