@hydranium/protocol 1.0.0-next.35 → 1.0.0-next.350

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 (285) hide show
  1. package/README.md +44 -83
  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 +302 -0
  7. package/lib/client/data-connection.d.ts.map +1 -0
  8. package/lib/client/data-connection.js +533 -0
  9. package/lib/client/data-connection.js.map +1 -0
  10. package/lib/client/data-events.d.ts +17 -1
  11. package/lib/client/data-events.d.ts.map +1 -1
  12. package/lib/client/data-events.js +25 -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 +684 -89
  17. package/lib/client/data-session.d.ts.map +1 -1
  18. package/lib/client/data-session.js +1148 -115
  19. package/lib/client/data-session.js.map +1 -1
  20. package/lib/client/index.d.ts +15 -9
  21. package/lib/client/index.d.ts.map +1 -1
  22. package/lib/client/index.js +15 -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/worker-handshake.d.ts +86 -0
  36. package/lib/client/worker-handshake.d.ts.map +1 -0
  37. package/lib/client/worker-handshake.js +51 -0
  38. package/lib/client/worker-handshake.js.map +1 -0
  39. package/lib/client-ids.d.ts +45 -0
  40. package/lib/client-ids.d.ts.map +1 -0
  41. package/lib/client-ids.js +48 -0
  42. package/lib/client-ids.js.map +1 -0
  43. package/lib/clock.d.ts +50 -10
  44. package/lib/clock.d.ts.map +1 -1
  45. package/lib/clock.js +36 -1
  46. package/lib/clock.js.map +1 -1
  47. package/lib/console-logger.d.ts +23 -0
  48. package/lib/console-logger.d.ts.map +1 -0
  49. package/lib/console-logger.js +39 -0
  50. package/lib/console-logger.js.map +1 -0
  51. package/lib/data/data-protocol-methods.d.ts +4 -4
  52. package/lib/data/data-protocol-methods.d.ts.map +1 -1
  53. package/lib/data/data-protocol-methods.js +13 -1
  54. package/lib/data/data-protocol-methods.js.map +1 -1
  55. package/lib/data/data-server-protocol.d.ts +170 -48
  56. package/lib/data/data-server-protocol.d.ts.map +1 -1
  57. package/lib/data/events.d.ts +137 -21
  58. package/lib/data/events.d.ts.map +1 -1
  59. package/lib/data/requests.d.ts +71 -11
  60. package/lib/data/requests.d.ts.map +1 -1
  61. package/lib/debouncer.d.ts +3 -3
  62. package/lib/debouncer.d.ts.map +1 -1
  63. package/lib/debouncer.js +6 -9
  64. package/lib/debouncer.js.map +1 -1
  65. package/lib/errors.d.ts +183 -30
  66. package/lib/errors.d.ts.map +1 -1
  67. package/lib/errors.js +268 -32
  68. package/lib/errors.js.map +1 -1
  69. package/lib/glsp-edits-settled-actions.d.ts +52 -0
  70. package/lib/glsp-edits-settled-actions.d.ts.map +1 -0
  71. package/lib/glsp-edits-settled-actions.js +28 -0
  72. package/lib/glsp-edits-settled-actions.js.map +1 -0
  73. package/lib/glsp-request-model-args.d.ts +16 -0
  74. package/lib/glsp-request-model-args.d.ts.map +1 -0
  75. package/lib/glsp-request-model-args.js +19 -0
  76. package/lib/glsp-request-model-args.js.map +1 -0
  77. package/lib/glsp-save-model-actions.d.ts +50 -0
  78. package/lib/glsp-save-model-actions.d.ts.map +1 -0
  79. package/lib/glsp-save-model-actions.js +28 -0
  80. package/lib/glsp-save-model-actions.js.map +1 -0
  81. package/lib/index.d.ts +10 -0
  82. package/lib/index.d.ts.map +1 -1
  83. package/lib/index.js +10 -0
  84. package/lib/index.js.map +1 -1
  85. package/lib/latency-collector.d.ts +8 -4
  86. package/lib/latency-collector.d.ts.map +1 -1
  87. package/lib/latency-collector.js.map +1 -1
  88. package/lib/logger.d.ts +38 -7
  89. package/lib/logger.d.ts.map +1 -1
  90. package/lib/logger.js +42 -4
  91. package/lib/logger.js.map +1 -1
  92. package/lib/messages/index.d.ts +4 -2
  93. package/lib/messages/index.d.ts.map +1 -1
  94. package/lib/messages/index.js +15 -4
  95. package/lib/messages/index.js.map +1 -1
  96. package/lib/messages/primitives.d.ts +59 -4
  97. package/lib/messages/primitives.d.ts.map +1 -1
  98. package/lib/messages/primitives.js +97 -4
  99. package/lib/messages/primitives.js.map +1 -1
  100. package/lib/model-server.d.ts +60 -13
  101. package/lib/model-server.d.ts.map +1 -1
  102. package/lib/model-server.js +4 -2
  103. package/lib/model-server.js.map +1 -1
  104. package/lib/model-service/base-version.d.ts +67 -0
  105. package/lib/model-service/base-version.d.ts.map +1 -0
  106. package/lib/model-service/base-version.js +44 -0
  107. package/lib/model-service/base-version.js.map +1 -0
  108. package/lib/model-service/index.d.ts +1 -1
  109. package/lib/model-service/index.d.ts.map +1 -1
  110. package/lib/model-service/index.js +4 -5
  111. package/lib/model-service/index.js.map +1 -1
  112. package/lib/model-service/reference-candidate.d.ts +5 -3
  113. package/lib/model-service/reference-candidate.d.ts.map +1 -1
  114. package/lib/node/index.d.ts +10 -0
  115. package/lib/node/index.d.ts.map +1 -0
  116. package/lib/node/index.js +29 -0
  117. package/lib/node/index.js.map +1 -0
  118. package/lib/node/process-memory.d.ts +66 -0
  119. package/lib/node/process-memory.d.ts.map +1 -0
  120. package/lib/node/process-memory.js +291 -0
  121. package/lib/node/process-memory.js.map +1 -0
  122. package/lib/noop-logger.d.ts.map +1 -1
  123. package/lib/noop-logger.js.map +1 -1
  124. package/lib/observable-value.js.map +1 -1
  125. package/lib/patch-merge.d.ts +63 -35
  126. package/lib/patch-merge.d.ts.map +1 -1
  127. package/lib/patch-merge.js +171 -25
  128. package/lib/patch-merge.js.map +1 -1
  129. package/lib/pending-work-tracker.d.ts +29 -0
  130. package/lib/pending-work-tracker.d.ts.map +1 -0
  131. package/lib/pending-work-tracker.js +46 -0
  132. package/lib/pending-work-tracker.js.map +1 -0
  133. package/lib/profile-session.d.ts +8 -4
  134. package/lib/profile-session.d.ts.map +1 -1
  135. package/lib/profile-session.js.map +1 -1
  136. package/lib/project.d.ts +4 -1
  137. package/lib/project.d.ts.map +1 -1
  138. package/lib/project.js.map +1 -1
  139. package/lib/random-uuid.d.ts +14 -0
  140. package/lib/random-uuid.d.ts.map +1 -0
  141. package/lib/random-uuid.js +24 -0
  142. package/lib/random-uuid.js.map +1 -0
  143. package/lib/reconcile-write.d.ts +67 -0
  144. package/lib/reconcile-write.d.ts.map +1 -0
  145. package/lib/reconcile-write.js +69 -0
  146. package/lib/reconcile-write.js.map +1 -0
  147. package/lib/rpc/bind-rpc-methods.d.ts +6 -2
  148. package/lib/rpc/bind-rpc-methods.d.ts.map +1 -1
  149. package/lib/rpc/bind-rpc-methods.js +17 -7
  150. package/lib/rpc/bind-rpc-methods.js.map +1 -1
  151. package/lib/rpc/create-rpc-proxy.d.ts +3 -0
  152. package/lib/rpc/create-rpc-proxy.d.ts.map +1 -1
  153. package/lib/rpc/create-rpc-proxy.js +6 -1
  154. package/lib/rpc/create-rpc-proxy.js.map +1 -1
  155. package/lib/rpc/index.d.ts +1 -0
  156. package/lib/rpc/index.d.ts.map +1 -1
  157. package/lib/rpc/index.js +1 -0
  158. package/lib/rpc/index.js.map +1 -1
  159. package/lib/rpc/send-by-method-name.d.ts +76 -0
  160. package/lib/rpc/send-by-method-name.d.ts.map +1 -0
  161. package/lib/rpc/send-by-method-name.js +120 -0
  162. package/lib/rpc/send-by-method-name.js.map +1 -0
  163. package/lib/rpc/wire-prefix.js.map +1 -1
  164. package/lib/save-text-document.d.ts +40 -0
  165. package/lib/save-text-document.d.ts.map +1 -0
  166. package/lib/save-text-document.js +34 -0
  167. package/lib/save-text-document.js.map +1 -0
  168. package/lib/testing/catalogue-audit.d.ts +1 -1
  169. package/lib/testing/catalogue-audit.js +1 -1
  170. package/lib/testing/catalogue-audit.js.map +1 -1
  171. package/lib/testing/data-doubles.d.ts +41 -12
  172. package/lib/testing/data-doubles.d.ts.map +1 -1
  173. package/lib/testing/data-doubles.js +56 -8
  174. package/lib/testing/data-doubles.js.map +1 -1
  175. package/lib/testing/fake-clock.d.ts +17 -2
  176. package/lib/testing/fake-clock.d.ts.map +1 -1
  177. package/lib/testing/fake-clock.js +61 -46
  178. package/lib/testing/fake-clock.js.map +1 -1
  179. package/lib/testing/index.d.ts +1 -0
  180. package/lib/testing/index.d.ts.map +1 -1
  181. package/lib/testing/index.js +4 -3
  182. package/lib/testing/index.js.map +1 -1
  183. package/lib/testing/node/duplex-connection.d.ts.map +1 -1
  184. package/lib/testing/node/duplex-connection.js +3 -2
  185. package/lib/testing/node/duplex-connection.js.map +1 -1
  186. package/lib/testing/node/duplex-stream.js.map +1 -1
  187. package/lib/testing/node/index.d.ts +1 -0
  188. package/lib/testing/node/index.d.ts.map +1 -1
  189. package/lib/testing/node/index.js +2 -2
  190. package/lib/testing/node/index.js.map +1 -1
  191. package/lib/testing/node/message-port-pair.d.ts +25 -0
  192. package/lib/testing/node/message-port-pair.d.ts.map +1 -0
  193. package/lib/testing/node/message-port-pair.js +26 -0
  194. package/lib/testing/node/message-port-pair.js.map +1 -0
  195. package/lib/testing/transfer-node-builder.d.ts +81 -0
  196. package/lib/testing/transfer-node-builder.d.ts.map +1 -0
  197. package/lib/testing/transfer-node-builder.js +47 -0
  198. package/lib/testing/transfer-node-builder.js.map +1 -0
  199. package/lib/testing/wait-for.d.ts +9 -3
  200. package/lib/testing/wait-for.d.ts.map +1 -1
  201. package/lib/testing/wait-for.js +57 -11
  202. package/lib/testing/wait-for.js.map +1 -1
  203. package/lib/tracer.d.ts.map +1 -1
  204. package/lib/tracer.js +5 -9
  205. package/lib/tracer.js.map +1 -1
  206. package/lib/transfer-diagnostic.js.map +1 -1
  207. package/lib/transfer-document.d.ts +95 -32
  208. package/lib/transfer-document.d.ts.map +1 -1
  209. package/lib/transfer-document.js +17 -9
  210. package/lib/transfer-document.js.map +1 -1
  211. package/lib/transfer-element.d.ts +4 -4
  212. package/lib/types.d.ts +32 -0
  213. package/lib/types.d.ts.map +1 -0
  214. package/lib/{model-service/args.js → types.js} +2 -2
  215. package/lib/types.js.map +1 -0
  216. package/lib/uri.d.ts.map +1 -1
  217. package/lib/uri.js.map +1 -1
  218. package/lib/util.d.ts +8 -2
  219. package/lib/util.d.ts.map +1 -1
  220. package/lib/util.js +32 -4
  221. package/lib/util.js.map +1 -1
  222. package/package.json +24 -40
  223. package/src/abstract-logger.ts +8 -0
  224. package/src/client/data-connection.ts +653 -0
  225. package/src/client/data-events.ts +37 -1
  226. package/src/client/data-port.ts +36 -25
  227. package/src/client/data-session.ts +1469 -137
  228. package/src/client/index.ts +15 -9
  229. package/src/client/message-relay.ts +4 -4
  230. package/src/client/post-message-transport.ts +219 -4
  231. package/src/client/rpc-connection.ts +281 -0
  232. package/src/client/worker-handshake.ts +113 -0
  233. package/src/client-ids.ts +49 -0
  234. package/src/clock.ts +68 -10
  235. package/src/console-logger.ts +39 -0
  236. package/src/data/data-protocol-methods.ts +14 -4
  237. package/src/data/data-server-protocol.ts +197 -48
  238. package/src/data/events.ts +143 -21
  239. package/src/data/requests.ts +77 -11
  240. package/src/debouncer.ts +7 -10
  241. package/src/errors.ts +326 -40
  242. package/src/glsp-edits-settled-actions.ts +60 -0
  243. package/src/glsp-request-model-args.ts +16 -0
  244. package/src/glsp-save-model-actions.ts +59 -0
  245. package/src/index.ts +10 -0
  246. package/src/latency-collector.ts +8 -3
  247. package/src/logger.ts +44 -8
  248. package/src/messages/index.ts +4 -2
  249. package/src/messages/primitives.ts +129 -5
  250. package/src/model-server.ts +64 -19
  251. package/src/model-service/base-version.ts +75 -0
  252. package/src/model-service/index.ts +4 -5
  253. package/src/model-service/reference-candidate.ts +5 -3
  254. package/src/node/index.ts +14 -0
  255. package/src/node/process-memory.ts +299 -0
  256. package/src/patch-merge.ts +230 -45
  257. package/src/pending-work-tracker.ts +46 -0
  258. package/src/profile-session.ts +9 -4
  259. package/src/project.ts +4 -1
  260. package/src/random-uuid.ts +21 -0
  261. package/src/reconcile-write.ts +128 -0
  262. package/src/rpc/README.md +6 -6
  263. package/src/rpc/bind-rpc-methods.ts +18 -8
  264. package/src/rpc/create-rpc-proxy.ts +6 -1
  265. package/src/rpc/index.ts +1 -0
  266. package/src/rpc/send-by-method-name.ts +140 -0
  267. package/src/save-text-document.ts +39 -0
  268. package/src/testing/catalogue-audit.ts +1 -1
  269. package/src/testing/data-doubles.ts +141 -19
  270. package/src/testing/fake-clock.ts +76 -48
  271. package/src/testing/index.ts +4 -3
  272. package/src/testing/node/duplex-connection.ts +3 -2
  273. package/src/testing/node/index.ts +2 -2
  274. package/src/testing/node/message-port-pair.ts +40 -0
  275. package/src/testing/transfer-node-builder.ts +107 -0
  276. package/src/testing/wait-for.ts +61 -13
  277. package/src/tracer.ts +5 -9
  278. package/src/transfer-document.ts +115 -34
  279. package/src/transfer-element.ts +4 -4
  280. package/src/types.ts +30 -0
  281. package/src/util.ts +33 -6
  282. package/lib/model-service/args.d.ts +0 -64
  283. package/lib/model-service/args.d.ts.map +0 -1
  284. package/lib/model-service/args.js.map +0 -1
  285. package/src/model-service/args.ts +0 -67
@@ -0,0 +1,653 @@
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, UNKNOWN_CLIENT_ID } 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 TransferDocumentDeletedEvent,
20
+ type TransferDocumentDirtyChangedEvent,
21
+ type TransferDocumentUpdatedEvent
22
+ } from '../data';
23
+ import type { TransferWatchedDocument } from '../transfer-document';
24
+ import { DuplicateClientIdError, ReservedClientIdError } from '../errors';
25
+ import type { Logger } from '../logger';
26
+ import { defineMessage, describeError, describeErrorWithStack, resolve } from '../messages/primitives';
27
+ import { NoopLogger } from '../noop-logger';
28
+ import { randomUuid } from '../random-uuid';
29
+ import type { TransferElement } from '../transfer-element';
30
+ import { DataEvents } from './data-events';
31
+ import type { DataPort } from './data-port';
32
+ import { DataSession, type DataSessionFactory } from './data-session';
33
+ import { RpcConnection, type RpcConnectionGeneration, type RpcConnectionLifecycle } from './rpc-connection';
34
+
35
+ /**
36
+ * A watch {@link DataConnection.watchDocument} keeps could not be sent again to
37
+ * a connection that became ready after a drop; the next one sends it again.
38
+ */
39
+ export const DATA_CONNECTION_WATCH_RESTORE_FAILED = defineMessage(
40
+ 'hydranium/protocol/data-connection-watch-restore-failed',
41
+ 'Could not watch {uri} again after reconnecting to the data server: {detail}'
42
+ );
43
+
44
+ /**
45
+ * A session's restore threw when its connection came back; the connection
46
+ * went on restoring the others.
47
+ */
48
+ export const DATA_CONNECTION_SESSION_RESTORE_FAILED = defineMessage(
49
+ 'hydranium/protocol/data-connection-session-restore-failed',
50
+ 'Could not restore a session after reconnecting to the data server: {detail}'
51
+ );
52
+
53
+ /**
54
+ * A watch {@link DataConnection.watchDocument} keeps, with what the client last
55
+ * heard of its document: a reconnect whose watch answers that no document
56
+ * exists tells the client of a deletion only where it had heard one did.
57
+ */
58
+ export interface DataConnectionWatch {
59
+ /** The URI as the caller named it, which the watch is sent under. */
60
+ readonly uri: string;
61
+ /** The key a watch of it last answered with, which events name; absent until one answered. */
62
+ readonly serverUri?: string;
63
+ /** Whether the client last heard that the document exists. */
64
+ readonly exists: boolean;
65
+ }
66
+
67
+ /** What an event heard while a watch was in flight said of its document, and the event's position. */
68
+ export interface DataConnectionHeardEvent {
69
+ readonly exists: boolean;
70
+ readonly sequence: number;
71
+ }
72
+
73
+ /** Whether the document exists, by the newer of a watch's answer and an event heard while the watch was in flight. */
74
+ function existsAfter(heard: DataConnectionHeardEvent | undefined, answer: TransferWatchedDocument): boolean {
75
+ return heard !== undefined && heard.sequence > answer.sequence ? heard.exists : answer.exists;
76
+ }
77
+
78
+ /** Options for {@link DataConnection}. */
79
+ export interface DataConnectionOptions<
80
+ TTransfer extends TransferElement = TransferElement,
81
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
82
+ > extends RpcConnectionLifecycle {
83
+ /**
84
+ * Wire namespace the server is addressed under. Defaults to the
85
+ * framework's {@link DATA_SERVER_WIRE_PREFIX}, which is what an unmodified
86
+ * `DataServer` binds. Override only alongside the server's own
87
+ * `methodNamespace` option — a mismatch turns every request into
88
+ * "Unhandled method" rather than failing at wire-up.
89
+ */
90
+ readonly methodNamespace?: string;
91
+ /** Builds the sessions `createSession` hands out. Defaults to a plain {@link DataSession}. */
92
+ readonly sessionFactory?: DataSessionFactory<TTransfer, TServer>;
93
+ }
94
+
95
+ /** {@link DataConnectionOptions} for a client that does not speak {@link DataClientProtocol}. */
96
+ export interface DataConnectionOptionsWithMethods<
97
+ TClient extends object,
98
+ TTransfer extends TransferElement = TransferElement,
99
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
100
+ > extends DataConnectionOptions<TTransfer, TServer> {
101
+ /**
102
+ * Method names of the client to bind as inbound handlers. Declare it
103
+ * `as const satisfies ReadonlyArray<keyof YourClient & string>` so the list
104
+ * cannot drift from the interface.
105
+ */
106
+ readonly clientMethods: readonly (keyof TClient & string)[];
107
+ }
108
+
109
+ /**
110
+ * Trailing constructor arguments, required only when the client cannot take
111
+ * the framework's default method list.
112
+ *
113
+ * `bindRpcMethods` throws for a name the target does not implement, so a
114
+ * request/response-only client binding the default list fails at wire-up. The
115
+ * conditional turns that into a compile error.
116
+ */
117
+ export type DataConnectionArgs<
118
+ TTransfer extends TransferElement,
119
+ TClient extends object,
120
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
121
+ > =
122
+ TClient extends DataClientProtocol<TTransfer>
123
+ ? [options?: DataConnectionOptions<TTransfer, TServer> & Partial<DataConnectionOptionsWithMethods<TClient, TTransfer, TServer>>]
124
+ : [options: DataConnectionOptionsWithMethods<TClient, TTransfer, TServer>];
125
+
126
+ /**
127
+ * A {@link RpcConnection} to the data head, carrying as many participants as
128
+ * the host has interested parties.
129
+ *
130
+ * Document operations live on the participants rather than here: they carry a
131
+ * `clientId`, which identifies a participant rather than a wire, and the server
132
+ * keys its opens and watches per `(uri, clientId)`. Two parties sharing one
133
+ * identity cannot tell each other's writes from their own echoes.
134
+ * {@link DataConnection.watchDocument} is the exception: it acts as no
135
+ * participant, under an id no session holds, and opens or writes nothing.
136
+ *
137
+ * Generic over the transfer root so this file names no grammar. An adopter
138
+ * binds the concrete root (or the union of them, for a multi-grammar head) at
139
+ * its own edge.
140
+ */
141
+ export class DataConnection<
142
+ TTransfer extends TransferElement,
143
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>,
144
+ TClient extends object = DataClientProtocol<TTransfer>
145
+ > extends RpcConnection<TServer, TClient> {
146
+ protected readonly sessions = new Set<DataSession<TTransfer, TServer>>();
147
+ protected readonly sessionFactory: DataSessionFactory<TTransfer, TServer>;
148
+ protected readonly createSessionEmitter = new Emitter<DataSession<TTransfer, TServer>>();
149
+ /**
150
+ * Fires with each session {@link createSession} starts, before it returns,
151
+ * so a listener sees every session a caller can. A session started before
152
+ * the listener subscribed is in {@link liveSessions}.
153
+ */
154
+ readonly onDidCreateSession: Event<DataSession<TTransfer, TServer>> = this.createSessionEmitter.event;
155
+ /**
156
+ * Per URI, the `dirty` the client was last told, whether a session of this
157
+ * connection has it open or a watch follows it. A session's open or close
158
+ * of the URI forgets it; disposing a watch does not, since a watch knows
159
+ * only the caller's spelling of the URI, not the server's key. A
160
+ * session's restore and a watch sent again after a reconnect tell the
161
+ * client their answer where it differs, a forgotten URI included; see
162
+ * {@link restoreDirty}.
163
+ */
164
+ protected readonly dirtyStates = new Map<string, boolean>();
165
+ /** Backs each session's {@link DataSessionHost.onDidChangeDirty}. */
166
+ protected readonly dirtyChangedEmitter = new Emitter<TransferDocumentDirtyChangedEvent>();
167
+ /** Backs each session's {@link DataSessionHost.onDidUpdateDocument}. */
168
+ protected readonly documentUpdatedEmitter = new Emitter<TransferDocumentUpdatedEvent<TTransfer, DiagnosticOf<TServer>>>();
169
+ /** Backs each session's {@link DataSessionHost.onDidDeleteDocument}. */
170
+ protected readonly documentDeletedEmitter = new Emitter<TransferDocumentDeletedEvent>();
171
+ /**
172
+ * Per id {@link watchDocument} watches under, the watch, which
173
+ * {@link generationReady} sends again to every later generation until the
174
+ * watch's handle is disposed.
175
+ */
176
+ protected readonly watches = new Map<string, DataConnectionWatch>();
177
+ /**
178
+ * Per id, the URI of a watch whose handle was disposed with no ready
179
+ * generation to unwatch on. {@link generationReady} sends the unwatch to the
180
+ * next ready one: a generation that failed its readiness check after its
181
+ * watches were sent leaves them on a connection the port may hand back.
182
+ */
183
+ protected readonly pendingUnwatches = new Map<string, string>();
184
+ /**
185
+ * The keys of the deletions the current generation's reconnect told the
186
+ * client of, so a URI several sessions and watches follow is told once.
187
+ */
188
+ protected readonly toldDeletions = new Set<string>();
189
+ /**
190
+ * One map per watch in flight, keyed by document, of what the last event
191
+ * heard since the watch was sent said of its existence, and the event's
192
+ * position. The server may take the answer before an event goes out, so
193
+ * an event heard in flight wins over the answer where its position is
194
+ * past the one the answer carries.
195
+ */
196
+ protected readonly heardInFlight = new Set<Map<string, DataConnectionHeardEvent>>();
197
+ /** The port's logger, or one that logs nothing. */
198
+ protected readonly logger: Logger;
199
+ /** Backs {@link onDidReconnect}. */
200
+ protected readonly reconnectEmitter = new Emitter<void>();
201
+ /**
202
+ * Fires on every reconnect: once a connection becomes ready after an
203
+ * earlier one was, and its watches have been sent. The server sends no
204
+ * event for a change made while the connection was down, so a watcher reads
205
+ * its document again on this; a read it sends now reaches the server after
206
+ * its watch.
207
+ */
208
+ readonly onDidReconnect: Event<void> = this.reconnectEmitter.event;
209
+ /** Whether a generation was ready before, which makes the next one a reconnect. */
210
+ protected readyBefore = false;
211
+
212
+ constructor(port: DataPort, client: TClient, ...rest: DataConnectionArgs<TTransfer, TClient, TServer>) {
213
+ const [options = {}] = rest as [
214
+ (DataConnectionOptions<TTransfer, TServer> & Partial<DataConnectionOptionsWithMethods<TClient, TTransfer, TServer>>)?
215
+ ];
216
+ super(port, client, {
217
+ methodNamespace: options.methodNamespace ?? DATA_SERVER_WIRE_PREFIX,
218
+ // The default is reachable only where `TClient` satisfies
219
+ // `DataClientProtocol`, which the constructor's conditional enforces;
220
+ // the compiler cannot carry that through to the generic parameter.
221
+ clientMethods: options.clientMethods ?? (DATA_CLIENT_PROTOCOL_METHODS as unknown as readonly (keyof TClient & string)[]),
222
+ lifecycle: options
223
+ });
224
+ this.sessionFactory =
225
+ options.sessionFactory ?? ((clientId, host, label) => new DataSession<TTransfer, TServer>(clientId, host, label));
226
+ this.logger = (port.logger ?? new NoopLogger()).for('DataConnection');
227
+ }
228
+
229
+ /**
230
+ * The sessions of this connection that have not ended, in the order they
231
+ * started. A session is listed until its `onDidDispose` fires, or until
232
+ * {@link dispose} clears the list.
233
+ */
234
+ get liveSessions(): readonly DataSession<TTransfer, TServer>[] {
235
+ return [...this.sessions];
236
+ }
237
+
238
+ /**
239
+ * Start a participant on this connection, registered with the server under a
240
+ * fresh id, `label` plus `#` plus a random UUID, or under `clientId` when
241
+ * given. Pass a `label` naming the participant; without one it is
242
+ * `session`. Synchronous: the registration is sent at once, and the
243
+ * session's calls wait for it. The server refuses an id live anywhere in
244
+ * its process, and every call of that session then rejects with an error
245
+ * `isDuplicateClientIdError` recognises; an id the server reserves beyond
246
+ * {@link FRAMEWORK_CLIENT_IDS}, such as the integrity author, with one
247
+ * `isReservedClientIdError` recognises. Only the code crosses the wire, so
248
+ * test with those guards rather than `instanceof`.
249
+ *
250
+ * Throws a {@link ReservedClientIdError} for an id in
251
+ * {@link FRAMEWORK_CLIENT_IDS} — those are authors the SERVER emits rather
252
+ * than participants, so a session holding one would read the framework's
253
+ * own broadcasts as its own echoes and drop them — and a
254
+ * {@link DuplicateClientIdError} for an id a live session on this
255
+ * connection already holds.
256
+ */
257
+ createSession(label = 'session', clientId?: string): DataSession<TTransfer, TServer> {
258
+ this.assertLive();
259
+ const id = clientId ?? `${label}#${randomUuid()}`;
260
+ if (FRAMEWORK_CLIENT_IDS.includes(id)) {
261
+ throw new ReservedClientIdError(id);
262
+ }
263
+ if ([...this.sessions].some(session => session.clientId === id)) {
264
+ throw new DuplicateClientIdError(id);
265
+ }
266
+ const session = this.sessionFactory(
267
+ id,
268
+ {
269
+ connected: () => this.connected(),
270
+ reportError: (error, reported) => this.reportError(error, reported),
271
+ restoreDirty: event => this.restoreDirty(event),
272
+ // Without it the session reports the unsaved text it loses.
273
+ restoreDeletion: this.hearsDeletions ? event => this.restoreDeletion(event) : undefined,
274
+ forgetDirty: uri => this.dirtyStates.delete(uri),
275
+ onDidChangeDirty: this.dirtyChangedEmitter.event,
276
+ onDidUpdateDocument: this.documentUpdatedEmitter.event,
277
+ onDidDeleteDocument: this.documentDeletedEmitter.event,
278
+ logger: this.logger.for('DataSession').with(id)
279
+ },
280
+ label
281
+ );
282
+ this.sessions.add(session);
283
+ // Subscribed before the session is handed out, so the id is free again
284
+ // on this connection by the time any caller's listener runs.
285
+ session.onDidDispose(() => this.sessions.delete(session));
286
+ // A failure reaches the session's own calls, which wait for the same
287
+ // registration; caught here only so it is not also reported unhandled.
288
+ session.connected().catch(() => undefined);
289
+ this.createSessionEmitter.fire(session);
290
+ return session;
291
+ }
292
+
293
+ /**
294
+ * Follow `uri` without opening it: its update events reach this
295
+ * connection's client once this resolves. An open would hold the document
296
+ * for as long as the caller follows it. The watch runs under an id of its
297
+ * own, `label` plus `#` plus a random UUID, and needs no session: a session
298
+ * closing the document would also end its own watch of it. Every later
299
+ * connection that becomes ready gets the watch again, and tells the client
300
+ * of a deletion while it was down. Disposing the handle unwatches.
301
+ */
302
+ async watchDocument(uri: string, label = 'watch'): Promise<Disposable> {
303
+ const clientId = `${label}#${randomUuid()}`;
304
+ const server = await this.connected();
305
+ // Kept only from here: kept during the wait, a generation that became
306
+ // ready meanwhile would send the watch a second time.
307
+ this.watches.set(clientId, { uri, exists: false });
308
+ const heard = new Map<string, DataConnectionHeardEvent>();
309
+ this.heardInFlight.add(heard);
310
+ let answer: TransferWatchedDocument;
311
+ try {
312
+ answer = await server.watchModelDocument({ uri, clientId });
313
+ } catch (error: unknown) {
314
+ this.watches.delete(clientId);
315
+ throw error;
316
+ } finally {
317
+ this.heardInFlight.delete(heard);
318
+ }
319
+ this.logger.debug(`Watch ${uri} as ${clientId}`);
320
+ this.watches.set(clientId, { uri, serverUri: answer.uri, exists: existsAfter(heard.get(answer.uri), answer) });
321
+ return Disposable.create(() => {
322
+ if (!this.watches.delete(clientId)) {
323
+ return;
324
+ }
325
+ // Without a ready generation the unwatch waits for the next one,
326
+ // rather than opening a connection only for it.
327
+ const unwatchLater = (): void => {
328
+ this.pendingUnwatches.set(clientId, uri);
329
+ };
330
+ const generation = this.generation;
331
+ if (!generation) {
332
+ unwatchLater();
333
+ return;
334
+ }
335
+ (generation.ready ??= this.awaitReady(generation)).then(() => {
336
+ if (this.generation === generation) {
337
+ this.unwatch(generation, clientId, uri);
338
+ } else {
339
+ unwatchLater();
340
+ }
341
+ }, unwatchLater);
342
+ });
343
+ }
344
+
345
+ /**
346
+ * The client, with its `onDocumentDirtyChanged` passing through
347
+ * {@link deliverDirty} first, so {@link dirtyStates} holds what the server
348
+ * told it, and every session hears it through {@link dirtyChangedEmitter};
349
+ * and with its `onDocumentUpdated` and `onDocumentDeleted` heard by every
350
+ * session through {@link documentUpdatedEmitter} and
351
+ * {@link documentDeletedEmitter} first. Every other bound method forwards
352
+ * to the client unchanged, and one the client lacks stays absent, so the
353
+ * binding still refuses it.
354
+ */
355
+ protected override localTarget(): TClient {
356
+ const client = this.client as unknown as Record<string, unknown>;
357
+ const hearsDirty = this.bindsClientMethod('onDocumentDirtyChanged');
358
+ const hearsUpdates = this.bindsClientMethod('onDocumentUpdated');
359
+ const hearsDeletions = this.hearsDeletions;
360
+ if (!hearsDirty && !hearsUpdates && !hearsDeletions) {
361
+ return this.client;
362
+ }
363
+ const target: Record<string, unknown> = {};
364
+ for (const name of this.clientMethods) {
365
+ const method: unknown = client[name];
366
+ if (typeof method === 'function') {
367
+ target[name] = (params: unknown): unknown => (method as (params: unknown) => unknown).call(client, params);
368
+ }
369
+ }
370
+ if (hearsDirty) {
371
+ target.onDocumentDirtyChanged = (event: TransferDocumentDirtyChangedEvent): void => {
372
+ this.dirtyChangedEmitter.fire(event);
373
+ this.deliverDirty(event);
374
+ };
375
+ }
376
+ if (hearsUpdates) {
377
+ const forward = target.onDocumentUpdated as (event: TransferDocumentUpdatedEvent<TTransfer, DiagnosticOf<TServer>>) => void;
378
+ target.onDocumentUpdated = (event: TransferDocumentUpdatedEvent<TTransfer, DiagnosticOf<TServer>>): void => {
379
+ if (event.document.model) {
380
+ this.markWatches(event.document.uri, true, event.sequence);
381
+ }
382
+ this.documentUpdatedEmitter.fire(event);
383
+ forward(event);
384
+ };
385
+ }
386
+ if (hearsDeletions) {
387
+ const forward = target.onDocumentDeleted as (event: TransferDocumentDeletedEvent) => void;
388
+ target.onDocumentDeleted = (event: TransferDocumentDeletedEvent): void => {
389
+ // Held gone, so a reconnect tells the client of it no second time.
390
+ // A server sending no position has its deletion count as sent
391
+ // before any answer.
392
+ this.markWatches(event.uri, false, event.sequence ?? 0);
393
+ this.documentDeletedEmitter.fire(event);
394
+ forward(event);
395
+ };
396
+ }
397
+ return target as unknown as TClient;
398
+ }
399
+
400
+ /**
401
+ * Whether the client binds `onDocumentDeleted`. Without it no deletion
402
+ * reaches the client or the sessions, the server's or one a reconnect
403
+ * found, and a session's restore reports what a gone document took.
404
+ */
405
+ protected get hearsDeletions(): boolean {
406
+ return this.bindsClientMethod('onDocumentDeleted');
407
+ }
408
+
409
+ /** Whether `name` is among the methods bound for the client, and the client implements it. */
410
+ protected bindsClientMethod(name: string): boolean {
411
+ const client = this.client as unknown as Record<string, unknown>;
412
+ return (this.clientMethods as readonly string[]).includes(name) && typeof client[name] === 'function';
413
+ }
414
+
415
+ /**
416
+ * Hand the client a deletion a session's restore or a watch sent again
417
+ * found, which no event brought while the connection was down, unless
418
+ * {@link toldDeletions} says this generation told it already. The sessions
419
+ * do not hear it: each finds what it lost in its own restore.
420
+ */
421
+ protected restoreDeletion(event: TransferDocumentDeletedEvent): void {
422
+ if (this.toldDeletions.has(event.uri)) {
423
+ return;
424
+ }
425
+ this.toldDeletions.add(event.uri);
426
+ const client = this.client as unknown as Pick<DataClientProtocol<TTransfer>, 'onDocumentDeleted'>;
427
+ client.onDocumentDeleted(event);
428
+ }
429
+
430
+ /**
431
+ * Record in every watch whose answer named `uri` whether the document
432
+ * exists, and in {@link heardInFlight} for the watches not answered yet,
433
+ * with the event's position.
434
+ */
435
+ protected markWatches(uri: string, exists: boolean, sequence: number): void {
436
+ this.watches.forEach((watch, clientId) => {
437
+ if (watch.serverUri === uri) {
438
+ this.watches.set(clientId, { ...watch, exists });
439
+ }
440
+ });
441
+ this.heardInFlight.forEach(heard => heard.set(uri, { exists, sequence }));
442
+ }
443
+
444
+ /**
445
+ * Hand a dirty state a restore read to the client, unless it is what
446
+ * {@link dirtyStates} says the client was last told; a URI it holds
447
+ * nothing for counts as different.
448
+ */
449
+ protected restoreDirty(event: TransferDocumentDirtyChangedEvent): void {
450
+ if (this.dirtyStates.get(event.uri) !== (event.text?.dirty ?? false)) {
451
+ this.deliverDirty(event);
452
+ }
453
+ }
454
+
455
+ /** Record `event` in {@link dirtyStates} and hand it to the client. */
456
+ protected deliverDirty(event: TransferDocumentDirtyChangedEvent): void {
457
+ this.dirtyStates.set(event.uri, event.text?.dirty ?? false);
458
+ if (this.bindsClientMethod('onDocumentDirtyChanged')) {
459
+ const client = this.client as unknown as Pick<DataClientProtocol<TTransfer>, 'onDocumentDirtyChanged'>;
460
+ client.onDocumentDirtyChanged(event);
461
+ }
462
+ }
463
+
464
+ /**
465
+ * After the transport dropped, reconnect on the next macrotask for the
466
+ * sessions with documents open, so they re-watch and follow their documents
467
+ * again without waiting for a call of their own, and connect for what
468
+ * {@link watchDocument} watches, which {@link generationReady} places
469
+ * again; a session with nothing open restores on its next call. Nothing is
470
+ * scheduled once this connection is disposed, which drops its generation
471
+ * too.
472
+ */
473
+ protected override dropGeneration(): void {
474
+ const dropped = this.generation !== undefined;
475
+ super.dropGeneration();
476
+ if (dropped && !this.disposed) {
477
+ setTimeout(() => {
478
+ if (!this.disposed) {
479
+ this.reconnectSessions();
480
+ if (this.watches.size > 0) {
481
+ // One generation, not `connected`, which follows a drop to
482
+ // the next: that drop's own timer asks again whether
483
+ // anything is still kept. A failure is reported by the gate.
484
+ const generation = this.currentGeneration();
485
+ (generation.ready ??= this.awaitReady(generation)).catch(() => undefined);
486
+ }
487
+ }
488
+ }, 0);
489
+ }
490
+ }
491
+
492
+ /**
493
+ * Call `reconnect()` on every session, reporting a throw instead of letting
494
+ * one session's restore stop the others and the watches after them, and,
495
+ * inside the readiness gate, fail the whole generation.
496
+ */
497
+ protected reconnectSessions(): void {
498
+ for (const session of this.sessions) {
499
+ try {
500
+ session.reconnect();
501
+ } catch (error: unknown) {
502
+ // Reported, so it reaches the user on a port without a logger;
503
+ // logged too, since only the log names the session.
504
+ this.reportError(error, resolve(DATA_CONNECTION_SESSION_RESTORE_FAILED, { detail: describeError(error) }));
505
+ this.logger.error(`Could not restore session ${session.clientId}: ${describeErrorWithStack(error)}`);
506
+ }
507
+ }
508
+ }
509
+
510
+ /**
511
+ * Restore what the server lost with an earlier generation, whichever
512
+ * request brought this one up: the documents of sessions that have some
513
+ * open, and every watch {@link watchDocument} keeps.
514
+ */
515
+ protected override generationReady(generation: RpcConnectionGeneration<TServer>): void {
516
+ super.generationReady(generation);
517
+ this.toldDeletions.clear();
518
+ this.reconnectSessions();
519
+ this.watches.forEach((watch, clientId) => this.watchAgain(generation, clientId, watch.uri));
520
+ this.pendingUnwatches.forEach((uri, clientId) => this.unwatch(generation, clientId, uri));
521
+ this.pendingUnwatches.clear();
522
+ if (this.readyBefore) {
523
+ this.reconnectEmitter.fire(undefined);
524
+ }
525
+ this.readyBefore = true;
526
+ }
527
+
528
+ /** Take back the watch of `uri` under `clientId` on `generation`; the server ignores one it does not hold. */
529
+ protected unwatch(generation: RpcConnectionGeneration<TServer>, clientId: string, uri: string): void {
530
+ this.logger.debug(`Unwatch ${uri} as ${clientId}`);
531
+ generation.server.unwatchModelDocument({ uri, clientId }).catch(() => undefined);
532
+ }
533
+
534
+ /**
535
+ * Send the watch of `uri` under `clientId` to `generation`, which has just
536
+ * passed its readiness gate. Sent at once rather than after a wait, so no
537
+ * drop can come between choosing the generation and sending. A failure is
538
+ * reported, since no caller waits on it, only while the watch is kept and
539
+ * `generation` is still current: otherwise the next generation sends it
540
+ * again.
541
+ *
542
+ * A document the client last heard exists that the watch's answer says
543
+ * is gone goes to the client as a deletion; once the watch is in place,
544
+ * the document's dirty state is read and goes through
545
+ * {@link restoreDirty}, as a session's restore does. Neither reached
546
+ * anyone while the connection was down.
547
+ */
548
+ protected watchAgain(generation: RpcConnectionGeneration<TServer>, clientId: string, uri: string): void {
549
+ const heard = new Map<string, DataConnectionHeardEvent>();
550
+ this.heardInFlight.add(heard);
551
+ generation.server
552
+ .watchModelDocument({ uri, clientId })
553
+ .finally(() => this.heardInFlight.delete(heard))
554
+ .then(
555
+ answer => {
556
+ const known = this.watches.get(clientId);
557
+ if (!known) {
558
+ return;
559
+ }
560
+ this.logger.debug(`Watch ${uri} again as ${clientId}`);
561
+ const exists = existsAfter(heard.get(answer.uri), answer);
562
+ this.watches.set(clientId, { uri, serverUri: answer.uri, exists });
563
+ if (known.exists && !exists && this.hearsDeletions) {
564
+ try {
565
+ this.restoreDeletion({ uri: answer.uri, sourceClientId: UNKNOWN_CLIENT_ID });
566
+ } catch {
567
+ // The client's listener failed, not the watch, which stays kept.
568
+ }
569
+ }
570
+ generation.server.getModelDocument({ uri }).then(
571
+ current => {
572
+ if (current.text && this.watches.has(clientId)) {
573
+ try {
574
+ this.restoreDirty({ uri: current.uri, text: current.text });
575
+ } catch {
576
+ // The client's listener failed, not the watch, which stays kept.
577
+ }
578
+ }
579
+ },
580
+ () => undefined
581
+ );
582
+ },
583
+ (error: unknown) => {
584
+ if (!this.watches.has(clientId)) {
585
+ return;
586
+ }
587
+ if (this.generation !== generation) {
588
+ this.logger.debug(`Watch of ${uri} as ${clientId} cut short by a lost connection; the next one sends it again`);
589
+ return;
590
+ }
591
+ this.reportError(error, resolve(DATA_CONNECTION_WATCH_RESTORE_FAILED, { uri, detail: describeError(error) }));
592
+ }
593
+ );
594
+ }
595
+
596
+ /**
597
+ * Sessions are detached rather than disposed: the server ends every session
598
+ * on a connection it sees close, so ending each one first sends requests
599
+ * over a connection this call is about to dispose.
600
+ */
601
+ override dispose(): void {
602
+ for (const session of [...this.sessions]) {
603
+ session.detach();
604
+ }
605
+ // For a factory's session whose `detach` does not fire.
606
+ this.sessions.clear();
607
+ this.watches.clear();
608
+ this.pendingUnwatches.clear();
609
+ this.createSessionEmitter.dispose();
610
+ this.reconnectEmitter.dispose();
611
+ this.dirtyChangedEmitter.dispose();
612
+ this.documentUpdatedEmitter.dispose();
613
+ this.documentDeletedEmitter.dispose();
614
+ super.dispose();
615
+ }
616
+ }
617
+
618
+ /**
619
+ * A {@link DataConnection} that brings its own {@link DataEvents}, so a host
620
+ * with several interested parties does not have to supply one.
621
+ *
622
+ * **The client slot holds exactly one object, and that is why this exists.**
623
+ * `createRpcProxy` binds a single `localTarget`, and underneath a method name
624
+ * maps to one handler — a second registration replaces the first silently. So a
625
+ * properties panel and a tree cannot both be the client; one fan-out sits in the
626
+ * slot and both subscribe to it.
627
+ *
628
+ * Use {@link DataConnection} directly instead when the client is yours: an
629
+ * adopter service that implements the protocol plus its own methods, a single
630
+ * consumer that IS the client, or a request/response-only client that binds
631
+ * nothing.
632
+ */
633
+ export class DataConnectionWithEvents<
634
+ TTransfer extends TransferElement,
635
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
636
+ > extends DataConnection<TTransfer, TServer, DataEvents<TTransfer, DiagnosticOf<TServer>, ProjectOf<TServer>>> {
637
+ /** Server pushes, fanned out to as many local listeners as the host has. */
638
+ readonly events: DataEvents<TTransfer, DiagnosticOf<TServer>, ProjectOf<TServer>>;
639
+
640
+ constructor(port: DataPort, options?: DataConnectionOptions<TTransfer, TServer>) {
641
+ // Built as a local because `this` is unavailable before `super`, then
642
+ // read back onto the field.
643
+ const events = new DataEvents<TTransfer, DiagnosticOf<TServer>, ProjectOf<TServer>>();
644
+ super(port, events, options);
645
+ this.events = events;
646
+ }
647
+
648
+ /** Disposes the fan-out it created, which no caller else holds. */
649
+ override dispose(): void {
650
+ super.dispose();
651
+ this.events.dispose();
652
+ }
653
+ }