@hydranium/protocol 1.0.0-next.7 → 1.0.0-next.70

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 (104) hide show
  1. package/README.md +35 -1
  2. package/lib/client/data-connection.d.ts +103 -0
  3. package/lib/client/data-connection.d.ts.map +1 -0
  4. package/lib/client/data-connection.js +114 -0
  5. package/lib/client/data-connection.js.map +1 -0
  6. package/lib/client/data-events.d.ts +9 -1
  7. package/lib/client/data-events.d.ts.map +1 -1
  8. package/lib/client/data-events.js +14 -0
  9. package/lib/client/data-events.js.map +1 -1
  10. package/lib/client/data-port.d.ts +16 -21
  11. package/lib/client/data-port.d.ts.map +1 -1
  12. package/lib/client/data-session.d.ts +56 -74
  13. package/lib/client/data-session.d.ts.map +1 -1
  14. package/lib/client/data-session.js +67 -101
  15. package/lib/client/data-session.js.map +1 -1
  16. package/lib/client/index.d.ts +10 -7
  17. package/lib/client/index.d.ts.map +1 -1
  18. package/lib/client/index.js +10 -7
  19. package/lib/client/index.js.map +1 -1
  20. package/lib/client/message-relay.d.ts +8 -2
  21. package/lib/client/message-relay.d.ts.map +1 -1
  22. package/lib/client/message-relay.js +10 -4
  23. package/lib/client/message-relay.js.map +1 -1
  24. package/lib/client/rpc-connection.d.ts +131 -0
  25. package/lib/client/rpc-connection.d.ts.map +1 -0
  26. package/lib/client/rpc-connection.js +171 -0
  27. package/lib/client/rpc-connection.js.map +1 -0
  28. package/lib/client-ids.d.ts +41 -0
  29. package/lib/client-ids.d.ts.map +1 -0
  30. package/lib/client-ids.js +44 -0
  31. package/lib/client-ids.js.map +1 -0
  32. package/lib/data/data-protocol-methods.d.ts +2 -2
  33. package/lib/data/data-protocol-methods.d.ts.map +1 -1
  34. package/lib/data/data-protocol-methods.js +6 -1
  35. package/lib/data/data-protocol-methods.js.map +1 -1
  36. package/lib/data/data-server-protocol.d.ts +21 -1
  37. package/lib/data/data-server-protocol.d.ts.map +1 -1
  38. package/lib/data/events.d.ts +70 -3
  39. package/lib/data/events.d.ts.map +1 -1
  40. package/lib/errors.d.ts +25 -6
  41. package/lib/errors.d.ts.map +1 -1
  42. package/lib/errors.js +32 -12
  43. package/lib/errors.js.map +1 -1
  44. package/lib/index.d.ts +2 -0
  45. package/lib/index.d.ts.map +1 -1
  46. package/lib/index.js +5 -0
  47. package/lib/index.js.map +1 -1
  48. package/lib/messages/index.d.ts +28 -0
  49. package/lib/messages/index.d.ts.map +1 -0
  50. package/lib/messages/index.js +52 -0
  51. package/lib/messages/index.js.map +1 -0
  52. package/lib/messages/primitives.d.ts +141 -0
  53. package/lib/messages/primitives.d.ts.map +1 -0
  54. package/lib/messages/primitives.js +138 -0
  55. package/lib/messages/primitives.js.map +1 -0
  56. package/lib/model-server.d.ts +2 -2
  57. package/lib/model-server.d.ts.map +1 -1
  58. package/lib/rpc/bind-rpc-methods.d.ts +29 -3
  59. package/lib/rpc/bind-rpc-methods.d.ts.map +1 -1
  60. package/lib/rpc/bind-rpc-methods.js +22 -3
  61. package/lib/rpc/bind-rpc-methods.js.map +1 -1
  62. package/lib/rpc/create-rpc-proxy.d.ts +7 -0
  63. package/lib/rpc/create-rpc-proxy.d.ts.map +1 -1
  64. package/lib/rpc/create-rpc-proxy.js +6 -1
  65. package/lib/rpc/create-rpc-proxy.js.map +1 -1
  66. package/lib/testing/catalogue-audit.d.ts +80 -0
  67. package/lib/testing/catalogue-audit.d.ts.map +1 -0
  68. package/lib/testing/catalogue-audit.js +94 -0
  69. package/lib/testing/catalogue-audit.js.map +1 -0
  70. package/lib/testing/data-doubles.d.ts +11 -12
  71. package/lib/testing/data-doubles.d.ts.map +1 -1
  72. package/lib/testing/data-doubles.js +14 -5
  73. package/lib/testing/data-doubles.js.map +1 -1
  74. package/lib/testing/index.d.ts +1 -0
  75. package/lib/testing/index.d.ts.map +1 -1
  76. package/lib/testing/index.js +4 -1
  77. package/lib/testing/index.js.map +1 -1
  78. package/lib/transfer-diagnostic.d.ts +33 -0
  79. package/lib/transfer-diagnostic.d.ts.map +1 -1
  80. package/lib/transfer-diagnostic.js +23 -0
  81. package/lib/transfer-diagnostic.js.map +1 -1
  82. package/package.json +11 -2
  83. package/src/client/data-connection.ts +160 -0
  84. package/src/client/data-events.ts +24 -1
  85. package/src/client/data-port.ts +16 -22
  86. package/src/client/data-session.ts +86 -124
  87. package/src/client/index.ts +10 -7
  88. package/src/client/message-relay.ts +28 -6
  89. package/src/client/rpc-connection.ts +222 -0
  90. package/src/client-ids.ts +45 -0
  91. package/src/data/data-protocol-methods.ts +6 -3
  92. package/src/data/data-server-protocol.ts +29 -1
  93. package/src/data/events.ts +74 -3
  94. package/src/errors.ts +38 -14
  95. package/src/index.ts +5 -0
  96. package/src/messages/index.ts +35 -0
  97. package/src/messages/primitives.ts +215 -0
  98. package/src/model-server.ts +2 -2
  99. package/src/rpc/bind-rpc-methods.ts +49 -4
  100. package/src/rpc/create-rpc-proxy.ts +14 -1
  101. package/src/testing/catalogue-audit.ts +111 -0
  102. package/src/testing/data-doubles.ts +33 -17
  103. package/src/testing/index.ts +4 -1
  104. package/src/transfer-diagnostic.ts +40 -0
@@ -0,0 +1,160 @@
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 { FRAMEWORK_CLIENT_IDS } from '../client-ids';
11
+ import { DATA_CLIENT_PROTOCOL_METHODS, DATA_SERVER_WIRE_PREFIX, type DataClientProtocol, type DataServerProtocol } from '../data';
12
+ import type { TransferElement } from '../transfer-element';
13
+ import { DataEvents } from './data-events';
14
+ import type { DataPort } from './data-port';
15
+ import { DataSession } from './data-session';
16
+ import { RpcConnection, type RpcConnectionLifecycle } from './rpc-connection';
17
+
18
+ /** Options for {@link DataConnection}. */
19
+ export interface DataConnectionOptions extends RpcConnectionLifecycle {
20
+ /**
21
+ * Wire namespace the server is addressed under. Defaults to the
22
+ * framework's {@link DATA_SERVER_WIRE_PREFIX}, which is what an unmodified
23
+ * `DataServer` binds. Override only alongside the server's own
24
+ * `methodNamespace` option — a mismatch turns every request into
25
+ * "Unhandled method" rather than failing at wire-up.
26
+ */
27
+ readonly methodNamespace?: string;
28
+ }
29
+
30
+ /** {@link DataConnectionOptions} for a client that does not speak {@link DataClientProtocol}. */
31
+ export interface DataConnectionOptionsWithMethods<TClient extends object> extends DataConnectionOptions {
32
+ /**
33
+ * Method names of the client to bind as inbound handlers. Declare it
34
+ * `as const satisfies ReadonlyArray<keyof YourClient & string>` so the list
35
+ * cannot drift from the interface.
36
+ */
37
+ readonly clientMethods: readonly (keyof TClient & string)[];
38
+ }
39
+
40
+ /**
41
+ * Trailing constructor arguments, required only when the client cannot take
42
+ * the framework's default method list.
43
+ *
44
+ * `bindRpcMethods` throws for a name the target does not implement, so a
45
+ * request/response-only client binding the default list fails at wire-up. The
46
+ * conditional turns that into a compile error.
47
+ */
48
+ export type DataConnectionArgs<TTransfer extends TransferElement, TClient extends object> =
49
+ TClient extends DataClientProtocol<TTransfer>
50
+ ? [options?: DataConnectionOptions & Partial<DataConnectionOptionsWithMethods<TClient>>]
51
+ : [options: DataConnectionOptionsWithMethods<TClient>];
52
+
53
+ /**
54
+ * A {@link RpcConnection} to the data head, carrying as many participants as
55
+ * the host has interested parties.
56
+ *
57
+ * Document operations live on the participants rather than here: they carry a
58
+ * `clientId`, which identifies a participant rather than a wire, and the server
59
+ * keys its holds and watches per `(uri, clientId)`. Two parties sharing one
60
+ * identity cannot tell each other's writes from their own echoes.
61
+ *
62
+ * Generic over the transfer root so this file names no grammar. An adopter
63
+ * binds the concrete root (or the union of them, for a multi-grammar head) at
64
+ * its own edge.
65
+ */
66
+ export class DataConnection<
67
+ TTransfer extends TransferElement,
68
+ TServer extends DataServerProtocol<TTransfer> = DataServerProtocol<TTransfer>,
69
+ TClient extends object = DataClientProtocol<TTransfer>
70
+ > extends RpcConnection<TServer, TClient> {
71
+ protected readonly sessions = new Set<DataSession<TTransfer, TServer>>();
72
+
73
+ constructor(port: DataPort, client: TClient, ...rest: DataConnectionArgs<TTransfer, TClient>) {
74
+ const [options = {}] = rest as [(DataConnectionOptions & Partial<DataConnectionOptionsWithMethods<TClient>>)?];
75
+ super(port, client, {
76
+ methodNamespace: options.methodNamespace ?? DATA_SERVER_WIRE_PREFIX,
77
+ // The default is reachable only where `TClient` satisfies
78
+ // `DataClientProtocol`, which the constructor's conditional enforces;
79
+ // the compiler cannot carry that through to the generic parameter.
80
+ clientMethods: options.clientMethods ?? (DATA_CLIENT_PROTOCOL_METHODS as unknown as readonly (keyof TClient & string)[]),
81
+ lifecycle: options
82
+ });
83
+ }
84
+
85
+ /**
86
+ * Mint a participant on this connection under `clientId`.
87
+ *
88
+ * `clientId` must be distinct per participant and stable for its lifetime:
89
+ * it keys the server's per-`(uri, clientId)` hold and watch, and it is the
90
+ * echo key an inbound `onDocumentUpdated` is matched against.
91
+ *
92
+ * Throws for an id in {@link FRAMEWORK_CLIENT_IDS} — those are authors the
93
+ * SERVER emits rather than participants, so a session holding one would read
94
+ * the framework's own broadcasts as its own echoes and drop them. Nothing
95
+ * about that fails on its own: the document simply stops following, which
96
+ * looks like a dead connection.
97
+ */
98
+ createSession(clientId: string): DataSession<TTransfer, TServer> {
99
+ this.assertLive();
100
+ if (FRAMEWORK_CLIENT_IDS.includes(clientId)) {
101
+ throw new Error(`clientId '${clientId}' is reserved by the framework and cannot identify a participant`);
102
+ }
103
+ const session = new DataSession<TTransfer, TServer>(clientId, {
104
+ connected: () => this.connected(),
105
+ releaseSession: released => this.sessions.delete(released)
106
+ });
107
+ this.sessions.add(session);
108
+ return session;
109
+ }
110
+
111
+ /**
112
+ * Sessions are detached rather than disposed: the server releases every hold
113
+ * on a connection it sees close, so closing each document first sends
114
+ * requests over a connection this call is about to dispose.
115
+ */
116
+ override dispose(): void {
117
+ for (const session of [...this.sessions]) {
118
+ session.detach();
119
+ }
120
+ this.sessions.clear();
121
+ super.dispose();
122
+ }
123
+ }
124
+
125
+ /**
126
+ * A {@link DataConnection} that brings its own {@link DataEvents}, so a host
127
+ * with several interested parties does not have to supply one.
128
+ *
129
+ * **The client slot holds exactly one object, and that is why this exists.**
130
+ * `createRpcProxy` binds a single `localTarget`, and underneath a method name
131
+ * maps to one handler — a second registration replaces the first silently. So a
132
+ * properties panel and a tree cannot both be the client; one fan-out sits in the
133
+ * slot and both subscribe to it.
134
+ *
135
+ * Use {@link DataConnection} directly instead when the client is yours: an
136
+ * adopter service that implements the protocol plus its own methods, a single
137
+ * consumer that IS the client, or a request/response-only client that binds
138
+ * nothing.
139
+ */
140
+ export class DataConnectionWithEvents<
141
+ TTransfer extends TransferElement,
142
+ TServer extends DataServerProtocol<TTransfer> = DataServerProtocol<TTransfer>
143
+ > extends DataConnection<TTransfer, TServer, DataEvents<TTransfer>> {
144
+ /** Server pushes, fanned out to as many local listeners as the host has. */
145
+ readonly events: DataEvents<TTransfer>;
146
+
147
+ constructor(port: DataPort, options?: DataConnectionOptions) {
148
+ // Built as a local because `this` is unavailable before `super`, then
149
+ // read back onto the field.
150
+ const events = new DataEvents<TTransfer>();
151
+ super(port, events, options);
152
+ this.events = events;
153
+ }
154
+
155
+ /** Disposes the fan-out it created, which no caller else holds. */
156
+ override dispose(): void {
157
+ super.dispose();
158
+ this.events.dispose();
159
+ }
160
+ }
@@ -8,7 +8,14 @@
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
+ TransferDocumentSavedEvent,
16
+ TransferDocumentsBuiltEvent,
17
+ TransferDocumentUpdatedEvent
18
+ } from '../data';
12
19
  import type { Project } from '../project';
13
20
  import type { TransferDiagnostic } from '../transfer-diagnostic';
14
21
  import type { TransferElement } from '../transfer-element';
@@ -40,12 +47,18 @@ export class DataEvents<
40
47
  > implements DataClientProtocol<TTransfer, TDiagnostic, TProject> {
41
48
  protected readonly documentUpdatedEmitter = new Emitter<TransferDocumentUpdatedEvent<TTransfer, TDiagnostic>>();
42
49
  protected readonly documentSavedEmitter = new Emitter<TransferDocumentSavedEvent<TTransfer, TDiagnostic>>();
50
+ protected readonly documentDeletedEmitter = new Emitter<TransferDocumentDeletedEvent>();
51
+ protected readonly documentsBuiltEmitter = new Emitter<TransferDocumentsBuiltEvent>();
43
52
  protected readonly projectsChangedEmitter = new Emitter<ProjectsChangedEvent<TProject>>();
44
53
 
45
54
  /** A build-phase event for a watched document. Carries the originating `sourceClientId`. */
46
55
  readonly onDidUpdateDocument: Event<TransferDocumentUpdatedEvent<TTransfer, TDiagnostic>> = this.documentUpdatedEmitter.event;
47
56
  /** A watched document was persisted to disk. */
48
57
  readonly onDidSaveDocument: Event<TransferDocumentSavedEvent<TTransfer, TDiagnostic>> = this.documentSavedEmitter.event;
58
+ /** A document's backing file was removed, watched or not. Any watch survives. */
59
+ readonly onDidDeleteDocument: Event<TransferDocumentDeletedEvent> = this.documentDeletedEmitter.event;
60
+ /** Documents built that nobody watches — re-read anything derived from them. */
61
+ readonly onDidBuildDocuments: Event<TransferDocumentsBuiltEvent> = this.documentsBuiltEmitter.event;
49
62
  /** The project set changed. */
50
63
  readonly onDidChangeProjects: Event<ProjectsChangedEvent<TProject>> = this.projectsChangedEmitter.event;
51
64
 
@@ -59,6 +72,14 @@ export class DataEvents<
59
72
  this.documentSavedEmitter.fire(event);
60
73
  }
61
74
 
75
+ onDocumentDeleted(event: TransferDocumentDeletedEvent): void {
76
+ this.documentDeletedEmitter.fire(event);
77
+ }
78
+
79
+ onDocumentsBuilt(event: TransferDocumentsBuiltEvent): void {
80
+ this.documentsBuiltEmitter.fire(event);
81
+ }
82
+
62
83
  onProjectsChanged(event: ProjectsChangedEvent<TProject>): void {
63
84
  this.projectsChangedEmitter.fire(event);
64
85
  }
@@ -66,6 +87,8 @@ export class DataEvents<
66
87
  dispose(): void {
67
88
  this.documentUpdatedEmitter.dispose();
68
89
  this.documentSavedEmitter.dispose();
90
+ this.documentDeletedEmitter.dispose();
91
+ this.documentsBuiltEmitter.dispose();
69
92
  this.projectsChangedEmitter.dispose();
70
93
  }
71
94
  }
@@ -8,15 +8,19 @@
8
8
  ********************************************************************************/
9
9
 
10
10
  import type { Event, MessageConnection } from 'vscode-jsonrpc';
11
+ import type { ResolvedMessage } from '../messages/primitives';
11
12
 
12
13
  /**
13
14
  * 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.
15
+ * connection to the data server, plus the failure sink that goes with it.
16
16
  *
17
- * "Port" in the hexagonal sense — the host implements it, `DataSession`
17
+ * "Port" in the hexagonal sense — the host implements it, `DataConnection`
18
18
  * consumes it, and nothing on either side of the boundary imports the other.
19
19
  *
20
+ * Carries no identity. A `clientId` names a participant, and one transport
21
+ * serves as many as the host has; binding an identity here is what makes two
22
+ * of them share one, so it lives on `DataSession` instead.
23
+ *
20
24
  * **This deliberately does NOT wrap the protocol methods.** `createRpcProxy`
21
25
  * already takes a promise of a connection and produces the whole typed
22
26
  * `DataServerProtocol` surface, so wrapping it would re-derive the framework's
@@ -45,22 +49,6 @@ import type { Event, MessageConnection } from 'vscode-jsonrpc';
45
49
  * calls on the promise but never calls `listen` itself.
46
50
  */
47
51
  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
52
  /**
65
53
  * Open the transport and hand back a listening `MessageConnection`.
66
54
  *
@@ -77,10 +65,16 @@ export interface DataPort {
77
65
  *
78
66
  * It exists because the alternative is worse in both directions: this tier
79
67
  * 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.
68
+ * connection look like an empty model.
69
+ *
70
+ * `reported` is a complete sentence plus the identity needed to render it in
71
+ * another language. It carries a value rather than using a protocol field
72
+ * because this tier does not know whether a process hop intervenes — in a
73
+ * webview host the render happens across one — and a `ResolvedMessage` is
74
+ * structured-clone safe either way. Render it with `renderFrameworkMessage`;
75
+ * passing no translation map yields the English.
82
76
  */
83
- reportError(error: unknown, context: string): void;
77
+ reportError(error: unknown, reported: ResolvedMessage): void;
84
78
 
85
79
  /**
86
80
  * Fires when the host tears the transport down and the current connection
@@ -7,101 +7,64 @@
7
7
  * SPDX-License-Identifier: MIT
8
8
  ********************************************************************************/
9
9
 
10
- import type { MessageConnection } from 'vscode-jsonrpc';
11
- import { DATA_CLIENT_PROTOCOL_METHODS, DATA_SERVER_WIRE_PREFIX, type DataClientProtocol, type DataServerProtocol } from '../data';
12
- import { type RpcProxy, createRpcProxy } from '../rpc';
10
+ import type { DataServerProtocol, TransferSaveDocumentArgs, TransferUpdateDocumentArgs } from '../data';
11
+ import type { RpcProxy } from '../rpc';
13
12
  import type { TransferDocument } from '../transfer-document';
14
13
  import type { TransferElement } from '../transfer-element';
15
- import type { DataPort } from './data-port';
16
14
 
17
- /** Options for {@link DataSession}. */
18
- export interface DataSessionOptions {
19
- /**
20
- * Wire namespace the server is addressed under. Defaults to the
21
- * framework's {@link DATA_SERVER_WIRE_PREFIX}, which is what an unmodified
22
- * `DataServer` binds. Override only alongside the server's own
23
- * `methodNamespace` option — a mismatch turns every request into
24
- * "Unhandled method" rather than failing at wire-up.
25
- */
26
- readonly methodNamespace?: string;
27
- }
15
+ /** Update a document through a session; the session supplies `clientId`. */
16
+ export type DataSessionUpdateArgs<TTransfer> = Omit<TransferUpdateDocumentArgs<TTransfer>, 'clientId'>;
28
17
 
29
- /** One connection generation: its connection, its proxy, and its readiness. */
30
- interface Generation<TTransfer extends TransferElement> {
31
- readonly connection: Promise<MessageConnection>;
32
- readonly server: RpcProxy<DataServerProtocol<TTransfer>>;
33
- /** Set on first use; the shared readiness gate for this generation. */
34
- ready?: Promise<void>;
35
- }
18
+ /** Persist a document through a session; the session supplies `clientId`. */
19
+ export type DataSessionSaveArgs<TTransfer> = Omit<TransferSaveDocumentArgs<TTransfer>, 'clientId'>;
36
20
 
37
21
  /**
38
- * The host-invariant half of talking to the data head: everything above
39
- * {@link DataPort} that would otherwise be re-derived by every host
40
- * adapter.
22
+ * What a {@link DataSession} needs from the connection that minted it.
41
23
  *
42
- * Three jobs, and deliberately no fourth:
24
+ * Narrower than the connection itself so the dependency points one way:
25
+ * `DataConnection` constructs sessions, and nothing here imports it back.
26
+ */
27
+ export interface DataSessionHost<TTransfer extends TransferElement, TServer extends DataServerProtocol<TTransfer>> {
28
+ connected(): Promise<RpcProxy<TServer>>;
29
+ releaseSession(session: DataSession<TTransfer, TServer>): void;
30
+ }
31
+
32
+ /**
33
+ * One participant on a data connection: a properties panel, a tree, a
34
+ * form editor.
43
35
  *
44
- * 1. **Build the typed proxy** over the port's connection, with the framework's
45
- * wire prefix and its drift-proof client-method allowlist.
46
- * 2. **Own the readiness gate** — `waitForReady` once per connection, shared
47
- * across concurrent callers. A socket client can connect before the
48
- * workspace walk finishes, and an early request is then answered correctly
49
- * from an empty registry, which reads as a broken project tier rather than
50
- * as a race.
51
- * 3. **Own the reconnect policy**, by dropping its connection generation when
52
- * the port disposes and building a fresh one on the next request.
36
+ * The server keys every hold and watch per `(uri, clientId)`, so the identity
37
+ * belongs to the participant rather than to the wire — several sessions share
38
+ * one connection, and two participants forced to share one identity cannot
39
+ * distinguish each other's writes from their own echoes.
53
40
  *
54
- * It does **not** wrap the protocol methods; callers reach them through
55
- * {@link connected}. The one exception is {@link openDocument}, which exists
56
- * because the open/watch *order* is silently wrong the other way round — see
57
- * its own doc.
41
+ * Every document operation stamps {@link clientId} itself. A caller that
42
+ * passed its own could pass another participant's, and the server would
43
+ * attribute the write and release the hold accordingly.
58
44
  *
59
- * Generic over the transfer root so this file names no grammar. An adopter
60
- * binds the concrete root (or the union of them, for a multi-grammar head) at
61
- * its own edge.
45
+ * Generic over the transfer root so this file names no grammar.
62
46
  */
63
- export class DataSession<TTransfer extends TransferElement> {
64
- protected readonly methodNamespace: string;
65
- /** The current generation, or `undefined` before the first request / after a teardown. */
66
- protected generation?: Generation<TTransfer>;
47
+ export class DataSession<TTransfer extends TransferElement, TServer extends DataServerProtocol<TTransfer> = DataServerProtocol<TTransfer>> {
48
+ /** URIs this session holds open, so {@link dispose} can release exactly those. */
49
+ protected readonly openUris = new Set<string>();
67
50
  protected disposed = false;
68
- protected readonly portDisposeListener: { dispose(): void };
69
51
 
70
52
  constructor(
71
- protected readonly port: DataPort,
72
- protected readonly client: DataClientProtocol<TTransfer>,
73
- options: DataSessionOptions = {}
74
- ) {
75
- this.methodNamespace = options.methodNamespace ?? DATA_SERVER_WIRE_PREFIX;
76
- this.portDisposeListener = this.port.onDispose(() => this.dropGeneration());
77
- }
78
-
79
- /** The identity every request is made under — the port's, not a second one. */
80
- get clientId(): string {
81
- return this.port.clientId;
82
- }
53
+ readonly clientId: string,
54
+ protected readonly host: DataSessionHost<TTransfer, TServer>
55
+ ) {}
83
56
 
84
57
  /**
85
- * The connected, READY server proxy.
86
- *
87
- * Returns the proxy rather than `void` on purpose. A reconnect replaces the
88
- * proxy, so a caller that cached one from an earlier call would go on
89
- * addressing a dead connection with no error — handing it back per call
90
- * makes the stale reference unrepresentable.
91
- *
92
- * Concurrent callers share one readiness promise, so `waitForReady` is
93
- * awaited once per generation and not once per caller.
58
+ * The connected, READY server proxy, for protocol methods this session does
59
+ * not wrap — the ones carrying no `clientId`, so no identity can be got
60
+ * wrong through them.
94
61
  */
95
- async connected(): Promise<RpcProxy<DataServerProtocol<TTransfer>>> {
96
- if (this.disposed) {
97
- throw new Error('DataSession is disposed');
98
- }
99
- const generation = this.currentGeneration();
100
- if (!generation.ready) {
101
- generation.ready = this.awaitReady(generation);
102
- }
103
- await generation.ready;
104
- return generation.server;
62
+ async connected(): Promise<RpcProxy<TServer>> {
63
+ // `async` so a disposed session REJECTS rather than throwing
64
+ // synchronously: the connection's own `connected` rejects, and a caller
65
+ // reaching for `.catch` on one of them would not catch the other.
66
+ this.assertLive();
67
+ return this.host.connected();
105
68
  }
106
69
 
107
70
  /**
@@ -126,6 +89,7 @@ export class DataSession<TTransfer extends TransferElement> {
126
89
  const server = await this.connected();
127
90
  const document = await server.openModelDocument({ uri, clientId: this.clientId });
128
91
  await server.watchModelDocument({ uri, clientId: this.clientId });
92
+ this.openUris.add(uri);
129
93
  return document;
130
94
  }
131
95
 
@@ -135,11 +99,24 @@ export class DataSession<TTransfer extends TransferElement> {
135
99
  */
136
100
  async closeDocument(uri: string): Promise<void> {
137
101
  const server = await this.connected();
102
+ this.openUris.delete(uri);
138
103
  await server.closeModelDocument({ uri, clientId: this.clientId });
139
104
  }
140
105
 
106
+ /** Write `args.model` back as this session. */
107
+ async updateDocument(args: DataSessionUpdateArgs<TTransfer>): Promise<TransferDocument<TTransfer>> {
108
+ const server = await this.connected();
109
+ return server.updateModelDocument({ ...args, clientId: this.clientId });
110
+ }
111
+
112
+ /** Persist `args.model` to disk as this session. */
113
+ async saveDocument(args: DataSessionSaveArgs<TTransfer>): Promise<TransferDocument<TTransfer>> {
114
+ const server = await this.connected();
115
+ return server.saveModelDocument({ ...args, clientId: this.clientId });
116
+ }
117
+
141
118
  /**
142
- * Whether `event.sourceClientId` identifies this session's own write.
119
+ * Whether `sourceClientId` identifies this session's own write.
143
120
  *
144
121
  * Every watcher needs this and the check is one comparison, so getting it
145
122
  * wrong is cheap to do and expensive to find: an unfiltered echo looks
@@ -149,61 +126,46 @@ export class DataSession<TTransfer extends TransferElement> {
149
126
  return sourceClientId === this.clientId;
150
127
  }
151
128
 
152
- /** Tear down the current connection and stop tracking the port. Idempotent. */
129
+ /**
130
+ * Release this session's holds and detach it from the connection.
131
+ * Idempotent, and leaves the connection usable by its other sessions.
132
+ *
133
+ * The closes are fired without being awaited, because a `Disposable` cannot
134
+ * be: a host disposing a widget has nowhere to put the promise. A close
135
+ * that fails is no worse than the leak this exists to prevent, so the
136
+ * rejection is swallowed rather than surfaced from a teardown.
137
+ */
153
138
  dispose(): void {
154
139
  if (this.disposed) {
155
140
  return;
156
141
  }
157
142
  this.disposed = true;
158
- this.portDisposeListener.dispose();
159
- this.dropGeneration();
160
- }
161
-
162
- /** The live generation, building one if there is none. */
163
- protected currentGeneration(): Generation<TTransfer> {
164
- if (this.generation) {
165
- return this.generation;
166
- }
167
- const connection = this.port.connect();
168
- // Rejection is reported here rather than left to float: an unhandled
169
- // rejection on a connection promise is the failure mode that reads as
170
- // "the model is empty" instead of "the transport never opened".
171
- connection.catch((error: unknown) => this.port.reportError(error, 'connecting to the data server'));
172
- const server = createRpcProxy<DataServerProtocol<TTransfer>, DataClientProtocol<TTransfer>>(connection, {
173
- methodNamespace: this.methodNamespace,
174
- localTarget: this.client,
175
- localMethods: DATA_CLIENT_PROTOCOL_METHODS
176
- });
177
- this.generation = { connection, server };
178
- return this.generation;
179
- }
180
-
181
- /** Await the connection and the server's startup gate for one generation. */
182
- protected async awaitReady(generation: Generation<TTransfer>): Promise<void> {
183
- try {
184
- await generation.connection;
185
- await generation.server.waitForReady();
186
- } catch (error: unknown) {
187
- // Drop the generation so the next request retries rather than
188
- // re-awaiting a settled rejection forever.
189
- if (this.generation === generation) {
190
- this.generation = undefined;
191
- }
192
- this.port.reportError(error, 'waiting for the data server to become ready');
193
- throw error;
143
+ const uris = [...this.openUris];
144
+ this.openUris.clear();
145
+ this.host.releaseSession(this);
146
+ for (const uri of uris) {
147
+ void this.host
148
+ .connected()
149
+ .then(server => server.closeModelDocument({ uri, clientId: this.clientId }))
150
+ .catch(() => undefined);
194
151
  }
195
152
  }
196
153
 
197
154
  /**
198
- * Discard the current generation, disposing its connection if it opened.
199
- * The next {@link connected} builds a fresh one.
155
+ * Come off the connection because it is going away.
156
+ *
157
+ * Sends no close, unlike {@link dispose}: the server releases every hold on
158
+ * a connection it sees close, and the close would travel over the very
159
+ * connection being disposed.
200
160
  */
201
- protected dropGeneration(): void {
202
- const generation = this.generation;
203
- this.generation = undefined;
204
- if (!generation) {
205
- return;
161
+ detach(): void {
162
+ this.disposed = true;
163
+ this.openUris.clear();
164
+ }
165
+
166
+ protected assertLive(): void {
167
+ if (this.disposed) {
168
+ throw new Error('DataSession is disposed');
206
169
  }
207
- generation.connection.then(connection => connection.dispose()).catch(() => undefined);
208
170
  }
209
171
  }
@@ -13,8 +13,9 @@
13
13
  *
14
14
  * Where `./data` is the wire *contract* and `./rpc` is the machinery that lowers
15
15
  * it onto a connection, this is what a client wraps around both: the seam a host
16
- * fills in (`DataPort`), the lifecycle above it (`DataSession` —
17
- * readiness gate, open/watch ordering, echo recognition, reconnect), the inbound
16
+ * fills in (`DataPort`), the connection above it (`DataConnection` — readiness
17
+ * gate and reconnect), the participants on that connection (`DataSession` —
18
+ * identity, open/watch ordering, echo recognition), the inbound
18
19
  * fan-out (`DataEvents`), and the two halves of the hop for hosts whose
19
20
  * client cannot hold a socket — `createPostMessageTransport` on the client
20
21
  * side and `relayToPostMessageChannel` on the side that does hold it.
@@ -26,15 +27,17 @@
26
27
  * carries the entries.
27
28
  *
28
29
  * The Theia-specific mounting of the same contract lives in
29
- * `@hydranium/data-client-theia`: its `AbstractDataServiceFrontend` solves the
30
- * same problem against Theia's channel transport, and its `EmitterDataClient`
31
- * is the Theia-bound counterpart of `DataEvents`. Prefer this tier for
32
- * anything new, and reach for the Theia package only for what genuinely needs
33
- * Theia DI.
30
+ * `@hydranium/data-client-theia`, and is now only the TRANSPORT: its
31
+ * `ChannelDataPort` fills the `DataPort` seam over a Theia channel, and its
32
+ * `EmitterDataClient` is the Theia-bound counterpart of `DataEvents`.
33
+ * Everything above the port is here, so a Theia frontend and a browser page
34
+ * differ by which port they construct and nothing else.
34
35
  */
35
36
 
37
+ export * from './data-connection';
36
38
  export * from './data-events';
37
39
  export * from './data-port';
38
40
  export * from './data-session';
39
41
  export * from './message-relay';
40
42
  export * from './post-message-transport';
43
+ export * from './rpc-connection';