@hydranium/data-server 1.0.0-next.42 → 1.0.0-next.421

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 (48) hide show
  1. package/README.md +62 -77
  2. package/lib/browser/index.d.ts +10 -0
  3. package/lib/browser/index.d.ts.map +1 -0
  4. package/lib/browser/index.js +15 -0
  5. package/lib/browser/index.js.map +1 -0
  6. package/lib/browser/start-data-server-in-worker.d.ts +23 -0
  7. package/lib/browser/start-data-server-in-worker.d.ts.map +1 -0
  8. package/lib/browser/start-data-server-in-worker.js +29 -0
  9. package/lib/browser/start-data-server-in-worker.js.map +1 -0
  10. package/lib/data-server.d.ts +411 -331
  11. package/lib/data-server.d.ts.map +1 -1
  12. package/lib/data-server.js +728 -530
  13. package/lib/data-server.js.map +1 -1
  14. package/lib/default-diagnostics.d.ts +1 -25
  15. package/lib/default-diagnostics.d.ts.map +1 -1
  16. package/lib/default-diagnostics.js +8 -27
  17. package/lib/default-diagnostics.js.map +1 -1
  18. package/lib/diagnostics-provider.d.ts +1 -1
  19. package/lib/messages/index.d.ts +1 -1
  20. package/lib/messages/index.d.ts.map +1 -1
  21. package/lib/messages/index.js +1 -1
  22. package/lib/messages/index.js.map +1 -1
  23. package/lib/node/node-diagnostics-provider.d.ts +18 -6
  24. package/lib/node/node-diagnostics-provider.d.ts.map +1 -1
  25. package/lib/node/node-diagnostics-provider.js +63 -20
  26. package/lib/node/node-diagnostics-provider.js.map +1 -1
  27. package/lib/testing/data-server-harness.d.ts +27 -14
  28. package/lib/testing/data-server-harness.d.ts.map +1 -1
  29. package/lib/testing/data-server-harness.js +5 -2
  30. package/lib/testing/data-server-harness.js.map +1 -1
  31. package/lib/testing/index.d.ts +1 -0
  32. package/lib/testing/index.d.ts.map +1 -1
  33. package/lib/testing/index.js.map +1 -1
  34. package/package.json +32 -44
  35. package/src/browser/index.ts +15 -0
  36. package/src/browser/start-data-server-in-worker.ts +35 -0
  37. package/src/data-server.ts +909 -592
  38. package/src/default-diagnostics.ts +8 -27
  39. package/src/diagnostics-provider.ts +1 -1
  40. package/src/messages/index.ts +8 -1
  41. package/src/node/node-diagnostics-provider.ts +73 -27
  42. package/src/testing/data-server-harness.ts +44 -25
  43. package/src/testing/index.ts +5 -2
  44. package/lib/default-diagnostics.browser.d.ts +0 -18
  45. package/lib/default-diagnostics.browser.d.ts.map +0 -1
  46. package/lib/default-diagnostics.browser.js +0 -36
  47. package/lib/default-diagnostics.browser.js.map +0 -1
  48. package/src/default-diagnostics.browser.ts +0 -41
@@ -6,8 +6,8 @@
6
6
  *
7
7
  * SPDX-License-Identifier: MIT
8
8
  ********************************************************************************/
9
- import { DisposableCollection, ReferenceSource, type CloseModelArgs, type HydraniumResponseError, type Disposable, type ElementSource, type FindNextNameArgs, type LatencyCollector, type LatencyReport, type OpenModelArgs, type Project, type ReferenceCandidate, type ReferenceContext, type ReferenceRequest, type ReferenceTarget, type Tracer, type TransferDiagnostic, type TransferDocument, type TransferElement } from '@hydranium/protocol';
10
- import { type DataClientProtocol, type DataServerDiagnosticsProtocol, type DataServerProtocol, type DumpServerStateArgs, type StartProfilingArgs, type StopProfilingArgs, type WriteServerHeapSnapshotArgs, type GetModelDocumentArgs, type GetProjectForUriArgs, type TransferSaveDocumentArgs, type WatchModelDocumentArgs, type TransferDocumentUpdatedEvent, type TransferUpdateDocumentArgs } from '@hydranium/protocol/data';
9
+ import { DisposableCollection, type BaseVersionGate, ReferenceSource, type CloseModelArgs, type HydraniumMessageData, type HydraniumResponseError, type CanonicalUri, type Disposable, type ElementSource, type FindNextNameArgs, type LatencyCollector, type LatencyReport, type OpenModelArgs, type Project, type ReferenceCandidate, type ReferenceContext, type ReferenceRequest, type ReferenceTarget, type ModelVersion, type TextState, type Tracer, type TransferDiagnostic, TransferDocument, type TransferCreatedDocument, type TransferSavedDocument, type TransferWatchedDocument, type TransferWrittenDocument, type TransferElement, STALE_BASE_VERSION_SAVE, STALE_BASE_VERSION_UPDATE } from '@hydranium/protocol';
10
+ import { type DataClientProtocol, type DataServerDiagnosticsProtocol, type DataServerProtocol, type DumpServerStateArgs, type StartProfilingArgs, type StopProfilingArgs, type WriteServerHeapSnapshotArgs, type CloseSessionArgs, type CreatedSession, type CreateModelDocumentArgs, type CreateSessionArgs, type GetModelDocumentArgs, type GetProjectForUriArgs, type TransferDeleteDocumentArgs, type TransferPersistDocumentArgs, type TransferSaveDocumentArgs, type WatchModelDocumentArgs, type TransferUpdateDocumentArgs, type TransferUpdateDocumentsArgs } from '@hydranium/protocol/data';
11
11
  /**
12
12
  * Raised when a profiling command arrives with no capture running.
13
13
  *
@@ -21,13 +21,27 @@ export declare const NO_ACTIVE_PROFILE: import("@hydranium/protocol").MessageDef
21
21
  * The JSON-RPC code, unrelated to the catalogue code above: this one is numeric,
22
22
  * survives reconstruction and is what a caller switches on.
23
23
  */
24
- export declare const NO_ACTIVE_PROFILE_CODE = 1002;
24
+ export declare const NO_ACTIVE_PROFILE_CODE: 42002;
25
25
  export declare const noActiveProfileError: () => HydraniumResponseError;
26
+ /**
27
+ * Raised when a reference question's wait for the build exceeds
28
+ * {@link DataServerOptions.referenceSettleTimeoutMs}.
29
+ *
30
+ * A `ResponseError` because a class name does not cross RPC: without the code a
31
+ * wire client cannot tell a wedged build from a reference that resolves to
32
+ * nothing, which is the distinction the wait exists to keep.
33
+ */
34
+ export declare const REFERENCE_SETTLE_TIMEOUT: import("@hydranium/protocol").MessageDefinition<"The model is still being processed; try again in a moment.">;
35
+ /** See {@link NO_ACTIVE_PROFILE_CODE} for why this is separate from the catalogue code. */
36
+ export declare const REFERENCE_SETTLE_TIMEOUT_CODE: 42003;
37
+ /** The wait's length rides in `data` as `elapsedMs`, for the code that reacts rather than the reader. */
38
+ export declare const referenceSettleTimeoutError: (elapsedMs: number) => ResponseError<HydraniumMessageData & {
39
+ readonly elapsedMs: number;
40
+ }>;
26
41
  import type { DataServerDiagnosticsProvider, DataServerProfileCapture } from './diagnostics-provider.js';
27
- import type { ClientTextDocumentChangeEvent, HydraniumLanguageServices, LogNameOptions, ModelService, ProjectChangeEvent, ServerSharedServices, TransferEncoder } from '@hydranium/core';
28
- import type { TextDocument } from 'vscode-languageserver-textdocument';
29
- import { type AstNode, DocumentState, type LangiumDocument, type URI } from '@hydranium/langium';
30
- import type { CancellationToken, MessageConnection } from 'vscode-jsonrpc';
42
+ import type { ClientSession, ClientSessionWriteArgs, HydraniumLanguageServices, LogNameOptions, AstDiagnostic, AstDocument, AstDocumentSavedEvent, EncodedTransferDocument, ModelDeletedEvent, ModelDirtyChangedEvent, ModelService, ModelUpdatedEvent, ProjectChangeEvent, ServerSharedServices, SessionEndCause, TransferEncoder } from '@hydranium/core';
43
+ import { type AstNode, DocumentState, type URI } from '@hydranium/langium';
44
+ import { type MessageConnection, ResponseError } from 'vscode-jsonrpc';
31
45
  /**
32
46
  * Which observable state {@link DataServer.computeDocumentFingerprint} hashes to
33
47
  * de-dup `onDocumentUpdated` emissions.
@@ -39,9 +53,9 @@ import type { CancellationToken, MessageConnection } from 'vscode-jsonrpc';
39
53
  * folded in on a cascade rebuild that leaves the document's own text
40
54
  * untouched. Safe for any adopter whose AST extensions fold derived state
41
55
  * into the transfer projection (the framework norm).
42
- * - `'text-diagnostics'` — the cheaper `getText()` + diagnostics hash. An
43
- * opt-DOWN for adopters that fold no derived state and want to avoid the
44
- * transfer-encode per phase event.
56
+ * - `'text-diagnostics'` — the cheaper parsed-text + diagnostics hash. An
57
+ * opt-DOWN for adopters that fold no derived state and want to avoid
58
+ * stringifying the transfer root per phase event.
45
59
  */
46
60
  export type FingerprintStrategy = 'transfer-document' | 'text-diagnostics';
47
61
  /**
@@ -54,12 +68,14 @@ export interface DataServerOptions extends LogNameOptions {
54
68
  * (`DataClientProtocol.onDocumentUpdated`).
55
69
  *
56
70
  * **Subscription dispatch only** — distinct from the synchronous RPC
57
- * response phase. The lifecycle reads/writes (`getModelDocument` /
58
- * `updateModelDocument` / `saveModelDocument`) settle at the
59
- * integrity-settled landmark (`IntegrityService.SettledState`); a
60
- * read additionally upgrades to `Validated` per call when
61
- * {@link GetModelDocumentArgs.includeDiagnostics} is set. This option
62
- * controls only the async notification phase.
71
+ * response phase. A read (`getModelDocument`) settles at the
72
+ * integrity-settled landmark (`IntegrityService.SettledState`), or at
73
+ * `Validated` when {@link GetModelDocumentArgs.includeDiagnostics} is set.
74
+ * A write (`updateModelDocument` / `updateModelDocuments` /
75
+ * `saveModelDocument`) answers once its document is validated, as a
76
+ * session's write does, and then waits for
77
+ * `ModelService.settleLanguageClient`. This option controls only the async
78
+ * notification phase.
63
79
  *
64
80
  * Default: `DocumentState.Validated` — validation is the last builder
65
81
  * phase and produces the full diagnostic set, so subscription events fired
@@ -78,17 +94,9 @@ export interface DataServerOptions extends LogNameOptions {
78
94
  * a process to inspect — heap snapshot, profile capture, pod memory, server
79
95
  * state.
80
96
  *
81
- * **Defaulted per platform, so most hosts pass nothing.** On Node the default
82
- * is the real implementation; in a browser bundle `package.json`'s `browser`
83
- * field selects a twin whose methods reject, because there is no process to
84
- * inspect. Supply this only to override — a custom implementation, or to say
85
- * explicitly at the call site which one you mean.
86
- *
87
- * It is injected rather than reached for because a static
88
- * `@hydranium/core/node` import on this package's portable entry pulls
89
- * `node:fs`, `node:v8` and `node:perf_hooks` into any browser build, over
90
- * methods a browser cannot call anyway — which is what previously made the
91
- * head unbundleable.
97
+ * Disabled by default on every platform. A host supplies a provider only
98
+ * on connections authorized to inspect the process and write diagnostic
99
+ * artifacts. Session registration does not grant that authorization.
92
100
  */
93
101
  readonly diagnostics?: DataServerDiagnosticsProvider;
94
102
  /**
@@ -97,6 +105,21 @@ export interface DataServerOptions extends LogNameOptions {
97
105
  * state included). See {@link FingerprintStrategy}.
98
106
  */
99
107
  readonly fingerprintStrategy?: FingerprintStrategy;
108
+ /**
109
+ * How long a reference question waits for the build to reach `Linked` before
110
+ * failing with {@link REFERENCE_SETTLE_TIMEOUT_CODE}. Bounded because the
111
+ * wait resolves off a build-phase notification, so a build cancelled below
112
+ * `Linked` with nothing after it leaves the request unanswered for the life
113
+ * of the server.
114
+ *
115
+ * Expiry rejects rather than reading the index anyway: the unsettled index
116
+ * is what the wait keeps the caller away from, so falling through to it on a
117
+ * slow build reinstates the fault — and on a name proposal persists it.
118
+ *
119
+ * Default {@link DataServer.DEFAULT_OPTIONS}, sized for a cold workspace
120
+ * still reaching `Linked` for the first time.
121
+ */
122
+ readonly referenceSettleTimeoutMs?: number;
100
123
  /**
101
124
  * Wire-method namespace for both inbound request handlers and the
102
125
  * outbound notification client proxy. Defaults to
@@ -151,21 +174,60 @@ export interface DataServerOptions extends LogNameOptions {
151
174
  * When supplied, every inbound data-server RPC is timed into this collector
152
175
  * (via the `createRpcProxy` binding) and exposed through
153
176
  * {@link DataServerDiagnosticsProtocol.getLatency}. A head that also runs an
154
- * LSP connection can pass the SAME collector to
155
- * `instrumentLspConnection(connection, latency)` so one report covers both
156
- * heads. Absent by default (no timing overhead).
177
+ * LSP connection can pass the SAME collector through `lspLatencyOptions` to
178
+ * that connection, so one report covers both heads. Absent by default (no
179
+ * timing overhead).
157
180
  */
158
181
  readonly latency?: LatencyCollector;
159
182
  }
160
- /** Fully-resolved variant — every field set, used internally after merging defaults. */
161
- interface ResolvedDataServerOptions {
183
+ /**
184
+ * Fully-resolved variant of {@link DataServerOptions} — every field set, after
185
+ * merging defaults. Returned by the `protected`
186
+ * {@link DataServer.resolveOptions} and held on {@link DataServer.options}, so
187
+ * an adopter changing how defaults resolve has to name it.
188
+ */
189
+ export interface ResolvedDataServerOptions {
162
190
  readonly subscriptionPhase: DocumentState;
163
191
  readonly fingerprintStrategy: FingerprintStrategy;
164
192
  readonly methodNamespace: string;
165
193
  readonly additionalMethods: readonly string[];
166
194
  readonly excludedMethods: readonly string[];
167
- /** Always resolved — to the caller's, or to the platform default. */
195
+ /** Always resolved — to the host's provider or the rejecting default. */
168
196
  readonly diagnostics: DataServerDiagnosticsProvider;
197
+ readonly referenceSettleTimeoutMs: number;
198
+ }
199
+ /**
200
+ * What a {@link DataServer} keeps per canonical URI, in the `protected`
201
+ * {@link DataServer.uriWatchRecords}. A record lives while it has a watcher
202
+ * or a release mark; {@link DataServer.pruneUriWatchRecord} enforces that on
203
+ * every path that removes either, so a record with no watcher has a release
204
+ * broadcast pending. Test the size of {@link DataServerUriWatchRecord.watchers}, not the
205
+ * record's presence, for "watched".
206
+ */
207
+ export interface DataServerUriWatchRecord {
208
+ /** The client ids watching the URI; save, dirty and phase events go out only while it is non-empty, a pending release mark aside. */
209
+ readonly watchers: Set<string>;
210
+ /** Digest of the last emitted state, or of the state a first watch found; see {@link DataServer.dispatchPhaseEvent} for why it de-duplicates, {@link DataServer.computeDocumentFingerprint} for its inputs. */
211
+ fingerprint?: string;
212
+ /**
213
+ * The version {@link DataServerUriWatchRecord.fingerprint} was taken at; an
214
+ * event goes out when either moves. Not {@link DataServerUriWatchRecord.sentVersion}:
215
+ * a first watch sets this and sends nothing, so the next event at its
216
+ * version still carries the manager's attribution.
217
+ */
218
+ fingerprintVersion?: ModelVersion;
219
+ /** Set by {@link DataServer.subscribeToModelReleases} once a release happened: its broadcast, the next phase event, goes out even without a watcher. */
220
+ releaseBroadcastPending?: boolean;
221
+ /**
222
+ * The version of an open document the last event sent was built at. The
223
+ * version sent again goes out as `'rebuilt'` from no client: the manager
224
+ * counts a version delivered only once its `Validated` listeners ran, so a
225
+ * build cancelled after the subscription phase would send it as a change
226
+ * twice. Only while the store has the document open: without it, a
227
+ * document can keep one version through changes of its file, so its events
228
+ * keep the manager's attribution.
229
+ */
230
+ sentVersion?: number;
169
231
  }
170
232
  /**
171
233
  * Typed-RPC protocol head for the hydranium framework. The data-server
@@ -188,15 +250,19 @@ interface ResolvedDataServerOptions {
188
250
  * adopters subclass ONLY when they need to decorate wire returns or
189
251
  * notifications. The usual adoption path is DI rebinds alone.
190
252
  *
253
+ * **`TTransfer` is not checked.** It declares the union of the transfer roots
254
+ * the workspace's languages produce. Which root a document has is known only
255
+ * at runtime, from its language, so a `TTransfer` missing a language compiles.
256
+ *
191
257
  * Lifecycle: the constructor registers framework request handlers (plus
192
258
  * any names supplied via {@link DataServerOptions.additionalMethods}) and
193
259
  * builds the {@link DataClientProtocol} notification proxy on the same
194
260
  * connection in one {@link createRpcProxy} call (binding `this` as its
195
- * `localTarget`) under the configured namespace, and subscribes two listeners
196
- * at the configured phase: a `DocumentBuilder.onDocumentPhase` one dispatching
197
- * per-document `clientProxy.onDocumentUpdated` for watched URIs, and a
198
- * `DocumentBuilder.onBuildPhase` one dispatching a single
199
- * `clientProxy.onDocumentsBuilt` naming the batch's unwatched documents.
261
+ * `localTarget`) under the configured namespace, and follows documents
262
+ * through `ModelService`'s events: at the configured phase, `onModelUpdated`
263
+ * dispatches per-document `clientProxy.onDocumentUpdated` for watched URIs and
264
+ * `onModelsBuilt` a single `clientProxy.onDocumentsBuilt` naming the batch's
265
+ * unwatched documents.
200
266
  *
201
267
  * The data-server requires the full {@link ServerSharedServices}
202
268
  * shape — `HydraniumTextDocuments` for client-attributed updates,
@@ -215,94 +281,43 @@ interface ResolvedDataServerOptions {
215
281
  */
216
282
  export declare class DataServer<TTransfer extends TransferElement, TDiagnostic extends TransferDiagnostic = TransferDiagnostic, TProject extends Project = Project> implements DataServerProtocol<TTransfer, TDiagnostic, TProject>, DataServerDiagnosticsProtocol, Disposable {
217
283
  protected readonly connection: MessageConnection;
218
- protected readonly services: ServerSharedServices<TProject>;
284
+ protected readonly services: ServerSharedServices<TProject, TDiagnostic>;
219
285
  /**
220
286
  * Framework defaults, exposed so an adopter can spread them when
221
287
  * extending rather than restate a value the framework may change.
222
288
  */
223
- static readonly DEFAULT_OPTIONS: Required<Pick<DataServerOptions, 'subscriptionPhase'>>;
289
+ static readonly DEFAULT_OPTIONS: Required<Pick<DataServerOptions, 'subscriptionPhase' | 'referenceSettleTimeoutMs'>>;
224
290
  protected readonly options: ResolvedDataServerOptions;
225
- /** Subscription bookkeeping: URI → set of clientIds that subscribed for that URI. */
226
- protected readonly subscriptions: Map<string, Set<string>>;
291
+ /** This connection's {@link DataServerUriWatchRecord} per canonical URI; see there for when a record lives. */
292
+ protected readonly uriWatchRecords: Map<string, DataServerUriWatchRecord>;
227
293
  /**
228
- * Open-document bookkeeping: URI → set of clientIds that opened it over THIS
229
- * connection.
230
- *
231
- * Kept because the document store releases a client's hold only from an
232
- * explicit close, and a client that dies without closing would otherwise keep
233
- * the document open forever — resident, and with its last-close revert
234
- * suppressed. The store has no notion of which connection a clientId reached
235
- * it over, so the connection-scoped set has to live here; teaching it a client
236
- * identity is the more robust and much larger alternative.
294
+ * Per client id, the key each URI it watched resolved to when it watched.
295
+ * An unwatch looks the key up here: once a file is gone, a symlink to it
296
+ * no longer resolves to the key the watch is under.
297
+ */
298
+ protected readonly watchKeys: Map<string, Map<string, string>>;
299
+ /**
300
+ * The position of the last update or deletion event sent, which each
301
+ * such event carries, and a watch's answer carries as of the moment it
302
+ * took whether its document exists: an event past it was sent after.
303
+ */
304
+ protected eventSequence: number;
305
+ /**
306
+ * The live client sessions this connection registered, by client id. A
307
+ * document request carrying one of these ids acts as that session; one
308
+ * carrying any other id fails. A session leaves once it ends, so a
309
+ * connection that registers many over its life does not accumulate them.
310
+ */
311
+ protected readonly clientSessions: Map<string, ClientSession<AstNode, AstDiagnostic, TTransfer, object>>;
312
+ /**
313
+ * Typed client proxy — sends `data-server/on*` notifications back over the same wire.
314
+ * The proxy sends any `on[A-Z]*` name other than `onDidOpenConnection` and
315
+ * `onDidCloseConnection`, for which it returns its own events, so a subclass
316
+ * with notifications of its own narrows only the type:
317
+ * `declare protected readonly clientProxy: TheirClient`.
237
318
  */
238
- protected readonly openedDocuments: Map<string, Set<string>>;
239
- /** Typed client proxy — sends `data-server/on*` notifications back over the same wire. */
240
319
  protected readonly clientProxy: DataClientProtocol<TTransfer, TDiagnostic, TProject>;
241
320
  protected readonly disposables: DisposableCollection;
242
- /**
243
- * Snapshot of the most recent `DocumentBuilder.onUpdate` event. Drives
244
- * `reason` discrimination on outbound `onDocumentUpdated` notifications:
245
- * a URI in the `changed` list emits `'changed'`, otherwise `'rebuilt'`
246
- * (cascade rebuild from a dependent URI's change). The same mechanism
247
- * `AstDocumentManager.onUpdate` uses on the LSP side, so reason fidelity
248
- * stays consistent between heads. The `deleted` half is read by
249
- * {@link dispatchDeleteEvents} rather than by the reason discrimination,
250
- * a deletion travelling on its own channel.
251
- */
252
- protected lastBuildUpdate?: {
253
- changed: readonly URI[];
254
- deleted: readonly URI[];
255
- };
256
- /**
257
- * Per-URI hash of the last emitted (text + diagnostics) state,
258
- * used by {@link dispatchPhaseEvent} to suppress duplicate
259
- * `onDocumentUpdated` notifications for rebuilds that produce no
260
- * observable change since the last emit.
261
- *
262
- * Two scenarios routinely produce such rebuilds:
263
- * 1. **Refresh-triggered rebuilds.** When a second client attaches to a
264
- * document already open in another client,
265
- * `HydraniumTextDocuments.refreshContent` fires `onDidChangeContent`
266
- * purely to re-trigger the build pipeline — the text and diagnostics
267
- * are identical to the prior emit.
268
- * 2. **Cascade rebuilds with no diagnostic delta.** Langium rebuilds a
269
- * document when a dependency changes; if the rebuild produces the
270
- * same diagnostics, there is nothing new to communicate to subscribers.
271
- *
272
- * Without this filter, both scenarios reach subscribers as wire-side
273
- * `'changed'` events. A subscriber that interprets `'changed'` as
274
- * "another client wrote new content" and resets its in-memory root to
275
- * the server view then misreads the spurious event as a concurrent
276
- * third-party write and loses the user's edits.
277
- *
278
- * Initialised on {@link watchModelDocument} to the current
279
- * document fingerprint so the FIRST phase event after a fresh
280
- * subscription is also de-duplicated against the state subscribers
281
- * obtained via `getModelDocument` — they do not need a redundant phase
282
- * notification for the state they just fetched.
283
- *
284
- * Cleared in {@link unwatchModelDocument} when the last
285
- * subscriber for a URI leaves so memory does not accumulate.
286
- *
287
- * Stored as a cyrb53 hex digest (16 chars per URI) rather than the raw
288
- * text + diagnostics serialisation so the memory cost is constant in
289
- * document size. See {@link computeDocumentFingerprint} for the inputs.
290
- */
291
- protected readonly lastEmittedFingerprint: Map<string, string>;
292
- /**
293
- * URIs whose LAST client just closed. The update handler rebuilds such a
294
- * document from its disk content (discarding unsaved in-session edits),
295
- * but {@link dispatchPhaseEvent} gates on the subscription map — and the
296
- * last close typically also removed the last watcher, so consumers that
297
- * only ever fetch via `getModelDocument` would keep showing the
298
- * discarded state forever. Marked on the last-close transition (see
299
- * {@link subscribeToTextDocumentCloses}) and consumed by
300
- * {@link dispatchPhaseEvent}, which broadcasts the following rebuild's
301
- * phase event even without a subscription — de-duplicated against
302
- * {@link lastEmittedFingerprint} where an entry survives, so a close
303
- * whose disk state equals the last emitted state stays silent.
304
- */
305
- protected readonly pendingRevertBroadcasts: Set<string>;
306
321
  protected readonly tracer: Tracer;
307
322
  /** The in-flight interactive profile capture, held between {@link startProfiling} and {@link stopProfiling}. */
308
323
  protected activeProfile?: DataServerProfileCapture;
@@ -314,85 +329,125 @@ export declare class DataServer<TTransfer extends TransferElement, TDiagnostic e
314
329
  protected readonly encoder: TransferEncoder<TDiagnostic>;
315
330
  /**
316
331
  * In-process workspace facade — the lifecycle delegate `get` / `update` / `save` go through.
317
- * The facade's AstDocument diagnostic shape is intentionally typed `unknown` here: adopters
318
- * carry LSP-shape diagnostics in their AstDocument (e.g. an adopter's LSP-shape diagnostic type)
319
- * while the wire shape stays `TDiagnostic extends TransferDiagnostic`. The encoder's
320
- * `astDocumentToTransferDocument` accepts both shapes (wire-shape or LSP-shape) and projects
321
- * to wire shape on the return — see `TransferEncoder.astDocumentToTransferDocument`.
332
+ * Its documents carry the AST-layer {@link AstDiagnostic}, never the wire `TDiagnostic`:
333
+ * {@link encoder} converts one into the other on the way out.
322
334
  */
323
- protected readonly modelService: ModelService<AstNode, unknown, TTransfer>;
324
- constructor(connection: MessageConnection, services: ServerSharedServices<TProject>, options?: DataServerOptions);
335
+ protected readonly modelService: ModelService<AstNode, AstDiagnostic, TTransfer>;
336
+ constructor(connection: MessageConnection, services: ServerSharedServices<TProject, TDiagnostic>, options?: DataServerOptions);
325
337
  /**
326
338
  * Release everything the constructor wired up — the bound protocol
327
- * handlers and every listener — and clear the subscription map and the
328
- * per-URI emission-fingerprint cache, so a long-lived shared services
329
- * bundle does not retain per-connection memory after the connection
330
- * closes. Also closes every document still open over this connection (see
331
- * {@link closeOpenDocuments}), which is the SHARED store's state rather than
332
- * this server's and so outlives the connection unless released here.
333
- *
334
- * Idempotent: subsequent calls are no-ops. Self-fires on
335
- * `connection.onClose` so adopters who don't hold a reference still
336
- * get per-connection cleanup; adopters that DO hold a reference may
337
- * call `dispose()` directly for early teardown.
338
- */
339
- dispose(): void;
340
- openModelDocument(args: OpenModelArgs): Promise<TransferDocument<TTransfer, TDiagnostic>>;
339
+ * handlers and every listener — and clear {@link uriWatchRecords}, so a
340
+ * long-lived shared services bundle does not retain per-connection memory
341
+ * after the connection closes. Also ends every session this connection registered, which closes
342
+ * every document it has open: the SHARED store's state rather than this
343
+ * server's, which outlives the connection unless released here.
344
+ *
345
+ * Idempotent: subsequent calls are no-ops. Runs by itself when the
346
+ * connection closes, so adopters who don't hold a reference still get
347
+ * per-connection cleanup; adopters that DO hold a reference may call
348
+ * `dispose()` directly for early teardown. The sessions end with `cause`:
349
+ * `'closed'` releases every document whose last open they close at once,
350
+ * and `'lost'`, the connection's own close, lets each wait out the release
351
+ * grace.
352
+ */
353
+ dispose(cause?: SessionEndCause): void;
354
+ createSession(args: CreateSessionArgs): Promise<CreatedSession>;
355
+ /**
356
+ * The epoch this server numbers versions in, which every registration and
357
+ * document names: the text store's, so every connection to the server
358
+ * answers the same one.
359
+ */
360
+ protected get epoch(): string;
361
+ /**
362
+ * Refuse a write whose base version is numbered in another epoch, as a
363
+ * restarted server's predecessor numbered it. Versions start afresh with
364
+ * each epoch, so the session's gate would take the version for text the
365
+ * writer never saw. Checked once the session is found, before the open
366
+ * check and every other check of its documents.
367
+ */
368
+ protected assertEpoch(uri: string, gate: BaseVersionGate, message?: typeof STALE_BASE_VERSION_UPDATE | typeof STALE_BASE_VERSION_SAVE): void;
369
+ /** End a session this connection registered. */
370
+ closeSession(args: CloseSessionArgs): Promise<void>;
371
+ /** End `session`, registered here under `clientId`, with `cause`, and drop its watches on this connection. */
372
+ protected endSession(clientId: string, session: ClientSession<AstNode, AstDiagnostic, TTransfer>, cause?: SessionEndCause): void;
373
+ protected dropWatches(clientId: string): void;
374
+ createModelDocument(args: CreateModelDocumentArgs): Promise<TransferCreatedDocument<TTransfer, TDiagnostic>>;
375
+ updateModelDocuments(args: TransferUpdateDocumentsArgs<TTransfer>): Promise<TransferWrittenDocument<TTransfer, TDiagnostic>[]>;
376
+ /**
377
+ * The session write a wire write request carries. Only the fields a session
378
+ * takes: a field an adopter adds to a request reaches the session only
379
+ * through an override of this.
380
+ */
381
+ protected toSessionWrite(request: Omit<TransferUpdateDocumentArgs<TTransfer>, 'clientId'>): ClientSessionWriteArgs<TTransfer>;
382
+ /**
383
+ * The session this connection registered under `clientId`, which every
384
+ * document request acts as. An id that is not one fails with the
385
+ * closed-session code: opening or writing under it would leave an open that
386
+ * no session end ever closes.
387
+ */
388
+ protected requireSession(clientId: string): ClientSession<AstNode, AstDiagnostic, TTransfer>;
389
+ openModelDocument(args: Pick<OpenModelArgs, 'uri' | 'clientId' | 'options'>): Promise<TransferDocument<TTransfer, TDiagnostic>>;
390
+ /**
391
+ * The snapshot a session's open or create answers with. When the read
392
+ * fails, `rollback` undoes the open this call made before the failure is
393
+ * rethrown: the caller sees no open, so nothing on its side would ever close
394
+ * it.
395
+ */
396
+ protected openedSnapshot(uri: string, rollback?: () => Promise<void>): Promise<TransferDocument<TTransfer, TDiagnostic>>;
341
397
  closeModelDocument(args: CloseModelArgs): Promise<void>;
398
+ getModelDocument(args: GetModelDocumentArgs): Promise<TransferDocument<TTransfer, TDiagnostic>>;
399
+ updateModelDocument(args: TransferUpdateDocumentArgs<TTransfer>): Promise<TransferWrittenDocument<TTransfer, TDiagnostic>>;
400
+ saveModelDocument(args: TransferSaveDocumentArgs<TTransfer>): Promise<TransferSavedDocument<TTransfer, TDiagnostic>>;
401
+ persistModelDocument(args: TransferPersistDocumentArgs): Promise<TransferSavedDocument<TTransfer, TDiagnostic>>;
342
402
  /**
343
- * Drop the recorded hold for `(uri, clientId)` so {@link dispose} does not
344
- * close it a second time. Idempotent.
403
+ * Delete the document through the session, then release the session's
404
+ * watch of it, as {@link closeModelDocument} does. Released only after the
405
+ * delete: one that fails leaves the session its open and its watch. Other
406
+ * sessions' watches survive, as for any deletion.
345
407
  */
346
- protected forgetOpenDocument(uri: string, clientId: string): void;
408
+ deleteModelDocument(args: TransferDeleteDocumentArgs): Promise<void>;
347
409
  /**
348
- * Close every document still open over this connection, for the clients that
349
- * opened it here.
410
+ * Record a watch for `(uri, clientId)` in {@link uriWatchRecords}.
411
+ * Subsequent phase events on `uri` fan out to the wired
412
+ * `clientProxy.onDocumentUpdated`. The bidirectional pattern means the
413
+ * event channel is the client notification surface, not a returned
414
+ * handle.
350
415
  *
351
- * The document store releases a per-URI hold only from an explicit close, so
352
- * without this a client that dies mid-session keeps its documents open for the
353
- * lifetime of the process: `isOpenInAnyClient` stays true, the document stays
354
- * resident, and the last-close revert never runs. A long-lived multi-client
355
- * head is the configuration where a dead client is normal rather than
356
- * exceptional, so the leak accumulates there.
357
- *
358
- * Runs from {@link dispose}, which is synchronous, so each close is fired and
359
- * its failure swallowed — a teardown must not reject, and a URI whose close
360
- * fails is no worse off than it was before this drain existed.
361
- */
362
- protected closeOpenDocuments(): void;
363
- getModelDocument(args: GetModelDocumentArgs): Promise<TransferDocument<TTransfer, TDiagnostic>>;
364
- updateModelDocument(args: TransferUpdateDocumentArgs<TTransfer>): Promise<TransferDocument<TTransfer, TDiagnostic>>;
365
- saveModelDocument(args: TransferSaveDocumentArgs<TTransfer>): Promise<TransferDocument<TTransfer, TDiagnostic>>;
366
- /**
367
- * Record a watch for `(uri, clientId)`. Subsequent phase events on `uri`
368
- * fan out to the wired `clientProxy.onDocumentUpdated`. The
369
- * bidirectional pattern means the event channel is the client
370
- * notification surface, not a returned handle — this method only
371
- * registers the URI in the dispatch table.
416
+ * Also baselines the URI's emission fingerprint (see
417
+ * {@link dispatchPhaseEvent}) to the document's current state when the
418
+ * first watcher for the URI registers. This guarantees that any phase event firing immediately after
419
+ * the watch with no observable change is suppressed — watchers obtain
420
+ * initial state via `getModelDocument` (or {@link openModelDocument}) and
421
+ * do not need a redundant phase notification for that same state.
372
422
  *
373
- * Also baselines the per-URI emission fingerprint (see
374
- * {@link lastEmittedFingerprint}) to the document's current state when
375
- * the first watcher for the URI registers. This guarantees that any
376
- * phase event firing immediately after the watch with no observable
377
- * change is suppressed — watchers obtain initial state via
378
- * `getModelDocument` (or {@link openModelDocument}) and do not need a
379
- * redundant phase notification for that same state.
423
+ * Answers once the document is loaded as a read loads it, with the key
424
+ * events name it by and whether a document exists, taken after the watch
425
+ * is in place and the load, so an event sent while it loads is older.
380
426
  */
381
- watchModelDocument(args: WatchModelDocumentArgs): Promise<void>;
427
+ watchModelDocument(args: WatchModelDocumentArgs): Promise<TransferWatchedDocument>;
382
428
  /**
383
429
  * Remove a watch for `(uri, clientId)` previously created by
384
430
  * {@link watchModelDocument}. Idempotent — unwatching twice is a no-op.
385
- * Dispatch for `uri` stops once no watchers remain, at which point the
386
- * per-URI emission fingerprint is also cleared so the next first-watch
387
- * re-baselines against the then-current document state rather than a
388
- * stale snapshot from the previous watch.
431
+ * Dispatch for `uri` stops once no watchers remain, and the emission
432
+ * fingerprint goes with the last watcher (see {@link pruneUriWatchRecord}).
433
+ *
434
+ * A URI the client watched is unwatched under the key it resolved to then,
435
+ * from {@link watchKeys}, which still holds once its file is gone.
389
436
  */
390
437
  unwatchModelDocument(args: WatchModelDocumentArgs): Promise<void>;
391
438
  /**
392
- * Canonicalise a URI string for use as a subscription / fingerprint
393
- * map key, via the shared `DocumentUriPolicy`. Callers may send
394
- * non-canonical URIs (drive-letter casing, percent-encoding differences,
395
- * or a symlink path) over the wire; the dispatch side keys by
439
+ * Drop what `uri` no longer needs: the
440
+ * {@link DataServerUriWatchRecord.fingerprint} once no client watches it,
441
+ * and the whole record once it holds no
442
+ * {@link DataServerUriWatchRecord.releaseBroadcastPending} mark either.
443
+ * Every path that removes a watcher or consumes a mark ends here.
444
+ */
445
+ protected pruneUriWatchRecord(uri: string): void;
446
+ /**
447
+ * Canonicalise a URI string for use as a {@link uriWatchRecords} key, via the
448
+ * shared `DocumentUriPolicy`. Callers may send non-canonical URIs
449
+ * (drive-letter casing, percent-encoding differences, or a symlink path)
450
+ * over the wire; the dispatch side keys by
396
451
  * `document.uri.toString()` from `LangiumDocuments`, so writer keys must
397
452
  * canonicalise to the same form or events silently fail to deliver.
398
453
  * Routing through the seam (rather than a bare `UriUtils.normalize`)
@@ -402,6 +457,7 @@ export declare class DataServer<TTransfer extends TransferElement, TDiagnostic e
402
457
  * LSP head resolves.
403
458
  *
404
459
  * Adopters can still override for head-specific URI policy by subclassing.
460
+ * The result keys watches only; a document is looked up by its own URI.
405
461
  */
406
462
  protected canonicalKey(uri: string): string;
407
463
  getProjects(): Promise<readonly TProject[]>;
@@ -414,8 +470,25 @@ export declare class DataServer<TTransfer extends TransferElement, TDiagnostic e
414
470
  * subclass.
415
471
  */
416
472
  waitForReady(): Promise<void>;
473
+ /**
474
+ * Settle the build before a reference question is answered from the index.
475
+ *
476
+ * A query issued right after a model update otherwise races the rebuild and
477
+ * reads an index missing the symbols it asks about. The cost is not confined
478
+ * to this call: a scope built inside that window is cached, and the build's
479
+ * remaining documents link against it.
480
+ *
481
+ * Waits the source document specifically, but ONLY when one is loaded at
482
+ * that URI: a synthetic source can address a URI with no document (a
483
+ * directory URI, typically), where a per-URI `waitUntil` throws "No document
484
+ * found". Falls back to a global settle, matching the id-based
485
+ * `ElementSource` path.
486
+ *
487
+ * Bounded by {@link DataServerOptions.referenceSettleTimeoutMs}.
488
+ */
489
+ protected awaitReferencesLinked(source: ReferenceSource): Promise<void>;
417
490
  findReferenceCandidates(ctx: ReferenceContext): Promise<ReferenceCandidate[]>;
418
- resolveReference(ref: ReferenceRequest): Promise<ReferenceTarget<TTransfer> | undefined>;
491
+ resolveReference<TElement extends TransferElement = TransferElement>(ref: ReferenceRequest): Promise<ReferenceTarget<TElement> | undefined>;
419
492
  findNextName(args: FindNextNameArgs): Promise<string>;
420
493
  /**
421
494
  * Resolve the per-language `references` services for a reference source.
@@ -426,38 +499,17 @@ export declare class DataServer<TTransfer extends TransferElement, TDiagnostic e
426
499
  */
427
500
  protected resolveReferenceServices(source: ReferenceSource): HydraniumLanguageServices['references'];
428
501
  /**
429
- * Pick the language that owns a reference source, in order:
430
- *
431
- * 1. A URI-bearing source ({@link isDocumentSource}/{@link isSyntheticSource})
432
- * whose URI resolves to a registered language routes by URI.
433
- * 2. A single-language workspace always routes to that one language — so
434
- * single-language adopters never reach the steps below, and never pay
435
- * for them.
436
- * 3. An {@link isElementSource} source carries no URI, so in a
437
- * multi-language workspace it is routed via the document that holds the
438
- * element (see {@link findElementDocumentUri}).
439
- * 4. A source carrying an AST type is routed by that type when exactly one
440
- * registered grammar can produce it (see
441
- * {@link resolveReferenceLanguageByType}, over the registry's own type
442
- * index). This is what resolves a create-element flow's synthetic source
443
- * on a bare directory URI without asking the adopter.
444
- * 5. Anything still unresolved falls to {@link fallbackReferenceLanguage},
445
- * which is adopter policy.
446
- */
447
- protected resolveReferenceLanguage(source: ReferenceSource): HydraniumLanguageServices | undefined;
448
- /**
449
- * Route a reference source by the AST type it carries — a
450
- * {@link isSyntheticSource}'s `type` (the transient node being created) or an
451
- * {@link isElementSource}'s optional narrowing `type`.
502
+ * Pick the language that owns a reference source: the registry's
503
+ * `getLanguageFor` over the source's declared language, URI and AST type,
504
+ * with an {@link isElementSource} routed by the document that holds the
505
+ * element (see {@link findElementDocumentUri}) before its type, and
506
+ * {@link fallbackReferenceLanguage}, adopter policy, last.
452
507
  *
453
- * Answers only when EXACTLY ONE registered grammar can produce the type.
454
- * Several can when the type comes from a grammar both import, and then the
455
- * type genuinely does not identify a language — that is a fall-through to
456
- * adopter policy, not a coin toss. Note this asks which grammar can *produce*
457
- * the type, not which mentions it: a grammar that merely cross-references a
458
- * type can never hold a node of it.
508
+ * An unregistered declared language falls through rather than failing: the
509
+ * id crosses the wire, so a client built against a head with one more
510
+ * grammar would otherwise lose queries the other signals answer.
459
511
  */
460
- protected resolveReferenceLanguageByType(source: ReferenceSource): HydraniumLanguageServices | undefined;
512
+ protected resolveReferenceLanguage(source: ReferenceSource): HydraniumLanguageServices | undefined;
461
513
  /**
462
514
  * Locate the document that holds the element an {@link ElementSource}
463
515
  * addresses, via the index's O(1) name lookup — `name` is the qualified
@@ -465,15 +517,14 @@ export declare class DataServer<TTransfer extends TransferElement, TDiagnostic e
465
517
  * disambiguates names that repeat across types (honouring grammar
466
518
  * subtyping through `AstReflection.isSubtype`).
467
519
  *
468
- * Only reached on the multi-language, name-based path (step 3 of
469
- * {@link resolveReferenceLanguage}); single-language adopters return at
470
- * step 2.
520
+ * Only reached in a multi-language workspace, once the declared language
521
+ * and the URI have abstained.
471
522
  *
472
523
  * Abstains when the name matches elements in more than one DOCUMENT — the
473
524
  * index spans every language and is filled in build order, so "the
474
- * first match" would be file-watch order rather than an answer. Step 3
475
- * then falls through to the type-based step 4, which abstains on ties
476
- * in the same way, and finally to adopter policy.
525
+ * first match" would be file-watch order rather than an answer. Routing
526
+ * then falls through to the element's type, which abstains on ties in the
527
+ * same way, and finally to adopter policy.
477
528
  */
478
529
  protected findElementDocumentUri(source: ElementSource): URI | undefined;
479
530
  /**
@@ -488,26 +539,65 @@ export declare class DataServer<TTransfer extends TransferElement, TDiagnostic e
488
539
  * to.
489
540
  */
490
541
  protected fallbackReferenceLanguage(_source: ReferenceSource): HydraniumLanguageServices | undefined;
542
+ /**
543
+ * Whether `error`, from waiting on `uri`'s document, means that `uri` has
544
+ * no document: a URI with neither a file nor text builds nothing, and
545
+ * Langium's wait after the build rejects for want of one, with a
546
+ * `ServerCancelled` response error. Any other failure, such as a read
547
+ * that fails before a document is registered, a cancelled wait or a
548
+ * `ReentrantWriteLockError`, is the caller's to see.
549
+ */
550
+ protected isMissingDocument(error: unknown, uri: string): boolean;
491
551
  /**
492
552
  * Build a {@link TransferDocument} envelope from the current document state,
493
553
  * delegating root + diagnostic encoding to {@link encoder} (see
494
- * `TransferEncoder.toTransferDocument` for the walk).
495
- *
496
- * The encoder field's generic-map binding is widened to
497
- * `Record<string, TransferElement>` at the framework-default level, and an
498
- * adopter supplying a typed-overlay encoder narrows the runtime shape to
499
- * its wire types. The cast on the return is where that invariant — the
500
- * adopter's `TTransfer` matches its encoder's overlay — is asserted, at a
501
- * single boundary point rather than spread across the callers.
554
+ * `TransferEncoder.toTransferDocument` for the walk). `fingerprint` is the
555
+ * caller's {@link computeDocumentFingerprint} of that same state, which
556
+ * spares hashing it twice.
557
+ */
558
+ protected envelope(uri: URI, fingerprint?: string): TransferDocument<TTransfer, TDiagnostic>;
559
+ /**
560
+ * The transfer document a request answers with for `astDocument`, its model
561
+ * hashed and the text stamped on it by {@link withServerState}. Every
562
+ * document a request answers with goes through here, so none goes out
563
+ * without them.
564
+ */
565
+ protected encodeDocument(astDocument: AstDocument<AstNode, AstDiagnostic>): TransferDocument<TTransfer, TDiagnostic>;
566
+ /**
567
+ * The project a client receives for `project`, unchanged by default. Every
568
+ * project a request answers with or a change notification carries goes
569
+ * through here, so a field derived for clients cannot miss one path. The
570
+ * result crosses as JSON, so a value a client reads goes in a data field,
571
+ * not a getter.
572
+ */
573
+ protected encodeProject(project: TProject): TProject;
574
+ /**
575
+ * `encoded` with `hash` on its model and the text the server holds for it:
576
+ * the store's while it holds the document, the build's otherwise. The text
577
+ * is read when the document is sent rather than kept with the build: a save
578
+ * changes `text.dirty` without a rebuild, and the store's text moves on before
579
+ * the build that follows it.
580
+ */
581
+ protected withServerState(encoded: EncodedTransferDocument<TransferElement, TDiagnostic>, hash: string): TransferDocument<TTransfer, TDiagnostic>;
582
+ /** Per session registered on this connection, the highest of its numbered writes of `uri` that `version` holds. */
583
+ protected heldWrites(uri: string, version: number): Record<string, number>;
584
+ /**
585
+ * The text the server holds for `uri`, as every envelope and a watch's
586
+ * answer carry it: the store's while it holds the document, the build's
587
+ * otherwise, and none for a document it has neither of.
502
588
  */
503
- protected envelope(uri: URI): TransferDocument<TTransfer, TDiagnostic>;
589
+ protected serverTextState(uri: string): TextState | undefined;
504
590
  /**
505
- * Subscribe one listener at the configured {@link DataServerOptions.subscriptionPhase}.
506
- * The listener dispatches subscription events for every matching URI. A
507
- * single listener (rather than one per subscription) keeps the cost flat
508
- * regardless of subscriber count.
591
+ * The text a build read for a document the store never held, which is
592
+ * clean: the store holds every text a client gave it.
509
593
  */
510
- protected subscribeToDocumentBuilder(): void;
594
+ protected builtTextState(uri: string): TextState | undefined;
595
+ /**
596
+ * Follow every document at the configured
597
+ * {@link DataServerOptions.subscriptionPhase}, once per connection rather
598
+ * than once per watch, so the cost stays flat in the number of watches.
599
+ */
600
+ protected subscribeToModelUpdates(): void;
511
601
  /**
512
602
  * Report the documents that reached {@link DataServerOptions.subscriptionPhase}
513
603
  * and that NOBODY on this
@@ -528,7 +618,7 @@ export declare class DataServer<TTransfer extends TransferElement, TDiagnostic e
528
618
  *
529
619
  * Payload-free on purpose: URIs only, so a client re-reads what it displays
530
620
  * rather than being handed transfer documents it did not ask for. That is the
531
- * property the subscription map protects, and it is preserved here by
621
+ * property the watcher gate protects, and it is preserved here by
532
622
  * carrying no document rather than by gating the message.
533
623
  *
534
624
  * Quiet in the common case. Editing a document that an editor has open leaves
@@ -536,22 +626,15 @@ export declare class DataServer<TTransfer extends TransferElement, TDiagnostic e
536
626
  * dependents produces nothing at all, and workspace initialisation produces
537
627
  * nothing because it does not build to this phase. The ceiling is a
538
628
  * whole-workspace rebuild at the subscription phase: one message, URIs only.
539
- *
540
- * The URI is canonicalised for the same reason the subscription map is keyed
541
- * that way, and is untested for the same reason as its twin in
542
- * {@link dispatchDeleteEvents}: the builder reports URIs out of its own
543
- * store, so a non-canonical one cannot be produced without a fixture
544
- * asserting a shape the real system never emits.
545
629
  */
546
- protected dispatchBuiltEvent(built: readonly LangiumDocument[]): void;
630
+ protected dispatchBuiltEvent(built: readonly CanonicalUri[]): void;
547
631
  /**
548
- * Subscribe to the universal save event on `HydraniumTextDocuments` so a
549
- * single `onDocumentSaved` wire notification fires for ANY save of a
550
- * subscribed URI — regardless of whether the save originated from the
551
- * data-server's RPC `saveModelDocument`, the LSP head's text-editor save,
552
- * or any other client writing through `notifyDidSaveTextDocument`.
632
+ * Follow every save so a single `onDocumentSaved` wire notification fires
633
+ * for ANY save of a subscribed URI — regardless of whether the save
634
+ * originated from the data-server's RPC `saveModelDocument`, the LSP head's
635
+ * text-editor save, or any other client.
553
636
  *
554
- * Architectural symmetry with {@link subscribeToDocumentBuilder}: every
637
+ * Architectural symmetry with {@link subscribeToModelUpdates}: every
555
638
  * subscribed client sees every state change to documents they care about,
556
639
  * regardless of which client triggered it. Firing `onDocumentSaved` only
557
640
  * from the data-server's own RPC path is a bug, not an optimisation: an
@@ -559,20 +642,42 @@ export declare class DataServer<TTransfer extends TransferElement, TDiagnostic e
559
642
  * clients, which never clear their dirty state.
560
643
  */
561
644
  protected subscribeToTextDocumentSaves(): void;
562
- /**
563
- * Mark the last-close transition per URI (see
564
- * {@link pendingRevertBroadcasts}). The listener consults
565
- * `isOpenInAnyClient` AFTER the store decremented the closing client's
566
- * hold, so a `false` answer means this close was the last one.
567
- */
568
- protected subscribeToTextDocumentCloses(): void;
645
+ /** Relay each change of a document's dirty state; see {@link dispatchDirtyEvent}. */
646
+ protected subscribeToDirtyChanges(): void;
647
+ /**
648
+ * Send a dirty flip to the connection, gated on the URI's watchers as
649
+ * {@link dispatchSaveEvent} is: the answer at any one moment travels on
650
+ * every document sent, so a client that watches nothing reads it there.
651
+ */
652
+ protected dispatchDirtyEvent(event: ModelDirtyChangedEvent): void;
653
+ /**
654
+ * Mark each document the store releases, so {@link dispatchPhaseEvent}
655
+ * broadcasts the build that follows even without a watcher. By default
656
+ * that build reverts the document to its disk content, discarding unsaved
657
+ * in-session edits, and the last close typically also
658
+ * removed the last watcher: without the broadcast, a consumer that only
659
+ * ever fetches via `getModelDocument` keeps showing the discarded state.
660
+ * The broadcast is de-duplicated against the fingerprint while a watcher
661
+ * holds one, so a close whose disk state equals the last emitted state
662
+ * stays silent; with no watcher there is no fingerprint, and every release
663
+ * build is sent. The first build after the release consumes the mark, and
664
+ * goes out as the release unless it is stamped past the version a client
665
+ * opened the document at again: a client's write or an integrity repair
666
+ * that rides it keeps its author.
667
+ *
668
+ * A release, not the close itself: a document whose last client lost its
669
+ * connection is released only once the release grace runs out, or when
670
+ * another client opens it meanwhile, and not at all when a client lost
671
+ * from it opens it again within its own grace.
672
+ */
673
+ protected subscribeToModelReleases(): void;
569
674
  /**
570
675
  * Fan out a deletion for each removed URI, to EVERY client on the connection
571
676
  * rather than only to the ones watching that URI.
572
677
  *
573
678
  * **Deliberately ungated, where {@link dispatchPhaseEvent} and
574
679
  * {@link dispatchSaveEvent} are gated.** Those two carry a built document and
575
- * fire on every build, so the subscription map is what keeps bandwidth
680
+ * fire on every build, so the watcher gate is what keeps bandwidth
576
681
  * proportional to what a client asked for. A deletion is neither: it is one
577
682
  * URI, it is rare, and it reports the workspace's STRUCTURE rather than a
578
683
  * document's content. Gating it forces any consumer that displays the
@@ -581,35 +686,28 @@ export declare class DataServer<TTransfer extends TransferElement, TDiagnostic e
581
686
  * no way to run: its workspace lives behind the head. A client that does not
582
687
  * care filters on the URI, which costs it a comparison.
583
688
  *
584
- * The precedent is the last-close revert broadcast (see
585
- * {@link pendingRevertBroadcasts}), where the same judgement was already made
689
+ * The precedent is the release broadcast (see
690
+ * {@link subscribeToModelReleases}), where the same judgement was already made
586
691
  * in the other direction: a transition that matters enough is delivered
587
692
  * without a subscription.
588
693
  *
589
- * Runs from the `DocumentBuilder.onUpdate` listener rather than from a phase
590
- * listener, which is the only place a deletion is observable: `update`
591
- * removes the document before deriving the rebuild set, so it is never built.
592
- * That ordering also puts this notification ahead of the `'rebuilt'` events
593
- * for the dependents whose references the deletion just broke.
594
- *
595
- * The `deleted` list arrives already expanded to concrete document URIs —
596
- * `deleteDocuments` resolves a directory URI to the documents beneath it — so
597
- * no caller has to handle a directory here.
694
+ * A deletion is announced before the build that follows it, so this goes
695
+ * out ahead of the `'rebuilt'` events for the dependents whose references
696
+ * the deletion just broke.
598
697
  *
599
- * Per-URI derived state is dropped for the same reason it is dropped
600
- * anywhere: it describes a document that no longer exists.
601
- * {@link lastEmittedFingerprint} in particular can outlive its subscriptions
602
- * through the last-close revert path — left behind, it is adopted as the
603
- * baseline by the next {@link watchModelDocument} and suppresses the first
604
- * emit after the file returns with its previous content.
698
+ * The URI's fingerprint and release mark are dropped: they describe a
699
+ * document that no longer exists. A kept fingerprint is adopted as the
700
+ * baseline and suppresses the first emit after the file returns with its
701
+ * previous content.
605
702
  *
606
- * The subscription itself SURVIVES: a recreated file resumes delivering to
607
- * the same watchers with no re-subscription, and a client that answers the
608
- * deletion by closing releases the watch through `closeModelDocument` anyway.
703
+ * The watchers SURVIVE: a recreated file resumes delivering to them with no
704
+ * re-subscription, and a client that answers the deletion by closing
705
+ * releases the watch through `closeModelDocument` anyway. A session that
706
+ * deleted the document has its own released by {@link deleteModelDocument}.
609
707
  */
610
- protected dispatchDeleteEvents(deleted: readonly URI[]): void;
611
- /** Fan out a save event for the document's URI, gated by the subscription map. */
612
- protected dispatchSaveEvent(event: ClientTextDocumentChangeEvent<TextDocument>): void;
708
+ protected dispatchDeleteEvent(event: ModelDeletedEvent): void;
709
+ /** Fan out a save event for the document's URI, gated on the URI's watchers. */
710
+ protected dispatchSaveEvent(event: AstDocumentSavedEvent<AstNode>): void;
613
711
  /**
614
712
  * Fan out a phase event for the document's URI by calling
615
713
  * `clientProxy.onDocumentUpdated`. The proxy lowers the call to a
@@ -619,52 +717,43 @@ export declare class DataServer<TTransfer extends TransferElement, TDiagnostic e
619
717
  * out to multiple local subscribers with an `Emitter<T>` — the
620
718
  * framework deliberately does NOT promise multi-listener semantics.
621
719
  *
622
- * The dispatch is guarded by two filters:
623
- * 1. **Subscription map**: events for URIs no subscriber registered for
624
- * are NOT sent over the wire (bandwidth scales with subscribed URIs,
625
- * not phase events).
626
- * 2. **Emission fingerprint**: events for rebuilds that produce no
627
- * observable change since the last emit are suppressed. See
628
- * {@link lastEmittedFingerprint} for the rationale.
629
- */
630
- protected dispatchPhaseEvent(document: LangiumDocument, cancelToken: CancellationToken): void;
631
- /**
632
- * Fingerprint of the document's observable state, used to de-dup
633
- * `onDocumentUpdated` emissions. The {@link FingerprintStrategy} option
634
- * selects what is hashed (default `'transfer-document'` — see the type), and
635
- * {@link additionalFingerprintInputs} folds in any extra adopter signal.
636
- *
637
- * The default `'transfer-document'` strategy goes through the encoder's
638
- * {@link TransferEncoder.toTransferDocument}, which is cached per build —
639
- * so within one phase event the fingerprint and the subsequently-emitted
640
- * `envelope` share a single encode walk.
720
+ * An event for a URI no client watches is NOT sent over the wire, so
721
+ * bandwidth scales with watched URIs rather than with phase events; a
722
+ * pending release mark is the exception (see
723
+ * {@link subscribeToModelReleases}).
724
+ *
725
+ * An event for a rebuild with no observable change since the last emit is
726
+ * suppressed against the URI's fingerprint and the version it was taken at;
727
+ * a new version with the same fingerprint goes out with the same
728
+ * `model.hash`, so a watcher still learns the version. Such rebuilds are routine: a
729
+ * second client attaching to an open document makes
730
+ * `HydraniumTextDocuments.refreshContent` fire `onDidChangeContent` purely
731
+ * to re-trigger the build, and Langium rebuilds a document when a
732
+ * dependency changes even if its diagnostics come out the same. Sent at a
733
+ * version this head has not sent, they reach watchers as `'changed'`, and a
734
+ * watcher that reads `'changed'` as another client's write and resets its
735
+ * root to the server view loses the user's edits. The first {@link watchModelDocument} baselines the
736
+ * fingerprint, so the first event after a watch is de-duplicated against
737
+ * the state the watcher just fetched; it goes with the last watcher, so the
738
+ * next first watch re-baselines rather than adopting a stale digest. A
739
+ * digest keeps its memory constant in document size; see
740
+ * {@link computeDocumentFingerprint} for the inputs.
741
+ */
742
+ protected dispatchPhaseEvent(event: ModelUpdatedEvent<AstNode>): void;
743
+ /**
744
+ * Fingerprint of the snapshot `root` and its encoding `encoded`, used to
745
+ * de-dup `onDocumentUpdated` emissions and sent as every document's
746
+ * `model.hash`, so it must not depend on the version or on live state. The
747
+ * {@link FingerprintStrategy} option selects what is hashed (default
748
+ * `'transfer-document'` — see the type).
749
+ *
750
+ * {@link TransferEncoder.toTransferDocument} is cached per build, so within
751
+ * one phase event the fingerprint and the subsequently-emitted `envelope`
752
+ * share a single encode walk.
641
753
  *
642
754
  * Wrapped in {@link Tracer.time} against {@link FINGERPRINT_LOG_AFTER_MS}.
643
755
  */
644
- protected computeDocumentFingerprint(document: LangiumDocument): string;
645
- /**
646
- * Extra inputs folded into {@link computeDocumentFingerprint} alongside the
647
- * chosen {@link FingerprintStrategy}. Default: none. Override to contribute a
648
- * signal that lives outside the document's text / root / diagnostics — each
649
- * entry need only be stable across equivalent emissions and
650
- * JSON-serialisable.
651
- */
652
- protected additionalFingerprintInputs(_document: LangiumDocument): readonly unknown[];
653
- /**
654
- * Discriminate the reason for a phase-event-driven update notification.
655
- * Uses the most recent `DocumentBuilder.onUpdate` snapshot:
656
- * - URI in the `changed` list → `'changed'` (the URI was passed to
657
- * `documentBuilder.update(changed, deleted)`, which spans `didChange`
658
- * text-document events and programmatic `update([uri], [])` calls).
659
- * - Otherwise → `'rebuilt'` (cascade re-derivation: this URI was rebuilt
660
- * because something it depends on changed; its own text wasn't flagged).
661
- *
662
- * `'saved'` is NOT emitted here — saves take the dedicated
663
- * `DataClientProtocol.onDocumentSaved` channel, and adopters wanting a
664
- * unified stream synthesise it in their bridge layer. A deletion is not a
665
- * reason at all; see {@link dispatchDeleteEvents}.
666
- */
667
- protected resolveUpdateReason(uri: URI): TransferDocumentUpdatedEvent<TTransfer, TDiagnostic>['reason'];
756
+ protected computeDocumentFingerprint(root: AstNode, encoded: EncodedTransferDocument<TransferElement, TDiagnostic>): string;
668
757
  /**
669
758
  * Subscribe to the project tier's change channel and re-fan registry
670
759
  * diffs into per-project wire notifications. The internal
@@ -685,19 +774,11 @@ export declare class DataServer<TTransfer extends TransferElement, TDiagnostic e
685
774
  /**
686
775
  * Fan one internal {@link ProjectChangeEvent} out to per-project wire
687
776
  * notifications. Each `removed` entry pairs the id with the pre-removal
688
- * snapshot needed for the `'removed'` wire payload.
777
+ * snapshot needed for the `'removed'` wire payload. A project whose
778
+ * {@link encodeProject} throws is logged and skipped, so the rest of the
779
+ * batch still reaches the client.
689
780
  */
690
781
  protected dispatchProjectChangeEvent(event: ProjectChangeEvent<TProject>): void;
691
- /**
692
- * Resolve the wire-level `sourceClientId` for `document`'s events — the client
693
- * that authored its current version, from the version-author history on
694
- * `HydraniumTextDocuments`. The protocol-level counterpart of the internal
695
- * `AstDocumentManager.getAuthor`: a framework-internal rebuild has no author,
696
- * so this surfaces the {@link UNKNOWN_CLIENT_ID} presentation default. Adopters
697
- * that rebuild through non-text-document channels override to derive a
698
- * source id of their own.
699
- */
700
- protected resolveSourceClientId(document: LangiumDocument): string;
701
782
  dumpServerState(args: DumpServerStateArgs): Promise<string>;
702
783
  writeHeapSnapshot(args: WriteServerHeapSnapshotArgs): Promise<string>;
703
784
  dumpPodMemory(): Promise<string>;
@@ -707,5 +788,4 @@ export declare class DataServer<TTransfer extends TransferElement, TDiagnostic e
707
788
  /** Resolve a partial options object into a fully-defaulted form. */
708
789
  protected resolveOptions(partial: DataServerOptions): ResolvedDataServerOptions;
709
790
  }
710
- export {};
711
791
  //# sourceMappingURL=data-server.d.ts.map