@openfairygui/backend 0.5.0 → 0.6.1

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.
@@ -0,0 +1,550 @@
1
+ import { commitUamProjectSourcePaths, materializeUamProject, validateUamProject } from '@openfairygui/core/uam';
2
+ import type { BackendDiagnostic } from '../contracts.js';
3
+ import { ProjectWriteTransactionError } from '../runtime/contracts.js';
4
+ import { normalizeComparablePath, type PathPolicyViolationError, validateSaveTarget } from '../path-policy.js';
5
+ import type {
6
+ BackendCapabilityUnavailableError,
7
+ BackendFileSystem,
8
+ BackendResult,
9
+ BackendSessionSnapshot,
10
+ InProcessLockConflictError,
11
+ MaterializeSessionInput,
12
+ MaterializeSessionSnapshot,
13
+ MaterializeValidationFailedError,
14
+ MaterializeWriteFailedError,
15
+ SavePartialFailureError,
16
+ SaveSessionInput,
17
+ SessionNotFoundError,
18
+ SessionStaleWriteError,
19
+ UamFidelityUnsupportedError,
20
+ } from '../runtime/contracts.js';
21
+ import type { CacheService } from './cache-service.js';
22
+ import { type BackendContext, type BackendSessionState, failure, success } from './context.js';
23
+ import type { EventService } from './event-service.js';
24
+ import type { SessionOperationQueue } from './session-operation-queue.js';
25
+ import { createSessionNotFoundError, createStaleWriteError, toSessionSnapshot } from './session-utils.js';
26
+ import { writeSessionProject } from './session-project-writer.js';
27
+
28
+ function createCapabilityUnavailableError(message: string): BackendCapabilityUnavailableError {
29
+ return {
30
+ code: 'capability_unavailable',
31
+ message,
32
+ capability: 'fileSystem',
33
+ requiredAdapter: 'BackendFileSystem',
34
+ };
35
+ }
36
+
37
+ function createUamFidelityUnsupportedError(session: BackendSessionState): UamFidelityUnsupportedError {
38
+ return {
39
+ code: 'uam_fidelity_unsupported',
40
+ message: 'The source project contains formal properties that the current UAM cannot preserve.',
41
+ sessionId: session.sessionId,
42
+ canonicalPathKey: session.canonicalPathKey,
43
+ };
44
+ }
45
+
46
+ function validationDiagnostics(sessionProject: Parameters<typeof validateUamProject>[0]): BackendDiagnostic[] {
47
+ const issues = validateUamProject(sessionProject);
48
+ return issues.map((issue) => ({
49
+ code: 'materialize_validation_failed',
50
+ message: issue.message,
51
+ severity: 'error',
52
+ path: issue.path,
53
+ operationKind: 'materializeSession',
54
+ }));
55
+ }
56
+
57
+ function toMaterializeSnapshot(
58
+ session: BackendSessionState,
59
+ capabilities: Parameters<typeof toSessionSnapshot>[1],
60
+ input: {
61
+ reason?: string;
62
+ writtenPaths: string[];
63
+ skippedPaths: string[];
64
+ diagnostics: BackendDiagnostic[];
65
+ },
66
+ ): MaterializeSessionSnapshot {
67
+ return {
68
+ ...toSessionSnapshot(session, capabilities),
69
+ mode: 'fullProject',
70
+ reason: input.reason,
71
+ materializeRevision: session.revision,
72
+ saveRevision: session.lastSavedRevision,
73
+ writtenPaths: [...input.writtenPaths],
74
+ skippedPaths: [...input.skippedPaths],
75
+ diagnostics: input.diagnostics.map((diagnostic) => ({ ...diagnostic })),
76
+ };
77
+ }
78
+
79
+ function storageCanonicalTarget(input: NonNullable<MaterializeSessionInput['storage']>): {
80
+ fileSystem: BackendFileSystem;
81
+ fairyPath: string;
82
+ canonicalProjectPath: string;
83
+ canonicalPathKey: string;
84
+ } {
85
+ const canonicalProjectPath = input.canonicalProjectPath ?? (input.fileSystem.dirname(input.fairyPath) || '.');
86
+ return {
87
+ fileSystem: input.fileSystem,
88
+ fairyPath: input.fairyPath,
89
+ canonicalProjectPath,
90
+ canonicalPathKey: input.canonicalPathKey ?? normalizeComparablePath(canonicalProjectPath),
91
+ };
92
+ }
93
+
94
+ export class PersistenceService {
95
+ public constructor(
96
+ private readonly context: Pick<BackendContext, 'capabilities'> & {
97
+ sessions: Pick<BackendContext['sessions'], 'get' | 'reserve'>;
98
+ },
99
+ private readonly cacheService: CacheService,
100
+ private readonly eventService: EventService,
101
+ private readonly sessionOperations: SessionOperationQueue,
102
+ ) {}
103
+
104
+ public async saveSession(
105
+ input: SaveSessionInput,
106
+ ): Promise<
107
+ BackendResult<
108
+ BackendSessionSnapshot | MaterializeSessionSnapshot,
109
+ | SessionNotFoundError
110
+ | SessionStaleWriteError
111
+ | SavePartialFailureError
112
+ | UamFidelityUnsupportedError
113
+ | MaterializeValidationFailedError
114
+ | MaterializeWriteFailedError
115
+ | PathPolicyViolationError
116
+ | InProcessLockConflictError
117
+ | BackendCapabilityUnavailableError
118
+ >
119
+ > {
120
+ if (input.force === true || input.mode === 'materializeCleanSession') {
121
+ return this.materializeSession({
122
+ sessionId: input.sessionId,
123
+ expectedRevision: input.expectedRevision,
124
+ targetPath: input.targetPath,
125
+ fileSystem: input.fileSystem,
126
+ mode: 'fullProject',
127
+ reason: 'force_save',
128
+ });
129
+ }
130
+ const captured = { ...input };
131
+ return this.sessionOperations.run(captured.sessionId, () => this.saveSessionExclusive(captured));
132
+ }
133
+
134
+ private finishSuccessfulSave(session: BackendSessionState): void {
135
+ session.lastSavedRevision = session.revision;
136
+ session.dirty = false;
137
+ const cacheEntry = this.cacheService.refreshSession(session);
138
+ this.eventService.emit({
139
+ kind: 'save.completed',
140
+ sessionId: session.sessionId,
141
+ canonicalPathKey: session.canonicalPathKey,
142
+ revision: session.revision,
143
+ });
144
+ this.eventService.emit({
145
+ kind: 'cache.updated',
146
+ sessionId: session.sessionId,
147
+ canonicalPathKey: session.canonicalPathKey,
148
+ revision: session.revision,
149
+ cacheRevision: cacheEntry.revision,
150
+ });
151
+ }
152
+
153
+ private async saveSessionExclusive(
154
+ input: SaveSessionInput,
155
+ ): Promise<
156
+ BackendResult<
157
+ BackendSessionSnapshot | MaterializeSessionSnapshot,
158
+ | SessionNotFoundError
159
+ | SessionStaleWriteError
160
+ | SavePartialFailureError
161
+ | UamFidelityUnsupportedError
162
+ | MaterializeValidationFailedError
163
+ | MaterializeWriteFailedError
164
+ | PathPolicyViolationError
165
+ | InProcessLockConflictError
166
+ | BackendCapabilityUnavailableError
167
+ >
168
+ > {
169
+ const startedAt = Date.now();
170
+ const session = this.context.sessions.get(input.sessionId);
171
+ if (!session || session.closed) {
172
+ return failure('authoring', startedAt, createSessionNotFoundError(input.sessionId));
173
+ }
174
+ const fileSystem = session.fileSystem ?? input.fileSystem;
175
+ if (!fileSystem) {
176
+ return failure(
177
+ 'authoring',
178
+ startedAt,
179
+ createCapabilityUnavailableError('saveSession requires an injected BackendFileSystem adapter.'),
180
+ toSessionSnapshot(session, this.context.capabilities),
181
+ {
182
+ sessionId: session.sessionId,
183
+ revision: session.revision,
184
+ },
185
+ );
186
+ }
187
+ if (input.expectedRevision !== undefined && input.expectedRevision !== session.revision) {
188
+ return failure(
189
+ 'authoring',
190
+ startedAt,
191
+ createStaleWriteError(session, input.expectedRevision),
192
+ toSessionSnapshot(session, this.context.capabilities),
193
+ {
194
+ sessionId: session.sessionId,
195
+ revision: session.revision,
196
+ },
197
+ );
198
+ }
199
+ const targetViolation = await validateSaveTarget(fileSystem, session.fairyPath, input.targetPath);
200
+ if (targetViolation) {
201
+ return failure(
202
+ 'authoring',
203
+ startedAt,
204
+ targetViolation,
205
+ toSessionSnapshot(session, this.context.capabilities),
206
+ {
207
+ sessionId: session.sessionId,
208
+ revision: session.revision,
209
+ },
210
+ );
211
+ }
212
+ if (!session.dirty) {
213
+ return success('authoring', startedAt, toSessionSnapshot(session, this.context.capabilities), {
214
+ sessionId: session.sessionId,
215
+ revision: session.revision,
216
+ });
217
+ }
218
+ if (session.uamFidelity === 'unsupported') {
219
+ return failure(
220
+ 'authoring',
221
+ startedAt,
222
+ createUamFidelityUnsupportedError(session),
223
+ toSessionSnapshot(session, this.context.capabilities),
224
+ {
225
+ sessionId: session.sessionId,
226
+ revision: session.revision,
227
+ },
228
+ );
229
+ }
230
+
231
+ const committedPaths: string[] = [];
232
+ const failedPaths: string[] = [];
233
+ this.eventService.emit({
234
+ kind: 'save.started',
235
+ sessionId: session.sessionId,
236
+ canonicalPathKey: session.canonicalPathKey,
237
+ revision: session.revision,
238
+ });
239
+ try {
240
+ await writeSessionProject({
241
+ fileSystem,
242
+ document: materializeUamProject(session.project),
243
+ fairyPath: session.fairyPath,
244
+ staleSourceFiles: [...session.pendingStaleSourceFiles.values()],
245
+ staleResourceFolders: [...session.pendingStaleResourceFolders.values()],
246
+ staleBranchDirectories: [...session.pendingStaleBranchDirectories.values()],
247
+ writtenPaths: committedPaths,
248
+ failedPaths,
249
+ });
250
+ session.fileSystem ??= fileSystem;
251
+ session.pendingStaleSourceFiles.clear();
252
+ session.pendingStaleResourceFolders.clear();
253
+ session.pendingStaleBranchDirectories.clear();
254
+ commitUamProjectSourcePaths(session.project);
255
+ this.finishSuccessfulSave(session);
256
+ return success('authoring', startedAt, toSessionSnapshot(session, this.context.capabilities), {
257
+ sessionId: session.sessionId,
258
+ revision: session.revision,
259
+ });
260
+ } catch (error) {
261
+ this.cacheService.invalidateSession(session);
262
+ this.eventService.emit({
263
+ kind: 'save.failed',
264
+ sessionId: session.sessionId,
265
+ canonicalPathKey: session.canonicalPathKey,
266
+ revision: session.revision,
267
+ });
268
+ return failure(
269
+ 'authoring',
270
+ startedAt,
271
+ {
272
+ code: 'save_partial_failure',
273
+ message: error instanceof Error ? error.message : String(error),
274
+ sessionId: session.sessionId,
275
+ canonicalPathKey: session.canonicalPathKey,
276
+ attemptedRevision: session.revision,
277
+ lastSavedRevision: session.lastSavedRevision,
278
+ committedPaths,
279
+ failedPaths,
280
+ diskMayBePartiallyUpdated: !ProjectWriteTransactionError.is(error) || error.diskMayBePartiallyUpdated,
281
+ ...(ProjectWriteTransactionError.is(error) && error.recoveryPaths.length ? { recoveryPaths: error.recoveryPaths } : {}),
282
+ },
283
+ toSessionSnapshot(session, this.context.capabilities),
284
+ {
285
+ sessionId: session.sessionId,
286
+ revision: session.revision,
287
+ },
288
+ );
289
+ }
290
+ }
291
+
292
+ public async materializeSession(
293
+ input: MaterializeSessionInput,
294
+ ): Promise<
295
+ BackendResult<
296
+ MaterializeSessionSnapshot,
297
+ | SessionNotFoundError
298
+ | SessionStaleWriteError
299
+ | UamFidelityUnsupportedError
300
+ | MaterializeValidationFailedError
301
+ | MaterializeWriteFailedError
302
+ | PathPolicyViolationError
303
+ | InProcessLockConflictError
304
+ | BackendCapabilityUnavailableError
305
+ >
306
+ > {
307
+ const captured = { ...input, storage: input.storage && { ...input.storage } };
308
+ return this.sessionOperations.run(captured.sessionId, () => this.materializeSessionExclusive(captured));
309
+ }
310
+
311
+ private async materializeSessionExclusive(
312
+ input: MaterializeSessionInput,
313
+ ): Promise<
314
+ BackendResult<
315
+ MaterializeSessionSnapshot,
316
+ | SessionNotFoundError
317
+ | SessionStaleWriteError
318
+ | UamFidelityUnsupportedError
319
+ | MaterializeValidationFailedError
320
+ | MaterializeWriteFailedError
321
+ | PathPolicyViolationError
322
+ | InProcessLockConflictError
323
+ | BackendCapabilityUnavailableError
324
+ >
325
+ > {
326
+ const startedAt = Date.now();
327
+ const session = this.context.sessions.get(input.sessionId);
328
+ if (!session || session.closed) {
329
+ return failure('authoring', startedAt, createSessionNotFoundError(input.sessionId));
330
+ }
331
+ if (input.expectedRevision !== undefined && input.expectedRevision !== session.revision) {
332
+ return failure(
333
+ 'authoring',
334
+ startedAt,
335
+ createStaleWriteError(session, input.expectedRevision),
336
+ toSessionSnapshot(session, this.context.capabilities),
337
+ {
338
+ sessionId: session.sessionId,
339
+ revision: session.revision,
340
+ },
341
+ );
342
+ }
343
+
344
+ const storageTarget = input.storage ? storageCanonicalTarget(input.storage) : null;
345
+ const fileSystem = storageTarget?.fileSystem ?? input.fileSystem ?? session.fileSystem;
346
+ if (!fileSystem) {
347
+ return failure(
348
+ 'authoring',
349
+ startedAt,
350
+ createCapabilityUnavailableError('materializeSession requires an injected BackendFileSystem adapter.'),
351
+ toSessionSnapshot(session, this.context.capabilities),
352
+ {
353
+ sessionId: session.sessionId,
354
+ revision: session.revision,
355
+ },
356
+ );
357
+ }
358
+
359
+ const fairyPath = storageTarget?.fairyPath ?? session.fairyPath;
360
+ if (session.lockHeld && (fileSystem !== session.fileSystem || fairyPath !== session.fairyPath
361
+ || (storageTarget && (storageTarget.canonicalPathKey !== session.canonicalPathKey
362
+ || storageTarget.canonicalProjectPath !== session.canonicalProjectPath)))) {
363
+ return failure('authoring', startedAt, {
364
+ code: 'path_policy_violation',
365
+ message: 'A locked file-backed session must keep its opened storage binding.',
366
+ policy: 'save_target',
367
+ attemptedPath: fairyPath,
368
+ allowedPath: session.fairyPath,
369
+ }, toSessionSnapshot(session, this.context.capabilities), { sessionId: session.sessionId, revision: session.revision });
370
+ }
371
+ const targetViolation = await validateSaveTarget(fileSystem, fairyPath, input.targetPath);
372
+ if (targetViolation) {
373
+ return failure(
374
+ 'authoring',
375
+ startedAt,
376
+ targetViolation,
377
+ toSessionSnapshot(session, this.context.capabilities),
378
+ {
379
+ sessionId: session.sessionId,
380
+ revision: session.revision,
381
+ },
382
+ );
383
+ }
384
+
385
+ if (session.uamFidelity === 'unsupported') {
386
+ return failure(
387
+ 'authoring',
388
+ startedAt,
389
+ createUamFidelityUnsupportedError(session),
390
+ toSessionSnapshot(session, this.context.capabilities),
391
+ {
392
+ sessionId: session.sessionId,
393
+ revision: session.revision,
394
+ },
395
+ );
396
+ }
397
+
398
+ const diagnostics = validationDiagnostics(session.project);
399
+ if (diagnostics.length > 0) {
400
+ const error: MaterializeValidationFailedError = {
401
+ code: 'materialize_validation_failed',
402
+ message: `UAM materialize validation failed with ${diagnostics.length} issue(s).`,
403
+ sessionId: session.sessionId,
404
+ canonicalPathKey: session.canonicalPathKey,
405
+ issueCount: diagnostics.length,
406
+ diagnostics,
407
+ };
408
+ return failure('authoring', startedAt, error, toSessionSnapshot(session, this.context.capabilities), {
409
+ sessionId: session.sessionId,
410
+ revision: session.revision,
411
+ diagnostics,
412
+ });
413
+ }
414
+
415
+ let document: ReturnType<typeof materializeUamProject>;
416
+ try {
417
+ document = materializeUamProject(session.project);
418
+ } catch (error) {
419
+ const diagnosticsFromError: BackendDiagnostic[] = [
420
+ {
421
+ code: 'materialize_validation_failed',
422
+ message: error instanceof Error ? error.message : String(error),
423
+ severity: 'error',
424
+ operationKind: 'materializeSession',
425
+ },
426
+ ];
427
+ return failure(
428
+ 'authoring',
429
+ startedAt,
430
+ {
431
+ code: 'materialize_validation_failed',
432
+ message: error instanceof Error ? error.message : String(error),
433
+ sessionId: session.sessionId,
434
+ canonicalPathKey: session.canonicalPathKey,
435
+ issueCount: diagnosticsFromError.length,
436
+ diagnostics: diagnosticsFromError,
437
+ },
438
+ toSessionSnapshot(session, this.context.capabilities),
439
+ {
440
+ sessionId: session.sessionId,
441
+ revision: session.revision,
442
+ diagnostics: diagnosticsFromError,
443
+ },
444
+ );
445
+ }
446
+
447
+ const writtenPaths: string[] = [];
448
+ const failedPaths: string[] = [];
449
+ const skippedPaths: string[] = [];
450
+ const reservation = storageTarget ? this.context.sessions.reserve(session.sessionId, storageTarget) : null;
451
+ if (reservation && 'code' in reservation) {
452
+ return failure('authoring', startedAt, reservation, toSessionSnapshot(session, this.context.capabilities), {
453
+ sessionId: session.sessionId,
454
+ revision: session.revision,
455
+ });
456
+ }
457
+ this.eventService.emit({
458
+ kind: 'save.started',
459
+ sessionId: session.sessionId,
460
+ canonicalPathKey: storageTarget?.canonicalPathKey ?? session.canonicalPathKey,
461
+ revision: session.revision,
462
+ });
463
+ try {
464
+ const isSessionStorageTarget = fileSystem === session.fileSystem && fairyPath === session.fairyPath;
465
+ await writeSessionProject({
466
+ fileSystem,
467
+ document,
468
+ fairyPath,
469
+ staleSourceFiles: isSessionStorageTarget ? [...session.pendingStaleSourceFiles.values()] : [],
470
+ staleResourceFolders: isSessionStorageTarget ? [...session.pendingStaleResourceFolders.values()] : [],
471
+ staleBranchDirectories: isSessionStorageTarget
472
+ ? [...session.pendingStaleBranchDirectories.values()]
473
+ : [],
474
+ writtenPaths,
475
+ failedPaths,
476
+ });
477
+ if (isSessionStorageTarget) {
478
+ session.pendingStaleSourceFiles.clear();
479
+ session.pendingStaleResourceFolders.clear();
480
+ session.pendingStaleBranchDirectories.clear();
481
+ }
482
+ if (storageTarget && !isSessionStorageTarget) {
483
+ session.pendingStaleSourceFiles.clear();
484
+ session.pendingStaleResourceFolders.clear();
485
+ session.pendingStaleBranchDirectories.clear();
486
+ }
487
+ if (isSessionStorageTarget || storageTarget) commitUamProjectSourcePaths(session.project);
488
+ reservation?.commit(session);
489
+ this.finishSuccessfulSave(session);
490
+ return success(
491
+ 'authoring',
492
+ startedAt,
493
+ toMaterializeSnapshot(session, this.context.capabilities, {
494
+ reason: input.reason,
495
+ writtenPaths,
496
+ skippedPaths,
497
+ diagnostics: [],
498
+ }),
499
+ {
500
+ sessionId: session.sessionId,
501
+ revision: session.revision,
502
+ },
503
+ );
504
+ } catch (error) {
505
+ const diagnosticsFromError: BackendDiagnostic[] = [
506
+ {
507
+ code: 'write_failed',
508
+ message: error instanceof Error ? error.message : String(error),
509
+ severity: 'error',
510
+ path: failedPaths[0],
511
+ operationKind: 'materializeSession',
512
+ },
513
+ ];
514
+ this.cacheService.invalidateSession(session);
515
+ this.eventService.emit({
516
+ kind: 'save.failed',
517
+ sessionId: session.sessionId,
518
+ canonicalPathKey: session.canonicalPathKey,
519
+ revision: session.revision,
520
+ diagnostics: diagnosticsFromError,
521
+ });
522
+ return failure(
523
+ 'authoring',
524
+ startedAt,
525
+ {
526
+ code: 'write_failed',
527
+ message: error instanceof Error ? error.message : String(error),
528
+ sessionId: session.sessionId,
529
+ canonicalPathKey: session.canonicalPathKey,
530
+ attemptedRevision: session.revision,
531
+ lastSavedRevision: session.lastSavedRevision,
532
+ writtenPaths,
533
+ failedPaths,
534
+ skippedPaths,
535
+ diagnostics: diagnosticsFromError,
536
+ diskMayBePartiallyUpdated: !ProjectWriteTransactionError.is(error) || error.diskMayBePartiallyUpdated,
537
+ ...(ProjectWriteTransactionError.is(error) && error.recoveryPaths.length ? { recoveryPaths: error.recoveryPaths } : {}),
538
+ },
539
+ toSessionSnapshot(session, this.context.capabilities),
540
+ {
541
+ sessionId: session.sessionId,
542
+ revision: session.revision,
543
+ diagnostics: diagnosticsFromError,
544
+ },
545
+ );
546
+ } finally {
547
+ reservation?.release();
548
+ }
549
+ }
550
+ }
@@ -1,4 +1,4 @@
1
- import { failure, success, type BackendContext, type BackendSessionState } from './context.js';
1
+ import { failure, success, cloneReadData, type ReadonlyData, type SessionLookup, type SessionReadView } from './context.js';
2
2
  import type {
3
3
  BackendCapabilities,
4
4
  BackendProjectOutline,
@@ -52,7 +52,7 @@ function readFailure(startedAt: number, sessionId: string, reason: SessionReadEr
52
52
  }, undefined, { sessionId, revision });
53
53
  }
54
54
 
55
- function toProjectOutline(session: BackendSessionState): BackendProjectOutline {
55
+ function toProjectOutline(session: SessionReadView): BackendProjectOutline {
56
56
  const project = session.project;
57
57
  // ponytail: full outline is O(project size); add filters or pagination only if payload size becomes a measured problem.
58
58
  return {
@@ -93,19 +93,19 @@ function toProjectOutline(session: BackendSessionState): BackendProjectOutline {
93
93
  }
94
94
 
95
95
  export class ReadService {
96
- public constructor(private readonly context: BackendContext) {}
96
+ public constructor(private readonly getSessionState: SessionLookup, private readonly capabilities: ReadonlyData<BackendCapabilities>) {}
97
97
 
98
98
  public getCapabilities(): BackendResult<BackendCapabilities> {
99
- return success('read', Date.now(), structuredClone(this.context.capabilities));
99
+ return success('read', Date.now(), cloneReadData<BackendCapabilities>(this.capabilities));
100
100
  }
101
101
 
102
102
  public getSession(input: { sessionId: string }): BackendResult<BackendSessionSnapshot, SessionNotFoundError> {
103
103
  const startedAt = Date.now();
104
- const session = this.context.sessions.get(input.sessionId);
104
+ const session = this.getSessionState(input.sessionId);
105
105
  if (!session || session.closed) {
106
106
  return failure('read', startedAt, createSessionNotFoundError(input.sessionId));
107
107
  }
108
- return success('read', startedAt, toSessionSnapshot(session, this.context.capabilities), {
108
+ return success('read', startedAt, toSessionSnapshot(session, this.capabilities), {
109
109
  sessionId: session.sessionId,
110
110
  revision: session.revision,
111
111
  });
@@ -115,7 +115,7 @@ export class ReadService {
115
115
  input: GetProjectOutlineInput,
116
116
  ): BackendResult<BackendProjectOutline, SessionNotFoundError> {
117
117
  const startedAt = Date.now();
118
- const session = this.context.sessions.get(input.sessionId);
118
+ const session = this.getSessionState(input.sessionId);
119
119
  if (!session || session.closed) {
120
120
  return failure('read', startedAt, createSessionNotFoundError(input.sessionId));
121
121
  }
@@ -127,7 +127,7 @@ export class ReadService {
127
127
 
128
128
  public queryEntity(input: QueryEntityInput): BackendResult<BackendEntitySnapshot, SessionNotFoundError | EntityQueryError> {
129
129
  const startedAt = Date.now();
130
- const session = this.context.sessions.get(input.sessionId);
130
+ const session = this.getSessionState(input.sessionId);
131
131
  if (!session || session.closed) return failure('read', startedAt, createSessionNotFoundError(input.sessionId));
132
132
  const meta = { sessionId: session.sessionId, revision: session.revision };
133
133
  const reject = (reason: EntityQueryError['reason']) => failure('read', startedAt, {
@@ -136,10 +136,10 @@ export class ReadService {
136
136
  }, undefined, meta);
137
137
  const target = input.target;
138
138
  if (!target || typeof target !== 'object' || Array.isArray(target) || Object.keys(target).some((key) => key !== 'kind' && key !== 'selector')) return reject('invalid_query');
139
- const respond = (entity: BackendEntitySnapshot['entity']) => {
139
+ const respond = (entity: ReadonlyData<BackendEntitySnapshot['entity']>) => {
140
140
  const data = { ...meta, target, entity };
141
141
  const problem = queryResponseProblem(data);
142
- return problem ? reject(problem) : success('read', startedAt, structuredClone(data), meta);
142
+ return problem ? reject(problem) : success('read', startedAt, cloneReadData<BackendEntitySnapshot>(data), meta);
143
143
  };
144
144
  if (target.kind === 'project') {
145
145
  if (Object.hasOwn(target, 'selector')) return reject('invalid_query');
@@ -165,7 +165,7 @@ export class ReadService {
165
165
  const resources = packages[0].resources.filter((resource) => resource.id === (target.kind === 'resource' ? selector.resourceId : selector.componentResourceId));
166
166
  if (resources.length !== 1) return reject(resources.length ? 'ambiguous' : 'not_found');
167
167
  const resource = resources[0];
168
- let entity: BackendEntitySnapshot['entity'];
168
+ let entity: ReadonlyData<BackendEntitySnapshot['entity']>;
169
169
  if (target.kind === 'resource') {
170
170
  const record = resource as unknown as Record<string, unknown>;
171
171
  entity = { kind: 'resource', properties: Object.fromEntries(BACKEND_RESOURCE_QUERY_FIELDS
@@ -192,12 +192,12 @@ export class ReadService {
192
192
  return respond(entity);
193
193
  }
194
194
 
195
- private resolveReadSession(input: ReadSessionStateInput, startedAt: number): BackendResult<BackendSessionState, SessionNotFoundError | SessionReadError | SessionStaleReadError> {
195
+ private resolveReadSession(input: ReadSessionStateInput, startedAt: number): BackendResult<SessionReadView, SessionNotFoundError | SessionReadError | SessionStaleReadError> {
196
196
  if (!input || typeof input.sessionId !== 'string' || !input.sessionId.length || input.sessionId.length > 256
197
197
  || (input.expectedRevision !== undefined && (!Number.isSafeInteger(input.expectedRevision) || input.expectedRevision < 0))) {
198
198
  return readFailure(startedAt, typeof input?.sessionId === 'string' ? input.sessionId : '', 'invalid_query');
199
199
  }
200
- const session = this.context.sessions.get(input.sessionId);
200
+ const session = this.getSessionState(input.sessionId);
201
201
  if (!session || session.closed) return failure('read', startedAt, createSessionNotFoundError(input.sessionId));
202
202
  const meta = { sessionId: session.sessionId, revision: session.revision };
203
203
  if (input.expectedRevision !== undefined && input.expectedRevision !== session.revision) return failure('read', startedAt, {
@@ -214,7 +214,7 @@ export class ReadService {
214
214
  const session = resolved.data;
215
215
  const meta = { sessionId: session.sessionId, revision: session.revision };
216
216
  // Capture synchronously: pending transactions have not committed; save bookkeeping may change without an edit revision.
217
- const data: BackendSessionStateSnapshot = {
217
+ const data: ReadonlyData<BackendSessionStateSnapshot> = {
218
218
  ...meta, dirty: session.dirty, lastSavedRevision: session.lastSavedRevision,
219
219
  uamFidelity: session.uamFidelity, readComplete: session.readComplete, readDiagnostics: session.readDiagnostics,
220
220
  project: { ...session.project, packages: session.project.packages.map((pkg) => ({
@@ -227,7 +227,7 @@ export class ReadService {
227
227
  };
228
228
  const problem = queryResponseProblem(data, BACKEND_SESSION_READ_LIMITS.model);
229
229
  return problem ? readFailure(startedAt, session.sessionId, problem, session.revision)
230
- : success('read', startedAt, structuredClone(data), meta);
230
+ : success('read', startedAt, cloneReadData<BackendSessionStateSnapshot>(data), meta);
231
231
  }
232
232
 
233
233
  public readResourceBytes(input: ReadResourceBytesInput): BackendResult<BackendResourceBytesSnapshot, SessionNotFoundError | SessionReadError | SessionStaleReadError> {
@@ -256,12 +256,12 @@ export class ReadService {
256
256
  input: { sessionId: string },
257
257
  ): BackendResult<ProjectValidationReport, SessionNotFoundError> {
258
258
  const startedAt = Date.now();
259
- const session = this.context.sessions.get(input.sessionId);
259
+ const session = this.getSessionState(input.sessionId);
260
260
  if (!session || session.closed) {
261
261
  return failure('read', startedAt, createSessionNotFoundError(input.sessionId));
262
262
  }
263
- const report = validateProject(session.project, {
264
- readDiagnostics: session.readDiagnostics,
263
+ const report = validateProject(cloneReadData<import('@openfairygui/core/uam').UamProject>(session.project), {
264
+ readDiagnostics: cloneReadData<import('@openfairygui/core').ProjectDiagnostic[]>(session.readDiagnostics),
265
265
  complete: session.readComplete,
266
266
  validateSources: true,
267
267
  });