@hydranium/data-server 1.0.0-next.4 → 1.0.0-next.400

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