@mostra/runtime 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/dist/bin.js +7 -7
  2. package/dist/bin.js.map +1 -1
  3. package/dist/builder/child/main.js +18 -17
  4. package/dist/builder/child/main.js.map +1 -1
  5. package/dist/{child-xrHmytks.js → child-BQc3arf7.js} +5 -2
  6. package/dist/{child-xrHmytks.js.map → child-BQc3arf7.js.map} +1 -1
  7. package/dist/deps/child/install.js +9 -6
  8. package/dist/deps/child/install.js.map +1 -1
  9. package/dist/files-KxzOxckl.js +674 -0
  10. package/dist/files-KxzOxckl.js.map +1 -0
  11. package/dist/index.d.ts +2 -0
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +2 -2
  14. package/dist/{instance-CzBkUyHu.js → instance-DiKSe7s6.js} +1148 -737
  15. package/dist/instance-DiKSe7s6.js.map +1 -0
  16. package/package.json +5 -5
  17. package/src/bin.ts +4 -10
  18. package/src/builder/child/dev.ts +4 -3
  19. package/src/builder/child/plugins.ts +12 -7
  20. package/src/builder/child/spa.ts +15 -9
  21. package/src/builder/index.ts +3 -6
  22. package/src/deps/child/install.ts +3 -2
  23. package/src/deps/index.ts +21 -16
  24. package/src/deps/warm.ts +3 -16
  25. package/src/faults.ts +9 -2
  26. package/src/gateway/capabilities.ts +2 -2
  27. package/src/home/acquire.ts +27 -11
  28. package/src/home/paths.ts +45 -135
  29. package/src/home/platform.ts +17 -9
  30. package/src/home/record.ts +3 -3
  31. package/src/home/settings.ts +5 -16
  32. package/src/instance/index.ts +31 -7
  33. package/src/ledger/index.ts +5 -27
  34. package/src/platform/control.ts +409 -0
  35. package/src/platform/directories.ts +212 -0
  36. package/src/platform/environment.ts +64 -0
  37. package/src/platform/files.ts +368 -0
  38. package/src/platform/helper.ts +152 -0
  39. package/src/{processes → platform}/identity.ts +40 -8
  40. package/src/platform/index.ts +46 -0
  41. package/src/platform/launch.ts +373 -0
  42. package/src/processes/child.ts +4 -1
  43. package/src/processes/environment.ts +22 -3
  44. package/src/processes/index.ts +2 -1
  45. package/src/processes/manager.ts +76 -179
  46. package/src/protocol-server/client.ts +19 -18
  47. package/src/protocol-server/server.ts +75 -54
  48. package/src/publish/publisher.ts +16 -9
  49. package/src/publish/source.ts +7 -4
  50. package/src/registry/store.ts +7 -65
  51. package/src/secrets/index.ts +2 -2
  52. package/src/service/unit.ts +3 -2
  53. package/src/verify/index.ts +5 -3
  54. package/src/verify/typecheck.ts +3 -2
  55. package/src/workers/launcher.ts +3 -1
  56. package/dist/instance-CzBkUyHu.js.map +0 -1
  57. package/dist/types-NjNy7gXX.js +0 -57
  58. package/dist/types-NjNy7gXX.js.map +0 -1
@@ -0,0 +1,674 @@
1
+ import { chmodSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, statSync } from "node:fs";
2
+ import { dirname, join, posix, resolve, win32 } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { RpcError, createDiagnostic } from "@mostra/protocol";
5
+ import { execFileSync, spawn } from "node:child_process";
6
+ import { chmod, lstat, mkdir, readFile, readdir, readlink, realpath, rename, rm, rmdir, symlink, unlink, writeFile } from "node:fs/promises";
7
+ //#region src/builder/types.ts
8
+ /** The IPC method the supervisor calls on the builder child. */
9
+ const BUILD_METHOD = "builder/build";
10
+ /**
11
+ * `mostra dev`'s child (D140 item 12): the supervisor asks the builder child for a Vite dev
12
+ * server over a mirror of the artifact's source, reached only through the dev sandbox's gateway.
13
+ */
14
+ const DEV_METHOD = "builder/dev";
15
+ /**
16
+ * Supervisor to child: these files of the mirror changed (`{ changes: DevChange[] }`). The child
17
+ * watches nothing itself: the supervisor, which keeps the mirror, says exactly what changed.
18
+ */
19
+ const DEV_CHANGED_METHOD = "builder/dev.changed";
20
+ /** Supervisor to child: tell every page to load again (a new server bundle runs now). */
21
+ const DEV_RELOAD_METHOD = "builder/dev.reload";
22
+ /** Child to supervisor: the server bundle was built again (or failed to build). */
23
+ const DEV_SERVER_NOTIFICATION = "builder/dev.server";
24
+ /** Child to supervisor: the client modules of these files were updated in place (HMR). */
25
+ const DEV_UPDATE_NOTIFICATION = "builder/dev.update";
26
+ /** The header that carries {@link DevRequest.secret}. */
27
+ const DEV_SECRET_HEADER = "x-mostra-dev-secret";
28
+ /**
29
+ * The files written into the staging root so the bundler's upward searches stop there instead of
30
+ * reaching directories above the home (VR-01): a `tsconfig.json` with the compile settings Mostra
31
+ * chooses (an artifact's own `tsconfig.json`, part of its source, still applies to its files),
32
+ * and a `package.json` that marks the build as ES modules. Their contents are part of
33
+ * `buildConfigDigest`.
34
+ */
35
+ const STAGING_FILES = {
36
+ "tsconfig.json": `${JSON.stringify({ compilerOptions: {
37
+ target: "ES2022",
38
+ useDefineForClassFields: true,
39
+ jsx: "react-jsx",
40
+ jsxImportSource: "react",
41
+ experimentalDecorators: false
42
+ } }, null, 2)}\n`,
43
+ "package.json": `${JSON.stringify({
44
+ private: true,
45
+ type: "module"
46
+ }, null, 2)}\n`
47
+ };
48
+ /**
49
+ * The declaration that types `useLive` from `live.ts` (D56): client code reads the source types
50
+ * through `typeof import`, never by importing server code at run time. Written beside the build's
51
+ * other generated files for the type check, never into the artifact's source.
52
+ */
53
+ const LIVE_DECLARATION = `// Generated by Mostra: the types of this artifact's live sources (D56).
54
+ import type { LiveValuesOf } from "@mostra/react";
55
+
56
+ declare module "@mostra/react" {
57
+ interface LiveSources extends LiveValuesOf<typeof import("../source/live")> {}
58
+ }
59
+ `;
60
+ //#endregion
61
+ //#region src/platform/helper.ts
62
+ /**
63
+ * Running `mostra-win`, the Windows platform helper (`crates/mostra-win`, WP-W1): finding it and
64
+ * reading its one-line JSON answers. The runtime asks it for what Node.js can't do on Windows:
65
+ * owner-only access control, process identity by creation time, the child gate and reaping, and
66
+ * the owner-only control pipe. Only this module's Windows code calls it.
67
+ */
68
+ /** The name `bundle.json` gives a runtime bundle (D142). */
69
+ const BUNDLE_NAME$1 = "mostra-runtime-bundle";
70
+ /** The directory of `@mostra/runtime`'s `package.json`, wherever the code runs from. */
71
+ function runtimeRoot() {
72
+ let dir = dirname(fileURLToPath(import.meta.url));
73
+ for (;;) {
74
+ const manifest = join(dir, "package.json");
75
+ if (existsSync(manifest)) {
76
+ const { name } = JSON.parse(readFileSync(manifest, "utf8"));
77
+ if (name === "@mostra/runtime") return dir;
78
+ }
79
+ const parent = dirname(dir);
80
+ if (parent === dir) throw new Error("Couldn't find @mostra/runtime's package.json.");
81
+ dir = parent;
82
+ }
83
+ }
84
+ /** The runtime bundle the runtime sits in (four levels above its package), if any. */
85
+ function enclosingBundle(root) {
86
+ const bundle = resolve(root, "..", "..", "..", "..");
87
+ try {
88
+ return JSON.parse(readFileSync(join(bundle, "bundle.json"), "utf8")).name === BUNDLE_NAME$1 ? bundle : void 0;
89
+ } catch {
90
+ return;
91
+ }
92
+ }
93
+ let located;
94
+ /**
95
+ * The helper's path: `MOSTRA_WIN_HELPER`; else the runtime bundle's `bin/mostra-win.exe`; else,
96
+ * in a development checkout, the one Cargo built (`target/release`, then `target/debug`). Throws
97
+ * `MOSTRA_ENV_HELPER_MISSING` when none exists.
98
+ */
99
+ function helperPath(env = process.env) {
100
+ const override = env["MOSTRA_WIN_HELPER"];
101
+ if (override) {
102
+ if (!existsSync(override)) throw missing(`MOSTRA_WIN_HELPER names ${override}, which doesn't exist.`);
103
+ return override;
104
+ }
105
+ if (located !== void 0) return located;
106
+ const root = runtimeRoot();
107
+ const bundle = enclosingBundle(root);
108
+ const candidates = bundle !== void 0 ? [join(bundle, "bin", "mostra-win.exe")] : ["release", "debug"].map((profile) => resolve(root, "..", "..", "target", profile, "mostra-win.exe"));
109
+ const found = candidates.find((candidate) => existsSync(candidate));
110
+ if (found === void 0) throw missing(`Mostra's Windows helper isn't installed; looked for ${candidates.join(", ")}.`);
111
+ located = found;
112
+ return found;
113
+ }
114
+ function missing(message) {
115
+ return new RpcError(createDiagnostic("MOSTRA_ENV_HELPER_MISSING", { message }));
116
+ }
117
+ /** A failure the helper reported, with the Windows error code when there is one. */
118
+ var HelperError = class extends Error {
119
+ os;
120
+ constructor(command, message, os) {
121
+ super(`mostra-win ${command}: ${message}`);
122
+ this.os = os;
123
+ }
124
+ };
125
+ function parse(command, stdout) {
126
+ const line = stdout.trim().split("\n").at(-1) ?? "";
127
+ let answer;
128
+ try {
129
+ answer = JSON.parse(line);
130
+ } catch {
131
+ throw new HelperError(command, `answered something that isn't JSON: ${line.slice(0, 200)}`, void 0);
132
+ }
133
+ if (!answer.ok) throw new HelperError(command, answer.error.message, answer.error.os ?? void 0);
134
+ return answer.result;
135
+ }
136
+ /** Runs a helper command and returns its result; for the calls that must finish before going on. */
137
+ function runHelper(args) {
138
+ const helper = helperPath();
139
+ let stdout;
140
+ try {
141
+ stdout = execFileSync(helper, args, {
142
+ encoding: "utf8",
143
+ windowsHide: true,
144
+ stdio: [
145
+ "ignore",
146
+ "pipe",
147
+ "pipe"
148
+ ]
149
+ });
150
+ } catch (error) {
151
+ const failed = error;
152
+ if (failed.stdout) return parse(args[0] ?? "", failed.stdout);
153
+ throw new HelperError(args[0] ?? "", failed.message, void 0);
154
+ }
155
+ return parse(args[0] ?? "", stdout);
156
+ }
157
+ /** Runs a helper command without blocking the event loop. */
158
+ function runHelperAsync(args) {
159
+ const helper = helperPath();
160
+ return new Promise((resolvePromise, reject) => {
161
+ const child = spawn(helper, args, {
162
+ windowsHide: true,
163
+ stdio: [
164
+ "ignore",
165
+ "pipe",
166
+ "pipe"
167
+ ]
168
+ });
169
+ let stdout = "";
170
+ let stderr = "";
171
+ child.stdout.setEncoding("utf8");
172
+ child.stderr.setEncoding("utf8");
173
+ child.stdout.on("data", (chunk) => {
174
+ stdout += chunk;
175
+ });
176
+ child.stderr.on("data", (chunk) => {
177
+ stderr += chunk;
178
+ });
179
+ child.once("error", reject);
180
+ child.once("close", () => {
181
+ try {
182
+ resolvePromise(parse(args[0] ?? "", stdout || stderr));
183
+ } catch (error) {
184
+ reject(error);
185
+ }
186
+ });
187
+ });
188
+ }
189
+ //#endregion
190
+ //#region src/platform/directories.ts
191
+ /**
192
+ * Where a home and its control endpoint live on each operating system, and how a directory is
193
+ * made owner-only (DATA_MODEL §1; D82, D84, D85; RT-10). Resolving a path never touches the file
194
+ * system; `ownedDirectory` creates or checks one.
195
+ *
196
+ * - macOS: the home defaults to `~/.mostra`, the runtime directory to `~/.mostra/run`.
197
+ * - Linux: `${XDG_DATA_HOME:-~/.local/share}/mostra`; `$XDG_RUNTIME_DIR/mostra` when that
198
+ * directory is the user's and private, else `${XDG_STATE_HOME:-~/.local/state}/mostra/run`.
199
+ * - Windows: `%LOCALAPPDATA%\mostra`. The control endpoint is a named pipe, which lives in no
200
+ * directory, so there is no runtime directory and `MOSTRA_RUNTIME_DIR` doesn't apply.
201
+ *
202
+ * Owner-only means mode 0700 on POSIX, and on Windows a protected access list that grants only the
203
+ * user and `SYSTEM`, inherited by everything inside (the helper's `secure-dir`).
204
+ */
205
+ /** The operating system this process runs on. Every other module asks here. */
206
+ const OS = process.platform;
207
+ /** Whether this process runs on Windows. */
208
+ const WINDOWS = OS === "win32";
209
+ const nonEmpty = (value) => value === void 0 || value === "" ? void 0 : value;
210
+ /** The path rules of an operating system, so resolution for another one can be computed and tested. */
211
+ function pathsOf(os) {
212
+ return os === "win32" ? win32 : posix;
213
+ }
214
+ /** The home a platform uses when neither `--home` nor `MOSTRA_HOME` names one. */
215
+ function defaultHome(os, env, userHome) {
216
+ if (os === "darwin") return posix.join(userHome, ".mostra");
217
+ if (os === "win32") {
218
+ const local = nonEmpty(env["LOCALAPPDATA"]);
219
+ return win32.join(local !== void 0 && win32.isAbsolute(local) ? local : win32.join(userHome, "AppData", "Local"), "mostra");
220
+ }
221
+ const data = nonEmpty(env["XDG_DATA_HOME"]);
222
+ return posix.join(data !== void 0 && posix.isAbsolute(data) ? data : posix.join(userHome, ".local", "share"), "mostra");
223
+ }
224
+ /**
225
+ * The runtime directory for control sockets (D82), or `undefined` on Windows, whose control pipe
226
+ * lives in the system's pipe namespace.
227
+ */
228
+ function runtimeDirFor(inputs) {
229
+ if (inputs.os === "win32") return void 0;
230
+ const override = nonEmpty(inputs.env["MOSTRA_RUNTIME_DIR"]);
231
+ if (override !== void 0) return {
232
+ dir: posix.resolve(inputs.cwd, override),
233
+ source: "override"
234
+ };
235
+ if (inputs.os === "darwin") return {
236
+ dir: posix.join(inputs.userHome, ".mostra", "run"),
237
+ source: "fallback"
238
+ };
239
+ const xdg = nonEmpty(inputs.env["XDG_RUNTIME_DIR"]);
240
+ let rejected;
241
+ if (xdg !== void 0) {
242
+ rejected = unsafeXdgRuntimeDir(xdg);
243
+ if (rejected === void 0) return {
244
+ dir: posix.join(xdg, "mostra"),
245
+ source: "xdg"
246
+ };
247
+ }
248
+ const state = nonEmpty(inputs.env["XDG_STATE_HOME"]);
249
+ const base = state !== void 0 && posix.isAbsolute(state) ? state : posix.join(inputs.userHome, ".local", "state");
250
+ const dir = posix.join(base, "mostra", "run");
251
+ return rejected === void 0 ? {
252
+ dir,
253
+ source: "fallback"
254
+ } : {
255
+ dir,
256
+ source: "fallback",
257
+ rejected
258
+ };
259
+ }
260
+ /** The current user's ID on POSIX. */
261
+ function uid() {
262
+ return process.getuid?.() ?? -1;
263
+ }
264
+ /** Why `$XDG_RUNTIME_DIR` can't be used, or `undefined` when it can (XDG Base Directory spec). */
265
+ function unsafeXdgRuntimeDir(dir) {
266
+ if (!posix.isAbsolute(dir)) return "it isn't an absolute path";
267
+ let stats;
268
+ try {
269
+ stats = statSync(dir);
270
+ } catch {
271
+ return "it doesn't exist";
272
+ }
273
+ if (!stats.isDirectory()) return "it isn't a directory";
274
+ if (stats.uid !== uid()) return "another user owns it";
275
+ if ((stats.mode & 63) !== 0) return "other users can access it";
276
+ }
277
+ /** The longest control socket path the operating system accepts, in bytes (VERIFIED_FACTS). */
278
+ function socketPathLimit(os) {
279
+ return os === "darwin" ? 103 : 107;
280
+ }
281
+ function notOwned(path, why) {
282
+ return new RpcError(createDiagnostic("MOSTRA_HOME_NOT_OWNED", { message: `Mostra can't use ${path}: ${why}.` }));
283
+ }
284
+ /**
285
+ * Makes `path` a directory only its owner can use (D85): creates it owner-only when missing,
286
+ * tightens one the user owns, and throws `MOSTRA_HOME_NOT_OWNED` for one owned by another user or
287
+ * a path that isn't a directory. Symlinks are followed.
288
+ */
289
+ function ownedDirectory(path) {
290
+ if (WINDOWS) return ownedDirectoryWindows(path);
291
+ try {
292
+ return preparePosix(path);
293
+ } catch (error) {
294
+ const code = error.code;
295
+ if (code === "ENOTDIR" || code === "EEXIST") throw notOwned(path, "a part of the path isn't a directory");
296
+ if (code === "EACCES" || code === "EPERM") throw notOwned(path, "you have no permission to use it");
297
+ throw error;
298
+ }
299
+ }
300
+ function preparePosix(path) {
301
+ let created = false;
302
+ try {
303
+ statSync(path);
304
+ } catch (error) {
305
+ if (error.code !== "ENOENT") throw error;
306
+ mkdirSync(path, {
307
+ recursive: true,
308
+ mode: 448
309
+ });
310
+ created = true;
311
+ }
312
+ const realPath = realpathSync(path);
313
+ const stats = statSync(realPath);
314
+ if (!stats.isDirectory()) throw notOwned(path, "it isn't a directory");
315
+ if (stats.uid !== uid()) throw notOwned(path, `it belongs to user ${stats.uid}, not to you`);
316
+ const mode = stats.mode & 511;
317
+ if (mode !== 448) {
318
+ chmodSync(realPath, 448);
319
+ return created ? {
320
+ realPath,
321
+ created
322
+ } : {
323
+ realPath,
324
+ created,
325
+ tightenedFrom: mode.toString(8)
326
+ };
327
+ }
328
+ return {
329
+ realPath,
330
+ created
331
+ };
332
+ }
333
+ function ownedDirectoryWindows(path) {
334
+ let answer;
335
+ try {
336
+ answer = runHelper(["secure-dir", path]);
337
+ } catch (error) {
338
+ if (error.os === 5) throw notOwned(path, "you have no permission to use it");
339
+ throw error;
340
+ }
341
+ if ("refused" in answer) throw notOwned(path, answer.refused === "not-owned" ? `it belongs to ${answer.owner}, not to you` : "it isn't a directory");
342
+ const realPath = realpathSync.native(path);
343
+ if (answer.secured === "tightened") return {
344
+ realPath,
345
+ created: false,
346
+ tightenedFrom: answer.from
347
+ };
348
+ return {
349
+ realPath,
350
+ created: answer.secured === "created"
351
+ };
352
+ }
353
+ //#endregion
354
+ //#region src/platform/files.ts
355
+ /**
356
+ * File operations whose semantics differ between POSIX and Windows (FAILURE_MODEL §3, RT-10):
357
+ *
358
+ * - **Renames.** Windows refuses to replace or move a file another process has open without
359
+ * sharing deletion, and antivirus scanners and the search indexer open new files for a moment
360
+ * after they are written. A rename that meets a sharing violation is tried again for a short
361
+ * while (`EPERM`, `EACCES`, `EBUSY`), never weakened into a copy: the step stays atomic or fails.
362
+ * - **Syncing.** Windows syncs a file only through a handle open for writing.
363
+ * - **Directory links.** A directory symlink needs a privilege most Windows users don't hold;
364
+ * junctions need none, and Node.js and pnpm resolve through them like symlinks.
365
+ * - **Sealing.** A sealed version is read-only for everyone (0444 files and 0555 directories on
366
+ * POSIX; on Windows an access list granting only reading, applied by the helper). Its owner can
367
+ * always unseal it, as on POSIX.
368
+ * - **Names.** Windows file names are case-insensitive: two names that differ only in case are
369
+ * one file.
370
+ */
371
+ /** Errors a Windows rename or removal meets while another process briefly holds the file. */
372
+ const TRANSIENT = /* @__PURE__ */ new Set([
373
+ "EPERM",
374
+ "EACCES",
375
+ "EBUSY",
376
+ "ENOTEMPTY"
377
+ ]);
378
+ /** How long a rename keeps trying through sharing violations. */
379
+ const RETRY_MS = 3e3;
380
+ const errno = (error) => error.code;
381
+ const sleep = (ms) => new Promise((done) => setTimeout(done, ms));
382
+ function sleepSync(ms) {
383
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
384
+ }
385
+ /**
386
+ * Renames `from` to `to`, replacing a file at `to` (POSIX `rename`). On Windows a sharing
387
+ * violation is retried with backoff for up to 3 s before it is thrown.
388
+ */
389
+ async function renamePath(from, to) {
390
+ const deadline = Date.now() + RETRY_MS;
391
+ for (let wait = 10;; wait = Math.min(wait * 2, 250)) try {
392
+ await rename(from, to);
393
+ return;
394
+ } catch (error) {
395
+ if (!WINDOWS || !TRANSIENT.has(errno(error) ?? "") || Date.now() >= deadline) throw error;
396
+ await sleep(wait);
397
+ }
398
+ }
399
+ /** {@link renamePath}, blocking. */
400
+ function renamePathSync(from, to) {
401
+ const deadline = Date.now() + RETRY_MS;
402
+ for (let wait = 10;; wait = Math.min(wait * 2, 250)) try {
403
+ renameSync(from, to);
404
+ return;
405
+ } catch (error) {
406
+ if (!WINDOWS || !TRANSIENT.has(errno(error) ?? "") || Date.now() >= deadline) throw error;
407
+ sleepSync(wait);
408
+ }
409
+ }
410
+ /**
411
+ * Syncs a file or a directory to disk. A file that can't be synced fails the caller (its bytes
412
+ * would not be durable); a directory may not support it on some file systems (Windows can't open
413
+ * one this way at all), and only that case is tolerated.
414
+ */
415
+ function fsyncPath(path, directory = false) {
416
+ if (directory && WINDOWS) {
417
+ statSync(path);
418
+ return;
419
+ }
420
+ let fd;
421
+ try {
422
+ fd = openSync(path, WINDOWS ? "r+" : "r");
423
+ fsyncSync(fd);
424
+ } catch (error) {
425
+ const code = errno(error);
426
+ if (!directory || ![
427
+ "EINVAL",
428
+ "ENOTSUP",
429
+ "EISDIR",
430
+ "EPERM",
431
+ "EACCES"
432
+ ].includes(code ?? "")) throw error;
433
+ } finally {
434
+ if (fd !== void 0) closeSync(fd);
435
+ }
436
+ }
437
+ /**
438
+ * Makes `path` a link to the `node_modules`-like directory `target`: a symlink on POSIX; on
439
+ * Windows a {@link linkFarm}, since a junction to the directory would break the relative links
440
+ * inside it (pnpm's), which Windows resolves against the path they were reached by (VERIFIED_FACTS,
441
+ * WP-W1).
442
+ */
443
+ async function linkDirectory(target, path) {
444
+ if (WINDOWS) await linkFarm(target, path);
445
+ else await symlink(target, path, "dir");
446
+ }
447
+ /** The marker a link farm keeps: what it mirrors, and the entries it mirrored. */
448
+ const FARM_MARKER = ".mostra-link";
449
+ /** Every entry of a `node_modules`-like directory, scoped ones as `@scope/name`, dot entries left out. */
450
+ async function farmEntries(target) {
451
+ const names = [];
452
+ for (const entry of await readdir(target, { withFileTypes: true })) {
453
+ if (entry.name.startsWith(".")) continue;
454
+ if (entry.name.startsWith("@") && entry.isDirectory()) for (const scoped of await readdir(join(target, entry.name))) names.push(`${entry.name}/${scoped}`);
455
+ else names.push(entry.name);
456
+ }
457
+ const entries = [];
458
+ for (const name of names.sort()) try {
459
+ entries.push({
460
+ name,
461
+ real: await realpath(join(target, ...name.split("/")))
462
+ });
463
+ } catch {}
464
+ return entries;
465
+ }
466
+ /**
467
+ * A directory that stands for `target`: one junction per entry, to the entry's real path, so every
468
+ * link inside resolves from where it really is, and a marker naming what it mirrors. Built aside
469
+ * and renamed into place, so `path` is either missing or complete. Used on Windows; it works on
470
+ * POSIX too, where the tests exercise it.
471
+ */
472
+ async function linkFarm(target, path) {
473
+ const source = resolve(target);
474
+ const entries = await farmEntries(source);
475
+ const building = `${path}.${process.pid}.${Date.now()}.farm`;
476
+ await mkdir(building, { recursive: true });
477
+ try {
478
+ for (const entry of entries) {
479
+ const at = join(building, ...entry.name.split("/"));
480
+ if (entry.name.includes("/")) await mkdir(join(at, ".."), { recursive: true });
481
+ await symlink(entry.real, at, "junction");
482
+ }
483
+ await writeFile(join(building, FARM_MARKER), `${JSON.stringify({
484
+ target: source,
485
+ entries
486
+ })}\n`);
487
+ await renamePath(building, path);
488
+ } catch (error) {
489
+ await removeFarm(building).catch(() => {});
490
+ throw error;
491
+ }
492
+ }
493
+ /** Removes a link farm's junctions, never what they point to, then its directories. */
494
+ async function removeFarm(path) {
495
+ for (const entry of await readdir(path, { withFileTypes: true }).catch(() => [])) {
496
+ const at = join(path, entry.name);
497
+ if (entry.isSymbolicLink()) await unlinkEntry(at);
498
+ else if (entry.isDirectory()) await removeFarm(at);
499
+ else await rm(at, { force: true });
500
+ }
501
+ await rmdir(path);
502
+ }
503
+ /** Removes one link: on Windows a junction is removed as the directory entry it is. */
504
+ async function unlinkEntry(path) {
505
+ try {
506
+ await unlink(path);
507
+ } catch (error) {
508
+ if (!WINDOWS || errno(error) !== "EPERM") throw error;
509
+ await rmdir(path);
510
+ }
511
+ }
512
+ /**
513
+ * What the directory link `path` stands for, or `undefined` when it is missing, isn't a link, or
514
+ * (a link farm) no longer mirrors its target's current entries.
515
+ */
516
+ async function linkTarget(path) {
517
+ try {
518
+ const info = await lstat(path);
519
+ if (info.isSymbolicLink()) return resolve(join(path, ".."), await readlink(path));
520
+ if (!info.isDirectory()) return void 0;
521
+ const marker = JSON.parse(await readFile(join(path, FARM_MARKER), "utf8"));
522
+ const now = await farmEntries(marker.target);
523
+ return JSON.stringify(now) === JSON.stringify(marker.entries) ? marker.target : void 0;
524
+ } catch {
525
+ return;
526
+ }
527
+ }
528
+ /**
529
+ * Points the directory link `path` at `target`, replacing what it pointed at with no moment
530
+ * where `path` is missing on POSIX (a new link renamed over it). Windows can't rename a link over
531
+ * an existing directory entry, so the old link is renamed aside first and removed after.
532
+ */
533
+ async function replaceDirectoryLink(target, path) {
534
+ const fresh = `${path}.${process.pid}.${Date.now()}.new`;
535
+ await linkDirectory(target, fresh);
536
+ if (!WINDOWS) {
537
+ await rename(fresh, path);
538
+ return;
539
+ }
540
+ const aside = `${path}.${process.pid}.${Date.now()}.old`;
541
+ let moved = false;
542
+ try {
543
+ await renamePath(path, aside);
544
+ moved = true;
545
+ } catch (error) {
546
+ if (errno(error) !== "ENOENT") {
547
+ await unlinkDirectory(fresh);
548
+ throw error;
549
+ }
550
+ }
551
+ await renamePath(fresh, path);
552
+ if (moved) await unlinkDirectory(aside);
553
+ }
554
+ /**
555
+ * `path` without the separators it ends in (a loop: a regular expression here is quadratic). On
556
+ * POSIX a backslash is an ordinary character of a name, never a separator.
557
+ */
558
+ function trimSeparators(path) {
559
+ let end = path.length;
560
+ while (end > 0 && (path[end - 1] === "/" || WINDOWS && path[end - 1] === "\\")) end--;
561
+ return path.slice(0, end);
562
+ }
563
+ /** Whether a link points at `target` (paths compared as this file system compares them). */
564
+ function samePath(a, b) {
565
+ const normal = (path) => nameKey(trimSeparators(resolve(path.startsWith("\\\\?\\") ? path.slice(4) : path)));
566
+ return normal(a) === normal(b);
567
+ }
568
+ /**
569
+ * A path as a key for comparison: `/`-separated, without a trailing `/`, and on Windows in lower
570
+ * case, since Windows names compare without case and bundlers spell `C:\x` as `C:/x`. The key has
571
+ * the path's length, so an index found in it holds in the path too.
572
+ */
573
+ function pathKey(path) {
574
+ return nameKey(WINDOWS ? path.replaceAll("\\", "/") : path);
575
+ }
576
+ /** Whether `file` is `dir` itself or lies under it, however either spells its separators. */
577
+ function isUnder(file, dir) {
578
+ const key = pathKey(file);
579
+ const root = trimSeparators(pathKey(dir));
580
+ return key === root || key.startsWith(`${root}/`);
581
+ }
582
+ /** Removes a link made by {@link linkDirectory}, never what it points to. */
583
+ async function unlinkDirectory(path) {
584
+ let info;
585
+ try {
586
+ info = await lstat(path);
587
+ } catch (error) {
588
+ if (errno(error) === "ENOENT") return;
589
+ throw error;
590
+ }
591
+ if (info.isDirectory() && !info.isSymbolicLink()) await removeFarm(path);
592
+ else await unlinkEntry(path);
593
+ }
594
+ /** Calls `visit` for every entry under `dir`, children before their directory. */
595
+ async function walk(dir, visit) {
596
+ const entries = await readdir(dir, { withFileTypes: true });
597
+ for (const entry of entries) {
598
+ const path = join(dir, entry.name);
599
+ if (entry.isDirectory()) await walk(path, visit);
600
+ await visit(path, entry.isDirectory());
601
+ }
602
+ }
603
+ /**
604
+ * Makes a tree read-only and syncs it to disk. On POSIX the top directory is left writable when
605
+ * `keepTop` is set, since renaming a directory needs write access to it; on Windows the whole tree
606
+ * is synced first and sealed in one step after it is in place ({@link sealPlaced}).
607
+ */
608
+ async function sealTree(dir, keepTop = false) {
609
+ if (WINDOWS) {
610
+ await walk(dir, async (path, isDirectory) => {
611
+ if (!isDirectory) fsyncPath(path);
612
+ });
613
+ return;
614
+ }
615
+ await walk(dir, async (path, isDirectory) => {
616
+ await chmod(path, isDirectory ? 365 : 292);
617
+ fsyncPath(path, isDirectory);
618
+ });
619
+ if (!keepTop) await chmod(dir, 365);
620
+ fsyncPath(dir, true);
621
+ }
622
+ /**
623
+ * Finishes sealing a tree that is in its final place: on POSIX its top directory becomes 0555; on
624
+ * Windows the whole tree gets the read-only access list (moving a sealed directory would need the
625
+ * delete right the seal withholds).
626
+ */
627
+ async function sealPlaced(dir) {
628
+ if (WINDOWS) {
629
+ await runHelperAsync(["seal", dir]);
630
+ return;
631
+ }
632
+ await chmod(dir, 365);
633
+ fsyncPath(dir, true);
634
+ }
635
+ /** Removes a tree, sealed or not. Missing trees are fine. Links inside are removed, never followed. */
636
+ async function removeTree(dir) {
637
+ let info;
638
+ try {
639
+ info = await lstat(dir);
640
+ } catch {
641
+ return;
642
+ }
643
+ if (info.isDirectory() && !WINDOWS) {
644
+ await chmod(dir, 493);
645
+ await walk(dir, async (path, isDirectory) => {
646
+ if (isDirectory) await chmod(path, 493);
647
+ }).catch(() => {});
648
+ }
649
+ const deadline = Date.now() + RETRY_MS;
650
+ let unsealed = false;
651
+ for (let wait = 10;; wait = Math.min(wait * 2, 250)) try {
652
+ await rm(dir, {
653
+ recursive: true,
654
+ force: true
655
+ });
656
+ return;
657
+ } catch (error) {
658
+ if (!WINDOWS || !TRANSIENT.has(errno(error) ?? "") || Date.now() >= deadline) throw error;
659
+ if (!unsealed && info.isDirectory()) {
660
+ unsealed = true;
661
+ await runHelperAsync(["unseal", dir]).catch(() => {});
662
+ continue;
663
+ }
664
+ await sleep(wait);
665
+ }
666
+ }
667
+ /** The form under which two file names are the same name on this file system. */
668
+ function nameKey(name) {
669
+ return WINDOWS ? name.toLowerCase() : name;
670
+ }
671
+ //#endregion
672
+ export { DEV_UPDATE_NOTIFICATION as A, runtimeRoot as C, DEV_RELOAD_METHOD as D, DEV_METHOD as E, STAGING_FILES as M, DEV_SECRET_HEADER as O, runHelperAsync as S, DEV_CHANGED_METHOD as T, ownedDirectory as _, nameKey as a, socketPathLimit as b, renamePath as c, samePath as d, sealPlaced as f, defaultHome as g, WINDOWS as h, linkTarget as i, LIVE_DECLARATION as j, DEV_SERVER_NOTIFICATION as k, renamePathSync as l, OS as m, isUnder as n, pathKey as o, sealTree as p, linkDirectory as r, removeTree as s, fsyncPath as t, replaceDirectoryLink as u, pathsOf as v, BUILD_METHOD as w, helperPath as x, runtimeDirFor as y };
673
+
674
+ //# sourceMappingURL=files-KxzOxckl.js.map