@openfairygui/backend 0.6.3 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/dist/contracts-Bx8HUr7I.d.cts +756 -0
  2. package/dist/contracts-CMQiPEyz.d.mts +756 -0
  3. package/dist/diagnostics-CIe7S-RW.cjs +670 -0
  4. package/dist/diagnostics-CZ12H1Mx.d.cts +1679 -0
  5. package/dist/diagnostics-CpJ8cAP6.d.mts +1679 -0
  6. package/dist/diagnostics-DTnLXQGs.mjs +641 -0
  7. package/dist/docs.cjs +11530 -5940
  8. package/dist/docs.d.cts +5 -185
  9. package/dist/docs.d.mts +5 -185
  10. package/dist/docs.mjs +11528 -5939
  11. package/dist/index.cjs +16 -2703
  12. package/dist/index.d.cts +5 -2362
  13. package/dist/index.d.mts +5 -2362
  14. package/dist/index.mjs +4 -2691
  15. package/dist/node.cjs +367 -2779
  16. package/dist/node.d.cts +4 -724
  17. package/dist/node.d.mts +4 -724
  18. package/dist/node.mjs +359 -2751
  19. package/dist/rolldown-runtime-BJqNVkSG.cjs +28 -0
  20. package/dist/runtime-DYqG77ak.cjs +2249 -0
  21. package/dist/runtime-gStewf1p.mjs +2189 -0
  22. package/package.json +4 -5
  23. package/src/contracts.ts +0 -58
  24. package/src/diagnostics.ts +0 -188
  25. package/src/docs.ts +0 -109
  26. package/src/generated/contracts.ts +0 -24207
  27. package/src/generated/docs.ts +0 -12
  28. package/src/index.ts +0 -99
  29. package/src/node.ts +0 -317
  30. package/src/path-policy.ts +0 -123
  31. package/src/runtime/capabilities.ts +0 -131
  32. package/src/runtime/contracts.ts +0 -672
  33. package/src/runtime.ts +0 -231
  34. package/src/services/artifact-service.ts +0 -19
  35. package/src/services/authoring-service.ts +0 -229
  36. package/src/services/cache-service.ts +0 -81
  37. package/src/services/capture-project.ts +0 -75
  38. package/src/services/context.ts +0 -150
  39. package/src/services/event-service.ts +0 -86
  40. package/src/services/persistence-service.ts +0 -550
  41. package/src/services/read-service.ts +0 -274
  42. package/src/services/runtime-service.ts +0 -342
  43. package/src/services/session-operation-queue.ts +0 -21
  44. package/src/services/session-project-writer.ts +0 -89
  45. package/src/services/session-registry.ts +0 -70
  46. package/src/services/session-utils.ts +0 -45
  47. package/src/services/transaction-preview.ts +0 -116
  48. package/src/storage.ts +0 -232
package/dist/node.mjs CHANGED
@@ -1,2725 +1,322 @@
1
+ import { a as ProjectWriteTransactionError, s as resolveFairyPath, t as BackendRuntime } from "./runtime-gStewf1p.mjs";
1
2
  import fs from "node:fs/promises";
2
- import os from "node:os";
3
3
  import path from "node:path";
4
4
  import { randomUUID } from "node:crypto";
5
- import { UAM_SUPPORTED_MATERIALIZATION_SCOPE, UAM_SUPPORTED_TRANSACTION_SCOPE, commitUamProjectSourcePaths, liftDocumentToUamProject, materializeUamProject, normalizeUamProject, staleBranchDirectories, staleResourceFolders, staleSourceFiles, validateUamProject } from "@openfairygui/core/uam";
6
- import { applyUamTransactionAppAsync } from "@openfairygui/functions/uam";
7
- import { ProjectReader, ProjectWriter } from "@openfairygui/core/project-io";
8
- import { validateProject } from "@openfairygui/functions";
9
- //#region src/contracts.ts
10
- const BACKEND_CONTRACT_VERSION = "3.0.0";
11
- const BACKEND_COMPATIBILITY_POLICY = {
12
- incompatibleChange: "requires contractVersion bump",
13
- capabilitySchemaChange: "requires capabilitySchemaVersion bump",
14
- additiveChange: "allowed without breaking existing consumers"
15
- };
16
- //#endregion
17
- //#region src/diagnostics.ts
18
- const selector = {
19
- kind: "revise-selector",
20
- 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."
21
- };
22
- const source = {
23
- kind: "host-action",
24
- 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."
25
- };
26
- const path$1 = {
27
- kind: "host-action",
28
- 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."
29
- };
30
- const unsupported = {
31
- kind: "revise-operation",
32
- 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."
33
- };
34
- const payload = {
35
- kind: "revise-operation",
36
- 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."
37
- };
38
- const unchanged = {
39
- kind: "refresh-and-replan",
40
- 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."
41
- };
42
- const duplicate = {
43
- kind: "revise-operation",
44
- 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."
45
- };
46
- const references = {
47
- kind: "revise-operation",
48
- 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."
49
- };
50
- const project = {
51
- kind: "host-action",
52
- 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."
53
- };
54
- const capability = {
55
- kind: "host-action",
56
- 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."
57
- };
58
- const write = {
59
- kind: "host-action",
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."
61
- };
62
- /** Exhaustiveness and exact ownership are checked against the canonical unions. */
63
- const BACKEND_DIAGNOSTIC_GUIDES = [
64
- {
65
- code: "stale_read",
66
- owners: ["backend"],
67
- remediation: {
68
- kind: "refresh-and-replan",
69
- message: "Discard the incomplete model/bytes read and restart with readSessionState. Use its revision for every readResourceBytes call. No historical state is retained or reserved; do not combine resources from different edit revisions."
70
- }
71
- },
72
- {
73
- code: "session_read_failed",
74
- owners: ["backend"],
75
- remediation: {
76
- kind: "host-action",
77
- message: "Inspect error.reason: invalid_query requires valid inputs; not_found/ambiguous requires exact current resource identifiers; unsupported_resource/bytes_unavailable means primary bytes cannot be read from this session. Budget or non-JSON failures require host inspection. Preserve unsaved work; do not save, reopen, repair or mutate the model merely to obtain a read."
78
- }
79
- },
80
- {
81
- code: "transaction_preview_failed",
82
- owners: ["backend"],
83
- remediation: {
84
- kind: "host-action",
85
- 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."
86
- }
87
- },
88
- {
89
- code: "stale_write",
90
- owners: ["backend"],
91
- remediation: {
92
- kind: "refresh-and-replan",
93
- 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."
94
- }
95
- },
96
- {
97
- code: "entity_query_failed",
98
- owners: ["backend"],
99
- remediation: {
100
- kind: "host-action",
101
- 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."
102
- }
103
- },
104
- {
105
- code: "session_not_found",
106
- owners: ["backend"],
107
- remediation: {
108
- kind: "host-action",
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."
110
- }
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
- },
120
- {
121
- code: "path_policy_violation",
122
- owners: ["backend"],
123
- remediation: path$1
124
- },
125
- {
126
- code: "project_root_not_allowed",
127
- owners: ["backend"],
128
- remediation: path$1
129
- },
130
- {
131
- code: "invalid_package_selector",
132
- owners: ["core.transaction"],
133
- remediation: selector
134
- },
135
- {
136
- code: "invalid_component_selector",
137
- owners: ["core.transaction"],
138
- remediation: selector
139
- },
140
- {
141
- code: "invalid_resource_selector",
142
- owners: ["core.transaction"],
143
- remediation: selector
144
- },
145
- {
146
- code: "invalid_display_node_selector",
147
- owners: ["core.transaction"],
148
- remediation: selector
149
- },
150
- {
151
- code: "invalid_resource_folder_selector",
152
- owners: ["core.transaction"],
153
- remediation: selector
154
- },
155
- {
156
- code: "invalid_branch_selector",
157
- owners: ["core.transaction"],
158
- remediation: selector
159
- },
160
- {
161
- code: "invalid_gear_selector",
162
- owners: ["core.transaction"],
163
- remediation: selector
164
- },
165
- {
166
- code: "invalid_look_gear_selector",
167
- owners: ["core.transaction"],
168
- remediation: selector
169
- },
170
- {
171
- code: "selector_ambiguity",
172
- owners: ["core.transaction"],
173
- remediation: selector
174
- },
175
- {
176
- code: "unavailable_resource_source_bytes",
177
- owners: ["core.transaction"],
178
- remediation: source
179
- },
180
- {
181
- code: "missing_source",
182
- owners: ["core.validation"],
183
- remediation: source
184
- },
185
- {
186
- code: "unreadable_source",
187
- owners: ["core.validation"],
188
- remediation: source
189
- },
190
- {
191
- code: "decode_capability_unavailable",
192
- owners: ["core.validation"],
193
- remediation: {
194
- kind: "host-action",
195
- 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."
196
- }
197
- },
198
- {
199
- code: "session_id_conflict",
200
- owners: ["backend"],
201
- remediation: {
202
- kind: "host-action",
203
- 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."
204
- }
205
- },
206
- {
207
- code: "lock_conflict",
208
- owners: ["backend"],
209
- remediation: {
210
- kind: "host-action",
211
- 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."
212
- }
213
- },
214
- {
215
- code: "event_cursor_invalid",
216
- owners: ["backend"],
217
- remediation: {
218
- kind: "refresh-and-replan",
219
- 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."
220
- }
221
- },
222
- {
223
- code: "corrupt_source",
224
- owners: ["core.validation"],
225
- remediation: source
226
- },
227
- {
228
- code: "unsupported_operation",
229
- owners: ["core.transaction"],
230
- remediation: unsupported
231
- },
232
- {
233
- code: "transaction_unsupported",
234
- owners: ["core.transaction"],
235
- remediation: unsupported
236
- },
237
- {
238
- code: "unsupported_display_node_kind",
239
- owners: ["core.transaction"],
240
- remediation: unsupported
241
- },
242
- {
243
- code: "unsupported_cross_package_image_ref",
244
- owners: ["core.transaction"],
245
- remediation: unsupported
246
- },
247
- {
248
- code: "unsupported_gear_kind",
249
- owners: ["core.transaction"],
250
- remediation: unsupported
251
- },
252
- {
253
- code: "unsupported_resource_mutation",
254
- owners: ["core.transaction"],
255
- remediation: unsupported
256
- },
257
- {
258
- code: "unsupported_display_node_mutation",
259
- owners: ["core.transaction"],
260
- remediation: unsupported
261
- },
262
- {
263
- code: "unsupported_text_field_target",
264
- owners: ["core.transaction"],
265
- remediation: unsupported
266
- },
267
- {
268
- code: "unsupported_display_node_field",
269
- owners: ["core.transaction"],
270
- remediation: unsupported
271
- },
272
- {
273
- code: "unsupported_operation_batch",
274
- owners: ["core.transaction"],
275
- remediation: unsupported
276
- },
277
- {
278
- code: "unsupported_resource_kind",
279
- owners: ["core.transaction", "core.validation"],
280
- remediation: unsupported
281
- },
282
- {
283
- code: "invalid_project_settings",
284
- owners: ["core.transaction"],
285
- remediation: payload
286
- },
287
- {
288
- code: "invalid_package_settings",
289
- owners: ["core.transaction"],
290
- remediation: payload
291
- },
292
- {
293
- code: "invalid_display_node_payload",
294
- owners: ["core.transaction"],
295
- remediation: payload
296
- },
297
- {
298
- code: "invalid_resource_name",
299
- owners: ["core.transaction"],
300
- remediation: payload
301
- },
302
- {
303
- code: "invalid_resource_path",
304
- owners: ["core.transaction"],
305
- remediation: payload
306
- },
307
- {
308
- code: "invalid_resource_folder_path",
309
- owners: ["core.transaction"],
310
- remediation: payload
311
- },
312
- {
313
- code: "invalid_resource_folder_atlas",
314
- owners: ["core.transaction"],
315
- remediation: payload
316
- },
317
- {
318
- code: "invalid_attach_index",
319
- owners: ["core.transaction"],
320
- remediation: payload
321
- },
322
- {
323
- code: "invalid_controller_payload",
324
- owners: ["core.transaction"],
325
- remediation: payload
326
- },
327
- {
328
- code: "invalid_transition_payload",
329
- owners: ["core.transaction"],
330
- remediation: payload
331
- },
332
- {
333
- code: "invalid_look_gear_payload",
334
- owners: ["core.transaction"],
335
- remediation: payload
336
- },
337
- {
338
- code: "invalid_gear_payload",
339
- owners: ["core.transaction"],
340
- remediation: payload
341
- },
342
- {
343
- code: "invalid_resource_payload",
344
- owners: ["core.transaction"],
345
- remediation: payload
346
- },
347
- {
348
- code: "invalid_resource_bytes",
349
- owners: ["core.transaction"],
350
- remediation: payload
351
- },
352
- {
353
- code: "invalid_movie_clip_jta",
354
- owners: ["core.transaction"],
355
- remediation: payload
356
- },
357
- {
358
- code: "invalid_resource_index",
359
- owners: ["core.transaction"],
360
- remediation: payload
361
- },
362
- {
363
- code: "invalid_branch_name",
364
- owners: ["core.transaction"],
365
- remediation: payload
366
- },
367
- {
368
- code: "invalid_package_payload",
369
- owners: ["core.transaction"],
370
- remediation: payload
371
- },
372
- {
373
- code: "invalid_package_index",
374
- owners: ["core.transaction"],
375
- remediation: payload
376
- },
377
- {
378
- code: "invalid_component_payload",
379
- owners: ["core.transaction"],
380
- remediation: payload
381
- },
382
- {
383
- code: "invalid_component_index",
384
- owners: ["core.transaction"],
385
- remediation: payload
386
- },
387
- {
388
- code: "invalid_component_move",
389
- owners: ["core.transaction"],
390
- remediation: payload
391
- },
392
- {
393
- code: "invalid_uam",
394
- owners: ["core.transaction", "core.validation"],
395
- remediation: payload
396
- },
397
- {
398
- code: "project_settings_unchanged",
399
- owners: ["core.transaction"],
400
- remediation: unchanged
401
- },
402
- {
403
- code: "package_settings_unchanged",
404
- owners: ["core.transaction"],
405
- remediation: unchanged
406
- },
407
- {
408
- code: "display_node_props_unchanged",
409
- owners: ["core.transaction"],
410
- remediation: unchanged
411
- },
412
- {
413
- code: "resource_folder_atlas_unchanged",
414
- owners: ["core.transaction"],
415
- remediation: unchanged
416
- },
417
- {
418
- code: "duplicate_look_gear_controller",
419
- owners: ["core.transaction"],
420
- remediation: duplicate
421
- },
422
- {
423
- code: "duplicate_transition_name",
424
- owners: ["core.transaction"],
425
- remediation: duplicate
426
- },
427
- {
428
- code: "duplicate_look_gear_state_page",
429
- owners: ["core.transaction"],
430
- remediation: duplicate
431
- },
432
- {
433
- code: "duplicate_gear_controller",
434
- owners: ["core.transaction"],
435
- remediation: duplicate
436
- },
437
- {
438
- code: "duplicate_gear_state_page",
439
- owners: ["core.transaction"],
440
- remediation: duplicate
441
- },
442
- {
443
- code: "duplicate_branch_name",
444
- owners: ["core.transaction"],
445
- remediation: duplicate
446
- },
447
- {
448
- code: "duplicate_component_id",
449
- owners: ["core.transaction"],
450
- remediation: duplicate
451
- },
452
- {
453
- code: "resource_folder_conflict",
454
- owners: ["core.transaction"],
455
- remediation: duplicate
456
- },
457
- {
458
- code: "duplicate_resource_id",
459
- owners: ["core.transaction", "core.validation"],
460
- remediation: duplicate
461
- },
462
- {
463
- code: "duplicate_package_id",
464
- owners: ["core.transaction", "core.validation"],
465
- remediation: duplicate
466
- },
467
- {
468
- code: "duplicate_package_name",
469
- owners: ["core.transaction", "core.validation"],
470
- remediation: duplicate
471
- },
472
- {
473
- code: "resource_folder_not_empty",
474
- owners: ["core.transaction"],
475
- remediation: references
476
- },
477
- {
478
- code: "branch_not_empty",
479
- owners: ["core.transaction"],
480
- remediation: references
481
- },
482
- {
483
- code: "branch_referenced",
484
- owners: ["core.transaction"],
485
- remediation: references
486
- },
487
- {
488
- code: "invalid_resource_reference",
489
- owners: ["core.transaction"],
490
- remediation: references
491
- },
492
- {
493
- code: "invalid_component_reference",
494
- owners: ["core.transaction"],
495
- remediation: references
496
- },
497
- {
498
- code: "invalid_group_reference",
499
- owners: ["core.transaction"],
500
- remediation: references
501
- },
502
- {
503
- code: "package_referenced",
504
- owners: ["core.transaction"],
505
- remediation: references
506
- },
507
- {
508
- code: "component_referenced",
509
- owners: ["core.transaction"],
510
- remediation: references
511
- },
512
- {
513
- code: "component_has_package_dependencies",
514
- owners: ["core.transaction"],
515
- remediation: references
516
- },
517
- {
518
- code: "dangling_resource_reference",
519
- owners: ["core.validation"],
520
- remediation: references
521
- },
522
- {
523
- code: "invalid_project_xml",
524
- owners: ["core.validation"],
525
- remediation: project
526
- },
527
- {
528
- code: "invalid_package_xml",
529
- owners: ["core.validation"],
530
- remediation: project
531
- },
532
- {
533
- code: "invalid_branch_package_xml",
534
- owners: ["core.validation"],
535
- remediation: project
536
- },
537
- {
538
- code: "invalid_component_xml",
539
- owners: ["core.validation"],
540
- remediation: project
541
- },
542
- {
543
- code: "invalid_project_value",
544
- owners: ["core.validation"],
545
- remediation: project
546
- },
547
- {
548
- code: "desktop_incompatible_geometry",
549
- owners: ["core.validation"],
550
- remediation: project
551
- },
552
- {
553
- code: "invalid_settings_json",
554
- owners: ["core.validation"],
555
- remediation: project
556
- },
557
- {
558
- code: "path_collision",
559
- owners: ["core.validation"],
560
- remediation: path$1
561
- },
562
- {
563
- code: "unsafe_path",
564
- owners: ["core.validation"],
565
- remediation: path$1
566
- },
567
- {
568
- code: "capability_unavailable",
569
- owners: ["backend"],
570
- remediation: capability
571
- },
572
- {
573
- code: "uam_fidelity_unsupported",
574
- owners: ["backend"],
575
- remediation: capability
576
- },
577
- {
578
- code: "save_partial_failure",
579
- owners: ["backend"],
580
- remediation: write
581
- },
582
- {
583
- code: "write_failed",
584
- owners: ["backend"],
585
- remediation: write
586
- },
587
- {
588
- code: "project_open_failed",
589
- owners: ["backend"],
590
- remediation: project
591
- },
592
- {
593
- code: "materialize_validation_failed",
594
- owners: ["backend"],
595
- remediation: project
596
- },
597
- {
598
- code: "execution_failure",
599
- owners: ["core.transaction"],
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
- }
604
- }
605
- ];
606
- const BACKEND_DIAGNOSTICS_URI = "openfairygui://docs/diagnostics";
607
- `${BACKEND_DIAGNOSTICS_URI}`;
608
- function enrichBackendDiagnostic(diagnostic, sessionId) {
609
- const guide = BACKEND_DIAGNOSTIC_GUIDES.find((entry) => entry.code === diagnostic.code);
610
- if (!guide) return { ...diagnostic };
611
- return {
612
- ...diagnostic,
613
- owner: diagnostic.owner ?? guide.owners[0],
614
- docsUri: `${BACKEND_DIAGNOSTICS_URI}/${guide.code}`,
615
- remediation: {
616
- ...guide.remediation,
617
- ...sessionId && guide.remediation.kind !== "host-action" ? { read: {
618
- method: "getProjectOutline",
619
- input: { sessionId }
620
- } } : {}
621
- }
622
- };
623
- }
624
- //#endregion
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
- }
634
- function diagnosticFromError(error) {
635
- return {
636
- code: error.code,
637
- message: error.message,
638
- severity: "error"
639
- };
640
- }
641
- function randomId$1() {
642
- return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
643
- }
644
- function createMeta(stage, startedAt, options) {
645
- return {
646
- requestId: options?.requestId ?? randomId$1(),
647
- sessionId: options?.sessionId,
648
- revision: options?.revision,
649
- durationMs: Math.max(0, Date.now() - startedAt),
650
- warnings: options?.warnings ?? [],
651
- diagnostics: (options?.diagnostics ?? []).map((entry) => enrichBackendDiagnostic(entry, options?.sessionId)),
652
- stage,
653
- contractVersion: BACKEND_CONTRACT_VERSION,
654
- capabilitySchemaVersion: 12
655
- };
656
- }
657
- function success(stage, startedAt, data, options) {
658
- return {
659
- ok: true,
660
- meta: createMeta(stage, startedAt, options),
661
- data
662
- };
663
- }
664
- function failure(stage, startedAt, error, session, options) {
665
- const diagnostics = options?.diagnostics ?? [diagnosticFromError(error)];
666
- return {
667
- ok: false,
668
- meta: createMeta(stage, startedAt, {
669
- ...options,
670
- diagnostics
671
- }),
672
- error,
673
- session
674
- };
675
- }
676
- //#endregion
677
- //#region src/services/session-utils.ts
678
- function toSessionSnapshot(session, capabilities) {
679
- return {
680
- sessionId: session.sessionId,
681
- canonicalProjectPath: session.canonicalProjectPath,
682
- revision: session.revision,
683
- lastSavedRevision: session.lastSavedRevision,
684
- dirty: session.dirty,
685
- uamFidelity: session.uamFidelity,
686
- lockHeld: session.lockHeld,
687
- capabilities: cloneReadData(capabilities)
688
- };
689
- }
690
- function createSessionNotFoundError(sessionId) {
691
- return {
692
- code: "session_not_found",
693
- message: `Session was not found: ${sessionId}`,
694
- sessionId
695
- };
696
- }
697
- function createStaleWriteError(session, expectedRevision) {
698
- return {
699
- code: "stale_write",
700
- message: `Expected revision ${expectedRevision} does not match current revision ${session.revision}.`,
701
- sessionId: session.sessionId,
702
- canonicalPathKey: session.canonicalPathKey,
703
- expectedRevision,
704
- actualRevision: session.revision
705
- };
706
- }
707
- //#endregion
708
- //#region src/runtime/contracts.ts
709
- const BACKEND_ENTITY_QUERY_LIMITS = {
710
- maxBytes: 262144,
711
- maxDepth: 32,
712
- maxNodes: 1e5
713
- };
714
- const BACKEND_SESSION_READ_LIMITS = {
715
- model: {
716
- maxBytes: 4194304,
717
- maxDepth: 64,
718
- maxNodes: 5e5
719
- },
720
- resourceBytes: 1048576
721
- };
722
- const BACKEND_TRANSACTION_PREVIEW_LIMITS = {
723
- maxBytes: 262144,
724
- maxEntries: 2e3
725
- };
726
- /** Fixed resource projection. Binary content, source bookkeeping and arbitrary metadata are excluded. */
727
- const BACKEND_RESOURCE_QUERY_FIELDS = [
728
- "kind",
729
- "id",
730
- "name",
731
- "path",
732
- "exported",
733
- "favorite",
734
- "branch",
735
- "branchItemIds",
736
- "fileName",
737
- "file",
738
- "dimensions",
739
- "image",
740
- "movieClip"
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
- };
758
- //#endregion
759
- //#region src/services/capture-project.ts
760
- function createCaptureFileSystem(files, directories) {
761
- const normalize = (filePath) => filePath.replace(/\\/g, "/").replace(/\/+/g, "/");
762
- return {
763
- async readFile(filePath) {
764
- const value = files.get(normalize(filePath));
765
- if (typeof value !== "string") throw new Error(`Captured text file was not found: ${filePath}`);
766
- return value;
767
- },
768
- async readFileRaw(filePath) {
769
- const value = files.get(normalize(filePath));
770
- if (!(value instanceof Uint8Array)) throw new Error(`Captured binary file was not found: ${filePath}`);
771
- return value.slice();
772
- },
773
- async writeFile(filePath, content) {
774
- files.set(normalize(filePath), content);
775
- },
776
- async writeFileRaw(filePath, data) {
777
- files.set(normalize(filePath), data.slice());
778
- },
779
- async mkdir(dirPath) {
780
- directories.add(normalize(dirPath));
781
- },
782
- async readdir() {
783
- return [];
784
- },
785
- async exists(filePath) {
786
- return files.has(normalize(filePath));
787
- },
788
- join(...paths) {
789
- return normalize(paths.filter(Boolean).join("/"));
790
- },
791
- dirname(filePath) {
792
- const normalized = normalize(filePath);
793
- const separator = normalized.lastIndexOf("/");
794
- return separator < 0 ? "" : normalized.slice(0, separator);
795
- },
796
- async unlink(filePath) {
797
- files.delete(normalize(filePath));
798
- }
799
- };
800
- }
801
- function capturedFilesEqual(left, right) {
802
- if (left.size !== right.size) return false;
803
- for (const [filePath, leftValue] of left) {
804
- const rightValue = right.get(filePath);
805
- if (typeof leftValue === "string") {
806
- if (leftValue !== rightValue) return false;
807
- continue;
808
- }
809
- if (!(rightValue instanceof Uint8Array) || leftValue.length !== rightValue.length) return false;
810
- for (let index = 0; index < leftValue.length; index += 1) if (leftValue[index] !== rightValue[index]) return false;
811
- }
812
- return true;
813
- }
814
- function capturedDirectoriesEqual(left, right) {
815
- return left.size === right.size && [...left].every((directory) => right.has(directory));
816
- }
817
- /** Serialize only into memory. This is a model projection, not a disk inventory or write plan. */
818
- async function captureProject(document, fairyFileName) {
819
- const files = /* @__PURE__ */ new Map();
820
- const directories = /* @__PURE__ */ new Set();
821
- await new ProjectWriter(createCaptureFileSystem(files, directories)).write(document, fairyFileName);
822
- return {
823
- files,
824
- directories
825
- };
826
- }
827
- //#endregion
828
- //#region src/services/transaction-preview.ts
829
- /** Keep child identities/order on their parent, and compare each child's own properties separately. */
830
- function entities(project) {
831
- const result = /* @__PURE__ */ new Map();
832
- function add(target, properties) {
833
- const key = JSON.stringify(target);
834
- if (result.has(key)) throw new Error(`Ambiguous preview identity: ${key}`);
835
- result.set(key, {
836
- target,
837
- properties
838
- });
839
- }
840
- const { packages, ...properties } = project;
841
- add({ kind: "project" }, {
842
- ...properties,
843
- packages: packages.map((pkg) => pkg.id)
844
- });
845
- for (const { resources, ...pkg } of packages) {
846
- const packageId = pkg.id;
847
- add({
848
- kind: "package",
849
- selector: { packageId }
850
- }, {
851
- ...pkg,
852
- resources: resources.map((resource) => resource.id)
853
- });
854
- for (const resource of resources) {
855
- const resourceTarget = {
856
- kind: "resource",
857
- selector: {
858
- packageId,
859
- resourceId: resource.id
860
- }
861
- };
862
- if (resource.kind !== "component") {
863
- add(resourceTarget, resource);
864
- continue;
865
- }
866
- const { component, ...resourceProperties } = resource;
867
- add(resourceTarget, resourceProperties);
868
- const { displayList, controllers, transitions, ...componentProperties } = component;
869
- const selector = {
870
- packageId,
871
- componentResourceId: resource.id
872
- };
873
- add({
874
- kind: "component",
875
- selector
876
- }, {
877
- ...componentProperties,
878
- displayList: displayList.map((node) => node.id),
879
- controllers: controllers.map((controller) => controller.name),
880
- transitions: transitions.map((transition) => transition.name)
881
- });
882
- for (const node of displayList) add({
883
- kind: "displayNode",
884
- selector: {
885
- ...selector,
886
- displayNodeId: node.id
887
- }
888
- }, node);
889
- for (const controller of controllers) add({
890
- kind: "controller",
891
- selector: {
892
- ...selector,
893
- controllerName: controller.name
894
- }
895
- }, controller);
896
- for (const transition of transitions) add({
897
- kind: "transition",
898
- selector: {
899
- ...selector,
900
- transitionName: transition.name
901
- }
902
- }, transition);
903
- }
904
- }
905
- return result;
906
- }
907
- function equal(left, right, depth = 0) {
908
- if (left === right) return true;
909
- if (!left || !right || typeof left !== "object" || typeof right !== "object") return false;
910
- 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]);
911
- if (depth > 128) throw new Error("Preview property comparison exceeds the supported nesting depth.");
912
- if (Array.isArray(left) !== Array.isArray(right)) return false;
913
- if (Array.isArray(left) && Array.isArray(right) && left.length !== right.length) return false;
914
- const a = left, b = right;
915
- const keys = Object.keys(a);
916
- return keys.length === Object.keys(b).length && keys.every((key) => Object.hasOwn(b, key) && equal(a[key], b[key], depth + 1));
917
- }
918
- var PreviewBudgetError = class extends Error {};
919
- /** No host filesystem, cache, event or session mutation is involved in the projection. */
920
- async function previewTransactionImpact(session, project, fileSystemAvailable) {
921
- const impact = {
922
- entities: [],
923
- files: []
924
- };
925
- const before = entities(session.project), after = entities(project);
926
- let entries = 0, bytes = 0;
927
- const encoder = new TextEncoder();
928
- function count(value) {
929
- bytes += encoder.encode(JSON.stringify(value)).byteLength;
930
- 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.");
931
- }
932
- for (const key of new Set([...before.keys(), ...after.keys()])) {
933
- const previous = before.get(key), next = after.get(key);
934
- const fields = [...new Set([...Object.keys(previous?.properties ?? {}), ...Object.keys(next?.properties ?? {})])].filter((field) => !previous || !next || !equal(previous.properties[field], next.properties[field])).sort();
935
- if (!fields.length && previous && next) continue;
936
- const change = {
937
- target: (next ?? previous).target,
938
- change: !previous ? "added" : !next ? "removed" : "updated",
939
- fields
940
- };
941
- count(change);
942
- impact.entities.push(change);
943
- }
944
- const fairyFileName = session.fileSystem ? session.fairyPath.replace(/\\/g, "/").split("/").at(-1) : "Project.fairy";
945
- const [previousFiles, nextFiles] = await Promise.all([captureProject(materializeUamProject(session.project, { validate: false }), fairyFileName), captureProject(materializeUamProject(project), fairyFileName)]);
946
- for (const path of new Set([...previousFiles.files.keys(), ...nextFiles.files.keys()])) {
947
- const previous = previousFiles.files.get(path), next = nextFiles.files.get(path);
948
- if (equal(previous, next)) continue;
949
- const change = {
950
- path,
951
- kind: "file",
952
- change: previous === void 0 ? "added" : next === void 0 ? "removed" : "updated"
953
- };
954
- count(change);
955
- impact.files.push(change);
956
- }
957
- for (const path of new Set([...previousFiles.directories, ...nextFiles.directories])) {
958
- if (previousFiles.directories.has(path) === nextFiles.directories.has(path)) continue;
959
- const change = {
960
- path,
961
- kind: "directory",
962
- change: nextFiles.directories.has(path) ? "added" : "removed"
963
- };
964
- count(change);
965
- impact.files.push(change);
5
+ import os from "node:os";
6
+ import { execFile } from "node:child_process";
7
+ import { promisify } from "node:util";
8
+ //#region src/node-session-lock.ts
9
+ const PROCESS_START_TIME = Math.trunc(Date.now() - process.uptime() * 1e3);
10
+ /** Windows reports sharing violations and delete-pending files (scanners, concurrent unlinks) with these codes. */
11
+ function isTransientWindowsLockError(error) {
12
+ const code = error?.code;
13
+ return process.platform === "win32" && [
14
+ "EPERM",
15
+ "EACCES",
16
+ "EBUSY"
17
+ ].includes(code ?? "");
18
+ }
19
+ async function retryLockIo(operation) {
20
+ for (let attempt = 0;; attempt++) try {
21
+ return await operation();
22
+ } catch (error) {
23
+ if (attempt >= 7 || !isTransientWindowsLockError(error)) throw error;
24
+ await new Promise((resolve) => setTimeout(resolve, 10 * 2 ** attempt));
966
25
  }
967
- impact.files.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : a.kind.localeCompare(b.kind));
968
- const preview = {
969
- sessionId: session.sessionId,
970
- baseRevision: session.revision,
971
- projectedRevision: session.revision + 1,
972
- mode: "execute-and-discard",
973
- impact,
974
- persistence: {
975
- requiredAfterApply: true,
976
- fileSystemAvailable,
977
- uamFidelity: session.uamFidelity,
978
- writeVerified: false,
979
- nextAction: session.uamFidelity === "unsupported" || !fileSystemAvailable ? "host-action" : session.fileSystem ? "saveSession" : "materializeSession"
980
- }
981
- };
982
- if (encoder.encode(JSON.stringify(preview)).byteLength > BACKEND_TRANSACTION_PREVIEW_LIMITS.maxBytes) throw new PreviewBudgetError("The complete transaction preview exceeds the response byte budget.");
983
- return preview;
984
- }
985
- //#endregion
986
- //#region src/services/authoring-service.ts
987
- function sourceFileKey(source) {
988
- return [
989
- source.branch,
990
- source.packageName,
991
- source.path,
992
- source.fileName
993
- ].join("\0");
994
- }
995
- function resourceFolderKey(folder) {
996
- return [
997
- folder.branch,
998
- folder.packageName,
999
- folder.path
1000
- ].join("\0");
1001
- }
1002
- function branchDirectoryKey(directory) {
1003
- return [directory.branch, directory.packageName ?? ""].join("\0");
1004
26
  }
1005
- function recordStaleProjectFiles(session, previousProject, nextProject) {
1006
- if (!session.fileSystem) return;
1007
- for (const source of staleSourceFiles(previousProject, nextProject)) session.pendingStaleSourceFiles.set(sourceFileKey(source), source);
1008
- for (const source of staleSourceFiles(nextProject, previousProject)) session.pendingStaleSourceFiles.delete(sourceFileKey(source));
1009
- for (const folder of staleResourceFolders(previousProject, nextProject)) session.pendingStaleResourceFolders.set(resourceFolderKey(folder), folder);
1010
- for (const folder of staleResourceFolders(nextProject, previousProject)) session.pendingStaleResourceFolders.delete(resourceFolderKey(folder));
1011
- for (const directory of staleBranchDirectories(previousProject, nextProject)) session.pendingStaleBranchDirectories.set(branchDirectoryKey(directory), directory);
1012
- for (const directory of staleBranchDirectories(nextProject, previousProject)) session.pendingStaleBranchDirectories.delete(branchDirectoryKey(directory));
1013
- }
1014
- function toBackendDiagnostics(error) {
1015
- return error.diagnostics.length > 0 ? error.diagnostics.map((diagnostic) => ({
1016
- ...diagnostic,
1017
- owner: "core.transaction"
1018
- })) : [{
1019
- code: error.code,
1020
- owner: "core.transaction",
1021
- message: error.message,
1022
- severity: "error",
1023
- operationKind: error.operationKind,
1024
- opIndex: error.opIndex,
1025
- opId: error.opId
1026
- }];
1027
- }
1028
- function detachSharedByteViews(value, seen = /* @__PURE__ */ new WeakSet()) {
1029
- if (!value || typeof value !== "object" || seen.has(value)) return;
1030
- seen.add(value);
1031
- for (const [key, child] of Object.entries(value)) {
1032
- if (child instanceof Uint8Array) {
1033
- if (typeof SharedArrayBuffer !== "undefined" && child.buffer instanceof SharedArrayBuffer) value[key] = new Uint8Array(child);
1034
- continue;
1035
- }
1036
- detachSharedByteViews(child, seen);
27
+ function parseLockMetadata(content) {
28
+ try {
29
+ const value = JSON.parse(content);
30
+ if (value.schemaVersion !== 2 || typeof value.processIdentity !== "string" || !value.processIdentity || !Number.isSafeInteger(value.pid) || value.pid <= 0 || !Number.isFinite(value.processStartTime) || typeof value.hostname !== "string" || typeof value.token !== "string" || !/^[a-zA-Z0-9_-]+$/.test(value.token)) return null;
31
+ return value;
32
+ } catch {
33
+ return null;
1037
34
  }
1038
35
  }
1039
- var AuthoringService = class {
1040
- constructor(context, cacheService, eventService, sessionOperations) {
1041
- this.context = context;
1042
- this.cacheService = cacheService;
1043
- this.eventService = eventService;
1044
- this.sessionOperations = sessionOperations;
1045
- }
1046
- async preflightTransaction(input) {
1047
- const queuedInput = structuredClone(input);
1048
- detachSharedByteViews(queuedInput);
1049
- return this.sessionOperations.run(queuedInput.sessionId, async () => {
1050
- const startedAt = Date.now();
1051
- const session = this.context.sessions.get(queuedInput.sessionId);
1052
- if (!session || session.closed) return failure("authoring", startedAt, createSessionNotFoundError(queuedInput.sessionId));
1053
- const meta = {
1054
- sessionId: session.sessionId,
1055
- revision: session.revision
1056
- };
1057
- if (queuedInput.expectedRevision !== session.revision) return failure("authoring", startedAt, createStaleWriteError(session, queuedInput.expectedRevision), toSessionSnapshot(session, this.context.capabilities), meta);
1058
- const project = structuredClone(session.project);
1059
- detachSharedByteViews(project);
1060
- const result = await applyUamTransactionAppAsync({
1061
- project,
1062
- operations: queuedInput.operations
1063
- });
1064
- if (this.context.sessions.get(queuedInput.sessionId) !== session || session.closed) return failure("authoring", startedAt, createSessionNotFoundError(queuedInput.sessionId));
1065
- if (!result.ok) return failure("authoring", startedAt, result.error, toSessionSnapshot(session, this.context.capabilities), {
1066
- ...meta,
1067
- diagnostics: toBackendDiagnostics(result.error)
1068
- });
1069
- try {
1070
- const preview = await previewTransactionImpact({
1071
- ...session,
1072
- project
1073
- }, result.project, Boolean(session.fileSystem));
1074
- if (this.context.sessions.get(queuedInput.sessionId) !== session || session.closed) return failure("authoring", startedAt, createSessionNotFoundError(queuedInput.sessionId));
1075
- return success("authoring", startedAt, preview, meta);
1076
- } catch (error) {
1077
- return failure("authoring", startedAt, {
1078
- code: "transaction_preview_failed",
1079
- sessionId: session.sessionId,
1080
- reason: error instanceof PreviewBudgetError ? "response_budget_exceeded" : "projection_failed",
1081
- message: error instanceof Error ? error.message : String(error)
1082
- }, toSessionSnapshot(session, this.context.capabilities), meta);
1083
- }
1084
- });
1085
- }
1086
- async applyTransaction(input) {
1087
- const queuedInput = structuredClone(input);
1088
- detachSharedByteViews(queuedInput);
1089
- return this.sessionOperations.run(queuedInput.sessionId, () => this.applyTransactionExclusive(queuedInput));
1090
- }
1091
- async applyTransactionExclusive(input) {
1092
- const startedAt = Date.now();
1093
- const session = this.context.sessions.get(input.sessionId);
1094
- if (!session || session.closed) return failure("authoring", startedAt, createSessionNotFoundError(input.sessionId));
1095
- if (input.expectedRevision !== session.revision) {
1096
- this.eventService.emit({
1097
- kind: "transaction.rejected",
1098
- sessionId: session.sessionId,
1099
- canonicalPathKey: session.canonicalPathKey,
1100
- revision: session.revision
1101
- });
1102
- return failure("authoring", startedAt, createStaleWriteError(session, input.expectedRevision), toSessionSnapshot(session, this.context.capabilities), {
1103
- sessionId: session.sessionId,
1104
- revision: session.revision
1105
- });
1106
- }
1107
- const result = await applyUamTransactionAppAsync({
1108
- project: session.project,
1109
- operations: input.operations
1110
- });
1111
- if (this.context.sessions.get(input.sessionId) !== session || session.closed) return failure("authoring", startedAt, createSessionNotFoundError(input.sessionId));
1112
- if (result.ok === false) {
1113
- const diagnostics = toBackendDiagnostics(result.error);
1114
- this.eventService.emit({
1115
- kind: "transaction.rejected",
1116
- sessionId: session.sessionId,
1117
- canonicalPathKey: session.canonicalPathKey,
1118
- revision: session.revision,
1119
- diagnostics
1120
- });
1121
- return failure("authoring", startedAt, result.error, toSessionSnapshot(session, this.context.capabilities), {
1122
- sessionId: session.sessionId,
1123
- revision: session.revision,
1124
- diagnostics
36
+ const execute = promisify(execFile);
37
+ /** OS creation identity distinguishes a live process from a later process reusing its PID. */
38
+ async function processIdentity(pid) {
39
+ try {
40
+ if (process.platform === "linux") {
41
+ const [stat, boot] = await Promise.all([fs.readFile(`/proc/${pid}/stat`, "utf8"), fs.readFile("/proc/sys/kernel/random/boot_id", "utf8")]);
42
+ const start = stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19];
43
+ return start ? `linux:${boot.trim()}:${start}` : null;
44
+ }
45
+ if (process.platform === "win32") {
46
+ const pending = execute("powershell.exe", [
47
+ "-NoProfile",
48
+ "-NonInteractive",
49
+ "-Command",
50
+ `[System.Diagnostics.Process]::GetProcessById(${pid}).StartTime.ToUniversalTime().Ticks`
51
+ ], {
52
+ windowsHide: true,
53
+ timeout: 15e3
1125
54
  });
1126
- }
1127
- recordStaleProjectFiles(session, session.project, result.project);
1128
- session.project = result.project;
1129
- session.revision += 1;
1130
- session.dirty = true;
1131
- const cacheEntry = this.cacheService.invalidateSession(session);
1132
- this.eventService.emit({
1133
- kind: "transaction.applied",
1134
- sessionId: session.sessionId,
1135
- canonicalPathKey: session.canonicalPathKey,
1136
- revision: session.revision
1137
- });
1138
- this.eventService.emit({
1139
- kind: "cache.invalidated",
1140
- sessionId: session.sessionId,
1141
- canonicalPathKey: session.canonicalPathKey,
1142
- revision: session.revision,
1143
- cacheRevision: cacheEntry.revision
1144
- });
1145
- return success("authoring", startedAt, toSessionSnapshot(session, this.context.capabilities), {
1146
- sessionId: session.sessionId,
1147
- revision: session.revision
55
+ pending.child?.stdin?.end();
56
+ const { stdout } = await pending;
57
+ return /^\d+$/.test(stdout.trim()) ? `win32:${stdout.trim()}` : null;
58
+ }
59
+ const { stdout } = await execute("ps", [
60
+ "-p",
61
+ String(pid),
62
+ "-o",
63
+ "lstart="
64
+ ], {
65
+ env: {
66
+ ...process.env,
67
+ LC_ALL: "C"
68
+ },
69
+ timeout: 5e3
1148
70
  });
71
+ return stdout.trim() ? `unix:${stdout.trim()}` : null;
72
+ } catch {
73
+ return null;
1149
74
  }
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
75
  }
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
- };
76
+ /** Recorded when the OS probe is unavailable (missing, blocked or hung PowerShell / `ps`); no other process can recompute it. */
77
+ const UNVERIFIED_IDENTITY_PREFIX = "unverified:";
78
+ let ownIdentity;
79
+ /** Resolved once per process, so every lock record this process writes carries the same identity. */
80
+ function getOwnIdentity() {
81
+ return ownIdentity ??= processIdentity(process.pid).then((identity) => identity ?? `${UNVERIFIED_IDENTITY_PREFIX}${randomUUID()}`);
1271
82
  }
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);
83
+ async function isProcessAlive(metadata) {
84
+ if (metadata.hostname !== os.hostname()) return true;
1282
85
  try {
1283
- await input.fileSystem.runProjectWriteTransaction(projectRoot, write);
86
+ process.kill(metadata.pid, 0);
1284
87
  } 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
- }
1344
- async saveSession(input) {
1345
- if (input.force === true || input.mode === "materializeCleanSession") return this.materializeSession({
1346
- sessionId: input.sessionId,
1347
- expectedRevision: input.expectedRevision,
1348
- targetPath: input.targetPath,
1349
- fileSystem: input.fileSystem,
1350
- mode: "fullProject",
1351
- reason: "force_save"
1352
- });
1353
- const captured = { ...input };
1354
- return this.sessionOperations.run(captured.sessionId, () => this.saveSessionExclusive(captured));
1355
- }
1356
- finishSuccessfulSave(session) {
1357
- session.lastSavedRevision = session.revision;
1358
- session.dirty = false;
1359
- const cacheEntry = this.cacheService.refreshSession(session);
1360
- this.eventService.emit({
1361
- kind: "save.completed",
1362
- sessionId: session.sessionId,
1363
- canonicalPathKey: session.canonicalPathKey,
1364
- revision: session.revision
1365
- });
1366
- this.eventService.emit({
1367
- kind: "cache.updated",
1368
- sessionId: session.sessionId,
1369
- canonicalPathKey: session.canonicalPathKey,
1370
- revision: session.revision,
1371
- cacheRevision: cacheEntry.revision
1372
- });
88
+ return error.code !== "ESRCH";
1373
89
  }
1374
- async saveSessionExclusive(input) {
1375
- const startedAt = Date.now();
1376
- const session = this.context.sessions.get(input.sessionId);
1377
- if (!session || session.closed) return failure("authoring", startedAt, createSessionNotFoundError(input.sessionId));
1378
- const fileSystem = session.fileSystem ?? input.fileSystem;
1379
- if (!fileSystem) return failure("authoring", startedAt, createCapabilityUnavailableError$1("saveSession requires an injected BackendFileSystem adapter."), toSessionSnapshot(session, this.context.capabilities), {
1380
- sessionId: session.sessionId,
1381
- revision: session.revision
1382
- });
1383
- if (input.expectedRevision !== void 0 && input.expectedRevision !== session.revision) return failure("authoring", startedAt, createStaleWriteError(session, input.expectedRevision), toSessionSnapshot(session, this.context.capabilities), {
1384
- sessionId: session.sessionId,
1385
- revision: session.revision
1386
- });
1387
- const targetViolation = await validateSaveTarget(fileSystem, session.fairyPath, input.targetPath);
1388
- if (targetViolation) return failure("authoring", startedAt, targetViolation, toSessionSnapshot(session, this.context.capabilities), {
1389
- sessionId: session.sessionId,
1390
- revision: session.revision
1391
- });
1392
- if (!session.dirty) return success("authoring", startedAt, toSessionSnapshot(session, this.context.capabilities), {
1393
- sessionId: session.sessionId,
1394
- revision: session.revision
1395
- });
1396
- if (session.uamFidelity === "unsupported") return failure("authoring", startedAt, createUamFidelityUnsupportedError(session), toSessionSnapshot(session, this.context.capabilities), {
1397
- sessionId: session.sessionId,
1398
- revision: session.revision
1399
- });
1400
- const committedPaths = [];
1401
- const failedPaths = [];
1402
- this.eventService.emit({
1403
- kind: "save.started",
1404
- sessionId: session.sessionId,
1405
- canonicalPathKey: session.canonicalPathKey,
1406
- revision: session.revision
1407
- });
90
+ const identity = metadata.pid === process.pid ? await getOwnIdentity() : await processIdentity(metadata.pid);
91
+ return identity === null || identity.startsWith(UNVERIFIED_IDENTITY_PREFIX) || metadata.processIdentity.startsWith(UNVERIFIED_IDENTITY_PREFIX) || identity === metadata.processIdentity;
92
+ }
93
+ /** Lamport's bakery doorway serializes short lock-file operations across processes.
94
+ * Each contender owns a unique file, so removing a dead contender cannot remove a newer owner.
95
+ * The directory is retained: deleting it while another contender enters would split the doorway.
96
+ */
97
+ async function coordinateLock(filePath, action) {
98
+ const directory = `${filePath}.coordination`;
99
+ await fs.mkdir(directory, { recursive: true });
100
+ const identity = await getOwnIdentity();
101
+ const token = randomUUID();
102
+ const candidate = path.join(directory, token);
103
+ const temporary = path.join(directory, `.${token}.tmp`);
104
+ const ticketTemporary = path.join(directory, `.${token}.ticket.tmp`);
105
+ const ticketPath = path.join(directory, `.ticket-${token}`);
106
+ const owner = {
107
+ schemaVersion: 2,
108
+ pid: process.pid,
109
+ processStartTime: PROCESS_START_TIME,
110
+ processIdentity: identity,
111
+ hostname: os.hostname(),
112
+ token,
113
+ ticket: 0
114
+ };
115
+ const publish = async () => {
116
+ await retryLockIo(() => fs.writeFile(temporary, JSON.stringify(owner)));
117
+ await retryLockIo(() => fs.link(temporary, candidate));
118
+ await retryLockIo(() => fs.unlink(temporary));
119
+ };
120
+ const readContender = async (name) => {
1408
121
  try {
1409
- await writeSessionProject({
1410
- fileSystem,
1411
- document: materializeUamProject(session.project),
1412
- fairyPath: session.fairyPath,
1413
- staleSourceFiles: [...session.pendingStaleSourceFiles.values()],
1414
- staleResourceFolders: [...session.pendingStaleResourceFolders.values()],
1415
- staleBranchDirectories: [...session.pendingStaleBranchDirectories.values()],
1416
- writtenPaths: committedPaths,
1417
- failedPaths
1418
- });
1419
- session.fileSystem ??= fileSystem;
1420
- session.pendingStaleSourceFiles.clear();
1421
- session.pendingStaleResourceFolders.clear();
1422
- session.pendingStaleBranchDirectories.clear();
1423
- commitUamProjectSourcePaths(session.project);
1424
- this.finishSuccessfulSave(session);
1425
- return success("authoring", startedAt, toSessionSnapshot(session, this.context.capabilities), {
1426
- sessionId: session.sessionId,
1427
- revision: session.revision
1428
- });
1429
- } catch (error) {
1430
- this.cacheService.invalidateSession(session);
1431
- this.eventService.emit({
1432
- kind: "save.failed",
1433
- sessionId: session.sessionId,
1434
- canonicalPathKey: session.canonicalPathKey,
1435
- revision: session.revision
1436
- });
1437
- return failure("authoring", startedAt, {
1438
- code: "save_partial_failure",
1439
- message: error instanceof Error ? error.message : String(error),
1440
- sessionId: session.sessionId,
1441
- canonicalPathKey: session.canonicalPathKey,
1442
- attemptedRevision: session.revision,
1443
- lastSavedRevision: session.lastSavedRevision,
1444
- committedPaths,
1445
- failedPaths,
1446
- diskMayBePartiallyUpdated: !ProjectWriteTransactionError.is(error) || error.diskMayBePartiallyUpdated,
1447
- ...ProjectWriteTransactionError.is(error) && error.recoveryPaths.length ? { recoveryPaths: error.recoveryPaths } : {}
1448
- }, toSessionSnapshot(session, this.context.capabilities), {
1449
- sessionId: session.sessionId,
1450
- revision: session.revision
1451
- });
1452
- }
1453
- }
1454
- async materializeSession(input) {
1455
- const captured = {
1456
- ...input,
1457
- storage: input.storage && { ...input.storage }
1458
- };
1459
- return this.sessionOperations.run(captured.sessionId, () => this.materializeSessionExclusive(captured));
1460
- }
1461
- async materializeSessionExclusive(input) {
1462
- const startedAt = Date.now();
1463
- const session = this.context.sessions.get(input.sessionId);
1464
- if (!session || session.closed) return failure("authoring", startedAt, createSessionNotFoundError(input.sessionId));
1465
- if (input.expectedRevision !== void 0 && input.expectedRevision !== session.revision) return failure("authoring", startedAt, createStaleWriteError(session, input.expectedRevision), toSessionSnapshot(session, this.context.capabilities), {
1466
- sessionId: session.sessionId,
1467
- revision: session.revision
1468
- });
1469
- const storageTarget = input.storage ? storageCanonicalTarget(input.storage) : null;
1470
- const fileSystem = storageTarget?.fileSystem ?? input.fileSystem ?? session.fileSystem;
1471
- if (!fileSystem) return failure("authoring", startedAt, createCapabilityUnavailableError$1("materializeSession requires an injected BackendFileSystem adapter."), toSessionSnapshot(session, this.context.capabilities), {
1472
- sessionId: session.sessionId,
1473
- revision: session.revision
1474
- });
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
- });
1486
- const targetViolation = await validateSaveTarget(fileSystem, fairyPath, input.targetPath);
1487
- if (targetViolation) return failure("authoring", startedAt, targetViolation, toSessionSnapshot(session, this.context.capabilities), {
1488
- sessionId: session.sessionId,
1489
- revision: session.revision
1490
- });
1491
- if (session.uamFidelity === "unsupported") return failure("authoring", startedAt, createUamFidelityUnsupportedError(session), toSessionSnapshot(session, this.context.capabilities), {
1492
- sessionId: session.sessionId,
1493
- revision: session.revision
1494
- });
1495
- const diagnostics = validationDiagnostics(session.project);
1496
- if (diagnostics.length > 0) return failure("authoring", startedAt, {
1497
- code: "materialize_validation_failed",
1498
- message: `UAM materialize validation failed with ${diagnostics.length} issue(s).`,
1499
- sessionId: session.sessionId,
1500
- canonicalPathKey: session.canonicalPathKey,
1501
- issueCount: diagnostics.length,
1502
- diagnostics
1503
- }, toSessionSnapshot(session, this.context.capabilities), {
1504
- sessionId: session.sessionId,
1505
- revision: session.revision,
1506
- diagnostics
1507
- });
1508
- let document;
1509
- try {
1510
- document = materializeUamProject(session.project);
1511
- } catch (error) {
1512
- const diagnosticsFromError = [{
1513
- code: "materialize_validation_failed",
1514
- message: error instanceof Error ? error.message : String(error),
1515
- severity: "error",
1516
- operationKind: "materializeSession"
1517
- }];
1518
- return failure("authoring", startedAt, {
1519
- code: "materialize_validation_failed",
1520
- message: error instanceof Error ? error.message : String(error),
1521
- sessionId: session.sessionId,
1522
- canonicalPathKey: session.canonicalPathKey,
1523
- issueCount: diagnosticsFromError.length,
1524
- diagnostics: diagnosticsFromError
1525
- }, toSessionSnapshot(session, this.context.capabilities), {
1526
- sessionId: session.sessionId,
1527
- revision: session.revision,
1528
- diagnostics: diagnosticsFromError
1529
- });
1530
- }
1531
- const writtenPaths = [];
1532
- const failedPaths = [];
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
- });
1539
- this.eventService.emit({
1540
- kind: "save.started",
1541
- sessionId: session.sessionId,
1542
- canonicalPathKey: storageTarget?.canonicalPathKey ?? session.canonicalPathKey,
1543
- revision: session.revision
1544
- });
1545
- try {
1546
- const isSessionStorageTarget = fileSystem === session.fileSystem && fairyPath === session.fairyPath;
1547
- await writeSessionProject({
1548
- fileSystem,
1549
- document,
1550
- fairyPath,
1551
- staleSourceFiles: isSessionStorageTarget ? [...session.pendingStaleSourceFiles.values()] : [],
1552
- staleResourceFolders: isSessionStorageTarget ? [...session.pendingStaleResourceFolders.values()] : [],
1553
- staleBranchDirectories: isSessionStorageTarget ? [...session.pendingStaleBranchDirectories.values()] : [],
1554
- writtenPaths,
1555
- failedPaths
122
+ const metadata = parseLockMetadata(await retryLockIo(() => fs.readFile(path.join(directory, name), "utf8")));
123
+ const ticketFile = path.join(directory, `.ticket-${name}`);
124
+ const ticket = await retryLockIo(() => fs.readFile(ticketFile, "utf8")).then(Number, (error) => {
125
+ if (error.code === "ENOENT") return 0;
126
+ throw error;
1556
127
  });
1557
- if (isSessionStorageTarget) {
1558
- session.pendingStaleSourceFiles.clear();
1559
- session.pendingStaleResourceFolders.clear();
1560
- session.pendingStaleBranchDirectories.clear();
128
+ if (!metadata || !Number.isSafeInteger(ticket) || ticket < 0) throw new Error("Invalid lock coordination record.");
129
+ if (!await isProcessAlive(metadata)) {
130
+ await retryLockIo(() => fs.unlink(path.join(directory, name))).catch(() => void 0);
131
+ await retryLockIo(() => fs.unlink(ticketFile)).catch(() => void 0);
132
+ return null;
1561
133
  }
1562
- if (storageTarget && !isSessionStorageTarget) {
1563
- session.pendingStaleSourceFiles.clear();
1564
- session.pendingStaleResourceFolders.clear();
1565
- session.pendingStaleBranchDirectories.clear();
1566
- }
1567
- if (isSessionStorageTarget || storageTarget) commitUamProjectSourcePaths(session.project);
1568
- reservation?.commit(session);
1569
- this.finishSuccessfulSave(session);
1570
- return success("authoring", startedAt, toMaterializeSnapshot(session, this.context.capabilities, {
1571
- reason: input.reason,
1572
- writtenPaths,
1573
- skippedPaths,
1574
- diagnostics: []
1575
- }), {
1576
- sessionId: session.sessionId,
1577
- revision: session.revision
1578
- });
134
+ return {
135
+ ...metadata,
136
+ ticket
137
+ };
1579
138
  } catch (error) {
1580
- const diagnosticsFromError = [{
1581
- code: "write_failed",
1582
- message: error instanceof Error ? error.message : String(error),
1583
- severity: "error",
1584
- path: failedPaths[0],
1585
- operationKind: "materializeSession"
1586
- }];
1587
- this.cacheService.invalidateSession(session);
1588
- this.eventService.emit({
1589
- kind: "save.failed",
1590
- sessionId: session.sessionId,
1591
- canonicalPathKey: session.canonicalPathKey,
1592
- revision: session.revision,
1593
- diagnostics: diagnosticsFromError
1594
- });
1595
- return failure("authoring", startedAt, {
1596
- code: "write_failed",
1597
- message: error instanceof Error ? error.message : String(error),
1598
- sessionId: session.sessionId,
1599
- canonicalPathKey: session.canonicalPathKey,
1600
- attemptedRevision: session.revision,
1601
- lastSavedRevision: session.lastSavedRevision,
1602
- writtenPaths,
1603
- failedPaths,
1604
- skippedPaths,
1605
- diagnostics: diagnosticsFromError,
1606
- diskMayBePartiallyUpdated: !ProjectWriteTransactionError.is(error) || error.diskMayBePartiallyUpdated,
1607
- ...ProjectWriteTransactionError.is(error) && error.recoveryPaths.length ? { recoveryPaths: error.recoveryPaths } : {}
1608
- }, toSessionSnapshot(session, this.context.capabilities), {
1609
- sessionId: session.sessionId,
1610
- revision: session.revision,
1611
- diagnostics: diagnosticsFromError
1612
- });
1613
- } finally {
1614
- reservation?.release();
1615
- }
1616
- }
1617
- };
1618
- //#endregion
1619
- //#region src/services/cache-service.ts
1620
- function createCacheEntry(session, valid) {
1621
- return {
1622
- canonicalPathKey: session.canonicalPathKey,
1623
- sessionId: session.sessionId,
1624
- revision: session.revision,
1625
- lastSavedRevision: session.lastSavedRevision,
1626
- dirty: session.dirty,
1627
- valid,
1628
- indexedAt: (/* @__PURE__ */ new Date()).toISOString(),
1629
- summary: {
1630
- packageCount: session.project.packages.length,
1631
- resourceCount: session.project.packages.reduce((total, pkg) => total + pkg.resources.length, 0),
1632
- diagnostics: []
1633
- }
1634
- };
1635
- }
1636
- var CacheService = class {
1637
- cacheBySession = /* @__PURE__ */ new Map();
1638
- constructor(getSession, events) {
1639
- this.getSession = getSession;
1640
- this.events = events;
1641
- }
1642
- getCacheSnapshot(input) {
1643
- const startedAt = Date.now();
1644
- const session = this.getSession(input.sessionId);
1645
- if (!session || session.closed) return failure("read", startedAt, createSessionNotFoundError(input.sessionId));
1646
- const entry = this.cacheBySession.get(input.sessionId);
1647
- return success("read", startedAt, {
1648
- cacheRevision: entry?.revision ?? session.revision,
1649
- entries: entry ? [structuredClone(entry)] : []
1650
- }, {
1651
- sessionId: session.sessionId,
1652
- revision: session.revision
1653
- });
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
- }
1676
- refreshSession(session) {
1677
- const entry = createCacheEntry(session, true);
1678
- this.cacheBySession.set(session.sessionId, entry);
1679
- return entry;
1680
- }
1681
- invalidateSession(session) {
1682
- const entry = createCacheEntry(session, false);
1683
- this.cacheBySession.set(session.sessionId, entry);
1684
- return entry;
1685
- }
1686
- removeSession(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
- }
1763
- }
1764
- };
1765
- //#endregion
1766
- //#region src/services/event-service.ts
1767
- const DEFAULT_EVENT_RETENTION_LIMIT = 1e3;
1768
- var EventService = class {
1769
- eventsBySession = /* @__PURE__ */ new Map();
1770
- sequence = 0;
1771
- constructor(getSession) {
1772
- this.getSession = getSession;
1773
- }
1774
- emit(event) {
1775
- const emitted = {
1776
- ...event,
1777
- sequence: ++this.sequence,
1778
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1779
- diagnostics: (event.diagnostics ?? []).map((entry) => enrichBackendDiagnostic(entry, event.sessionId))
1780
- };
1781
- const sessionId = event.sessionId;
1782
- if (!sessionId) return emitted;
1783
- const events = this.eventsBySession.get(sessionId) ?? [];
1784
- events.push(emitted);
1785
- while (events.length > DEFAULT_EVENT_RETENTION_LIMIT) events.shift();
1786
- this.eventsBySession.set(sessionId, events);
1787
- return emitted;
1788
- }
1789
- getEvents(input) {
1790
- const startedAt = Date.now();
1791
- const session = this.getSession(input.sessionId);
1792
- if (!session || session.closed) return failure("runtime", startedAt, createSessionNotFoundError(input.sessionId));
1793
- const events = this.eventsBySession.get(input.sessionId) ?? [];
1794
- const oldestSequence = events[0]?.sequence ?? (events.length === 0 ? 1 : 0);
1795
- const currentSequence = events.at(-1)?.sequence ?? 0;
1796
- const after = input.after === void 0 ? 0 : Number(input.after);
1797
- if (!Number.isInteger(after) || after < 0) return failure("runtime", startedAt, {
1798
- code: "event_cursor_invalid",
1799
- message: `Invalid event cursor: ${input.after}`,
1800
- sessionId: input.sessionId,
1801
- after: String(input.after)
1802
- });
1803
- if (events.length > 0 && after !== 0 && after < oldestSequence - 1) return failure("runtime", startedAt, {
1804
- code: "event_cursor_invalid",
1805
- message: `Event cursor has expired: ${after}`,
1806
- sessionId: input.sessionId,
1807
- after: String(input.after)
1808
- });
1809
- if (after > currentSequence) return failure("runtime", startedAt, {
1810
- code: "event_cursor_invalid",
1811
- message: `Unknown event cursor: ${after}`,
1812
- sessionId: input.sessionId,
1813
- after: String(input.after)
1814
- });
1815
- const filtered = events.filter((event) => event.sequence > after);
1816
- const limit = input.limit === void 0 ? filtered.length : Math.max(0, input.limit);
1817
- return success("runtime", startedAt, {
1818
- events: filtered.slice(0, limit).map((event) => structuredClone(event)),
1819
- oldestSequence,
1820
- currentSequence,
1821
- cursorExpired: false
1822
- }, {
1823
- sessionId: session.sessionId,
1824
- revision: session.revision
1825
- });
1826
- }
1827
- removeSession(sessionId) {
1828
- this.eventsBySession.delete(sessionId);
1829
- }
1830
- };
1831
- //#endregion
1832
- //#region src/services/read-service.ts
1833
- /** Bound traversal before serialization or cloning, including non-JSON values on a malformed native input. */
1834
- function queryResponseProblem(value, limits = BACKEND_ENTITY_QUERY_LIMITS) {
1835
- const pending = [{
1836
- value,
1837
- depth: 0
1838
- }];
1839
- let nodes = 0;
1840
- let stringUnits = 0;
1841
- while (pending.length) {
1842
- const { value, depth } = pending.pop();
1843
- if (++nodes > limits.maxNodes || depth > limits.maxDepth) return "response_budget_exceeded";
1844
- if (typeof value === "string" && (stringUnits += value.length) > limits.maxBytes) return "response_budget_exceeded";
1845
- if (value === void 0 || value === null || typeof value === "string" || typeof value === "boolean") continue;
1846
- if (typeof value === "number") {
1847
- if (!Number.isFinite(value)) return "non_json_value";
1848
- continue;
1849
- }
1850
- if (typeof value !== "object" || !Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) return "non_json_value";
1851
- if (Array.isArray(value) && value.length + pending.length + nodes > limits.maxNodes) return "response_budget_exceeded";
1852
- const entries = Object.entries(value);
1853
- if (entries.length + pending.length + nodes > limits.maxNodes) return "response_budget_exceeded";
1854
- for (const [key, child] of entries) {
1855
- if (!Array.isArray(value) && (stringUnits += key.length) > limits.maxBytes) return "response_budget_exceeded";
1856
- pending.push({
1857
- value: child,
1858
- depth: depth + 1
1859
- });
139
+ if (error.code === "ENOENT") return null;
140
+ throw error;
1860
141
  }
1861
- }
1862
- if (new TextEncoder().encode(JSON.stringify(value)).byteLength > limits.maxBytes) return "response_budget_exceeded";
1863
- }
1864
- function readFailure(startedAt, sessionId, reason, revision) {
1865
- return failure("read", startedAt, {
1866
- code: "session_read_failed",
1867
- sessionId,
1868
- reason,
1869
- message: `Session read failed: ${reason}.`
1870
- }, void 0, {
1871
- sessionId,
1872
- revision
1873
- });
1874
- }
1875
- function toProjectOutline(session) {
1876
- const project = session.project;
1877
- return {
1878
- sessionId: session.sessionId,
1879
- revision: session.revision,
1880
- projectId: project.projectId,
1881
- projectType: project.projectType,
1882
- version: project.version,
1883
- branches: [...project.branches],
1884
- packages: project.packages.map((pkg) => ({
1885
- id: pkg.id,
1886
- name: pkg.name,
1887
- branchNames: [...pkg.branchNames],
1888
- folders: pkg.folders.map((folder) => ({
1889
- branch: folder.branch,
1890
- path: folder.path
1891
- })),
1892
- resources: pkg.resources.map((resource) => ({
1893
- id: resource.id,
1894
- name: resource.name,
1895
- path: resource.path,
1896
- kind: resource.kind,
1897
- branch: resource.branch,
1898
- ...resource.kind === "component" ? { component: {
1899
- displayList: resource.component.displayList.map((node) => ({
1900
- id: node.id,
1901
- name: node.name,
1902
- kind: node.kind
1903
- })),
1904
- controllers: resource.component.controllers.map((controller) => ({
1905
- name: controller.name,
1906
- pages: controller.pages.map((page) => ({
1907
- id: page.id,
1908
- name: page.name
1909
- }))
1910
- })),
1911
- transitions: resource.component.transitions.map((transition) => ({ name: transition.name }))
1912
- } } : {}
1913
- }))
1914
- }))
1915
142
  };
1916
- }
1917
- var ReadService = class {
1918
- constructor(getSessionState, capabilities) {
1919
- this.getSessionState = getSessionState;
1920
- this.capabilities = capabilities;
1921
- }
1922
- getCapabilities() {
1923
- return success("read", Date.now(), cloneReadData(this.capabilities));
1924
- }
1925
- getSession(input) {
1926
- const startedAt = Date.now();
1927
- const session = this.getSessionState(input.sessionId);
1928
- if (!session || session.closed) return failure("read", startedAt, createSessionNotFoundError(input.sessionId));
1929
- return success("read", startedAt, toSessionSnapshot(session, this.capabilities), {
1930
- sessionId: session.sessionId,
1931
- revision: session.revision
1932
- });
1933
- }
1934
- getProjectOutline(input) {
1935
- const startedAt = Date.now();
1936
- const session = this.getSessionState(input.sessionId);
1937
- if (!session || session.closed) return failure("read", startedAt, createSessionNotFoundError(input.sessionId));
1938
- return success("read", startedAt, toProjectOutline(session), {
1939
- sessionId: session.sessionId,
1940
- revision: session.revision
1941
- });
1942
- }
1943
- queryEntity(input) {
1944
- const startedAt = Date.now();
1945
- const session = this.getSessionState(input.sessionId);
1946
- if (!session || session.closed) return failure("read", startedAt, createSessionNotFoundError(input.sessionId));
1947
- const meta = {
1948
- sessionId: session.sessionId,
1949
- revision: session.revision
1950
- };
1951
- const reject = (reason) => failure("read", startedAt, {
1952
- code: "entity_query_failed",
1953
- sessionId: session.sessionId,
1954
- reason,
1955
- message: `Entity query failed: ${reason}.`
1956
- }, void 0, meta);
1957
- const target = input.target;
1958
- if (!target || typeof target !== "object" || Array.isArray(target) || Object.keys(target).some((key) => key !== "kind" && key !== "selector")) return reject("invalid_query");
1959
- const respond = (entity) => {
1960
- const data = {
1961
- ...meta,
1962
- target,
1963
- entity
1964
- };
1965
- const problem = queryResponseProblem(data);
1966
- return problem ? reject(problem) : success("read", startedAt, cloneReadData(data), meta);
1967
- };
1968
- if (target.kind === "project") {
1969
- if (Object.hasOwn(target, "selector")) return reject("invalid_query");
1970
- const { projectId, settings } = session.project;
1971
- return respond({
1972
- kind: "project",
1973
- properties: {
1974
- projectId,
1975
- settings
1976
- }
1977
- });
1978
- }
1979
- const keys = target.kind === "package" ? ["packageId"] : target.kind === "resource" ? ["packageId", "resourceId"] : target.kind === "component" ? ["packageId", "componentResourceId"] : target.kind === "displayNode" ? [
1980
- "packageId",
1981
- "componentResourceId",
1982
- "displayNodeId"
1983
- ] : target.kind === "controller" ? [
1984
- "packageId",
1985
- "componentResourceId",
1986
- "controllerName"
1987
- ] : target.kind === "transition" ? [
1988
- "packageId",
1989
- "componentResourceId",
1990
- "transitionName"
1991
- ] : [];
1992
- const selector = target.selector;
1993
- 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");
1994
- const packages = session.project.packages.filter((pkg) => pkg.id === selector.packageId);
1995
- if (packages.length !== 1) return reject(packages.length ? "ambiguous" : "not_found");
1996
- if (target.kind === "package") {
1997
- const { id, name, compressPNG, jpegQuality, publish } = packages[0];
1998
- return respond({
1999
- kind: "package",
2000
- properties: {
2001
- id,
2002
- name,
2003
- settings: {
2004
- compressPNG,
2005
- jpegQuality,
2006
- publish
2007
- }
143
+ try {
144
+ await publish();
145
+ let maximum = 0;
146
+ for (const name of await fs.readdir(directory)) {
147
+ if (name.startsWith(".") || name === token) continue;
148
+ maximum = Math.max(maximum, (await readContender(name))?.ticket ?? 0);
149
+ }
150
+ owner.ticket = maximum + 1;
151
+ await retryLockIo(() => fs.writeFile(ticketTemporary, String(owner.ticket), { flag: "wx" }));
152
+ await retryLockIo(() => fs.link(ticketTemporary, ticketPath));
153
+ await retryLockIo(() => fs.unlink(ticketTemporary));
154
+ const deadline = Date.now() + 15e3;
155
+ for (;;) {
156
+ let waiting = false;
157
+ for (const name of await fs.readdir(directory)) {
158
+ if (name.startsWith(".") || name === token) continue;
159
+ const other = await readContender(name);
160
+ if (other && (other.ticket === 0 || other.ticket < owner.ticket || other.ticket === owner.ticket && name < token)) {
161
+ waiting = true;
162
+ break;
2008
163
  }
2009
- });
2010
- }
2011
- const resources = packages[0].resources.filter((resource) => resource.id === (target.kind === "resource" ? selector.resourceId : selector.componentResourceId));
2012
- if (resources.length !== 1) return reject(resources.length ? "ambiguous" : "not_found");
2013
- const resource = resources[0];
2014
- let entity;
2015
- if (target.kind === "resource") {
2016
- const record = resource;
2017
- entity = {
2018
- kind: "resource",
2019
- properties: Object.fromEntries(BACKEND_RESOURCE_QUERY_FIELDS.filter((key) => Object.hasOwn(record, key)).map((key) => [key, record[key]]))
2020
- };
2021
- } else {
2022
- if (resource.kind !== "component") return reject("not_found");
2023
- if (target.kind === "component") {
2024
- const { size, properties, customData } = resource.component;
2025
- entity = {
2026
- kind: "component",
2027
- properties: {
2028
- size,
2029
- properties,
2030
- customData
2031
- }
2032
- };
2033
- } else if (target.kind === "controller") {
2034
- const controllers = resource.component.controllers.filter((controller) => controller.name === selector.controllerName);
2035
- if (controllers.length !== 1) return reject(controllers.length ? "ambiguous" : "not_found");
2036
- entity = {
2037
- kind: "controller",
2038
- properties: controllers[0]
2039
- };
2040
- } else if (target.kind === "transition") {
2041
- const transitions = resource.component.transitions.filter((transition) => transition.name === selector.transitionName);
2042
- if (transitions.length !== 1) return reject(transitions.length ? "ambiguous" : "not_found");
2043
- entity = {
2044
- kind: "transition",
2045
- properties: transitions[0]
2046
- };
2047
- } else {
2048
- const nodes = resource.component.displayList.filter((node) => node.id === selector.displayNodeId);
2049
- if (nodes.length !== 1) return reject(nodes.length ? "ambiguous" : "not_found");
2050
- entity = {
2051
- kind: "displayNode",
2052
- properties: nodes[0]
2053
- };
2054
164
  }
165
+ if (!waiting) return await action();
166
+ if (Date.now() >= deadline) throw Object.assign(/* @__PURE__ */ new Error("Lock coordination is busy."), { code: "EEXIST" });
167
+ await new Promise((resolve) => setTimeout(resolve, 10));
2055
168
  }
2056
- return respond(entity);
169
+ } finally {
170
+ await retryLockIo(() => fs.unlink(candidate)).catch(() => void 0);
171
+ await retryLockIo(() => fs.unlink(ticketPath)).catch(() => void 0);
172
+ await retryLockIo(() => fs.unlink(temporary)).catch(() => void 0);
173
+ await retryLockIo(() => fs.unlink(ticketTemporary)).catch(() => void 0);
2057
174
  }
2058
- resolveReadSession(input, startedAt) {
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");
2060
- const session = this.getSessionState(input.sessionId);
2061
- if (!session || session.closed) return failure("read", startedAt, createSessionNotFoundError(input.sessionId));
2062
- const meta = {
2063
- sessionId: session.sessionId,
2064
- revision: session.revision
2065
- };
2066
- if (input.expectedRevision !== void 0 && input.expectedRevision !== session.revision) return failure("read", startedAt, {
2067
- code: "stale_read",
2068
- sessionId: session.sessionId,
2069
- expectedRevision: input.expectedRevision,
2070
- actualRevision: session.revision,
2071
- message: "The session edit revision changed. Restart the model and resource read."
2072
- }, void 0, meta);
2073
- return success("read", startedAt, session, meta);
2074
- }
2075
- readSessionState(input) {
2076
- const startedAt = Date.now();
2077
- const resolved = this.resolveReadSession(input, startedAt);
2078
- if (!resolved.ok) return resolved;
2079
- const session = resolved.data;
2080
- const meta = {
2081
- sessionId: session.sessionId,
2082
- revision: session.revision
2083
- };
2084
- const data = {
2085
- ...meta,
2086
- dirty: session.dirty,
2087
- lastSavedRevision: session.lastSavedRevision,
2088
- uamFidelity: session.uamFidelity,
2089
- readComplete: session.readComplete,
2090
- readDiagnostics: session.readDiagnostics,
2091
- project: {
2092
- ...session.project,
2093
- packages: session.project.packages.map((pkg) => ({
2094
- ...pkg,
2095
- resources: pkg.resources.map((resource) => {
2096
- if (resource.kind === "component") return resource;
2097
- const { sourceBytes: _sourceBytes, ...model } = resource;
2098
- return model;
2099
- })
2100
- }))
2101
- }
2102
- };
2103
- const problem = queryResponseProblem(data, BACKEND_SESSION_READ_LIMITS.model);
2104
- return problem ? readFailure(startedAt, session.sessionId, problem, session.revision) : success("read", startedAt, cloneReadData(data), meta);
175
+ }
176
+ /** A creator writes metadata right after creating the lock; an unwritten lock this old was left by a crash. */
177
+ const UNWRITTEN_LOCK_STALE_MS = 3e4;
178
+ function isUnwrittenLock(content) {
179
+ if (!content.trim()) return true;
180
+ try {
181
+ JSON.parse(content);
182
+ return false;
183
+ } catch {
184
+ return true;
2105
185
  }
2106
- readResourceBytes(input) {
2107
- const startedAt = Date.now();
2108
- const resolved = this.resolveReadSession(input, startedAt);
2109
- if (!resolved.ok) return resolved;
2110
- const session = resolved.data;
2111
- const reject = (reason) => readFailure(startedAt, session.sessionId, reason, session.revision);
2112
- const selector = input.selector;
2113
- if (input.expectedRevision === void 0 || !selector || typeof selector !== "object" || Array.isArray(selector) || Object.keys(selector).length !== 2 || ["packageId", "resourceId"].some((key) => !Object.hasOwn(selector, key)) || [selector.packageId, selector.resourceId].some((value) => typeof value !== "string" || !value.length || value.length > 256)) return reject("invalid_query");
2114
- const packages = session.project.packages.filter((pkg) => pkg.id === selector.packageId);
2115
- if (packages.length !== 1) return reject(packages.length ? "ambiguous" : "not_found");
2116
- const resources = packages[0].resources.filter((resource) => resource.id === selector.resourceId);
2117
- if (resources.length !== 1) return reject(resources.length ? "ambiguous" : "not_found");
2118
- const resource = resources[0];
2119
- if (resource.kind === "component") return reject("unsupported_resource");
2120
- if (!(resource.sourceBytes instanceof Uint8Array)) return reject("bytes_unavailable");
2121
- if (resource.sourceBytes.byteLength > BACKEND_SESSION_READ_LIMITS.resourceBytes) return reject("response_budget_exceeded");
2122
- const meta = {
2123
- sessionId: session.sessionId,
2124
- revision: session.revision
186
+ }
187
+ async function readLockFile(filePath) {
188
+ try {
189
+ const [content, stat] = await Promise.all([fs.readFile(filePath, "utf-8"), fs.stat(filePath)]);
190
+ return {
191
+ content,
192
+ modifiedAt: stat.mtimeMs
2125
193
  };
2126
- return success("read", startedAt, {
2127
- ...meta,
2128
- selector: { ...selector },
2129
- sourceBytes: new Uint8Array(resource.sourceBytes)
2130
- }, meta);
2131
- }
2132
- validateSession(input) {
2133
- const startedAt = Date.now();
2134
- const session = this.getSessionState(input.sessionId);
2135
- if (!session || session.closed) return failure("read", startedAt, createSessionNotFoundError(input.sessionId));
2136
- const report = validateProject(cloneReadData(session.project), {
2137
- readDiagnostics: cloneReadData(session.readDiagnostics),
2138
- complete: session.readComplete,
2139
- validateSources: true
2140
- });
2141
- return success("read", startedAt, report, {
2142
- sessionId: session.sessionId,
2143
- revision: session.revision,
2144
- diagnostics: report.diagnostics.map(({ code, message, severity, path }) => ({
2145
- code,
2146
- message,
2147
- severity,
2148
- path,
2149
- owner: "core.validation"
2150
- }))
2151
- });
194
+ } catch {
195
+ return null;
2152
196
  }
2153
- };
2154
- //#endregion
2155
- //#region src/services/runtime-service.ts
2156
- function randomId() {
2157
- return crypto.randomUUID();
2158
- }
2159
- function createCapabilityUnavailableError(capability) {
2160
- const artifactCapability = capability === "artifact.publish" || capability === "artifact.restore";
2161
- return {
2162
- code: "capability_unavailable",
2163
- message: artifactCapability ? `${capability} requires the Node bridge boundary exposed by @openfairygui/backend/node.` : `${capability} requires an injected BackendFileSystem adapter.`,
2164
- capability,
2165
- requiredAdapter: capability === "fileSystem" ? "BackendFileSystem" : void 0,
2166
- requiredHost: artifactCapability ? "node" : void 0,
2167
- bridgeBoundary: artifactCapability ? "external-bridge" : void 0
2168
- };
2169
197
  }
2170
- function createProjectReaderFileSystem(fileSystem, projectRoot) {
2171
- const contained = async (filePath, operation) => {
2172
- await assertProjectPathContained(fileSystem, projectRoot, filePath);
2173
- return operation();
2174
- };
2175
- return {
2176
- stat: (path) => contained(path, () => fileSystem.stat(path)),
2177
- readFile(filePath) {
2178
- return contained(filePath, () => fileSystem.readFile(filePath));
2179
- },
2180
- readFileRaw(filePath) {
2181
- return contained(filePath, () => fileSystem.readFileRaw(filePath));
2182
- },
2183
- writeFile(filePath, content) {
2184
- return contained(filePath, () => fileSystem.writeFile(filePath, content));
2185
- },
2186
- writeFileRaw(filePath, data) {
2187
- return contained(filePath, () => fileSystem.writeFileRaw(filePath, data));
2188
- },
2189
- async mkdir(dirPath) {
2190
- await contained(dirPath, () => fileSystem.mkdir(dirPath, { recursive: true }));
2191
- },
2192
- readdir(dirPath) {
2193
- return contained(dirPath, () => fileSystem.readdir(dirPath));
2194
- },
2195
- async exists(filePath) {
2196
- try {
2197
- await contained(filePath, () => fileSystem.stat(filePath));
2198
- return true;
2199
- } catch {
2200
- return false;
2201
- }
2202
- },
2203
- join(...paths) {
2204
- return fileSystem.join(...paths);
2205
- },
2206
- dirname(filePath) {
2207
- return fileSystem.dirname(filePath);
2208
- }
2209
- };
2210
- }
2211
- async function hasFullUamFidelity(document, project) {
2212
- const sourceFiles = /* @__PURE__ */ new Map();
2213
- const materializedFiles = /* @__PURE__ */ new Map();
2214
- const sourceDirectories = /* @__PURE__ */ new Set();
2215
- const materializedDirectories = /* @__PURE__ */ new Set();
198
+ async function recoverStaleLock(filePath) {
199
+ const before = await readLockFile(filePath);
200
+ if (!before) return false;
201
+ const metadata = parseLockMetadata(before.content);
202
+ if (!(metadata ? !await isProcessAlive(metadata) : isUnwrittenLock(before.content) && Date.now() - before.modifiedAt > UNWRITTEN_LOCK_STALE_MS)) return false;
203
+ const claimed = `${filePath}.stale-${randomUUID()}`;
2216
204
  try {
2217
- await Promise.all([new ProjectWriter(createCaptureFileSystem(sourceFiles, sourceDirectories)).write(document, "Project.fairy"), new ProjectWriter(createCaptureFileSystem(materializedFiles, materializedDirectories)).write(materializeUamProject(project), "Project.fairy")]);
205
+ await retryLockIo(() => fs.rename(filePath, claimed));
2218
206
  } catch {
2219
207
  return false;
2220
208
  }
2221
- return capturedFilesEqual(sourceFiles, materializedFiles) && capturedDirectoriesEqual(sourceDirectories, materializedDirectories);
2222
- }
2223
- var RuntimeService = class {
2224
- constructor(context, cacheService, eventService) {
2225
- this.context = context;
2226
- this.cacheService = cacheService;
2227
- this.eventService = eventService;
209
+ if ((await readLockFile(claimed))?.content === before.content) {
210
+ if (metadata) await retryLockIo(() => fs.unlink(path.join(`${filePath}.coordination`, `.host-${metadata.token}`))).catch(() => void 0);
211
+ await fs.unlink(claimed).catch(() => void 0);
212
+ return true;
2228
213
  }
2229
- async openSession(input) {
2230
- const startedAt = Date.now();
2231
- if (!this.context.fileSystem) return failure("runtime", startedAt, createCapabilityUnavailableError("fileSystem"));
2232
- const fileSystem = this.context.fileSystem;
2233
- if (this.context.allowedProjectRoots?.length) {
2234
- let allowed = false;
2235
- for (const root of this.context.allowedProjectRoots) try {
2236
- await assertProjectPathContained(fileSystem, root, input.projectPath);
2237
- allowed = true;
2238
- break;
2239
- } catch (error) {
2240
- if (error.code !== "EACCES") throw error;
214
+ await fs.link(claimed, filePath).catch(() => void 0);
215
+ await fs.unlink(claimed).catch(() => void 0);
216
+ return false;
217
+ }
218
+ async function isHeldByLiveForeignOwner(filePath, token) {
219
+ const current = await readLockFile(filePath);
220
+ const metadata = current ? parseLockMetadata(current.content) : null;
221
+ return !!metadata && metadata.token !== token && await isProcessAlive(metadata);
222
+ }
223
+ async function acquireNodeSessionLock(filePath) {
224
+ const identity = await getOwnIdentity();
225
+ const owner = {
226
+ schemaVersion: 2,
227
+ pid: process.pid,
228
+ processStartTime: PROCESS_START_TIME,
229
+ processIdentity: identity,
230
+ hostname: os.hostname(),
231
+ token: randomUUID()
232
+ };
233
+ try {
234
+ await coordinateLock(filePath, async () => {
235
+ const prepared = `${filePath}.owner-${owner.token}`;
236
+ await retryLockIo(() => fs.writeFile(prepared, JSON.stringify(owner), { flag: "wx" }));
237
+ try {
238
+ try {
239
+ await retryLockIo(() => fs.link(prepared, filePath));
240
+ } catch (error) {
241
+ if (error.code !== "EEXIST" || !await recoverStaleLock(filePath)) throw error;
242
+ await retryLockIo(() => fs.link(prepared, filePath));
243
+ }
244
+ } finally {
245
+ await retryLockIo(() => fs.unlink(prepared));
2241
246
  }
2242
- if (!allowed) return failure("runtime", startedAt, {
2243
- code: "project_root_not_allowed",
2244
- message: "Project path is outside the configured allowed roots.",
2245
- projectPath: input.projectPath
2246
- });
2247
- }
2248
- const { fairyPath, canonicalProjectPath, canonicalPathKey } = await resolveCanonicalProjectRoot(fileSystem, input.projectPath);
2249
- await fileSystem.validateProjectRoot?.(canonicalProjectPath);
2250
- const lockFilePath = fileSystem.getSessionLockPath?.(canonicalProjectPath) ?? fileSystem.join(canonicalProjectPath, ".openfairygui.backend.lock");
2251
- const sessionId = randomId();
2252
- const reservation = this.context.sessions.reserve(sessionId, {
2253
- canonicalPathKey,
2254
- canonicalProjectPath,
2255
- lockFilePath
2256
- });
2257
- if ("code" in reservation) return failure("runtime", startedAt, reservation);
2258
- let sessionLock = null;
2259
- try {
2260
- sessionLock = await fileSystem.acquireSessionLock(lockFilePath);
2261
- await sessionLock.writeMetadata(JSON.stringify(this.context.host?.lockMetadata?.({
2262
- canonicalPathKey,
2263
- canonicalProjectPath,
2264
- lockFilePath
2265
- }) ?? {
2266
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
2267
- canonicalPathKey
2268
- }));
2269
- const read = await new ProjectReader(createProjectReaderFileSystem(fileSystem, canonicalProjectPath)).readDetailed(fairyPath, { hydrateResourceBytes: true });
2270
- if (!read.document) throw new Error(read.diagnostics[0]?.message ?? `Unable to read project: ${fairyPath}`);
2271
- const document = read.document;
2272
- const project = liftDocumentToUamProject(document);
2273
- const session = {
2274
- sessionId,
2275
- fairyPath,
2276
- canonicalProjectPath,
2277
- canonicalPathKey,
2278
- lockFilePath,
2279
- sessionLock,
2280
- fileSystem,
2281
- project,
2282
- readDiagnostics: read.diagnostics,
2283
- readComplete: read.complete,
2284
- uamFidelity: read.complete && await hasFullUamFidelity(document, project) ? "full" : "unsupported",
2285
- revision: 0,
2286
- lastSavedRevision: 0,
2287
- pendingStaleSourceFiles: /* @__PURE__ */ new Map(),
2288
- pendingStaleResourceFolders: /* @__PURE__ */ new Map(),
2289
- pendingStaleBranchDirectories: /* @__PURE__ */ new Map(),
2290
- dirty: false,
2291
- lockHeld: true,
2292
- closed: false
2293
- };
2294
- reservation.commit(session);
2295
- this.cacheService.refreshSession(session);
2296
- this.eventService.emit({
2297
- kind: "session.opened",
2298
- sessionId,
2299
- canonicalPathKey,
2300
- revision: session.revision
2301
- });
2302
- return success("runtime", startedAt, toSessionSnapshot(session, this.context.capabilities), {
2303
- sessionId: session.sessionId,
2304
- revision: session.revision
2305
- });
2306
- } catch (error) {
2307
- if (sessionLock) await sessionLock.release().catch(() => void 0);
2308
- if (typeof error === "object" && error !== null && "code" in error && error.code === "EEXIST") return failure("runtime", startedAt, {
2309
- code: "lock_conflict",
2310
- kind: "advisory_lock_conflict",
2311
- message: `Advisory lock already exists for project: ${canonicalProjectPath}`,
2312
- canonicalPathKey,
2313
- lockFilePath
2314
- });
2315
- if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOTSUP") return failure("runtime", startedAt, {
2316
- ...createCapabilityUnavailableError("fileSystem"),
2317
- message: error instanceof Error ? error.message : String(error)
2318
- });
2319
- throw error;
2320
- } finally {
2321
- reservation.release();
2322
- }
2323
- }
2324
- openProjectSession(input) {
2325
- const startedAt = Date.now();
2326
- const sessionId = input.sessionId ?? randomId();
2327
- if (this.context.sessions.has(sessionId)) return failure("runtime", startedAt, {
2328
- code: "session_id_conflict",
2329
- message: `Session id is already in use: ${sessionId}`,
2330
- sessionId
2331
- });
2332
- const storage = input.storage;
2333
- const memoryProjectPath = `memory://${sessionId}`;
2334
- const canonicalProjectPath = storage?.canonicalProjectPath ?? input.canonicalProjectPath ?? (storage ? storage.fileSystem.dirname(storage.fairyPath) || "." : memoryProjectPath);
2335
- const canonicalPathKey = storage?.canonicalPathKey ?? input.canonicalPathKey ?? (storage ? normalizeComparablePath(canonicalProjectPath) : canonicalProjectPath.toLowerCase());
2336
- const project = normalizeUamProject(input.project);
2337
- const reservation = this.context.sessions.reserve(sessionId, {
2338
- canonicalPathKey,
2339
- canonicalProjectPath
2340
247
  });
2341
- if ("code" in reservation) return failure("runtime", startedAt, reservation);
2342
- const session = {
2343
- sessionId,
2344
- fairyPath: storage?.fairyPath ?? canonicalProjectPath,
2345
- canonicalProjectPath,
2346
- canonicalPathKey,
2347
- lockFilePath: "",
2348
- sessionLock: null,
2349
- fileSystem: storage?.fileSystem,
2350
- project,
2351
- readDiagnostics: [],
2352
- readComplete: true,
2353
- uamFidelity: "full",
2354
- revision: 0,
2355
- lastSavedRevision: 0,
2356
- pendingStaleSourceFiles: /* @__PURE__ */ new Map(),
2357
- pendingStaleResourceFolders: /* @__PURE__ */ new Map(),
2358
- pendingStaleBranchDirectories: /* @__PURE__ */ new Map(),
2359
- dirty: false,
2360
- lockHeld: false,
2361
- closed: false
2362
- };
2363
- reservation.commit(session);
2364
- this.cacheService.refreshSession(session);
2365
- this.eventService.emit({
2366
- kind: "session.opened",
2367
- sessionId,
2368
- canonicalPathKey,
2369
- revision: session.revision
2370
- });
2371
- return success("runtime", startedAt, toSessionSnapshot(session, this.context.capabilities), {
2372
- sessionId: session.sessionId,
2373
- revision: session.revision
2374
- });
2375
- }
2376
- async closeSession(input) {
2377
- const startedAt = Date.now();
2378
- const session = this.context.sessions.get(input.sessionId);
2379
- if (!session || session.closed) return failure("runtime", startedAt, createSessionNotFoundError(input.sessionId));
2380
- this.eventService.emit({
2381
- kind: "session.closeRequested",
2382
- sessionId: session.sessionId,
2383
- canonicalPathKey: session.canonicalPathKey,
2384
- revision: session.revision
2385
- });
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
- }
2399
- session.sessionLock = null;
2400
- session.lockHeld = false;
2401
- session.closed = true;
2402
- this.context.sessions.remove(session);
2403
- this.cacheService.removeSession(session.sessionId);
2404
- this.eventService.emit({
2405
- kind: "session.closed",
2406
- sessionId: session.sessionId,
2407
- canonicalPathKey: session.canonicalPathKey,
2408
- revision: session.revision
2409
- });
2410
- this.eventService.removeSession(session.sessionId);
2411
- return success("runtime", startedAt, {
2412
- sessionId: session.sessionId,
2413
- closed: true
2414
- }, {
2415
- sessionId: session.sessionId,
2416
- revision: session.revision
248
+ } catch (error) {
249
+ if (isTransientWindowsLockError(error) && await isHeldByLiveForeignOwner(filePath, owner.token)) throw Object.assign(/* @__PURE__ */ new Error(`Session lock is held by another process: ${filePath}`), {
250
+ code: "EEXIST",
251
+ cause: error
2417
252
  });
253
+ throw error;
2418
254
  }
2419
- };
2420
- //#endregion
2421
- //#region src/services/artifact-service.ts
2422
- function createArtifactCapabilities() {
2423
- const bridge = {
2424
- available: false,
2425
- requiredHost: "node",
2426
- executionBoundary: "external-bridge",
2427
- bridgeEntrypoint: "@openfairygui/backend/node",
2428
- reason: "publish/restore require explicit Node-hosted filesystem and artifact execution."
2429
- };
2430
- return {
2431
- publish: false,
2432
- restore: false,
2433
- status: "bridge-required",
2434
- publishBridge: bridge,
2435
- restoreBridge: bridge
255
+ let released = false;
256
+ const hostMetadataPath = path.join(`${filePath}.coordination`, `.host-${owner.token}`);
257
+ const assertOwner = async () => {
258
+ const current = parseLockMetadata(await fs.readFile(filePath, "utf8"));
259
+ if (!current || current.token !== owner.token) throw new Error("Cannot release session lock: invalid or changed ownership metadata");
2436
260
  };
2437
- }
2438
- //#endregion
2439
- //#region src/runtime/capabilities.ts
2440
- const BACKEND_METHODS = [
2441
- "getCapabilities",
2442
- "openSession",
2443
- "openProjectSession",
2444
- "getSession",
2445
- "getProjectOutline",
2446
- "queryEntity",
2447
- "readSessionState",
2448
- "readResourceBytes",
2449
- "validateSession",
2450
- "preflightTransaction",
2451
- "applyTransaction",
2452
- "saveSession",
2453
- "materializeSession",
2454
- "closeSession",
2455
- "getEvents",
2456
- "getCacheSnapshot",
2457
- "refreshCache"
2458
- ];
2459
- const ARTIFACT_BRIDGE_CAPABILITY = {
2460
- available: false,
2461
- requiredHost: "node",
2462
- executionBoundary: "external-bridge",
2463
- bridgeEntrypoint: "@openfairygui/backend/node",
2464
- reason: "publish/restore require explicit Node-hosted filesystem and artifact execution."
2465
- };
2466
- function createCapabilities(atomicSave = false) {
2467
261
  return {
2468
- contractVersion: BACKEND_CONTRACT_VERSION,
2469
- capabilitySchemaVersion: 12,
2470
- transactionKernelOwner: "@openfairygui/core",
2471
- appSeamOwner: "@openfairygui/functions",
2472
- runtimeOwner: "@openfairygui/backend",
2473
- methods: BACKEND_METHODS,
2474
- read: {
2475
- capabilitySnapshot: true,
2476
- sessionSnapshot: true,
2477
- projectOutline: true,
2478
- entityQuery: {
2479
- kinds: [
2480
- "project",
2481
- "package",
2482
- "resource",
2483
- "component",
2484
- "displayNode",
2485
- "controller",
2486
- "transition"
2487
- ],
2488
- projection: "properties",
2489
- sourceBytes: false,
2490
- limits: BACKEND_ENTITY_QUERY_LIMITS
2491
- },
2492
- sessionState: {
2493
- sourceBytes: false,
2494
- limits: BACKEND_SESSION_READ_LIMITS.model
2495
- },
2496
- resourceBytes: {
2497
- expectedRevisionRequired: true,
2498
- hydration: false,
2499
- maxBytes: BACKEND_SESSION_READ_LIMITS.resourceBytes
2500
- },
2501
- projectValidation: true
2502
- },
2503
- authoring: {
2504
- preflightTransaction: {
2505
- mode: "execute-and-discard",
2506
- reservesRevision: false,
2507
- impact: "model-diff",
2508
- limits: BACKEND_TRANSACTION_PREVIEW_LIMITS
2509
- },
2510
- applyTransaction: true,
2511
- saveSession: true,
2512
- resourceKinds: [...UAM_SUPPORTED_MATERIALIZATION_SCOPE.resourceKinds],
2513
- nodeKinds: [...UAM_SUPPORTED_MATERIALIZATION_SCOPE.nodeKinds],
2514
- gearKinds: [...UAM_SUPPORTED_MATERIALIZATION_SCOPE.gearKinds],
2515
- transactionScope: {
2516
- resourceKinds: [...UAM_SUPPORTED_TRANSACTION_SCOPE.resourceKinds],
2517
- nodeKinds: [...UAM_SUPPORTED_TRANSACTION_SCOPE.nodeKinds],
2518
- gearKinds: [...UAM_SUPPORTED_TRANSACTION_SCOPE.gearKinds]
2519
- },
2520
- unsupported: ["artifact.publish", "artifact.restore"]
262
+ async writeMetadata(content) {
263
+ await coordinateLock(filePath, async () => {
264
+ await assertOwner();
265
+ let supplied = {};
266
+ try {
267
+ const value = JSON.parse(content);
268
+ if (value && typeof value === "object" && !Array.isArray(value)) supplied = value;
269
+ } catch {}
270
+ await fs.writeFile(hostMetadataPath, JSON.stringify(supplied));
271
+ });
2521
272
  },
2522
- artifact: createArtifactCapabilities(),
2523
- manifest: {
2524
- browserSafe: true,
2525
- rootEntrypoint: "@openfairygui/backend",
2526
- nodeEntrypoint: "@openfairygui/backend/node",
2527
- adapters: {
2528
- fileSystem: {
2529
- injected: true,
2530
- requiredFor: [
2531
- "openSession",
2532
- "saveSession",
2533
- "materializeSession"
2534
- ]
2535
- },
2536
- projectStorage: {
2537
- injected: true,
2538
- browserSafe: true,
2539
- requiredFor: [
2540
- "openProjectSession.writeback",
2541
- "saveSession",
2542
- "materializeSession"
2543
- ],
2544
- adapterFactory: "createBackendStorageFileSystem"
2545
- },
2546
- host: {
2547
- injected: true,
2548
- requiredFor: ["advisoryLockMetadata"]
273
+ async release() {
274
+ if (released) return;
275
+ await coordinateLock(filePath, async () => {
276
+ try {
277
+ await assertOwner();
278
+ await retryLockIo(() => fs.unlink(filePath));
279
+ } catch (error) {
280
+ if (error.code !== "ENOENT") throw error;
2549
281
  }
2550
- },
2551
- executionBoundaries: {
2552
- projectSession: "in-process-browser-safe",
2553
- fileBackedSession: "adapter-backed",
2554
- artifactPublish: ARTIFACT_BRIDGE_CAPABILITY,
2555
- artifactRestore: ARTIFACT_BRIDGE_CAPABILITY
2556
- },
2557
- diagnostics: {
2558
- stableCodes: true,
2559
- errorDiagnosticMirror: true,
2560
- recoveryGuides: "all-formal-codes",
2561
- automaticRepair: false
2562
- }
2563
- },
2564
- compatibilityPolicy: BACKEND_COMPATIBILITY_POLICY,
2565
- runtime: {
2566
- sessionRuntime: true,
2567
- advisoryLocking: true,
2568
- coordinatedSave: true,
2569
- atomicSave,
2570
- staleRevisionProtection: true,
2571
- pathPolicy: createRuntimePathPolicy(),
2572
- events: {
2573
- polling: true,
2574
- subscriptions: false,
2575
- retentionLimit: 1e3,
2576
- sequenceScope: "runtime"
2577
- },
2578
- cache: {
2579
- derivedReadOnly: true,
2580
- keyedBy: "sessionId",
2581
- refreshMode: "synchronous",
2582
- sourceOfTruth: false,
2583
- refreshMethod: "refreshCache"
2584
- }
282
+ await retryLockIo(() => fs.unlink(hostMetadataPath)).catch(() => void 0);
283
+ released = true;
284
+ });
2585
285
  }
2586
286
  };
2587
287
  }
2588
288
  //#endregion
2589
- //#region src/runtime.ts
2590
- var BackendRuntime = class {
2591
- fileSystem;
2592
- capabilities;
2593
- sessions = new SessionRegistry();
2594
- sessionOperations = new SessionOperationQueue();
2595
- context;
2596
- readService;
2597
- runtimeService;
2598
- authoringService;
2599
- persistenceService;
2600
- cacheService;
2601
- eventService;
2602
- constructor(options = {}) {
2603
- this.fileSystem = options.fileSystem;
2604
- this.capabilities = createCapabilities(Boolean(options.fileSystem?.runProjectWriteTransaction));
2605
- this.context = {
2606
- fileSystem: this.fileSystem,
2607
- host: options.host,
2608
- allowedProjectRoots: options.allowedProjectRoots,
2609
- capabilities: this.capabilities,
2610
- sessions: this.sessions
2611
- };
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);
2619
- }
2620
- getCapabilities() {
2621
- return this.readService.getCapabilities();
2622
- }
2623
- async openSession(input) {
2624
- const startedAt = Date.now();
2625
- try {
2626
- return await this.runtimeService.openSession(input);
2627
- } catch {
2628
- return failure("runtime", startedAt, {
2629
- code: "project_open_failed",
2630
- message: "Unable to open project.",
2631
- projectPath: input.projectPath
2632
- });
2633
- }
2634
- }
2635
- openProjectSession(input) {
2636
- return this.runtimeService.openProjectSession(input);
2637
- }
2638
- getSession(input) {
2639
- return this.readService.getSession(input);
2640
- }
2641
- getProjectOutline(input) {
2642
- return this.readService.getProjectOutline(input);
2643
- }
2644
- queryEntity(input) {
2645
- return this.readService.queryEntity(input);
2646
- }
2647
- readSessionState(input) {
2648
- return this.readService.readSessionState(input);
2649
- }
2650
- readResourceBytes(input) {
2651
- return this.readService.readResourceBytes(input);
2652
- }
2653
- validateSession(input) {
2654
- return this.readService.validateSession(input);
2655
- }
2656
- async preflightTransaction(input) {
2657
- return this.authoringService.preflightTransaction(input);
2658
- }
2659
- async applyTransaction(input) {
2660
- return this.authoringService.applyTransaction(input);
2661
- }
2662
- async saveSession(input) {
2663
- return this.persistenceService.saveSession(input);
2664
- }
2665
- async materializeSession(input) {
2666
- return this.persistenceService.materializeSession(input);
2667
- }
2668
- async closeSession(input) {
2669
- const captured = { ...input };
2670
- return this.sessionOperations.run(captured.sessionId, () => this.runtimeService.closeSession(captured));
2671
- }
2672
- getEvents(input) {
2673
- return this.eventService.getEvents(input);
2674
- }
2675
- getCacheSnapshot(input) {
2676
- return this.cacheService.getCacheSnapshot(input);
2677
- }
2678
- refreshCache(input) {
2679
- return this.cacheService.refreshCache(input);
2680
- }
2681
- };
2682
- //#endregion
2683
289
  //#region src/node.ts
2684
- const PROCESS_START_TIME = Math.trunc(Date.now() - process.uptime() * 1e3);
2685
- function parseLockMetadata(content) {
2686
- try {
2687
- const value = JSON.parse(content);
2688
- if (value.schemaVersion !== 1 || !Number.isSafeInteger(value.pid) || !Number.isFinite(value.processStartTime) || typeof value.hostname !== "string" || typeof value.token !== "string") return null;
2689
- return value;
2690
- } catch {
2691
- return null;
2692
- }
2693
- }
2694
- function isProcessAlive(metadata) {
2695
- if (metadata.hostname !== os.hostname()) return true;
2696
- if (metadata.pid === process.pid) return Math.abs(metadata.processStartTime - PROCESS_START_TIME) < 1e3;
2697
- try {
2698
- process.kill(metadata.pid, 0);
2699
- return true;
2700
- } catch (error) {
2701
- return error.code !== "ESRCH";
2702
- }
2703
- }
2704
- async function recoverStaleLock(filePath) {
2705
- let before;
2706
- try {
2707
- before = await fs.readFile(filePath, "utf-8");
2708
- } catch {
2709
- return false;
2710
- }
2711
- const metadata = parseLockMetadata(before);
2712
- if (!metadata || isProcessAlive(metadata)) return false;
2713
- const current = parseLockMetadata(await fs.readFile(filePath, "utf-8").catch(() => ""));
2714
- if (!current || current.token !== metadata.token) return false;
2715
- await fs.unlink(filePath);
2716
- return true;
290
+ async function canonicalEntryName(parent, name) {
291
+ const variant = name === name.toLowerCase() ? name.toUpperCase() : name.toLowerCase();
292
+ if (variant === name) return name;
293
+ const [target, alias] = await Promise.all([fs.stat(path.join(parent, name), { bigint: true }), fs.stat(path.join(parent, variant), { bigint: true }).catch((error) => {
294
+ if (error.code === "ENOENT") return null;
295
+ throw error;
296
+ })]);
297
+ if (!alias || alias.dev !== target.dev || alias.ino !== target.ino) return name;
298
+ const entries = await fs.readdir(parent);
299
+ if (entries.includes(name)) return name;
300
+ for (const entry of entries) {
301
+ if (entry.toLowerCase() !== name.toLowerCase()) continue;
302
+ const candidate = await fs.stat(path.join(parent, entry), { bigint: true });
303
+ if (candidate.dev === target.dev && candidate.ino === target.ino) return entry;
304
+ }
305
+ throw Object.assign(/* @__PURE__ */ new Error("Unable to establish canonical path identity."), { code: "EACCES" });
306
+ }
307
+ async function canonicalExistingPath(filePath) {
308
+ const resolved = await fs.realpath(filePath);
309
+ if (process.platform === "win32") return resolved;
310
+ const { root } = path.parse(resolved);
311
+ let canonical = root;
312
+ for (const name of resolved.slice(root.length).split(path.sep)) if (name) canonical = path.join(canonical, await canonicalEntryName(canonical, name));
313
+ return canonical;
2717
314
  }
2718
315
  async function resolvePathThroughExistingAncestor(filePath) {
2719
316
  const missing = [];
2720
317
  let candidate = path.resolve(filePath);
2721
318
  for (;;) try {
2722
- const resolved = await fs.realpath(candidate);
319
+ const resolved = await canonicalExistingPath(candidate);
2723
320
  return path.join(resolved, ...missing);
2724
321
  } catch (error) {
2725
322
  const code = error.code;
@@ -2736,10 +333,40 @@ async function pathExists(filePath) {
2736
333
  throw error;
2737
334
  });
2738
335
  }
2739
- async function assertNoSymlinks(dirPath) {
336
+ function isProjectEntry(name) {
337
+ return name.endsWith(".fairy") || name === "settings" || name === "assets" || name.startsWith("assets_");
338
+ }
339
+ async function projectEntries(root) {
340
+ const names = await fs.readdir(root);
341
+ const owned = new Set(names.filter(isProjectEntry));
342
+ for (const fixed of ["assets", "settings"]) {
343
+ if (owned.has(fixed)) continue;
344
+ const aliases = names.filter((name) => name.toLowerCase() === fixed);
345
+ if (!aliases.length) continue;
346
+ let actual;
347
+ try {
348
+ actual = await fs.lstat(path.join(root, fixed), { bigint: true });
349
+ } catch (error) {
350
+ if (error.code === "ENOENT") continue;
351
+ throw error;
352
+ }
353
+ for (const alias of aliases) {
354
+ const entry = await fs.lstat(path.join(root, alias), { bigint: true });
355
+ if (entry.dev === actual.dev && entry.ino === actual.ino) owned.add(alias);
356
+ }
357
+ }
358
+ return owned;
359
+ }
360
+ async function assertNoSymlinks(dirPath, projectRoot = false) {
361
+ const owned = projectRoot ? await projectEntries(dirPath) : null;
2740
362
  for (const entry of await fs.readdir(dirPath, { withFileTypes: true })) {
363
+ if (owned && !owned.has(entry.name)) continue;
2741
364
  const entryPath = path.join(dirPath, entry.name);
2742
- if (entry.isSymbolicLink()) throw new Error(`Symbolic links are not supported in project directories: ${entryPath}`);
365
+ if (entry.isSymbolicLink()) {
366
+ const error = /* @__PURE__ */ new Error(`Symbolic links are not supported in project directories: ${entryPath}`);
367
+ error.code = "ELOOP";
368
+ throw error;
369
+ }
2743
370
  if (entry.isDirectory()) await assertNoSymlinks(entryPath);
2744
371
  }
2745
372
  }
@@ -2747,7 +374,7 @@ function createStagedNodeFileSystem(projectRoot, stagingRoot) {
2747
374
  const { runProjectWriteTransaction: _, ...base } = createNodeBackendFileSystem();
2748
375
  const translate = (filePath) => {
2749
376
  const relative = path.relative(projectRoot, path.resolve(filePath));
2750
- if (relative.startsWith("..") || path.isAbsolute(relative)) {
377
+ if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative) || relative && !isProjectEntry(relative.split(path.sep)[0])) {
2751
378
  const error = /* @__PURE__ */ new Error(`Project path escapes the staged root: ${filePath}`);
2752
379
  error.code = "EACCES";
2753
380
  throw error;
@@ -2785,25 +412,52 @@ async function runNodeProjectWriteTransaction(projectRoot, write) {
2785
412
  const staging = path.join(parent, `.${name}.save-${randomUUID()}`);
2786
413
  const backup = path.join(parent, `.${name}.save-backup-${randomUUID()}`);
2787
414
  const existed = await pathExists(root);
415
+ const changes = [];
2788
416
  try {
417
+ await fs.mkdir(staging, { recursive: true });
418
+ await fs.mkdir(backup);
419
+ const original = existed ? [...await projectEntries(root)] : [];
2789
420
  if (existed) {
2790
- await assertNoSymlinks(root);
2791
- await fs.cp(root, staging, {
421
+ await assertNoSymlinks(root, true);
422
+ for (const entry of original) await fs.cp(path.join(root, entry), path.join(staging, entry), {
2792
423
  recursive: true,
2793
424
  errorOnExist: true,
2794
425
  force: false
2795
426
  });
2796
- } else await fs.mkdir(staging, { recursive: true });
427
+ }
2797
428
  await write(createStagedNodeFileSystem(root, staging));
2798
- if (existed) await fs.rename(root, backup);
429
+ await assertNoSymlinks(root, true).catch((error) => {
430
+ if (error.code !== "ENOENT") throw error;
431
+ });
432
+ const entries = new Set([...original, ...await fs.readdir(staging)]);
433
+ if (!existed) await fs.mkdir(root, { recursive: true });
2799
434
  try {
2800
- await fs.rename(staging, root);
435
+ for (const entry of entries) {
436
+ const change = {
437
+ name: entry,
438
+ backedUp: false,
439
+ installed: false
440
+ };
441
+ changes.push(change);
442
+ if (await pathExists(path.join(root, entry))) {
443
+ await fs.rename(path.join(root, entry), path.join(backup, entry));
444
+ change.backedUp = true;
445
+ }
446
+ if (await pathExists(path.join(staging, entry))) {
447
+ await fs.rename(path.join(staging, entry), path.join(root, entry));
448
+ change.installed = true;
449
+ }
450
+ }
2801
451
  } 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]);
452
+ const errors = [commitError];
453
+ for (const change of changes.reverse()) try {
454
+ if (change.installed) await fs.rename(path.join(root, change.name), path.join(staging, change.name));
455
+ if (change.backedUp) await fs.rename(path.join(backup, change.name), path.join(root, change.name));
456
+ } catch (error) {
457
+ errors.push(error);
2806
458
  }
459
+ if (errors.length > 1) throw new ProjectWriteTransactionError(new AggregateError(errors, "Project commit and rollback both failed."), true, [backup, staging]);
460
+ if (!existed) await fs.rmdir(root);
2807
461
  throw commitError;
2808
462
  }
2809
463
  } catch (error) {
@@ -2812,12 +466,22 @@ async function runNodeProjectWriteTransaction(projectRoot, write) {
2812
466
  recursive: true,
2813
467
  force: true
2814
468
  }).catch(() => void 0);
469
+ await fs.rm(backup, {
470
+ recursive: true,
471
+ force: true
472
+ }).catch(() => void 0);
2815
473
  throw new ProjectWriteTransactionError(error, false);
2816
474
  }
2817
- if (existed) await fs.rm(backup, {
2818
- recursive: true,
2819
- force: true
2820
- }).catch(() => void 0);
475
+ const retainedBackupPaths = [];
476
+ for (const directory of [backup, staging]) try {
477
+ await fs.rm(directory, {
478
+ recursive: true,
479
+ force: true
480
+ });
481
+ } catch {
482
+ retainedBackupPaths.push(directory);
483
+ }
484
+ return { retainedBackupPaths };
2821
485
  }
2822
486
  function createNodeBackendFileSystem() {
2823
487
  return {
@@ -2825,14 +489,7 @@ function createNodeBackendFileSystem() {
2825
489
  return fs.stat(filePath);
2826
490
  },
2827
491
  async readdir(dirPath) {
2828
- const entries = await fs.readdir(dirPath, { withFileTypes: true });
2829
- const symlink = entries.find((entry) => entry.isSymbolicLink());
2830
- if (symlink) {
2831
- const error = /* @__PURE__ */ new Error(`Symbolic links are not supported in project directories: ${path.join(dirPath, symlink.name)}`);
2832
- error.code = "ELOOP";
2833
- throw error;
2834
- }
2835
- return entries.map((entry) => entry.name);
492
+ return (await fs.readdir(dirPath, { withFileTypes: true })).map((entry) => entry.name);
2836
493
  },
2837
494
  readFile(filePath) {
2838
495
  return fs.readFile(filePath, "utf-8");
@@ -2853,66 +510,13 @@ function createNodeBackendFileSystem() {
2853
510
  async resolvePath(filePath) {
2854
511
  return resolvePathThroughExistingAncestor(filePath);
2855
512
  },
2856
- validateProjectRoot: assertNoSymlinks,
513
+ caseSensitivePaths: true,
514
+ validateProjectRoot: (root) => assertNoSymlinks(root, true),
2857
515
  getSessionLockPath(canonicalProjectPath) {
2858
516
  return path.join(path.dirname(canonicalProjectPath), `.${path.basename(canonicalProjectPath)}.openfairygui.backend.lock`);
2859
517
  },
2860
518
  runProjectWriteTransaction: runNodeProjectWriteTransaction,
2861
- async acquireSessionLock(filePath) {
2862
- let handle;
2863
- try {
2864
- handle = await fs.open(filePath, "wx");
2865
- } catch (error) {
2866
- if (error.code !== "EEXIST" || !await recoverStaleLock(filePath)) throw error;
2867
- handle = await fs.open(filePath, "wx");
2868
- }
2869
- const owner = {
2870
- schemaVersion: 1,
2871
- pid: process.pid,
2872
- processStartTime: PROCESS_START_TIME,
2873
- hostname: os.hostname(),
2874
- token: randomUUID(),
2875
- createdAt: (/* @__PURE__ */ new Date()).toISOString()
2876
- };
2877
- let closed = false;
2878
- let released = false;
2879
- let metadataWritten = false;
2880
- const closeHandle = async () => {
2881
- if (closed) return;
2882
- await handle.close();
2883
- closed = true;
2884
- };
2885
- return {
2886
- async writeMetadata(content) {
2887
- let supplied = {};
2888
- try {
2889
- const parsed = JSON.parse(content);
2890
- if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) supplied = parsed;
2891
- } catch {}
2892
- await handle.writeFile(JSON.stringify({
2893
- ...supplied,
2894
- ...owner
2895
- }, null, 2), "utf-8");
2896
- metadataWritten = true;
2897
- await closeHandle();
2898
- },
2899
- async release() {
2900
- if (released) return;
2901
- await closeHandle();
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) {
2910
- if (error.code !== "ENOENT") throw error;
2911
- }
2912
- released = true;
2913
- }
2914
- };
2915
- },
519
+ acquireSessionLock: acquireNodeSessionLock,
2916
520
  unlink(filePath) {
2917
521
  return fs.unlink(filePath);
2918
522
  },
@@ -2942,5 +546,9 @@ function createNodeBackendRuntime(options = {}) {
2942
546
  host: options.host ?? createNodeBackendHostAdapter()
2943
547
  });
2944
548
  }
549
+ /** Resolve a CLI/SDK project input using the same rules as Node sessions. */
550
+ function resolveNodeFairyPath(input) {
551
+ return resolveFairyPath(createNodeBackendFileSystem(), input);
552
+ }
2945
553
  //#endregion
2946
- export { BackendRuntime, createNodeBackendFileSystem, createNodeBackendHostAdapter, createNodeBackendRuntime };
554
+ export { BackendRuntime, createNodeBackendFileSystem, createNodeBackendHostAdapter, createNodeBackendRuntime, resolveNodeFairyPath };