@mostra/runtime 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/dist/bin.js +23 -12
  2. package/dist/bin.js.map +1 -1
  3. package/dist/builder/child/main.js +20 -18
  4. package/dist/builder/child/main.js.map +1 -1
  5. package/dist/{child-xrHmytks.js → child-Chiavhdx.js} +7 -3
  6. package/dist/child-Chiavhdx.js.map +1 -0
  7. package/dist/deps/child/install.js +9 -6
  8. package/dist/deps/child/install.js.map +1 -1
  9. package/dist/directories-mJ1qlVht.js +322 -0
  10. package/dist/directories-mJ1qlVht.js.map +1 -0
  11. package/dist/files-FygSJIzK.js +388 -0
  12. package/dist/files-FygSJIzK.js.map +1 -0
  13. package/dist/index.d.ts +2 -0
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +2 -2
  16. package/dist/{instance-CzBkUyHu.js → instance-DxcGEQj_.js} +1680 -934
  17. package/dist/instance-DxcGEQj_.js.map +1 -0
  18. package/package.json +5 -5
  19. package/src/bin.ts +18 -16
  20. package/src/builder/child/dev.ts +8 -4
  21. package/src/builder/child/plugins.ts +12 -7
  22. package/src/builder/child/spa.ts +15 -9
  23. package/src/builder/index.ts +3 -6
  24. package/src/deps/child/install.ts +3 -2
  25. package/src/deps/index.ts +21 -16
  26. package/src/deps/warm.ts +3 -16
  27. package/src/dev/index.ts +37 -19
  28. package/src/faults.ts +9 -2
  29. package/src/gateway/capabilities.ts +2 -2
  30. package/src/gateway/listener.ts +36 -0
  31. package/src/home/acquire.ts +27 -11
  32. package/src/home/index.ts +1 -1
  33. package/src/home/paths.ts +45 -135
  34. package/src/home/platform.ts +17 -9
  35. package/src/home/record.ts +3 -3
  36. package/src/home/settings.ts +5 -16
  37. package/src/instance/index.ts +41 -9
  38. package/src/ledger/index.ts +5 -27
  39. package/src/platform/control.ts +409 -0
  40. package/src/platform/directories.ts +212 -0
  41. package/src/platform/environment.ts +64 -0
  42. package/src/platform/files.ts +386 -0
  43. package/src/platform/helper.ts +178 -0
  44. package/src/{processes → platform}/identity.ts +40 -8
  45. package/src/platform/index.ts +53 -0
  46. package/src/platform/launch.ts +373 -0
  47. package/src/processes/child.ts +11 -5
  48. package/src/processes/environment.ts +22 -3
  49. package/src/processes/index.ts +2 -1
  50. package/src/processes/manager.ts +76 -179
  51. package/src/protocol-server/client.ts +19 -18
  52. package/src/protocol-server/server.ts +75 -54
  53. package/src/publish/index.ts +2 -1
  54. package/src/publish/publisher.ts +17 -10
  55. package/src/publish/source.ts +7 -4
  56. package/src/registry/store.ts +7 -65
  57. package/src/secrets/index.ts +2 -2
  58. package/src/service/unit.ts +353 -33
  59. package/src/verify/index.ts +5 -3
  60. package/src/verify/typecheck.ts +3 -2
  61. package/src/workers/launcher.ts +3 -1
  62. package/src/workers/pool.ts +14 -1
  63. package/dist/child-xrHmytks.js.map +0 -1
  64. package/dist/instance-CzBkUyHu.js.map +0 -1
  65. package/dist/types-NjNy7gXX.js +0 -57
  66. package/dist/types-NjNy7gXX.js.map +0 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mostra/runtime",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "description": "The Mostra runtime: the supervisor that owns a home, its ledger, its child processes and the host protocol server (mostra-runtime host|daemon).",
5
5
  "license": "Apache-2.0",
6
6
  "author": "The Mostra Authors",
@@ -36,7 +36,7 @@
36
36
  "dependencies": {
37
37
  "@hono/node-server": "2.1.3",
38
38
  "@mdx-js/mdx": "3.1.1",
39
- "@mostra/protocol": "0.2.0",
39
+ "@mostra/protocol": "0.4.0",
40
40
  "@tailwindcss/vite": "4.3.3",
41
41
  "@vitejs/plugin-react": "6.1.1",
42
42
  "better-sqlite3": "13.0.3",
@@ -54,11 +54,11 @@
54
54
  "zod": "4.6.5"
55
55
  },
56
56
  "devDependencies": {
57
- "@mostra/shell": "0.2.0",
57
+ "@mostra/shell": "0.4.0",
58
58
  "@mostra/tools": "0.0.0",
59
- "@mostra/verify": "0.2.0",
59
+ "@mostra/verify": "0.4.0",
60
60
  "@mostra/warm": "0.0.0",
61
- "@mostra/worker": "0.2.0",
61
+ "@mostra/worker": "0.4.0",
62
62
  "@types/better-sqlite3": "9.6.0",
63
63
  "@types/node": "24.19.1",
64
64
  "@types/semver": "7.8.0",
package/src/bin.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { mkdirSync, realpathSync } from "node:fs";
2
+ import { mkdirSync } from "node:fs";
3
3
  import { fileURLToPath } from "node:url";
4
4
  /**
5
5
  * `mostra-runtime`, the runtime bundle's entry point (D85).
@@ -33,6 +33,7 @@ import {
33
33
  } from "@mostra/protocol";
34
34
  import { checkPlatform, resolveHomePath } from "./home/index.ts";
35
35
  import { type Instance, runtimeVersion, startInstance } from "./instance/index.ts";
36
+ import { realPath } from "./platform/index.ts";
36
37
  import { installService, serviceStatus, uninstallService } from "./service/index.ts";
37
38
 
38
39
  /** Exit codes, as INTERFACES §9 defines them for the CLI. */
@@ -92,20 +93,14 @@ function refuseOverStdio(diagnostic: Diagnostic, exitCode: number): void {
92
93
  }
93
94
 
94
95
  function handleSignals(instance: Instance): void {
95
- for (const signal of ["SIGTERM", "SIGINT"] as const) {
96
+ // SIGTERM and SIGINT on POSIX; on Windows Ctrl+C and Ctrl+Break reach a console process as
97
+ // SIGINT and SIGBREAK, and everything else stops it over the protocol (`mostra/shutdown`, D87).
98
+ for (const signal of ["SIGTERM", "SIGINT", "SIGBREAK"] as const) {
96
99
  process.on(signal, () => void instance.stop(signal, EXIT.ok));
97
100
  }
98
101
  process.on("SIGPIPE", () => {});
99
102
  // Last resort: children never outlive an exiting supervisor (FAILURE_MODEL §2).
100
- process.on("exit", () => {
101
- for (const child of instance.processes.list()) {
102
- try {
103
- process.kill(-child.pid, "SIGKILL");
104
- } catch {
105
- // Already gone.
106
- }
107
- }
108
- });
103
+ process.on("exit", () => instance.processes.killAll());
109
104
  process.on("uncaughtException", (error) => {
110
105
  mirror(`${JSON.stringify({ level: "error", event: "uncaught", message: error.message })}\n`);
111
106
  void instance.stop("uncaught exception", EXIT.failure);
@@ -128,7 +123,7 @@ async function main(argv: readonly string[]): Promise<number> {
128
123
  }
129
124
  const [mode, ...rest] = positionals;
130
125
  if (mode === "service" && !values.help)
131
- return service(rest, values.home, values["no-start"] === true);
126
+ return await service(rest, values.home, values["no-start"] === true);
132
127
  if (values.help || (mode !== "host" && mode !== "daemon") || rest.length > 0) {
133
128
  (values.help ? process.stdout : process.stderr).write(`${USAGE}\n`);
134
129
  return values.help ? EXIT.ok : EXIT.usage;
@@ -185,7 +180,11 @@ async function main(argv: readonly string[]): Promise<number> {
185
180
  }
186
181
 
187
182
  /** `mostra-runtime service …`: the home's login service, as one JSON line (D62, RT-08). */
188
- function service(args: readonly string[], home: string | undefined, noStart: boolean): number {
183
+ async function service(
184
+ args: readonly string[],
185
+ home: string | undefined,
186
+ noStart: boolean,
187
+ ): Promise<number> {
189
188
  const [action, ...extra] = args;
190
189
  if ((action !== "install" && action !== "uninstall" && action !== "status") || extra.length > 0) {
191
190
  process.stderr.write(`${USAGE}\n`);
@@ -200,15 +199,18 @@ function service(args: readonly string[], home: string | undefined, noStart: boo
200
199
  const resolved = resolveHomePath({ home, env: process.env });
201
200
  mkdirSync(resolved, { recursive: true, mode: 0o700 });
202
201
  const spec = {
203
- home: realpathSync(resolved),
202
+ // As the daemon spells its home, so the service's name and hash are the daemon's (D82).
203
+ home: realPath(resolved),
204
204
  node: process.execPath,
205
205
  entry: fileURLToPath(import.meta.url),
206
206
  };
207
+ // Who asks, should a Windows uninstall stop the daemon over its pipe.
208
+ const client = { name: "mostra-runtime-service", version: runtimeVersion() };
207
209
  const status =
208
210
  action === "install"
209
- ? installService(spec, { noStart })
211
+ ? await installService(spec, { noStart, client })
210
212
  : action === "uninstall"
211
- ? uninstallService(spec, { noStart })
213
+ ? await uninstallService(spec, { noStart, client })
212
214
  : serviceStatus(spec);
213
215
  process.stdout.write(`${JSON.stringify({ status: "ok", action, service: status })}\n`);
214
216
  return EXIT.ok;
@@ -13,7 +13,7 @@
13
13
  * When `pages/`, `"use server"` modules or `live.ts` change, the generated entry is written again.
14
14
  */
15
15
  import { createHash, timingSafeEqual } from "node:crypto";
16
- import { mkdir, readdir, readFile, rm, symlink, writeFile } from "node:fs/promises";
16
+ import { mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises";
17
17
  import {
18
18
  createServer as createHttpServer,
19
19
  type IncomingMessage,
@@ -25,6 +25,7 @@ import tailwind from "@tailwindcss/vite";
25
25
  import react from "@vitejs/plugin-react";
26
26
  import { parseSync } from "oxc-parser";
27
27
  import { build, createServer, type Plugin, type ViteDevServer } from "vite";
28
+ import { linkDirectory, pathKey } from "../../platform/index.ts";
28
29
  import type { SupervisorConnection } from "../../processes/index.ts";
29
30
  import {
30
31
  DEV_SECRET_HEADER,
@@ -95,7 +96,7 @@ export async function startDev(
95
96
  await mkdir(generated, { recursive: true });
96
97
  for (const [name, text] of Object.entries(STAGING_FILES)) await writeFile(join(root, name), text);
97
98
  await rm(join(root, "node_modules"), { force: true, recursive: true });
98
- await symlink(request.nodeModules, join(root, "node_modules"), "dir");
99
+ await linkDirectory(request.nodeModules, join(root, "node_modules"));
99
100
  await writeFile(join(generated, "styles.css"), `@import "tailwindcss" source("../source");\n`);
100
101
  await mkdir(request.outDir, { recursive: true });
101
102
  // Vite's pre-bundled dependencies live in the session's root (`cacheDir` below); they are
@@ -114,7 +115,7 @@ export async function startDev(
114
115
  const refreshServerModules = (): void => {
115
116
  serverModules.clear();
116
117
  for (const [module, entries] of scan.serverModules)
117
- serverModules.set(join(sourceDir, module), entries);
118
+ serverModules.set(pathKey(join(sourceDir, module)), entries);
118
119
  };
119
120
  refreshServerModules();
120
121
  const writeEntry = async (): Promise<void> => {
@@ -337,11 +338,14 @@ export async function startDev(
337
338
  * statically.
338
339
  */
339
340
  export function manifestExportPlugin(entryFile: string): Plugin {
341
+ // Vite names modules with `/` on every platform (`C:/…` on Windows), so the entry is compared
342
+ // as the platform layer spells paths, never as the system does.
343
+ const entryKey = pathKey(entryFile);
340
344
  return {
341
345
  name: "mostra:dev-manifest-export",
342
346
  enforce: "pre",
343
347
  transform(code, id) {
344
- if (id.split("?")[0] !== entryFile || !/\.[jt]sx$/.test(entryFile)) return null;
348
+ if (pathKey(id.split("?")[0] ?? "") !== entryKey || !/\.[jt]sx$/.test(entryFile)) return null;
345
349
  const parsed = parseSync(entryFile, code, {
346
350
  lang: entryFile.endsWith(".tsx") ? "tsx" : "jsx",
347
351
  });
@@ -10,6 +10,7 @@ import { compile } from "@mdx-js/mdx";
10
10
  import remarkFrontmatter from "remark-frontmatter";
11
11
  import remarkGfm from "remark-gfm";
12
12
  import type { Plugin } from "vite";
13
+ import { isUnder, pathKey } from "../../platform/index.ts";
13
14
  import type { ServerFunctionEntry } from "../types.ts";
14
15
  import { SCRIPT, startsWithUseServer } from "./scan.ts";
15
16
 
@@ -54,7 +55,7 @@ export function fieldHookUsePlugin(
54
55
  uses: FieldHookUse[],
55
56
  ): Plugin {
56
57
  const inside = (file: string, dir: string | undefined): boolean =>
57
- dir !== undefined && (file === dir || file.startsWith(`${dir}/`));
58
+ dir !== undefined && isUnder(file, dir);
58
59
  return {
59
60
  name: "mostra:field-hook-use",
60
61
  enforce: "pre",
@@ -68,7 +69,8 @@ export function fieldHookUsePlugin(
68
69
  inside(file, roots.runtimeDir)
69
70
  )
70
71
  return null;
71
- if (!uses.some((use) => use.importer === file)) uses.push({ importer: file });
72
+ if (!uses.some((use) => pathKey(use.importer) === pathKey(file)))
73
+ uses.push({ importer: file });
72
74
  return null;
73
75
  },
74
76
  };
@@ -92,7 +94,8 @@ const STUB_PREFIX = "\0mostra-server-reference:";
92
94
 
93
95
  /**
94
96
  * Replaces `"use server"` modules with their client stubs. `modules` maps each module's absolute
95
- * path to its exports, from the scan.
97
+ * path, as its {@link pathKey}, to its exports, from the scan: bundlers spell Windows paths with
98
+ * `/`, the file system with `\\`.
96
99
  */
97
100
  export function serverClientStubPlugin(
98
101
  modules: ReadonlyMap<string, readonly ServerFunctionEntry[]>,
@@ -107,7 +110,9 @@ export function serverClientStubPlugin(
107
110
  if (source.startsWith(STUB_PREFIX)) return source;
108
111
  const resolved = await this.resolve(source, importer, { ...options, skipSelf: true });
109
112
  const file = resolved?.id.split("?")[0];
110
- return file !== undefined && modules.has(file) ? `${STUB_PREFIX}${file}.mjs` : null;
113
+ return file !== undefined && modules.has(pathKey(file))
114
+ ? `${STUB_PREFIX}${pathKey(file)}.mjs`
115
+ : null;
111
116
  },
112
117
  load(id) {
113
118
  if (!id.startsWith(STUB_PREFIX)) return null;
@@ -118,7 +123,7 @@ export function serverClientStubPlugin(
118
123
  // directive, but without a stub, would ship its server code to every viewer.
119
124
  transform(code, id) {
120
125
  const file = id.split("?")[0] ?? id;
121
- if (!file.startsWith(`${sourceDir}/`) || modules.has(file)) return null;
126
+ if (!isUnder(file, sourceDir) || modules.has(pathKey(file))) return null;
122
127
  if (!SCRIPT.has(extname(file))) return null;
123
128
  if (startsWithUseServer(file, code) !== true) return null;
124
129
  return this.error(
@@ -149,7 +154,7 @@ export interface BuildInputs {
149
154
  * later change to them would go unnoticed.
150
155
  */
151
156
  export function confinePlugin(inputs: BuildInputs): Plugin {
152
- const under = (file: string, dir: string): boolean => file.startsWith(`${dir}/`);
157
+ const under = (file: string, dir: string): boolean => isUnder(file, dir);
153
158
  const ours = (file: string): boolean =>
154
159
  under(file, inputs.sourceDir) || under(file, inputs.generatedDir);
155
160
  const packaged = (file: string): boolean => inputs.packageRoots.some((root) => under(file, root));
@@ -168,7 +173,7 @@ export function confinePlugin(inputs: BuildInputs): Plugin {
168
173
  if (from === undefined || source.startsWith("\0")) return null;
169
174
  const fromPackage = !ours(from);
170
175
  if (fromPackage && !packaged(from)) return null;
171
- const bare = !source.startsWith(".") && !source.startsWith("/");
176
+ const bare = !source.startsWith(".") && !source.startsWith("/") && !isAbsolute(source);
172
177
  const resolved = await this.resolve(source, importer, { ...options, skipSelf: true });
173
178
  if (!resolved || resolved.external) return resolved;
174
179
  const id = resolved.id.split("?")[0] ?? resolved.id;
@@ -6,13 +6,14 @@
6
6
  * Nothing in the artifact runs.
7
7
  */
8
8
  import type { Dirent } from "node:fs";
9
- import { mkdir, readdir, realpath, rm, symlink, writeFile } from "node:fs/promises";
9
+ import { mkdir, readdir, realpath, rm, writeFile } from "node:fs/promises";
10
10
  import { join, relative } from "node:path";
11
11
  import { stripVTControlCharacters } from "node:util";
12
12
  import { createDiagnostic, type Diagnostic } from "@mostra/protocol";
13
13
  import tailwind from "@tailwindcss/vite";
14
14
  import react from "@vitejs/plugin-react";
15
15
  import { build, type InlineConfig, type PluginOption } from "vite";
16
+ import { isUnder, linkDirectory, pathKey } from "../../platform/index.ts";
16
17
  import type { FieldCoverage } from "../coverage.ts";
17
18
  import {
18
19
  type BuildRequest,
@@ -140,12 +141,16 @@ export function diagnose(error: unknown, sourceDir: string): Diagnostic {
140
141
  };
141
142
  const first = failure.errors?.[0] ?? failure;
142
143
  // Bundler messages carry terminal colours; diagnostics are plain text.
143
- const rawMessage = stripVTControlCharacters(first.message ?? String(error)).replaceAll(
144
- `${sourceDir}/`,
145
- "",
146
- );
144
+ // Paths in the message as the bundler spells them (`/`-separated on Windows too).
145
+ const rawMessage = stripVTControlCharacters(first.message ?? String(error))
146
+ .replaceAll(`${sourceDir}/`, "")
147
+ .replaceAll(`${sourceDir.replaceAll("\\", "/")}/`, "")
148
+ .replaceAll(`${sourceDir}\\`, "");
147
149
  const file = first.loc?.file ?? first.id;
148
- const inSource = file?.startsWith(sourceDir) ? relative(sourceDir, file) : undefined;
150
+ const inSource =
151
+ file !== undefined && isUnder(file, sourceDir)
152
+ ? relative(sourceDir, file).replaceAll("\\", "/")
153
+ : undefined;
149
154
  const location =
150
155
  inSource !== undefined
151
156
  ? { file: inSource, line: first.loc?.line ?? 1, column: (first.loc?.column ?? 0) + 1 }
@@ -216,7 +221,8 @@ export async function packageRoots(nodeModules: string): Promise<string[]> {
216
221
  } catch {
217
222
  continue; // A dangling link brings nothing in.
218
223
  }
219
- const store = dir.lastIndexOf("/.pnpm/");
224
+ // pnpm's store, found however the platform spells separators (the key keeps the length).
225
+ const store = pathKey(dir).lastIndexOf("/.pnpm/");
220
226
  const root = store === -1 ? dir : dir.slice(0, store + "/.pnpm".length);
221
227
  if (roots.has(root)) continue;
222
228
  roots.add(root);
@@ -257,7 +263,7 @@ export async function buildSpa(input: BuildRequest): Promise<BuildResponse> {
257
263
  packageRoots: await packageRoots(request.nodeModules),
258
264
  };
259
265
  await rm(join(request.stagingDir, "node_modules"), { force: true, recursive: true });
260
- await symlink(request.nodeModules, join(request.stagingDir, "node_modules"), "dir");
266
+ await linkDirectory(request.nodeModules, join(request.stagingDir, "node_modules"));
261
267
  await writeFile(
262
268
  join(request.stagingDir, "index.html"),
263
269
  html(request.manifest.title, request.versionId),
@@ -267,7 +273,7 @@ export async function buildSpa(input: BuildRequest): Promise<BuildResponse> {
267
273
  if (scan.hasLive) await writeFile(join(generated, "mostra-env.d.ts"), LIVE_DECLARATION);
268
274
 
269
275
  const serverModules = new Map<string, readonly ServerFunctionEntry[]>(
270
- [...scan.serverModules].map(([module, entries]) => [join(sourceDir, module), entries]),
276
+ [...scan.serverModules].map(([module, entries]) => [pathKey(join(sourceDir, module)), entries]),
271
277
  );
272
278
  // Packages that use the field hooks themselves open the version's coverage (D109).
273
279
  const hookUses: FieldHookUse[] = [];
@@ -48,6 +48,8 @@ export {
48
48
  type VersionRegistry,
49
49
  } from "./types.ts";
50
50
 
51
+ import { baseEnvironment } from "../platform/index.ts";
52
+
51
53
  /** How long one build may take (FAILURE_MODEL §9). */
52
54
  export const BUILD_TIMEOUT_MS = 180_000;
53
55
 
@@ -187,12 +189,7 @@ export function createSpaRenderMode(options: SpaRenderModeOptions): RenderMode {
187
189
  const timeoutMs = options.timeoutMs ?? BUILD_TIMEOUT_MS;
188
190
  const env = options.env ?? process.env;
189
191
  // The builder gets only what it needs: no secrets, nothing that could reach a bundle.
190
- const childEnv: Environment = {
191
- PATH: env["PATH"] ?? "/usr/bin:/bin",
192
- HOME: env["HOME"] ?? "/",
193
- NODE_ENV: "production",
194
- ...(env["TMPDIR"] ? { TMPDIR: env["TMPDIR"] } : {}),
195
- };
192
+ const childEnv: Environment = { ...baseEnvironment(env), NODE_ENV: "production" };
196
193
 
197
194
  return {
198
195
  id: "spa",
@@ -16,10 +16,11 @@ if (entry === undefined) {
16
16
  console.error("The install child needs the installer's entry as its first argument.");
17
17
  process.exit(2);
18
18
  }
19
- // Not detached: pnpm stays in this child's process group, which the supervisor and the disconnect
20
- // rule both end as a whole.
19
+ // Not detached: pnpm stays in this child's process group (on Windows its Job Object), which the
20
+ // supervisor and the disconnect rule both end as a whole. No console window opens on Windows.
21
21
  const installer = spawn(process.execPath, [entry, ...args], {
22
22
  stdio: ["ignore", "inherit", "inherit"],
23
+ windowsHide: true,
23
24
  });
24
25
  installer.on("error", (error) => {
25
26
  console.error(`The installer couldn't start: ${error.message}`);
package/src/deps/index.ts CHANGED
@@ -20,8 +20,8 @@
20
20
  * ```
21
21
  */
22
22
  import { randomBytes } from "node:crypto";
23
- import { existsSync, readlinkSync } from "node:fs";
24
- import { lstat, mkdir, readdir, readFile, rename, rm, symlink, writeFile } from "node:fs/promises";
23
+ import { existsSync } from "node:fs";
24
+ import { lstat, mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises";
25
25
  import { networkInterfaces } from "node:os";
26
26
  import { join } from "node:path";
27
27
  import {
@@ -43,6 +43,13 @@ import {
43
43
  recordResult,
44
44
  } from "../ledger/index.ts";
45
45
  import type { Environment, Log } from "../log.ts";
46
+ import {
47
+ linkDirectory,
48
+ linkTarget,
49
+ replaceDirectoryLink,
50
+ samePath,
51
+ WINDOWS,
52
+ } from "../platform/index.ts";
46
53
  import type { ProcessManager } from "../processes/index.ts";
47
54
  import { createInstaller, INSTALL_TIMEOUT_MS, type Installer } from "./installer.ts";
48
55
  import { type Lock, lockDigest, lockText, parseLock, pinnedPackages } from "./lock.ts";
@@ -223,8 +230,13 @@ export function isOffline(env: Environment): boolean {
223
230
  );
224
231
  }
225
232
 
226
- /** A shell-safe rendering of `value`, for the commands in diagnostics. */
233
+ /**
234
+ * A shell-safe rendering of `value`, for the commands in diagnostics: POSIX shell quoting, or on
235
+ * Windows the double quotes PowerShell and `cmd` both read (a Windows path holds no `"`), and a
236
+ * plain path with backslashes as it is.
237
+ */
227
238
  function shellQuote(value: string): string {
239
+ if (WINDOWS) return /^[\w@%+=:,./\\-]+$/.test(value) ? value : `"${value}"`;
228
240
  return /^[\w@%+=:,./-]+$/.test(value) ? value : `'${value.replaceAll("'", `'\\''`)}'`;
229
241
  }
230
242
 
@@ -369,7 +381,7 @@ export function createDependencies(options: DependenciesOptions): Dependencies {
369
381
  const work = join(dirs.tmp, `resolve-${randomBytes(6).toString("hex")}`);
370
382
  await mkdir(work);
371
383
  try {
372
- await symlink(warm.nodeModules, join(work, "warm"), "dir");
384
+ await linkDirectory(warm.nodeModules, join(work, "warm"));
373
385
  await writeFile(join(work, "package.json"), manifestOf(input.pins));
374
386
  if (input.previous !== undefined)
375
387
  await writeFile(join(work, "pnpm-lock.yaml"), input.previous);
@@ -412,16 +424,9 @@ export function createDependencies(options: DependenciesOptions): Dependencies {
412
424
  /** Points a layout's `warm` symlink at the current warm set (the runtime may have moved). */
413
425
  const relinkWarm = async (dir: string): Promise<void> => {
414
426
  const link = join(dir, "warm");
415
- let target: string | undefined;
416
- try {
417
- target = readlinkSync(link);
418
- } catch {
419
- target = undefined;
420
- }
421
- if (target === warm.nodeModules) return;
422
- const fresh = `${link}.${randomBytes(4).toString("hex")}`;
423
- await symlink(warm.nodeModules, fresh, "dir");
424
- await rename(fresh, link);
427
+ const target = await linkTarget(link);
428
+ if (target !== undefined && samePath(target, warm.nodeModules)) return;
429
+ await replaceDirectoryLink(warm.nodeModules, link);
425
430
  };
426
431
 
427
432
  /**
@@ -456,7 +461,7 @@ export function createDependencies(options: DependenciesOptions): Dependencies {
456
461
  await rm(dir, { recursive: true, force: true });
457
462
  await mkdir(dir, { recursive: true });
458
463
  try {
459
- await symlink(warm.nodeModules, join(dir, "warm"), "dir");
464
+ await linkDirectory(warm.nodeModules, join(dir, "warm"));
460
465
  await writeFile(join(dir, "package.json"), manifestOf(lock.packages));
461
466
  await writeFile(join(dir, "pnpm-lock.yaml"), pnpm);
462
467
  const outcome = await install().run({
@@ -536,7 +541,7 @@ export function createDependencies(options: DependenciesOptions): Dependencies {
536
541
  await rm(dir, { recursive: true, force: true });
537
542
  await mkdir(dir, { recursive: true });
538
543
  try {
539
- await symlink(warm.nodeModules, join(dir, "warm"), "dir");
544
+ await linkDirectory(warm.nodeModules, join(dir, "warm"));
540
545
  await writeFile(
541
546
  join(dir, "package.json"),
542
547
  `${JSON.stringify(
package/src/deps/warm.ts CHANGED
@@ -3,10 +3,10 @@
3
3
  * install. `@mostra/warm`'s `dependencies` are the warm packages; its `node_modules` is the layout.
4
4
  */
5
5
  import { existsSync, readFileSync, realpathSync } from "node:fs";
6
- import { dirname, join, resolve } from "node:path";
7
- import { fileURLToPath } from "node:url";
6
+ import { join, resolve } from "node:path";
8
7
  import { createDiagnostic, RpcError } from "@mostra/protocol";
9
8
  import type { Environment } from "../log.ts";
9
+ import { runtimeRoot } from "../platform/index.ts";
10
10
 
11
11
  /** The warm set: where its layout is and what versions it holds. */
12
12
  export interface WarmSet {
@@ -16,20 +16,7 @@ export interface WarmSet {
16
16
  readonly packages: Readonly<Record<string, string>>;
17
17
  }
18
18
 
19
- /** The directory of `@mostra/runtime`'s package.json. */
20
- export function runtimeRoot(): string {
21
- let dir = dirname(fileURLToPath(import.meta.url));
22
- for (;;) {
23
- const manifest = join(dir, "package.json");
24
- if (existsSync(manifest)) {
25
- const { name } = JSON.parse(readFileSync(manifest, "utf8")) as { name?: string };
26
- if (name === "@mostra/runtime") return dir;
27
- }
28
- const parent = dirname(dir);
29
- if (parent === dir) throw new Error("Couldn't find @mostra/runtime's package.json.");
30
- dir = parent;
31
- }
32
- }
19
+ export { runtimeRoot };
33
20
 
34
21
  function warmMissing(message: string): RpcError {
35
22
  return new RpcError(createDiagnostic("MOSTRA_ENV_WARM_MISSING", { message }));
package/src/dev/index.ts CHANGED
@@ -17,7 +17,7 @@
17
17
 
18
18
  import { createHash, randomBytes } from "node:crypto";
19
19
  import { type FSWatcher, watch } from "node:fs";
20
- import { copyFile, mkdir, readdir, readFile, rm, stat, unlink, writeFile } from "node:fs/promises";
20
+ import { copyFile, mkdir, readdir, readFile, stat, unlink, writeFile } from "node:fs/promises";
21
21
  import { dirname, join } from "node:path";
22
22
  import {
23
23
  ArtifactId,
@@ -38,13 +38,9 @@ import { type Dependencies, lockKey } from "../deps/index.ts";
38
38
  import type { Faults } from "../faults.ts";
39
39
  import type { Gate } from "../gate.ts";
40
40
  import type { Log } from "../log.ts";
41
+ import { removeTree } from "../platform/index.ts";
41
42
  import { handler, type MethodHandler, type Session } from "../protocol-server/index.ts";
42
- import {
43
- extractManifest,
44
- listSource,
45
- type ResolvedSource,
46
- resolveSource,
47
- } from "../publish/index.ts";
43
+ import { defaultTitle, extractManifest, listSource, resolveSource } from "../publish/index.ts";
48
44
  import type { Registry } from "../registry/index.ts";
49
45
  import { type Sandbox, type SandboxOptions, startSandbox } from "../verify/index.ts";
50
46
 
@@ -98,7 +94,7 @@ export async function recoverDev(home: string, log: Log): Promise<void> {
98
94
  } catch {
99
95
  return;
100
96
  }
101
- for (const name of left) await rm(join(devRoot(home), name), { recursive: true, force: true });
97
+ for (const name of left) await removeTree(join(devRoot(home), name));
102
98
  if (left.length > 0) log.info("dev.sessions_removed", { count: left.length });
103
99
  }
104
100
 
@@ -177,14 +173,24 @@ export function createDev(options: DevOptions): Dev {
177
173
  let manifestKey = "";
178
174
  let artifactId = "";
179
175
  const mirrored = new Map<string, string>();
176
+ /** When each mirrored file was first missed: a save that moves the old file aside first. */
177
+ const missing = new Map<string, number>();
180
178
 
181
- /** Copies changed files into the mirror and removes deleted ones; what changed. */
179
+ /**
180
+ * Copies changed files into the mirror and removes deleted ones; what changed. Editors save
181
+ * in several ways (in place, a temporary file renamed over the old one, the old one renamed
182
+ * to a backup first), and on Windows an editor may hold a file it is writing so that nothing
183
+ * else can read it: a file that can't be read now is left for the next sync, never recorded,
184
+ * and a file is removed from the mirror only once it has been missing for
185
+ * {@link MISSING_GRACE_MS}, so a save never looks like a deletion (WP-W2).
186
+ */
182
187
  const sync = async (): Promise<DevChange[]> => {
183
188
  const files = await listSource(source);
184
189
  const changed: DevChange[] = [];
185
190
  const seen = new Set<string>();
186
191
  for (const file of files) {
187
192
  seen.add(file.path);
193
+ missing.delete(file.path);
188
194
  let info: Awaited<ReturnType<typeof stat>>;
189
195
  try {
190
196
  info = await stat(file.absolute);
@@ -195,13 +201,23 @@ export function createDev(options: DevOptions): Dev {
195
201
  const before = mirrored.get(file.path);
196
202
  if (before === key) continue;
197
203
  const target = join(root, "source", ...file.path.split("/"));
198
- await mkdir(dirname(target), { recursive: true });
199
- await copyFile(file.absolute, target);
204
+ try {
205
+ await mkdir(dirname(target), { recursive: true });
206
+ await copyFile(file.absolute, target);
207
+ } catch (error) {
208
+ log.info("dev.sync_deferred", { sessionId, file: file.path, error });
209
+ continue;
210
+ }
200
211
  mirrored.set(file.path, key);
201
212
  changed.push({ file: file.path, kind: before === undefined ? "add" : "change" });
202
213
  }
214
+ const now = Date.now();
203
215
  for (const path of [...mirrored.keys()]) {
204
216
  if (seen.has(path)) continue;
217
+ const since = missing.get(path) ?? now;
218
+ missing.set(path, since);
219
+ if (now - since < MISSING_GRACE_MS) continue;
220
+ missing.delete(path);
205
221
  mirrored.delete(path);
206
222
  await unlink(join(root, "source", ...path.split("/"))).catch(() => {});
207
223
  changed.push({ file: path, kind: "unlink" });
@@ -220,7 +236,7 @@ export function createDev(options: DevOptions): Dev {
220
236
  source.entry,
221
237
  await readFile(join(root, "source", source.entry), "utf8"),
222
238
  );
223
- const manifest = extracted.manifest ?? { title: titleOf(source) };
239
+ const manifest = extracted.manifest ?? { title: defaultTitle(source) };
224
240
  const artifactId =
225
241
  manifest.id ??
226
242
  options.registry.artifactAt(source.bindingPath) ??
@@ -369,7 +385,9 @@ export function createDev(options: DevOptions): Dev {
369
385
  await child?.stop().catch(() => {});
370
386
  await sandbox?.close().catch(() => {});
371
387
  locksInUse.delete(sessionId);
372
- await rm(dir, { recursive: true, force: true });
388
+ // Through the platform layer: on Windows a file the dev server or an antivirus scan still
389
+ // holds for a moment refuses removal, which it retries (D150 item 8).
390
+ await removeTree(dir);
373
391
  };
374
392
  const stop = async (): Promise<void> => {
375
393
  if (closed) return;
@@ -500,12 +518,12 @@ export function createDev(options: DevOptions): Dev {
500
518
  };
501
519
  }
502
520
 
503
- /** The title of a source without a manifest: its directory's or file's name (INTERFACES §2.2). */
504
- function titleOf(source: ResolvedSource): string {
505
- const name =
506
- source.kind === "dir" ? source.root.split("/").at(-1) : source.entry.replace(/\.[^.]+$/, "");
507
- return name || "Untitled";
508
- }
521
+ /**
522
+ * How long a mirrored file must stay missing before `mostra dev` removes it: an editor that moves
523
+ * the old file aside before writing the new one leaves a gap of milliseconds, a deletion lasts.
524
+ * The 1 s comparison notices the removal within this and a second more.
525
+ */
526
+ const MISSING_GRACE_MS = 1500;
509
527
 
510
528
  const CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
511
529
 
package/src/faults.ts CHANGED
@@ -14,7 +14,7 @@
14
14
  import type { Environment } from "./log.ts";
15
15
 
16
16
  /** What a fault point does. */
17
- export type FaultAction = "throw" | "crash" | "hang";
17
+ export type FaultAction = "throw" | "throw-once" | "crash" | "hang";
18
18
 
19
19
  /** The test fault points of one instance. */
20
20
  export interface Faults {
@@ -47,7 +47,10 @@ export function faultsFrom(env: Environment): Faults {
47
47
  const separator = entry.lastIndexOf(":");
48
48
  const point = entry.slice(0, separator).trim();
49
49
  const action = entry.slice(separator + 1).trim();
50
- if (point && (action === "throw" || action === "crash" || action === "hang"))
50
+ if (
51
+ point &&
52
+ (action === "throw" || action === "throw-once" || action === "crash" || action === "hang")
53
+ )
51
54
  configured.set(point, action);
52
55
  }
53
56
  return {
@@ -55,6 +58,10 @@ export function faultsFrom(env: Environment): Faults {
55
58
  at(point) {
56
59
  const action = configured.get(point);
57
60
  if (action === "throw") throw new InjectedFault(point);
61
+ if (action === "throw-once") {
62
+ configured.delete(point);
63
+ throw new InjectedFault(point);
64
+ }
58
65
  if (action === "crash") {
59
66
  process.kill(process.pid, "SIGKILL");
60
67
  // The signal is delivered at once; block until it lands so no later step runs.
@@ -14,7 +14,6 @@ import {
14
14
  mkdirSync,
15
15
  openSync,
16
16
  readFileSync,
17
- renameSync,
18
17
  writeSync,
19
18
  } from "node:fs";
20
19
  import { join } from "node:path";
@@ -30,6 +29,7 @@ import {
30
29
  import { appendEvent } from "../interaction/index.ts";
31
30
  import type { Ledger, LedgerDb } from "../ledger/index.ts";
32
31
  import type { Log } from "../log.ts";
32
+ import { renamePathSync } from "../platform/index.ts";
33
33
 
34
34
  /** Crockford base32, the alphabet of every Mostra ID body (D77). */
35
35
  const CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
@@ -127,7 +127,7 @@ export function capabilityKey(home: string, log: Log): Buffer {
127
127
  } finally {
128
128
  closeSync(fd);
129
129
  }
130
- renameSync(aside, file);
130
+ renamePathSync(aside, file);
131
131
  chmodSync(file, 0o600);
132
132
  return key;
133
133
  }