@mostra/runtime 0.0.0-stage → 0.1.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 (114) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +39 -2
  3. package/dist/bin.d.ts +1 -0
  4. package/dist/bin.js +236 -0
  5. package/dist/bin.js.map +1 -0
  6. package/dist/builder/child/main.d.ts +1 -0
  7. package/dist/builder/child/main.js +1408 -0
  8. package/dist/builder/child/main.js.map +1 -0
  9. package/dist/child-xrHmytks.js +49 -0
  10. package/dist/child-xrHmytks.js.map +1 -0
  11. package/dist/deps/child/install.d.ts +1 -0
  12. package/dist/deps/child/install.js +33 -0
  13. package/dist/deps/child/install.js.map +1 -0
  14. package/dist/index.d.ts +221 -0
  15. package/dist/index.d.ts.map +1 -0
  16. package/dist/index.js +3 -0
  17. package/dist/instance-D7_UVdoN.js +15752 -0
  18. package/dist/instance-D7_UVdoN.js.map +1 -0
  19. package/dist/types-NjNy7gXX.js +57 -0
  20. package/dist/types-NjNy7gXX.js.map +1 -0
  21. package/package.json +87 -3
  22. package/src/actions/index.ts +622 -0
  23. package/src/addressing/index.ts +281 -0
  24. package/src/bin.ts +240 -0
  25. package/src/builder/child/dev.ts +383 -0
  26. package/src/builder/child/fields.ts +363 -0
  27. package/src/builder/child/main.ts +47 -0
  28. package/src/builder/child/plugins.ts +195 -0
  29. package/src/builder/child/scan.ts +459 -0
  30. package/src/builder/child/spa.ts +348 -0
  31. package/src/builder/coverage.ts +72 -0
  32. package/src/builder/index.ts +406 -0
  33. package/src/builder/types.ts +180 -0
  34. package/src/deps/child/install.ts +30 -0
  35. package/src/deps/index.ts +918 -0
  36. package/src/deps/installer.ts +321 -0
  37. package/src/deps/lock.ts +82 -0
  38. package/src/deps/scan.ts +266 -0
  39. package/src/deps/specifier.ts +64 -0
  40. package/src/deps/warm.ts +57 -0
  41. package/src/dev/index.ts +518 -0
  42. package/src/faults.ts +65 -0
  43. package/src/gate.ts +55 -0
  44. package/src/gateway/actions.ts +268 -0
  45. package/src/gateway/browser.ts +650 -0
  46. package/src/gateway/capabilities.ts +739 -0
  47. package/src/gateway/controls.ts +91 -0
  48. package/src/gateway/dev.ts +119 -0
  49. package/src/gateway/http.ts +229 -0
  50. package/src/gateway/index.ts +1209 -0
  51. package/src/gateway/integrity.ts +117 -0
  52. package/src/gateway/listener.ts +217 -0
  53. package/src/gateway/routes.ts +197 -0
  54. package/src/gateway/serve.ts +138 -0
  55. package/src/gc/index.ts +451 -0
  56. package/src/home/acquire.ts +276 -0
  57. package/src/home/index.ts +16 -0
  58. package/src/home/paths.ts +192 -0
  59. package/src/home/platform.ts +34 -0
  60. package/src/home/record.ts +76 -0
  61. package/src/home/settings.ts +113 -0
  62. package/src/index.ts +30 -0
  63. package/src/instance/index.ts +942 -0
  64. package/src/interaction/ephemeral.ts +300 -0
  65. package/src/interaction/events.ts +355 -0
  66. package/src/interaction/fields.ts +392 -0
  67. package/src/interaction/index.ts +1009 -0
  68. package/src/interaction/outbox.ts +493 -0
  69. package/src/interaction/policy.ts +26 -0
  70. package/src/interaction/results.ts +341 -0
  71. package/src/interaction/runs.ts +313 -0
  72. package/src/interaction/signals.ts +120 -0
  73. package/src/interaction/submissions.ts +585 -0
  74. package/src/interaction/subscriptions.ts +258 -0
  75. package/src/interaction/viewers.ts +173 -0
  76. package/src/interaction/wait.ts +201 -0
  77. package/src/ledger/index.ts +442 -0
  78. package/src/ledger/migrations.ts +583 -0
  79. package/src/ledger/requests.ts +105 -0
  80. package/src/ledger/types.ts +28 -0
  81. package/src/live/index.ts +573 -0
  82. package/src/log.ts +316 -0
  83. package/src/processes/child.ts +67 -0
  84. package/src/processes/environment.ts +64 -0
  85. package/src/processes/identity.ts +191 -0
  86. package/src/processes/index.ts +19 -0
  87. package/src/processes/manager.ts +543 -0
  88. package/src/protocol-server/client.ts +94 -0
  89. package/src/protocol-server/index.ts +91 -0
  90. package/src/protocol-server/server.ts +509 -0
  91. package/src/protocol-server/streams.ts +81 -0
  92. package/src/publish/checks.ts +92 -0
  93. package/src/publish/digest.ts +87 -0
  94. package/src/publish/index.ts +23 -0
  95. package/src/publish/manifest.ts +409 -0
  96. package/src/publish/methods.ts +96 -0
  97. package/src/publish/publisher.ts +913 -0
  98. package/src/publish/source.ts +272 -0
  99. package/src/publish/tar.ts +110 -0
  100. package/src/registry/index.ts +481 -0
  101. package/src/registry/store.ts +136 -0
  102. package/src/secrets/index.ts +223 -0
  103. package/src/service/idle.ts +64 -0
  104. package/src/service/index.ts +3 -0
  105. package/src/service/unit.ts +250 -0
  106. package/src/verify/fields.ts +125 -0
  107. package/src/verify/index.ts +913 -0
  108. package/src/verify/regression.ts +157 -0
  109. package/src/verify/runner.ts +230 -0
  110. package/src/verify/sandbox.ts +407 -0
  111. package/src/verify/typecheck.ts +371 -0
  112. package/src/workers/index.ts +17 -0
  113. package/src/workers/launcher.ts +260 -0
  114. package/src/workers/pool.ts +708 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"main.js","names":["lineColumn","unwrap","createHttpServer","createServer"],"sources":["../../../src/builder/child/fields.ts","../../../src/builder/child/scan.ts","../../../src/builder/child/plugins.ts","../../../src/builder/child/spa.ts","../../../src/builder/child/dev.ts","../../../src/builder/child/main.ts"],"sourcesContent":["/**\n * The field scan (D109): every field ID the artifact's own code can use, read statically from its\n * scripts and MDX pages, for `registry.json`. Literal IDs of `useField` and `useChoice`, the form\n * adapter's `useForm({ id })` and `window.storage` become entries; anything the scan can't follow\n * (a computed ID, a hook passed around or re-exported) makes the coverage open, so a version never\n * orphans a field by a guess. Parsing only; nothing runs.\n */\nimport { readFile } from \"node:fs/promises\";\nimport { extname, join } from \"node:path\";\nimport { compile } from \"@mdx-js/mdx\";\nimport { parseSync } from \"oxc-parser\";\nimport remarkFrontmatter from \"remark-frontmatter\";\nimport remarkGfm from \"remark-gfm\";\nimport type { FieldCoverage, FieldEntry, FieldHook, FieldLocation } from \"../coverage.ts\";\n\ninterface Node {\n readonly type: string;\n readonly start: number;\n readonly end: number;\n readonly [key: string]: unknown;\n}\n\n/** The packages whose hooks name fields, and the hooks they export. */\nconst HOOKS: Readonly<Record<string, ReadonlySet<string>>> = {\n \"@mostra/react\": new Set([\"useField\", \"useChoice\"]),\n \"@mostra/react/form\": new Set([\"useForm\"]),\n};\n\n/** The global objects `storage` hangs off (D53). */\nconst GLOBALS = new Set([\"window\", \"globalThis\", \"self\"]);\n\n/** `window.storage`'s methods. */\nconst STORAGE_METHODS = new Set([\"get\", \"set\", \"delete\", \"list\"]);\n\nconst SCRIPT_LANG: Readonly<Record<string, \"ts\" | \"tsx\" | \"js\" | \"jsx\">> = {\n \".ts\": \"ts\",\n \".mts\": \"ts\",\n \".cts\": \"ts\",\n \".tsx\": \"tsx\",\n \".js\": \"js\",\n \".mjs\": \"js\",\n \".cjs\": \"js\",\n \".jsx\": \"jsx\",\n};\n\nfunction lineColumn(text: string, offset: number): { line: number; column: number } {\n const before = text.slice(0, offset);\n return { line: before.split(\"\\n\").length, column: offset - before.lastIndexOf(\"\\n\") };\n}\n\nfunction each(node: Node, visit: (child: Node, key: string) => void): void {\n for (const [key, value] of Object.entries(node)) {\n if (Array.isArray(value)) {\n for (const item of value)\n if (item && typeof item === \"object\" && \"type\" in item) visit(item as Node, key);\n } else if (value && typeof value === \"object\" && \"type\" in value) visit(value as Node, key);\n }\n}\n\n/** TypeScript wrappers that compile away. */\nconst ERASED = new Set([\n \"TSAsExpression\",\n \"TSSatisfiesExpression\",\n \"TSNonNullExpression\",\n \"TSTypeAssertion\",\n \"ParenthesizedExpression\",\n]);\n\nfunction unwrap(node: Node | undefined): Node | undefined {\n let current = node;\n while (current !== undefined && ERASED.has(current.type))\n current = current[\"expression\"] as Node | undefined;\n return current;\n}\n\n/** A string literal or template's parts: one part for a literal, holes between parts otherwise. */\nfunction idParts(node: Node | undefined): string[] | undefined {\n const target = unwrap(node);\n if (target?.type === \"Literal\" && typeof target[\"value\"] === \"string\") return [target[\"value\"]];\n if (target?.type === \"TemplateLiteral\") {\n const parts = (target[\"quasis\"] as Node[]).map(\n (quasi) => (quasi[\"value\"] as { cooked: string | null }).cooked,\n );\n if (parts.some((part) => part === null)) return undefined;\n return parts as string[];\n }\n return undefined;\n}\n\n/**\n * A literal object's literal string or boolean properties, as they stand after every property\n * in order: a spread or a computed key may override anything before it, so what came before is\n * forgotten (GPT review finding 12); a property the scan can't read is left out.\n */\nfunction literalOptions(node: Node | undefined): Record<string, string | boolean> | undefined {\n const target = unwrap(node);\n if (target?.type !== \"ObjectExpression\") return undefined;\n let out: Record<string, string | boolean> = {};\n for (const property of target[\"properties\"] as Node[]) {\n if (property.type !== \"Property\" || property[\"computed\"]) {\n out = {};\n continue;\n }\n const key = property[\"key\"] as Node;\n const name = key.type === \"Identifier\" ? key[\"name\"] : key[\"value\"];\n const value = unwrap(property[\"value\"] as Node);\n if (\n typeof name === \"string\" &&\n value?.type === \"Literal\" &&\n (typeof value[\"value\"] === \"string\" || typeof value[\"value\"] === \"boolean\")\n ) {\n out[name] = value[\"value\"];\n }\n }\n return out;\n}\n\n/** The scan of one artifact. */\nclass FieldScan {\n readonly entries: FieldEntry[] = [];\n readonly openReasons: { reason: string; location?: FieldLocation }[] = [];\n\n open(reason: string, location?: FieldLocation): void {\n this.openReasons.push({ reason, ...(location ? { location } : {}) });\n }\n\n /** Scans one parsed module; `text` is what offsets refer to. */\n module(file: string, text: string, program: Node): void {\n const at = (node: Node): FieldLocation => ({ file, ...lineColumn(text, node.start) });\n // Local names of the hooks, and namespaces of their packages.\n const hooks = new Map<string, FieldHook>();\n const namespaces = new Map<string, ReadonlySet<string>>();\n for (const statement of program[\"body\"] as Node[]) {\n const source =\n statement.type === \"ImportDeclaration\" ||\n statement.type === \"ExportNamedDeclaration\" ||\n statement.type === \"ExportAllDeclaration\"\n ? ((statement[\"source\"] as Node | null)?.[\"value\"] as string | undefined)\n : undefined;\n const exported = source === undefined ? undefined : HOOKS[source];\n if (!exported) continue;\n if (statement.type !== \"ImportDeclaration\") {\n // Re-exporting a hook hands it to code the scan can't follow.\n this.open(`${file} re-exports from ${source}`, at(statement));\n continue;\n }\n if (statement[\"importKind\"] === \"type\") continue;\n for (const specifier of statement[\"specifiers\"] as Node[]) {\n const local = (specifier[\"local\"] as Node)[\"name\"] as string;\n if (specifier.type === \"ImportNamespaceSpecifier\") namespaces.set(local, exported);\n else if (specifier.type === \"ImportSpecifier\" && specifier[\"importKind\"] !== \"type\") {\n const imported = specifier[\"imported\"] as Node;\n const name = (imported[\"name\"] ?? imported[\"value\"]) as string;\n if (exported.has(name)) hooks.set(local, name as FieldHook);\n }\n }\n }\n\n const hookOf = (callee: Node | undefined): FieldHook | undefined => {\n const target = unwrap(callee);\n if (target?.type === \"Identifier\") return hooks.get(target[\"name\"] as string);\n if (target?.type === \"MemberExpression\" && !target[\"computed\"]) {\n const object = target[\"object\"] as Node;\n const property = (target[\"property\"] as Node)[\"name\"] as string;\n const names =\n object.type === \"Identifier\" ? namespaces.get(object[\"name\"] as string) : undefined;\n if (names?.has(property)) return property as FieldHook;\n }\n return undefined;\n };\n\n const callees = new Set<Node>();\n const visit = (node: Node): void => {\n if (node.type === \"CallExpression\") {\n const callee = node[\"callee\"] as Node;\n const hook = hookOf(callee);\n if (hook) {\n callees.add(unwrap(callee) as Node);\n this.call(hook, node[\"arguments\"] as Node[], at(node));\n }\n // `window.storage.get(…)` and the bare `storage.get(…)` of Claude's artifacts (D53).\n const target = unwrap(callee);\n if (target?.type === \"MemberExpression\" && !target[\"computed\"]) {\n const object = unwrap(target[\"object\"] as Node);\n const method = (target[\"property\"] as Node)[\"name\"] as string;\n const isStorage =\n (object?.type === \"MemberExpression\" &&\n !object[\"computed\"] &&\n (object[\"object\"] as Node).type === \"Identifier\" &&\n GLOBALS.has((object[\"object\"] as Node)[\"name\"] as string) &&\n (object[\"property\"] as Node)[\"name\"] === \"storage\") ||\n (object?.type === \"Identifier\" && object[\"name\"] === \"storage\");\n if (isStorage && STORAGE_METHODS.has(method)) this.storage(at(node));\n }\n }\n // `const s = window.storage` hands storage on: every key is possible.\n if (\n node.type === \"MemberExpression\" &&\n !node[\"computed\"] &&\n (node[\"object\"] as Node).type === \"Identifier\" &&\n GLOBALS.has((node[\"object\"] as Node)[\"name\"] as string) &&\n (node[\"property\"] as Node)[\"name\"] === \"storage\"\n ) {\n this.storage(at(node));\n }\n each(node, (child) => visit(child));\n };\n visit(program);\n\n // A hook referenced anywhere but as a callee is passed around: its IDs are unknowable.\n const references = (node: Node, parentKey: string, parent: Node | undefined): void => {\n if (\n node.type === \"Identifier\" &&\n parentKey !== \"property\" &&\n parentKey !== \"key\" &&\n parent?.type !== \"ImportSpecifier\" &&\n parent?.type !== \"ImportNamespaceSpecifier\"\n ) {\n const name = node[\"name\"] as string;\n if (hooks.has(name) && !callees.has(node)) {\n this.open(`${file} uses ${name} other than by calling it`, at(node));\n }\n const exported = namespaces.get(name);\n if (exported) {\n const member =\n parent?.type === \"MemberExpression\" && parentKey === \"object\" && !parent[\"computed\"]\n ? ((parent[\"property\"] as Node)[\"name\"] as string)\n : undefined;\n const passedOn =\n member === undefined || (exported.has(member) && !callees.has(parent as Node));\n if (passedOn) this.open(`${file} uses ${name} other than by calling its hooks`, at(node));\n }\n }\n each(node, (child, key) => references(child, key, node));\n };\n references(program, \"\", undefined);\n }\n\n storage(location: FieldLocation): void {\n if (this.entries.some((entry) => entry.hook === \"storage\")) return;\n // Personal keys are the viewer's fields under `storage.`; shared ones are artifact state.\n this.entries.push(\n { template: [\"storage.\", \"\"], hook: \"storage\", scope: \"viewer\", location },\n { template: [\"storage.\", \"\"], hook: \"storage\", scope: \"artifact\", location },\n );\n }\n\n call(hook: FieldHook, args: Node[], location: FieldLocation): void {\n const first = args[0];\n if (hook === \"useForm\") {\n const options = unwrap(first);\n // The id that stands: the last one, unless a spread or computed key after it may replace it.\n let idProperty: Node | undefined;\n if (options?.type === \"ObjectExpression\") {\n for (const property of options[\"properties\"] as Node[]) {\n if (property.type !== \"Property\" || property[\"computed\"]) idProperty = undefined;\n else if (\n ((property[\"key\"] as Node)[\"name\"] ?? (property[\"key\"] as Node)[\"value\"]) === \"id\"\n ) {\n idProperty = property;\n }\n }\n }\n const parts = idParts(idProperty?.[\"value\"] as Node | undefined);\n if (!parts) {\n this.open(\"a useForm call without a literal id\", location);\n return;\n }\n // Every registered field is `<id>.<name>` (the form adapter).\n const template = [...parts.slice(0, -1), `${parts.at(-1) as string}.`, \"\"];\n this.entries.push({ template, hook, location });\n return;\n }\n const parts = idParts(first);\n if (!parts) {\n this.open(`a ${hook} call whose ID isn't a string literal or template`, location);\n return;\n }\n // A choice is the field `review.<set>.choice` (D65).\n const wrap = (inner: string[]): string[] => {\n if (hook !== \"useChoice\") return inner;\n const out = [...inner];\n out[0] = `review.${out[0] as string}`;\n out[out.length - 1] = `${out.at(-1) as string}.choice`;\n return out;\n };\n const wrapped = wrap(parts);\n const singleLiteral = parts.length === 1;\n const options = hook === \"useField\" ? literalOptions(args[2]) : undefined;\n // Only `\"artifact\"` takes a field out of drafts; a scope the scan can't read may be the\n // viewer's, which keeps the field covered.\n const scopeOption = options?.[\"scope\"];\n const scope = scopeOption === \"artifact\" || scopeOption === \"viewer\" ? scopeOption : undefined;\n this.entries.push({\n ...(singleLiteral ? { id: wrapped.join(\"\") } : { template: wrapped }),\n hook,\n ...(scope !== undefined ? { scope } : {}),\n ...(typeof options?.[\"label\"] === \"string\" ? { label: options[\"label\"] } : {}),\n ...(typeof options?.[\"required\"] === \"boolean\" ? { required: options[\"required\"] } : {}),\n ...(typeof options?.[\"sensitive\"] === \"boolean\" ? { sensitive: options[\"sensitive\"] } : {}),\n location,\n });\n }\n\n result(): FieldCoverage {\n // A version that declares no field through the hooks may still take answers through the\n // browser protocol itself; the scan can't see those, so nothing is orphaned by a guess.\n if (this.entries.length === 0 && this.openReasons.length === 0) {\n this.open(\"the artifact declares no fields through @mostra/react\");\n }\n return {\n open: this.openReasons.length > 0,\n openReasons: this.openReasons,\n entries: this.entries,\n };\n }\n}\n\n/** Mentions that make a file worth parsing for fields. */\nconst MENTIONS = /@mostra\\/react|storage/;\n\n/** A file that speaks the browser protocol itself writes fields the scan can't follow. */\nconst RAW_PROTOCOL = /_mostra\\/v\\//;\n\n/** Scans the artifact's scripts and MDX pages (`files` are paths inside `sourceDir`). */\nexport async function scanFields(\n sourceDir: string,\n files: readonly string[],\n): Promise<FieldCoverage> {\n const scan = new FieldScan();\n for (const file of [...files].sort()) {\n const ext = extname(file);\n const lang = SCRIPT_LANG[ext];\n if (lang === undefined && ext !== \".mdx\") continue;\n const source = await readFile(join(sourceDir, file), \"utf8\");\n if (RAW_PROTOCOL.test(source)) scan.open(`${file} calls the browser protocol directly`);\n if (!MENTIONS.test(source)) continue;\n let text = source;\n let parseLang: \"ts\" | \"tsx\" | \"js\" | \"jsx\" = lang ?? \"jsx\";\n if (ext === \".mdx\") {\n try {\n const compiled = await compile(\n { value: source, path: file },\n { jsxImportSource: \"react\", remarkPlugins: [remarkFrontmatter, remarkGfm] },\n );\n text = String(compiled.value);\n parseLang = \"js\";\n } catch {\n // The bundler reports the MDX error; nothing here can be known about its fields.\n scan.open(`${file} doesn't compile`);\n continue;\n }\n }\n const parsed = parseSync(file, text, { lang: parseLang });\n if (parsed.errors.length > 0) {\n scan.open(`${file} doesn't parse`);\n continue;\n }\n // MDX offsets refer to the compiled text, so its locations name only the file.\n scan.module(file, text, parsed.program as unknown as Node);\n }\n return scan.result();\n}\n","/**\n * The builder child's static scan of an artifact (INTERFACES §11): its `\"use server\"` modules with\n * their exports and `dryRun()` opt-ins (D54, D55), the live sources of `live.ts` (D56) and the\n * routes of `pages/` (D57). Parsing only; nothing in the artifact runs.\n */\nimport { readdir, readFile } from \"node:fs/promises\";\nimport { extname, join } from \"node:path\";\nimport { createDiagnostic, type Diagnostic } from \"@mostra/protocol\";\nimport { parseSync } from \"oxc-parser\";\nimport type { FieldCoverage } from \"../coverage.ts\";\nimport type { PageRoute, ServerFunctionEntry } from \"../types.ts\";\nimport { scanFields } from \"./fields.ts\";\n\ninterface Node {\n readonly type: string;\n readonly start: number;\n readonly end: number;\n readonly [key: string]: unknown;\n}\n\n/** Every script extension the bundler loads; a \"use server\" module may have any of them. */\nexport const SCRIPT: ReadonlySet<string> = new Set([\n \".ts\",\n \".tsx\",\n \".mts\",\n \".cts\",\n \".js\",\n \".jsx\",\n \".mjs\",\n \".cjs\",\n]);\n\n/** Oxc's language for a script file. */\nfunction langOf(file: string): \"ts\" | \"tsx\" | \"js\" | \"jsx\" {\n const ext = extname(file);\n if (ext === \".tsx\") return \"tsx\";\n if (ext === \".jsx\") return \"jsx\";\n if (ext === \".ts\" || ext === \".mts\" || ext === \".cts\") return \"ts\";\n return \"js\";\n}\n\n/**\n * Whether a script starts with the `\"use server\"` directive. `undefined` when it doesn't parse:\n * the bundler, which parses the same way, then reports the syntax error.\n */\nexport function startsWithUseServer(file: string, text: string): boolean | undefined {\n if (!text.includes(\"use server\")) return false;\n const parsed = parseSync(file, text, { lang: langOf(file) });\n if (parsed.errors.length > 0) return undefined;\n return isServerModule(parsed.program as unknown as Node);\n}\nconst PAGE = new Set([\".tsx\", \".jsx\", \".mdx\"]);\nconst SERVER_PACKAGE = \"@mostra/server\";\n\n/** What the scan found. */\nexport interface ScanResult {\n /** `\"use server\"` modules (paths inside the artifact) with their exports. */\n readonly serverModules: ReadonlyMap<string, readonly ServerFunctionEntry[]>;\n readonly liveSources: readonly { readonly key: string; readonly always?: boolean }[];\n readonly hasLive: boolean;\n readonly pages: readonly PageRoute[];\n /** The field IDs the artifact's own code can use (D109). */\n readonly fields: FieldCoverage;\n readonly diagnostics: readonly Diagnostic[];\n /**\n * Server-code candidates (a script naming `\"use server\"`, or `live.ts`) that don't parse. A\n * build's bundler reports them with full context; `mostra dev`, which bundles server code only\n * from what the scan found, reports them itself.\n */\n readonly unparsed: readonly Diagnostic[];\n}\n\nasync function walk(dir: string, prefix: string, out: string[]): Promise<void> {\n for (const entry of await readdir(dir, { withFileTypes: true })) {\n const path = prefix ? `${prefix}/${entry.name}` : entry.name;\n if (entry.isDirectory()) await walk(join(dir, entry.name), path, out);\n else if (entry.isFile()) out.push(path);\n }\n}\n\nfunction lineColumn(text: string, offset: number): { line: number; column: number } {\n const before = text.slice(0, offset);\n const line = before.split(\"\\n\").length;\n return { line, column: offset - before.lastIndexOf(\"\\n\") };\n}\n\n/** Calls each child node of `node`. */\nfunction children(node: Node, visit: (child: Node, parent: Node, key: string) => void): void {\n for (const [key, value] of Object.entries(node)) {\n if (Array.isArray(value)) {\n for (const item of value)\n if (item && typeof item === \"object\" && \"type\" in item) visit(item as Node, node, key);\n } else if (value && typeof value === \"object\" && \"type\" in value) {\n visit(value as Node, node, key);\n }\n }\n}\n\n/** Whether the module starts with the `\"use server\"` directive. */\nfunction isServerModule(program: Node): boolean {\n for (const statement of program[\"body\"] as Node[]) {\n if (statement.type !== \"ExpressionStatement\" || typeof statement[\"directive\"] !== \"string\")\n return false;\n if (statement[\"directive\"] === \"use server\") return true;\n }\n return false;\n}\n\n/** TypeScript wrappers that compile away: `as`, `satisfies`, `!`, `<T>x` and parentheses. */\nconst ERASED_WRAPPERS = new Set([\n \"TSAsExpression\",\n \"TSSatisfiesExpression\",\n \"TSNonNullExpression\",\n \"TSTypeAssertion\",\n \"TSInstantiationExpression\",\n \"ParenthesizedExpression\",\n]);\n\n/** The expression a wrapper chain wraps: `(async () => 1) satisfies F` is the arrow function. */\nfunction unwrap(node: Node | undefined): Node | undefined {\n let current = node;\n while (current !== undefined && ERASED_WRAPPERS.has(current.type)) {\n current = current[\"expression\"] as Node | undefined;\n }\n return current;\n}\n\nconst isAsyncFunction = (node: Node | undefined): boolean => {\n const target = unwrap(node);\n return (\n target !== undefined &&\n (target.type === \"FunctionDeclaration\" ||\n target.type === \"FunctionExpression\" ||\n target.type === \"ArrowFunctionExpression\") &&\n target[\"async\"] === true\n );\n};\n\n/**\n * Declarations that exist only for the type checker: types, interfaces, overload signatures and\n * anything `declare`d. Enums and namespaces are values at run time, so they are not among them.\n */\nconst isErasedDeclaration = (node: Node): boolean =>\n node[\"declare\"] === true ||\n node.type === \"TSTypeAliasDeclaration\" ||\n node.type === \"TSInterfaceDeclaration\" ||\n node.type === \"TSDeclareFunction\";\n\n/**\n * Reads one `\"use server\"` module: every export must be an async function (React's contract),\n * and an export opts into `verify`'s smoke test when it, or a module-level function it calls,\n * calls `dryRun()` from `@mostra/server` (D55).\n */\nfunction serverExports(\n module: string,\n text: string,\n program: Node,\n diagnostics: Diagnostic[],\n): ServerFunctionEntry[] {\n const dryRunNames = new Set<string>();\n const namespaces = new Set<string>();\n const functions = new Map<string, Node>();\n const exported: { name: string; local: Node | undefined; at: number }[] = [];\n const invalid = (at: number, message: string): void => {\n diagnostics.push(\n createDiagnostic(\"MOSTRA_ACTION_EXPORT_INVALID\", {\n message,\n location: { file: module, ...lineColumn(text, at) },\n }),\n );\n };\n\n const remember = (declaration: Node): void => {\n if (declaration.type === \"FunctionDeclaration\" && declaration[\"id\"]) {\n functions.set((declaration[\"id\"] as Node)[\"name\"] as string, declaration);\n }\n if (declaration.type === \"VariableDeclaration\") {\n for (const declarator of declaration[\"declarations\"] as Node[]) {\n const id = declarator[\"id\"] as Node;\n if (id.type === \"Identifier\" && declarator[\"init\"]) {\n functions.set(id[\"name\"] as string, declarator[\"init\"] as Node);\n }\n }\n }\n };\n\n for (const statement of program[\"body\"] as Node[]) {\n if (\n statement.type === \"ImportDeclaration\" &&\n (statement[\"source\"] as Node)[\"value\"] === SERVER_PACKAGE\n ) {\n for (const specifier of statement[\"specifiers\"] as Node[]) {\n const local = (specifier[\"local\"] as Node)[\"name\"] as string;\n if (specifier.type === \"ImportNamespaceSpecifier\") namespaces.add(local);\n const imported = specifier[\"imported\"] as Node | undefined;\n if (\n specifier.type === \"ImportSpecifier\" &&\n (imported?.[\"name\"] ?? imported?.[\"value\"]) === \"dryRun\"\n ) {\n dryRunNames.add(local);\n }\n }\n } else if (statement.type === \"ExportNamedDeclaration\") {\n if (statement[\"exportKind\"] === \"type\") continue;\n if (statement[\"source\"]) {\n invalid(\n statement.start,\n `${module} re-exports from another module; a \"use server\" module exports only its own async functions.`,\n );\n continue;\n }\n const declaration = statement[\"declaration\"] as Node | null;\n if (declaration) {\n if (isErasedDeclaration(declaration)) continue;\n remember(declaration);\n if (declaration.type === \"FunctionDeclaration\") {\n const name = (declaration[\"id\"] as Node)[\"name\"] as string;\n exported.push({ name, local: declaration, at: declaration.start });\n } else if (declaration.type === \"VariableDeclaration\") {\n for (const declarator of declaration[\"declarations\"] as Node[]) {\n const id = declarator[\"id\"] as Node;\n exported.push({\n name: id.type === \"Identifier\" ? (id[\"name\"] as string) : \"(pattern)\",\n local: (declarator[\"init\"] as Node | null) ?? undefined,\n at: declarator.start,\n });\n }\n } else {\n exported.push({ name: \"(declaration)\", local: declaration, at: declaration.start });\n }\n }\n for (const specifier of (statement[\"specifiers\"] as Node[]) ?? []) {\n if (specifier[\"exportKind\"] === \"type\") continue;\n const name = ((specifier[\"exported\"] as Node)[\"name\"] ??\n (specifier[\"exported\"] as Node)[\"value\"]) as string;\n const local = (specifier[\"local\"] as Node)[\"name\"] as string;\n exported.push({\n name,\n local: { type: \"Ref\", start: specifier.start, end: specifier.end, name: local },\n at: specifier.start,\n });\n }\n } else if (statement.type === \"ExportDefaultDeclaration\") {\n const declaration = statement[\"declaration\"] as Node;\n if (declaration.type === \"FunctionDeclaration\" && declaration[\"id\"]) remember(declaration);\n exported.push({\n name: \"default\",\n local:\n declaration.type === \"Identifier\"\n ? {\n type: \"Ref\",\n start: declaration.start,\n end: declaration.end,\n name: declaration[\"name\"],\n }\n : declaration,\n at: statement.start,\n });\n } else if (statement.type === \"ExportAllDeclaration\") {\n invalid(\n statement.start,\n `${module} re-exports with \\`export *\\`; a \"use server\" module exports only its own async functions.`,\n );\n } else if (!isErasedDeclaration(statement)) {\n remember(statement);\n }\n }\n\n // Which module-level functions call dryRun(), directly or through other module-level functions.\n const calls = new Map<string, Set<string>>();\n const direct = new Set<string>();\n const scan = (node: Node, owner: string): void => {\n if (node.type === \"CallExpression\") {\n const callee = node[\"callee\"] as Node;\n if (callee.type === \"Identifier\") {\n const name = callee[\"name\"] as string;\n if (dryRunNames.has(name)) direct.add(owner);\n else calls.get(owner)?.add(name);\n } else if (\n callee.type === \"MemberExpression\" &&\n !callee[\"computed\"] &&\n (callee[\"object\"] as Node).type === \"Identifier\" &&\n namespaces.has((callee[\"object\"] as Node)[\"name\"] as string) &&\n (callee[\"property\"] as Node)[\"name\"] === \"dryRun\"\n ) {\n direct.add(owner);\n }\n }\n children(node, (child) => scan(child, owner));\n };\n for (const [name, node] of functions) {\n calls.set(name, new Set());\n scan(node, name);\n }\n const optsIn = (name: string, seen = new Set<string>()): boolean => {\n if (direct.has(name)) return true;\n if (seen.has(name)) return false;\n seen.add(name);\n return [...(calls.get(name) ?? [])].some((callee) => optsIn(callee, seen));\n };\n\n const entries: ServerFunctionEntry[] = [];\n for (const { name, local, at } of exported) {\n // Follow `export const x = y` (and `y!`, `y as F`) to the function `y` names.\n let target = unwrap(local?.type === \"Ref\" ? functions.get(local[\"name\"] as string) : local);\n const followed = new Set<string>();\n while (target?.type === \"Identifier\" && !followed.has(target[\"name\"] as string)) {\n followed.add(target[\"name\"] as string);\n target = unwrap(functions.get(target[\"name\"] as string));\n }\n if (!isAsyncFunction(target)) {\n invalid(\n at,\n `The export \\`${name}\\` of ${module} isn't an async function; a \"use server\" module exports only async functions.`,\n );\n continue;\n }\n let dryRun: boolean;\n if (local?.type === \"Ref\") dryRun = optsIn(local[\"name\"] as string);\n else {\n const owner = `export:${name}`;\n calls.set(owner, new Set());\n scan(target as Node, owner);\n dryRun = optsIn(owner);\n }\n entries.push({ id: `${module}#${name}`, module, export: name, dryRun });\n }\n return entries;\n}\n\n/**\n * Whether a `defineLive({ … })` argument says `always: true` (D63): `true` or `false` when the\n * object literal tells, `undefined` when it can't be known without running it (a spread, a\n * computed key, a value other than a literal, or no object literal at all).\n */\nfunction literalAlways(argument: Node | undefined): boolean | undefined {\n if (argument?.type !== \"ObjectExpression\") return undefined;\n let always: boolean | undefined = false;\n for (const property of argument[\"properties\"] as Node[]) {\n if (property.type !== \"Property\" || property[\"computed\"] === true) {\n always = undefined;\n continue;\n }\n const key = property[\"key\"] as Node;\n const name = key.type === \"Identifier\" ? key[\"name\"] : key[\"value\"];\n if (name !== \"always\") continue;\n const value = property[\"value\"] as Node;\n always =\n value.type === \"Literal\" && typeof value[\"value\"] === \"boolean\"\n ? (value[\"value\"] as boolean)\n : undefined;\n }\n return always;\n}\n\n/** The exports of `live.ts` that are `defineLive(...)` calls (D56), with their literal `always`. */\nfunction liveExports(program: Node): { key: string; always?: boolean }[] {\n const keys: { key: string; always?: boolean }[] = [];\n for (const statement of program[\"body\"] as Node[]) {\n if (statement.type !== \"ExportNamedDeclaration\") continue;\n const declaration = statement[\"declaration\"] as Node | null;\n if (declaration?.type !== \"VariableDeclaration\") continue;\n for (const declarator of declaration[\"declarations\"] as Node[]) {\n const id = declarator[\"id\"] as Node;\n const init = declarator[\"init\"] as Node | null;\n const callee = init?.type === \"CallExpression\" ? (init[\"callee\"] as Node) : undefined;\n const calleeName =\n callee?.type === \"Identifier\"\n ? callee[\"name\"]\n : callee?.type === \"MemberExpression\"\n ? (callee[\"property\"] as Node)[\"name\"]\n : undefined;\n if (id.type === \"Identifier\" && calleeName === \"defineLive\") {\n const always = literalAlways((init?.[\"arguments\"] as Node[] | undefined)?.[0]);\n keys.push({ key: id[\"name\"] as string, ...(always === undefined ? {} : { always }) });\n }\n }\n }\n return keys;\n}\n\n/** `pages/reports/[id].tsx` → `/reports/:id`; `index` names its folder (D57). */\nfunction routePath(file: string): string {\n const segments = file\n .slice(\"pages/\".length, file.length - extname(file).length)\n .split(\"/\")\n .filter((segment, index, all) => !(segment === \"index\" && index === all.length - 1))\n .map((segment) => {\n const rest = /^\\[\\.\\.\\.(.+)\\]$/.exec(segment);\n if (rest) return \"*\";\n const param = /^\\[(.+)\\]$/.exec(segment);\n return param ? `:${param[1]}` : segment;\n });\n return `/${segments.join(\"/\")}`;\n}\n\n/** Scans the snapshot in `sourceDir`. */\nexport async function scanArtifact(sourceDir: string): Promise<ScanResult> {\n const files: string[] = [];\n await walk(sourceDir, \"\", files);\n const diagnostics: Diagnostic[] = [];\n const serverModules = new Map<string, ServerFunctionEntry[]>();\n const unparsed: Diagnostic[] = [];\n let liveSources: { key: string; always?: boolean }[] = [];\n for (const file of files.sort()) {\n if (!SCRIPT.has(extname(file))) continue;\n const text = await readFile(join(sourceDir, file), \"utf8\");\n if (!text.includes(\"use server\") && file !== \"live.ts\") continue;\n const parsed = parseSync(file, text, { lang: langOf(file) });\n if (parsed.errors.length > 0) {\n // The bundler reports syntax errors with full context; dev reports them from here.\n const first = parsed.errors[0];\n const offset = first?.labels[0]?.start ?? 0;\n const before = text.slice(0, offset).split(\"\\n\");\n unparsed.push(\n createDiagnostic(\"MOSTRA_BUILD_FAILED\", {\n message: `${file}: ${first?.message ?? \"a syntax error\"}.`,\n location: {\n file,\n line: before.length,\n column: (before.at(-1)?.length ?? 0) + 1,\n },\n }),\n );\n continue;\n }\n const program = parsed.program as unknown as Node;\n if (file === \"live.ts\") liveSources = liveExports(program);\n if (isServerModule(program))\n serverModules.set(file, serverExports(file, text, program, diagnostics));\n }\n const pages = files\n .filter((file) => file.startsWith(\"pages/\") && PAGE.has(extname(file)))\n .sort()\n .map((file) => ({ path: routePath(file), file }));\n const byPath = new Map<string, string>();\n for (const page of pages) {\n const other = byPath.get(page.path);\n if (other) {\n diagnostics.push(\n createDiagnostic(\"MOSTRA_BUILD_FAILED\", {\n message: `${other} and ${page.file} are both the page ${page.path}; keep one.`,\n location: { file: page.file, line: 1, column: 1 },\n }),\n );\n }\n byPath.set(page.path, page.file);\n }\n const fields = await scanFields(sourceDir, files);\n return {\n serverModules,\n liveSources,\n hasLive: files.includes(\"live.ts\"),\n pages,\n fields,\n diagnostics,\n unparsed,\n };\n}\n","/**\n * The Vite plugins of the SPA build (D19 seams 1 and 2): MDX compilation, and the `\"use server\"`\n * client-stub transform, which replaces each server module in the client build with\n * `createServerReference` stubs so no server code reaches the browser (D54).\n */\n\nimport { existsSync, realpathSync } from \"node:fs\";\nimport { extname, isAbsolute, relative } from \"node:path\";\nimport { compile } from \"@mdx-js/mdx\";\nimport remarkFrontmatter from \"remark-frontmatter\";\nimport remarkGfm from \"remark-gfm\";\nimport type { Plugin } from \"vite\";\nimport type { ServerFunctionEntry } from \"../types.ts\";\nimport { SCRIPT, startsWithUseServer } from \"./scan.ts\";\n\n/** Compiles `.mdx` files to JavaScript with React's JSX runtime, frontmatter removed (MDX 3). */\nexport function mdxPlugin(): Plugin {\n return {\n name: \"mostra:mdx\",\n enforce: \"pre\",\n async transform(code, id) {\n const file = id.split(\"?\")[0] ?? id;\n if (!file.endsWith(\".mdx\")) return null;\n const compiled = await compile(\n { value: code, path: file },\n {\n jsxImportSource: \"react\",\n remarkPlugins: [remarkFrontmatter, remarkGfm],\n development: false,\n },\n );\n return { code: String(compiled.value), map: null, moduleType: \"js\" };\n },\n };\n}\n\n/** Where packages outside the artifact use the client runtime's field hooks (D109). */\nexport interface FieldHookUse {\n /** The importing module's path, relative to the build's `node_modules` when it is a package. */\n readonly importer: string;\n}\n\n/**\n * Records every module outside the artifact that imports `@mostra/react` or `@mostra/react/form`\n * (D109): such a package may name fields the artifact's scan can't see, so the version's coverage\n * is open. `@mostra/react` itself and Mostra's generated files don't count. It resolves nothing.\n */\nexport function fieldHookUsePlugin(\n roots: {\n readonly sourceDir: string;\n readonly generatedDir: string;\n readonly runtimeDir?: string;\n },\n uses: FieldHookUse[],\n): Plugin {\n const inside = (file: string, dir: string | undefined): boolean =>\n dir !== undefined && (file === dir || file.startsWith(`${dir}/`));\n return {\n name: \"mostra:field-hook-use\",\n enforce: \"pre\",\n resolveId(source, importer) {\n if (source !== \"@mostra/react\" && source !== \"@mostra/react/form\") return null;\n if (importer === undefined || importer.startsWith(\"\\0\")) return null;\n const file = existsSync(importer) ? realpathSync(importer) : importer;\n if (\n inside(file, roots.sourceDir) ||\n inside(file, roots.generatedDir) ||\n inside(file, roots.runtimeDir)\n )\n return null;\n if (!uses.some((use) => use.importer === file)) uses.push({ importer: file });\n return null;\n },\n };\n}\n\n/** The client stub of one `\"use server\"` module. */\nexport function serverStub(entries: readonly ServerFunctionEntry[]): string {\n const lines = ['import { createServerReference } from \"@mostra/react\";'];\n // `export { local as \"name\" }` covers default and string export names alike (ES2022).\n entries.forEach((entry, index) => {\n lines.push(\n `const reference${index} = createServerReference(${JSON.stringify(entry.id)});`,\n `export { reference${index} as ${JSON.stringify(entry.export)} };`,\n );\n });\n return `${lines.join(\"\\n\")}\\n`;\n}\n\n/** The ID prefix of the virtual stub modules that stand in for server modules in the client. */\nconst STUB_PREFIX = \"\\0mostra-server-reference:\";\n\n/**\n * Replaces `\"use server\"` modules with their client stubs. `modules` maps each module's absolute\n * path to its exports, from the scan.\n */\nexport function serverClientStubPlugin(\n modules: ReadonlyMap<string, readonly ServerFunctionEntry[]>,\n sourceDir: string,\n): Plugin {\n return {\n name: \"mostra:use-server-client\",\n enforce: \"pre\",\n // Server modules resolve to a virtual stub module whose ID ends in `.mjs`: the bundler reads a\n // `.cts` or `.cjs` file name as CommonJS, and the stub is an ES module.\n async resolveId(source, importer, options) {\n if (source.startsWith(STUB_PREFIX)) return source;\n const resolved = await this.resolve(source, importer, { ...options, skipSelf: true });\n const file = resolved?.id.split(\"?\")[0];\n return file !== undefined && modules.has(file) ? `${STUB_PREFIX}${file}.mjs` : null;\n },\n load(id) {\n if (!id.startsWith(STUB_PREFIX)) return null;\n const entries = modules.get(id.slice(STUB_PREFIX.length, -\".mjs\".length));\n return entries === undefined ? null : { code: serverStub(entries), moduleType: \"js\" };\n },\n // Fails closed (D54): a module of the artifact that reaches the client build with the\n // directive, but without a stub, would ship its server code to every viewer.\n transform(code, id) {\n const file = id.split(\"?\")[0] ?? id;\n if (!file.startsWith(`${sourceDir}/`) || modules.has(file)) return null;\n if (!SCRIPT.has(extname(file))) return null;\n if (startsWithUseServer(file, code) !== true) return null;\n return this.error(\n `${relative(sourceDir, file)} starts with \"use server\" but has no client stub, so its server code would reach the browser; give it one of the extensions ${[...SCRIPT].join(\", \")}.`,\n );\n },\n };\n}\n\n/** Where an artifact's build may read from (VR-01: every input is covered by a digest). */\nexport interface BuildInputs {\n /** The artifact's snapshot (`sourceDigest`). */\n readonly sourceDir: string;\n /** Mostra's generated build files (`buildConfigDigest`), whose imports are checked like the artifact's. */\n readonly generatedDir: string;\n /** Real directories holding the build's packages and their dependencies (`lockDigest`). */\n readonly packageRoots: readonly string[];\n}\n\n/**\n * Keeps a build's inputs inside what the version's digests cover (VR-01, DATA_MODEL §2). A relative\n * or absolute import from an artifact file must resolve inside the artifact, and a package import\n * from an artifact file or a generated file must resolve into the build's packages (the warm set\n * and the artifact's lockfile). An import from inside a package must stay among those packages\n * too: a package that imports a dependency it doesn't declare would otherwise find it in any\n * `node_modules` above the home. Anything else (a file beside the artifact, a stray\n * `node_modules` above the home) would bring bytes into the build that no digest covers, so a\n * later change to them would go unnoticed.\n */\nexport function confinePlugin(inputs: BuildInputs): Plugin {\n const under = (file: string, dir: string): boolean => file.startsWith(`${dir}/`);\n const ours = (file: string): boolean =>\n under(file, inputs.sourceDir) || under(file, inputs.generatedDir);\n const packaged = (file: string): boolean => inputs.packageRoots.some((root) => under(file, root));\n const real = (file: string): string => {\n try {\n return realpathSync.native(file);\n } catch {\n return file;\n }\n };\n return {\n name: \"mostra:confine\",\n enforce: \"pre\",\n async resolveId(source, importer, options) {\n const from = importer?.split(\"?\")[0];\n if (from === undefined || source.startsWith(\"\\0\")) return null;\n const fromPackage = !ours(from);\n if (fromPackage && !packaged(from)) return null;\n const bare = !source.startsWith(\".\") && !source.startsWith(\"/\");\n const resolved = await this.resolve(source, importer, { ...options, skipSelf: true });\n if (!resolved || resolved.external) return resolved;\n const id = resolved.id.split(\"?\")[0] ?? resolved.id;\n // Virtual modules, browser stubs for Node built-ins and public URLs (`/logo.svg` from\n // `public/`) aren't files, so there is nothing outside to read.\n if (id.startsWith(\"\\0\") || !isAbsolute(id) || !existsSync(id)) return resolved;\n const file = real(id);\n if (fromPackage) {\n if (packaged(file)) return resolved;\n return this.error(\n `Could not resolve \"${source}\" from the package file ${from}: it isn't among the build's packages (the warm set and the artifact's lockfile), and a package can't take a dependency it doesn't declare from elsewhere.`,\n );\n }\n if (ours(file)) return resolved;\n if (bare && packaged(file)) return resolved;\n const where = relative(inputs.sourceDir, from);\n return this.error(\n bare\n ? `Could not resolve \"${source}\" from ${where}: it isn't in the warm set or the artifact's lockfile, and a version is built only from the artifact's own files and those packages; add it with \\`mostra add\\`.`\n : `Could not resolve \"${source}\" from ${where}: it is outside the artifact, and a version is built only from the artifact's own files.`,\n );\n },\n };\n}\n","/**\n * The SPA render mode's build (D19, ROUND-3 §7): one Vite 8 build of the client, and, when the\n * artifact has `\"use server\"` modules or `live.ts`, one build of the server bundle the worker\n * loads (WP-08). The build runs in a staging directory whose `node_modules` is a link to the warm\n * set (D91) or to the artifact's lock layout (D95), so an artifact needs no `package.json` (AU-03).\n * Nothing in the artifact runs.\n */\nimport type { Dirent } from \"node:fs\";\nimport { mkdir, readdir, realpath, rm, symlink, writeFile } from \"node:fs/promises\";\nimport { join, relative } from \"node:path\";\nimport { stripVTControlCharacters } from \"node:util\";\nimport { createDiagnostic, type Diagnostic } from \"@mostra/protocol\";\nimport tailwind from \"@tailwindcss/vite\";\nimport react from \"@vitejs/plugin-react\";\nimport { build, type InlineConfig, type PluginOption } from \"vite\";\nimport type { FieldCoverage } from \"../coverage.ts\";\nimport {\n type BuildRequest,\n type BuildResponse,\n LIVE_DECLARATION,\n type ServerFunctionEntry,\n STAGING_FILES,\n type VersionRegistry,\n} from \"../types.ts\";\nimport {\n type BuildInputs,\n confinePlugin,\n type FieldHookUse,\n fieldHookUsePlugin,\n mdxPlugin,\n serverClientStubPlugin,\n} from \"./plugins.ts\";\nimport { type ScanResult, scanArtifact } from \"./scan.ts\";\n\n/** Where generated build files live inside the staging directory (never in the snapshot). */\nexport const GENERATED = \".mostra-build\";\n\nexport const html = (title: string, versionId: string): string =>\n `<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <meta name=\"mostra-version\" content=\"${versionId}\" />\n <title>${title.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\")}</title>\n </head>\n <body>\n <div id=\"root\"></div>\n <script type=\"module\" src=\"/${GENERATED}/entry.js\"></script>\n </body>\n</html>\n`;\n\n/**\n * The client entry: hands the page, or the `pages/` routes inside the entry's layout (D57), to the\n * client runtime, which picks the history mode for its delivery target (D111), connects to the\n * shell over the bridge, reports the current page and `mostra/ready` (SH-04), and installs\n * `window.storage` (D53). A single page never loads React Router.\n */\nexport function clientEntry(\n request: Pick<BuildRequest, \"entry\" | \"entryHasDefault\">,\n scan: ScanResult,\n): string {\n const source = (file: string): string => JSON.stringify(`../source/${file}`);\n const lines = [`import \"./styles.css\";`];\n if (scan.pages.length === 0) {\n lines.push(\n `import { mountArtifact } from \"@mostra/react\";`,\n `import Page from ${source(request.entry)};`,\n `mountArtifact({ page: Page });`,\n );\n return `${lines.join(\"\\n\")}\\n`;\n }\n lines.push(\n `import { mountRoutes } from \"@mostra/react/router\";`,\n request.entryHasDefault\n ? `import Layout from ${source(request.entry)};`\n : `import ${source(request.entry)};`,\n );\n for (const [index, page] of scan.pages.entries()) {\n lines.push(`import Page${index} from ${source(page.file)};`);\n }\n const routes = scan.pages\n .map((page, index) => `{ path: ${JSON.stringify(page.path)}, page: Page${index} }`)\n .join(\", \");\n const layout = request.entryHasDefault ? \", layout: Layout\" : \"\";\n lines.push(`mountRoutes({ routes: [${routes}]${layout} });`);\n return `${lines.join(\"\\n\")}\\n`;\n}\n\n/** The field coverage, opened by every package outside the artifact that uses the field hooks. */\nexport function withPackageUses(\n fields: FieldCoverage,\n uses: readonly FieldHookUse[],\n): FieldCoverage {\n const packageOf = (file: string): string => {\n const names = [...file.matchAll(/node_modules\\/((?:@[^/]+\\/)?[^/]+)/g)];\n return names.at(-1)?.[1] ?? file;\n };\n const openReasons = [\n ...fields.openReasons,\n ...[...new Set(uses.map((use) => packageOf(use.importer)))].map((name) => ({\n reason: `the package ${name} uses @mostra/react's field hooks`,\n })),\n ];\n return { ...fields, open: openReasons.length > 0, openReasons };\n}\n\n/** The server entry: every server function by ID, and the live sources (loaded by WP-08's worker). */\nexport function serverEntry(scan: ScanResult): string {\n const lines: string[] = [];\n const functions: string[] = [];\n [...scan.serverModules.entries()].forEach(([module, entries], index) => {\n lines.push(`import * as module${index} from ${JSON.stringify(`../source/${module}`)};`);\n for (const entry of entries) {\n functions.push(\n ` ${JSON.stringify(entry.id)}: module${index}[${JSON.stringify(entry.export)}],`,\n );\n }\n });\n lines.push(`export const functions = {\\n${functions.join(\"\\n\")}\\n};`);\n if (scan.hasLive) lines.push(`export * as live from \"../source/live.ts\";`);\n else lines.push(\"export const live = {};\");\n return `${lines.join(\"\\n\")}\\n`;\n}\n\n/** Turns a bundler error into a diagnostic with the file relative to the artifact. */\nexport function diagnose(error: unknown, sourceDir: string): Diagnostic {\n const failure = error as {\n message?: string;\n code?: string;\n id?: string;\n loc?: { file?: string; line?: number; column?: number };\n errors?: {\n message?: string;\n code?: string;\n id?: string;\n loc?: { file?: string; line?: number; column?: number };\n }[];\n };\n const first = failure.errors?.[0] ?? failure;\n // Bundler messages carry terminal colours; diagnostics are plain text.\n const rawMessage = stripVTControlCharacters(first.message ?? String(error)).replaceAll(\n `${sourceDir}/`,\n \"\",\n );\n const file = first.loc?.file ?? first.id;\n const inSource = file?.startsWith(sourceDir) ? relative(sourceDir, file) : undefined;\n const location =\n inSource !== undefined\n ? { file: inSource, line: first.loc?.line ?? 1, column: (first.loc?.column ?? 0) + 1 }\n : undefined;\n const unresolved =\n first.code === \"UNRESOLVED_IMPORT\" || /\\b(?:could not|failed to) resolve\\b/i.test(rawMessage);\n return createDiagnostic(unresolved ? \"MOSTRA_BUILD_UNRESOLVED\" : \"MOSTRA_BUILD_FAILED\", {\n message: rawMessage.split(\"\\n\").slice(0, 6).join(\"\\n\"),\n ...(location ? { location } : {}),\n });\n}\n\nexport function baseConfig(\n request: Pick<BuildRequest, \"stagingDir\">,\n sourceDir: string,\n plugins: PluginOption[],\n): InlineConfig {\n return {\n root: request.stagingDir,\n configFile: false,\n envDir: false,\n // Only variables with this prefix would reach the bundle; the builder's environment has none.\n envPrefix: \"MOSTRA_ARTIFACT_PUBLIC_\",\n logLevel: \"warn\",\n clearScreen: false,\n base: \"/\",\n mode: \"production\",\n resolve: {\n alias: [{ find: /^@\\//, replacement: `${sourceDir}/` }],\n dedupe: [\"react\", \"react-dom\"],\n },\n // Settings given here are never searched for: no PostCSS config, from anywhere above the\n // home, is loaded or run (VR-01). Tailwind is a plugin of its own.\n css: { postcss: {} },\n plugins,\n };\n}\n\n/**\n * The real directories the build's packages and their dependencies live in: for a package in a\n * pnpm store, the store (`.pnpm`) that holds it and its dependencies; otherwise the package's own\n * directory (a workspace link such as `@mostra/react`), followed by the packages it depends on in\n * turn (`@mostra/protocol`, say).\n */\nexport async function packageRoots(nodeModules: string): Promise<string[]> {\n const roots = new Set<string>();\n const visit = async (modules: string): Promise<void> => {\n let entries: Dirent[];\n try {\n entries = await readdir(modules, { withFileTypes: true });\n } catch {\n return;\n }\n roots.add(await realpath(modules));\n const packages: string[] = [];\n for (const entry of entries) {\n if (entry.name.startsWith(\".\")) continue;\n if (entry.name.startsWith(\"@\")) {\n for (const scoped of await readdir(join(modules, entry.name))) {\n packages.push(join(modules, entry.name, scoped));\n }\n } else packages.push(join(modules, entry.name));\n }\n for (const link of packages) {\n let dir: string;\n try {\n dir = await realpath(link);\n } catch {\n continue; // A dangling link brings nothing in.\n }\n const store = dir.lastIndexOf(\"/.pnpm/\");\n const root = store === -1 ? dir : dir.slice(0, store + \"/.pnpm\".length);\n if (roots.has(root)) continue;\n roots.add(root);\n if (store === -1) await visit(join(dir, \"node_modules\"));\n }\n };\n await visit(nodeModules);\n return [...roots];\n}\n\n/** Runs the SPA build of `request`. */\nexport async function buildSpa(input: BuildRequest): Promise<BuildResponse> {\n // Bundler paths are real paths; staging may sit behind a symbolic link (macOS /tmp).\n const request = { ...input, stagingDir: await realpath(input.stagingDir) };\n const sourceDir = join(request.stagingDir, \"source\");\n const scan = await scanArtifact(sourceDir);\n if (scan.diagnostics.length > 0) return { ok: false, diagnostics: scan.diagnostics };\n if (!request.entryHasDefault && scan.pages.length === 0) {\n return {\n ok: false,\n diagnostics: [\n createDiagnostic(\"MOSTRA_ARTIFACT_NO_PAGE\", {\n message: `${request.entry} has no default export and the artifact has no pages/ folder.`,\n location: { file: request.entry, line: 1, column: 1 },\n }),\n ],\n };\n }\n\n const generated = join(request.stagingDir, GENERATED);\n await mkdir(generated, { recursive: true });\n for (const [name, text] of Object.entries(STAGING_FILES)) {\n await writeFile(join(request.stagingDir, name), text);\n }\n const inputs: BuildInputs = {\n sourceDir,\n generatedDir: generated,\n packageRoots: await packageRoots(request.nodeModules),\n };\n await rm(join(request.stagingDir, \"node_modules\"), { force: true, recursive: true });\n await symlink(request.nodeModules, join(request.stagingDir, \"node_modules\"), \"dir\");\n await writeFile(\n join(request.stagingDir, \"index.html\"),\n html(request.manifest.title, request.versionId),\n );\n await writeFile(join(generated, \"entry.js\"), clientEntry(request, scan));\n await writeFile(join(generated, \"styles.css\"), `@import \"tailwindcss\" source(\"../source\");\\n`);\n if (scan.hasLive) await writeFile(join(generated, \"mostra-env.d.ts\"), LIVE_DECLARATION);\n\n const serverModules = new Map<string, readonly ServerFunctionEntry[]>(\n [...scan.serverModules].map(([module, entries]) => [join(sourceDir, module), entries]),\n );\n // Packages that use the field hooks themselves open the version's coverage (D109).\n const hookUses: FieldHookUse[] = [];\n let runtimeDir: string | undefined;\n try {\n runtimeDir = await realpath(join(request.nodeModules, \"@mostra\", \"react\"));\n } catch {\n runtimeDir = undefined;\n }\n try {\n await build({\n ...baseConfig(request, sourceDir, [\n fieldHookUsePlugin(\n { sourceDir, generatedDir: generated, ...(runtimeDir ? { runtimeDir } : {}) },\n hookUses,\n ),\n confinePlugin(inputs),\n mdxPlugin(),\n serverClientStubPlugin(serverModules, sourceDir),\n react(),\n tailwind(),\n ]),\n // The artifact's public/ is served as-is at the root (INTERFACES §2.1).\n publicDir: join(sourceDir, \"public\"),\n build: {\n outDir: join(request.outDir, \"client\"),\n emptyOutDir: true,\n sourcemap: true,\n reportCompressedSize: false,\n },\n });\n } catch (error) {\n return { ok: false, diagnostics: [diagnose(error, sourceDir)] };\n }\n\n const server = scan.serverModules.size > 0 || scan.hasLive;\n if (server) {\n await writeFile(join(generated, \"server-entry.js\"), serverEntry(scan));\n try {\n await build({\n ...baseConfig(request, sourceDir, [confinePlugin(inputs), mdxPlugin(), react()]),\n publicDir: false,\n // Packages stay external (Vite's default for a server build, D135): the worker resolves\n // them from the layout this build resolved them in (the warm set's, or the lockfile's,\n // whose digest the version's identity covers), so each runs from its own directory with\n // its native addons and its own files, and React exists once. The artifact's own code is\n // bundled; a package Vite can't run unbundled (a linked one, or one whose entry isn't\n // JavaScript) is bundled too.\n ssr: { external: [\"@mostra/server\"], target: \"node\" },\n build: {\n ssr: join(generated, \"server-entry.js\"),\n outDir: join(request.outDir, \"server\"),\n emptyOutDir: true,\n sourcemap: true,\n rolldownOptions: {\n // The worker provides @mostra/server (WP-08), its own copy, so the two share context.\n external: [\"@mostra/server\"],\n output: { entryFileNames: \"entry.mjs\", format: \"es\" },\n },\n },\n });\n } catch (error) {\n return { ok: false, diagnostics: [diagnose(error, sourceDir)] };\n }\n }\n\n const registry: VersionRegistry = {\n schemaVersion: 1,\n entry: request.entry,\n actions: [...scan.serverModules.values()].flat(),\n liveSources: scan.liveSources,\n pages: scan.pages,\n terminals: Object.keys(request.manifest.terminals ?? {}).sort(),\n demos: Object.keys(request.manifest.demos ?? {}).sort(),\n fields: withPackageUses(scan.fields, hookUses),\n };\n return { ok: true, registry, server };\n}\n","/**\n * `mostra dev`'s server (D140 item 12, VR-08): Vite in middleware mode over the dev root, whose\n * `source/` the supervisor keeps a mirror of the artifact's source, with the SPA build's own\n * plugins, so a page in dev is built as its published version would be. It listens on a loopback\n * port the operating system picks and answers only requests that carry the session's secret,\n * which only the dev sandbox's gateway sends: a browser reaches it only through the gateway's\n * route table (Host, Origin, session), never directly, and never through a capability URL of the\n * home. Its HMR WebSocket is served through the same check, on Vite's own token and allowed hosts.\n *\n * When the source changes, Vite updates client modules in place (HMR). When the artifact has\n * server code, the server bundle and `registry.json` are built again and the supervisor told\n * (`builder/dev.server`); once it runs the new bundle, it asks the child to reload every page.\n * When `pages/`, `\"use server\"` modules or `live.ts` change, the generated entry is written again.\n */\nimport { createHash, timingSafeEqual } from \"node:crypto\";\nimport { mkdir, readdir, readFile, rm, symlink, writeFile } from \"node:fs/promises\";\nimport {\n createServer as createHttpServer,\n type IncomingMessage,\n type ServerResponse,\n} from \"node:http\";\nimport { join } from \"node:path\";\nimport type { Duplex } from \"node:stream\";\nimport tailwind from \"@tailwindcss/vite\";\nimport react from \"@vitejs/plugin-react\";\nimport { parseSync } from \"oxc-parser\";\nimport { build, createServer, type Plugin, type ViteDevServer } from \"vite\";\nimport type { SupervisorConnection } from \"../../processes/index.ts\";\nimport {\n DEV_SECRET_HEADER,\n DEV_SERVER_NOTIFICATION,\n DEV_UPDATE_NOTIFICATION,\n type DevChange,\n type DevReady,\n type DevRequest,\n type DevServerBuild,\n LIVE_DECLARATION,\n type ServerFunctionEntry,\n STAGING_FILES,\n type VersionRegistry,\n} from \"../types.ts\";\nimport { type BuildInputs, confinePlugin, mdxPlugin, serverClientStubPlugin } from \"./plugins.ts\";\nimport { type ScanResult, scanArtifact } from \"./scan.ts\";\nimport {\n baseConfig,\n clientEntry,\n diagnose,\n GENERATED,\n html,\n packageRoots,\n serverEntry,\n} from \"./spa.ts\";\n\n/** A running dev server. */\nexport interface DevServer {\n readonly ready: DevReady;\n /** The supervisor changed these files of the mirror: update the pages, rebuild what depends on them. */\n changed(changes: readonly DevChange[]): Promise<void>;\n /** Tells every page to load again. */\n reload(): void;\n close(): Promise<void>;\n}\n\n/** The custom HMR event a dev page sends with the time it was served. */\nconst LOADED_EVENT = \"mostra:dev.loaded\";\n\n/** Whether a request carries the session's secret (compared in constant time). */\nfunction hasSecret(headers: IncomingMessage[\"headers\"], secret: string): boolean {\n const given = headers[DEV_SECRET_HEADER];\n if (typeof given !== \"string\") return false;\n const a = Buffer.from(given);\n const b = Buffer.from(secret);\n return a.length === b.length && timingSafeEqual(a, b);\n}\n\n/** What the server entry depends on: which server modules, functions and live sources exist. */\nfunction serverShape(scan: ScanResult): string {\n return JSON.stringify({\n modules: [...scan.serverModules].map(([module, entries]) => [module, entries.map((e) => e.id)]),\n live: scan.hasLive,\n });\n}\n\n/** What the client entry depends on: the pages. */\nconst pageShape = (scan: ScanResult): string => JSON.stringify(scan.pages);\n\n/** Starts the dev server for `request`. */\nexport async function startDev(\n request: DevRequest,\n supervisor: SupervisorConnection,\n): Promise<DevServer> {\n const root = request.root;\n const sourceDir = join(root, \"source\");\n const generated = join(root, GENERATED);\n await mkdir(generated, { recursive: true });\n for (const [name, text] of Object.entries(STAGING_FILES)) await writeFile(join(root, name), text);\n await rm(join(root, \"node_modules\"), { force: true, recursive: true });\n await symlink(request.nodeModules, join(root, \"node_modules\"), \"dir\");\n await writeFile(join(generated, \"styles.css\"), `@import \"tailwindcss\" source(\"../source\");\\n`);\n await mkdir(request.outDir, { recursive: true });\n // Vite's pre-bundled dependencies live in the session's root (`cacheDir` below); they are\n // packages the build may import, as the layout they were bundled from is.\n const viteCache = join(root, \".vite\");\n const inputs: BuildInputs = {\n sourceDir,\n generatedDir: generated,\n packageRoots: [...(await packageRoots(request.nodeModules)), viteCache],\n };\n\n let scan = await scanArtifact(sourceDir);\n // The client stubs read this map on every transform, so a new \"use server\" export is stubbed\n // once the map is refreshed and the module invalidated.\n const serverModules = new Map<string, readonly ServerFunctionEntry[]>();\n const refreshServerModules = (): void => {\n serverModules.clear();\n for (const [module, entries] of scan.serverModules)\n serverModules.set(join(sourceDir, module), entries);\n };\n refreshServerModules();\n const writeEntry = async (): Promise<void> => {\n await writeFile(join(generated, \"entry.js\"), clientEntry(request, scan));\n if (scan.hasLive) await writeFile(join(generated, \"mostra-env.d.ts\"), LIVE_DECLARATION);\n };\n await writeEntry();\n await writeFile(\n join(generated, \"dev-loaded.js\"),\n `const served = Number(document.querySelector('meta[name=\"mostra-dev-served\"]')?.content);\\nimport.meta.hot?.send(${JSON.stringify(LOADED_EVENT)}, served);\\n`,\n );\n const indexHtml = html(request.manifest.title, request.versionId);\n\n /** Builds the server bundle and `registry.json` into the dev version's directory. */\n let lastBundle = \"\";\n const buildServer = async (): Promise<DevServerBuild> => {\n if (scan.diagnostics.length > 0 || scan.unparsed.length > 0)\n return { ok: false, diagnostics: [...scan.diagnostics, ...scan.unparsed] };\n const server = scan.serverModules.size > 0 || scan.hasLive;\n if (server) {\n await writeFile(join(generated, \"server-entry.js\"), serverEntry(scan));\n try {\n await build({\n ...baseConfig({ stagingDir: root }, sourceDir, [\n confinePlugin(inputs),\n mdxPlugin(),\n react(),\n ]),\n mode: \"development\",\n publicDir: false,\n ssr: { external: [\"@mostra/server\"], target: \"node\" },\n build: {\n ssr: join(generated, \"server-entry.js\"),\n outDir: join(request.outDir, \"server\"),\n emptyOutDir: true,\n sourcemap: true,\n rolldownOptions: {\n external: [\"@mostra/server\"],\n output: { entryFileNames: \"entry.mjs\", format: \"es\" },\n },\n },\n });\n } catch (error) {\n return { ok: false, diagnostics: [diagnose(error, sourceDir)] };\n }\n } else {\n await rm(join(request.outDir, \"server\"), { recursive: true, force: true });\n }\n lastBundle = await bundleDigest(join(request.outDir, \"server\"));\n const registry: VersionRegistry = {\n schemaVersion: 1,\n entry: request.entry,\n actions: [...scan.serverModules.values()].flat(),\n liveSources: scan.liveSources,\n pages: scan.pages,\n terminals: Object.keys(request.manifest.terminals ?? {}).sort(),\n demos: Object.keys(request.manifest.demos ?? {}).sort(),\n // Dev serves whatever the source names; nothing is ever orphaned in a preview.\n fields: { ...scan.fields, open: true, openReasons: [{ reason: \"a development preview\" }] },\n };\n await writeFile(\n join(request.outDir, \"registry.json\"),\n `${JSON.stringify(registry, null, 2)}\\n`,\n );\n return { ok: true, registry, server };\n };\n\n const firstBuild = await buildServer();\n\n // Vite's HMR WebSocket attaches to this server, which never listens: the real server hands it\n // only upgrades that carry the secret.\n const hmrServer = createHttpServer();\n const vite: ViteDevServer = await createServer({\n ...baseConfig({ stagingDir: root }, sourceDir, [\n confinePlugin(inputs),\n mdxPlugin(),\n serverClientStubPlugin(serverModules, sourceDir),\n manifestExportPlugin(join(sourceDir, request.entry)),\n react(),\n tailwind(),\n ]),\n mode: \"development\",\n appType: \"custom\",\n // Vite's pre-bundled dependencies stay in the session's own root, never in the shared warm\n // set or a lock layout behind `node_modules`, which other sessions and builds read.\n cacheDir: viteCache,\n publicDir: join(sourceDir, \"public\"),\n server: {\n middlewareMode: true,\n ws: { server: hmrServer },\n // Vite watches nothing: the supervisor, which keeps the mirror, says what changed (and a\n // watcher would walk the whole package layout behind node_modules).\n watch: null,\n // Requests arrive from the gateway's artifact origin on loopback; any other Host (a DNS\n // rebinding) is refused by Vite as well as by the gateway.\n allowedHosts: [\"127.0.0.1\", \"localhost\"],\n cors: false,\n fs: { strict: true, allow: [root, ...inputs.packageRoots] },\n },\n optimizeDeps: { entries: [`${GENERATED}/entry.js`] },\n });\n\n // A page reports when it was served once its modules have run; one served before the last\n // change (that update reached it before its modules accepted updates, or before its socket\n // opened, as after a new dev server) loads again. Vite's own client drops such updates. Times,\n // not a counter, so a page a previous dev server of the session served compares too.\n let changedAt = 0;\n vite.ws.on(LOADED_EVENT, (served: unknown, client) => {\n if (typeof served === \"number\" && served <= changedAt) client.send({ type: \"full-reload\" });\n });\n const serveHtml = async (req: IncomingMessage, res: ServerResponse): Promise<void> => {\n // The time is a meta tag the report module reads: an inline module would be cached by Vite\n // (and by the browser, behind its ETag) with the first page's time. The report runs after the\n // entry's module graph has run (module scripts run in document order, each after its\n // imports), so every module that accepts updates has said so: an update that arrived before\n // that was dropped by Vite's client, and the report makes the page load again.\n const served = `<meta name=\"mostra-dev-served\" content=\"${Date.now()}\" />`;\n const report = `<script type=\"module\" src=\"/${GENERATED}/dev-loaded.js\"></script>`;\n const page = await vite.transformIndexHtml(\n req.url ?? \"/\",\n indexHtml\n .replace(\"</head>\", ` ${served}\\n </head>`)\n .replace(\"</body>\", ` ${report}\\n </body>`),\n );\n res.writeHead(200, { \"content-type\": \"text/html; charset=utf-8\", \"cache-control\": \"no-cache\" });\n res.end(page);\n };\n const http = createHttpServer((req, res) => {\n if (!hasSecret(req.headers, request.secret)) {\n res.writeHead(403).end();\n return;\n }\n const path = (req.url ?? \"/\").split(\"?\")[0] ?? \"/\";\n const navigation =\n req.headers[\"sec-fetch-dest\"] === \"document\" ||\n req.headers[\"sec-fetch-dest\"] === \"iframe\" ||\n path === \"/\" ||\n path === \"/index.html\";\n if ((req.method === \"GET\" || req.method === \"HEAD\") && navigation) {\n serveHtml(req, res).catch((error: unknown) => {\n res.writeHead(500, { \"content-type\": \"text/plain\" }).end(String(error));\n });\n return;\n }\n vite.middlewares(req, res, () => {\n // A deep link inside the artifact's routes gets its page (D57).\n if (req.headers.accept?.includes(\"text/html\")) {\n serveHtml(req, res).catch(() => res.writeHead(500).end());\n return;\n }\n res.writeHead(404).end();\n });\n });\n http.on(\"upgrade\", (req: IncomingMessage, socket: Duplex, head: Buffer) => {\n if (!hasSecret(req.headers, request.secret)) {\n socket.destroy();\n return;\n }\n hmrServer.emit(\"upgrade\", req, socket, head);\n });\n await new Promise<void>((done) => http.listen(0, \"127.0.0.1\", done));\n const port = (http.address() as { port: number }).port;\n\n // Changes in the mirror: Vite updates the client modules (HMR); rescan; write the entry again\n // when the pages changed; rebuild the server bundle when the artifact has server code.\n let running: Promise<void> = Promise.resolve();\n const settle = async (changes: readonly DevChange[]): Promise<void> => {\n const files = changes.map((change) => change.file);\n changedAt = Date.now();\n for (const change of changes)\n vite.watcher.emit(change.kind, join(sourceDir, ...change.file.split(\"/\")));\n const before = { pages: pageShape(scan), server: serverShape(scan) };\n scan = await scanArtifact(sourceDir);\n const serverChanged = before.server !== serverShape(scan);\n const pagesChanged = before.pages !== pageShape(scan);\n if (pagesChanged || serverChanged) {\n refreshServerModules();\n await writeEntry();\n // Vite watches nothing, so it hears of the rewritten entry from here: the route table\n // (or the server stubs) it imports changed, and every page loads it again.\n vite.watcher.emit(\"change\", join(generated, \"entry.js\"));\n if (serverChanged) vite.moduleGraph.invalidateAll();\n }\n if (pagesChanged && !serverChanged) vite.ws.send({ type: \"full-reload\" });\n const hasServer = scan.serverModules.size > 0 || scan.hasLive || scan.unparsed.length > 0;\n if (hasServer || serverChanged) {\n // The server bundle is built again; only a bundle that changed restarts the worker and\n // loads the pages again. A client edit stays a hot update.\n const before = lastBundle;\n const built = await buildServer();\n if (!built.ok || serverChanged || lastBundle !== before) {\n supervisor.notify(DEV_SERVER_NOTIFICATION, { build: built, files });\n return;\n }\n }\n supervisor.notify(DEV_UPDATE_NOTIFICATION, { files });\n };\n return {\n ready: { port, build: firstBuild },\n changed: (changes) => {\n running = running.then(() => settle(changes)).catch(() => {});\n return running;\n },\n reload: () => vite.ws.send({ type: \"full-reload\" }),\n close: async () => {\n await running;\n http.closeAllConnections();\n await new Promise<void>((done) => http.close(() => done()));\n await vite.close();\n },\n };\n}\n\n/**\n * Keeps React Fast Refresh working on the entry (D140 item 12): the entry exports its manifest\n * (`export const artifact = defineArtifact(…)`, D51), and a module that exports anything but\n * components can't be refreshed in place, so every edit of a single-file artifact would load the\n * page again. In dev only, the `export` keyword of that one declaration becomes spaces (positions\n * and source maps stay exact); nothing imports the manifest at run time, since Mostra reads it\n * statically.\n */\nexport function manifestExportPlugin(entryFile: string): Plugin {\n return {\n name: \"mostra:dev-manifest-export\",\n enforce: \"pre\",\n transform(code, id) {\n if (id.split(\"?\")[0] !== entryFile || !/\\.[jt]sx$/.test(entryFile)) return null;\n const parsed = parseSync(entryFile, code, {\n lang: entryFile.endsWith(\".tsx\") ? \"tsx\" : \"jsx\",\n });\n if (parsed.errors.length > 0) return null;\n for (const statement of parsed.program.body) {\n if (statement.type !== \"ExportNamedDeclaration\") continue;\n const declaration = statement.declaration;\n if (declaration?.type !== \"VariableDeclaration\" || declaration.declarations.length !== 1)\n continue;\n const id = declaration.declarations[0]?.id;\n if (id?.type !== \"Identifier\" || id.name !== \"artifact\") continue;\n const blank = \" \".repeat(declaration.start - statement.start);\n return {\n code: code.slice(0, statement.start) + blank + code.slice(declaration.start),\n map: null,\n };\n }\n return null;\n },\n };\n}\n\n/** A digest of the server bundle's files, to tell a rebuild that changed nothing. */\nexport async function bundleDigest(dir: string): Promise<string> {\n const hash = createHash(\"sha256\");\n let names: string[];\n try {\n names = (await readdir(dir, { recursive: true })).sort();\n } catch {\n return \"\";\n }\n for (const name of names) {\n if (name.endsWith(\".map\")) continue;\n const text = await readFile(join(dir, name)).catch(() => undefined);\n if (text === undefined) continue;\n hash.update(name).update(\"\\u0000\").update(text).update(\"\\u0000\");\n }\n return hash.digest(\"hex\");\n}\n","/**\n * The builder child's entry (`mostra-runtime`'s `dist/builder/child/main.js`, ARCHITECTURE §1): the\n * only process that loads Vite. The supervisor starts one per build through the process manager,\n * sends `builder/build` over IPC, and stops it after the answer; for `mostra dev` it starts one per\n * session and sends `builder/dev`, and the child serves until it is stopped (D140 item 12). It\n * exits with its supervisor (`connectToSupervisor`) and never runs artifact code: bundling reads\n * modules, it doesn't run them.\n */\nimport { connectToSupervisor } from \"../../processes/index.ts\";\nimport {\n BUILD_METHOD,\n type BuildRequest,\n DEV_CHANGED_METHOD,\n DEV_METHOD,\n DEV_RELOAD_METHOD,\n type DevChange,\n type DevRequest,\n} from \"../types.ts\";\nimport { type DevServer, startDev } from \"./dev.ts\";\nimport { buildSpa } from \"./spa.ts\";\n\nlet dev: DevServer | undefined;\n\nconst supervisor = connectToSupervisor({\n onRequest: async (method, params) => {\n if (method === BUILD_METHOD) {\n const request = params as BuildRequest;\n // A test's hung builder (issue #18): it never answers.\n if (request.hang === true) return new Promise<never>(() => {});\n return buildSpa(request);\n }\n if (method === DEV_METHOD) {\n if (dev) throw new Error(\"This builder child already serves a dev session.\");\n dev = await startDev(params as DevRequest, supervisor);\n return dev.ready;\n }\n if (method === DEV_CHANGED_METHOD) {\n await dev?.changed((params as { changes: DevChange[] }).changes);\n return {};\n }\n if (method === DEV_RELOAD_METHOD) {\n dev?.reload();\n return {};\n }\n throw new Error(`The builder doesn't serve ${method}.`);\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAuBA,MAAM,QAAuD;CAC3D,iCAAiB,IAAI,IAAI,CAAC,YAAY,WAAW,CAAC;CAClD,sCAAsB,IAAI,IAAI,CAAC,SAAS,CAAC;AAC3C;;AAGA,MAAM,0BAAU,IAAI,IAAI;CAAC;CAAU;CAAc;AAAM,CAAC;;AAGxD,MAAM,kCAAkB,IAAI,IAAI;CAAC;CAAO;CAAO;CAAU;AAAM,CAAC;AAEhE,MAAM,cAAqE;CACzE,OAAO;CACP,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,OAAO;CACP,QAAQ;CACR,QAAQ;CACR,QAAQ;AACV;AAEA,SAASA,aAAW,MAAc,QAAkD;CAClF,MAAM,SAAS,KAAK,MAAM,GAAG,MAAM;CACnC,OAAO;EAAE,MAAM,OAAO,MAAM,IAAI,CAAC,CAAC;EAAQ,QAAQ,SAAS,OAAO,YAAY,IAAI;CAAE;AACtF;AAEA,SAAS,KAAK,MAAY,OAAiD;CACzE,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,IAAI,GAC5C,IAAI,MAAM,QAAQ,KAAK,GAChB;OAAA,MAAM,QAAQ,OACjB,IAAI,QAAQ,OAAO,SAAS,YAAY,UAAU,MAAM,MAAM,M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T;CACF;AACF;;AAGA,eAAsB,aAAa,KAA8B;CAC/D,MAAM,OAAO,WAAW,QAAQ;CAChC,IAAI;CACJ,IAAI;EACF,SAAS,MAAM,QAAQ,KAAK,EAAE,WAAW,KAAK,CAAC,EAAA,CAAG,KAAK;CACzD,QAAQ;EACN,OAAO;CACT;CACA,KAAK,MAAM,QAAQ,OAAO;EACxB,IAAI,KAAK,SAAS,MAAM,GAAG;EAC3B,MAAM,OAAO,MAAM,SAAS,KAAK,KAAK,IAAI,CAAC,CAAC,CAAC,YAAY,KAAA,CAAS;EAClE,IAAI,SAAS,KAAA,GAAW;EACxB,KAAK,OAAO,IAAI,CAAC,CAAC,OAAO,IAAQ,CAAC,CAAC,OAAO,IAAI,CAAC,CAAC,OAAO,IAAQ;CACjE;CACA,OAAO,KAAK,OAAO,KAAK;AAC1B;;;;;;;;;;;ACzWA,IAAI;AAEJ,MAAM,aAAa,oBAAoB,EACrC,WAAW,OAAO,QAAQ,WAAW;CACnC,IAAI,WAAA,iBAAyB;EAC3B,MAAM,UAAU;EAEhB,IAAI,QAAQ,SAAS,MAAM,OAAO,IAAI,cAAqB,CAAC,CAAC;EAC7D,OAAO,SAAS,OAAO;CACzB;CACA,IAAI,WAAA,eAAuB;EACzB,IAAI,KAAK,MAAM,IAAI,MAAM,kDAAkD;EAC3E,MAAM,MAAM,SAAS,QAAsB,UAAU;EACrD,OAAO,IAAI;CACb;CACA,IAAI,WAAA,uBAA+B;EACjC,MAAM,KAAK,QAAS,OAAoC,OAAO;EAC/D,OAAO,CAAC;CACV;CACA,IAAI,WAAA,sBAA8B;EAChC,KAAK,OAAO;EACZ,OAAO,CAAC;CACV;CACA,MAAM,IAAI,MAAM,6BAA6B,OAAO,EAAE;AACxD,EACF,CAAC"}
@@ -0,0 +1,49 @@
1
+ import { RpcPeer } from "@mostra/protocol";
2
+ //#region src/processes/child.ts
3
+ /**
4
+ * The child side of supervisor messaging, for Node children the process manager starts with an
5
+ * IPC channel. It wires the JSON-RPC core to Node IPC and keeps the rule that a child never
6
+ * outlives its supervisor: when the channel disconnects (the supervisor exited or was killed), the
7
+ * child signals its own process group, so grandchildren go too, and exits (FAILURE_MODEL §2).
8
+ *
9
+ * ```ts
10
+ * const supervisor = connectToSupervisor({ onRequest: (method, params) => handle(method, params) });
11
+ * await supervisor.request("child/adopt", { pid: pty.pid }); // a program in its own session
12
+ * ```
13
+ */
14
+ /**
15
+ * Connects a Node child to its supervisor over the IPC channel.
16
+ *
17
+ * @throws Error when the process wasn't started with an IPC channel.
18
+ */
19
+ function connectToSupervisor(options = {}) {
20
+ const send = process.send?.bind(process);
21
+ if (!send) throw new Error("This process wasn't started by a Mostra supervisor (no IPC channel).");
22
+ const peer = new RpcPeer({
23
+ send: (message) => {
24
+ send(message);
25
+ },
26
+ ...options.onRequest ? { onRequest: options.onRequest } : {},
27
+ ...options.onNotification ? { onNotification: options.onNotification } : {}
28
+ });
29
+ process.on("message", (message) => peer.receive(message));
30
+ process.on("disconnect", () => {
31
+ peer.close();
32
+ exitWithGroup();
33
+ });
34
+ return {
35
+ request: (method, params) => peer.request(method, params),
36
+ notify: (method, params) => peer.notify(method, params)
37
+ };
38
+ }
39
+ /** Signals this child's whole process group (it leads it) and exits. */
40
+ function exitWithGroup() {
41
+ try {
42
+ process.kill(-process.pid, "SIGTERM");
43
+ } catch {}
44
+ process.exit(0);
45
+ }
46
+ //#endregion
47
+ export { connectToSupervisor as t };
48
+
49
+ //# sourceMappingURL=child-xrHmytks.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"child-xrHmytks.js","names":[],"sources":["../src/processes/child.ts"],"sourcesContent":["/**\n * The child side of supervisor messaging, for Node children the process manager starts with an\n * IPC channel. It wires the JSON-RPC core to Node IPC and keeps the rule that a child never\n * outlives its supervisor: when the channel disconnects (the supervisor exited or was killed), the\n * child signals its own process group, so grandchildren go too, and exits (FAILURE_MODEL §2).\n *\n * ```ts\n * const supervisor = connectToSupervisor({ onRequest: (method, params) => handle(method, params) });\n * await supervisor.request(\"child/adopt\", { pid: pty.pid }); // a program in its own session\n * ```\n */\nimport { type JsonRpcParams, RpcPeer } from \"@mostra/protocol\";\n\n/** Options for {@link connectToSupervisor}. */\nexport interface SupervisorConnectionOptions {\n /** Answers the supervisor's requests. */\n readonly onRequest?: (method: string, params: unknown) => unknown;\n /** Receives the supervisor's notifications. */\n readonly onNotification?: (method: string, params: unknown) => void;\n}\n\n/** The child's end of the connection. */\nexport interface SupervisorConnection {\n /** Sends a request to the supervisor, such as `child/adopt`. */\n request(method: string, params?: JsonRpcParams): Promise<unknown>;\n /** Sends a notification to the supervisor. */\n notify(method: string, params?: JsonRpcParams): void;\n}\n\n/**\n * Connects a Node child to its supervisor over the IPC channel.\n *\n * @throws Error when the process wasn't started with an IPC channel.\n */\nexport function connectToSupervisor(\n options: SupervisorConnectionOptions = {},\n): SupervisorConnection {\n const send = process.send?.bind(process);\n if (!send)\n throw new Error(\"This process wasn't started by a Mostra supervisor (no IPC channel).\");\n const peer = new RpcPeer({\n send: (message) => {\n send(message);\n },\n ...(options.onRequest ? { onRequest: options.onRequest } : {}),\n ...(options.onNotification ? { onNotification: options.onNotification } : {}),\n });\n process.on(\"message\", (message) => peer.receive(message));\n process.on(\"disconnect\", () => {\n peer.close();\n exitWithGroup();\n });\n return {\n request: (method, params) => peer.request(method, params),\n notify: (method, params) => peer.notify(method, params),\n };\n}\n\n/** Signals this child's whole process group (it leads it) and exits. */\nfunction exitWithGroup(): void {\n try {\n process.kill(-process.pid, \"SIGTERM\");\n } catch {\n // The group is already gone.\n }\n process.exit(0);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAkCA,SAAgB,oBACd,UAAuC,CAAC,GAClB;CACtB,MAAM,OAAO,QAAQ,MAAM,KAAK,OAAO;CACvC,IAAI,CAAC,MACH,MAAM,IAAI,MAAM,sEAAsE;CACxF,MAAM,OAAO,IAAI,QAAQ;EACvB,OAAO,YAAY;GACjB,KAAK,OAAO;EACd;EACA,GAAI,QAAQ,YAAY,EAAE,WAAW,QAAQ,UAAU,IAAI,CAAC;EAC5D,GAAI,QAAQ,iBAAiB,EAAE,gBAAgB,QAAQ,eAAe,IAAI,CAAC;CAC7E,CAAC;CACD,QAAQ,GAAG,YAAY,YAAY,KAAK,QAAQ,OAAO,CAAC;CACxD,QAAQ,GAAG,oBAAoB;EAC7B,KAAK,MAAM;EACX,cAAc;CAChB,CAAC;CACD,OAAO;EACL,UAAU,QAAQ,WAAW,KAAK,QAAQ,QAAQ,MAAM;EACxD,SAAS,QAAQ,WAAW,KAAK,OAAO,QAAQ,MAAM;CACxD;AACF;;AAGA,SAAS,gBAAsB;CAC7B,IAAI;EACF,QAAQ,KAAK,CAAC,QAAQ,KAAK,SAAS;CACtC,QAAQ,CAER;CACA,QAAQ,KAAK,CAAC;AAChB"}
@@ -0,0 +1 @@
1
+ export {}
@@ -0,0 +1,33 @@
1
+ import { t as connectToSupervisor } from "../../child-xrHmytks.js";
2
+ import { spawn } from "node:child_process";
3
+ //#region src/deps/child/install.ts
4
+ /**
5
+ * The install child's entry (`dist/deps/child/install.js`, D95, DP-05): the process the process
6
+ * manager starts for every installer run, in the artifact's source directory with the artifact
7
+ * environment. It connects to its supervisor over IPC, so that when the supervisor exits or is
8
+ * killed, its whole process group ends with it (FAILURE_MODEL §2): pnpm, and every lifecycle
9
+ * script pnpm starts, run in that group. Its arguments are pnpm's entry and pnpm's arguments; pnpm
10
+ * runs as its child with the same output, and its exit code is the install child's.
11
+ */
12
+ connectToSupervisor();
13
+ const [entry, ...args] = process.argv.slice(2);
14
+ if (entry === void 0) {
15
+ console.error("The install child needs the installer's entry as its first argument.");
16
+ process.exit(2);
17
+ }
18
+ const installer = spawn(process.execPath, [entry, ...args], { stdio: [
19
+ "ignore",
20
+ "inherit",
21
+ "inherit"
22
+ ] });
23
+ installer.on("error", (error) => {
24
+ console.error(`The installer couldn't start: ${error.message}`);
25
+ process.exit(1);
26
+ });
27
+ installer.on("exit", (code, signal) => {
28
+ process.exit(code ?? (signal ? 1 : 0));
29
+ });
30
+ //#endregion
31
+ export {};
32
+
33
+ //# sourceMappingURL=install.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"install.js","names":[],"sources":["../../../src/deps/child/install.ts"],"sourcesContent":["/**\n * The install child's entry (`dist/deps/child/install.js`, D95, DP-05): the process the process\n * manager starts for every installer run, in the artifact's source directory with the artifact\n * environment. It connects to its supervisor over IPC, so that when the supervisor exits or is\n * killed, its whole process group ends with it (FAILURE_MODEL §2): pnpm, and every lifecycle\n * script pnpm starts, run in that group. Its arguments are pnpm's entry and pnpm's arguments; pnpm\n * runs as its child with the same output, and its exit code is the install child's.\n */\nimport { spawn } from \"node:child_process\";\nimport { connectToSupervisor } from \"../../processes/index.ts\";\n\nconnectToSupervisor();\n\nconst [entry, ...args] = process.argv.slice(2);\nif (entry === undefined) {\n console.error(\"The install child needs the installer's entry as its first argument.\");\n process.exit(2);\n}\n// Not detached: pnpm stays in this child's process group, which the supervisor and the disconnect\n// rule both end as a whole.\nconst installer = spawn(process.execPath, [entry, ...args], {\n stdio: [\"ignore\", \"inherit\", \"inherit\"],\n});\ninstaller.on(\"error\", (error) => {\n console.error(`The installer couldn't start: ${error.message}`);\n process.exit(1);\n});\ninstaller.on(\"exit\", (code, signal) => {\n process.exit(code ?? (signal ? 1 : 0));\n});\n"],"mappings":";;;;;;;;;;;AAWA,oBAAoB;AAEpB,MAAM,CAAC,OAAO,GAAG,QAAQ,QAAQ,KAAK,MAAM,CAAC;AAC7C,IAAI,UAAU,KAAA,GAAW;CACvB,QAAQ,MAAM,sEAAsE;CACpF,QAAQ,KAAK,CAAC;AAChB;AAGA,MAAM,YAAY,MAAM,QAAQ,UAAU,CAAC,OAAO,GAAG,IAAI,GAAG,EAC1D,OAAO;CAAC;CAAU;CAAW;AAAS,EACxC,CAAC;AACD,UAAU,GAAG,UAAU,UAAU;CAC/B,QAAQ,MAAM,iCAAiC,MAAM,SAAS;CAC9D,QAAQ,KAAK,CAAC;AAChB,CAAC;AACD,UAAU,GAAG,SAAS,MAAM,WAAW;CACrC,QAAQ,KAAK,SAAS,SAAS,IAAI,EAAE;AACvC,CAAC"}
@@ -0,0 +1,221 @@
1
+ import { Diagnostic, InstanceInfo, JsonRpcParams, MostraInitializeResult, RpcPeer, SubmissionPolicy } from "@mostra/protocol";
2
+ import { Duplex, Readable, Writable } from "node:stream";
3
+ //#region src/log.d.ts
4
+ /** Environment variables, as `process.env` holds them. */
5
+ type Environment = Readonly<Record<string, string | undefined>>;
6
+ //#endregion
7
+ //#region src/home/record.d.ts
8
+ /** What `instance.json` holds. */
9
+ interface InstanceRecord {
10
+ /** The owner's process ID. */
11
+ readonly pid: number;
12
+ /** The owner's process start time (processes/identity.ts). */
13
+ readonly startTime: string;
14
+ /** The control socket clients attach to. */
15
+ readonly socket: string;
16
+ /** The owner's runtime release. */
17
+ readonly runtimeVersion: string;
18
+ /** The host protocol revisions the owner speaks. */
19
+ readonly revisions: readonly string[];
20
+ /** `host` or `daemon` (`InstanceInfo.mode`). */
21
+ readonly mode: "host" | "daemon";
22
+ /** When the owner took the home (RFC 3339). */
23
+ readonly startedAt: string;
24
+ }
25
+ //#endregion
26
+ //#region src/processes/child.d.ts
27
+ /** Options for {@link connectToSupervisor}. */
28
+ interface SupervisorConnectionOptions {
29
+ /** Answers the supervisor's requests. */
30
+ readonly onRequest?: (method: string, params: unknown) => unknown;
31
+ /** Receives the supervisor's notifications. */
32
+ readonly onNotification?: (method: string, params: unknown) => void;
33
+ }
34
+ /** The child's end of the connection. */
35
+ interface SupervisorConnection {
36
+ /** Sends a request to the supervisor, such as `child/adopt`. */
37
+ request(method: string, params?: JsonRpcParams): Promise<unknown>;
38
+ /** Sends a notification to the supervisor. */
39
+ notify(method: string, params?: JsonRpcParams): void;
40
+ }
41
+ /**
42
+ * Connects a Node child to its supervisor over the IPC channel.
43
+ *
44
+ * @throws Error when the process wasn't started with an IPC channel.
45
+ */
46
+ export declare function connectToSupervisor(options?: SupervisorConnectionOptions): SupervisorConnection;
47
+ //#endregion
48
+ //#region src/processes/manager.d.ts
49
+ /** How a child ended. */
50
+ interface ChildExit {
51
+ /** The exit code, or `null` when a signal ended it. */
52
+ readonly code: number | null;
53
+ /** The signal that ended it, if any. */
54
+ readonly signal: string | null;
55
+ /** Its last stderr lines, for diagnostics such as `MOSTRA_BUILD_CRASHED`. */
56
+ readonly stderrTail: readonly string[];
57
+ }
58
+ /** What to start. */
59
+ interface SpawnSpec {
60
+ /** What the child is: `builder`, `verify`, `worker`, `pty-host`, `demo`, `install` … */
61
+ readonly kind: string;
62
+ /** What it serves, such as an artifact or version ID. */
63
+ readonly ownerRef: string;
64
+ /** The executable. */
65
+ readonly command: string;
66
+ /** Its arguments. */
67
+ readonly args?: readonly string[];
68
+ /** Its working directory. Default: the supervisor's. */
69
+ readonly cwd?: string;
70
+ /** The child's whole environment. Default: the supervisor's. */
71
+ readonly env?: Environment;
72
+ /**
73
+ * Values the child receives that must never appear in logs or reports, such as secrets.
74
+ * Variables whose names look like secrets (`*_TOKEN`, `*_SECRET` …) are redacted as well.
75
+ */
76
+ readonly redact?: readonly string[];
77
+ /**
78
+ * Receives each line the child writes to stdout, redacted, instead of the log: for children
79
+ * whose output is data, such as the installer's NDJSON report. Every line has arrived before
80
+ * `exited` resolves.
81
+ */
82
+ readonly onStdout?: (line: string) => void;
83
+ /**
84
+ * Opens a JSON-RPC channel over Node IPC; the command must then be a Node.js executable. The
85
+ * handlers answer the child's requests besides the built-in `child/adopt` and `child/release`.
86
+ */
87
+ readonly ipc?: {
88
+ readonly onRequest?: (method: string, params: unknown) => unknown;
89
+ readonly onNotification?: (method: string, params: unknown) => void;
90
+ };
91
+ /**
92
+ * Opens a plain byte channel as the child's fd 4 (an artifact's worker, D124): a pipe the child
93
+ * reads and writes as it likes, unlike `ipc`, which is Node's own channel on the main thread.
94
+ * The two exclude each other.
95
+ */
96
+ readonly channel?: true;
97
+ }
98
+ /** A running child. */
99
+ interface ChildHandle {
100
+ /** Its process ID, which is also its process group ID. */
101
+ readonly pid: number;
102
+ /** What it is (`SpawnSpec.kind`). */
103
+ readonly kind: string;
104
+ /** What it serves (`SpawnSpec.ownerRef`). */
105
+ readonly ownerRef: string;
106
+ /** When it was started (RFC 3339). */
107
+ readonly startedAt: string;
108
+ /** Sends requests to the child, when it was started with `ipc`. */
109
+ request(method: string, params?: JsonRpcParams, options?: {
110
+ timeoutMs?: number;
111
+ }): Promise<unknown>;
112
+ /** The child's fd 4, when it was started with `channel`. */
113
+ readonly channel?: Duplex;
114
+ /** Resolves when the child has exited and its process groups are gone. */
115
+ readonly exited: Promise<ChildExit>;
116
+ /** Stops the child: SIGTERM to its group, SIGKILL after `graceMs`. */
117
+ stop(graceMs?: number): Promise<ChildExit>;
118
+ }
119
+ /** What reaping found for one recorded child. */
120
+ interface ReapedChild {
121
+ /** The recorded process ID. */
122
+ readonly pid: number;
123
+ /** The recorded kind; a program a child adopted has its parent's kind plus "/adopted". */
124
+ readonly kind: string;
125
+ /** What it served. */
126
+ readonly ownerRef: string;
127
+ /** The processes that were signalled: the leader if it still ran, and its group's members. */
128
+ readonly signalled: readonly number[];
129
+ /** Why nothing was signalled, when nothing was. */
130
+ readonly skipped?: "gone" | "pid reused" | "other boot";
131
+ }
132
+ /** The process manager of one supervisor. */
133
+ interface ProcessManager {
134
+ /** Starts a child in its own process group and records it. */
135
+ spawn(spec: SpawnSpec): Promise<ChildHandle>;
136
+ /** The children running now, for `instance/status`. */
137
+ list(): readonly {
138
+ pid: number;
139
+ kind: string;
140
+ ownerRef: string;
141
+ startedAt: string;
142
+ }[];
143
+ /** Stops every child; used when the supervisor stops. */
144
+ stopAll(graceMs?: number): Promise<void>;
145
+ }
146
+ //#endregion
147
+ //#region src/instance/index.d.ts
148
+ /** Options for {@link startInstance}. */
149
+ interface StartInstanceOptions {
150
+ /** `host`: serve `stdio` and live as long as it; `daemon`: serve the socket until stopped. */
151
+ readonly mode: "host" | "daemon";
152
+ /** `--home`. */
153
+ readonly home?: string | undefined;
154
+ /** The environment: `MOSTRA_HOME`, `MOSTRA_RUNTIME_DIR`, XDG variables. Default `process.env`. */
155
+ readonly env?: Environment;
156
+ /** The host's connection, required in `host` mode. */
157
+ readonly stdio?: {
158
+ readonly input: Readable;
159
+ readonly output: Writable;
160
+ };
161
+ /** How long a starter waits for a locked home's owner. Default 20 s. */
162
+ readonly waitMs?: number;
163
+ /** How often the socket and the home are checked, in ms (at most 10 s). Default 5 s. */
164
+ readonly checkIntervalMs?: number;
165
+ /** Where warnings and errors are mirrored besides the log, such as stderr. */
166
+ readonly mirror?: (line: string) => void;
167
+ /** `--bind`: the address the gateway listens on; `127.0.0.1` when absent (D99). */
168
+ readonly bind?: string | undefined;
169
+ /** `--url-host`: the host name URLs use; required with a wildcard `--bind` (D99). */
170
+ readonly urlHost?: string | undefined;
171
+ /**
172
+ * `--always-on`: a daemon that never exits for lack of work, as the login service runs it
173
+ * (D62). Without it a daemon exits after 30 idle minutes.
174
+ */
175
+ readonly alwaysOn?: boolean;
176
+ }
177
+ /** How a stopped instance ended. */
178
+ interface InstanceStop {
179
+ /** Why it stopped. */
180
+ readonly reason: string;
181
+ /** 0 for a requested stop; 3 when the home disappeared; 1 for an unexpected failure. */
182
+ readonly exitCode: number;
183
+ /** The diagnostic, when it stopped because of one. */
184
+ readonly diagnostic?: Diagnostic;
185
+ }
186
+ /** A running instance that owns its home. */
187
+ interface Instance {
188
+ /** What `mostra/initialize` reports. */
189
+ readonly info: InstanceInfo;
190
+ /** The control socket clients attach to. */
191
+ readonly socketPath: string;
192
+ /** The process manager every child goes through. */
193
+ readonly processes: ProcessManager;
194
+ /** What start-up reaped from an earlier supervisor of this home. */
195
+ readonly reaped: readonly ReapedChild[];
196
+ /** Resolves when the instance has stopped and released its home. */
197
+ readonly stopped: Promise<InstanceStop>;
198
+ /** Stops the instance (D87). Idempotent; resolves with the first stop's outcome. */
199
+ stop(reason: string, exitCode?: number, diagnostic?: Diagnostic): Promise<InstanceStop>;
200
+ }
201
+ /** The outcome of {@link startInstance}. */
202
+ type StartedInstance = {
203
+ readonly kind: "owner";
204
+ readonly instance: Instance;
205
+ } | {
206
+ readonly kind: "attached";
207
+ /** The instance that owns the home. */
208
+ readonly record: InstanceRecord;
209
+ readonly result: MostraInitializeResult;
210
+ };
211
+ /** This runtime's release, from its package.json. */
212
+ export declare function runtimeVersion(): string;
213
+ /**
214
+ * Starts an instance for a home (RT-06): the platform gate, then the home's lock, migrations,
215
+ * reaping, the socket and `instance.json`. A daemon starter that finds the home owned attaches
216
+ * to the owner instead. Throws an `RpcError` carrying the diagnostic when it can do neither.
217
+ */
218
+ export declare function startInstance(options: StartInstanceOptions): Promise<StartedInstance>;
219
+ //#endregion
220
+ export type { ChildExit, ChildHandle, Environment, Instance, InstanceRecord, InstanceStop, ProcessManager, ReapedChild, SpawnSpec, StartInstanceOptions, StartedInstance, SupervisorConnection, SupervisorConnectionOptions };
221
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/log.ts","../src/home/record.ts","../src/processes/child.ts","../src/processes/manager.ts","../src/instance/index.ts"],"mappings":";;;;KAmLY,cAAc,SAAS;;;;UCpKlB;;WAEN;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;;;;UCfM;;WAEN,aAAa,gBAAgB;;WAE7B,kBAAkB,gBAAgB;;;UAI5B;;EAEf,QAAQ,gBAAgB,SAAS,gBAAgB;;EAEjD,OAAO,gBAAgB,SAAS;;;;;;;wBAQlB,oBACd,UAAS,8BACR;;;;UCIc;;WAEN;;WAEA;;WAEA;;;UAIM;;WAEN;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA,MAAM;;;;;WAKN;;;;;;WAMA,YAAY;;;;;WAKZ;aACE,aAAa,gBAAgB;aAC7B,kBAAkB,gBAAgB;;;;;;;WAOpC;;;UAIM;;WAEN;;WAEA;;WAEA;;WAEA;;EAET,QACE,gBACA,SAAS,eACT;IAAY;MACX;;WAEM,UAAU;;WAEV,QAAQ,QAAQ;;EAEzB,KAAK,mBAAmB,QAAQ;;;UAIjB;;WAEN;;WAEA;;WAEA;;WAEA;;WAEA;;;UAgBM;;EAEf,MAAM,MAAM,YAAY,QAAQ;;EAEhC;IAAmB;IAAa;IAAc;IAAkB;;;EAEhE,QAAQ,mBAAmB;;;;;UC5BZ;;WAEN;;WAEA;;WAEA,MAAM;;WAEN;aAAmB,OAAO;aAAmB,QAAQ;;;WAErD;;WAEA;;WAEA,UAAU;;WAEV;;WAEA;;;;;WAKA;;;UAIM;;WAEN;;WAEA;;WAEA,aAAa;;;UAIP;;WAEN,MAAM;;WAEN;;WAEA,WAAW;;WAEX,iBAAiB;;WAEjB,SAAS,QAAQ;;EAE1B,KAAK,gBAAgB,mBAAmB,aAAa,aAAa,QAAQ;;;KAIhE;WACG;WAAwB,UAAU;;WAElC;;WAEA,QAAQ;WACR,QAAQ;;;wBAKP;;;;;;wBA6BM,cAAc,SAAS,uBAAuB,QAAQ"}
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ import { n as startInstance, t as runtimeVersion } from "./instance-D7_UVdoN.js";
2
+ import { t as connectToSupervisor } from "./child-xrHmytks.js";
3
+ export { connectToSupervisor, runtimeVersion, startInstance };