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