@openfairygui/backend 0.6.3 → 0.7.0

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/dist/contracts-Bx8HUr7I.d.cts +756 -0
  2. package/dist/contracts-CMQiPEyz.d.mts +756 -0
  3. package/dist/diagnostics-CIe7S-RW.cjs +670 -0
  4. package/dist/diagnostics-CZ12H1Mx.d.cts +1679 -0
  5. package/dist/diagnostics-CpJ8cAP6.d.mts +1679 -0
  6. package/dist/diagnostics-DTnLXQGs.mjs +641 -0
  7. package/dist/docs.cjs +11530 -5940
  8. package/dist/docs.d.cts +5 -185
  9. package/dist/docs.d.mts +5 -185
  10. package/dist/docs.mjs +11528 -5939
  11. package/dist/index.cjs +16 -2703
  12. package/dist/index.d.cts +5 -2362
  13. package/dist/index.d.mts +5 -2362
  14. package/dist/index.mjs +4 -2691
  15. package/dist/node.cjs +367 -2779
  16. package/dist/node.d.cts +4 -724
  17. package/dist/node.d.mts +4 -724
  18. package/dist/node.mjs +359 -2751
  19. package/dist/rolldown-runtime-BJqNVkSG.cjs +28 -0
  20. package/dist/runtime-DYqG77ak.cjs +2249 -0
  21. package/dist/runtime-gStewf1p.mjs +2189 -0
  22. package/package.json +4 -5
  23. package/src/contracts.ts +0 -58
  24. package/src/diagnostics.ts +0 -188
  25. package/src/docs.ts +0 -109
  26. package/src/generated/contracts.ts +0 -24207
  27. package/src/generated/docs.ts +0 -12
  28. package/src/index.ts +0 -99
  29. package/src/node.ts +0 -317
  30. package/src/path-policy.ts +0 -123
  31. package/src/runtime/capabilities.ts +0 -131
  32. package/src/runtime/contracts.ts +0 -672
  33. package/src/runtime.ts +0 -231
  34. package/src/services/artifact-service.ts +0 -19
  35. package/src/services/authoring-service.ts +0 -229
  36. package/src/services/cache-service.ts +0 -81
  37. package/src/services/capture-project.ts +0 -75
  38. package/src/services/context.ts +0 -150
  39. package/src/services/event-service.ts +0 -86
  40. package/src/services/persistence-service.ts +0 -550
  41. package/src/services/read-service.ts +0 -274
  42. package/src/services/runtime-service.ts +0 -342
  43. package/src/services/session-operation-queue.ts +0 -21
  44. package/src/services/session-project-writer.ts +0 -89
  45. package/src/services/session-registry.ts +0 -70
  46. package/src/services/session-utils.ts +0 -45
  47. package/src/services/transaction-preview.ts +0 -116
  48. package/src/storage.ts +0 -232
@@ -1,550 +0,0 @@
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
- }