@openfairygui/backend 0.3.0 → 0.4.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
@@ -1,5 +1,7 @@
1
1
  import fs from "node:fs/promises";
2
+ import os from "node:os";
2
3
  import path from "node:path";
4
+ import { randomUUID } from "node:crypto";
3
5
  import { UAM_SUPPORTED_MATERIALIZATION_SCOPE, UAM_SUPPORTED_TRANSACTION_SCOPE, commitUamProjectSourcePaths, liftDocumentToUamProject, materializeUamProject, normalizeUamProject, staleBranchDirectories, staleResourceFolders, staleSourceFiles, validateUamProject } from "@openfairygui/core/uam";
4
6
  import { applyUamTransactionAppAsync } from "@openfairygui/functions/uam";
5
7
  import { ProjectReader, ProjectWriter } from "@openfairygui/core/project-io";
@@ -34,6 +36,16 @@ function createRuntimePathPolicy() {
34
36
  workspaceBoundary: "project-root-only"
35
37
  };
36
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
+ }
37
49
  async function resolveFairyPath(fileSystem, input) {
38
50
  const resolvedInput = fileSystem.resolve(input);
39
51
  const stat = await fileSystem.stat(resolvedInput);
@@ -70,13 +82,622 @@ async function validateSaveTarget(fileSystem, openedFairyPath, targetPath) {
70
82
  }
71
83
  //#endregion
72
84
  //#region src/contracts.ts
73
- const BACKEND_CONTRACT_VERSION = "1.1.0-p2";
85
+ const BACKEND_CONTRACT_VERSION = "2.0.0-p2";
74
86
  const BACKEND_COMPATIBILITY_POLICY = {
75
87
  incompatibleChange: "requires contractVersion bump",
76
88
  capabilitySchemaChange: "requires capabilitySchemaVersion bump",
77
89
  additiveChange: "allowed without breaking existing consumers"
78
90
  };
79
91
  //#endregion
92
+ //#region src/diagnostics.ts
93
+ const selector = {
94
+ kind: "revise-selector",
95
+ message: "Read the current outline and query the relevant entity. Use its exact identifiers, inspect the reported selector path, then rebuild and preflight the transaction. Do not guess identifiers or retry the unchanged transaction."
96
+ };
97
+ const source = {
98
+ kind: "host-action",
99
+ message: "Ask the host to inspect the reported source and hydrate its bytes through project I/O or import. Preserve unsaved work; reopening disk state can discard it. No session hydration/repair API is exposed. Revalidate and replan after the host has supplied a complete project."
100
+ };
101
+ const path$1 = {
102
+ kind: "host-action",
103
+ message: "Ask the host to review the attempted path and authorized project root. saveSession only writes the original project; it is not Save As. Do not widen allowed roots or bypass path checks. A separately authorized export may use materializeSession."
104
+ };
105
+ const unsupported = {
106
+ kind: "revise-operation",
107
+ message: "Read the operation schema, capabilities and reported target kind/field. Stop unsupported work or replan using supported operations with equivalent intended semantics. Never silently drop fields or objects to make a transaction pass."
108
+ };
109
+ const payload = {
110
+ kind: "revise-operation",
111
+ message: "Inspect the diagnostic path and current operation schema or UAM issues. Correct values, required fields and indices against exact queried entities, then preflight. Do not invent defaults or coerce away invalid data."
112
+ };
113
+ const unchanged = {
114
+ kind: "refresh-and-replan",
115
+ message: "Query current settings/entity and compare with the request. If already satisfied, report no change; otherwise replan from the current revision. Do not manufacture a mutation or resubmit the same no-op."
116
+ };
117
+ const duplicate = {
118
+ kind: "revise-operation",
119
+ message: "Query current entities and resolve the conflicting ID, name or page explicitly. Choose an unused value only when authorized by the intended edit, then preflight. Never overwrite or delete an existing entity to clear the conflict."
120
+ };
121
+ const references = {
122
+ kind: "revise-operation",
123
+ message: "Query affected entities and references before editing, moving or removing anything. Replan intended dependent changes together and preflight. Do not delete dependent objects or strip references without authorization."
124
+ };
125
+ const project = {
126
+ kind: "host-action",
127
+ message: "Inspect the project path and validation diagnostics with the host. Correct source XML/settings or unsupported geometry using authoritative project data; preserve originals and unsaved work before reopening or validating. Do not guess missing structure or discard rejected content."
128
+ };
129
+ const capability = {
130
+ kind: "host-action",
131
+ message: "Read capability/error details. Ask the host to provide the required filesystem, decoder or complete UAM adapter. Preserve the session and unsaved work; do not substitute a lossy path or bypass checks."
132
+ };
133
+ const write = {
134
+ kind: "host-action",
135
+ 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
+ };
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
+ /** Exhaustiveness and exact ownership are checked against the canonical unions. */
146
+ const BACKEND_DIAGNOSTIC_GUIDES = [
147
+ {
148
+ code: "transaction_preview_failed",
149
+ owners: ["backend"],
150
+ remediation: {
151
+ kind: "host-action",
152
+ message: "No complete preview is available. Inspect error.reason with the host: response_budget_exceeded requires a smaller independently meaningful authorized batch; projection_failed requires inspecting the project serialization failure. Preserve the session and never treat a missing or truncated impact as approval to apply or save."
153
+ }
154
+ },
155
+ {
156
+ code: "stale_write",
157
+ owners: ["backend"],
158
+ remediation: {
159
+ kind: "refresh-and-replan",
160
+ message: "Refresh the outline and affected entities, then replan from their current revision and preflight again. A preview reserves no revision. Never replace expectedRevision and blindly retry the original transaction or save."
161
+ }
162
+ },
163
+ {
164
+ code: "entity_query_failed",
165
+ owners: ["backend"],
166
+ remediation: {
167
+ kind: "host-action",
168
+ message: "Inspect error.reason: invalid_query requires correcting the target; not_found/ambiguous requires current exact identifiers; response_budget_exceeded/non_json_value requires host inspection of the entity. Do not broaden queries or mutate data to evade the response limits."
169
+ }
170
+ },
171
+ {
172
+ code: "session_not_found",
173
+ owners: ["backend"],
174
+ remediation: {
175
+ kind: "host-action",
176
+ 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."
177
+ }
178
+ },
179
+ {
180
+ code: "path_policy_violation",
181
+ owners: ["backend"],
182
+ remediation: path$1
183
+ },
184
+ {
185
+ code: "project_root_not_allowed",
186
+ owners: ["backend"],
187
+ remediation: path$1
188
+ },
189
+ {
190
+ code: "invalid_package_selector",
191
+ owners: ["core.transaction"],
192
+ remediation: selector
193
+ },
194
+ {
195
+ code: "invalid_component_selector",
196
+ owners: ["core.transaction"],
197
+ remediation: selector
198
+ },
199
+ {
200
+ code: "invalid_resource_selector",
201
+ owners: ["core.transaction"],
202
+ remediation: selector
203
+ },
204
+ {
205
+ code: "invalid_display_node_selector",
206
+ owners: ["core.transaction"],
207
+ remediation: selector
208
+ },
209
+ {
210
+ code: "invalid_resource_folder_selector",
211
+ owners: ["core.transaction"],
212
+ remediation: selector
213
+ },
214
+ {
215
+ code: "invalid_branch_selector",
216
+ owners: ["core.transaction"],
217
+ remediation: selector
218
+ },
219
+ {
220
+ code: "invalid_gear_selector",
221
+ owners: ["core.transaction"],
222
+ remediation: selector
223
+ },
224
+ {
225
+ code: "invalid_look_gear_selector",
226
+ owners: ["core.transaction"],
227
+ remediation: selector
228
+ },
229
+ {
230
+ code: "selector_ambiguity",
231
+ owners: ["core.transaction"],
232
+ remediation: selector
233
+ },
234
+ {
235
+ code: "unavailable_resource_source_bytes",
236
+ owners: ["core.transaction"],
237
+ remediation: source
238
+ },
239
+ {
240
+ code: "missing_source",
241
+ owners: ["core.validation"],
242
+ remediation: source
243
+ },
244
+ {
245
+ code: "unreadable_source",
246
+ owners: ["core.validation"],
247
+ remediation: source
248
+ },
249
+ {
250
+ code: "decode_capability_unavailable",
251
+ owners: ["core.validation"],
252
+ remediation: {
253
+ kind: "host-action",
254
+ message: "Validation is incomplete, not passed. Inspect whether source bytes are unloaded or a decoder is unavailable. Ask the host to hydrate sources or provide the required decoder (Node image validation uses optional Sharp), then validate again. Do not install dependencies or change the project automatically."
255
+ }
256
+ },
257
+ {
258
+ code: "session_id_conflict",
259
+ owners: ["backend"],
260
+ remediation: {
261
+ kind: "host-action",
262
+ message: "Use getSession to inspect the existing session. Reuse it only for the intended project, or choose a new session ID; do not close another owner\\u0027s session to make room."
263
+ }
264
+ },
265
+ {
266
+ code: "lock_conflict",
267
+ owners: ["backend"],
268
+ remediation: {
269
+ kind: "host-action",
270
+ message: "Another owner holds the project lock. Preserve unsaved work and ask that owner to close its session, then explicitly reopen. Never remove a live lock, force-close a peer, or bypass locking."
271
+ }
272
+ },
273
+ {
274
+ code: "event_cursor_invalid",
275
+ owners: ["backend"],
276
+ remediation: {
277
+ kind: "refresh-and-replan",
278
+ message: "Read the error and getEvents cursor bounds. Request a fresh bounded event page without the invalid cursor and refresh the current outline before replanning; missing retained history is not evidence that nothing changed."
279
+ }
280
+ },
281
+ {
282
+ code: "corrupt_source",
283
+ owners: ["core.validation"],
284
+ remediation: source
285
+ },
286
+ {
287
+ code: "unsupported_operation",
288
+ owners: ["core.transaction"],
289
+ remediation: unsupported
290
+ },
291
+ {
292
+ code: "transaction_unsupported",
293
+ owners: ["core.transaction"],
294
+ remediation: unsupported
295
+ },
296
+ {
297
+ code: "unsupported_display_node_kind",
298
+ owners: ["core.transaction"],
299
+ remediation: unsupported
300
+ },
301
+ {
302
+ code: "unsupported_cross_package_image_ref",
303
+ owners: ["core.transaction"],
304
+ remediation: unsupported
305
+ },
306
+ {
307
+ code: "unsupported_gear_kind",
308
+ owners: ["core.transaction"],
309
+ remediation: unsupported
310
+ },
311
+ {
312
+ code: "unsupported_resource_mutation",
313
+ owners: ["core.transaction"],
314
+ remediation: unsupported
315
+ },
316
+ {
317
+ code: "unsupported_display_node_mutation",
318
+ owners: ["core.transaction"],
319
+ remediation: unsupported
320
+ },
321
+ {
322
+ code: "unsupported_text_field_target",
323
+ owners: ["core.transaction"],
324
+ remediation: unsupported
325
+ },
326
+ {
327
+ code: "unsupported_display_node_field",
328
+ owners: ["core.transaction"],
329
+ remediation: unsupported
330
+ },
331
+ {
332
+ code: "unsupported_operation_batch",
333
+ owners: ["core.transaction"],
334
+ remediation: unsupported
335
+ },
336
+ {
337
+ code: "unsupported_resource_kind",
338
+ owners: ["core.transaction", "core.validation"],
339
+ remediation: unsupported
340
+ },
341
+ {
342
+ code: "invalid_project_settings",
343
+ owners: ["core.transaction"],
344
+ remediation: payload
345
+ },
346
+ {
347
+ code: "invalid_package_settings",
348
+ owners: ["core.transaction"],
349
+ remediation: payload
350
+ },
351
+ {
352
+ code: "invalid_display_node_payload",
353
+ owners: ["core.transaction"],
354
+ remediation: payload
355
+ },
356
+ {
357
+ code: "invalid_resource_name",
358
+ owners: ["core.transaction"],
359
+ remediation: payload
360
+ },
361
+ {
362
+ code: "invalid_resource_path",
363
+ owners: ["core.transaction"],
364
+ remediation: payload
365
+ },
366
+ {
367
+ code: "invalid_resource_folder_path",
368
+ owners: ["core.transaction"],
369
+ remediation: payload
370
+ },
371
+ {
372
+ code: "invalid_resource_folder_atlas",
373
+ owners: ["core.transaction"],
374
+ remediation: payload
375
+ },
376
+ {
377
+ code: "invalid_attach_index",
378
+ owners: ["core.transaction"],
379
+ remediation: payload
380
+ },
381
+ {
382
+ code: "invalid_controller_payload",
383
+ owners: ["core.transaction"],
384
+ remediation: payload
385
+ },
386
+ {
387
+ code: "invalid_transition_payload",
388
+ owners: ["core.transaction"],
389
+ remediation: payload
390
+ },
391
+ {
392
+ code: "invalid_look_gear_payload",
393
+ owners: ["core.transaction"],
394
+ remediation: payload
395
+ },
396
+ {
397
+ code: "invalid_gear_payload",
398
+ owners: ["core.transaction"],
399
+ remediation: payload
400
+ },
401
+ {
402
+ code: "invalid_resource_payload",
403
+ owners: ["core.transaction"],
404
+ remediation: payload
405
+ },
406
+ {
407
+ code: "invalid_resource_bytes",
408
+ owners: ["core.transaction"],
409
+ remediation: payload
410
+ },
411
+ {
412
+ code: "invalid_movie_clip_jta",
413
+ owners: ["core.transaction"],
414
+ remediation: payload
415
+ },
416
+ {
417
+ code: "invalid_resource_index",
418
+ owners: ["core.transaction"],
419
+ remediation: payload
420
+ },
421
+ {
422
+ code: "invalid_branch_name",
423
+ owners: ["core.transaction"],
424
+ remediation: payload
425
+ },
426
+ {
427
+ code: "invalid_package_payload",
428
+ owners: ["core.transaction"],
429
+ remediation: payload
430
+ },
431
+ {
432
+ code: "invalid_package_index",
433
+ owners: ["core.transaction"],
434
+ remediation: payload
435
+ },
436
+ {
437
+ code: "invalid_component_payload",
438
+ owners: ["core.transaction"],
439
+ remediation: payload
440
+ },
441
+ {
442
+ code: "invalid_component_index",
443
+ owners: ["core.transaction"],
444
+ remediation: payload
445
+ },
446
+ {
447
+ code: "invalid_component_move",
448
+ owners: ["core.transaction"],
449
+ remediation: payload
450
+ },
451
+ {
452
+ code: "invalid_uam",
453
+ owners: ["core.transaction", "core.validation"],
454
+ remediation: payload
455
+ },
456
+ {
457
+ code: "project_settings_unchanged",
458
+ owners: ["core.transaction"],
459
+ remediation: unchanged
460
+ },
461
+ {
462
+ code: "package_settings_unchanged",
463
+ owners: ["core.transaction"],
464
+ remediation: unchanged
465
+ },
466
+ {
467
+ code: "display_node_props_unchanged",
468
+ owners: ["core.transaction"],
469
+ remediation: unchanged
470
+ },
471
+ {
472
+ code: "resource_folder_atlas_unchanged",
473
+ owners: ["core.transaction"],
474
+ remediation: unchanged
475
+ },
476
+ {
477
+ code: "duplicate_look_gear_controller",
478
+ owners: ["core.transaction"],
479
+ remediation: duplicate
480
+ },
481
+ {
482
+ code: "duplicate_transition_name",
483
+ owners: ["core.transaction"],
484
+ remediation: duplicate
485
+ },
486
+ {
487
+ code: "duplicate_look_gear_state_page",
488
+ owners: ["core.transaction"],
489
+ remediation: duplicate
490
+ },
491
+ {
492
+ code: "duplicate_gear_controller",
493
+ owners: ["core.transaction"],
494
+ remediation: duplicate
495
+ },
496
+ {
497
+ code: "duplicate_gear_state_page",
498
+ owners: ["core.transaction"],
499
+ remediation: duplicate
500
+ },
501
+ {
502
+ code: "duplicate_branch_name",
503
+ owners: ["core.transaction"],
504
+ remediation: duplicate
505
+ },
506
+ {
507
+ code: "duplicate_component_id",
508
+ owners: ["core.transaction"],
509
+ remediation: duplicate
510
+ },
511
+ {
512
+ code: "resource_folder_conflict",
513
+ owners: ["core.transaction"],
514
+ remediation: duplicate
515
+ },
516
+ {
517
+ code: "duplicate_resource_id",
518
+ owners: ["core.transaction", "core.validation"],
519
+ remediation: duplicate
520
+ },
521
+ {
522
+ code: "duplicate_package_id",
523
+ owners: ["core.transaction", "core.validation"],
524
+ remediation: duplicate
525
+ },
526
+ {
527
+ code: "duplicate_package_name",
528
+ owners: ["core.transaction", "core.validation"],
529
+ remediation: duplicate
530
+ },
531
+ {
532
+ code: "resource_folder_not_empty",
533
+ owners: ["core.transaction"],
534
+ remediation: references
535
+ },
536
+ {
537
+ code: "branch_not_empty",
538
+ owners: ["core.transaction"],
539
+ remediation: references
540
+ },
541
+ {
542
+ code: "branch_referenced",
543
+ owners: ["core.transaction"],
544
+ remediation: references
545
+ },
546
+ {
547
+ code: "invalid_resource_reference",
548
+ owners: ["core.transaction"],
549
+ remediation: references
550
+ },
551
+ {
552
+ code: "invalid_component_reference",
553
+ owners: ["core.transaction"],
554
+ remediation: references
555
+ },
556
+ {
557
+ code: "invalid_group_reference",
558
+ owners: ["core.transaction"],
559
+ remediation: references
560
+ },
561
+ {
562
+ code: "package_referenced",
563
+ owners: ["core.transaction"],
564
+ remediation: references
565
+ },
566
+ {
567
+ code: "component_referenced",
568
+ owners: ["core.transaction"],
569
+ remediation: references
570
+ },
571
+ {
572
+ code: "component_has_package_dependencies",
573
+ owners: ["core.transaction"],
574
+ remediation: references
575
+ },
576
+ {
577
+ code: "dangling_resource_reference",
578
+ owners: ["core.validation"],
579
+ remediation: references
580
+ },
581
+ {
582
+ code: "invalid_project_xml",
583
+ owners: ["core.validation"],
584
+ remediation: project
585
+ },
586
+ {
587
+ code: "invalid_package_xml",
588
+ owners: ["core.validation"],
589
+ remediation: project
590
+ },
591
+ {
592
+ code: "invalid_branch_package_xml",
593
+ owners: ["core.validation"],
594
+ remediation: project
595
+ },
596
+ {
597
+ code: "invalid_component_xml",
598
+ owners: ["core.validation"],
599
+ remediation: project
600
+ },
601
+ {
602
+ code: "invalid_project_value",
603
+ owners: ["core.validation"],
604
+ remediation: project
605
+ },
606
+ {
607
+ code: "desktop_incompatible_geometry",
608
+ owners: ["core.validation"],
609
+ remediation: project
610
+ },
611
+ {
612
+ code: "invalid_settings_json",
613
+ owners: ["core.validation"],
614
+ remediation: project
615
+ },
616
+ {
617
+ code: "path_collision",
618
+ owners: ["core.validation"],
619
+ remediation: path$1
620
+ },
621
+ {
622
+ code: "unsafe_path",
623
+ owners: ["core.validation"],
624
+ remediation: path$1
625
+ },
626
+ {
627
+ code: "capability_unavailable",
628
+ owners: ["backend"],
629
+ remediation: capability
630
+ },
631
+ {
632
+ code: "uam_fidelity_unsupported",
633
+ owners: ["backend"],
634
+ remediation: capability
635
+ },
636
+ {
637
+ code: "save_partial_failure",
638
+ owners: ["backend"],
639
+ remediation: write
640
+ },
641
+ {
642
+ code: "write_failed",
643
+ owners: ["backend"],
644
+ remediation: write
645
+ },
646
+ {
647
+ code: "project_open_failed",
648
+ owners: ["backend"],
649
+ remediation: project
650
+ },
651
+ {
652
+ code: "materialize_validation_failed",
653
+ owners: ["backend"],
654
+ remediation: project
655
+ },
656
+ {
657
+ code: "execution_failure",
658
+ owners: ["core.transaction"],
659
+ remediation: execution
660
+ },
661
+ {
662
+ code: "cache_refresh_failed",
663
+ owners: ["backend"],
664
+ remediation: execution
665
+ },
666
+ {
667
+ code: "job_not_found",
668
+ owners: ["backend"],
669
+ remediation: job
670
+ },
671
+ {
672
+ code: "job_not_cancellable",
673
+ owners: ["backend"],
674
+ remediation: job
675
+ },
676
+ {
677
+ code: "job_cancelled",
678
+ owners: ["backend"],
679
+ remediation: job
680
+ }
681
+ ];
682
+ const BACKEND_DIAGNOSTICS_URI = "openfairygui://docs/diagnostics";
683
+ `${BACKEND_DIAGNOSTICS_URI}`;
684
+ function enrichBackendDiagnostic(diagnostic, sessionId) {
685
+ const guide = BACKEND_DIAGNOSTIC_GUIDES.find((entry) => entry.code === diagnostic.code);
686
+ if (!guide) return { ...diagnostic };
687
+ return {
688
+ ...diagnostic,
689
+ owner: diagnostic.owner ?? guide.owners[0],
690
+ docsUri: `${BACKEND_DIAGNOSTICS_URI}/${guide.code}`,
691
+ remediation: {
692
+ ...guide.remediation,
693
+ ...sessionId && guide.remediation.kind !== "host-action" ? { read: {
694
+ method: "getProjectOutline",
695
+ input: { sessionId }
696
+ } } : {}
697
+ }
698
+ };
699
+ }
700
+ //#endregion
80
701
  //#region src/services/context.ts
81
702
  function diagnosticFromError(error) {
82
703
  return {
@@ -95,10 +716,10 @@ function createMeta(stage, startedAt, options) {
95
716
  revision: options?.revision,
96
717
  durationMs: Math.max(0, Date.now() - startedAt),
97
718
  warnings: options?.warnings ?? [],
98
- diagnostics: options?.diagnostics ?? [],
719
+ diagnostics: (options?.diagnostics ?? []).map((entry) => enrichBackendDiagnostic(entry, options?.sessionId)),
99
720
  stage,
100
721
  contractVersion: BACKEND_CONTRACT_VERSION,
101
- capabilitySchemaVersion: 3
722
+ capabilitySchemaVersion: 10
102
723
  };
103
724
  }
104
725
  function success(stage, startedAt, data, options) {
@@ -122,10 +743,14 @@ function failure(stage, startedAt, error, session, options) {
122
743
  }
123
744
  //#endregion
124
745
  //#region src/services/session-project-writer.ts
125
- function createWriterFileSystem(fileSystem, writtenPaths, failedPaths) {
746
+ function createWriterFileSystem(fileSystem, projectRoot, writtenPaths, failedPaths) {
747
+ const contained = async (targetPath, operation) => {
748
+ await assertProjectPathContained(fileSystem, projectRoot, targetPath);
749
+ return operation();
750
+ };
126
751
  async function trackWrite(targetPath, write) {
127
752
  try {
128
- const result = await write();
753
+ const result = await contained(targetPath, write);
129
754
  writtenPaths.push(targetPath);
130
755
  return result;
131
756
  } catch (error) {
@@ -134,8 +759,8 @@ function createWriterFileSystem(fileSystem, writtenPaths, failedPaths) {
134
759
  }
135
760
  }
136
761
  return {
137
- readFile: (path) => fileSystem.readFile(path),
138
- readFileRaw: (path) => fileSystem.readFileRaw(path),
762
+ readFile: (path) => contained(path, () => fileSystem.readFile(path)),
763
+ readFileRaw: (path) => contained(path, () => fileSystem.readFileRaw(path)),
139
764
  writeFile: (path, content) => trackWrite(path, async () => {
140
765
  await fileSystem.mkdir(fileSystem.dirname(path), { recursive: true });
141
766
  await fileSystem.writeFile(path, content);
@@ -144,9 +769,10 @@ function createWriterFileSystem(fileSystem, writtenPaths, failedPaths) {
144
769
  await fileSystem.mkdir(fileSystem.dirname(path), { recursive: true });
145
770
  await fileSystem.writeFileRaw(path, data);
146
771
  }),
147
- mkdir: (path) => fileSystem.mkdir(path, { recursive: true }),
148
- readdir: (path) => fileSystem.readdir(path),
772
+ mkdir: (path) => contained(path, () => fileSystem.mkdir(path, { recursive: true })),
773
+ readdir: (path) => contained(path, () => fileSystem.readdir(path)),
149
774
  async exists(path) {
775
+ await assertProjectPathContained(fileSystem, projectRoot, path);
150
776
  try {
151
777
  await fileSystem.stat(path);
152
778
  return true;
@@ -161,11 +787,21 @@ function createWriterFileSystem(fileSystem, writtenPaths, failedPaths) {
161
787
  };
162
788
  }
163
789
  async function writeSessionProject(input) {
164
- await new ProjectWriter(createWriterFileSystem(input.fileSystem, input.writtenPaths, input.failedPaths)).write(input.document, input.fairyPath, {
165
- staleSourceFiles: input.staleSourceFiles,
166
- staleResourceFolders: input.staleResourceFolders,
167
- staleBranchDirectories: input.staleBranchDirectories
168
- });
790
+ const projectRoot = input.fileSystem.dirname(input.fairyPath);
791
+ const write = async (fileSystem) => {
792
+ await new ProjectWriter(createWriterFileSystem(fileSystem, projectRoot, input.writtenPaths, input.failedPaths)).write(input.document, input.fairyPath, {
793
+ staleSourceFiles: input.staleSourceFiles,
794
+ staleResourceFolders: input.staleResourceFolders,
795
+ staleBranchDirectories: input.staleBranchDirectories
796
+ });
797
+ };
798
+ if (!input.fileSystem.runProjectWriteTransaction) return write(input.fileSystem);
799
+ try {
800
+ await input.fileSystem.runProjectWriteTransaction(projectRoot, write);
801
+ } catch (error) {
802
+ input.writtenPaths.length = 0;
803
+ throw error;
804
+ }
169
805
  }
170
806
  //#endregion
171
807
  //#region src/services/session-utils.ts
@@ -199,6 +835,260 @@ function createStaleWriteError(session, expectedRevision) {
199
835
  };
200
836
  }
201
837
  //#endregion
838
+ //#region src/runtime/contracts.ts
839
+ const BACKEND_ENTITY_QUERY_LIMITS = {
840
+ maxBytes: 262144,
841
+ maxDepth: 32,
842
+ maxNodes: 1e5
843
+ };
844
+ const BACKEND_TRANSACTION_PREVIEW_LIMITS = {
845
+ maxBytes: 262144,
846
+ maxEntries: 2e3
847
+ };
848
+ /** Fixed resource projection. Binary content, source bookkeeping and arbitrary metadata are excluded. */
849
+ const BACKEND_RESOURCE_QUERY_FIELDS = [
850
+ "kind",
851
+ "id",
852
+ "name",
853
+ "path",
854
+ "exported",
855
+ "favorite",
856
+ "branch",
857
+ "branchItemIds",
858
+ "fileName",
859
+ "file",
860
+ "dimensions",
861
+ "image",
862
+ "movieClip"
863
+ ];
864
+ //#endregion
865
+ //#region src/services/capture-project.ts
866
+ function createCaptureFileSystem(files, directories) {
867
+ const normalize = (filePath) => filePath.replace(/\\/g, "/").replace(/\/+/g, "/");
868
+ return {
869
+ async readFile(filePath) {
870
+ const value = files.get(normalize(filePath));
871
+ if (typeof value !== "string") throw new Error(`Captured text file was not found: ${filePath}`);
872
+ return value;
873
+ },
874
+ async readFileRaw(filePath) {
875
+ const value = files.get(normalize(filePath));
876
+ if (!(value instanceof Uint8Array)) throw new Error(`Captured binary file was not found: ${filePath}`);
877
+ return value.slice();
878
+ },
879
+ async writeFile(filePath, content) {
880
+ files.set(normalize(filePath), content);
881
+ },
882
+ async writeFileRaw(filePath, data) {
883
+ files.set(normalize(filePath), data.slice());
884
+ },
885
+ async mkdir(dirPath) {
886
+ directories.add(normalize(dirPath));
887
+ },
888
+ async readdir() {
889
+ return [];
890
+ },
891
+ async exists(filePath) {
892
+ return files.has(normalize(filePath));
893
+ },
894
+ join(...paths) {
895
+ return normalize(paths.filter(Boolean).join("/"));
896
+ },
897
+ dirname(filePath) {
898
+ const normalized = normalize(filePath);
899
+ const separator = normalized.lastIndexOf("/");
900
+ return separator < 0 ? "" : normalized.slice(0, separator);
901
+ },
902
+ async unlink(filePath) {
903
+ files.delete(normalize(filePath));
904
+ }
905
+ };
906
+ }
907
+ function capturedFilesEqual(left, right) {
908
+ if (left.size !== right.size) return false;
909
+ for (const [filePath, leftValue] of left) {
910
+ const rightValue = right.get(filePath);
911
+ if (typeof leftValue === "string") {
912
+ if (leftValue !== rightValue) return false;
913
+ continue;
914
+ }
915
+ if (!(rightValue instanceof Uint8Array) || leftValue.length !== rightValue.length) return false;
916
+ for (let index = 0; index < leftValue.length; index += 1) if (leftValue[index] !== rightValue[index]) return false;
917
+ }
918
+ return true;
919
+ }
920
+ function capturedDirectoriesEqual(left, right) {
921
+ return left.size === right.size && [...left].every((directory) => right.has(directory));
922
+ }
923
+ /** Serialize only into memory. This is a model projection, not a disk inventory or write plan. */
924
+ async function captureProject(document, fairyFileName) {
925
+ const files = /* @__PURE__ */ new Map();
926
+ const directories = /* @__PURE__ */ new Set();
927
+ await new ProjectWriter(createCaptureFileSystem(files, directories)).write(document, fairyFileName);
928
+ return {
929
+ files,
930
+ directories
931
+ };
932
+ }
933
+ //#endregion
934
+ //#region src/services/transaction-preview.ts
935
+ /** Keep child identities/order on their parent, and compare each child's own properties separately. */
936
+ function entities(project) {
937
+ const result = /* @__PURE__ */ new Map();
938
+ function add(target, properties) {
939
+ const key = JSON.stringify(target);
940
+ if (result.has(key)) throw new Error(`Ambiguous preview identity: ${key}`);
941
+ result.set(key, {
942
+ target,
943
+ properties
944
+ });
945
+ }
946
+ const { packages, ...properties } = project;
947
+ add({ kind: "project" }, {
948
+ ...properties,
949
+ packages: packages.map((pkg) => pkg.id)
950
+ });
951
+ for (const { resources, ...pkg } of packages) {
952
+ const packageId = pkg.id;
953
+ add({
954
+ kind: "package",
955
+ selector: { packageId }
956
+ }, {
957
+ ...pkg,
958
+ resources: resources.map((resource) => resource.id)
959
+ });
960
+ for (const resource of resources) {
961
+ const resourceTarget = {
962
+ kind: "resource",
963
+ selector: {
964
+ packageId,
965
+ resourceId: resource.id
966
+ }
967
+ };
968
+ if (resource.kind !== "component") {
969
+ add(resourceTarget, resource);
970
+ continue;
971
+ }
972
+ const { component, ...resourceProperties } = resource;
973
+ add(resourceTarget, resourceProperties);
974
+ const { displayList, controllers, transitions, ...componentProperties } = component;
975
+ const selector = {
976
+ packageId,
977
+ componentResourceId: resource.id
978
+ };
979
+ add({
980
+ kind: "component",
981
+ selector
982
+ }, {
983
+ ...componentProperties,
984
+ displayList: displayList.map((node) => node.id),
985
+ controllers: controllers.map((controller) => controller.name),
986
+ transitions: transitions.map((transition) => transition.name)
987
+ });
988
+ for (const node of displayList) add({
989
+ kind: "displayNode",
990
+ selector: {
991
+ ...selector,
992
+ displayNodeId: node.id
993
+ }
994
+ }, node);
995
+ for (const controller of controllers) add({
996
+ kind: "controller",
997
+ selector: {
998
+ ...selector,
999
+ controllerName: controller.name
1000
+ }
1001
+ }, controller);
1002
+ for (const transition of transitions) add({
1003
+ kind: "transition",
1004
+ selector: {
1005
+ ...selector,
1006
+ transitionName: transition.name
1007
+ }
1008
+ }, transition);
1009
+ }
1010
+ }
1011
+ return result;
1012
+ }
1013
+ function equal(left, right, depth = 0) {
1014
+ if (left === right) return true;
1015
+ if (!left || !right || typeof left !== "object" || typeof right !== "object") return false;
1016
+ if (left instanceof Uint8Array || right instanceof Uint8Array) return left instanceof Uint8Array && right instanceof Uint8Array && left.length === right.length && left.every((value, index) => value === right[index]);
1017
+ if (depth > 128) throw new Error("Preview property comparison exceeds the supported nesting depth.");
1018
+ if (Array.isArray(left) !== Array.isArray(right)) return false;
1019
+ if (Array.isArray(left) && Array.isArray(right) && left.length !== right.length) return false;
1020
+ const a = left, b = right;
1021
+ const keys = Object.keys(a);
1022
+ return keys.length === Object.keys(b).length && keys.every((key) => Object.hasOwn(b, key) && equal(a[key], b[key], depth + 1));
1023
+ }
1024
+ var PreviewBudgetError = class extends Error {};
1025
+ /** No host filesystem, cache, event or session mutation is involved in the projection. */
1026
+ async function previewTransactionImpact(session, project, fileSystemAvailable) {
1027
+ const impact = {
1028
+ entities: [],
1029
+ files: []
1030
+ };
1031
+ const before = entities(session.project), after = entities(project);
1032
+ let entries = 0, bytes = 0;
1033
+ const encoder = new TextEncoder();
1034
+ function count(value) {
1035
+ bytes += encoder.encode(JSON.stringify(value)).byteLength;
1036
+ if (++entries > BACKEND_TRANSACTION_PREVIEW_LIMITS.maxEntries || bytes > BACKEND_TRANSACTION_PREVIEW_LIMITS.maxBytes) throw new PreviewBudgetError("The complete transaction impact exceeds the preview response budget.");
1037
+ }
1038
+ for (const key of new Set([...before.keys(), ...after.keys()])) {
1039
+ const previous = before.get(key), next = after.get(key);
1040
+ const fields = [...new Set([...Object.keys(previous?.properties ?? {}), ...Object.keys(next?.properties ?? {})])].filter((field) => !previous || !next || !equal(previous.properties[field], next.properties[field])).sort();
1041
+ if (!fields.length && previous && next) continue;
1042
+ const change = {
1043
+ target: (next ?? previous).target,
1044
+ change: !previous ? "added" : !next ? "removed" : "updated",
1045
+ fields
1046
+ };
1047
+ count(change);
1048
+ impact.entities.push(change);
1049
+ }
1050
+ const fairyFileName = session.fileSystem ? session.fairyPath.replace(/\\/g, "/").split("/").at(-1) : "Project.fairy";
1051
+ const [previousFiles, nextFiles] = await Promise.all([captureProject(materializeUamProject(session.project), fairyFileName), captureProject(materializeUamProject(project), fairyFileName)]);
1052
+ for (const path of new Set([...previousFiles.files.keys(), ...nextFiles.files.keys()])) {
1053
+ const previous = previousFiles.files.get(path), next = nextFiles.files.get(path);
1054
+ if (equal(previous, next)) continue;
1055
+ const change = {
1056
+ path,
1057
+ kind: "file",
1058
+ change: previous === void 0 ? "added" : next === void 0 ? "removed" : "updated"
1059
+ };
1060
+ count(change);
1061
+ impact.files.push(change);
1062
+ }
1063
+ for (const path of new Set([...previousFiles.directories, ...nextFiles.directories])) {
1064
+ if (previousFiles.directories.has(path) === nextFiles.directories.has(path)) continue;
1065
+ const change = {
1066
+ path,
1067
+ kind: "directory",
1068
+ change: nextFiles.directories.has(path) ? "added" : "removed"
1069
+ };
1070
+ count(change);
1071
+ impact.files.push(change);
1072
+ }
1073
+ impact.files.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : a.kind.localeCompare(b.kind));
1074
+ const preview = {
1075
+ sessionId: session.sessionId,
1076
+ baseRevision: session.revision,
1077
+ projectedRevision: session.revision + 1,
1078
+ mode: "execute-and-discard",
1079
+ impact,
1080
+ persistence: {
1081
+ requiredAfterApply: true,
1082
+ fileSystemAvailable,
1083
+ uamFidelity: session.uamFidelity,
1084
+ writeVerified: false,
1085
+ nextAction: session.uamFidelity === "unsupported" || !fileSystemAvailable ? "host-action" : session.fileSystem ? "saveSession" : "materializeSession"
1086
+ }
1087
+ };
1088
+ if (encoder.encode(JSON.stringify(preview)).byteLength > BACKEND_TRANSACTION_PREVIEW_LIMITS.maxBytes) throw new PreviewBudgetError("The complete transaction preview exceeds the response byte budget.");
1089
+ return preview;
1090
+ }
1091
+ //#endregion
202
1092
  //#region src/services/authoring-service.ts
203
1093
  function sourceFileKey(source) {
204
1094
  return [
@@ -228,8 +1118,12 @@ function recordStaleProjectFiles(session, previousProject, nextProject) {
228
1118
  for (const directory of staleBranchDirectories(nextProject, previousProject)) session.pendingStaleBranchDirectories.delete(branchDirectoryKey(directory));
229
1119
  }
230
1120
  function toBackendDiagnostics(error) {
231
- return error.diagnostics.length > 0 ? error.diagnostics.map((diagnostic) => ({ ...diagnostic })) : [{
1121
+ return error.diagnostics.length > 0 ? error.diagnostics.map((diagnostic) => ({
1122
+ ...diagnostic,
1123
+ owner: "core.transaction"
1124
+ })) : [{
232
1125
  code: error.code,
1126
+ owner: "core.transaction",
233
1127
  message: error.message,
234
1128
  severity: "error",
235
1129
  operationKind: error.operationKind,
@@ -317,6 +1211,46 @@ var AuthoringService = class {
317
1211
  if (this.sessionOperations.get(sessionId) === tail) this.sessionOperations.delete(sessionId);
318
1212
  }
319
1213
  }
1214
+ async preflightTransaction(input) {
1215
+ const queuedInput = structuredClone(input);
1216
+ detachSharedByteViews(queuedInput);
1217
+ return this.runSessionExclusive(queuedInput.sessionId, async () => {
1218
+ const startedAt = Date.now();
1219
+ const session = this.context.sessions.get(queuedInput.sessionId);
1220
+ if (!session || session.closed) return failure("authoring", startedAt, createSessionNotFoundError(queuedInput.sessionId));
1221
+ const meta = {
1222
+ sessionId: session.sessionId,
1223
+ revision: session.revision
1224
+ };
1225
+ if (queuedInput.expectedRevision !== session.revision) return failure("authoring", startedAt, createStaleWriteError(session, queuedInput.expectedRevision), toSessionSnapshot(session, this.context.capabilities), meta);
1226
+ const project = structuredClone(session.project);
1227
+ detachSharedByteViews(project);
1228
+ const result = await applyUamTransactionAppAsync({
1229
+ project,
1230
+ operations: queuedInput.operations
1231
+ });
1232
+ if (this.context.sessions.get(queuedInput.sessionId) !== session || session.closed) return failure("authoring", startedAt, createSessionNotFoundError(queuedInput.sessionId));
1233
+ if (!result.ok) return failure("authoring", startedAt, result.error, toSessionSnapshot(session, this.context.capabilities), {
1234
+ ...meta,
1235
+ diagnostics: toBackendDiagnostics(result.error)
1236
+ });
1237
+ try {
1238
+ const preview = await previewTransactionImpact({
1239
+ ...session,
1240
+ project
1241
+ }, result.project, Boolean(session.fileSystem));
1242
+ if (this.context.sessions.get(queuedInput.sessionId) !== session || session.closed) return failure("authoring", startedAt, createSessionNotFoundError(queuedInput.sessionId));
1243
+ return success("authoring", startedAt, preview, meta);
1244
+ } catch (error) {
1245
+ return failure("authoring", startedAt, {
1246
+ code: "transaction_preview_failed",
1247
+ sessionId: session.sessionId,
1248
+ reason: error instanceof PreviewBudgetError ? "response_budget_exceeded" : "projection_failed",
1249
+ message: error instanceof Error ? error.message : String(error)
1250
+ }, toSessionSnapshot(session, this.context.capabilities), meta);
1251
+ }
1252
+ });
1253
+ }
320
1254
  async applyTransaction(input) {
321
1255
  const queuedInput = structuredClone(input);
322
1256
  detachSharedByteViews(queuedInput);
@@ -396,7 +1330,7 @@ var AuthoringService = class {
396
1330
  const startedAt = Date.now();
397
1331
  const session = this.context.sessions.get(input.sessionId);
398
1332
  if (!session || session.closed) return failure("authoring", startedAt, createSessionNotFoundError(input.sessionId));
399
- const fileSystem = session.fileSystem ?? input.fileSystem ?? this.context.fileSystem;
1333
+ const fileSystem = session.fileSystem ?? input.fileSystem;
400
1334
  if (!fileSystem) return failure("authoring", startedAt, createCapabilityUnavailableError$1("saveSession requires an injected BackendFileSystem adapter."), toSessionSnapshot(session, this.context.capabilities), {
401
1335
  sessionId: session.sessionId,
402
1336
  revision: session.revision
@@ -479,7 +1413,7 @@ var AuthoringService = class {
479
1413
  lastSavedRevision: session.lastSavedRevision,
480
1414
  committedPaths,
481
1415
  failedPaths,
482
- diskMayBePartiallyUpdated: true
1416
+ diskMayBePartiallyUpdated: !fileSystem.runProjectWriteTransaction
483
1417
  }, toSessionSnapshot(session, this.context.capabilities), {
484
1418
  sessionId: session.sessionId,
485
1419
  revision: session.revision
@@ -498,7 +1432,7 @@ var AuthoringService = class {
498
1432
  revision: session.revision
499
1433
  });
500
1434
  const storageTarget = input.storage ? storageCanonicalTarget(input.storage) : null;
501
- const fileSystem = storageTarget?.fileSystem ?? input.fileSystem ?? session.fileSystem ?? this.context.fileSystem;
1435
+ const fileSystem = storageTarget?.fileSystem ?? input.fileSystem ?? session.fileSystem;
502
1436
  if (!fileSystem) return failure("authoring", startedAt, createCapabilityUnavailableError$1("materializeSession requires an injected BackendFileSystem adapter."), toSessionSnapshot(session, this.context.capabilities), {
503
1437
  sessionId: session.sessionId,
504
1438
  revision: session.revision
@@ -654,7 +1588,7 @@ var AuthoringService = class {
654
1588
  failedPaths,
655
1589
  skippedPaths,
656
1590
  diagnostics: diagnosticsFromError,
657
- diskMayBePartiallyUpdated: true
1591
+ diskMayBePartiallyUpdated: !fileSystem.runProjectWriteTransaction
658
1592
  }, toSessionSnapshot(session, this.context.capabilities), {
659
1593
  sessionId: session.sessionId,
660
1594
  revision: session.revision,
@@ -724,7 +1658,7 @@ var EventService = class {
724
1658
  ...event,
725
1659
  sequence: this.context.nextEventSequence(),
726
1660
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
727
- diagnostics: event.diagnostics ?? []
1661
+ diagnostics: (event.diagnostics ?? []).map((entry) => enrichBackendDiagnostic(entry, event.sessionId))
728
1662
  };
729
1663
  const sessionId = event.sessionId;
730
1664
  if (!sessionId) return emitted;
@@ -1052,6 +1986,37 @@ var JobService = class {
1052
1986
  };
1053
1987
  //#endregion
1054
1988
  //#region src/services/read-service.ts
1989
+ /** Bound traversal before serialization or cloning, including non-JSON values on a malformed native input. */
1990
+ function queryResponseProblem(value) {
1991
+ const pending = [{
1992
+ value,
1993
+ depth: 0
1994
+ }];
1995
+ let nodes = 0;
1996
+ let stringUnits = 0;
1997
+ while (pending.length) {
1998
+ const { value, depth } = pending.pop();
1999
+ if (++nodes > BACKEND_ENTITY_QUERY_LIMITS.maxNodes || depth > BACKEND_ENTITY_QUERY_LIMITS.maxDepth) return "response_budget_exceeded";
2000
+ if (typeof value === "string" && (stringUnits += value.length) > BACKEND_ENTITY_QUERY_LIMITS.maxBytes) return "response_budget_exceeded";
2001
+ if (value === void 0 || value === null || typeof value === "string" || typeof value === "boolean") continue;
2002
+ if (typeof value === "number") {
2003
+ if (!Number.isFinite(value)) return "non_json_value";
2004
+ continue;
2005
+ }
2006
+ if (typeof value !== "object" || !Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) return "non_json_value";
2007
+ if (Array.isArray(value) && value.length + pending.length + nodes > BACKEND_ENTITY_QUERY_LIMITS.maxNodes) return "response_budget_exceeded";
2008
+ const entries = Object.entries(value);
2009
+ if (entries.length + pending.length + nodes > BACKEND_ENTITY_QUERY_LIMITS.maxNodes) return "response_budget_exceeded";
2010
+ for (const [key, child] of entries) {
2011
+ if (!Array.isArray(value) && (stringUnits += key.length) > BACKEND_ENTITY_QUERY_LIMITS.maxBytes) return "response_budget_exceeded";
2012
+ pending.push({
2013
+ value: child,
2014
+ depth: depth + 1
2015
+ });
2016
+ }
2017
+ }
2018
+ if (new TextEncoder().encode(JSON.stringify(value)).byteLength > BACKEND_ENTITY_QUERY_LIMITS.maxBytes) return "response_budget_exceeded";
2019
+ }
1055
2020
  function toProjectOutline(session) {
1056
2021
  const project = session.project;
1057
2022
  return {
@@ -1119,6 +2084,121 @@ var ReadService = class {
1119
2084
  revision: session.revision
1120
2085
  });
1121
2086
  }
2087
+ queryEntity(input) {
2088
+ const startedAt = Date.now();
2089
+ const session = this.context.sessions.get(input.sessionId);
2090
+ if (!session || session.closed) return failure("read", startedAt, createSessionNotFoundError(input.sessionId));
2091
+ const meta = {
2092
+ sessionId: session.sessionId,
2093
+ revision: session.revision
2094
+ };
2095
+ const reject = (reason) => failure("read", startedAt, {
2096
+ code: "entity_query_failed",
2097
+ sessionId: session.sessionId,
2098
+ reason,
2099
+ message: `Entity query failed: ${reason}.`
2100
+ }, void 0, meta);
2101
+ const target = input.target;
2102
+ if (!target || typeof target !== "object" || Array.isArray(target) || Object.keys(target).some((key) => key !== "kind" && key !== "selector")) return reject("invalid_query");
2103
+ const respond = (entity) => {
2104
+ const data = {
2105
+ ...meta,
2106
+ target,
2107
+ entity
2108
+ };
2109
+ const problem = queryResponseProblem(data);
2110
+ return problem ? reject(problem) : success("read", startedAt, structuredClone(data), meta);
2111
+ };
2112
+ if (target.kind === "project") {
2113
+ if (Object.hasOwn(target, "selector")) return reject("invalid_query");
2114
+ const { projectId, settings } = session.project;
2115
+ return respond({
2116
+ kind: "project",
2117
+ properties: {
2118
+ projectId,
2119
+ settings
2120
+ }
2121
+ });
2122
+ }
2123
+ const keys = target.kind === "package" ? ["packageId"] : target.kind === "resource" ? ["packageId", "resourceId"] : target.kind === "component" ? ["packageId", "componentResourceId"] : target.kind === "displayNode" ? [
2124
+ "packageId",
2125
+ "componentResourceId",
2126
+ "displayNodeId"
2127
+ ] : target.kind === "controller" ? [
2128
+ "packageId",
2129
+ "componentResourceId",
2130
+ "controllerName"
2131
+ ] : target.kind === "transition" ? [
2132
+ "packageId",
2133
+ "componentResourceId",
2134
+ "transitionName"
2135
+ ] : [];
2136
+ const selector = target.selector;
2137
+ if (!keys.length || !selector || typeof selector !== "object" || Array.isArray(selector) || Object.keys(selector).length !== keys.length || keys.some((key) => !Object.hasOwn(selector, key) || typeof selector[key] !== "string" || !selector[key].length || selector[key].length > 256)) return reject("invalid_query");
2138
+ const packages = session.project.packages.filter((pkg) => pkg.id === selector.packageId);
2139
+ if (packages.length !== 1) return reject(packages.length ? "ambiguous" : "not_found");
2140
+ if (target.kind === "package") {
2141
+ const { id, name, compressPNG, jpegQuality, publish } = packages[0];
2142
+ return respond({
2143
+ kind: "package",
2144
+ properties: {
2145
+ id,
2146
+ name,
2147
+ settings: {
2148
+ compressPNG,
2149
+ jpegQuality,
2150
+ publish
2151
+ }
2152
+ }
2153
+ });
2154
+ }
2155
+ const resources = packages[0].resources.filter((resource) => resource.id === (target.kind === "resource" ? selector.resourceId : selector.componentResourceId));
2156
+ if (resources.length !== 1) return reject(resources.length ? "ambiguous" : "not_found");
2157
+ const resource = resources[0];
2158
+ let entity;
2159
+ if (target.kind === "resource") {
2160
+ const record = resource;
2161
+ entity = {
2162
+ kind: "resource",
2163
+ properties: Object.fromEntries(BACKEND_RESOURCE_QUERY_FIELDS.filter((key) => Object.hasOwn(record, key)).map((key) => [key, record[key]]))
2164
+ };
2165
+ } else {
2166
+ if (resource.kind !== "component") return reject("not_found");
2167
+ if (target.kind === "component") {
2168
+ const { size, properties, customData } = resource.component;
2169
+ entity = {
2170
+ kind: "component",
2171
+ properties: {
2172
+ size,
2173
+ properties,
2174
+ customData
2175
+ }
2176
+ };
2177
+ } else if (target.kind === "controller") {
2178
+ const controllers = resource.component.controllers.filter((controller) => controller.name === selector.controllerName);
2179
+ if (controllers.length !== 1) return reject(controllers.length ? "ambiguous" : "not_found");
2180
+ entity = {
2181
+ kind: "controller",
2182
+ properties: controllers[0]
2183
+ };
2184
+ } else if (target.kind === "transition") {
2185
+ const transitions = resource.component.transitions.filter((transition) => transition.name === selector.transitionName);
2186
+ if (transitions.length !== 1) return reject(transitions.length ? "ambiguous" : "not_found");
2187
+ entity = {
2188
+ kind: "transition",
2189
+ properties: transitions[0]
2190
+ };
2191
+ } else {
2192
+ const nodes = resource.component.displayList.filter((node) => node.id === selector.displayNodeId);
2193
+ if (nodes.length !== 1) return reject(nodes.length ? "ambiguous" : "not_found");
2194
+ entity = {
2195
+ kind: "displayNode",
2196
+ properties: nodes[0]
2197
+ };
2198
+ }
2199
+ }
2200
+ return respond(entity);
2201
+ }
1122
2202
  validateSession(input) {
1123
2203
  const startedAt = Date.now();
1124
2204
  const session = this.context.sessions.get(input.sessionId);
@@ -1135,7 +2215,8 @@ var ReadService = class {
1135
2215
  code,
1136
2216
  message,
1137
2217
  severity,
1138
- path
2218
+ path,
2219
+ owner: "core.validation"
1139
2220
  }))
1140
2221
  });
1141
2222
  }
@@ -1143,7 +2224,7 @@ var ReadService = class {
1143
2224
  //#endregion
1144
2225
  //#region src/services/runtime-service.ts
1145
2226
  function randomId() {
1146
- return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
2227
+ return crypto.randomUUID();
1147
2228
  }
1148
2229
  function createCapabilityUnavailableError(capability) {
1149
2230
  const artifactCapability = capability === "artifact.publish" || capability === "artifact.restore";
@@ -1156,29 +2237,33 @@ function createCapabilityUnavailableError(capability) {
1156
2237
  bridgeBoundary: artifactCapability ? "external-bridge" : void 0
1157
2238
  };
1158
2239
  }
1159
- function createProjectReaderFileSystem(fileSystem) {
2240
+ function createProjectReaderFileSystem(fileSystem, projectRoot) {
2241
+ const contained = async (filePath, operation) => {
2242
+ await assertProjectPathContained(fileSystem, projectRoot, filePath);
2243
+ return operation();
2244
+ };
1160
2245
  return {
1161
2246
  readFile(filePath) {
1162
- return fileSystem.readFile(filePath);
2247
+ return contained(filePath, () => fileSystem.readFile(filePath));
1163
2248
  },
1164
2249
  readFileRaw(filePath) {
1165
- return fileSystem.readFileRaw(filePath);
2250
+ return contained(filePath, () => fileSystem.readFileRaw(filePath));
1166
2251
  },
1167
2252
  writeFile(filePath, content) {
1168
- return fileSystem.writeFile(filePath, content);
2253
+ return contained(filePath, () => fileSystem.writeFile(filePath, content));
1169
2254
  },
1170
2255
  writeFileRaw(filePath, data) {
1171
- return fileSystem.writeFileRaw(filePath, data);
2256
+ return contained(filePath, () => fileSystem.writeFileRaw(filePath, data));
1172
2257
  },
1173
2258
  async mkdir(dirPath) {
1174
- await fileSystem.mkdir(dirPath, { recursive: true });
2259
+ await contained(dirPath, () => fileSystem.mkdir(dirPath, { recursive: true }));
1175
2260
  },
1176
2261
  readdir(dirPath) {
1177
- return fileSystem.readdir(dirPath);
2262
+ return contained(dirPath, () => fileSystem.readdir(dirPath));
1178
2263
  },
1179
2264
  async exists(filePath) {
1180
2265
  try {
1181
- await fileSystem.stat(filePath);
2266
+ await contained(filePath, () => fileSystem.stat(filePath));
1182
2267
  return true;
1183
2268
  } catch {
1184
2269
  return false;
@@ -1192,63 +2277,6 @@ function createProjectReaderFileSystem(fileSystem) {
1192
2277
  }
1193
2278
  };
1194
2279
  }
1195
- function createCaptureFileSystem(files, directories) {
1196
- const normalize = (filePath) => filePath.replace(/\\/g, "/").replace(/\/+/g, "/");
1197
- return {
1198
- async readFile(filePath) {
1199
- const value = files.get(normalize(filePath));
1200
- if (typeof value !== "string") throw new Error(`Captured text file was not found: ${filePath}`);
1201
- return value;
1202
- },
1203
- async readFileRaw(filePath) {
1204
- const value = files.get(normalize(filePath));
1205
- if (!(value instanceof Uint8Array)) throw new Error(`Captured binary file was not found: ${filePath}`);
1206
- return value.slice();
1207
- },
1208
- async writeFile(filePath, content) {
1209
- files.set(normalize(filePath), content);
1210
- },
1211
- async writeFileRaw(filePath, data) {
1212
- files.set(normalize(filePath), data.slice());
1213
- },
1214
- async mkdir(dirPath) {
1215
- directories.add(normalize(dirPath));
1216
- },
1217
- async readdir() {
1218
- return [];
1219
- },
1220
- async exists(filePath) {
1221
- return files.has(normalize(filePath));
1222
- },
1223
- join(...paths) {
1224
- return normalize(paths.filter(Boolean).join("/"));
1225
- },
1226
- dirname(filePath) {
1227
- const normalized = normalize(filePath);
1228
- const separator = normalized.lastIndexOf("/");
1229
- return separator < 0 ? "" : normalized.slice(0, separator);
1230
- },
1231
- async unlink(filePath) {
1232
- files.delete(normalize(filePath));
1233
- }
1234
- };
1235
- }
1236
- function capturedFilesEqual(left, right) {
1237
- if (left.size !== right.size) return false;
1238
- for (const [filePath, leftValue] of left) {
1239
- const rightValue = right.get(filePath);
1240
- if (typeof leftValue === "string") {
1241
- if (leftValue !== rightValue) return false;
1242
- continue;
1243
- }
1244
- if (!(rightValue instanceof Uint8Array) || leftValue.length !== rightValue.length) return false;
1245
- for (let index = 0; index < leftValue.length; index += 1) if (leftValue[index] !== rightValue[index]) return false;
1246
- }
1247
- return true;
1248
- }
1249
- function capturedDirectoriesEqual(left, right) {
1250
- return left.size === right.size && [...left].every((directory) => right.has(directory));
1251
- }
1252
2280
  async function hasFullUamFidelity(document, project) {
1253
2281
  const sourceFiles = /* @__PURE__ */ new Map();
1254
2282
  const materializedFiles = /* @__PURE__ */ new Map();
@@ -1272,9 +2300,25 @@ var RuntimeService = class {
1272
2300
  const startedAt = Date.now();
1273
2301
  if (!this.context.fileSystem) return failure("runtime", startedAt, createCapabilityUnavailableError("fileSystem"));
1274
2302
  const fileSystem = this.context.fileSystem;
2303
+ if (this.context.allowedProjectRoots?.length) {
2304
+ let allowed = false;
2305
+ for (const root of this.context.allowedProjectRoots) try {
2306
+ await assertProjectPathContained(fileSystem, root, input.projectPath);
2307
+ allowed = true;
2308
+ break;
2309
+ } catch (error) {
2310
+ if (error.code !== "EACCES") throw error;
2311
+ }
2312
+ if (!allowed) return failure("runtime", startedAt, {
2313
+ code: "project_root_not_allowed",
2314
+ message: "Project path is outside the configured allowed roots.",
2315
+ projectPath: input.projectPath
2316
+ });
2317
+ }
1275
2318
  const { fairyPath, canonicalProjectPath, canonicalPathKey } = await resolveCanonicalProjectRoot(fileSystem, input.projectPath);
2319
+ await fileSystem.validateProjectRoot?.(canonicalProjectPath);
1276
2320
  const existingSessionId = this.context.sessionsByPath.get(canonicalPathKey);
1277
- const lockFilePath = fileSystem.join(canonicalProjectPath, ".openfairygui.backend.lock");
2321
+ const lockFilePath = fileSystem.getSessionLockPath?.(canonicalProjectPath) ?? fileSystem.join(canonicalProjectPath, ".openfairygui.backend.lock");
1278
2322
  if (existingSessionId) return failure("runtime", startedAt, {
1279
2323
  code: "lock_conflict",
1280
2324
  kind: "in_process_session_exists",
@@ -1294,7 +2338,7 @@ var RuntimeService = class {
1294
2338
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1295
2339
  canonicalPathKey
1296
2340
  }));
1297
- const read = await new ProjectReader(createProjectReaderFileSystem(fileSystem)).readDetailed(fairyPath, { hydrateResourceBytes: true });
2341
+ const read = await new ProjectReader(createProjectReaderFileSystem(fileSystem, canonicalProjectPath)).readDetailed(fairyPath, { hydrateResourceBytes: true });
1298
2342
  if (!read.document) throw new Error(read.diagnostics[0]?.message ?? `Unable to read project: ${fairyPath}`);
1299
2343
  const document = read.document;
1300
2344
  const project = liftDocumentToUamProject(document);
@@ -1352,6 +2396,11 @@ var RuntimeService = class {
1352
2396
  openProjectSession(input) {
1353
2397
  const startedAt = Date.now();
1354
2398
  const sessionId = input.sessionId ?? randomId();
2399
+ if (this.context.sessions.has(sessionId)) return failure("runtime", startedAt, {
2400
+ code: "session_id_conflict",
2401
+ message: `Session id is already in use: ${sessionId}`,
2402
+ sessionId
2403
+ });
1355
2404
  const storage = input.storage;
1356
2405
  const memoryProjectPath = `memory://${sessionId}`;
1357
2406
  const canonicalProjectPath = storage?.canonicalProjectPath ?? input.canonicalProjectPath ?? (storage ? storage.fileSystem.dirname(storage.fairyPath) || "." : memoryProjectPath);
@@ -1459,7 +2508,9 @@ const BACKEND_METHODS = [
1459
2508
  "openProjectSession",
1460
2509
  "getSession",
1461
2510
  "getProjectOutline",
2511
+ "queryEntity",
1462
2512
  "validateSession",
2513
+ "preflightTransaction",
1463
2514
  "applyTransaction",
1464
2515
  "saveSession",
1465
2516
  "materializeSession",
@@ -1478,10 +2529,10 @@ const ARTIFACT_BRIDGE_CAPABILITY = {
1478
2529
  bridgeEntrypoint: "@openfairygui/backend/node",
1479
2530
  reason: "publish/restore require explicit Node-hosted filesystem and artifact execution."
1480
2531
  };
1481
- function createCapabilities() {
2532
+ function createCapabilities(atomicSave = false) {
1482
2533
  return {
1483
2534
  contractVersion: BACKEND_CONTRACT_VERSION,
1484
- capabilitySchemaVersion: 3,
2535
+ capabilitySchemaVersion: 10,
1485
2536
  transactionKernelOwner: "@openfairygui/core",
1486
2537
  appSeamOwner: "@openfairygui/functions",
1487
2538
  runtimeOwner: "@openfairygui/backend",
@@ -1490,9 +2541,29 @@ function createCapabilities() {
1490
2541
  capabilitySnapshot: true,
1491
2542
  sessionSnapshot: true,
1492
2543
  projectOutline: true,
2544
+ entityQuery: {
2545
+ kinds: [
2546
+ "project",
2547
+ "package",
2548
+ "resource",
2549
+ "component",
2550
+ "displayNode",
2551
+ "controller",
2552
+ "transition"
2553
+ ],
2554
+ projection: "properties",
2555
+ sourceBytes: false,
2556
+ limits: BACKEND_ENTITY_QUERY_LIMITS
2557
+ },
1493
2558
  projectValidation: true
1494
2559
  },
1495
2560
  authoring: {
2561
+ preflightTransaction: {
2562
+ mode: "execute-and-discard",
2563
+ reservesRevision: false,
2564
+ impact: "model-diff",
2565
+ limits: BACKEND_TRANSACTION_PREVIEW_LIMITS
2566
+ },
1496
2567
  applyTransaction: true,
1497
2568
  saveSession: true,
1498
2569
  resourceKinds: [...UAM_SUPPORTED_MATERIALIZATION_SCOPE.resourceKinds],
@@ -1542,7 +2613,9 @@ function createCapabilities() {
1542
2613
  },
1543
2614
  diagnostics: {
1544
2615
  stableCodes: true,
1545
- errorDiagnosticMirror: true
2616
+ errorDiagnosticMirror: true,
2617
+ recoveryGuides: "all-formal-codes",
2618
+ automaticRepair: false
1546
2619
  }
1547
2620
  },
1548
2621
  compatibilityPolicy: BACKEND_COMPATIBILITY_POLICY,
@@ -1550,7 +2623,7 @@ function createCapabilities() {
1550
2623
  sessionRuntime: true,
1551
2624
  advisoryLocking: true,
1552
2625
  coordinatedSave: true,
1553
- atomicSave: false,
2626
+ atomicSave,
1554
2627
  staleRevisionProtection: true,
1555
2628
  pathPolicy: createRuntimePathPolicy(),
1556
2629
  events: {
@@ -1596,10 +2669,11 @@ var BackendRuntime = class {
1596
2669
  jobService;
1597
2670
  constructor(options = {}) {
1598
2671
  this.fileSystem = options.fileSystem;
1599
- this.capabilities = createCapabilities();
2672
+ this.capabilities = createCapabilities(Boolean(options.fileSystem?.runProjectWriteTransaction));
1600
2673
  this.context = {
1601
2674
  fileSystem: this.fileSystem,
1602
2675
  host: options.host,
2676
+ allowedProjectRoots: options.allowedProjectRoots,
1603
2677
  capabilities: this.capabilities,
1604
2678
  sessions: this.sessions,
1605
2679
  sessionsByPath: this.sessionsByPath,
@@ -1622,7 +2696,16 @@ var BackendRuntime = class {
1622
2696
  return this.readService.getCapabilities();
1623
2697
  }
1624
2698
  async openSession(input) {
1625
- return this.runtimeService.openSession(input);
2699
+ const startedAt = Date.now();
2700
+ try {
2701
+ return await this.runtimeService.openSession(input);
2702
+ } catch {
2703
+ return failure("runtime", startedAt, {
2704
+ code: "project_open_failed",
2705
+ message: "Unable to open project.",
2706
+ projectPath: input.projectPath
2707
+ });
2708
+ }
1626
2709
  }
1627
2710
  openProjectSession(input) {
1628
2711
  return this.runtimeService.openProjectSession(input);
@@ -1633,9 +2716,15 @@ var BackendRuntime = class {
1633
2716
  getProjectOutline(input) {
1634
2717
  return this.readService.getProjectOutline(input);
1635
2718
  }
2719
+ queryEntity(input) {
2720
+ return this.readService.queryEntity(input);
2721
+ }
1636
2722
  validateSession(input) {
1637
2723
  return this.readService.validateSession(input);
1638
2724
  }
2725
+ async preflightTransaction(input) {
2726
+ return this.authoringService.preflightTransaction(input);
2727
+ }
1639
2728
  async applyTransaction(input) {
1640
2729
  return this.authoringService.applyTransaction(input);
1641
2730
  }
@@ -1646,7 +2735,7 @@ var BackendRuntime = class {
1646
2735
  return this.authoringService.materializeSession(input);
1647
2736
  }
1648
2737
  async closeSession(input) {
1649
- return this.runtimeService.closeSession(input);
2738
+ return this.authoringService.runSessionExclusive(input.sessionId, () => this.runtimeService.closeSession(input));
1650
2739
  }
1651
2740
  getEvents(input) {
1652
2741
  return this.eventService.getEvents(input);
@@ -1669,13 +2758,161 @@ var BackendRuntime = class {
1669
2758
  };
1670
2759
  //#endregion
1671
2760
  //#region src/node.ts
2761
+ const PROCESS_START_TIME = Math.trunc(Date.now() - process.uptime() * 1e3);
2762
+ function parseLockMetadata(content) {
2763
+ try {
2764
+ const value = JSON.parse(content);
2765
+ if (value.schemaVersion !== 1 || !Number.isSafeInteger(value.pid) || !Number.isFinite(value.processStartTime) || typeof value.hostname !== "string" || typeof value.token !== "string") return null;
2766
+ return value;
2767
+ } catch {
2768
+ return null;
2769
+ }
2770
+ }
2771
+ function isProcessAlive(metadata) {
2772
+ if (metadata.hostname !== os.hostname()) return true;
2773
+ if (metadata.pid === process.pid) return Math.abs(metadata.processStartTime - PROCESS_START_TIME) < 1e3;
2774
+ try {
2775
+ process.kill(metadata.pid, 0);
2776
+ return true;
2777
+ } catch (error) {
2778
+ return error.code !== "ESRCH";
2779
+ }
2780
+ }
2781
+ async function recoverStaleLock(filePath) {
2782
+ let before;
2783
+ try {
2784
+ before = await fs.readFile(filePath, "utf-8");
2785
+ } catch {
2786
+ return false;
2787
+ }
2788
+ const metadata = parseLockMetadata(before);
2789
+ if (!metadata || isProcessAlive(metadata)) return false;
2790
+ const current = parseLockMetadata(await fs.readFile(filePath, "utf-8").catch(() => ""));
2791
+ if (!current || current.token !== metadata.token) return false;
2792
+ await fs.unlink(filePath);
2793
+ return true;
2794
+ }
2795
+ async function resolvePathThroughExistingAncestor(filePath) {
2796
+ const missing = [];
2797
+ let candidate = path.resolve(filePath);
2798
+ for (;;) try {
2799
+ const resolved = await fs.realpath(candidate);
2800
+ return path.join(resolved, ...missing);
2801
+ } catch (error) {
2802
+ const code = error.code;
2803
+ if (code !== "ENOENT" && code !== "ENOTDIR") throw error;
2804
+ const parent = path.dirname(candidate);
2805
+ if (parent === candidate) return path.resolve(filePath);
2806
+ missing.unshift(path.basename(candidate));
2807
+ candidate = parent;
2808
+ }
2809
+ }
2810
+ async function pathExists(filePath) {
2811
+ return fs.stat(filePath).then(() => true, (error) => {
2812
+ if (error.code === "ENOENT") return false;
2813
+ throw error;
2814
+ });
2815
+ }
2816
+ async function assertNoSymlinks(dirPath) {
2817
+ for (const entry of await fs.readdir(dirPath, { withFileTypes: true })) {
2818
+ const entryPath = path.join(dirPath, entry.name);
2819
+ if (entry.isSymbolicLink()) throw new Error(`Symbolic links are not supported in project directories: ${entryPath}`);
2820
+ if (entry.isDirectory()) await assertNoSymlinks(entryPath);
2821
+ }
2822
+ }
2823
+ function createStagedNodeFileSystem(projectRoot, stagingRoot) {
2824
+ const { runProjectWriteTransaction: _, ...base } = createNodeBackendFileSystem();
2825
+ const translate = (filePath) => {
2826
+ const relative = path.relative(projectRoot, path.resolve(filePath));
2827
+ if (relative.startsWith("..") || path.isAbsolute(relative)) {
2828
+ const error = /* @__PURE__ */ new Error(`Project path escapes the staged root: ${filePath}`);
2829
+ error.code = "EACCES";
2830
+ throw error;
2831
+ }
2832
+ return path.join(stagingRoot, relative);
2833
+ };
2834
+ return {
2835
+ ...base,
2836
+ stat: (filePath) => fs.stat(translate(filePath)),
2837
+ async readdir(dirPath) {
2838
+ const entries = await fs.readdir(translate(dirPath), { withFileTypes: true });
2839
+ const symlink = entries.find((entry) => entry.isSymbolicLink());
2840
+ if (symlink) throw new Error(`Symbolic links are not supported in project directories: ${path.join(dirPath, symlink.name)}`);
2841
+ return entries.map((entry) => entry.name);
2842
+ },
2843
+ readFile: (filePath) => fs.readFile(translate(filePath), "utf-8"),
2844
+ async readFileRaw(filePath) {
2845
+ const buffer = await fs.readFile(translate(filePath));
2846
+ return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
2847
+ },
2848
+ writeFile: (filePath, content) => fs.writeFile(translate(filePath), content, "utf-8"),
2849
+ writeFileRaw: (filePath, data) => fs.writeFile(translate(filePath), data),
2850
+ async mkdir(dirPath, options) {
2851
+ await fs.mkdir(translate(dirPath), { recursive: options?.recursive ?? false });
2852
+ },
2853
+ resolvePath: (filePath) => resolvePathThroughExistingAncestor(translate(filePath)),
2854
+ unlink: (filePath) => fs.unlink(translate(filePath)),
2855
+ rmdir: (dirPath) => fs.rmdir(translate(dirPath))
2856
+ };
2857
+ }
2858
+ async function runNodeProjectWriteTransaction(projectRoot, write) {
2859
+ const root = path.resolve(projectRoot);
2860
+ const parent = path.dirname(root);
2861
+ const name = path.basename(root);
2862
+ const staging = path.join(parent, `.${name}.save-${randomUUID()}`);
2863
+ const backup = path.join(parent, `.${name}.save-backup-${randomUUID()}`);
2864
+ const existed = await pathExists(root);
2865
+ if (existed) {
2866
+ await assertNoSymlinks(root);
2867
+ await fs.cp(root, staging, {
2868
+ recursive: true,
2869
+ errorOnExist: true,
2870
+ force: false
2871
+ });
2872
+ } else await fs.mkdir(staging, { recursive: true });
2873
+ try {
2874
+ await write(createStagedNodeFileSystem(root, staging));
2875
+ } catch (error) {
2876
+ await fs.rm(staging, {
2877
+ recursive: true,
2878
+ force: true
2879
+ });
2880
+ throw error;
2881
+ }
2882
+ if (!existed) {
2883
+ await fs.rename(staging, root);
2884
+ return;
2885
+ }
2886
+ await fs.rename(root, backup);
2887
+ try {
2888
+ await fs.rename(staging, root);
2889
+ } catch (error) {
2890
+ await fs.rename(backup, root);
2891
+ await fs.rm(staging, {
2892
+ recursive: true,
2893
+ force: true
2894
+ });
2895
+ throw error;
2896
+ }
2897
+ await fs.rm(backup, {
2898
+ recursive: true,
2899
+ force: true
2900
+ }).catch(() => void 0);
2901
+ }
1672
2902
  function createNodeBackendFileSystem() {
1673
2903
  return {
1674
2904
  stat(filePath) {
1675
2905
  return fs.stat(filePath);
1676
2906
  },
1677
- readdir(dirPath) {
1678
- return fs.readdir(dirPath);
2907
+ async readdir(dirPath) {
2908
+ const entries = await fs.readdir(dirPath, { withFileTypes: true });
2909
+ const symlink = entries.find((entry) => entry.isSymbolicLink());
2910
+ if (symlink) {
2911
+ const error = /* @__PURE__ */ new Error(`Symbolic links are not supported in project directories: ${path.join(dirPath, symlink.name)}`);
2912
+ error.code = "ELOOP";
2913
+ throw error;
2914
+ }
2915
+ return entries.map((entry) => entry.name);
1679
2916
  },
1680
2917
  readFile(filePath) {
1681
2918
  return fs.readFile(filePath, "utf-8");
@@ -1694,16 +2931,32 @@ function createNodeBackendFileSystem() {
1694
2931
  await fs.mkdir(dirPath, { recursive: options?.recursive ?? false });
1695
2932
  },
1696
2933
  async resolvePath(filePath) {
1697
- try {
1698
- return await fs.realpath(filePath);
1699
- } catch {
1700
- return path.resolve(filePath);
1701
- }
2934
+ return resolvePathThroughExistingAncestor(filePath);
1702
2935
  },
2936
+ validateProjectRoot: assertNoSymlinks,
2937
+ getSessionLockPath(canonicalProjectPath) {
2938
+ return path.join(path.dirname(canonicalProjectPath), `.${path.basename(canonicalProjectPath)}.openfairygui.backend.lock`);
2939
+ },
2940
+ runProjectWriteTransaction: runNodeProjectWriteTransaction,
1703
2941
  async acquireSessionLock(filePath) {
1704
- const handle = await fs.open(filePath, "wx");
2942
+ let handle;
2943
+ try {
2944
+ handle = await fs.open(filePath, "wx");
2945
+ } catch (error) {
2946
+ if (error.code !== "EEXIST" || !await recoverStaleLock(filePath)) throw error;
2947
+ handle = await fs.open(filePath, "wx");
2948
+ }
2949
+ const owner = {
2950
+ schemaVersion: 1,
2951
+ pid: process.pid,
2952
+ processStartTime: PROCESS_START_TIME,
2953
+ hostname: os.hostname(),
2954
+ token: randomUUID(),
2955
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
2956
+ };
1705
2957
  let closed = false;
1706
2958
  let released = false;
2959
+ let metadataWritten = false;
1707
2960
  const closeHandle = async () => {
1708
2961
  if (closed) return;
1709
2962
  await handle.close();
@@ -1711,13 +2964,23 @@ function createNodeBackendFileSystem() {
1711
2964
  };
1712
2965
  return {
1713
2966
  async writeMetadata(content) {
1714
- await handle.writeFile(content, "utf-8");
2967
+ let supplied = {};
2968
+ try {
2969
+ const parsed = JSON.parse(content);
2970
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) supplied = parsed;
2971
+ } catch {}
2972
+ await handle.writeFile(JSON.stringify({
2973
+ ...supplied,
2974
+ ...owner
2975
+ }, null, 2), "utf-8");
2976
+ metadataWritten = true;
1715
2977
  await closeHandle();
1716
2978
  },
1717
2979
  async release() {
1718
2980
  if (released) return;
1719
2981
  await closeHandle();
1720
- await fs.unlink(filePath).catch((error) => {
2982
+ const current = metadataWritten ? parseLockMetadata(await fs.readFile(filePath, "utf-8").catch(() => "")) : null;
2983
+ if (!metadataWritten || current?.token === owner.token) await fs.unlink(filePath).catch((error) => {
1721
2984
  if (error.code !== "ENOENT") throw error;
1722
2985
  });
1723
2986
  released = true;
@@ -1743,11 +3006,7 @@ function createNodeBackendFileSystem() {
1743
3006
  }
1744
3007
  function createNodeBackendHostAdapter() {
1745
3008
  return { lockMetadata(input) {
1746
- return {
1747
- pid: process.pid,
1748
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1749
- canonicalPathKey: input.canonicalPathKey
1750
- };
3009
+ return { canonicalPathKey: input.canonicalPathKey };
1751
3010
  } };
1752
3011
  }
1753
3012
  function createNodeBackendRuntime(options = {}) {