@hydranium/protocol 1.0.0-next.12 → 1.0.0-next.123

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 (142) hide show
  1. package/README.md +35 -1
  2. package/lib/client/data-connection.d.ts +114 -0
  3. package/lib/client/data-connection.d.ts.map +1 -0
  4. package/lib/client/data-connection.js +143 -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 +17 -22
  11. package/lib/client/data-port.d.ts.map +1 -1
  12. package/lib/client/data-session.d.ts +235 -82
  13. package/lib/client/data-session.d.ts.map +1 -1
  14. package/lib/client/data-session.js +337 -108
  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 +143 -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 +4 -4
  33. package/lib/data/data-protocol-methods.d.ts.map +1 -1
  34. package/lib/data/data-protocol-methods.js +10 -1
  35. package/lib/data/data-protocol-methods.js.map +1 -1
  36. package/lib/data/data-server-protocol.d.ts +100 -31
  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/data/requests.d.ts +67 -11
  41. package/lib/data/requests.d.ts.map +1 -1
  42. package/lib/errors.d.ts +91 -12
  43. package/lib/errors.d.ts.map +1 -1
  44. package/lib/errors.js +127 -18
  45. package/lib/errors.js.map +1 -1
  46. package/lib/index.d.ts +2 -0
  47. package/lib/index.d.ts.map +1 -1
  48. package/lib/index.js +5 -0
  49. package/lib/index.js.map +1 -1
  50. package/lib/latency-collector.d.ts +8 -4
  51. package/lib/latency-collector.d.ts.map +1 -1
  52. package/lib/latency-collector.js.map +1 -1
  53. package/lib/messages/index.d.ts +29 -0
  54. package/lib/messages/index.d.ts.map +1 -0
  55. package/lib/messages/index.js +55 -0
  56. package/lib/messages/index.js.map +1 -0
  57. package/lib/messages/primitives.d.ts +188 -0
  58. package/lib/messages/primitives.d.ts.map +1 -0
  59. package/lib/messages/primitives.js +161 -0
  60. package/lib/messages/primitives.js.map +1 -0
  61. package/lib/model-server.d.ts +44 -13
  62. package/lib/model-server.d.ts.map +1 -1
  63. package/lib/model-server.js +4 -2
  64. package/lib/model-server.js.map +1 -1
  65. package/lib/model-service/based-on.d.ts +57 -0
  66. package/lib/model-service/based-on.d.ts.map +1 -0
  67. package/lib/model-service/based-on.js +37 -0
  68. package/lib/model-service/based-on.js.map +1 -0
  69. package/lib/model-service/index.d.ts +1 -1
  70. package/lib/model-service/index.d.ts.map +1 -1
  71. package/lib/model-service/index.js +4 -5
  72. package/lib/model-service/index.js.map +1 -1
  73. package/lib/patch-merge.d.ts +28 -27
  74. package/lib/patch-merge.d.ts.map +1 -1
  75. package/lib/patch-merge.js +66 -22
  76. package/lib/patch-merge.js.map +1 -1
  77. package/lib/profile-session.d.ts +8 -4
  78. package/lib/profile-session.d.ts.map +1 -1
  79. package/lib/profile-session.js.map +1 -1
  80. package/lib/rpc/bind-rpc-methods.d.ts +29 -3
  81. package/lib/rpc/bind-rpc-methods.d.ts.map +1 -1
  82. package/lib/rpc/bind-rpc-methods.js +22 -3
  83. package/lib/rpc/bind-rpc-methods.js.map +1 -1
  84. package/lib/rpc/create-rpc-proxy.d.ts +7 -0
  85. package/lib/rpc/create-rpc-proxy.d.ts.map +1 -1
  86. package/lib/rpc/create-rpc-proxy.js +6 -1
  87. package/lib/rpc/create-rpc-proxy.js.map +1 -1
  88. package/lib/testing/catalogue-audit.d.ts +80 -0
  89. package/lib/testing/catalogue-audit.d.ts.map +1 -0
  90. package/lib/testing/catalogue-audit.js +94 -0
  91. package/lib/testing/catalogue-audit.js.map +1 -0
  92. package/lib/testing/data-doubles.d.ts +11 -12
  93. package/lib/testing/data-doubles.d.ts.map +1 -1
  94. package/lib/testing/data-doubles.js +14 -5
  95. package/lib/testing/data-doubles.js.map +1 -1
  96. package/lib/testing/index.d.ts +1 -0
  97. package/lib/testing/index.d.ts.map +1 -1
  98. package/lib/testing/index.js +4 -1
  99. package/lib/testing/index.js.map +1 -1
  100. package/lib/transfer-diagnostic.d.ts +33 -0
  101. package/lib/transfer-diagnostic.d.ts.map +1 -1
  102. package/lib/transfer-diagnostic.js +23 -0
  103. package/lib/transfer-diagnostic.js.map +1 -1
  104. package/lib/transfer-document.d.ts +14 -5
  105. package/lib/transfer-document.d.ts.map +1 -1
  106. package/lib/transfer-document.js +14 -1
  107. package/lib/transfer-document.js.map +1 -1
  108. package/package.json +11 -2
  109. package/src/client/data-connection.ts +216 -0
  110. package/src/client/data-events.ts +24 -1
  111. package/src/client/data-port.ts +17 -23
  112. package/src/client/data-session.ts +447 -128
  113. package/src/client/index.ts +10 -7
  114. package/src/client/message-relay.ts +28 -6
  115. package/src/client/rpc-connection.ts +235 -0
  116. package/src/client-ids.ts +45 -0
  117. package/src/data/data-protocol-methods.ts +10 -3
  118. package/src/data/data-server-protocol.ts +119 -31
  119. package/src/data/events.ts +74 -3
  120. package/src/data/requests.ts +71 -11
  121. package/src/errors.ts +139 -20
  122. package/src/index.ts +5 -0
  123. package/src/latency-collector.ts +8 -3
  124. package/src/messages/index.ts +36 -0
  125. package/src/messages/primitives.ts +271 -0
  126. package/src/model-server.ts +47 -18
  127. package/src/model-service/based-on.ts +63 -0
  128. package/src/model-service/index.ts +4 -5
  129. package/src/patch-merge.ts +90 -37
  130. package/src/profile-session.ts +9 -4
  131. package/src/rpc/bind-rpc-methods.ts +49 -4
  132. package/src/rpc/create-rpc-proxy.ts +14 -1
  133. package/src/testing/catalogue-audit.ts +111 -0
  134. package/src/testing/data-doubles.ts +33 -17
  135. package/src/testing/index.ts +4 -1
  136. package/src/transfer-diagnostic.ts +40 -0
  137. package/src/transfer-document.ts +21 -6
  138. package/lib/model-service/args.d.ts +0 -64
  139. package/lib/model-service/args.d.ts.map +0 -1
  140. package/lib/model-service/args.js +0 -11
  141. package/lib/model-service/args.js.map +0 -1
  142. package/src/model-service/args.ts +0 -67
@@ -30,10 +30,14 @@ import type { TransferDocument } from '../transfer-document';
30
30
  * from both `onDocumentUpdated` and `onDocumentSaved`. The framework's own
31
31
  * `dispatchPhaseEvent` does NOT emit `'saved'` — saves take the dedicated
32
32
  * `DataClientProtocol.onDocumentSaved` channel.
33
- * - `'deleted'` — the URI appeared in `DocumentBuilder.onUpdate`'s
34
- * `deleted` list. The backing file was removed.
33
+ *
34
+ * Deletion is deliberately NOT a member. An update event carries a built
35
+ * document, which a deleted one has none of, and the phase-driven path that
36
+ * produces these events never runs for a deleted URI — the builder drops the
37
+ * document before deriving the rebuild set. It travels as
38
+ * {@link TransferDocumentDeletedEvent} on its own channel instead.
35
39
  */
36
- export type TransferDocumentUpdateReason = 'changed' | 'rebuilt' | 'saved' | 'deleted';
40
+ export type TransferDocumentUpdateReason = 'changed' | 'rebuilt' | 'saved';
37
41
 
38
42
  /**
39
43
  * Delivered on the data-server when a document's content (or existence)
@@ -91,6 +95,73 @@ export type TransferDocumentSavedListener<
91
95
  TDiagnostic extends TransferDiagnostic = TransferDiagnostic
92
96
  > = (event: TransferDocumentSavedEvent<TTransfer, TDiagnostic>) => void;
93
97
 
98
+ /**
99
+ * Delivered on the data-server when a document's backing file was removed.
100
+ * Carries no document, and cannot: the state a
101
+ * {@link TransferDocumentUpdatedEvent} would have to carry no longer exists by
102
+ * the time anyone can be told. That is also why deletion is not a `reason` on
103
+ * the update stream — `DocumentBuilder.update` drops the document before
104
+ * deriving the rebuild set, so the phase-driven path that produces update
105
+ * events never runs for it.
106
+ *
107
+ * **Delivered for EVERY document, not only watched ones**, unlike
108
+ * `onDocumentUpdated` and `onDocumentSaved`. The test that decides which
109
+ * channels are gated is whether any OTHER source can observe the fact on the
110
+ * least capable host: a browser-hosted client's workspace lives behind the
111
+ * head, so nothing there can see a file disappear, and gating the notification
112
+ * would leave it blind. (A Theia frontend's filesystem watcher would cover it,
113
+ * which is why this is a host argument and not a structure-versus-content one.)
114
+ * A watcher is told about its own document's deletion here too, the update
115
+ * channel being silent for deletions by construction. Filter on {@link uri} if
116
+ * the receiver only cares about documents it opened.
117
+ *
118
+ * A watch survives the deletion, so a file that comes back resumes delivering
119
+ * `onDocumentUpdated` to the same subscribers with no re-subscription. A
120
+ * client that responds by closing its editor releases the watch through
121
+ * `closeModelDocument` as usual.
122
+ */
123
+ export interface TransferDocumentDeletedEvent {
124
+ /** Canonical URI of the removed document, keyed as the subscription is. */
125
+ readonly uri: string;
126
+ }
127
+
128
+ /** Callback shape for `DataClientProtocol.onDocumentDeleted`. */
129
+ export type TransferDocumentDeletedListener = (event: TransferDocumentDeletedEvent) => void;
130
+
131
+ /**
132
+ * Delivered on the data-server once per build, naming the documents that reached
133
+ * the configured subscription phase (`DataServerOptions.subscriptionPhase`,
134
+ * `Validated` by default) and that NO client on the connection is watching. Not
135
+ * the integrity-settled landmark, which is a different point and a different
136
+ * word in this framework.
137
+ *
138
+ * The complement of {@link TransferDocumentUpdatedEvent}, which is gated per
139
+ * URI: together the two cover every document a build touched. This one exists
140
+ * for the case no source outside the server can observe — a document rebuilt
141
+ * because something it DEPENDS ON changed. Its own file never changed, so a
142
+ * filesystem watcher cannot see it, and it has no subscriber, so the update
143
+ * channel does not report it. A consumer showing data derived from such a
144
+ * document (a tree label, a decorator) would otherwise hold a stale value with
145
+ * nothing to invalidate it.
146
+ *
147
+ * Carries URIs and no documents: a recipient re-reads what it displays, through
148
+ * `getModelDocument` or its own request. That keeps the bandwidth property the
149
+ * per-URI subscription exists for, without gating the message.
150
+ *
151
+ * Not sent when the set is empty, which is the normal case while editing — the
152
+ * document being edited is watched by its own editor and therefore excluded.
153
+ * Workspace initialisation sends nothing either: it does not build to the
154
+ * subscription phase. The largest message a workspace can produce is therefore
155
+ * a whole-workspace rebuild at that phase, which is one message of URIs.
156
+ */
157
+ export interface TransferDocumentsBuiltEvent {
158
+ /** Canonical URIs, keyed as subscriptions are. Never empty. */
159
+ readonly uris: readonly string[];
160
+ }
161
+
162
+ /** Callback shape for `DataClientProtocol.onDocumentsBuilt`. */
163
+ export type TransferDocumentsBuiltListener = (event: TransferDocumentsBuiltEvent) => void;
164
+
94
165
  /**
95
166
  * Why a project-change event fired. `added` — the project was newly
96
167
  * registered (descriptor discovered); `updated` — the project's
@@ -7,7 +7,7 @@
7
7
  * SPDX-License-Identifier: MIT
8
8
  ********************************************************************************/
9
9
 
10
- import type { TransferSaveArgs, TransferUpdateArgs } from '../model-service/args';
10
+ import type { BasedOn } from '../model-service/based-on';
11
11
 
12
12
  /** Get the current state of a single document. The server returns the latest built version. */
13
13
  export interface GetModelDocumentArgs {
@@ -41,24 +41,84 @@ export interface GetProjectForUriArgs {
41
41
  }
42
42
 
43
43
  /**
44
- * Update a document's content. Wire-side projection of the facade's
45
- * {@link TransferUpdateArgs}; structurally identical so the data-server RPC
46
- * handler can forward straight to the in-process `ModelService.update`
47
- * without an args mapping.
44
+ * Update a document the session `clientId` has open. Generic over `TTransfer`
45
+ * so adopters parameterise the structured shape against their grammar's
46
+ * transfer-model overlay; passing a string is always allowed.
48
47
  */
49
- export type TransferUpdateDocumentArgs<TTransfer> = TransferUpdateArgs<TTransfer>;
48
+ export interface TransferUpdateDocumentArgs<TTransfer> {
49
+ /** Document URI. */
50
+ uri: string;
51
+ /** The id of a live session registered on this connection. */
52
+ clientId: string;
53
+ /** The whole structured model root, or its serialised textual form. */
54
+ model: TTransfer | string;
55
+ /**
56
+ * What this write was authored against. A `SnapshotVersion` is compared
57
+ * against the server's current text-document version for `uri` and throws
58
+ * `ConflictError` on mismatch; `'anything'` writes unconditionally.
59
+ *
60
+ * **Required so that an ungated write is a decision rather than an
61
+ * omission.** An optional gate is indistinguishable from a forgotten one at
62
+ * the call site, and a file of twenty writes hides the one that lost the
63
+ * field. Nothing else here can see that, since the defect is an absence.
64
+ */
65
+ basedOn: BasedOn;
66
+ }
67
+
68
+ /** Update a document the session `clientId` has open, then persist it to disk. */
69
+ // eslint-disable-next-line @typescript-eslint/no-empty-object-type
70
+ export interface TransferSaveDocumentArgs<TTransfer> extends TransferUpdateDocumentArgs<TTransfer> {}
71
+
72
+ /** Register a client session on the connection. */
73
+ export interface CreateSessionArgs {
74
+ /** The session's id, minted by the client; unique in the server process while the session is live. */
75
+ clientId: string;
76
+ /** What the participant is; kept as the server session's `label`. */
77
+ label?: string;
78
+ /**
79
+ * A token the client keeps for the session's lifetime. It is no secret: the
80
+ * wire carries no authentication. A later `createSession` for the same id
81
+ * carrying the same token, from any connection, ends the session it names
82
+ * and registers the id afresh, so a client whose connection dropped before
83
+ * the server noticed can register again. Without it the id stays refused
84
+ * until the server notices.
85
+ */
86
+ resumeToken?: string;
87
+ }
88
+
89
+ /** End a client session registered on the connection. */
90
+ export interface CloseSessionArgs {
91
+ clientId: string;
92
+ }
93
+
94
+ /** Create a document that exists nowhere yet, open for the session creating it. */
95
+ export interface CreateModelDocumentArgs {
96
+ uri: string;
97
+ /** The id of a live session registered on this connection. */
98
+ clientId: string;
99
+ /** The document's initial content; it reaches disk with the first save. */
100
+ text: string;
101
+ }
50
102
 
51
- /** Persist a document to disk. Wire-side projection of {@link TransferSaveArgs}. */
52
- export type TransferSaveDocumentArgs<TTransfer> = TransferSaveArgs<TTransfer>;
103
+ /**
104
+ * Write several documents a session has open, all or none. `clientId` is on
105
+ * the set rather than on each update: an id per update would allow a set
106
+ * mixing clients, which the server would have to refuse.
107
+ */
108
+ export interface TransferUpdateDocumentsArgs<TTransfer> {
109
+ /** The id of a live session registered on this connection. */
110
+ clientId: string;
111
+ updates: Omit<TransferUpdateDocumentArgs<TTransfer>, 'clientId'>[];
112
+ }
53
113
 
54
114
  /**
55
115
  * Identifies a per-document watch on the data server. Shared by both
56
116
  * `watchModelDocument` and `unwatchModelDocument` — the `(uri, clientId)`
57
117
  * pair is the watch key, so unwatching names the same watch that was
58
118
  * started. The `clientId` identifies the originator the same way it does
59
- * on facade-side mutations (`TransferUpdateArgs.clientId`,
60
- * `TransferSaveArgs.clientId`): it keys the per-`(uri, clientId)` watch
61
- * bucket so multiple watchers on the same wire stay distinct, AND it lets
119
+ * on the document writes (`TransferUpdateDocumentArgs.clientId`,
120
+ * `TransferSaveDocumentArgs.clientId`): it keys the per-`(uri, clientId)`
121
+ * watch bucket so multiple watchers on the same wire stay distinct, AND it lets
62
122
  * each watcher recognise its own echo on inbound `onDocumentUpdated` events
63
123
  * (the wire shape's `sourceClientId` carries the originating mutation's
64
124
  * `clientId`).
package/src/errors.ts CHANGED
@@ -8,6 +8,20 @@
8
8
  ********************************************************************************/
9
9
 
10
10
  import { ResponseError } from 'vscode-jsonrpc';
11
+ import { defineMessage, type HydraniumMessageData, messageData } from './messages/primitives';
12
+
13
+ /**
14
+ * The catalogue declaration behind {@link ConflictError}'s sentence.
15
+ *
16
+ * Its English must keep containing {@link CONFLICT_ERROR_MESSAGE_MARKER}: the
17
+ * marker is tier 3 of {@link isConflictError}'s ladder, and it matches on text.
18
+ * That tier only ever works untranslated, which is why it is the last resort
19
+ * behind the numeric code rather than the primary check.
20
+ */
21
+ export const STALE_BASED_UPDATE = defineMessage(
22
+ 'hydranium/protocol/stale-based-update',
23
+ 'Stale-based update for {uri}: expected v{expectedVersion}, server is at v{actualVersion}'
24
+ );
11
25
 
12
26
  /**
13
27
  * Application-specific JSON-RPC error code for {@link ConflictError}.
@@ -24,16 +38,16 @@ export const CONFLICT_ERROR_CODE = 1001;
24
38
  * Structured payload carried in {@link ConflictError.data}, and the only place
25
39
  * a post-RPC caller can read the version mismatch from.
26
40
  */
27
- export interface ConflictErrorData {
41
+ export interface ConflictErrorData extends HydraniumMessageData {
28
42
  readonly uri: string;
29
43
  /** The based-on version the caller authored against. */
30
- readonly expected: number;
44
+ readonly expectedVersion: number;
31
45
  /** The server's current text-document version at the time of the throw. */
32
- readonly actual: number;
46
+ readonly actualVersion: number;
33
47
  }
34
48
 
35
49
  /**
36
- * Thrown by `ModelService.update` / `ModelService.save` when the caller-
50
+ * Thrown by a client session's `update` / `save` when the caller-
37
51
  * supplied based-on version no longer matches the server's current text-
38
52
  * document version for the same URI — i.e. the snapshot the caller
39
53
  * authored against has been superseded by an intervening edit.
@@ -46,11 +60,9 @@ export interface ConflictErrorData {
46
60
  * `err.data` (the instance is reconstructed as a generic
47
61
  * `ResponseError`, so subclass getters / fields do not survive).
48
62
  *
49
- * Detection is opt-in via the optional `baseVersion` field on
50
- * `TransferUpdateArgs` / `TransferSaveArgs`; callers that omit the field get
51
- * no gating. This mirrors LSP's `OptionalVersionedTextDocumentIdentifier`
52
- * posture, so headless / CLI / batch tooling with no meaningful based-on
53
- * version can opt out explicitly.
63
+ * Detection is driven by the required `basedOn` field of every write
64
+ * request; a caller with no meaningful based-on version passes
65
+ * `'anything'` and gets no gating.
54
66
  *
55
67
  * Three reasonable adopter recovery strategies:
56
68
  *
@@ -64,18 +76,19 @@ export interface ConflictErrorData {
64
76
  * No auto-retry or auto-merge ships by default.
65
77
  */
66
78
  export class ConflictError extends ResponseError<ConflictErrorData> {
67
- constructor(uri: string, expected: number, actual: number) {
68
- super(CONFLICT_ERROR_CODE, `Stale-based update for ${uri}: expected v${expected}, server is at v${actual}`, {
69
- uri,
70
- expected,
71
- actual
72
- });
79
+ constructor(uri: string, expectedVersion: number, actualVersion: number) {
80
+ const params = { uri, expectedVersion, actualVersion };
81
+ // The identity rides alongside the typed payload rather than replacing
82
+ // it: `isConflictError`'s name check is surface an adopter may bind, so
83
+ // adding the identity widens the payload rather than reshaping it.
84
+ super(CONFLICT_ERROR_CODE, STALE_BASED_UPDATE.format(params), { ...params, ...messageData(STALE_BASED_UPDATE, params) });
73
85
  this.name = 'ConflictError';
74
86
  // ResponseError's constructor calls `Object.setPrototypeOf(this,
75
87
  // ResponseError.prototype)` to keep its own prototype chain intact across
76
88
  // transpilation targets; that resets us to ResponseError, hiding the
77
89
  // ConflictError-specific getters. Restore the prototype here so
78
- // `err.uri` / `.expected` / `.actual` resolve through this class.
90
+ // `err.uri` / `.expectedVersion` / `.actualVersion` resolve through this
91
+ // class.
79
92
  Object.setPrototypeOf(this, ConflictError.prototype);
80
93
  }
81
94
 
@@ -83,15 +96,121 @@ export class ConflictError extends ResponseError<ConflictErrorData> {
83
96
  return this.data!.uri;
84
97
  }
85
98
 
86
- get expected(): number {
87
- return this.data!.expected;
99
+ /**
100
+ * The based-on version the caller authored against.
101
+ *
102
+ * Must not be renamed to `expected`, nor its sibling to `actual`: a test
103
+ * reporter reads an error carrying both as an assertion failure, and
104
+ * vitest's formatter then ASSIGNS to them, which throws on an accessor and
105
+ * replaces the real failure with a `TypeError`.
106
+ */
107
+ get expectedVersion(): number {
108
+ return this.data!.expectedVersion;
88
109
  }
89
110
 
90
- get actual(): number {
91
- return this.data!.actual;
111
+ /** The server's version at the time of the throw. Not `actual` — see {@link expectedVersion}. */
112
+ get actualVersion(): number {
113
+ return this.data!.actualVersion;
92
114
  }
93
115
  }
94
116
 
117
+ /**
118
+ * JSON-RPC code for {@link SessionClosedError}, beside {@link CONFLICT_ERROR_CODE}
119
+ * and for the same reason: the code survives reconstruction, the class does not.
120
+ */
121
+ export const SESSION_CLOSED_ERROR_CODE = 1004;
122
+ /** JSON-RPC code for {@link DocumentNotOpenError}. */
123
+ export const DOCUMENT_NOT_OPEN_ERROR_CODE = 1005;
124
+ /** JSON-RPC code for {@link DuplicateClientIdError}. */
125
+ export const DUPLICATE_CLIENT_ID_ERROR_CODE = 1006;
126
+
127
+ /**
128
+ * Thrown by every call on a client session after it ended, and by an open that
129
+ * was still in flight when its session ended.
130
+ *
131
+ * The message names the client id, so it is addressed to whoever composes the
132
+ * system rather than to an end user, and carries no message identity. A client
133
+ * recognises it after an RPC with {@link isSessionClosedError}.
134
+ */
135
+ export class SessionClosedError extends ResponseError<{ readonly clientId: string }> {
136
+ /** `message` replaces the default sentence, for a caller that knows more than that the session is gone. */
137
+ constructor(clientId: string, message = `Client session ${clientId} is closed`) {
138
+ super(SESSION_CLOSED_ERROR_CODE, message, { clientId });
139
+ this.name = 'SessionClosedError';
140
+ // `ResponseError` resets the prototype to its own; see `ConflictError`.
141
+ Object.setPrototypeOf(this, SessionClosedError.prototype);
142
+ }
143
+
144
+ get clientId(): string {
145
+ return this.data!.clientId;
146
+ }
147
+ }
148
+
149
+ /**
150
+ * Thrown when a client session writes a document it does not have open.
151
+ *
152
+ * A session writes only what it has open, so this is the answer both to a write
153
+ * that never opened and to one whose open was closed underneath it — by the
154
+ * session itself, or by the document being deleted.
155
+ */
156
+ export class DocumentNotOpenError extends ResponseError<{ readonly uri: string; readonly clientId: string }> {
157
+ constructor(uri: string, clientId: string) {
158
+ super(DOCUMENT_NOT_OPEN_ERROR_CODE, `Document ${uri} is not open in client session ${clientId}`, { uri, clientId });
159
+ this.name = 'DocumentNotOpenError';
160
+ Object.setPrototypeOf(this, DocumentNotOpenError.prototype);
161
+ }
162
+
163
+ get uri(): string {
164
+ return this.data!.uri;
165
+ }
166
+
167
+ get clientId(): string {
168
+ return this.data!.clientId;
169
+ }
170
+ }
171
+
172
+ /**
173
+ * Thrown when a client session is started under an id that is already live in
174
+ * the process, or that the framework reserves for itself.
175
+ *
176
+ * Ids are unique process-wide because the id is also the author label on every
177
+ * version and the key a client recognises its own echoes by; two participants
178
+ * sharing one would each take the other's writes for their own.
179
+ */
180
+ export class DuplicateClientIdError extends ResponseError<{ readonly clientId: string }> {
181
+ constructor(clientId: string) {
182
+ super(DUPLICATE_CLIENT_ID_ERROR_CODE, `Client id ${clientId} is already in use`, { clientId });
183
+ this.name = 'DuplicateClientIdError';
184
+ Object.setPrototypeOf(this, DuplicateClientIdError.prototype);
185
+ }
186
+
187
+ get clientId(): string {
188
+ return this.data!.clientId;
189
+ }
190
+ }
191
+
192
+ /**
193
+ * Whether `error` is a {@link SessionClosedError}: by name in-process, by code
194
+ * after an RPC, where it arrives as a plain `ResponseError`.
195
+ */
196
+ export function isSessionClosedError(error: unknown): error is SessionClosedError {
197
+ return hasErrorIdentity(error, 'SessionClosedError', SESSION_CLOSED_ERROR_CODE);
198
+ }
199
+
200
+ /** Whether `error` is a {@link DocumentNotOpenError}; see {@link isSessionClosedError}. */
201
+ export function isDocumentNotOpenError(error: unknown): error is DocumentNotOpenError {
202
+ return hasErrorIdentity(error, 'DocumentNotOpenError', DOCUMENT_NOT_OPEN_ERROR_CODE);
203
+ }
204
+
205
+ /** Whether `error` is a {@link DuplicateClientIdError}; see {@link isSessionClosedError}. */
206
+ export function isDuplicateClientIdError(error: unknown): error is DuplicateClientIdError {
207
+ return hasErrorIdentity(error, 'DuplicateClientIdError', DUPLICATE_CLIENT_ID_ERROR_CODE);
208
+ }
209
+
210
+ function hasErrorIdentity(error: unknown, name: string, code: number): boolean {
211
+ return error instanceof Error && (error.name === name || (error as Partial<ResponseError<unknown>>).code === code);
212
+ }
213
+
95
214
  /** Marker substring present in every {@link ConflictError} message, used by
96
215
  * {@link isConflictError} as a fallback when a transport re-wraps the error
97
216
  * and drops the JSON-RPC code. */
package/src/index.ts CHANGED
@@ -16,6 +16,7 @@
16
16
 
17
17
  export * from './abstract-logger';
18
18
  export * from './client';
19
+ export * from './client-ids';
19
20
  export * from './clock';
20
21
  export * from './data';
21
22
  export * from './browser-runtime';
@@ -24,6 +25,10 @@ export * from './errors';
24
25
  export * from './host-diagnostics';
25
26
  export * from './logger';
26
27
  export * from './latency-collector';
28
+ // The primitives only. The `./messages` subpath additionally enumerates this
29
+ // package's own declarations, which the root barrel already re-exports through
30
+ // the modules that raise them.
31
+ export * from './messages/primitives';
27
32
  export * from './patch-merge';
28
33
  export * from './noop-logger';
29
34
  export * from './observable-value';
@@ -87,8 +87,13 @@ export interface LatencyReport {
87
87
  */
88
88
  export type LatencyRetention = { readonly kind: 'keep-all' } | { readonly kind: 'ring-buffer'; readonly maxSamplesPerMethod: number };
89
89
 
90
- /** Per-method state: retained samples (bounded in ring-buffer mode) plus lifetime totals. */
91
- interface MethodAccumulator {
90
+ /**
91
+ * Per-method state: retained samples (bounded in ring-buffer mode) plus lifetime
92
+ * totals. The mutable tally behind {@link MethodLatency}, which is the derived
93
+ * report row. Held by the `protected` {@link LatencyCollector.durations}, so a
94
+ * subclass recording its own samples has to name it.
95
+ */
96
+ export interface MethodLatencyTally {
92
97
  /** Retained durations for percentile estimation; capped in ring-buffer mode. Order is irrelevant (report sorts). */
93
98
  readonly samples: number[];
94
99
  /** Next slot to overwrite once the ring buffer is full (ring-buffer mode only). */
@@ -119,7 +124,7 @@ function percentile(sortedAscending: readonly number[], percent: number): number
119
124
  * deterministic on a fake clock.
120
125
  */
121
126
  export class LatencyCollector {
122
- protected readonly durations = new Map<string, MethodAccumulator>();
127
+ protected readonly durations = new Map<string, MethodLatencyTally>();
123
128
  protected window: Stopwatch;
124
129
 
125
130
  constructor(
@@ -0,0 +1,36 @@
1
+ /********************************************************************************
2
+ * Copyright (c) 2026 CrossBreeze, EclipseSource and others.
3
+ *
4
+ * This program and the accompanying materials are made available under the
5
+ * terms of the MIT License which is available in the project root.
6
+ *
7
+ * SPDX-License-Identifier: MIT
8
+ ********************************************************************************/
9
+
10
+ /**
11
+ * The message-externalization mechanism, plus every user-facing message
12
+ * `@hydranium/protocol` itself raises.
13
+ *
14
+ * Declarations stay beside their call sites and are re-exported here, so this is
15
+ * enumeration rather than centralization: a code's package segment has to name
16
+ * the package that raises it, and a shared module would make that segment a lie
17
+ * for every message in it. Adding a message therefore touches the file that
18
+ * raises it and this list, and nothing else.
19
+ *
20
+ * A barrel makes every code and English default public API, so renaming a code
21
+ * is a breaking change. That was already true — an adopter's catalogue keys on
22
+ * these codes either way — but it is now in the type system rather than implicit.
23
+ * The English is a fallback, not a contract; the code is the contract.
24
+ */
25
+
26
+ export * from './primitives';
27
+
28
+ export { STALE_BASED_UPDATE } from '../errors';
29
+ export { DATA_SERVER_CONNECT_FAILED, DATA_SERVER_NOT_READY } from '../client/rpc-connection';
30
+ export { DATA_SESSION_RESTORE_FAILED, DATA_SESSION_UNSAVED_LOST } from '../client/data-session';
31
+ export {
32
+ RELAY_REPLAY_FAILED,
33
+ RELAY_TRANSPORT_OPEN_FAILED,
34
+ RELAY_TRANSPORT_READ_FAILED,
35
+ RELAY_TRANSPORT_WRITE_FAILED
36
+ } from '../client/message-relay';