@openfairygui/backend 0.5.0-alpha.4 → 0.6.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.
package/dist/node.mjs CHANGED
@@ -6,83 +6,8 @@ import { UAM_SUPPORTED_MATERIALIZATION_SCOPE, UAM_SUPPORTED_TRANSACTION_SCOPE, c
6
6
  import { applyUamTransactionAppAsync } from "@openfairygui/functions/uam";
7
7
  import { ProjectReader, ProjectWriter } from "@openfairygui/core/project-io";
8
8
  import { validateProject } from "@openfairygui/functions";
9
- //#region src/path-policy.ts
10
- function normalizeComparablePath(value) {
11
- const normalized = value.replace(/[/\\]+$/, "").replace(/\\/g, "/");
12
- const driveMatch = normalized.match(/^([a-z]:)(?:\/(.*))?$/i);
13
- const drivePrefix = driveMatch?.[1].toLowerCase() ?? "";
14
- const remainder = driveMatch ? driveMatch[2] ?? "" : normalized;
15
- const hasRoot = driveMatch ? true : remainder.startsWith("/");
16
- const rawSegments = remainder.split("/").filter((segment) => segment.length > 0);
17
- const segments = [];
18
- for (const segment of rawSegments) {
19
- if (segment === ".") continue;
20
- if (segment === "..") {
21
- if (segments.length > 0 && segments[segments.length - 1] !== "..") segments.pop();
22
- else if (!hasRoot) segments.push("..");
23
- continue;
24
- }
25
- segments.push(segment);
26
- }
27
- const joined = segments.join("/");
28
- return (drivePrefix ? `${drivePrefix}/${joined}`.replace(/\/$/, "") : hasRoot ? `/${joined}`.replace(/\/$/, "") : joined || ".").toLowerCase();
29
- }
30
- function createRuntimePathPolicy() {
31
- return {
32
- canonicalization: "realpath+normalized-casefold",
33
- sessionIdentity: "project-root",
34
- saveTarget: "opened-project-only",
35
- outputTargets: "deferred",
36
- workspaceBoundary: "project-root-only"
37
- };
38
- }
39
- async function assertProjectPathContained(fileSystem, projectRoot, targetPath) {
40
- const [resolvedRoot, resolvedTarget] = await Promise.all([fileSystem.resolvePath(projectRoot), fileSystem.resolvePath(targetPath)]);
41
- const root = normalizeComparablePath(resolvedRoot);
42
- const target = normalizeComparablePath(resolvedTarget);
43
- if (root === "." && !target.startsWith("/") && !/^[a-z]:\//i.test(target)) return;
44
- if (target === root || target.startsWith(`${root}/`)) return;
45
- const error = /* @__PURE__ */ new Error(`Project path escapes the opened root: ${targetPath}`);
46
- error.code = "EACCES";
47
- throw error;
48
- }
49
- async function resolveFairyPath(fileSystem, input) {
50
- const resolvedInput = fileSystem.resolve(input);
51
- const stat = await fileSystem.stat(resolvedInput);
52
- if (stat.isFile() && resolvedInput.endsWith(".fairy")) return await fileSystem.resolvePath(resolvedInput);
53
- if (stat.isDirectory()) {
54
- const fairyFiles = (await fileSystem.readdir(resolvedInput)).filter((entry) => entry.endsWith(".fairy"));
55
- if (fairyFiles.length === 1) return await fileSystem.resolvePath(fileSystem.join(resolvedInput, fairyFiles[0]));
56
- if (fairyFiles.length > 1) throw new Error(`Multiple .fairy files found in ${resolvedInput}: ${fairyFiles.join(", ")}`);
57
- throw new Error(`No .fairy file found in ${resolvedInput}`);
58
- }
59
- throw new Error(`Input is not a .fairy file or directory: ${resolvedInput}`);
60
- }
61
- async function resolveCanonicalProjectRoot(fileSystem, input) {
62
- const fairyPath = await resolveFairyPath(fileSystem, input);
63
- const canonicalProjectPath = await fileSystem.resolvePath(fileSystem.dirname(fairyPath));
64
- return {
65
- fairyPath,
66
- canonicalProjectPath,
67
- canonicalPathKey: normalizeComparablePath(canonicalProjectPath)
68
- };
69
- }
70
- async function validateSaveTarget(fileSystem, openedFairyPath, targetPath) {
71
- if (!targetPath) return null;
72
- const attemptedPath = await fileSystem.resolvePath(fileSystem.resolve(targetPath));
73
- const allowedPath = await fileSystem.resolvePath(openedFairyPath);
74
- if (normalizeComparablePath(attemptedPath) === normalizeComparablePath(allowedPath)) return null;
75
- return {
76
- code: "path_policy_violation",
77
- message: `Save target is restricted to the originally opened project file: ${allowedPath}`,
78
- policy: "save_target",
79
- attemptedPath,
80
- allowedPath
81
- };
82
- }
83
- //#endregion
84
9
  //#region src/contracts.ts
85
- const BACKEND_CONTRACT_VERSION = "2.0.0-p3";
10
+ const BACKEND_CONTRACT_VERSION = "3.0.0";
86
11
  const BACKEND_COMPATIBILITY_POLICY = {
87
12
  incompatibleChange: "requires contractVersion bump",
88
13
  capabilitySchemaChange: "requires capabilitySchemaVersion bump",
@@ -134,14 +59,6 @@ const write = {
134
59
  kind: "host-action",
135
60
  message: "Preserve the dirty session and inspect the error, actual target files and permissions with the host. Partial writes may have changed files: verify or recover them before a newly authorized save. Do not clear dirty state, discard memory or blindly retry."
136
61
  };
137
- const execution = {
138
- kind: "host-action",
139
- message: "Inspect the execution/cache failure and current session/revision. Preserve sources and unsaved work and report the cause to the host. Replan after resolution; failed execution or cache work is not a completed edit."
140
- };
141
- const job = {
142
- kind: "host-action",
143
- message: "Inspect the job ID and status with getJob/listJobs. Do not fabricate, restart or force-cancel a missing, terminal or non-cancellable job. Ask the host before scheduling new work; cancellation is not success."
144
- };
145
62
  /** Exhaustiveness and exact ownership are checked against the canonical unions. */
146
63
  const BACKEND_DIAGNOSTIC_GUIDES = [
147
64
  {
@@ -192,6 +109,14 @@ const BACKEND_DIAGNOSTIC_GUIDES = [
192
109
  message: "Ask the host to confirm the runtime and project, recover any unsaved state, then explicitly open a new session if appropriate. Session IDs are runtime-local. Read its new revision and replan; never reuse an expired session or assume disk contains unsaved changes."
193
110
  }
194
111
  },
112
+ {
113
+ code: "session_close_failed",
114
+ owners: ["backend"],
115
+ remediation: {
116
+ kind: "host-action",
117
+ message: "The session and lock ownership remain registered. Inspect the reported lock release failure, correct the storage problem, then retry closeSession with the same session ID. Do not remove the lock file or open a replacement session to bypass the owner."
118
+ }
119
+ },
195
120
  {
196
121
  code: "path_policy_violation",
197
122
  owners: ["backend"],
@@ -672,27 +597,10 @@ const BACKEND_DIAGNOSTIC_GUIDES = [
672
597
  {
673
598
  code: "execution_failure",
674
599
  owners: ["core.transaction"],
675
- remediation: execution
676
- },
677
- {
678
- code: "cache_refresh_failed",
679
- owners: ["backend"],
680
- remediation: execution
681
- },
682
- {
683
- code: "job_not_found",
684
- owners: ["backend"],
685
- remediation: job
686
- },
687
- {
688
- code: "job_not_cancellable",
689
- owners: ["backend"],
690
- remediation: job
691
- },
692
- {
693
- code: "job_cancelled",
694
- owners: ["backend"],
695
- remediation: job
600
+ remediation: {
601
+ kind: "host-action",
602
+ message: "Inspect the execution/cache failure and current session/revision. Preserve sources and unsaved work and report the cause to the host. Replan after resolution; failed execution or cache work is not a completed edit."
603
+ }
696
604
  }
697
605
  ];
698
606
  const BACKEND_DIAGNOSTICS_URI = "openfairygui://docs/diagnostics";
@@ -715,6 +623,14 @@ function enrichBackendDiagnostic(diagnostic, sessionId) {
715
623
  }
716
624
  //#endregion
717
625
  //#region src/services/context.ts
626
+ /** Borrow without copying the entire project before a read has checked its response budget. */
627
+ function readView(value) {
628
+ return value;
629
+ }
630
+ /** A detached copy is writable again; this is the only conversion from a borrowed read view. */
631
+ function cloneReadData(value) {
632
+ return structuredClone(value);
633
+ }
718
634
  function diagnosticFromError(error) {
719
635
  return {
720
636
  code: error.code,
@@ -735,7 +651,7 @@ function createMeta(stage, startedAt, options) {
735
651
  diagnostics: (options?.diagnostics ?? []).map((entry) => enrichBackendDiagnostic(entry, options?.sessionId)),
736
652
  stage,
737
653
  contractVersion: BACKEND_CONTRACT_VERSION,
738
- capabilitySchemaVersion: 11
654
+ capabilitySchemaVersion: 12
739
655
  };
740
656
  }
741
657
  function success(stage, startedAt, data, options) {
@@ -758,68 +674,6 @@ function failure(stage, startedAt, error, session, options) {
758
674
  };
759
675
  }
760
676
  //#endregion
761
- //#region src/services/session-project-writer.ts
762
- function createWriterFileSystem(fileSystem, projectRoot, writtenPaths, failedPaths) {
763
- const contained = async (targetPath, operation) => {
764
- await assertProjectPathContained(fileSystem, projectRoot, targetPath);
765
- return operation();
766
- };
767
- async function trackWrite(targetPath, write) {
768
- try {
769
- const result = await contained(targetPath, write);
770
- writtenPaths.push(targetPath);
771
- return result;
772
- } catch (error) {
773
- failedPaths.push(targetPath);
774
- throw error;
775
- }
776
- }
777
- return {
778
- readFile: (path) => contained(path, () => fileSystem.readFile(path)),
779
- readFileRaw: (path) => contained(path, () => fileSystem.readFileRaw(path)),
780
- writeFile: (path, content) => trackWrite(path, async () => {
781
- await fileSystem.mkdir(fileSystem.dirname(path), { recursive: true });
782
- await fileSystem.writeFile(path, content);
783
- }),
784
- writeFileRaw: (path, data) => trackWrite(path, async () => {
785
- await fileSystem.mkdir(fileSystem.dirname(path), { recursive: true });
786
- await fileSystem.writeFileRaw(path, data);
787
- }),
788
- mkdir: (path) => contained(path, () => fileSystem.mkdir(path, { recursive: true })),
789
- readdir: (path) => contained(path, () => fileSystem.readdir(path)),
790
- async exists(path) {
791
- await assertProjectPathContained(fileSystem, projectRoot, path);
792
- try {
793
- await fileSystem.stat(path);
794
- return true;
795
- } catch {
796
- return false;
797
- }
798
- },
799
- join: (...paths) => fileSystem.join(...paths),
800
- dirname: (path) => fileSystem.dirname(path),
801
- unlink: (path) => trackWrite(path, () => fileSystem.unlink(path)),
802
- rmdir: (path) => trackWrite(path, () => fileSystem.rmdir(path))
803
- };
804
- }
805
- async function writeSessionProject(input) {
806
- const projectRoot = input.fileSystem.dirname(input.fairyPath);
807
- const write = async (fileSystem) => {
808
- await new ProjectWriter(createWriterFileSystem(fileSystem, projectRoot, input.writtenPaths, input.failedPaths)).write(input.document, input.fairyPath, {
809
- staleSourceFiles: input.staleSourceFiles,
810
- staleResourceFolders: input.staleResourceFolders,
811
- staleBranchDirectories: input.staleBranchDirectories
812
- });
813
- };
814
- if (!input.fileSystem.runProjectWriteTransaction) return write(input.fileSystem);
815
- try {
816
- await input.fileSystem.runProjectWriteTransaction(projectRoot, write);
817
- } catch (error) {
818
- input.writtenPaths.length = 0;
819
- throw error;
820
- }
821
- }
822
- //#endregion
823
677
  //#region src/services/session-utils.ts
824
678
  function toSessionSnapshot(session, capabilities) {
825
679
  return {
@@ -830,7 +684,7 @@ function toSessionSnapshot(session, capabilities) {
830
684
  dirty: session.dirty,
831
685
  uamFidelity: session.uamFidelity,
832
686
  lockHeld: session.lockHeld,
833
- capabilities: structuredClone(capabilities)
687
+ capabilities: cloneReadData(capabilities)
834
688
  };
835
689
  }
836
690
  function createSessionNotFoundError(sessionId) {
@@ -885,6 +739,22 @@ const BACKEND_RESOURCE_QUERY_FIELDS = [
885
739
  "image",
886
740
  "movieClip"
887
741
  ];
742
+ /** A failed staged write with an explicit outcome for the original project. */
743
+ var ProjectWriteTransactionError = class extends Error {
744
+ code = "project_write_transaction_failed";
745
+ /** Recognizes the same contract across separately bundled Node/root or ESM/CJS entries. */
746
+ static is(error) {
747
+ if (typeof error !== "object" || error === null) return false;
748
+ const value = error;
749
+ return value.code === "project_write_transaction_failed" && typeof value.message === "string" && typeof value.diskMayBePartiallyUpdated === "boolean" && Array.isArray(value.recoveryPaths) && value.recoveryPaths.every((path) => typeof path === "string");
750
+ }
751
+ constructor(cause, diskMayBePartiallyUpdated, recoveryPaths = []) {
752
+ super(cause instanceof Error ? cause.message : String(cause), { cause });
753
+ this.diskMayBePartiallyUpdated = diskMayBePartiallyUpdated;
754
+ this.recoveryPaths = recoveryPaths;
755
+ this.name = "ProjectWriteTransactionError";
756
+ }
757
+ };
888
758
  //#endregion
889
759
  //#region src/services/capture-project.ts
890
760
  function createCaptureFileSystem(files, directories) {
@@ -1155,52 +1025,6 @@ function toBackendDiagnostics(error) {
1155
1025
  opId: error.opId
1156
1026
  }];
1157
1027
  }
1158
- function createCapabilityUnavailableError$1(message) {
1159
- return {
1160
- code: "capability_unavailable",
1161
- message,
1162
- capability: "fileSystem",
1163
- requiredAdapter: "BackendFileSystem"
1164
- };
1165
- }
1166
- function createUamFidelityUnsupportedError(session) {
1167
- return {
1168
- code: "uam_fidelity_unsupported",
1169
- message: "The source project contains formal properties that the current UAM cannot preserve.",
1170
- sessionId: session.sessionId,
1171
- canonicalPathKey: session.canonicalPathKey
1172
- };
1173
- }
1174
- function validationDiagnostics(sessionProject) {
1175
- return validateUamProject(sessionProject).map((issue) => ({
1176
- code: "materialize_validation_failed",
1177
- message: issue.message,
1178
- severity: "error",
1179
- path: issue.path,
1180
- operationKind: "materializeSession"
1181
- }));
1182
- }
1183
- function toMaterializeSnapshot(session, capabilities, input) {
1184
- return {
1185
- ...toSessionSnapshot(session, capabilities),
1186
- mode: "fullProject",
1187
- reason: input.reason,
1188
- materializeRevision: session.revision,
1189
- saveRevision: session.lastSavedRevision,
1190
- writtenPaths: [...input.writtenPaths],
1191
- skippedPaths: [...input.skippedPaths],
1192
- diagnostics: input.diagnostics.map((diagnostic) => ({ ...diagnostic }))
1193
- };
1194
- }
1195
- function storageCanonicalTarget(input) {
1196
- const canonicalProjectPath = input.canonicalProjectPath ?? (input.fileSystem.dirname(input.fairyPath) || ".");
1197
- return {
1198
- fileSystem: input.fileSystem,
1199
- fairyPath: input.fairyPath,
1200
- canonicalProjectPath,
1201
- canonicalPathKey: input.canonicalPathKey ?? normalizeComparablePath(canonicalProjectPath)
1202
- };
1203
- }
1204
1028
  function detachSharedByteViews(value, seen = /* @__PURE__ */ new WeakSet()) {
1205
1029
  if (!value || typeof value !== "object" || seen.has(value)) return;
1206
1030
  seen.add(value);
@@ -1213,32 +1037,16 @@ function detachSharedByteViews(value, seen = /* @__PURE__ */ new WeakSet()) {
1213
1037
  }
1214
1038
  }
1215
1039
  var AuthoringService = class {
1216
- sessionOperations = /* @__PURE__ */ new Map();
1217
- constructor(context, cacheService, eventService) {
1040
+ constructor(context, cacheService, eventService, sessionOperations) {
1218
1041
  this.context = context;
1219
1042
  this.cacheService = cacheService;
1220
1043
  this.eventService = eventService;
1221
- }
1222
- async runSessionExclusive(sessionId, operation) {
1223
- const previous = this.sessionOperations.get(sessionId) ?? Promise.resolve();
1224
- let release = () => void 0;
1225
- const current = new Promise((resolve) => {
1226
- release = resolve;
1227
- });
1228
- const tail = previous.then(() => current);
1229
- this.sessionOperations.set(sessionId, tail);
1230
- await previous;
1231
- try {
1232
- return await operation();
1233
- } finally {
1234
- release();
1235
- if (this.sessionOperations.get(sessionId) === tail) this.sessionOperations.delete(sessionId);
1236
- }
1044
+ this.sessionOperations = sessionOperations;
1237
1045
  }
1238
1046
  async preflightTransaction(input) {
1239
1047
  const queuedInput = structuredClone(input);
1240
1048
  detachSharedByteViews(queuedInput);
1241
- return this.runSessionExclusive(queuedInput.sessionId, async () => {
1049
+ return this.sessionOperations.run(queuedInput.sessionId, async () => {
1242
1050
  const startedAt = Date.now();
1243
1051
  const session = this.context.sessions.get(queuedInput.sessionId);
1244
1052
  if (!session || session.closed) return failure("authoring", startedAt, createSessionNotFoundError(queuedInput.sessionId));
@@ -1278,7 +1086,7 @@ var AuthoringService = class {
1278
1086
  async applyTransaction(input) {
1279
1087
  const queuedInput = structuredClone(input);
1280
1088
  detachSharedByteViews(queuedInput);
1281
- return this.runSessionExclusive(queuedInput.sessionId, () => this.applyTransactionExclusive(queuedInput));
1089
+ return this.sessionOperations.run(queuedInput.sessionId, () => this.applyTransactionExclusive(queuedInput));
1282
1090
  }
1283
1091
  async applyTransactionExclusive(input) {
1284
1092
  const startedAt = Date.now();
@@ -1339,6 +1147,200 @@ var AuthoringService = class {
1339
1147
  revision: session.revision
1340
1148
  });
1341
1149
  }
1150
+ };
1151
+ //#endregion
1152
+ //#region src/path-policy.ts
1153
+ function normalizeComparablePath(value) {
1154
+ const normalized = value.replace(/[/\\]+$/, "").replace(/\\/g, "/");
1155
+ const driveMatch = normalized.match(/^([a-z]:)(?:\/(.*))?$/i);
1156
+ const drivePrefix = driveMatch?.[1].toLowerCase() ?? "";
1157
+ const remainder = driveMatch ? driveMatch[2] ?? "" : normalized;
1158
+ const hasRoot = driveMatch ? true : remainder.startsWith("/");
1159
+ const rawSegments = remainder.split("/").filter((segment) => segment.length > 0);
1160
+ const segments = [];
1161
+ for (const segment of rawSegments) {
1162
+ if (segment === ".") continue;
1163
+ if (segment === "..") {
1164
+ if (segments.length > 0 && segments[segments.length - 1] !== "..") segments.pop();
1165
+ else if (!hasRoot) segments.push("..");
1166
+ continue;
1167
+ }
1168
+ segments.push(segment);
1169
+ }
1170
+ const joined = segments.join("/");
1171
+ return (drivePrefix ? `${drivePrefix}/${joined}`.replace(/\/$/, "") : hasRoot ? `/${joined}`.replace(/\/$/, "") : joined || ".").toLowerCase();
1172
+ }
1173
+ function createRuntimePathPolicy() {
1174
+ return {
1175
+ canonicalization: "realpath+normalized-casefold",
1176
+ sessionIdentity: "project-root",
1177
+ saveTarget: "opened-project-only",
1178
+ outputTargets: "deferred",
1179
+ workspaceBoundary: "project-root-only"
1180
+ };
1181
+ }
1182
+ async function assertProjectPathContained(fileSystem, projectRoot, targetPath) {
1183
+ const [resolvedRoot, resolvedTarget] = await Promise.all([fileSystem.resolvePath(projectRoot), fileSystem.resolvePath(targetPath)]);
1184
+ const root = normalizeComparablePath(resolvedRoot);
1185
+ const target = normalizeComparablePath(resolvedTarget);
1186
+ if (root === "." && !target.startsWith("/") && !/^[a-z]:\//i.test(target)) return;
1187
+ if (target === root || target.startsWith(`${root}/`)) return;
1188
+ const error = /* @__PURE__ */ new Error(`Project path escapes the opened root: ${targetPath}`);
1189
+ error.code = "EACCES";
1190
+ throw error;
1191
+ }
1192
+ async function resolveFairyPath(fileSystem, input) {
1193
+ const resolvedInput = fileSystem.resolve(input);
1194
+ const stat = await fileSystem.stat(resolvedInput);
1195
+ if (stat.isFile() && resolvedInput.endsWith(".fairy")) return await fileSystem.resolvePath(resolvedInput);
1196
+ if (stat.isDirectory()) {
1197
+ const fairyFiles = (await fileSystem.readdir(resolvedInput)).filter((entry) => entry.endsWith(".fairy"));
1198
+ if (fairyFiles.length === 1) return await fileSystem.resolvePath(fileSystem.join(resolvedInput, fairyFiles[0]));
1199
+ if (fairyFiles.length > 1) throw new Error(`Multiple .fairy files found in ${resolvedInput}: ${fairyFiles.join(", ")}`);
1200
+ throw new Error(`No .fairy file found in ${resolvedInput}`);
1201
+ }
1202
+ throw new Error(`Input is not a .fairy file or directory: ${resolvedInput}`);
1203
+ }
1204
+ async function resolveCanonicalProjectRoot(fileSystem, input) {
1205
+ const fairyPath = await resolveFairyPath(fileSystem, input);
1206
+ const canonicalProjectPath = await fileSystem.resolvePath(fileSystem.dirname(fairyPath));
1207
+ return {
1208
+ fairyPath,
1209
+ canonicalProjectPath,
1210
+ canonicalPathKey: normalizeComparablePath(canonicalProjectPath)
1211
+ };
1212
+ }
1213
+ async function validateSaveTarget(fileSystem, openedFairyPath, targetPath) {
1214
+ if (!targetPath) return null;
1215
+ const attemptedPath = await fileSystem.resolvePath(fileSystem.resolve(targetPath));
1216
+ const allowedPath = await fileSystem.resolvePath(openedFairyPath);
1217
+ if (normalizeComparablePath(attemptedPath) === normalizeComparablePath(allowedPath)) return null;
1218
+ return {
1219
+ code: "path_policy_violation",
1220
+ message: `Save target is restricted to the originally opened project file: ${allowedPath}`,
1221
+ policy: "save_target",
1222
+ attemptedPath,
1223
+ allowedPath
1224
+ };
1225
+ }
1226
+ //#endregion
1227
+ //#region src/services/session-project-writer.ts
1228
+ function createWriterFileSystem(fileSystem, projectRoot, writtenPaths, failedPaths) {
1229
+ const contained = async (targetPath, operation) => {
1230
+ await assertProjectPathContained(fileSystem, projectRoot, targetPath);
1231
+ return operation();
1232
+ };
1233
+ async function trackWrite(targetPath, write) {
1234
+ try {
1235
+ const result = await contained(targetPath, write);
1236
+ writtenPaths.push(targetPath);
1237
+ return result;
1238
+ } catch (error) {
1239
+ failedPaths.push(targetPath);
1240
+ throw error;
1241
+ }
1242
+ }
1243
+ return {
1244
+ resolvePath: (path) => contained(path, () => fileSystem.resolvePath(path)),
1245
+ readFile: (path) => contained(path, () => fileSystem.readFile(path)),
1246
+ readFileRaw: (path) => contained(path, () => fileSystem.readFileRaw(path)),
1247
+ writeFile: (path, content) => trackWrite(path, async () => {
1248
+ await fileSystem.mkdir(fileSystem.dirname(path), { recursive: true });
1249
+ await fileSystem.writeFile(path, content);
1250
+ }),
1251
+ writeFileRaw: (path, data) => trackWrite(path, async () => {
1252
+ await fileSystem.mkdir(fileSystem.dirname(path), { recursive: true });
1253
+ await fileSystem.writeFileRaw(path, data);
1254
+ }),
1255
+ mkdir: (path) => contained(path, () => fileSystem.mkdir(path, { recursive: true })),
1256
+ readdir: (path) => contained(path, () => fileSystem.readdir(path)),
1257
+ async exists(path) {
1258
+ await assertProjectPathContained(fileSystem, projectRoot, path);
1259
+ try {
1260
+ await fileSystem.stat(path);
1261
+ return true;
1262
+ } catch {
1263
+ return false;
1264
+ }
1265
+ },
1266
+ join: (...paths) => fileSystem.join(...paths),
1267
+ dirname: (path) => fileSystem.dirname(path),
1268
+ unlink: (path) => trackWrite(path, () => fileSystem.unlink(path)),
1269
+ rmdir: (path) => trackWrite(path, () => fileSystem.rmdir(path))
1270
+ };
1271
+ }
1272
+ async function writeSessionProject(input) {
1273
+ const projectRoot = input.fileSystem.dirname(input.fairyPath);
1274
+ const write = async (fileSystem) => {
1275
+ await new ProjectWriter(createWriterFileSystem(fileSystem, projectRoot, input.writtenPaths, input.failedPaths)).write(input.document, input.fairyPath, {
1276
+ staleSourceFiles: input.staleSourceFiles,
1277
+ staleResourceFolders: input.staleResourceFolders,
1278
+ staleBranchDirectories: input.staleBranchDirectories
1279
+ });
1280
+ };
1281
+ if (!input.fileSystem.runProjectWriteTransaction) return write(input.fileSystem);
1282
+ try {
1283
+ await input.fileSystem.runProjectWriteTransaction(projectRoot, write);
1284
+ } catch (error) {
1285
+ if (ProjectWriteTransactionError.is(error) && !error.diskMayBePartiallyUpdated) input.writtenPaths.length = 0;
1286
+ throw error;
1287
+ }
1288
+ }
1289
+ //#endregion
1290
+ //#region src/services/persistence-service.ts
1291
+ function createCapabilityUnavailableError$1(message) {
1292
+ return {
1293
+ code: "capability_unavailable",
1294
+ message,
1295
+ capability: "fileSystem",
1296
+ requiredAdapter: "BackendFileSystem"
1297
+ };
1298
+ }
1299
+ function createUamFidelityUnsupportedError(session) {
1300
+ return {
1301
+ code: "uam_fidelity_unsupported",
1302
+ message: "The source project contains formal properties that the current UAM cannot preserve.",
1303
+ sessionId: session.sessionId,
1304
+ canonicalPathKey: session.canonicalPathKey
1305
+ };
1306
+ }
1307
+ function validationDiagnostics(sessionProject) {
1308
+ return validateUamProject(sessionProject).map((issue) => ({
1309
+ code: "materialize_validation_failed",
1310
+ message: issue.message,
1311
+ severity: "error",
1312
+ path: issue.path,
1313
+ operationKind: "materializeSession"
1314
+ }));
1315
+ }
1316
+ function toMaterializeSnapshot(session, capabilities, input) {
1317
+ return {
1318
+ ...toSessionSnapshot(session, capabilities),
1319
+ mode: "fullProject",
1320
+ reason: input.reason,
1321
+ materializeRevision: session.revision,
1322
+ saveRevision: session.lastSavedRevision,
1323
+ writtenPaths: [...input.writtenPaths],
1324
+ skippedPaths: [...input.skippedPaths],
1325
+ diagnostics: input.diagnostics.map((diagnostic) => ({ ...diagnostic }))
1326
+ };
1327
+ }
1328
+ function storageCanonicalTarget(input) {
1329
+ const canonicalProjectPath = input.canonicalProjectPath ?? (input.fileSystem.dirname(input.fairyPath) || ".");
1330
+ return {
1331
+ fileSystem: input.fileSystem,
1332
+ fairyPath: input.fairyPath,
1333
+ canonicalProjectPath,
1334
+ canonicalPathKey: input.canonicalPathKey ?? normalizeComparablePath(canonicalProjectPath)
1335
+ };
1336
+ }
1337
+ var PersistenceService = class {
1338
+ constructor(context, cacheService, eventService, sessionOperations) {
1339
+ this.context = context;
1340
+ this.cacheService = cacheService;
1341
+ this.eventService = eventService;
1342
+ this.sessionOperations = sessionOperations;
1343
+ }
1342
1344
  async saveSession(input) {
1343
1345
  if (input.force === true || input.mode === "materializeCleanSession") return this.materializeSession({
1344
1346
  sessionId: input.sessionId,
@@ -1348,7 +1350,8 @@ var AuthoringService = class {
1348
1350
  mode: "fullProject",
1349
1351
  reason: "force_save"
1350
1352
  });
1351
- return this.runSessionExclusive(input.sessionId, () => this.saveSessionExclusive(input));
1353
+ const captured = { ...input };
1354
+ return this.sessionOperations.run(captured.sessionId, () => this.saveSessionExclusive(captured));
1352
1355
  }
1353
1356
  finishSuccessfulSave(session) {
1354
1357
  session.lastSavedRevision = session.revision;
@@ -1440,7 +1443,8 @@ var AuthoringService = class {
1440
1443
  lastSavedRevision: session.lastSavedRevision,
1441
1444
  committedPaths,
1442
1445
  failedPaths,
1443
- diskMayBePartiallyUpdated: !fileSystem.runProjectWriteTransaction
1446
+ diskMayBePartiallyUpdated: !ProjectWriteTransactionError.is(error) || error.diskMayBePartiallyUpdated,
1447
+ ...ProjectWriteTransactionError.is(error) && error.recoveryPaths.length ? { recoveryPaths: error.recoveryPaths } : {}
1444
1448
  }, toSessionSnapshot(session, this.context.capabilities), {
1445
1449
  sessionId: session.sessionId,
1446
1450
  revision: session.revision
@@ -1448,7 +1452,11 @@ var AuthoringService = class {
1448
1452
  }
1449
1453
  }
1450
1454
  async materializeSession(input) {
1451
- return this.runSessionExclusive(input.sessionId, () => this.materializeSessionExclusive(input));
1455
+ const captured = {
1456
+ ...input,
1457
+ storage: input.storage && { ...input.storage }
1458
+ };
1459
+ return this.sessionOperations.run(captured.sessionId, () => this.materializeSessionExclusive(captured));
1452
1460
  }
1453
1461
  async materializeSessionExclusive(input) {
1454
1462
  const startedAt = Date.now();
@@ -1465,24 +1473,21 @@ var AuthoringService = class {
1465
1473
  revision: session.revision
1466
1474
  });
1467
1475
  const fairyPath = storageTarget?.fairyPath ?? session.fairyPath;
1476
+ if (session.lockHeld && (fileSystem !== session.fileSystem || fairyPath !== session.fairyPath || storageTarget && (storageTarget.canonicalPathKey !== session.canonicalPathKey || storageTarget.canonicalProjectPath !== session.canonicalProjectPath))) return failure("authoring", startedAt, {
1477
+ code: "path_policy_violation",
1478
+ message: "A locked file-backed session must keep its opened storage binding.",
1479
+ policy: "save_target",
1480
+ attemptedPath: fairyPath,
1481
+ allowedPath: session.fairyPath
1482
+ }, toSessionSnapshot(session, this.context.capabilities), {
1483
+ sessionId: session.sessionId,
1484
+ revision: session.revision
1485
+ });
1468
1486
  const targetViolation = await validateSaveTarget(fileSystem, fairyPath, input.targetPath);
1469
1487
  if (targetViolation) return failure("authoring", startedAt, targetViolation, toSessionSnapshot(session, this.context.capabilities), {
1470
1488
  sessionId: session.sessionId,
1471
1489
  revision: session.revision
1472
1490
  });
1473
- if (storageTarget) {
1474
- const holderSessionId = this.context.sessionsByPath.get(storageTarget.canonicalPathKey);
1475
- if (holderSessionId && holderSessionId !== session.sessionId) return failure("authoring", startedAt, {
1476
- code: "lock_conflict",
1477
- kind: "in_process_session_exists",
1478
- message: `Project is already open in this backend runtime: ${storageTarget.canonicalProjectPath}`,
1479
- canonicalPathKey: storageTarget.canonicalPathKey,
1480
- holderSessionId
1481
- }, toSessionSnapshot(session, this.context.capabilities), {
1482
- sessionId: session.sessionId,
1483
- revision: session.revision
1484
- });
1485
- }
1486
1491
  if (session.uamFidelity === "unsupported") return failure("authoring", startedAt, createUamFidelityUnsupportedError(session), toSessionSnapshot(session, this.context.capabilities), {
1487
1492
  sessionId: session.sessionId,
1488
1493
  revision: session.revision
@@ -1526,6 +1531,11 @@ var AuthoringService = class {
1526
1531
  const writtenPaths = [];
1527
1532
  const failedPaths = [];
1528
1533
  const skippedPaths = [];
1534
+ const reservation = storageTarget ? this.context.sessions.reserve(session.sessionId, storageTarget) : null;
1535
+ if (reservation && "code" in reservation) return failure("authoring", startedAt, reservation, toSessionSnapshot(session, this.context.capabilities), {
1536
+ sessionId: session.sessionId,
1537
+ revision: session.revision
1538
+ });
1529
1539
  this.eventService.emit({
1530
1540
  kind: "save.started",
1531
1541
  sessionId: session.sessionId,
@@ -1555,14 +1565,7 @@ var AuthoringService = class {
1555
1565
  session.pendingStaleBranchDirectories.clear();
1556
1566
  }
1557
1567
  if (isSessionStorageTarget || storageTarget) commitUamProjectSourcePaths(session.project);
1558
- if (storageTarget) {
1559
- this.context.sessionsByPath.delete(session.canonicalPathKey);
1560
- session.fileSystem = storageTarget.fileSystem;
1561
- session.fairyPath = storageTarget.fairyPath;
1562
- session.canonicalProjectPath = storageTarget.canonicalProjectPath;
1563
- session.canonicalPathKey = storageTarget.canonicalPathKey;
1564
- this.context.sessionsByPath.set(session.canonicalPathKey, session.sessionId);
1565
- }
1568
+ reservation?.commit(session);
1566
1569
  this.finishSuccessfulSave(session);
1567
1570
  return success("authoring", startedAt, toMaterializeSnapshot(session, this.context.capabilities, {
1568
1571
  reason: input.reason,
@@ -1600,12 +1603,15 @@ var AuthoringService = class {
1600
1603
  failedPaths,
1601
1604
  skippedPaths,
1602
1605
  diagnostics: diagnosticsFromError,
1603
- diskMayBePartiallyUpdated: !fileSystem.runProjectWriteTransaction
1606
+ diskMayBePartiallyUpdated: !ProjectWriteTransactionError.is(error) || error.diskMayBePartiallyUpdated,
1607
+ ...ProjectWriteTransactionError.is(error) && error.recoveryPaths.length ? { recoveryPaths: error.recoveryPaths } : {}
1604
1608
  }, toSessionSnapshot(session, this.context.capabilities), {
1605
1609
  sessionId: session.sessionId,
1606
1610
  revision: session.revision,
1607
1611
  diagnostics: diagnosticsFromError
1608
1612
  });
1613
+ } finally {
1614
+ reservation?.release();
1609
1615
  }
1610
1616
  }
1611
1617
  };
@@ -1628,14 +1634,16 @@ function createCacheEntry(session, valid) {
1628
1634
  };
1629
1635
  }
1630
1636
  var CacheService = class {
1631
- constructor(context) {
1632
- this.context = context;
1637
+ cacheBySession = /* @__PURE__ */ new Map();
1638
+ constructor(getSession, events) {
1639
+ this.getSession = getSession;
1640
+ this.events = events;
1633
1641
  }
1634
1642
  getCacheSnapshot(input) {
1635
1643
  const startedAt = Date.now();
1636
- const session = this.context.sessions.get(input.sessionId);
1644
+ const session = this.getSession(input.sessionId);
1637
1645
  if (!session || session.closed) return failure("read", startedAt, createSessionNotFoundError(input.sessionId));
1638
- const entry = this.context.cacheBySession.get(input.sessionId);
1646
+ const entry = this.cacheBySession.get(input.sessionId);
1639
1647
  return success("read", startedAt, {
1640
1648
  cacheRevision: entry?.revision ?? session.revision,
1641
1649
  entries: entry ? [structuredClone(entry)] : []
@@ -1644,47 +1652,145 @@ var CacheService = class {
1644
1652
  revision: session.revision
1645
1653
  });
1646
1654
  }
1655
+ refreshCache(input) {
1656
+ const startedAt = Date.now();
1657
+ const session = this.getSession(input.sessionId);
1658
+ if (!session || session.closed) return failure("runtime", startedAt, createSessionNotFoundError(input.sessionId));
1659
+ const entry = this.refreshSession(session);
1660
+ this.events.emit({
1661
+ kind: "cache.updated",
1662
+ sessionId: session.sessionId,
1663
+ canonicalPathKey: session.canonicalPathKey,
1664
+ revision: session.revision,
1665
+ cacheRevision: entry.revision,
1666
+ payload: { reason: input.reason ?? "manual" }
1667
+ });
1668
+ return success("runtime", startedAt, {
1669
+ cacheRevision: entry.revision,
1670
+ entries: [structuredClone(entry)]
1671
+ }, {
1672
+ sessionId: session.sessionId,
1673
+ revision: session.revision
1674
+ });
1675
+ }
1647
1676
  refreshSession(session) {
1648
1677
  const entry = createCacheEntry(session, true);
1649
- this.context.cacheBySession.set(session.sessionId, entry);
1678
+ this.cacheBySession.set(session.sessionId, entry);
1650
1679
  return entry;
1651
1680
  }
1652
1681
  invalidateSession(session) {
1653
1682
  const entry = createCacheEntry(session, false);
1654
- this.context.cacheBySession.set(session.sessionId, entry);
1683
+ this.cacheBySession.set(session.sessionId, entry);
1655
1684
  return entry;
1656
1685
  }
1657
1686
  removeSession(sessionId) {
1658
- this.context.cacheBySession.delete(sessionId);
1687
+ this.cacheBySession.delete(sessionId);
1688
+ }
1689
+ };
1690
+ //#endregion
1691
+ //#region src/services/session-registry.ts
1692
+ /** Owns live sessions and path claims, including claims made before asynchronous I/O. */
1693
+ var SessionRegistry = class {
1694
+ sessions = /* @__PURE__ */ new Map();
1695
+ paths = /* @__PURE__ */ new Map();
1696
+ opening = /* @__PURE__ */ new Set();
1697
+ get(sessionId) {
1698
+ return this.sessions.get(sessionId);
1699
+ }
1700
+ has(sessionId) {
1701
+ return this.sessions.has(sessionId) || this.opening.has(sessionId);
1702
+ }
1703
+ reserve(sessionId, target) {
1704
+ const key = target.canonicalPathKey;
1705
+ const previous = this.paths.get(key);
1706
+ if (previous && previous.sessionId !== sessionId) return {
1707
+ code: "lock_conflict",
1708
+ kind: "in_process_session_exists",
1709
+ message: `Project is already open in this backend runtime: ${target.canonicalProjectPath}`,
1710
+ canonicalPathKey: key,
1711
+ holderSessionId: previous.sessionId,
1712
+ lockFilePath: target.lockFilePath
1713
+ };
1714
+ const claim = previous ?? { sessionId };
1715
+ this.paths.set(key, claim);
1716
+ if (!this.sessions.has(sessionId)) this.opening.add(sessionId);
1717
+ let committed = false;
1718
+ return {
1719
+ commit: (session) => {
1720
+ if (session.sessionId !== sessionId || this.paths.get(key) !== claim) throw new Error("Session path reservation lost.");
1721
+ if (session.canonicalPathKey !== key) this.releasePath(session.canonicalPathKey, sessionId);
1722
+ Object.assign(session, target);
1723
+ this.sessions.set(sessionId, session);
1724
+ this.opening.delete(sessionId);
1725
+ committed = true;
1726
+ },
1727
+ release: () => {
1728
+ if (committed) return;
1729
+ if (!previous && this.paths.get(key) === claim) this.paths.delete(key);
1730
+ this.opening.delete(sessionId);
1731
+ }
1732
+ };
1733
+ }
1734
+ remove(session) {
1735
+ if (this.sessions.get(session.sessionId) !== session) return;
1736
+ this.sessions.delete(session.sessionId);
1737
+ this.releasePath(session.canonicalPathKey, session.sessionId);
1738
+ }
1739
+ releasePath(key, sessionId) {
1740
+ if (this.paths.get(key)?.sessionId === sessionId) this.paths.delete(key);
1741
+ }
1742
+ };
1743
+ //#endregion
1744
+ //#region src/services/session-operation-queue.ts
1745
+ /** Serializes lifecycle and authoring operations for one session, without blocking other sessions. */
1746
+ var SessionOperationQueue = class {
1747
+ operations = /* @__PURE__ */ new Map();
1748
+ async run(sessionId, operation) {
1749
+ const previous = this.operations.get(sessionId) ?? Promise.resolve();
1750
+ let release = () => void 0;
1751
+ const current = new Promise((resolve) => {
1752
+ release = resolve;
1753
+ });
1754
+ const tail = previous.then(() => current);
1755
+ this.operations.set(sessionId, tail);
1756
+ await previous;
1757
+ try {
1758
+ return await operation();
1759
+ } finally {
1760
+ release();
1761
+ if (this.operations.get(sessionId) === tail) this.operations.delete(sessionId);
1762
+ }
1659
1763
  }
1660
1764
  };
1661
1765
  //#endregion
1662
1766
  //#region src/services/event-service.ts
1663
1767
  const DEFAULT_EVENT_RETENTION_LIMIT = 1e3;
1664
1768
  var EventService = class {
1665
- constructor(context) {
1666
- this.context = context;
1769
+ eventsBySession = /* @__PURE__ */ new Map();
1770
+ sequence = 0;
1771
+ constructor(getSession) {
1772
+ this.getSession = getSession;
1667
1773
  }
1668
1774
  emit(event) {
1669
1775
  const emitted = {
1670
1776
  ...event,
1671
- sequence: this.context.nextEventSequence(),
1777
+ sequence: ++this.sequence,
1672
1778
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1673
1779
  diagnostics: (event.diagnostics ?? []).map((entry) => enrichBackendDiagnostic(entry, event.sessionId))
1674
1780
  };
1675
1781
  const sessionId = event.sessionId;
1676
1782
  if (!sessionId) return emitted;
1677
- const events = this.context.eventsBySession.get(sessionId) ?? [];
1783
+ const events = this.eventsBySession.get(sessionId) ?? [];
1678
1784
  events.push(emitted);
1679
1785
  while (events.length > DEFAULT_EVENT_RETENTION_LIMIT) events.shift();
1680
- this.context.eventsBySession.set(sessionId, events);
1786
+ this.eventsBySession.set(sessionId, events);
1681
1787
  return emitted;
1682
1788
  }
1683
1789
  getEvents(input) {
1684
1790
  const startedAt = Date.now();
1685
- const session = this.context.sessions.get(input.sessionId);
1791
+ const session = this.getSession(input.sessionId);
1686
1792
  if (!session || session.closed) return failure("runtime", startedAt, createSessionNotFoundError(input.sessionId));
1687
- const events = this.context.eventsBySession.get(input.sessionId) ?? [];
1793
+ const events = this.eventsBySession.get(input.sessionId) ?? [];
1688
1794
  const oldestSequence = events[0]?.sequence ?? (events.length === 0 ? 1 : 0);
1689
1795
  const currentSequence = events.at(-1)?.sequence ?? 0;
1690
1796
  const after = input.after === void 0 ? 0 : Number(input.after);
@@ -1719,281 +1825,7 @@ var EventService = class {
1719
1825
  });
1720
1826
  }
1721
1827
  removeSession(sessionId) {
1722
- this.context.eventsBySession.delete(sessionId);
1723
- }
1724
- };
1725
- //#endregion
1726
- //#region src/services/job-service.ts
1727
- const COMPLETED_JOB_RETENTION_LIMIT = 100;
1728
- const REFRESH_START_DELAY_MS = 0;
1729
- const REFRESH_COMPLETE_DELAY_MS = 50;
1730
- function isTerminal(status) {
1731
- return status === "completed" || status === "failed" || status === "cancelled";
1732
- }
1733
- var JobService = class {
1734
- constructor(context, cacheService, eventService) {
1735
- this.context = context;
1736
- this.cacheService = cacheService;
1737
- this.eventService = eventService;
1738
- }
1739
- cancellationRequests = /* @__PURE__ */ new Set();
1740
- getJobs(sessionId) {
1741
- return this.context.jobsBySession.get(sessionId) ?? [];
1742
- }
1743
- setJobs(sessionId, jobs) {
1744
- const retained = [];
1745
- let terminalCount = 0;
1746
- for (let index = jobs.length - 1; index >= 0; index -= 1) {
1747
- const job = jobs[index];
1748
- if (isTerminal(job.status)) {
1749
- if (terminalCount >= COMPLETED_JOB_RETENTION_LIMIT) continue;
1750
- terminalCount += 1;
1751
- }
1752
- retained.push(job);
1753
- }
1754
- this.context.jobsBySession.set(sessionId, retained.reverse());
1755
- }
1756
- refreshCache(input) {
1757
- const startedAt = Date.now();
1758
- const session = this.context.sessions.get(input.sessionId);
1759
- if (!session || session.closed) return failure("runtime", startedAt, createSessionNotFoundError(input.sessionId));
1760
- const jobId = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
1761
- const job = {
1762
- jobId,
1763
- kind: "cache.refresh",
1764
- status: "queued",
1765
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1766
- sessionId: session.sessionId,
1767
- canonicalPathKey: session.canonicalPathKey,
1768
- revision: session.revision,
1769
- diagnostics: [],
1770
- progress: {
1771
- completed: 0,
1772
- total: 1,
1773
- message: input.reason ?? "manual"
1774
- }
1775
- };
1776
- const jobs = this.getJobs(session.sessionId);
1777
- jobs.push(job);
1778
- this.setJobs(session.sessionId, jobs);
1779
- this.eventService.emit({
1780
- kind: "job.created",
1781
- sessionId: session.sessionId,
1782
- canonicalPathKey: session.canonicalPathKey,
1783
- revision: session.revision,
1784
- jobId
1785
- });
1786
- this.scheduleRefreshJob(session.sessionId, jobId);
1787
- return success("runtime", startedAt, structuredClone(job), {
1788
- sessionId: session.sessionId,
1789
- revision: session.revision
1790
- });
1791
- }
1792
- getJob(input) {
1793
- const startedAt = Date.now();
1794
- const session = this.context.sessions.get(input.sessionId);
1795
- if (!session || session.closed) return failure("runtime", startedAt, createSessionNotFoundError(input.sessionId));
1796
- const job = this.getJobs(input.sessionId).find((item) => item.jobId === input.jobId);
1797
- if (!job) return failure("runtime", startedAt, {
1798
- code: "job_not_found",
1799
- message: `Job was not found: ${input.jobId}`,
1800
- sessionId: input.sessionId,
1801
- jobId: input.jobId
1802
- }, void 0, {
1803
- sessionId: session.sessionId,
1804
- revision: session.revision
1805
- });
1806
- return success("runtime", startedAt, structuredClone(job), {
1807
- sessionId: session.sessionId,
1808
- revision: session.revision
1809
- });
1810
- }
1811
- listJobs(input) {
1812
- const startedAt = Date.now();
1813
- const session = this.context.sessions.get(input.sessionId);
1814
- if (!session || session.closed) return failure("runtime", startedAt, createSessionNotFoundError(input.sessionId));
1815
- let jobs = [...this.getJobs(input.sessionId)];
1816
- if (input.kind) jobs = jobs.filter((job) => job.kind === input.kind);
1817
- if (input.status) if (input.status === "active") jobs = jobs.filter((job) => !isTerminal(job.status));
1818
- else if (input.status === "terminal") jobs = jobs.filter((job) => isTerminal(job.status));
1819
- else jobs = jobs.filter((job) => job.status === input.status);
1820
- if (input.limit !== void 0) jobs = jobs.slice(0, Math.max(0, input.limit));
1821
- return success("runtime", startedAt, { jobs: jobs.map((job) => structuredClone(job)) }, {
1822
- sessionId: session.sessionId,
1823
- revision: session.revision
1824
- });
1825
- }
1826
- cancelJob(input) {
1827
- const startedAt = Date.now();
1828
- const session = this.context.sessions.get(input.sessionId);
1829
- if (!session || session.closed) return failure("runtime", startedAt, createSessionNotFoundError(input.sessionId));
1830
- const job = this.getJobs(input.sessionId).find((item) => item.jobId === input.jobId);
1831
- if (!job) return failure("runtime", startedAt, {
1832
- code: "job_not_found",
1833
- message: `Job was not found: ${input.jobId}`,
1834
- sessionId: input.sessionId,
1835
- jobId: input.jobId
1836
- }, void 0, {
1837
- sessionId: session.sessionId,
1838
- revision: session.revision
1839
- });
1840
- if (isTerminal(job.status)) return failure("runtime", startedAt, {
1841
- code: "job_not_cancellable",
1842
- message: `Job is already terminal: ${input.jobId}`,
1843
- sessionId: input.sessionId,
1844
- jobId: input.jobId,
1845
- status: job.status
1846
- }, void 0, {
1847
- sessionId: session.sessionId,
1848
- revision: session.revision
1849
- });
1850
- this.cancellationRequests.add(job.jobId);
1851
- this.eventService.emit({
1852
- kind: "job.cancelRequested",
1853
- sessionId: input.sessionId,
1854
- canonicalPathKey: session.canonicalPathKey,
1855
- revision: session.revision,
1856
- jobId: job.jobId
1857
- });
1858
- const cancelled = this.cancelRefreshJob(session.sessionId, job);
1859
- return success("runtime", startedAt, structuredClone(cancelled), {
1860
- sessionId: session.sessionId,
1861
- revision: session.revision
1862
- });
1863
- }
1864
- removeSession(sessionId) {
1865
- for (const job of this.getJobs(sessionId)) this.cancellationRequests.delete(job.jobId);
1866
- this.context.jobsBySession.delete(sessionId);
1867
- }
1868
- replaceJob(sessionId, nextJob) {
1869
- const jobs = this.getJobs(sessionId).map((job) => job.jobId === nextJob.jobId ? nextJob : job);
1870
- this.setJobs(sessionId, jobs);
1871
- }
1872
- scheduleRefreshJob(sessionId, jobId) {
1873
- setTimeout(() => this.startRefreshJob(sessionId, jobId), REFRESH_START_DELAY_MS);
1874
- }
1875
- startRefreshJob(sessionId, jobId) {
1876
- const session = this.context.sessions.get(sessionId);
1877
- if (!session || session.closed) return;
1878
- const job = this.getJobs(sessionId).find((item) => item.jobId === jobId);
1879
- if (!job || isTerminal(job.status)) return;
1880
- if (this.cancellationRequests.has(jobId)) {
1881
- this.cancelRefreshJob(sessionId, job);
1882
- return;
1883
- }
1884
- const running = {
1885
- ...job,
1886
- status: "running",
1887
- startedAt: (/* @__PURE__ */ new Date()).toISOString(),
1888
- progress: {
1889
- completed: 0,
1890
- total: 1,
1891
- message: "refreshing cache"
1892
- }
1893
- };
1894
- this.replaceJob(sessionId, running);
1895
- this.eventService.emit({
1896
- kind: "job.started",
1897
- sessionId,
1898
- canonicalPathKey: session.canonicalPathKey,
1899
- revision: session.revision,
1900
- jobId
1901
- });
1902
- this.eventService.emit({
1903
- kind: "job.progress",
1904
- sessionId,
1905
- canonicalPathKey: session.canonicalPathKey,
1906
- revision: session.revision,
1907
- jobId,
1908
- payload: running.progress
1909
- });
1910
- setTimeout(() => this.completeRefreshJob(sessionId, jobId), REFRESH_COMPLETE_DELAY_MS);
1911
- }
1912
- completeRefreshJob(sessionId, jobId) {
1913
- const session = this.context.sessions.get(sessionId);
1914
- if (!session || session.closed) return;
1915
- const job = this.getJobs(sessionId).find((item) => item.jobId === jobId);
1916
- if (!job || isTerminal(job.status)) return;
1917
- if (this.cancellationRequests.has(jobId)) {
1918
- this.cancelRefreshJob(sessionId, job);
1919
- return;
1920
- }
1921
- try {
1922
- const entry = this.cacheService.refreshSession(session);
1923
- const completed = {
1924
- ...job,
1925
- status: "completed",
1926
- finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
1927
- cacheRevision: entry.revision,
1928
- progress: {
1929
- completed: 1,
1930
- total: 1,
1931
- message: "cache refreshed"
1932
- },
1933
- result: { cacheRevision: entry.revision }
1934
- };
1935
- this.replaceJob(sessionId, completed);
1936
- this.eventService.emit({
1937
- kind: "job.completed",
1938
- sessionId,
1939
- canonicalPathKey: session.canonicalPathKey,
1940
- revision: session.revision,
1941
- cacheRevision: entry.revision,
1942
- jobId
1943
- });
1944
- this.eventService.emit({
1945
- kind: "cache.updated",
1946
- sessionId,
1947
- canonicalPathKey: session.canonicalPathKey,
1948
- revision: session.revision,
1949
- cacheRevision: entry.revision
1950
- });
1951
- } catch (error) {
1952
- const failed = {
1953
- ...job,
1954
- status: "failed",
1955
- finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
1956
- error: {
1957
- code: "cache_refresh_failed",
1958
- message: error instanceof Error ? error.message : "Cache refresh failed",
1959
- sessionId,
1960
- jobId
1961
- }
1962
- };
1963
- this.replaceJob(sessionId, failed);
1964
- this.eventService.emit({
1965
- kind: "job.failed",
1966
- sessionId,
1967
- canonicalPathKey: session.canonicalPathKey,
1968
- revision: session.revision,
1969
- jobId,
1970
- diagnostics: failed.diagnostics
1971
- });
1972
- }
1973
- }
1974
- cancelRefreshJob(sessionId, job) {
1975
- const session = this.context.sessions.get(sessionId);
1976
- const cancelled = {
1977
- ...job,
1978
- status: "cancelled",
1979
- finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
1980
- error: {
1981
- code: "job_cancelled",
1982
- message: `Job was cancelled: ${job.jobId}`,
1983
- sessionId,
1984
- jobId: job.jobId
1985
- }
1986
- };
1987
- this.replaceJob(sessionId, cancelled);
1988
- this.cancellationRequests.delete(job.jobId);
1989
- this.eventService.emit({
1990
- kind: "job.cancelled",
1991
- sessionId,
1992
- canonicalPathKey: session?.canonicalPathKey ?? job.canonicalPathKey,
1993
- revision: session?.revision ?? job.revision,
1994
- jobId: job.jobId
1995
- });
1996
- return cancelled;
1828
+ this.eventsBySession.delete(sessionId);
1997
1829
  }
1998
1830
  };
1999
1831
  //#endregion
@@ -2083,24 +1915,25 @@ function toProjectOutline(session) {
2083
1915
  };
2084
1916
  }
2085
1917
  var ReadService = class {
2086
- constructor(context) {
2087
- this.context = context;
1918
+ constructor(getSessionState, capabilities) {
1919
+ this.getSessionState = getSessionState;
1920
+ this.capabilities = capabilities;
2088
1921
  }
2089
1922
  getCapabilities() {
2090
- return success("read", Date.now(), structuredClone(this.context.capabilities));
1923
+ return success("read", Date.now(), cloneReadData(this.capabilities));
2091
1924
  }
2092
1925
  getSession(input) {
2093
1926
  const startedAt = Date.now();
2094
- const session = this.context.sessions.get(input.sessionId);
1927
+ const session = this.getSessionState(input.sessionId);
2095
1928
  if (!session || session.closed) return failure("read", startedAt, createSessionNotFoundError(input.sessionId));
2096
- return success("read", startedAt, toSessionSnapshot(session, this.context.capabilities), {
1929
+ return success("read", startedAt, toSessionSnapshot(session, this.capabilities), {
2097
1930
  sessionId: session.sessionId,
2098
1931
  revision: session.revision
2099
1932
  });
2100
1933
  }
2101
1934
  getProjectOutline(input) {
2102
1935
  const startedAt = Date.now();
2103
- const session = this.context.sessions.get(input.sessionId);
1936
+ const session = this.getSessionState(input.sessionId);
2104
1937
  if (!session || session.closed) return failure("read", startedAt, createSessionNotFoundError(input.sessionId));
2105
1938
  return success("read", startedAt, toProjectOutline(session), {
2106
1939
  sessionId: session.sessionId,
@@ -2109,7 +1942,7 @@ var ReadService = class {
2109
1942
  }
2110
1943
  queryEntity(input) {
2111
1944
  const startedAt = Date.now();
2112
- const session = this.context.sessions.get(input.sessionId);
1945
+ const session = this.getSessionState(input.sessionId);
2113
1946
  if (!session || session.closed) return failure("read", startedAt, createSessionNotFoundError(input.sessionId));
2114
1947
  const meta = {
2115
1948
  sessionId: session.sessionId,
@@ -2130,7 +1963,7 @@ var ReadService = class {
2130
1963
  entity
2131
1964
  };
2132
1965
  const problem = queryResponseProblem(data);
2133
- return problem ? reject(problem) : success("read", startedAt, structuredClone(data), meta);
1966
+ return problem ? reject(problem) : success("read", startedAt, cloneReadData(data), meta);
2134
1967
  };
2135
1968
  if (target.kind === "project") {
2136
1969
  if (Object.hasOwn(target, "selector")) return reject("invalid_query");
@@ -2224,7 +2057,7 @@ var ReadService = class {
2224
2057
  }
2225
2058
  resolveReadSession(input, startedAt) {
2226
2059
  if (!input || typeof input.sessionId !== "string" || !input.sessionId.length || input.sessionId.length > 256 || input.expectedRevision !== void 0 && (!Number.isSafeInteger(input.expectedRevision) || input.expectedRevision < 0)) return readFailure(startedAt, typeof input?.sessionId === "string" ? input.sessionId : "", "invalid_query");
2227
- const session = this.context.sessions.get(input.sessionId);
2060
+ const session = this.getSessionState(input.sessionId);
2228
2061
  if (!session || session.closed) return failure("read", startedAt, createSessionNotFoundError(input.sessionId));
2229
2062
  const meta = {
2230
2063
  sessionId: session.sessionId,
@@ -2268,7 +2101,7 @@ var ReadService = class {
2268
2101
  }
2269
2102
  };
2270
2103
  const problem = queryResponseProblem(data, BACKEND_SESSION_READ_LIMITS.model);
2271
- return problem ? readFailure(startedAt, session.sessionId, problem, session.revision) : success("read", startedAt, structuredClone(data), meta);
2104
+ return problem ? readFailure(startedAt, session.sessionId, problem, session.revision) : success("read", startedAt, cloneReadData(data), meta);
2272
2105
  }
2273
2106
  readResourceBytes(input) {
2274
2107
  const startedAt = Date.now();
@@ -2298,10 +2131,10 @@ var ReadService = class {
2298
2131
  }
2299
2132
  validateSession(input) {
2300
2133
  const startedAt = Date.now();
2301
- const session = this.context.sessions.get(input.sessionId);
2134
+ const session = this.getSessionState(input.sessionId);
2302
2135
  if (!session || session.closed) return failure("read", startedAt, createSessionNotFoundError(input.sessionId));
2303
- const report = validateProject(session.project, {
2304
- readDiagnostics: session.readDiagnostics,
2136
+ const report = validateProject(cloneReadData(session.project), {
2137
+ readDiagnostics: cloneReadData(session.readDiagnostics),
2305
2138
  complete: session.readComplete,
2306
2139
  validateSources: true
2307
2140
  });
@@ -2340,6 +2173,7 @@ function createProjectReaderFileSystem(fileSystem, projectRoot) {
2340
2173
  return operation();
2341
2174
  };
2342
2175
  return {
2176
+ stat: (path) => contained(path, () => fileSystem.stat(path)),
2343
2177
  readFile(filePath) {
2344
2178
  return contained(filePath, () => fileSystem.readFile(filePath));
2345
2179
  },
@@ -2387,11 +2221,10 @@ async function hasFullUamFidelity(document, project) {
2387
2221
  return capturedFilesEqual(sourceFiles, materializedFiles) && capturedDirectoriesEqual(sourceDirectories, materializedDirectories);
2388
2222
  }
2389
2223
  var RuntimeService = class {
2390
- constructor(context, cacheService, eventService, jobService) {
2224
+ constructor(context, cacheService, eventService) {
2391
2225
  this.context = context;
2392
2226
  this.cacheService = cacheService;
2393
2227
  this.eventService = eventService;
2394
- this.jobService = jobService;
2395
2228
  }
2396
2229
  async openSession(input) {
2397
2230
  const startedAt = Date.now();
@@ -2414,16 +2247,14 @@ var RuntimeService = class {
2414
2247
  }
2415
2248
  const { fairyPath, canonicalProjectPath, canonicalPathKey } = await resolveCanonicalProjectRoot(fileSystem, input.projectPath);
2416
2249
  await fileSystem.validateProjectRoot?.(canonicalProjectPath);
2417
- const existingSessionId = this.context.sessionsByPath.get(canonicalPathKey);
2418
2250
  const lockFilePath = fileSystem.getSessionLockPath?.(canonicalProjectPath) ?? fileSystem.join(canonicalProjectPath, ".openfairygui.backend.lock");
2419
- if (existingSessionId) return failure("runtime", startedAt, {
2420
- code: "lock_conflict",
2421
- kind: "in_process_session_exists",
2422
- message: `Project is already open in this backend runtime: ${canonicalProjectPath}`,
2251
+ const sessionId = randomId();
2252
+ const reservation = this.context.sessions.reserve(sessionId, {
2423
2253
  canonicalPathKey,
2424
- holderSessionId: existingSessionId,
2254
+ canonicalProjectPath,
2425
2255
  lockFilePath
2426
2256
  });
2257
+ if ("code" in reservation) return failure("runtime", startedAt, reservation);
2427
2258
  let sessionLock = null;
2428
2259
  try {
2429
2260
  sessionLock = await fileSystem.acquireSessionLock(lockFilePath);
@@ -2439,7 +2270,6 @@ var RuntimeService = class {
2439
2270
  if (!read.document) throw new Error(read.diagnostics[0]?.message ?? `Unable to read project: ${fairyPath}`);
2440
2271
  const document = read.document;
2441
2272
  const project = liftDocumentToUamProject(document);
2442
- const sessionId = randomId();
2443
2273
  const session = {
2444
2274
  sessionId,
2445
2275
  fairyPath,
@@ -2451,7 +2281,7 @@ var RuntimeService = class {
2451
2281
  project,
2452
2282
  readDiagnostics: read.diagnostics,
2453
2283
  readComplete: read.complete,
2454
- uamFidelity: await hasFullUamFidelity(document, project) ? "full" : "unsupported",
2284
+ uamFidelity: read.complete && await hasFullUamFidelity(document, project) ? "full" : "unsupported",
2455
2285
  revision: 0,
2456
2286
  lastSavedRevision: 0,
2457
2287
  pendingStaleSourceFiles: /* @__PURE__ */ new Map(),
@@ -2461,8 +2291,7 @@ var RuntimeService = class {
2461
2291
  lockHeld: true,
2462
2292
  closed: false
2463
2293
  };
2464
- this.context.sessions.set(sessionId, session);
2465
- this.context.sessionsByPath.set(canonicalPathKey, sessionId);
2294
+ reservation.commit(session);
2466
2295
  this.cacheService.refreshSession(session);
2467
2296
  this.eventService.emit({
2468
2297
  kind: "session.opened",
@@ -2488,6 +2317,8 @@ var RuntimeService = class {
2488
2317
  message: error instanceof Error ? error.message : String(error)
2489
2318
  });
2490
2319
  throw error;
2320
+ } finally {
2321
+ reservation.release();
2491
2322
  }
2492
2323
  }
2493
2324
  openProjectSession(input) {
@@ -2502,14 +2333,12 @@ var RuntimeService = class {
2502
2333
  const memoryProjectPath = `memory://${sessionId}`;
2503
2334
  const canonicalProjectPath = storage?.canonicalProjectPath ?? input.canonicalProjectPath ?? (storage ? storage.fileSystem.dirname(storage.fairyPath) || "." : memoryProjectPath);
2504
2335
  const canonicalPathKey = storage?.canonicalPathKey ?? input.canonicalPathKey ?? (storage ? normalizeComparablePath(canonicalProjectPath) : canonicalProjectPath.toLowerCase());
2505
- const existingSessionId = this.context.sessionsByPath.get(canonicalPathKey);
2506
- if (existingSessionId) return failure("runtime", startedAt, {
2507
- code: "lock_conflict",
2508
- kind: "in_process_session_exists",
2509
- message: `Project is already open in this backend runtime: ${canonicalProjectPath}`,
2336
+ const project = normalizeUamProject(input.project);
2337
+ const reservation = this.context.sessions.reserve(sessionId, {
2510
2338
  canonicalPathKey,
2511
- holderSessionId: existingSessionId
2339
+ canonicalProjectPath
2512
2340
  });
2341
+ if ("code" in reservation) return failure("runtime", startedAt, reservation);
2513
2342
  const session = {
2514
2343
  sessionId,
2515
2344
  fairyPath: storage?.fairyPath ?? canonicalProjectPath,
@@ -2518,7 +2347,7 @@ var RuntimeService = class {
2518
2347
  lockFilePath: "",
2519
2348
  sessionLock: null,
2520
2349
  fileSystem: storage?.fileSystem,
2521
- project: normalizeUamProject(input.project),
2350
+ project,
2522
2351
  readDiagnostics: [],
2523
2352
  readComplete: true,
2524
2353
  uamFidelity: "full",
@@ -2531,8 +2360,7 @@ var RuntimeService = class {
2531
2360
  lockHeld: false,
2532
2361
  closed: false
2533
2362
  };
2534
- this.context.sessions.set(sessionId, session);
2535
- this.context.sessionsByPath.set(canonicalPathKey, sessionId);
2363
+ reservation.commit(session);
2536
2364
  this.cacheService.refreshSession(session);
2537
2365
  this.eventService.emit({
2538
2366
  kind: "session.opened",
@@ -2555,14 +2383,24 @@ var RuntimeService = class {
2555
2383
  canonicalPathKey: session.canonicalPathKey,
2556
2384
  revision: session.revision
2557
2385
  });
2558
- await session.sessionLock?.release().catch(() => void 0);
2386
+ try {
2387
+ await session.sessionLock?.release();
2388
+ } catch (error) {
2389
+ return failure("runtime", startedAt, {
2390
+ code: "session_close_failed",
2391
+ message: error instanceof Error ? error.message : String(error),
2392
+ sessionId: session.sessionId,
2393
+ lockFilePath: session.lockFilePath
2394
+ }, toSessionSnapshot(session, this.context.capabilities), {
2395
+ sessionId: session.sessionId,
2396
+ revision: session.revision
2397
+ });
2398
+ }
2559
2399
  session.sessionLock = null;
2560
2400
  session.lockHeld = false;
2561
2401
  session.closed = true;
2562
- this.context.sessions.delete(session.sessionId);
2563
- this.context.sessionsByPath.delete(session.canonicalPathKey);
2402
+ this.context.sessions.remove(session);
2564
2403
  this.cacheService.removeSession(session.sessionId);
2565
- this.jobService.removeSession(session.sessionId);
2566
2404
  this.eventService.emit({
2567
2405
  kind: "session.closed",
2568
2406
  sessionId: session.sessionId,
@@ -2615,9 +2453,6 @@ const BACKEND_METHODS = [
2615
2453
  "materializeSession",
2616
2454
  "closeSession",
2617
2455
  "getEvents",
2618
- "getJob",
2619
- "listJobs",
2620
- "cancelJob",
2621
2456
  "getCacheSnapshot",
2622
2457
  "refreshCache"
2623
2458
  ];
@@ -2631,7 +2466,7 @@ const ARTIFACT_BRIDGE_CAPABILITY = {
2631
2466
  function createCapabilities(atomicSave = false) {
2632
2467
  return {
2633
2468
  contractVersion: BACKEND_CONTRACT_VERSION,
2634
- capabilitySchemaVersion: 11,
2469
+ capabilitySchemaVersion: 12,
2635
2470
  transactionKernelOwner: "@openfairygui/core",
2636
2471
  appSeamOwner: "@openfairygui/functions",
2637
2472
  runtimeOwner: "@openfairygui/backend",
@@ -2740,17 +2575,10 @@ function createCapabilities(atomicSave = false) {
2740
2575
  retentionLimit: 1e3,
2741
2576
  sequenceScope: "runtime"
2742
2577
  },
2743
- jobs: {
2744
- inMemory: true,
2745
- cooperativeCancel: true,
2746
- persistent: false,
2747
- supportedKinds: ["cache.refresh"],
2748
- artifactJobs: false,
2749
- completedRetentionLimit: 100
2750
- },
2751
2578
  cache: {
2752
2579
  derivedReadOnly: true,
2753
- keyedBy: "canonicalPathKey",
2580
+ keyedBy: "sessionId",
2581
+ refreshMode: "synchronous",
2754
2582
  sourceOfTruth: false,
2755
2583
  refreshMethod: "refreshCache"
2756
2584
  }
@@ -2762,19 +2590,15 @@ function createCapabilities(atomicSave = false) {
2762
2590
  var BackendRuntime = class {
2763
2591
  fileSystem;
2764
2592
  capabilities;
2765
- sessions = /* @__PURE__ */ new Map();
2766
- sessionsByPath = /* @__PURE__ */ new Map();
2767
- eventsBySession = /* @__PURE__ */ new Map();
2768
- jobsBySession = /* @__PURE__ */ new Map();
2769
- cacheBySession = /* @__PURE__ */ new Map();
2770
- eventSequence = 0;
2593
+ sessions = new SessionRegistry();
2594
+ sessionOperations = new SessionOperationQueue();
2771
2595
  context;
2772
2596
  readService;
2773
2597
  runtimeService;
2774
2598
  authoringService;
2599
+ persistenceService;
2775
2600
  cacheService;
2776
2601
  eventService;
2777
- jobService;
2778
2602
  constructor(options = {}) {
2779
2603
  this.fileSystem = options.fileSystem;
2780
2604
  this.capabilities = createCapabilities(Boolean(options.fileSystem?.runProjectWriteTransaction));
@@ -2783,22 +2607,15 @@ var BackendRuntime = class {
2783
2607
  host: options.host,
2784
2608
  allowedProjectRoots: options.allowedProjectRoots,
2785
2609
  capabilities: this.capabilities,
2786
- sessions: this.sessions,
2787
- sessionsByPath: this.sessionsByPath,
2788
- eventsBySession: this.eventsBySession,
2789
- jobsBySession: this.jobsBySession,
2790
- cacheBySession: this.cacheBySession,
2791
- nextEventSequence: () => {
2792
- this.eventSequence += 1;
2793
- return this.eventSequence;
2794
- }
2610
+ sessions: this.sessions
2795
2611
  };
2796
- this.readService = new ReadService(this.context);
2797
- this.eventService = new EventService(this.context);
2798
- this.cacheService = new CacheService(this.context);
2799
- this.jobService = new JobService(this.context, this.cacheService, this.eventService);
2800
- this.runtimeService = new RuntimeService(this.context, this.cacheService, this.eventService, this.jobService);
2801
- this.authoringService = new AuthoringService(this.context, this.cacheService, this.eventService);
2612
+ const getSession = (sessionId) => this.sessions.get(sessionId);
2613
+ this.readService = new ReadService((sessionId) => readView(getSession(sessionId)), this.capabilities);
2614
+ this.eventService = new EventService(getSession);
2615
+ this.cacheService = new CacheService(getSession, this.eventService);
2616
+ this.runtimeService = new RuntimeService(this.context, this.cacheService, this.eventService);
2617
+ this.authoringService = new AuthoringService(this.context, this.cacheService, this.eventService, this.sessionOperations);
2618
+ this.persistenceService = new PersistenceService(this.context, this.cacheService, this.eventService, this.sessionOperations);
2802
2619
  }
2803
2620
  getCapabilities() {
2804
2621
  return this.readService.getCapabilities();
@@ -2843,31 +2660,23 @@ var BackendRuntime = class {
2843
2660
  return this.authoringService.applyTransaction(input);
2844
2661
  }
2845
2662
  async saveSession(input) {
2846
- return this.authoringService.saveSession(input);
2663
+ return this.persistenceService.saveSession(input);
2847
2664
  }
2848
2665
  async materializeSession(input) {
2849
- return this.authoringService.materializeSession(input);
2666
+ return this.persistenceService.materializeSession(input);
2850
2667
  }
2851
2668
  async closeSession(input) {
2852
- return this.authoringService.runSessionExclusive(input.sessionId, () => this.runtimeService.closeSession(input));
2669
+ const captured = { ...input };
2670
+ return this.sessionOperations.run(captured.sessionId, () => this.runtimeService.closeSession(captured));
2853
2671
  }
2854
2672
  getEvents(input) {
2855
2673
  return this.eventService.getEvents(input);
2856
2674
  }
2857
- getJob(input) {
2858
- return this.jobService.getJob(input);
2859
- }
2860
- listJobs(input) {
2861
- return this.jobService.listJobs(input);
2862
- }
2863
- cancelJob(input) {
2864
- return this.jobService.cancelJob(input);
2865
- }
2866
2675
  getCacheSnapshot(input) {
2867
2676
  return this.cacheService.getCacheSnapshot(input);
2868
2677
  }
2869
2678
  refreshCache(input) {
2870
- return this.jobService.refreshCache(input);
2679
+ return this.cacheService.refreshCache(input);
2871
2680
  }
2872
2681
  };
2873
2682
  //#endregion
@@ -2976,39 +2785,36 @@ async function runNodeProjectWriteTransaction(projectRoot, write) {
2976
2785
  const staging = path.join(parent, `.${name}.save-${randomUUID()}`);
2977
2786
  const backup = path.join(parent, `.${name}.save-backup-${randomUUID()}`);
2978
2787
  const existed = await pathExists(root);
2979
- if (existed) {
2980
- await assertNoSymlinks(root);
2981
- await fs.cp(root, staging, {
2982
- recursive: true,
2983
- errorOnExist: true,
2984
- force: false
2985
- });
2986
- } else await fs.mkdir(staging, { recursive: true });
2987
2788
  try {
2789
+ if (existed) {
2790
+ await assertNoSymlinks(root);
2791
+ await fs.cp(root, staging, {
2792
+ recursive: true,
2793
+ errorOnExist: true,
2794
+ force: false
2795
+ });
2796
+ } else await fs.mkdir(staging, { recursive: true });
2988
2797
  await write(createStagedNodeFileSystem(root, staging));
2798
+ if (existed) await fs.rename(root, backup);
2799
+ try {
2800
+ await fs.rename(staging, root);
2801
+ } catch (commitError) {
2802
+ if (existed) try {
2803
+ await fs.rename(backup, root);
2804
+ } catch (rollbackError) {
2805
+ throw new ProjectWriteTransactionError(new AggregateError([commitError, rollbackError], "Project commit and rollback both failed."), true, [backup, staging]);
2806
+ }
2807
+ throw commitError;
2808
+ }
2989
2809
  } catch (error) {
2810
+ if (ProjectWriteTransactionError.is(error)) throw error;
2990
2811
  await fs.rm(staging, {
2991
2812
  recursive: true,
2992
2813
  force: true
2993
- });
2994
- throw error;
2995
- }
2996
- if (!existed) {
2997
- await fs.rename(staging, root);
2998
- return;
2999
- }
3000
- await fs.rename(root, backup);
3001
- try {
3002
- await fs.rename(staging, root);
3003
- } catch (error) {
3004
- await fs.rename(backup, root);
3005
- await fs.rm(staging, {
3006
- recursive: true,
3007
- force: true
3008
- });
3009
- throw error;
2814
+ }).catch(() => void 0);
2815
+ throw new ProjectWriteTransactionError(error, false);
3010
2816
  }
3011
- await fs.rm(backup, {
2817
+ if (existed) await fs.rm(backup, {
3012
2818
  recursive: true,
3013
2819
  force: true
3014
2820
  }).catch(() => void 0);
@@ -3093,10 +2899,16 @@ function createNodeBackendFileSystem() {
3093
2899
  async release() {
3094
2900
  if (released) return;
3095
2901
  await closeHandle();
3096
- const current = metadataWritten ? parseLockMetadata(await fs.readFile(filePath, "utf-8").catch(() => "")) : null;
3097
- if (!metadataWritten || current?.token === owner.token) await fs.unlink(filePath).catch((error) => {
2902
+ try {
2903
+ if (metadataWritten) {
2904
+ const current = parseLockMetadata(await fs.readFile(filePath, "utf-8"));
2905
+ if (!current) throw new Error("Cannot release session lock: invalid ownership metadata");
2906
+ if (current.token !== owner.token) throw new Error("Cannot release session lock: ownership token changed");
2907
+ }
2908
+ await fs.unlink(filePath);
2909
+ } catch (error) {
3098
2910
  if (error.code !== "ENOENT") throw error;
3099
- });
2911
+ }
3100
2912
  released = true;
3101
2913
  }
3102
2914
  };