The Open Framework for Building Agents
fix(eve): Nitro integration - strengthen core boundaries (#2076)
Andrew Barbaa7d34e5577bd
diff --git a/.changeset/clean-nitro-boundaries.md b/.changeset/clean-nitro-boundaries.mdnew file mode 100644index 000000000..05e341b0b--- /dev/null+++ b/.changeset/clean-nitro-boundaries.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Make Nitro-backed builds more reliable by preserving per-import conditional exports, keeping authored and vendored OpenTelemetry tracers on one registered provider, and running development worker close hooks during an explicit shutdown handshake. Workflow artifacts are now emitted directly instead of repaired through post-build string rewrites.diff --git a/apps/frameworks/next-multi-agent/package.json b/apps/frameworks/next-multi-agent/package.jsonindex 053e20a6e..20c9af51d 100644--- a/apps/frameworks/next-multi-agent/package.json+++ b/apps/frameworks/next-multi-agent/package.json@@ -4,7 +4,7 @@"private": true,"type": "module","scripts": {- "build": "pnpm --filter eve build && next build",+ "build": "next build","build:billing-agent": "cd agents/billing && eve build","dev": "next dev","typecheck": "tsc --noEmit -p tsconfig.json"diff --git a/apps/frameworks/next/package.json b/apps/frameworks/next/package.jsonindex f36034e6e..2be2ee547 100644--- a/apps/frameworks/next/package.json+++ b/apps/frameworks/next/package.json@@ -3,7 +3,7 @@"version": "0.1.0","private": true,"scripts": {- "build": "pnpm --filter eve build && pnpm build:next",+ "build": "pnpm build:next","dev": "next dev","dev:eve": "eve dev","build:eve": "eve build",diff --git a/apps/frameworks/nuxt/package.json b/apps/frameworks/nuxt/package.jsonindex e4bd29031..ba6cdad5a 100644--- a/apps/frameworks/nuxt/package.json+++ b/apps/frameworks/nuxt/package.json@@ -3,7 +3,7 @@"private": true,"type": "module","scripts": {- "build": "pnpm --filter eve build && nuxt build",+ "build": "nuxt build","build:nuxt": "nuxt build","dev": "nuxt dev","generate": "nuxt generate",diff --git a/apps/frameworks/sveltekit/package.json b/apps/frameworks/sveltekit/package.jsonindex e5007739f..9ee339d0b 100644--- a/apps/frameworks/sveltekit/package.json+++ b/apps/frameworks/sveltekit/package.json@@ -3,7 +3,7 @@"private": true,"type": "module","scripts": {- "build": "pnpm --filter eve build && vite build",+ "build": "vite build","build:sveltekit": "vite build","dev": "vite dev","preview": "vite preview",diff --git a/packages/eve/scripts/build-rolldown.mjs b/packages/eve/scripts/build-rolldown.mjsindex 764c4fbbd..2f6ad7a73 100644--- a/packages/eve/scripts/build-rolldown.mjs+++ b/packages/eve/scripts/build-rolldown.mjs@@ -238,7 +238,7 @@ await buildWithNitroRolldown({// `eve-source` makes `#*.js` resolve to `./src/*.ts` at build time so// sibling source files become part of the graph instead of bare// imports rolldown would refuse to follow.- conditionNames: ["eve-source", "node", "import"],+ conditionNames: ["eve-source"],mainFields: ["module", "main"],},treeshake: false,@@ -318,7 +318,7 @@ if (vueSourceFiles.length > 0) {external: isVueBuildExternal,platform: "node",resolve: {- conditionNames: ["eve-source", "node", "import"],+ conditionNames: ["eve-source"],mainFields: ["module", "main"],},treeshake: true,@@ -375,7 +375,7 @@ if (svelteSourceFiles.length > 0) {external: isSvelteBuildExternal,platform: "node",resolve: {- conditionNames: ["eve-source", "node", "import"],+ conditionNames: ["eve-source"],mainFields: ["module", "main"],},treeshake: true,diff --git a/packages/eve/scripts/check-bin-runtime-dependencies.mjs b/packages/eve/scripts/check-bin-runtime-dependencies.mjsindex 98de63e3f..bedda492a 100644--- a/packages/eve/scripts/check-bin-runtime-dependencies.mjs+++ b/packages/eve/scripts/check-bin-runtime-dependencies.mjs@@ -1,16 +1,15 @@import { readFile, readdir } from "node:fs/promises";-import { createRequire, isBuiltin } from "node:module";+import { isBuiltin } from "node:module";import { join, relative } from "node:path";-import { fileURLToPath, pathToFileURL } from "node:url";+import { fileURLToPath } from "node:url";++import { loadNitroRolldownParseAst } from "./nitro-rolldown.mjs";const packageRoot = fileURLToPath(new URL("..", import.meta.url));const packageJson = JSON.parse(await readFile(join(packageRoot, "package.json"), "utf8"));const runtimeDependencies = new Set(Object.keys(packageJson.dependencies ?? {}));const binRoot = join(packageRoot, "bin");-const require = createRequire(import.meta.url);-const nitroRequire = createRequire(require.resolve("nitro/package.json"));-const parseAstPath = nitroRequire.resolve("rolldown/parseAst");-const { parseAst } = await import(pathToFileURL(parseAstPath).href);+const { parseAst } = await loadNitroRolldownParseAst();function packageName(specifier) {if (specifier.startsWith("@")) {diff --git a/packages/eve/scripts/nitro-rolldown.mjs b/packages/eve/scripts/nitro-rolldown.mjsindex 6c5ca153c..6a9b717e6 100644--- a/packages/eve/scripts/nitro-rolldown.mjs+++ b/packages/eve/scripts/nitro-rolldown.mjs@@ -2,18 +2,59 @@ import { createRequire } from "node:module";import { pathToFileURL } from "node:url";let rolldownPromise;+let rolldownParseAstPromise;++function createNitroRequire() {+ const require = createRequire(import.meta.url);+ return createRequire(require.resolve("nitro/package.json"));+}++export function resolveNitroRolldownVersion() {+ const packageJson = createNitroRequire()("rolldown/package.json");+ if (typeof packageJson.version !== "string") {+ throw new Error("Nitro's Rolldown package does not declare a version.");+ }+ return packageJson.version;+}export async function loadNitroRolldown() {rolldownPromise ??= (async () => {- const require = createRequire(import.meta.url);- const nitroRequire = createRequire(require.resolve("nitro/package.json"));+ const nitroRequire = createNitroRequire();return await import(pathToFileURL(nitroRequire.resolve("rolldown")).href);})();return await rolldownPromise;}+export async function loadNitroRolldownParseAst() {+ rolldownParseAstPromise ??= (async () => {+ const nitroRequire = createNitroRequire();+ return await import(pathToFileURL(nitroRequire.resolve("rolldown/parseAst")).href);+ })();++ return await rolldownParseAstPromise;+}+export async function buildWithNitroRolldown(options) {+ assertCustomRolldownConditionNames(options);const { build } = await loadNitroRolldown();return await build(options);}++const ROLLDOWN_STANDARD_CONDITION_NAMES = new Set([+ "browser",+ "default",+ "import",+ "node",+ "require",+]);++function assertCustomRolldownConditionNames(options) {+ for (const conditionName of options.resolve?.conditionNames ?? []) {+ if (ROLLDOWN_STANDARD_CONDITION_NAMES.has(conditionName)) {+ throw new Error(+ `Rolldown resolves the standard condition ${JSON.stringify(conditionName)} per import edge; conditionNames may contain only eve-specific additions.`,+ );+ }+ }+}diff --git a/packages/eve/scripts/vendor-compiled.mjs b/packages/eve/scripts/vendor-compiled.mjsindex ff49144b8..9b1029061 100644--- a/packages/eve/scripts/vendor-compiled.mjs+++ b/packages/eve/scripts/vendor-compiled.mjs@@ -12,6 +12,7 @@import { dirname, join } from "node:path";import { fileURLToPath } from "node:url";+import { resolveNitroRolldownVersion } from "./nitro-rolldown.mjs";import { collectFilesRecursively, runVendor } from "./vendor-compiled/_shared.mjs";import { MODULES } from "./vendor-compiled/index.mjs";@@ -25,6 +26,8 @@ const vendorCompiledDir = join(here, "vendor-compiled");// is invalidated and vendoring re-runs.const scriptFiles = [fileURLToPath(import.meta.url),+ join(here, "nitro-rolldown.mjs"),+ join(here, "vendor-warning-log.mjs"),...(await collectFilesRecursively(vendorCompiledDir, [".mjs", ".d.ts"])),];@@ -33,4 +36,5 @@ await runVendor({compiledRoot,modules: MODULES,scriptFiles,+ toolVersions: { rolldown: resolveNitroRolldownVersion() },});diff --git a/packages/eve/scripts/vendor-compiled/@opentelemetry/api.mjs b/packages/eve/scripts/vendor-compiled/@opentelemetry/api.mjsindex 1f6557534..da8ed54e4 100644--- a/packages/eve/scripts/vendor-compiled/@opentelemetry/api.mjs+++ b/packages/eve/scripts/vendor-compiled/@opentelemetry/api.mjs@@ -1,9 +1,26 @@+import { createRequire } from "node:module";+import { dirname, join } from "node:path";+import { loadDeclaration } from "../_shared.mjs";+const require = createRequire(import.meta.url);+const commonJsEntry = require.resolve("@opentelemetry/api");+const esmEntry = join(dirname(commonJsEntry), "..", "esm", "index.js");++// @vercel/otel requests the CommonJS condition, but every vendored consumer must+// share the ESM entrypoint's proxy while producing an ESM public surface.+const preserveApiSingleton = {+ name: "eve:preserve-opentelemetry-api-singleton",+ resolveId(source) {+ return source === "@opentelemetry/api" ? esmEntry : null;+ },+};+export default {packageName: "@opentelemetry/api",compiledPath: "@opentelemetry/api",chunkGroup: "workflow",entry: "build/esm/index.js",declaration: await loadDeclaration("@opentelemetry/api.d.ts"),+ plugins: [preserveApiSingleton],};diff --git a/packages/eve/scripts/vendor-compiled/_shared.mjs b/packages/eve/scripts/vendor-compiled/_shared.mjsindex e33aede4d..73813ee88 100644--- a/packages/eve/scripts/vendor-compiled/_shared.mjs+++ b/packages/eve/scripts/vendor-compiled/_shared.mjs@@ -410,14 +410,22 @@ export function createOptionalNativeStubPlugin(packageNames) {* these files changes the cached stamp is invalidated and vendoring re-runs.* Pass everything that influences the output: the orchestrator entry script,* the `_shared.mjs` library, per-package configs, and `.d.ts` declarations.+ * @param {Record<string, string>} [options.toolVersions]+ * Resolved versions of build tools whose output contributes to vendored files.*/-export async function runVendor({ packageRoot, compiledRoot, modules, scriptFiles }) {+export async function runVendor({+ packageRoot,+ compiledRoot,+ modules,+ scriptFiles,+ toolVersions = {},+}) {const stampPath = join(compiledRoot, ".vendor-stamp.json");const lockPath = join(compiledRoot, ".vendor-lock");await mkdir(compiledRoot, { recursive: true });- const desiredStamp = await computeStamp({ scriptFiles, modules, packageRoot });+ const desiredStamp = await computeStamp({ scriptFiles, modules, packageRoot, toolVersions });if (stampMatches(desiredStamp, await readExistingStamp(stampPath))) {console.log("Compiled vendor modules are already up to date.");@@ -624,16 +632,8 @@ function getModulePlatform(module) {return module.platform ?? "node";}-function getDefaultResolve(platform) {- return platform === "neutral"- ? {- conditionNames: ["import", "default"],- mainFields: ["module", "main"],- }- : {- conditionNames: ["node", "import", "default"],- mainFields: ["module", "main"],- };+function getDefaultResolve() {+ return { mainFields: ["module", "main"] };}async function bundleStandaloneModule({ destinationRoot, module, packageInfo, packageRoot }) {@@ -654,7 +654,7 @@ async function bundleStandaloneModule({ destinationRoot, module, packageInfo, pamoduleTypes: module.loader ?? {},platform,plugins: module.plugins ?? [],- resolve: module.resolve ?? getDefaultResolve(platform),+ resolve: module.resolve ?? getDefaultResolve(),treeshake: true,output: {banner: module.banner ?? "/* oxlint-disable */",@@ -800,7 +800,7 @@ async function writeTypeOnlyModule({ module, compiledRoot, packageRoot }) {* a no-op, which makes `build:compiled` safe to invoke concurrently from* sibling Turbo tasks without racing on shared destination directories.*/-async function computeStamp({ scriptFiles, modules, packageRoot }) {+async function computeStamp({ scriptFiles, modules, packageRoot, toolVersions }) {const scriptHash = createHash("sha256");// Hash file contents in a deterministic order so identical inputs always// produce identical stamps.@@ -825,6 +825,9 @@ async function computeStamp({ scriptFiles, modules, packageRoot }) {return {moduleVersions,scriptHash: scriptHash.digest("hex"),+ toolVersions: Object.fromEntries(+ Object.entries(toolVersions).sort(([a], [b]) => a.localeCompare(b)),+ ),};}diff --git a/packages/eve/scripts/vendor-compiled/commander.mjs b/packages/eve/scripts/vendor-compiled/commander.mjsindex 846a2846a..b60284527 100644--- a/packages/eve/scripts/vendor-compiled/commander.mjs+++ b/packages/eve/scripts/vendor-compiled/commander.mjs@@ -8,11 +8,10 @@ import { join } from "node:path";* - `esm.mjs` ESM wrapper that re-exports named bindings.* - `typings/index.d.ts` Single-file declaration with no external imports.*- * The default rolldown resolution picks `esm.mjs` because the per-package- * config inherits `conditionNames: ["node", "import", "default"]`. That- * collapses the CJS `index.js` graph through the wrapper and produces an- * ESM bundle whose named exports match the source-side usage- * (`Command`, `CommanderError`, `InvalidArgumentError`).+ * Rolldown resolves this ESM entry through `esm.mjs`, collapses the CJS+ * `index.js` graph through the wrapper, and produces named exports matching+ * the source-side usage (`Command`, `CommanderError`,+ * `InvalidArgumentError`).** Declarations are copied verbatim from `typings/index.d.ts` so the type* surface tracks upstream on every bump. `createDeclarationCopier` cannotdiff --git a/packages/eve/scripts/vendor-compiled/env-runner.mjs b/packages/eve/scripts/vendor-compiled/env-runner.mjsindex 90a95d69a..bde045151 100644--- a/packages/eve/scripts/vendor-compiled/env-runner.mjs+++ b/packages/eve/scripts/vendor-compiled/env-runner.mjs@@ -1,8 +1,47 @@import { loadDeclaration } from "./_shared.mjs";+const ENV_RUNNER_SHUTDOWN_SOURCE =+ "Promise.resolve(entry.ipc?.onClose?.()).then(() => server.close()).then(() => {";+const EVE_SHUTDOWN_SOURCE =+ "Promise.resolve(server.close(true)).then(() => entry.ipc?.onClose?.()).then(() => {";+const ENV_RUNNER_EXIT_SOURCE = 'parentPort?.postMessage({ event: "exit" });';+const EVE_EXIT_SOURCE = `${ENV_RUNNER_EXIT_SOURCE}\n parentPort?.close();`;++function createGracefulNodeWorkerShutdownPlugin() {+ let patched = false;++ return {+ name: "eve-env-runner-graceful-node-worker-shutdown",+ transform(code, id) {+ if (!id.replaceAll("\\", "/").endsWith("/runners/node-worker/worker.mjs")) {+ return null;+ }+ if (!code.includes(ENV_RUNNER_SHUTDOWN_SOURCE)) {+ throw new Error("env-runner's Node worker shutdown contract changed.");+ }+ if (!code.includes(ENV_RUNNER_EXIT_SOURCE)) {+ throw new Error("env-runner's Node worker exit contract changed.");+ }+ patched = true;+ return {+ code: code+ .replace(ENV_RUNNER_SHUTDOWN_SOURCE, EVE_SHUTDOWN_SOURCE)+ .replace(ENV_RUNNER_EXIT_SOURCE, EVE_EXIT_SOURCE),+ map: null,+ };+ },+ buildEnd() {+ if (!patched) {+ throw new Error("env-runner's Node worker entry was not patched.");+ }+ },+ };+}+export default {packageName: "env-runner",compiledPath: "env-runner",+ plugins: [createGracefulNodeWorkerShutdownPlugin()],entries: [{entry: "dist/_chunks/common-base-runner.mjs",diff --git a/packages/eve/scripts/vendor-warning-log.mjs b/packages/eve/scripts/vendor-warning-log.mjsindex 417ca0a12..772d9530a 100644--- a/packages/eve/scripts/vendor-warning-log.mjs+++ b/packages/eve/scripts/vendor-warning-log.mjs@@ -25,17 +25,14 @@ function getLogFilePaths(log) {return [];}- return [- log.id,- ...(log.ids ?? []),- log.loc?.file,- typeof log.pluginCode === "string" ? log.pluginCode : undefined,- ].filter((value) => typeof value === "string");+ return [log.id, ...(log.ids ?? []), log.loc?.file].filter((value) => typeof value === "string");}function isVendoredDependencyWarning(log) {- return getLogFilePaths(log).some(- (filePath) => isNodeModulesPath(filePath) || isCompiledVendorPath(filePath),+ const filePaths = getLogFilePaths(log);+ return (+ filePaths.length > 0 &&+ filePaths.every((filePath) => isNodeModulesPath(filePath) || isCompiledVendorPath(filePath)));}diff --git a/packages/eve/src/internal/bundler/nitro-rolldown.integration.test.ts b/packages/eve/src/internal/bundler/nitro-rolldown.integration.test.tsindex a2af73bb9..77e4f54f2 100644--- a/packages/eve/src/internal/bundler/nitro-rolldown.integration.test.ts+++ b/packages/eve/src/internal/bundler/nitro-rolldown.integration.test.ts@@ -1,10 +1,14 @@-import { mkdtempSync, writeFileSync } from "node:fs";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";+import { pathToFileURL } from "node:url";import { describe, expect, it } from "vitest";-import { buildSingleRolldownChunk } from "#internal/bundler/nitro-rolldown.js";+import {+ buildSingleRolldownChunk,+ buildWithNitroRolldown,+} from "#internal/bundler/nitro-rolldown.js";function scratchModuleWithDynamicImport(): string {const dir = mkdtempSync(join(tmpdir(), "eve-single-chunk-"));@@ -23,6 +27,70 @@ function scratchModuleWithDynamicImport(): string {}describe("buildSingleRolldownChunk", () => {+ it("rejects standard condition names that override per-edge resolution", async () => {+ await expect(+ buildWithNitroRolldown({+ input: "entry.js",+ resolve: { conditionNames: ["eve-source", "import"] },+ }),+ ).rejects.toThrow('standard condition "import"');+ });++ it("preserves require conditions inside bundled CommonJS dependencies", async () => {+ const dir = mkdtempSync(join(tmpdir(), "eve-rolldown-conditions-"));+ const parentRoot = join(dir, "node_modules", "cjs-parent");+ const baseRoot = join(dir, "node_modules", "conditional-base");+ const entryPath = join(dir, "entry.mjs");+ const bundlePath = join(dir, "bundle.mjs");++ try {+ mkdirSync(parentRoot, { recursive: true });+ mkdirSync(baseRoot, { recursive: true });+ writeFileSync(+ entryPath,+ 'import Child from "cjs-parent";\nimport imported from "conditional-base";\nexport const sources = [new Child().source, imported.source];\n',+ );+ writeFileSync(+ join(parentRoot, "index.cjs"),+ 'const Base = require("conditional-base");\nmodule.exports = class Child extends Base {};\n',+ );+ writeFileSync(+ join(parentRoot, "package.json"),+ `${JSON.stringify({ main: "./index.cjs", name: "cjs-parent", version: "1.0.0" })}\n`,+ );+ writeFileSync(join(baseRoot, "import.mjs"), 'export default { source: "import" };\n');+ writeFileSync(+ join(baseRoot, "require.cjs"),+ 'module.exports = class Base { constructor() { this.source = "require"; } };\n',+ );+ writeFileSync(+ join(baseRoot, "package.json"),+ `${JSON.stringify({+ exports: { ".": { import: "./import.mjs", require: "./require.cjs" } },+ name: "conditional-base",+ type: "module",+ version: "1.0.0",+ })}\n`,+ );++ const chunk = await buildSingleRolldownChunk("conditional exports fixture", {+ cwd: dir,+ input: entryPath,+ platform: "node",+ resolve: { mainFields: ["module", "main"] },+ output: { comments: false, format: "esm" },+ });+ writeFileSync(bundlePath, chunk.code);++ const bundle = (await import(`${pathToFileURL(bundlePath).href}?test=${Date.now()}`)) as {+ readonly sources: readonly string[];+ };+ expect(bundle.sources).toEqual(["require", "import"]);+ } finally {+ rmSync(dir, { force: true, recursive: true });+ }+ });+it("inlines dynamic imports into one chunk instead of splitting", async () => {const entryPath = scratchModuleWithDynamicImport();diff --git a/packages/eve/src/internal/bundler/nitro-rolldown.ts b/packages/eve/src/internal/bundler/nitro-rolldown.tsindex adecb28ae..ad3ece8cc 100644--- a/packages/eve/src/internal/bundler/nitro-rolldown.ts+++ b/packages/eve/src/internal/bundler/nitro-rolldown.ts@@ -98,10 +98,34 @@ export async function parseWithNitroRolldownAst(export async function buildWithNitroRolldown(options: Record<string, unknown>,): Promise<RolldownOutput> {+ assertCustomRolldownConditionNames(options);const { build } = await loadNitroRolldown();return await build(options);}+const ROLLDOWN_STANDARD_CONDITION_NAMES = new Set([+ "browser",+ "default",+ "import",+ "node",+ "require",+]);++function assertCustomRolldownConditionNames(options: Record<string, unknown>): void {+ const resolve = options.resolve;+ if (resolve === null || typeof resolve !== "object") return;+ const conditionNames = Reflect.get(resolve, "conditionNames");+ if (!Array.isArray(conditionNames)) return;++ for (const conditionName of conditionNames) {+ if (typeof conditionName === "string" && ROLLDOWN_STANDARD_CONDITION_NAMES.has(conditionName)) {+ throw new Error(+ `Rolldown resolves the standard condition ${JSON.stringify(conditionName)} per import edge; conditionNames may contain only eve-specific additions.`,+ );+ }+ }+}+/*** Runs a Rolldown build whose contract is exactly one in-memory chunk:* code splitting is disabled and the result is asserted to contain adiff --git a/packages/eve/src/internal/nitro/host/application-route-registry.test.ts b/packages/eve/src/internal/nitro/host/application-route-registry.test.tsnew file mode 100644index 000000000..256317151--- /dev/null+++ b/packages/eve/src/internal/nitro/host/application-route-registry.test.ts@@ -0,0 +1,132 @@+import { describe, expect, it } from "vitest";++import {+ createApplicationRouteRegistryFromInput,+ mergeApplicationChannelRouteRegistrations,+} from "#internal/nitro/host/application-route-registry.js";++describe("mergeApplicationChannelRouteRegistrations", () => {+ it("applies authored overrides, disabled defaults, and framework-first route dedupe", () => {+ const registrations = mergeApplicationChannelRouteRegistrations({+ frameworkChannelNames: new Set(["callback", "eve", "shared"]),+ frameworkChannels: [+ { method: "POST", name: "eve", urlPath: "/framework/session" },+ { method: "POST", name: "callback", urlPath: "/callback" },+ { method: "GET", name: "shared", urlPath: "/duplicate" },+ ],+ manifestChannels: [+ { kind: "disabled", name: "callback" },+ { kind: "channel", method: "POST", name: "eve", urlPath: "/authored/session" },+ { kind: "channel", method: "GET", name: "custom", urlPath: "/duplicate" },+ ],+ });++ expect(registrations).toEqual([+ { cors: undefined, method: "GET", route: "/duplicate" },+ { cors: undefined, method: "POST", route: "/authored/session" },+ ]);+ });++ it("rejects disable files that do not name a framework channel", () => {+ expect(() =>+ mergeApplicationChannelRouteRegistrations({+ frameworkChannelNames: new Set(["eve"]),+ frameworkChannels: [],+ manifestChannels: [{ kind: "disabled", name: "unknown" }],+ }),+ ).toThrow(+ 'agent/channels/unknown.ts exports disableRoute() but "unknown" is not a framework channel',+ );+ });+});++describe("createApplicationRouteRegistryFromInput", () => {+ it("centralizes package, channel, development, and workflow precedence", () => {+ const cors = { origin: ["https://example.com"] } as const;+ const registry = createApplicationRouteRegistryFromInput({+ development: true,+ frameworkChannelNames: new Set(),+ frameworkChannels: [],+ manifestChannels: [+ { cors, kind: "channel", method: "POST", name: "hooks", urlPath: "/hooks" },+ { cors, kind: "channel", method: "GET", name: "hooks", urlPath: "/hooks" },+ { cors, kind: "channel", method: "POST", name: "copy", urlPath: "/hooks" },+ {+ cors,+ kind: "channel",+ method: "WEBSOCKET",+ name: "socket",+ urlPath: "/socket/:room",+ },+ {+ kind: "channel",+ method: "GET",+ name: "reserved-health",+ urlPath: "/eve/v1/health",+ },+ {+ kind: "channel",+ method: "GET",+ name: "dev-shadow",+ urlPath: "/eve/v1/dev/runtime-artifacts",+ },+ ],+ });++ expect(registry.channelRegistrations).toEqual([+ { cors, method: "POST", route: "/hooks" },+ { cors, method: "GET", route: "/hooks" },+ { cors, method: "WEBSOCKET", route: "/socket/:room" },+ {+ cors: undefined,+ method: "GET",+ route: "/eve/v1/dev/runtime-artifacts",+ },+ ]);+ expect(registry.routes).toEqual([+ { kind: "home", method: "GET", path: "/" },+ { kind: "health", method: "GET", path: "/eve/v1/health" },+ { kind: "health", method: "HEAD", path: "/eve/v1/health" },+ { cors, kind: "channel", method: "POST", path: "/hooks" },+ { cors, kind: "channel-preflight", method: "OPTIONS", path: "/hooks" },+ { cors, kind: "channel", method: "GET", path: "/hooks" },+ {+ cors,+ kind: "channel",+ method: "WEBSOCKET",+ path: "/socket/:room",+ },+ {+ cors: undefined,+ kind: "channel",+ method: "GET",+ path: "/eve/v1/dev/runtime-artifacts",+ },+ {+ kind: "development-schedule",+ method: "POST",+ path: "/eve/v1/dev/schedules/:scheduleId",+ },+ {+ kind: "workflow",+ method: "ALL",+ path: "/.well-known/workflow/v1/flow",+ },+ ]);+ });++ it("omits development routes outside development", () => {+ const registry = createApplicationRouteRegistryFromInput({+ frameworkChannelNames: new Set(),+ frameworkChannels: [],+ manifestChannels: [],+ });++ expect(registry.routes.map((route) => route.kind)).toEqual([+ "home",+ "health",+ "health",+ "workflow",+ ]);+ });+});diff --git a/packages/eve/src/internal/nitro/host/application-route-registry.ts b/packages/eve/src/internal/nitro/host/application-route-registry.tsnew file mode 100644index 000000000..8e0a23089--- /dev/null+++ b/packages/eve/src/internal/nitro/host/application-route-registry.ts@@ -0,0 +1,273 @@+import type { NormalizedChannelCorsOptions } from "#channel/cors.js";+import type { CompiledAgentManifest } from "#compiler/manifest.js";+import type { ChannelRouteMethod } from "#public/definitions/channel.js";+import {+ EVE_DEV_DISPATCH_SCHEDULE_ROUTE_PATTERN,+ EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH,+ EVE_HEALTH_ROUTE_PATH,+} from "#protocol/routes.js";+import {+ getAllFrameworkChannelNames,+ getFrameworkChannelDefinitions,+} from "#runtime/framework-channels/index.js";+import { EVE_WORKFLOW_FLOW_ROUTE_PATH } from "#internal/workflow-bundle/eve-service-route-output.js";++export type ApplicationRouteMethod = ChannelRouteMethod | "ALL" | "HEAD" | "OPTIONS";++export interface ApplicationChannelRouteRegistration {+ readonly method: ChannelRouteMethod;+ readonly route: string;+ readonly cors?: NormalizedChannelCorsOptions;+}++export interface ApplicationChannelRoute {+ readonly kind: "channel";+ readonly method: ChannelRouteMethod;+ readonly path: string;+ readonly cors?: NormalizedChannelCorsOptions;+}++export interface ApplicationChannelPreflightRoute {+ readonly kind: "channel-preflight";+ readonly method: "OPTIONS";+ readonly path: string;+ readonly cors: NormalizedChannelCorsOptions;+}++export type ApplicationRouteRegistration =+ | ApplicationChannelPreflightRoute+ | ApplicationChannelRoute+ | {+ readonly kind: "development-artifacts";+ readonly method: "GET";+ readonly path: string;+ }+ | {+ readonly kind: "development-schedule";+ readonly method: "POST";+ readonly path: string;+ }+ | {+ readonly kind: "health";+ readonly method: "GET" | "HEAD";+ readonly path: string;+ }+ | {+ readonly kind: "home";+ readonly method: "GET";+ readonly path: string;+ }+ | {+ readonly kind: "workflow";+ readonly method: "ALL";+ readonly path: string;+ };++export interface ApplicationRouteRegistry {+ /** Active channel bindings after framework override and route deduplication. */+ readonly channelRegistrations: readonly ApplicationChannelRouteRegistration[];+ /** Channel and preflight routes accepted by the application-wide registry. */+ readonly channelRoutes: readonly (ApplicationChannelPreflightRoute | ApplicationChannelRoute)[];+ /** Globally deduplicated method/path bindings in Nitro registration order. */+ readonly routes: readonly ApplicationRouteRegistration[];+}++interface ApplicationRouteRegistryHost {+ readonly compileResult: {+ readonly manifest: Pick<CompiledAgentManifest, "channels">;+ };+}++type ApplicationChannelManifestEntry =+ | {+ readonly kind: "channel";+ readonly name: string;+ readonly method: ChannelRouteMethod;+ readonly urlPath: string;+ readonly cors?: NormalizedChannelCorsOptions;+ }+ | {+ readonly kind: "disabled";+ readonly name: string;+ };++interface ApplicationFrameworkChannelDefinition {+ readonly name: string;+ readonly method: ChannelRouteMethod;+ readonly urlPath: string;+ readonly cors?: NormalizedChannelCorsOptions;+}++interface MergeApplicationChannelRoutesInput {+ readonly frameworkChannelNames: ReadonlySet<string>;+ readonly frameworkChannels: readonly ApplicationFrameworkChannelDefinition[];+ readonly manifestChannels: readonly ApplicationChannelManifestEntry[];+}++interface CreateApplicationRouteRegistryInput extends MergeApplicationChannelRoutesInput {+ readonly development?: boolean;+}++const PACKAGE_ROUTES: readonly ApplicationRouteRegistration[] = [+ { kind: "home", method: "GET", path: "/" },+ { kind: "health", method: "GET", path: EVE_HEALTH_ROUTE_PATH },+ { kind: "health", method: "HEAD", path: EVE_HEALTH_ROUTE_PATH },+];++function createMethodPathKey(input: {+ readonly method: ApplicationRouteMethod;+ readonly path: string;+}): string {+ return `${input.method} ${input.path}`;+}++/** Applies authored-name overrides before deduplicating framework-first route bindings. */+export function mergeApplicationChannelRouteRegistrations(+ input: MergeApplicationChannelRoutesInput,+): readonly ApplicationChannelRouteRegistration[] {+ const authoredNames = new Set<string>();+ const authoredRoutes: ApplicationChannelRouteRegistration[] = [];+ const disabledNames = new Set<string>();++ for (const entry of input.manifestChannels) {+ if (entry.kind === "disabled") {+ if (!input.frameworkChannelNames.has(entry.name)) {+ throw new Error(+ `agent/channels/${entry.name}.ts exports disableRoute() but "${entry.name}" is not a framework channel. ` ++ `Rename the file to one of: ${[...input.frameworkChannelNames].sort().join(", ")}.`,+ );+ }+ disabledNames.add(entry.name);+ continue;+ }++ authoredNames.add(entry.name);+ authoredRoutes.push({+ cors: entry.cors,+ method: entry.method,+ route: entry.urlPath,+ });+ }++ const activeFrameworkRoutes = input.frameworkChannels+ .filter((channel) => !authoredNames.has(channel.name) && !disabledNames.has(channel.name))+ .map((channel): ApplicationChannelRouteRegistration => ({+ cors: channel.cors,+ method: channel.method,+ route: channel.urlPath,+ }));++ const seen = new Set<string>();+ const merged: ApplicationChannelRouteRegistration[] = [];+ for (const registration of [...activeFrameworkRoutes, ...authoredRoutes]) {+ const key = createMethodPathKey({+ method: registration.method,+ path: registration.route,+ });+ if (!seen.has(key)) {+ seen.add(key);+ merged.push(registration);+ }+ }++ return merged;+}++/** Compiles route identity, precedence, and deduplication without importing Nitro. */+export function createApplicationRouteRegistryFromInput(+ input: CreateApplicationRouteRegistryInput,+): ApplicationRouteRegistry {+ const routes: ApplicationRouteRegistration[] = [];+ const channelRoutes: Array<ApplicationChannelPreflightRoute | ApplicationChannelRoute> = [];+ const channelRegistrations: ApplicationChannelRouteRegistration[] = [];+ const methodPaths = new Set<string>();++ const addRoute = (route: ApplicationRouteRegistration): boolean => {+ const key = createMethodPathKey(route);+ if (methodPaths.has(key)) {+ return false;+ }+ methodPaths.add(key);+ routes.push(route);+ return true;+ };++ for (const route of PACKAGE_ROUTES) {+ addRoute(route);+ }++ const preflightPaths = new Set<string>();+ for (const channel of mergeApplicationChannelRouteRegistrations(input)) {+ const channelRoute: ApplicationChannelRoute = {+ cors: channel.cors,+ kind: "channel",+ method: channel.method,+ path: channel.route,+ };+ if (!addRoute(channelRoute)) {+ continue;+ }+ channelRegistrations.push(channel);+ channelRoutes.push(channelRoute);++ if (+ channel.method !== "WEBSOCKET" &&+ channel.cors !== undefined &&+ !preflightPaths.has(channel.route)+ ) {+ preflightPaths.add(channel.route);+ const preflightRoute: ApplicationChannelPreflightRoute = {+ cors: channel.cors,+ kind: "channel-preflight",+ method: "OPTIONS",+ path: channel.route,+ };+ if (addRoute(preflightRoute)) {+ channelRoutes.push(preflightRoute);+ }+ }+ }++ if (input.development === true) {+ addRoute({+ kind: "development-artifacts",+ method: "GET",+ path: EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH,+ });+ addRoute({+ kind: "development-schedule",+ method: "POST",+ path: EVE_DEV_DISPATCH_SCHEDULE_ROUTE_PATTERN,+ });+ }++ addRoute({+ kind: "workflow",+ method: "ALL",+ path: EVE_WORKFLOW_FLOW_ROUTE_PATH,+ });++ return { channelRegistrations, channelRoutes, routes };+}++export function createApplicationRouteRegistry(+ preparedHost: ApplicationRouteRegistryHost,+ options: { readonly development?: boolean } = {},+): ApplicationRouteRegistry {+ return createApplicationRouteRegistryFromInput({+ development: options.development,+ frameworkChannelNames: getAllFrameworkChannelNames(),+ frameworkChannels: getFrameworkChannelDefinitions(),+ manifestChannels: preparedHost.compileResult.manifest.channels,+ });+}++export function computeApplicationChannelRouteRegistrations(+ preparedHost: ApplicationRouteRegistryHost,+): readonly ApplicationChannelRouteRegistration[] {+ return mergeApplicationChannelRouteRegistrations({+ frameworkChannelNames: getAllFrameworkChannelNames(),+ frameworkChannels: getFrameworkChannelDefinitions(),+ manifestChannels: preparedHost.compileResult.manifest.channels,+ });+}diff --git a/packages/eve/src/internal/nitro/host/channel-routes.test.ts b/packages/eve/src/internal/nitro/host/channel-routes.test.tsindex 92e747326..80b8209f5 100644--- a/packages/eve/src/internal/nitro/host/channel-routes.test.ts+++ b/packages/eve/src/internal/nitro/host/channel-routes.test.ts@@ -16,7 +16,15 @@ describe("registerChannelVirtualHandlers", () => {artifactsConfig: createDevelopmentNitroArtifactsConfig({appRoot: "/app",}),- registrations: [{ cors: {}, method: "POST", route: "/eve/v1/session" }],+ routes: [+ { cors: {}, kind: "channel", method: "POST", path: "/eve/v1/session" },+ {+ cors: {},+ kind: "channel-preflight",+ method: "OPTIONS",+ path: "/eve/v1/session",+ },+ ],});expect(nitro.options.handlers).toEqual([@@ -54,9 +62,25 @@ describe("registerChannelVirtualHandlers", () => {artifactsConfig: createDevelopmentNitroArtifactsConfig({appRoot: "/app",}),- registrations: [- { cors: {}, method: "GET", route: "/eve/v1/session/:sessionId/events" },- { cors: {}, method: "POST", route: "/eve/v1/session/:sessionId/events" },+ routes: [+ {+ cors: {},+ kind: "channel",+ method: "GET",+ path: "/eve/v1/session/:sessionId/events",+ },+ {+ cors: {},+ kind: "channel-preflight",+ method: "OPTIONS",+ path: "/eve/v1/session/:sessionId/events",+ },+ {+ cors: {},+ kind: "channel",+ method: "POST",+ path: "/eve/v1/session/:sessionId/events",+ },],});@@ -80,7 +104,7 @@ describe("registerChannelVirtualHandlers", () => {artifactsConfig: createDevelopmentNitroArtifactsConfig({appRoot: "/app",}),- registrations: [{ method: "WEBSOCKET", route: "/voice" }],+ routes: [{ kind: "channel", method: "WEBSOCKET", path: "/voice" }],});expect(nitro.options.handlers).toEqual([diff --git a/packages/eve/src/internal/nitro/host/channel-routes.ts b/packages/eve/src/internal/nitro/host/channel-routes.tsindex 2ed17fde3..2d897d1a9 100644--- a/packages/eve/src/internal/nitro/host/channel-routes.ts+++ b/packages/eve/src/internal/nitro/host/channel-routes.ts@@ -1,16 +1,17 @@import type { Nitro } from "nitro/types";-import type { NormalizedChannelCorsOptions } from "#channel/cors.js";import type { ChannelRouteMethod } from "#public/definitions/channel.js";-import {- getAllFrameworkChannelNames,- getFrameworkChannelDefinitions,-} from "#runtime/framework-channels/index.js";import { stringifyEsmImportSpecifier } from "#internal/application/import-specifier.js";import {resolvePackageDependencyPath,resolvePackageSourceFilePath,} from "#internal/application/package.js";+import {+ type ApplicationChannelPreflightRoute,+ type ApplicationChannelRoute,+ type ApplicationChannelRouteRegistration,+ computeApplicationChannelRouteRegistrations,+} from "#internal/nitro/host/application-route-registry.js";import type { NitroArtifactsConfig } from "#internal/nitro/routes/runtime-artifacts.js";import type { PreparedApplicationHost } from "#internal/nitro/host/types.js";@@ -20,14 +21,8 @@ interface ChannelRouteNitro {readonly options: Pick<Nitro["options"], "handlers" | "virtual">;}-/**- * One Nitro route registration for an eve channel.- */-export interface NitroChannelRouteRegistration {- readonly method: ChannelRouteMethod;- readonly route: string;- readonly cors?: NormalizedChannelCorsOptions;-}+/** One active channel binding in the eve-owned application route registry. */+export type NitroChannelRouteRegistration = ApplicationChannelRouteRegistration;/*** Computes the merged set of channel routes the Nitro host should mount.@@ -35,51 +30,7 @@ export interface NitroChannelRouteRegistration {export function computeChannelRouteRegistrations(preparedHost: PreparedApplicationHost,): readonly NitroChannelRouteRegistration[] {- const manifestChannels = preparedHost.compileResult.manifest.channels;- const authoredNames = new Set<string>();- const authoredRoutes: NitroChannelRouteRegistration[] = [];- const disabledNames = new Set<string>();- const allFrameworkNames = getAllFrameworkChannelNames();-- for (const entry of manifestChannels) {- if (entry.kind === "disabled") {- if (!allFrameworkNames.has(entry.name)) {- // The runtime resolver throws on this case — surface the same- // problem here so the dev server fails fast on bad disable files.- throw new Error(- `agent/channels/${entry.name}.ts exports disableRoute() but "${entry.name}" is not a framework channel. ` +- `Rename the file to one of: ${[...allFrameworkNames].sort().join(", ")}.`,- );- }- disabledNames.add(entry.name);- continue;- }- authoredNames.add(entry.name);- authoredRoutes.push({ method: entry.method, route: entry.urlPath, cors: entry.cors });- }-- const activeFrameworkRoutes = getFrameworkChannelDefinitions()- .filter((channel) => !authoredNames.has(channel.name) && !disabledNames.has(channel.name))- .map((channel): NitroChannelRouteRegistration => ({- method: channel.method,- route: channel.urlPath,- cors: channel.cors,- }));-- // Concatenate framework defaults first, authored second. Each- // (method, route) pair is registered exactly once.- const seen = new Set<string>();- const merged: NitroChannelRouteRegistration[] = [];- for (const registration of [...activeFrameworkRoutes, ...authoredRoutes]) {- const key = createChannelRouteKey(registration);- if (seen.has(key)) {- continue;- }- seen.add(key);- merged.push(registration);- }-- return merged;+ return computeApplicationChannelRouteRegistrations(preparedHost);}/**@@ -89,36 +40,37 @@ export function registerChannelVirtualHandlers(nitro: Pick<ChannelRouteNitro, "options">,input: {readonly artifactsConfig: NitroArtifactsConfig;- readonly registrations: readonly NitroChannelRouteRegistration[];+ readonly routes: readonly (ApplicationChannelPreflightRoute | ApplicationChannelRoute)[];},): void {- const preflightRoutes = new Set<string>();- for (const registration of input.registrations) {+ for (const route of input.routes) {addChannelVirtualHandler(nitro, {artifactsConfig: input.artifactsConfig,- cors: registration.cors,- method: registration.method,- preflightRoutes,- route: registration.route,+ route,});}}-function createChannelRouteKey(registration: NitroChannelRouteRegistration): string {- return `${registration.method.toUpperCase()} ${registration.route}`;+function createChannelRouteKey(input: {+ readonly method: ChannelRouteMethod | "OPTIONS";+ readonly path: string;+}): string {+ return `${input.method.toUpperCase()} ${input.path}`;}function addChannelVirtualHandler(nitro: Pick<ChannelRouteNitro, "options">,input: {artifactsConfig: NitroArtifactsConfig;- cors?: NormalizedChannelCorsOptions;- method: ChannelRouteMethod;- preflightRoutes: Set<string>;- route: string;+ route: ApplicationChannelPreflightRoute | ApplicationChannelRoute;},): void {- const routeKey = createChannelRouteKey(input);+ if (input.route.kind === "channel-preflight") {+ addChannelCorsPreflightHandler(nitro, input.route);+ return;+ }++ const routeKey = createChannelRouteKey(input.route);const virtualId = `${EVE_CHANNEL_VIRTUAL_ID_PREFIX}${routeKey}`;const dispatchModulePath = stringifyEsmImportSpecifier(resolvePackageSourceFilePath("src/internal/nitro/routes/channel-dispatch.ts"),@@ -126,10 +78,10 @@ function addChannelVirtualHandler(const nitroModulePath = stringifyEsmImportSpecifier(resolvePackageDependencyPath("nitro"));const nitroH3ModulePath = stringifyEsmImportSpecifier(resolvePackageDependencyPath("nitro/h3"));- if (input.method === "WEBSOCKET") {+ if (input.route.method === "WEBSOCKET") {nitro.options.handlers.push({handler: virtualId,- route: input.route,+ route: input.route.path,});nitro.options.virtual[virtualId] = [`import { defineWebSocketHandler } from ${nitroModulePath};`,@@ -142,27 +94,19 @@ function addChannelVirtualHandler(nitro.options.handlers.push({handler: virtualId,- method: input.method,- route: input.route,+ method: input.route.method,+ route: input.route.path,});- if (input.cors !== undefined) {- addChannelCorsPreflightHandler(nitro, {- cors: input.cors,- nitroH3ModulePath,- preflightRoutes: input.preflightRoutes,- route: input.route,- });- }nitro.options.virtual[virtualId] = [- ...(input.cors === undefined+ ...(input.route.cors === undefined? []: [`import { handleCors } from ${nitroH3ModulePath};`,- `const cors = ${JSON.stringify(input.cors)};`,+ `const cors = ${JSON.stringify(input.route.cors)};`,]),`import { dispatchChannelRequest } from ${dispatchModulePath};`,`const config = ${JSON.stringify(input.artifactsConfig)};`,- input.cors === undefined+ input.route.cors === undefined? `export default (event) => dispatchChannelRequest(event, ${JSON.stringify(routeKey)}, config);`: [`export default (event) => {`,@@ -176,29 +120,20 @@ function addChannelVirtualHandler(function addChannelCorsPreflightHandler(nitro: Pick<ChannelRouteNitro, "options">,- input: {- cors: NormalizedChannelCorsOptions;- nitroH3ModulePath: string;- preflightRoutes: Set<string>;- route: string;- },+ route: ApplicationChannelPreflightRoute,): void {- if (input.preflightRoutes.has(input.route)) {- return;- }- input.preflightRoutes.add(input.route);-- const routeKey = `OPTIONS ${input.route}`;+ const routeKey = createChannelRouteKey(route);const virtualId = `${EVE_CHANNEL_VIRTUAL_ID_PREFIX}${routeKey}`;+ const nitroH3ModulePath = stringifyEsmImportSpecifier(resolvePackageDependencyPath("nitro/h3"));nitro.options.handlers.push({handler: virtualId,method: "OPTIONS",- route: input.route,+ route: route.path,});nitro.options.virtual[virtualId] = [- `import { handleCors } from ${input.nitroH3ModulePath};`,- `const cors = ${JSON.stringify(input.cors)};`,+ `import { handleCors } from ${nitroH3ModulePath};`,+ `const cors = ${JSON.stringify(route.cors)};`,`export default (event) => {`,` const corsResponse = handleCors(event, cors);`,` if (corsResponse !== false) return corsResponse;`,diff --git a/packages/eve/src/internal/nitro/host/configure-nitro-routes.ts b/packages/eve/src/internal/nitro/host/configure-nitro-routes.tsindex fd9487c00..9af4bec33 100644--- a/packages/eve/src/internal/nitro/host/configure-nitro-routes.ts+++ b/packages/eve/src/internal/nitro/host/configure-nitro-routes.ts@@ -2,11 +2,6 @@ import { mkdir, writeFile } from "node:fs/promises";import { dirname, join, relative } from "node:path";import type { Nitro } from "nitro/types";-import {- EVE_DEV_DISPATCH_SCHEDULE_ROUTE_PATTERN,- EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH,- EVE_HEALTH_ROUTE_PATH,-} from "#protocol/routes.js";import {normalizeEsmImportSpecifier,stringifyEsmImportSpecifier,@@ -29,11 +24,11 @@ import type {import { deriveEveWorkflowQueuePrefix } from "#internal/workflow/queue-namespace.js";import { usesParentDevelopmentWorkflowWorld } from "#internal/workflow/development-world-protocol.js";import {- computeChannelRouteRegistrations,- registerChannelVirtualHandlers,-} from "#internal/nitro/host/channel-routes.js";+ type ApplicationRouteRegistry,+ createApplicationRouteRegistry,+} from "#internal/nitro/host/application-route-registry.js";+import { registerChannelVirtualHandlers } from "#internal/nitro/host/channel-routes.js";import type { PreparedApplicationHost } from "#internal/nitro/host/types.js";-import { EVE_WORKFLOW_FLOW_ROUTE_PATH } from "#internal/nitro/host/vercel-build-output-config.js";function registerHandler(nitro: Nitro,@@ -279,51 +274,75 @@ function registerApplicationRoutes(nitro: Nitro,preparedHost: PreparedApplicationHost,artifactsConfig: NitroArtifactsConfig,+ registry: ApplicationRouteRegistry,): void {- addFrameworkVirtualHandler(nitro, {- args: JSON.stringify({- agentName: preparedHost.compileResult.manifest.config.name,- }),- handlerExport: "handleHomePageRequest",- method: "GET",- modulePath: resolvePackageSourceFilePath("src/internal/nitro/routes/index.ts"),- route: "/",- });- for (const method of ["GET", "HEAD"] as const) {- registerHandler(nitro, {- handlerPath: resolvePackageSourceFilePath("src/internal/nitro/routes/health.ts"),- method,- route: EVE_HEALTH_ROUTE_PATH,- });+ for (const route of registry.routes) {+ switch (route.kind) {+ case "home": {+ addFrameworkVirtualHandler(nitro, {+ args: JSON.stringify({+ agentName: preparedHost.compileResult.manifest.config.name,+ }),+ handlerExport: "handleHomePageRequest",+ method: route.method,+ modulePath: resolvePackageSourceFilePath("src/internal/nitro/routes/index.ts"),+ route: route.path,+ });+ break;+ }+ case "health": {+ registerHandler(nitro, {+ handlerPath: resolvePackageSourceFilePath("src/internal/nitro/routes/health.ts"),+ method: route.method,+ route: route.path,+ });+ break;+ }+ case "channel":+ case "channel-preflight": {+ registerChannelVirtualHandlers(nitro, {+ artifactsConfig,+ routes: [route],+ });+ break;+ }+ case "development-artifacts": {+ const developmentConfig = artifactsConfig as DevelopmentNitroArtifactsConfig;+ addFrameworkVirtualHandler(nitro, {+ args: JSON.stringify({ appRoot: developmentConfig.appRoot }),+ handlerExport: "handleDevRuntimeArtifactsRequest",+ method: route.method,+ modulePath: resolvePackageSourceFilePath(+ "src/internal/nitro/routes/dev-runtime-artifacts.ts",+ ),+ route: route.path,+ });+ break;+ }+ case "development-schedule": {+ // The complete config is resolved here, in the unbundled host process,+ // and baked into the handler: resolving the module-map loader path from+ // inside the bundled dev server can land on the authored app instead of+ // the installed eve package (vercel/eve#311).+ addFrameworkVirtualHandler(nitro, {+ args: JSON.stringify(artifactsConfig),+ handlerExport: "handleDevScheduleDispatchRequest",+ method: route.method,+ modulePath: resolvePackageSourceFilePath(+ "src/internal/nitro/routes/dev-schedule-dispatch.ts",+ ),+ route: route.path,+ });+ break;+ }+ case "workflow":+ break;+ }}- registerChannelVirtualHandlers(nitro, {- artifactsConfig,- registrations: computeChannelRouteRegistrations(preparedHost),- });}-function registerDevelopmentControlRoutes(- nitro: Nitro,- artifactsConfig: DevelopmentNitroArtifactsConfig,-): void {- addFrameworkVirtualHandler(nitro, {- args: JSON.stringify({ appRoot: artifactsConfig.appRoot }),- handlerExport: "handleDevRuntimeArtifactsRequest",- method: "GET",- modulePath: resolvePackageSourceFilePath("src/internal/nitro/routes/dev-runtime-artifacts.ts"),- route: EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH,- });- addFrameworkVirtualHandler(nitro, {- // The complete config is resolved here, in the unbundled host process,- // and baked into the handler: resolving the module-map loader path from- // inside the bundled dev server can land on the authored app instead of- // the installed eve package (vercel/eve#311).- args: JSON.stringify(artifactsConfig),- handlerExport: "handleDevScheduleDispatchRequest",- method: "POST",- modulePath: resolvePackageSourceFilePath("src/internal/nitro/routes/dev-schedule-dispatch.ts"),- route: EVE_DEV_DISPATCH_SCHEDULE_ROUTE_PATTERN,- });+function findWorkflowRoute(registry: ApplicationRouteRegistry): string | undefined {+ return registry.routes.find((route) => route.kind === "workflow")?.path;}function createWorkflowDirectHandlerEntry(@@ -341,6 +360,7 @@ async function registerWorkflowRoute(preparedHost: PreparedApplicationHost,workflowBundlePath: string,directHandlers: ReadonlyArray<WorkflowDirectHandlerEntry>,+ route: string,): Promise<void> {const runtimeImportSpecifier =directHandlers.length === 0@@ -351,7 +371,7 @@ async function registerWorkflowRoute(bundleName: "workflows",bundlePath: workflowBundlePath,directHandlers,- route: EVE_WORKFLOW_FLOW_ROUTE_PATH,+ route,runtimeImportSpecifier,workflowWorldPluginPath: preparedHost.compiledArtifacts.workflowWorldPluginPath,});@@ -387,8 +407,8 @@ export async function configureDevelopmentNitroRoutes(appRoot: preparedHost.appRoot,configuredWorld: preparedHost.compileResult.manifest.config.experimental?.workflow?.world,});- registerApplicationRoutes(nitro, preparedHost, artifactsConfig);- registerDevelopmentControlRoutes(nitro, artifactsConfig);+ const routeRegistry = createApplicationRouteRegistry(preparedHost, { development: true });+ registerApplicationRoutes(nitro, preparedHost, artifactsConfig, routeRegistry);const workflowBundlePath = join(workflowBuildDirectory, "workflows.mjs");const directHandlers: WorkflowDirectHandlerEntry[] = [];@@ -399,7 +419,16 @@ export async function configureDevelopmentNitroRoutes() {directHandlers.push(createWorkflowDirectHandlerEntry(preparedHost, workflowBundlePath));}- await registerWorkflowRoute(nitro, preparedHost, workflowBundlePath, directHandlers);+ const workflowRoute = findWorkflowRoute(routeRegistry);+ if (workflowRoute !== undefined) {+ await registerWorkflowRoute(+ nitro,+ preparedHost,+ workflowBundlePath,+ directHandlers,+ workflowRoute,+ );+ }nitro.routing.sync();}@@ -426,7 +455,13 @@ export async function configureProductionNitroRoutes(};await registerWorkflowArtifactBuildHook(nitro, syncWorkflowArtifacts);- registerApplicationRoutes(nitro, preparedHost, createProductionNitroArtifactsConfig());+ const routeRegistry = createApplicationRouteRegistry(preparedHost);+ registerApplicationRoutes(+ nitro,+ preparedHost,+ createProductionNitroArtifactsConfig(),+ routeRegistry,+ );const workflowBundlePath = join(preparedHost.workflowBuildDir, "workflows.mjs");const hasConfiguredWorkflowWorld =@@ -435,7 +470,16 @@ export async function configureProductionNitroRoutes(!isVercelBuildEnvironment() && hasConfiguredWorkflowWorld? [createWorkflowDirectHandlerEntry(preparedHost, workflowBundlePath)]: [];- await registerWorkflowRoute(nitro, preparedHost, workflowBundlePath, directHandlers);+ const workflowRoute = findWorkflowRoute(routeRegistry);+ if (workflowRoute !== undefined) {+ await registerWorkflowRoute(+ nitro,+ preparedHost,+ workflowBundlePath,+ directHandlers,+ workflowRoute,+ );+ }nitro.routing.sync();}diff --git a/packages/eve/src/internal/nitro/host/dev-runner.scenario.test.ts b/packages/eve/src/internal/nitro/host/dev-runner.scenario.test.tsnew file mode 100644index 000000000..0204b0806--- /dev/null+++ b/packages/eve/src/internal/nitro/host/dev-runner.scenario.test.ts@@ -0,0 +1,57 @@+import { readFile, writeFile } from "node:fs/promises";+import { join } from "node:path";++import { describe, expect, it, vi } from "vitest";++import { createNodeDevelopmentRunner } from "#internal/nitro/host/dev-runner.js";+import { useTemporaryDirectories } from "#internal/testing/use-temporary-app-roots.js";++const createScratchDirectory = useTemporaryDirectories();++describe("Node development runner", () => {+ it("runs the worker IPC close hook during graceful shutdown", async () => {+ const root = await createScratchDirectory("eve-dev-runner-shutdown-");+ const entryPath = join(root, "worker.mjs");+ const markerPath = join(root, "closed.txt");+ await writeFile(+ entryPath,+ [+ 'import { writeFile } from "node:fs/promises";',+ "",+ "export default {",+ ' fetch: () => new Response("worker-ready"),',+ " ipc: {",+ " async onClose() {",+ ` await writeFile(${JSON.stringify(markerPath)}, "gracefully-closed\\n", "utf8");`,+ " },",+ " },",+ "};",+ "",+ ].join("\n"),+ "utf8",+ );++ const runner = createNodeDevelopmentRunner({+ entry: entryPath,+ name: "eve-dev-runner-shutdown-test",+ workerData: {},+ });+ let closeDurationMs = Number.POSITIVE_INFINITY;++ try {+ await runner.waitForReady(5_000);+ const response = await runner.fetch(new Request("http://eve.test/"));+ await expect(response.text()).resolves.toBe("worker-ready");+ } finally {+ const closeStartedAt = performance.now();+ await runner.close();+ closeDurationMs = performance.now() - closeStartedAt;+ }++ expect(closeDurationMs).toBeLessThan(5_000);+ await expect(readFile(markerPath, "utf8")).resolves.toBe("gracefully-closed\n");+ const lateCloseListener = vi.fn();+ runner.onceClosed(lateCloseListener);+ expect(lateCloseListener).toHaveBeenCalledWith(undefined);+ });+});diff --git a/packages/eve/src/internal/nitro/host/dev-runner.ts b/packages/eve/src/internal/nitro/host/dev-runner.tsindex a30fd169d..b0897c9fa 100644--- a/packages/eve/src/internal/nitro/host/dev-runner.ts+++ b/packages/eve/src/internal/nitro/host/dev-runner.ts@@ -4,6 +4,8 @@ import { Worker } from "node:worker_threads";import { BaseEnvRunner } from "#compiled/env-runner/index.js";import { resolvePackageCompiledFilePath } from "#internal/application/package.js";+const DEVELOPMENT_WORKER_SHUTDOWN_TIMEOUT_MS = 15_000;+export interface DevelopmentRunner {readonly closed: boolean;close(cause?: unknown): Promise<void>;@@ -31,6 +33,8 @@ class NodeDevelopmentRunner extends BaseEnvRunner implements DevelopmentRunner {#closeCause: unknown;readonly #closedListeners = new Set<(cause?: unknown) => void>();#worker: Worker | undefined;+ #workerExit: Promise<void> | undefined;+ #workerHasExited = false;constructor(input: DevelopmentRunnerInput) {const workerEntry = resolvePackageCompiledFilePath("src/compiled/env-runner/node-worker.js");@@ -97,9 +101,24 @@ class NodeDevelopmentRunner extends BaseEnvRunner implements DevelopmentRunner {return;}+ const workerExit = this.#workerExit;this.#worker = undefined;- worker.removeAllListeners();- await worker.terminate();+ this.#workerExit = undefined;++ try {+ if (!this.#workerHasExited) {+ worker.postMessage({ event: "shutdown" });+ }+ if (+ !this.#workerHasExited &&+ workerExit !== undefined &&+ !(await waitForWorkerExit(workerExit))+ ) {+ await worker.terminate();+ }+ } finally {+ worker.removeAllListeners();+ }}protected override _handleMessage(message: unknown): void {@@ -123,14 +142,23 @@ class NodeDevelopmentRunner extends BaseEnvRunner implements DevelopmentRunner {},});this.#worker = worker;+ this.#workerHasExited = false;+ let resolveWorkerExit!: () => void;+ this.#workerExit = new Promise((resolve) => {+ resolveWorkerExit = resolve;+ });worker.once("error", (error) => {this.#closeCause = error;void this.close(error);});worker.once("exit", (code) => {- const error = new Error(`Development worker exited with code ${String(code)}.`);- this.#closeCause ??= error;- void this.close(error);+ this.#workerHasExited = true;+ resolveWorkerExit();+ if (!this.closed) {+ const error = new Error(`Development worker exited with code ${String(code)}.`);+ this.#closeCause ??= error;+ void this.close(error);+ }});worker.on("message", (message: unknown) => this._handleMessage(message));}@@ -139,6 +167,21 @@ class NodeDevelopmentRunner extends BaseEnvRunner implements DevelopmentRunner {export const createNodeDevelopmentRunner: DevelopmentRunnerFactory = (input) =>new NodeDevelopmentRunner(input);+async function waitForWorkerExit(workerExit: Promise<void>): Promise<boolean> {+ let timer: NodeJS.Timeout | undefined;+ try {+ return await Promise.race([+ workerExit.then(() => true),+ new Promise<false>((resolve) => {+ timer = setTimeout(() => resolve(false), DEVELOPMENT_WORKER_SHUTDOWN_TIMEOUT_MS);+ timer.unref();+ }),+ ]);+ } finally {+ clearTimeout(timer);+ }+}+function isWorkerInitializationError(value: unknown,): value is { readonly error: string; readonly event: "init-error" } {diff --git a/packages/eve/src/internal/nitro/host/nitro-bundler-config.test.ts b/packages/eve/src/internal/nitro/host/nitro-bundler-config.test.tsindex d34d61770..899b61cda 100644--- a/packages/eve/src/internal/nitro/host/nitro-bundler-config.test.ts+++ b/packages/eve/src/internal/nitro/host/nitro-bundler-config.test.ts@@ -79,4 +79,21 @@ describe("createNitroBundlerConfig", () => {expect.objectContaining({ message: "dependency build failure" }),);});++ it("preserves cross-module warnings that involve authored code", () => {+ const onLog = getBundlerLogHandler();+ const defaultHandler = vi.fn();+ const mixedWarning = {+ id: "/app/agent/tools/evaluate.ts",+ ids: [+ "/app/agent/tools/evaluate.ts",+ "/app/node_modules/eve/dist/src/compiled/vendor/index.js",+ ],+ pluginCode: "/app/node_modules/eve/dist/src/compiled/vendor/index.js",+ };++ onLog("warn", mixedWarning, defaultHandler);++ expect(defaultHandler).toHaveBeenCalledWith("warn", mixedWarning);+ });});diff --git a/packages/eve/src/internal/nitro/host/nitro-bundler-config.ts b/packages/eve/src/internal/nitro/host/nitro-bundler-config.tsindex 3bb1e90e2..21ccbfcef 100644--- a/packages/eve/src/internal/nitro/host/nitro-bundler-config.ts+++ b/packages/eve/src/internal/nitro/host/nitro-bundler-config.ts@@ -6,7 +6,6 @@ interface BundlerLog {readonly loc?: {readonly file?: string;};- readonly pluginCode?: unknown;}type BundlerDefaultLogHandler = (level: string, log: unknown) => void;@@ -41,17 +40,16 @@ function getLogFilePaths(log: unknown): string[] {const candidate = log as BundlerLog;const ids = Array.isArray(candidate.ids) ? candidate.ids : [];- return [- candidate.id,- ...ids,- candidate.loc?.file,- typeof candidate.pluginCode === "string" ? candidate.pluginCode : undefined,- ].filter((value): value is string => typeof value === "string");+ return [candidate.id, ...ids, candidate.loc?.file].filter(+ (value): value is string => typeof value === "string",+ );}function isVendoredDependencyWarning(log: unknown): boolean {- return getLogFilePaths(log).some(- (filePath) => isNodeModulesPath(filePath) || isCompiledVendorPath(filePath),+ const filePaths = getLogFilePaths(log);+ return (+ filePaths.length > 0 &&+ filePaths.every((filePath) => isNodeModulesPath(filePath) || isCompiledVendorPath(filePath)));}diff --git a/packages/eve/src/internal/workflow-bundle/builder-support.integration.test.ts b/packages/eve/src/internal/workflow-bundle/builder-support.integration.test.tsindex 6177dad9b..09abd3c07 100644--- a/packages/eve/src/internal/workflow-bundle/builder-support.integration.test.ts+++ b/packages/eve/src/internal/workflow-bundle/builder-support.integration.test.ts@@ -1,32 +1,52 @@+import { Buffer } from "node:buffer";import { mkdtemp, readFile, rm } from "node:fs/promises";import { tmpdir } from "node:os";import { join } from "node:path";import { describe, expect, it } from "vitest";-import { resolvePackageRoot, resolveWorkflowModulePath } from "#internal/application/package.js";+import { normalizeEsmImportSpecifier } from "#internal/application/import-specifier.js";+import { resolveWorkflowModulePath } from "#internal/application/package.js";import { bundleFinalWorkflowOutput } from "./builder-support.js";describe("bundleFinalWorkflowOutput", () => {- it("writes the intermediate wrapper against the namespaced eve Workflow runtime facade", async () => {+ it("writes the final wrapper with encoded code and resolved runtime imports", async () => {const dir = await mkdtemp(join(tmpdir(), "eve-workflow-runtime-facade-"));const target = join(dir, "workflows.mjs");+ const workflowCode = [+ "globalThis.__private_workflows = new Map();",+ "//# sourceMappingURL=data:application/json;base64,ZmFrZQ==",+ ].join("\n");try {await bundleFinalWorkflowOutput({- bundleFinalOutput: false,- code: "globalThis.__private_workflows = new Map();",- format: "esm",+ code: workflowCode,outfile: target,queueNamespace: "evetest",- workingDir: resolvePackageRoot(),+ stepRegistrationsPath: join(dir, "steps.mjs"),});const source = await readFile(target, "utf8");- const runtimePath = resolveWorkflowModulePath("workflow/runtime").replaceAll("\\", "/");- expect(source).toContain(`from ${JSON.stringify(runtimePath)}`);+ const runtimeSpecifier = normalizeEsmImportSpecifier(+ resolveWorkflowModulePath("workflow/runtime"),+ );+ expect(source).toContain(`from ${JSON.stringify(runtimeSpecifier)}`);+ expect(source).toContain('Buffer.from(["');+ expect(source).not.toContain("const workflowCode = `");expect(source).toContain('workflowEntrypoint(workflowCode, { namespace: "evetest" })');+ expect(source).toContain(+ 'import { __steps_registered as __eveWorkflowStepsRegistered } from "./steps.mjs";',+ );+ expect(source).toContain("void __eveWorkflowStepsRegistered;");expect(source).not.toContain('from "workflow/runtime"');++ const encodedChunksMatch = source.match(+ /Buffer\.from\((\[[\s\S]*?\])\.join\(""\), "base64"\)\.toString\("utf8"\)/,+ );+ const encodedChunks = JSON.parse(encodedChunksMatch?.[1] ?? "[]") as string[];+ expect(Buffer.from(encodedChunks.join(""), "base64").toString("utf8")).toBe(+ `${workflowCode}\n`,+ );} finally {await rm(dir, { recursive: true, force: true });}diff --git a/packages/eve/src/internal/workflow-bundle/builder-support.ts b/packages/eve/src/internal/workflow-bundle/builder-support.tsindex ec1cefd2b..9f8721cba 100644--- a/packages/eve/src/internal/workflow-bundle/builder-support.ts+++ b/packages/eve/src/internal/workflow-bundle/builder-support.ts@@ -6,6 +6,7 @@ import { dirname, join, relative, resolve } from "node:path";import { atomicWriteFile } from "#shared/atomic-write-file.js";import { buildSingleRolldownChunk } from "#internal/bundler/nitro-rolldown.js";+import { normalizeEsmImportSpecifier } from "#internal/application/import-specifier.js";import { resolveWorkflowModulePath } from "#internal/application/package.js";import {applyWorkflowTransform,@@ -78,21 +79,23 @@ export interface WorkflowBundleDiscoveredEntries {}export interface WorkflowBundleCreateWorkflowsBundleOptions {- readonly bundleFinalOutput?: boolean;+ readonly additionalOutputs?: readonly WorkflowBundleOutput[];readonly discoveredEntries?: WorkflowBundleDiscoveredEntries;- readonly format?: "cjs" | "esm";readonly inputFiles: readonly string[];- readonly keepInterimBundleContext?: boolean;readonly outfile: string;+ readonly stepRegistrationsPath: string;readonly tsconfigPath?: string;}export interface WorkflowBundleCreateWorkflowsBundleResult {- readonly bundleFinal?: (interimBundleResult: string) => Promise<void>;- readonly interimBundleCtx?: undefined;readonly manifest: WorkflowManifest;}+export interface WorkflowBundleOutput {+ readonly outfile: string;+ readonly stepRegistrationsPath: string;+}+interface WorkflowGraph {readonly edges: readonly unknown[];readonly nodes: readonly unknown[];@@ -342,7 +345,7 @@ export async function bundleWorkflowStepRegistrations(input: {}),],resolve: {- conditionNames: ["eve-source", "node", "import", "default"],+ conditionNames: ["eve-source"],extensions: [".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs"],mainFields: ["module", "main"],},@@ -385,41 +388,50 @@ export function createWorkflowNodeBuiltinGuardPlugin(): WorkflowRolldownPlugin {}export async function bundleFinalWorkflowOutput(input: {- bundleFinalOutput: boolean;code: string;- format: "cjs" | "esm";outfile: string;queueNamespace: string;- workingDir: string;+ stepRegistrationsPath?: string;}): Promise<void> {- const workflowBundleCode = input.code.endsWith("\n") ? input.code : `${input.code}\n`;- const workflowRuntimePath = resolveWorkflowModulePath("workflow/runtime").replaceAll("\\", "/");- const workflowFunctionCode = `// biome-ignore-all lint: generated file-/* eslint-disable */-import { workflowEntrypoint } from ${JSON.stringify(workflowRuntimePath)};+ const workflowFunctionCode = createWorkflowEntrypointSource({+ code: input.code,+ queueNamespace: input.queueNamespace,+ stepRegistrationsImport:+ input.stepRegistrationsPath === undefined+ ? undefined+ : toRelativeImportSpecifier(dirname(input.outfile), input.stepRegistrationsPath),+ });-const workflowCode = \`${workflowBundleCode.replace(/[\\`$]/g, "\\$&")}\`;+ await writeWorkflowBundleAtomically(input.outfile, workflowFunctionCode);+}-export const POST = workflowEntrypoint(workflowCode, { namespace: ${JSON.stringify(input.queueNamespace)} });`;+export function createWorkflowEntrypointSource(input: {+ readonly code: string;+ readonly queueNamespace: string;+ readonly stepRegistrationsImport?: string;+}): string {+ const workflowRuntimePath = normalizeEsmImportSpecifier(+ resolveWorkflowModulePath("workflow/runtime"),+ );+ const encodedWorkflowCode = Buffer.from(+ input.code.endsWith("\n") ? input.code : `${input.code}\n`,+ "utf8",+ ).toString("base64");+ const chunks = encodedWorkflowCode.match(/.{1,16384}/gu) ?? [""];++ const stepRegistrationsImport =+ input.stepRegistrationsImport === undefined+ ? ""+ : `import { __steps_registered as __eveWorkflowStepsRegistered } from ${JSON.stringify(input.stepRegistrationsImport)};\nvoid __eveWorkflowStepsRegistered;`;++ return `// Generated by eve. Do not edit by hand.+import { workflowEntrypoint } from ${JSON.stringify(workflowRuntimePath)};+${stepRegistrationsImport}- if (!input.bundleFinalOutput) {- await writeWorkflowBundleAtomically(input.outfile, workflowFunctionCode);- return;- }+const workflowCode = Buffer.from(${JSON.stringify(chunks)}.join(""), "base64").toString("utf8");- const chunk = await buildSingleRolldownChunk(`final workflow bundle for "${input.outfile}"`, {- cwd: input.workingDir,- input: WORKFLOW_VIRTUAL_ENTRY_ID,- external: (source: string) => source === "@aws-sdk/credential-provider-web-identity",- platform: "node",- plugins: [createWorkflowVirtualEntryPlugin(workflowFunctionCode)],- output: {- comments: false,- format: input.format,- sourcemap: false,- },- });- await writeWorkflowBundleAtomically(input.outfile, chunk.code);+export const POST = workflowEntrypoint(workflowCode, { namespace: ${JSON.stringify(input.queueNamespace)} });+`;}export function convertStepsManifest(steps: WorkflowManifest["steps"]): Record<string, unknown> {diff --git a/packages/eve/src/internal/workflow-bundle/builder.scenario.test.ts b/packages/eve/src/internal/workflow-bundle/builder.scenario.test.tsindex cd05adf91..4eaad4f0c 100644--- a/packages/eve/src/internal/workflow-bundle/builder.scenario.test.ts+++ b/packages/eve/src/internal/workflow-bundle/builder.scenario.test.ts@@ -14,8 +14,45 @@ import {} from "#internal/application/package.js";import { WorkflowBundleBuilder } from "#internal/workflow-bundle/builder.js";+import { createWorkflowEntrypointSource } from "#internal/workflow-bundle/builder-support.js";import type { WorkflowManifest } from "#internal/workflow-bundle/workflow-builders.js";+const REQUIRE_EXPORT_MARKER = "eve-workflow-conditional-require-export";+const IMPORT_EXPORT_MARKER = "eve-workflow-conditional-import-export";++async function writeConditionalRequirePackages(root: string): Promise<void> {+ const parentRoot = join(root, "node_modules", "cjs-parent");+ const baseRoot = join(root, "node_modules", "conditional-base");+ await Promise.all([mkdir(parentRoot, { recursive: true }), mkdir(baseRoot, { recursive: true })]);+ await Promise.all([+ writeFile(+ join(parentRoot, "index.cjs"),+ 'const Base = require("conditional-base");\nmodule.exports = class Child extends Base {};\n',+ ),+ writeFile(+ join(parentRoot, "package.json"),+ `${JSON.stringify({ main: "./index.cjs", name: "cjs-parent", version: "1.0.0" })}\n`,+ ),+ writeFile(+ join(baseRoot, "import.mjs"),+ `export default { source: ${JSON.stringify(IMPORT_EXPORT_MARKER)} };\n`,+ ),+ writeFile(+ join(baseRoot, "package.json"),+ `${JSON.stringify({+ exports: { ".": { import: "./import.mjs", require: "./require.cjs" } },+ name: "conditional-base",+ type: "module",+ version: "1.0.0",+ })}\n`,+ ),+ writeFile(+ join(baseRoot, "require.cjs"),+ `module.exports = class Base { constructor() { this.source = ${JSON.stringify(REQUIRE_EXPORT_MARKER)}; } };\n`,+ ),+ ]);+}+class InspectableWorkflowBundleBuilder extends WorkflowBundleBuilder {readonly outDir: string;@@ -59,8 +96,6 @@ class StepEntryOnlyWorkflowBundleBuilder extends WorkflowBundleBuilder {}protected override async createWorkflowsBundle(): Promise<{- bundleFinal?: (interimBundleResult: string) => Promise<void>;- interimBundleCtx?: undefined;manifest: Record<string, never>;}> {this.workflowBundleCalls += 1;@@ -162,6 +197,120 @@ describe("WorkflowBundleBuilder", () => {}});+ it("writes cache and Nitro workflow entries with target-relative step imports", async () => {+ const tempRoot = await mkdtemp(join(tmpdir(), "eve-workflow-bundle-nitro-outputs-"));+ const outDir = join(tempRoot, "workflow-cache");+ const flowFilePath = join(tempRoot, "flow.ts");+ const compiledArtifactsBootstrapPath = join(tempRoot, "compiled-artifacts-bootstrap.mjs");+ const nitroWorkflowOutfile = join(tempRoot, "nitro", "workflow", "workflows.mjs");+ const nitroStepOutfile = join(tempRoot, "nitro", "entries", "steps.mjs");++ try {+ await Promise.all([+ writeFile(compiledArtifactsBootstrapPath, "export {};\n"),+ writeFile(+ flowFilePath,+ [+ "export async function ping() {",+ ' "use step";',+ ' return "pong";',+ "}",+ "export async function flow() {",+ ' "use workflow";',+ " return ping();",+ "}",+ "",+ ].join("\n"),+ ),+ ]);++ const builder = new FixtureWorkflowBundleBuilder(+ {+ agentName: "test-agent",+ appRoot: tempRoot,+ compiledArtifactsBootstrapPath,+ outDir,+ rootDir: tempRoot,+ watch: false,+ },+ [flowFilePath],+ );++ await builder.build({ nitroStepOutfile, nitroWorkflowOutfile });++ const cacheWorkflowSource = await readFile(join(outDir, "workflows.mjs"), "utf8");+ const nitroWorkflowSource = await readFile(nitroWorkflowOutfile, "utf8");+ expect(cacheWorkflowSource).toContain('from "./steps.mjs";');+ expect(nitroWorkflowSource).toContain('from "../entries/steps.mjs";');+ expect(nitroWorkflowSource).toContain(resolveWorkflowModulePath("workflow/runtime"));+ await expect(readFile(nitroStepOutfile, "utf8")).resolves.toContain(+ "export const __steps_registered = true;",+ );++ for (const source of [cacheWorkflowSource, nitroWorkflowSource]) {+ const encodedChunksMatch = source.match(+ /Buffer\.from\((\[[\s\S]*?\])\.join\(""\), "base64"\)\.toString\("utf8"\)/,+ );+ const encodedChunks = JSON.parse(encodedChunksMatch?.[1] ?? "[]") as string[];+ const workflowCode = Buffer.from(encodedChunks.join(""), "base64").toString("utf8");+ expect(workflowCode).toContain("sourceMappingURL=data:application/json");+ expect(workflowCode).toContain(";base64,");+ }+ } finally {+ await rm(tempRoot, { force: true, recursive: true });+ }+ });++ it("preserves require exports in workflow CommonJS dependencies", async () => {+ const tempRoot = await mkdtemp(join(tmpdir(), "eve-workflow-bundle-conditions-"));+ const outDir = join(tempRoot, "workflow-build");+ const flowFilePath = join(tempRoot, "flow.ts");+ const compiledArtifactsBootstrapPath = join(tempRoot, "compiled-artifacts-bootstrap.mjs");++ try {+ await writeConditionalRequirePackages(tempRoot);+ await Promise.all([+ writeFile(compiledArtifactsBootstrapPath, "export {};\n"),+ writeFile(+ flowFilePath,+ [+ 'import Child from "cjs-parent";',+ "export async function conditionalWorkflow() {",+ ' "use workflow";',+ " return new Child().source;",+ "}",+ "",+ ].join("\n"),+ ),+ ]);++ const builder = new FixtureWorkflowBundleBuilder(+ {+ agentName: "test-agent",+ appRoot: tempRoot,+ compiledArtifactsBootstrapPath,+ outDir,+ rootDir: tempRoot,+ watch: false,+ },+ [flowFilePath],+ );++ await builder.build();++ const workflowsSource = await readFile(join(outDir, "workflows.mjs"), "utf8");+ const encodedChunksMatch = workflowsSource.match(+ /Buffer\.from\((\[[\s\S]*?\])\.join\(""\), "base64"\)\.toString\("utf8"\)/,+ );+ const encodedChunks = JSON.parse(encodedChunksMatch?.[1] ?? "[]") as string[];+ const workflowSource = Buffer.from(encodedChunks.join(""), "base64").toString("utf8");+ expect(workflowSource).toContain(REQUIRE_EXPORT_MARKER);+ expect(workflowSource).not.toContain(IMPORT_EXPORT_MARKER);+ } finally {+ await rm(tempRoot, { force: true, recursive: true });+ }+ });+it("clears workflow cache output from a different eve version", async () => {const tempRoot = await mkdtemp(join(tmpdir(), "eve-workflow-bundle-version-cache-"));const outDir = join(tempRoot, "workflow-build");@@ -227,7 +376,7 @@ describe("WorkflowBundleBuilder", () => {}});- it("rewrites generated workflow code template literals to parser-safe base64 chunks", async () => {+ it("writes generated workflow code as parser-safe base64 chunks", async () => {const tempRoot = await mkdtemp(join(tmpdir(), "eve-workflow-bundle-code-literal-"));const outDir = join(tempRoot, "workflow-build");const stepFilePath = join(tempRoot, "steps", "ping.ts");@@ -246,14 +395,11 @@ describe("WorkflowBundleBuilder", () => {await writeFile(outfile,- [- "import { workflowEntrypoint } from 'workflow/runtime';",- "",- `const workflowCode = \`${workflowBundleCode.replace(/[\\`$]/g, "\\$&")}\`;`,- "",- 'export const POST = workflowEntrypoint(workflowCode, { namespace: "eve746573742d6167656e74" });',- "",- ].join("\n"),+ createWorkflowEntrypointSource({+ code: workflowBundleCode,+ queueNamespace: "eve746573742d6167656e74",+ stepRegistrationsImport: "./steps.mjs",+ }),);return { manifest: {} };diff --git a/packages/eve/src/internal/workflow-bundle/builder.ts b/packages/eve/src/internal/workflow-bundle/builder.tsindex 0547510ff..f04951034 100644--- a/packages/eve/src/internal/workflow-bundle/builder.ts+++ b/packages/eve/src/internal/workflow-bundle/builder.ts@@ -1,6 +1,5 @@-import { Buffer } from "node:buffer";import { mkdir, readFile, writeFile } from "node:fs/promises";-import { dirname, join, relative, resolve } from "node:path";+import { dirname, join, resolve } from "node:path";import {resolvePackageSourceDirectoryPath,@@ -10,9 +9,7 @@ import {prepareEveVersionedCacheDirectory,writeEveVersionedCacheMetadata,} from "#internal/application/cache-metadata.js";-import { normalizeEsmImportSpecifier } from "#internal/application/import-specifier.js";import { runQueuedWorkflowBuild } from "#internal/workflow-bundle/build-queue.js";-import { atomicWriteFile } from "#shared/atomic-write-file.js";import {bundleFinalWorkflowOutput,collectWorkflowInputFiles,@@ -96,18 +93,10 @@ export class WorkflowBundleBuilder {await mkdir(this.#outDir, { recursive: true });const discoveredEntries = await this.discoverEntries(inputFiles, this.#outDir, tsconfigPath);- const workflowsOutfile = join(this.#outDir, "workflows.mjs");- const { manifest: workflowsManifest } = await this.createWorkflowsBundle({- discoveredEntries,- // eve owns dev rebuilds through `dev-authored-source-watcher`.- keepInterimBundleContext: false,- outfile: workflowsOutfile,- bundleFinalOutput: false,- format: "esm",- inputFiles,- tsconfigPath,- });const stepsOutfile = join(this.#outDir, "steps.mjs");+ const workflowsOutfile = join(this.#outDir, "workflows.mjs");+ const nitroStepOutfile = options.nitroStepOutfile;+ const nitroWorkflowOutfile = options.nitroWorkflowOutfile;const stepsManifest = await writeNitroStepEntrypoint({builtinsPath: resolveWorkflowModulePath("workflow/internal/builtins"),discoveredEntries,@@ -117,8 +106,6 @@ export class WorkflowBundleBuilder {sideEffectFiles: [this.#compiledArtifactsBootstrapPath],workingDir: this.config.workingDir,});- const nitroStepOutfile = options.nitroStepOutfile;-if (nitroStepOutfile !== undefined && nitroStepOutfile !== stepsOutfile) {await writeNitroStepEntrypoint({builtinsPath: resolveWorkflowModulePath("workflow/internal/builtins"),@@ -130,22 +117,22 @@ export class WorkflowBundleBuilder {workingDir: this.config.workingDir,});}-- await addStepRegistrationsImport(workflowsOutfile, stepsOutfile);- await rewriteWorkflowRuntimeImports(workflowsOutfile);- await rewriteWorkflowCodeLiteral(workflowsOutfile, this.#queueNamespace);-- const nitroWorkflowOutfile = options.nitroWorkflowOutfile;-- if (nitroWorkflowOutfile !== undefined && nitroWorkflowOutfile !== workflowsOutfile) {- await mkdir(dirname(nitroWorkflowOutfile), { recursive: true });- await mirrorFileBypassingUnlink(workflowsOutfile, nitroWorkflowOutfile);- if (nitroStepOutfile !== undefined) {- await addStepRegistrationsImport(nitroWorkflowOutfile, nitroStepOutfile);- await rewriteWorkflowRuntimeImports(nitroWorkflowOutfile);- await rewriteWorkflowCodeLiteral(nitroWorkflowOutfile, this.#queueNamespace);- }- }+ const { manifest: workflowsManifest } = await this.createWorkflowsBundle({+ additionalOutputs:+ nitroWorkflowOutfile === undefined || nitroWorkflowOutfile === workflowsOutfile+ ? []+ : [+ {+ outfile: nitroWorkflowOutfile,+ stepRegistrationsPath: nitroStepOutfile ?? stepsOutfile,+ },+ ],+ discoveredEntries,+ outfile: workflowsOutfile,+ inputFiles,+ stepRegistrationsPath: stepsOutfile,+ tsconfigPath,+ });await this.createManifest({workflowBundlePath: join(this.#outDir, "workflows.mjs"),@@ -244,12 +231,11 @@ export class WorkflowBundleBuilder {}protected async createWorkflowsBundle({- bundleFinalOutput = true,+ additionalOutputs = [],discoveredEntries,- format = "cjs",inputFiles,- keepInterimBundleContext = this.config.watch,outfile,+ stepRegistrationsPath,tsconfigPath,}: WorkflowBundleCreateWorkflowsBundleOptions): Promise<WorkflowBundleCreateWorkflowsBundleResult> {const discovered =@@ -285,7 +271,7 @@ export class WorkflowBundleBuilder {createWorkflowNodeBuiltinGuardPlugin(),],resolve: {- conditionNames: ["eve-source", "workflow", "node", "import", "default"],+ conditionNames: ["eve-source", "workflow"],extensions: [".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs"],mainFields: ["module", "main"],},@@ -299,31 +285,16 @@ export class WorkflowBundleBuilder {},);- await bundleFinalWorkflowOutput({- bundleFinalOutput,- code: interimBundle.code,- format,- outfile,- queueNamespace: this.#queueNamespace,- workingDir: this.config.workingDir,- });-- if (keepInterimBundleContext) {- return {- bundleFinal: async (interimBundleResult: string) => {- await bundleFinalWorkflowOutput({- bundleFinalOutput,- code: interimBundleResult,- format,- outfile,- queueNamespace: this.#queueNamespace,- workingDir: this.config.workingDir,- });- },- interimBundleCtx: undefined,- manifest: workflowManifest,- };- }+ await Promise.all(+ [{ outfile, stepRegistrationsPath }, ...additionalOutputs].map((output) =>+ bundleFinalWorkflowOutput({+ code: interimBundle.code,+ outfile: output.outfile,+ queueNamespace: this.#queueNamespace,+ stepRegistrationsPath: output.stepRegistrationsPath,+ }),+ ),+ );return { manifest: workflowManifest };}@@ -353,187 +324,3 @@ export class WorkflowBundleBuilder {return await this.getInputFiles();}}--async function addStepRegistrationsImport(- workflowBundlePath: string,- stepRegistrationsPath: string,-): Promise<void> {- const source = await readTextFileIfPresent(workflowBundlePath);-- if (source === null || source.includes("__eveWorkflowStepsRegistered")) {- return;- }-- const importSpecifier = createRelativeImportSpecifier(- dirname(workflowBundlePath),- stepRegistrationsPath,- );- const importSource = [- `import { __steps_registered as __eveWorkflowStepsRegistered } from ${JSON.stringify(importSpecifier)};`,- "void __eveWorkflowStepsRegistered;",- "",- ].join("\n");- const firstImportMatch = source.match(/^import\s.+?;\n/m);-- if (firstImportMatch === null || firstImportMatch.index === undefined) {- await atomicWriteFile(workflowBundlePath, `${importSource}${source}`);- return;- }-- const insertionIndex = firstImportMatch.index + firstImportMatch[0].length;- const nextSource = `${source.slice(0, insertionIndex)}${importSource}${source.slice(insertionIndex)}`;-- await atomicWriteFile(workflowBundlePath, nextSource);-}--async function rewriteWorkflowRuntimeImports(filePath: string): Promise<void> {- const source = await readTextFileIfPresent(filePath);-- if (source === null) {- return;- }-- let nextSource = source;-- for (const specifier of [- "workflow",- "workflow/api",- "workflow/internal/builtins",- "workflow/internal/private",- "workflow/runtime",- ]) {- const resolvedSpecifier = normalizeImportSpecifierPath(resolveWorkflowModulePath(specifier));- nextSource = replaceStringLiteralSpecifier(nextSource, specifier, resolvedSpecifier);- }-- if (nextSource !== source) {- await atomicWriteFile(filePath, nextSource);- }-}--async function rewriteWorkflowCodeLiteral(filePath: string, queueNamespace: string): Promise<void> {- const source = await readTextFileIfPresent(filePath);-- if (source === null) {- return;- }-- const declarationPrefix = "const workflowCode = ";- const declarationSuffix = `;\n\nexport const POST = workflowEntrypoint(workflowCode, { namespace: ${JSON.stringify(queueNamespace)} });`;- const expressionStart = source.indexOf(declarationPrefix);- const expressionEnd = source.lastIndexOf(declarationSuffix);-- if (expressionStart === -1 || expressionEnd === -1 || expressionEnd <= expressionStart) {- return;- }-- const valueStart = expressionStart + declarationPrefix.length;- const expression = source.slice(valueStart, expressionEnd);-- if (!expression.trimStart().startsWith("`")) {- return;- }-- const workflowCode = decodeWorkflowCodeTemplateLiteral(expression, filePath);- const nextSource = `${source.slice(0, valueStart)}${encodeWorkflowCodeLiteral(workflowCode)}${source.slice(- expressionEnd,- )}`;-- if (nextSource !== source) {- await atomicWriteFile(filePath, nextSource);- }-}--function encodeWorkflowCodeLiteral(workflowCode: string): string {- const encodedWorkflowCode = Buffer.from(workflowCode, "utf8").toString("base64");- const chunks = encodedWorkflowCode.match(/.{1,16384}/g) ?? [""];-- return `Buffer.from(${JSON.stringify(chunks)}.join(""), "base64").toString("utf8")`;-}--function decodeWorkflowCodeTemplateLiteral(expression: string, filePath: string): string {- const trimmedExpression = expression.trim();-- if (!trimmedExpression.startsWith("`") || !trimmedExpression.endsWith("`")) {- throw new Error(`Expected generated workflow code literal in "${filePath}" to be a template.`);- }-- const rawValue = trimmedExpression.slice(1, -1);- let value = "";-- for (let index = 0; index < rawValue.length; index += 1) {- const char = rawValue[index];-- if (char !== "\\") {- value += char;- continue;- }-- const escapedChar = rawValue[index + 1];-- if (escapedChar === "\\" || escapedChar === "`" || escapedChar === "$") {- value += escapedChar;- index += 1;- continue;- }-- value += char;- }-- return value;-}--function replaceStringLiteralSpecifier(source: string, from: string, to: string): string {- return source- .replaceAll(JSON.stringify(from), JSON.stringify(to))- .replaceAll(`'${from}'`, JSON.stringify(to));-}--function normalizeImportSpecifierPath(path: string): string {- return normalizeEsmImportSpecifier(path);-}--function createRelativeImportSpecifier(fromDirectoryPath: string, targetPath: string): string {- const relativePath = relative(fromDirectoryPath, targetPath).replaceAll("\\", "/");-- if (relativePath.startsWith(".")) {- return relativePath;- }-- return `./${relativePath}`;-}--async function readTextFileIfPresent(filePath: string): Promise<string | null> {- try {- return await readFile(filePath, "utf8");- } catch (error) {- if (error instanceof Error && "code" in error && error.code === "ENOENT") {- return null;- }-- throw error;- }-}--async function readBinaryFileIfPresent(filePath: string): Promise<Buffer | null> {- try {- return await readFile(filePath);- } catch (error) {- if (error instanceof Error && "code" in error && error.code === "ENOENT") {- return null;- }-- throw error;- }-}--async function mirrorFileBypassingUnlink(sourcePath: string, targetPath: string): Promise<void> {- const sourceContents = await readFile(sourcePath);- const existingContents = await readBinaryFileIfPresent(targetPath);-- if (existingContents !== null && existingContents.equals(sourceContents)) {- return;- }-- await atomicWriteFile(targetPath, sourceContents);-}diff --git a/packages/eve/src/tracing/local-instrumentation-runtime.scenario.test.ts b/packages/eve/src/tracing/local-instrumentation-runtime.scenario.test.tsindex fdca682b0..cea9bbba7 100644--- a/packages/eve/src/tracing/local-instrumentation-runtime.scenario.test.ts+++ b/packages/eve/src/tracing/local-instrumentation-runtime.scenario.test.ts@@ -5,7 +5,7 @@ import { join } from "node:path";import { ROOT_CONTEXT, trace as apiTrace } from "@opentelemetry/api";import { BasicTracerProvider } from "@opentelemetry/sdk-trace-base";-import { afterEach, describe, expect, it, vi } from "vitest";+import { afterEach, describe, expect, it } from "vitest";import {ROOT_CONTEXT as COMPILED_ROOT_CONTEXT,@@ -38,15 +38,16 @@ describe("local instrumentation runtime", () => {it("persists agent, AI, and user spans in one trace", async () => {const appRoot = await mkdtemp(join(tmpdir(), "eve-local-traces-"));temporaryDirectories.push(appRoot);+ // Resolve and cache the public API tracer before eve installs its vendored+ // provider, matching an authored module's normal module-scope setup.+ const authoredTracer = (+ require("@opentelemetry/api") as typeof import("@opentelemetry/api")+ ).trace.getTracer("test-user");const runtime = installLocalInstrumentationRuntime({appRoot,frameworkVersion: "test",serviceName: "test-agent",});- // Resolve the public API outside Vitest's transformed module graph, as an- // authored app does when it imports its own @opentelemetry/api dependency.- const authoredTrace = (require("@opentelemetry/api") as typeof import("@opentelemetry/api"))- .trace;const scope: InstrumentationAttemptScope = {attemptId: "session-1:turn-1:0:0",attemptIndex: 0,@@ -58,9 +59,8 @@ describe("local instrumentation runtime", () => {};const delivery = runtimeTrace.getTracer("workflow").startSpan("workflow.delivery");const activeContext = runtimeTrace.setSpan(COMPILED_ROOT_CONTEXT, delivery);- const contextActive = vi.spyOn(runtimeContext, "active").mockReturnValue(activeContext);- await contextStorage.run(new ContextContainer(), async () => {+ const exerciseRuntime = async () => {await runtime.hooks.publish({agentName: "weather",idempotencyKey: sessionIdempotencyKey("session-1"),@@ -87,12 +87,18 @@ describe("local instrumentation runtime", () => {]);await Reflect.apply(bridge.onStepStart!, bridge, [{ callId: "call-1", stepNumber: 0 }]);await Reflect.apply(bridge.onLanguageModelCallStart!, bridge, [- { callId: "call-1", messages: [], modelId: "model-1", provider: "test", tools: undefined },+ {+ callId: "call-1",+ messages: [],+ modelId: "model-1",+ provider: "test",+ tools: undefined,+ },]);await bridge.executeLanguageModelCall!({callId: "call-1",execute: async () => {- const span = authoredTrace.getTracer("test-user").startSpan("user.model-work");+ const span = authoredTracer.startSpan("user.model-work");expect(span.isRecording()).toBe(true);await Promise.resolve();span.end();@@ -127,7 +133,7 @@ describe("local instrumentation runtime", () => {await bridge.executeTool!({callId: "call-1",execute: async () => {- const span = authoredTrace.getTracer("test-user").startSpan("user.tool-work");+ const span = authoredTracer.startSpan("user.tool-work");expect(span.isRecording()).toBe(true);await Promise.resolve();span.end();@@ -168,8 +174,10 @@ describe("local instrumentation runtime", () => {turnId: "turn-1",type: "session.waiting",});- });- contextActive.mockRestore();+ };+ await runtimeContext.with(activeContext, () =>+ contextStorage.run(new ContextContainer(), exerciseRuntime),+ );delivery.end();await runtime.forceFlush();diff --git a/packages/eve/src/tracing/otel-registration.scenario.test.ts b/packages/eve/src/tracing/otel-registration.scenario.test.tsindex c9b70a089..21a46f94d 100644--- a/packages/eve/src/tracing/otel-registration.scenario.test.ts+++ b/packages/eve/src/tracing/otel-registration.scenario.test.ts@@ -1,3 +1,5 @@+import { createRequire } from "node:module";+import { context, propagation, trace, type Context } from "@opentelemetry/api";import {BasicTracerProvider,@@ -6,15 +8,59 @@ import {} from "@opentelemetry/sdk-trace-base";import { afterEach, describe, expect, it, vi } from "vitest";+import {+ ROOT_CONTEXT as COMPILED_ROOT_CONTEXT,+ context as runtimeContext,+ trace as runtimeTrace,+} from "#compiled/@opentelemetry/api/index.js";import { registerOtelPipeline } from "#tracing/otel-registration.js";+const require = createRequire(import.meta.url);+const authoredApi = require("@opentelemetry/api") as typeof import("@opentelemetry/api");+afterEach(() => {+ authoredApi.context.disable();+ authoredApi.propagation.disable();+ authoredApi.trace.disable();context.disable();propagation.disable();trace.disable();+ (runtimeContext as typeof runtimeContext & { disable(): void }).disable();+ (runtimeTrace as typeof runtimeTrace & { disable(): void }).disable();});describe("registerOtelPipeline", () => {+ it("delegates an authored tracer cached before registration", async () => {+ const authoredTracer = authoredApi.trace.getTracer("authored");+ expect(authoredTracer.startSpan("before-registration").isRecording()).toBe(false);++ const exporter = new InMemorySpanExporter();+ const processor = new SimpleSpanProcessor(exporter);+ const runtime = registerOtelPipeline({+ pipeline: { spanProcessors: [processor] },+ serviceName: "weather",+ });+ const parent = runtimeTrace.getTracer("eve").startSpan("eve.parent");+ const parentContext = parent.spanContext();+ const activeContext = runtimeTrace.setSpan(COMPILED_ROOT_CONTEXT, parent);+ const child = await runtimeContext.with(activeContext, async () => {+ await Promise.resolve();+ return authoredTracer.startSpan("authored.child");+ });++ expect(child.isRecording()).toBe(true);+ expect(child.spanContext().traceId).toBe(parentContext.traceId);+ child.end();+ parent.end();+ await runtime.forceFlush();++ const exportedChild = exporter+ .getFinishedSpans()+ .find((span) => span.name === "authored.child");+ expect(exportedChild?.parentSpanContext?.spanId).toBe(parentContext.spanId);+ await runtime.shutdown();+ });+it("verifies tracer ownership when the sampler records nothing", () => {expect(() =>registerOtelPipeline({@@ -59,7 +105,13 @@ describe("registerOtelPipeline", () => {it("leaves an existing tracer provider untouched when registration fails", () => {const provider = new BasicTracerProvider();const shutdown = vi.spyOn(provider, "shutdown");- expect(trace.setGlobalTracerProvider(provider)).toBe(true);+ expect(authoredApi.trace.setGlobalTracerProvider(provider)).toBe(true);+ const authoredProxy = authoredApi.trace.getTracerProvider();+ expect(authoredProxy).toBeInstanceOf(authoredApi.ProxyTracerProvider);+ const setDelegate = vi.spyOn(+ authoredProxy as InstanceType<typeof authoredApi.ProxyTracerProvider>,+ "setDelegate",+ );expect(() =>registerOtelPipeline({@@ -69,6 +121,7 @@ describe("registerOtelPipeline", () => {).toThrow(/another runtime already owns the global tracer provider/u);expect(currentTracerDelegate()).toBe(provider);+ expect(setDelegate).not.toHaveBeenCalled();expect(shutdown).not.toHaveBeenCalled();expect(propagation.setGlobalPropagator({diff --git a/packages/eve/src/tracing/otel-registration.ts b/packages/eve/src/tracing/otel-registration.tsindex eb54545a5..e9e02950d 100644--- a/packages/eve/src/tracing/otel-registration.ts+++ b/packages/eve/src/tracing/otel-registration.ts@@ -1,3 +1,5 @@+import { createRequire } from "node:module";+import { context, propagation, trace, type Context } from "#compiled/@opentelemetry/api/index.js";import {registerOTel,@@ -11,6 +13,7 @@ import type { OtelPipeline } from "#tracing/otel-declaration.js";const REGISTRATION_SPAN_NAME = "eve.otel.registration";const REPLAY_DEDUPLICATION_LIMIT = 100_000;+const require = createRequire(import.meta.url);class RegistrationMarkerPropagator {#injected = false;@@ -107,6 +110,9 @@ export function registerOtelPipeline(input: {readonly serviceName: string;}): RegisteredOtelPipeline {const { pipeline } = input;+ // A tracer cached before registration retains this private proxy even after+ // the vendored API takes the global slot. Delegate it only after ownership is proven.+ const optionalPeerTracerProxy = captureOptionalPeerTracerProxy();const idGenerator = new AgentSpanIdGenerator();const markerPropagator = new RegistrationMarkerPropagator();const configuration: Configuration = {@@ -150,6 +156,7 @@ export function registerOtelPipeline(input: {rollbackRegistration({ ownsPropagator, ownsTracer });throw new Error("The registered OpenTelemetry tracer provider has no lifecycle methods.");}+ optionalPeerTracerProxy?.setDelegate(provider);return {forceFlush: () => provider.forceFlush!(),idGenerator,@@ -173,6 +180,20 @@ interface ProxyTracerProvider {getDelegate(): unknown;}+interface OptionalPeerTracerProxy {+ setDelegate(delegate: unknown): void;+}++function captureOptionalPeerTracerProxy(): OptionalPeerTracerProxy | undefined {+ try {+ const api = require("@opentelemetry/api") as typeof import("@opentelemetry/api");+ const provider = api.trace.getTracerProvider();+ return provider instanceof api.ProxyTracerProvider ? provider : undefined;+ } catch {+ return undefined;+ }+}+function rollbackRegistration(input: {readonly ownsPropagator: boolean;readonly ownsTracer: boolean;diff --git a/packages/eve/test/scenarios/bundle-module-evaluation.scenario.test.ts b/packages/eve/test/scenarios/bundle-module-evaluation.scenario.test.tsindex 22929d5a8..1eeba0aba 100644--- a/packages/eve/test/scenarios/bundle-module-evaluation.scenario.test.ts+++ b/packages/eve/test/scenarios/bundle-module-evaluation.scenario.test.ts@@ -45,7 +45,7 @@ async function bundleEveDistAsSingleChunk(input: RolldownInputOptions): Promise<return !isEveOwnedSpecifier(source);},resolve: {- conditionNames: ["eve-source", "node", "import"],+ conditionNames: ["eve-source"],mainFields: ["module", "main"],},treeshake: false,diff --git a/packages/eve/test/scenarios/compiled-vendor-assets.scenario.test.ts b/packages/eve/test/scenarios/compiled-vendor-assets.scenario.test.tsindex c8461c8c7..a189be5bd 100644--- a/packages/eve/test/scenarios/compiled-vendor-assets.scenario.test.ts+++ b/packages/eve/test/scenarios/compiled-vendor-assets.scenario.test.ts@@ -1,13 +1,16 @@+import { execFile } from "node:child_process";import { readdir, readFile } from "node:fs/promises";import { createRequire } from "node:module";import { dirname, join } from "node:path";import { fileURLToPath, pathToFileURL } from "node:url";+import { promisify } from "node:util";import { describe, expect, it } from "vitest";const EVE_PACKAGE_ROOT = fileURLToPath(new URL("../../", import.meta.url));const COMPILED_VENDOR_ROOT = join(EVE_PACKAGE_ROOT, ".generated", "compiled");const VENDOR_WARNING_LOG_PATH = join(EVE_PACKAGE_ROOT, "scripts", "vendor-warning-log.mjs");+const execFileAsync = promisify(execFile);const require = createRequire(import.meta.url);const VERCEL_SANDBOX_DRIVES_DIST_ROOT = join(dirname(require.resolve("@vercel/sandbox-drives/package.json")),@@ -24,8 +27,10 @@ type VendorWarningLog = {level: string,log: {readonly id?: string;+ readonly ids?: readonly string[];readonly loc?: { readonly file?: string };readonly message: string;+ readonly pluginCode?: string;},defaultHandler: (level: string, log: { readonly message: string }) => void,) => void;@@ -56,6 +61,86 @@ function rewriteDeclarationImports(}describe("compiled vendor assets", () => {+ it("stamps the Nitro-resolved Rolldown version", async () => {+ const stamp = JSON.parse(+ await readFile(join(COMPILED_VENDOR_ROOT, ".vendor-stamp.json"), "utf8"),+ ) as { toolVersions?: { rolldown?: string } };+ const nitroRequire = createRequire(require.resolve("nitro/package.json"));+ const rolldownPackage = nitroRequire("rolldown/package.json") as { version: string };++ expect(stamp.toolVersions?.rolldown).toBe(rolldownPackage.version);+ });++ it("shares the OpenTelemetry provider registered through @vercel/otel", async () => {+ const apiUrl = pathToFileURL(+ join(COMPILED_VENDOR_ROOT, "@opentelemetry", "api", "index.js"),+ ).href;+ const vercelOtelUrl = pathToFileURL(+ join(COMPILED_VENDOR_ROOT, "@vercel", "otel", "index.js"),+ ).href;+ const { stdout } = await execFileAsync(process.execPath, [+ "--input-type=module",+ "--eval",+ [+ 'import { createRequire } from "node:module";',+ `import { ROOT_CONTEXT, context, trace } from ${JSON.stringify(apiUrl)};`,+ `import { registerOTel } from ${JSON.stringify(vercelOtelUrl)};`,+ "const require = createRequire(import.meta.url);",+ 'const authoredApi = require("@opentelemetry/api");',+ "const endedSpans = [];",+ "const spanProcessor = {",+ " forceFlush: async () => {},",+ " onEnd: (span) => endedSpans.push(span),",+ " onStart: () => {},",+ " shutdown: async () => {},",+ "};",+ 'const earlyTracer = trace.getTracer("early");',+ 'const before = earlyTracer.startSpan("before").isRecording();',+ "registerOTel({",+ " autoDetectResources: false,",+ " instrumentations: [],",+ ' serviceName: "eve-vendored-opentelemetry-test",',+ " spanProcessors: [spanProcessor],",+ "});",+ 'const earlySpan = earlyTracer.startSpan("early-after-registration");',+ 'const lateSpan = trace.getTracer("late").startSpan("late-after-registration");',+ "const earlyAfter = earlySpan.isRecording();",+ "const lateAfter = lateSpan.isRecording();",+ "earlySpan.end();",+ "lateSpan.end();",+ 'const parent = trace.getTracer("vendored").startSpan("vendored-parent");',+ "await context.with(trace.setSpan(ROOT_CONTEXT, parent), async () => {",+ " await Promise.resolve();",+ ' authoredApi.trace.getTracer("authored").startSpan("authored-child").end();',+ "});",+ "parent.end();",+ 'const child = endedSpans.find((span) => span.name === "authored-child");',+ "process.stdout.write(JSON.stringify({",+ " before,",+ " childParentSpanId: child?.parentSpanContext?.spanId,",+ " childParentTraceId: child?.parentSpanContext?.traceId,",+ " earlyAfter,",+ " lateAfter,",+ " parentSpanId: parent.spanContext().spanId,",+ " parentTraceId: parent.spanContext().traceId,",+ "}));",+ ].join("\n"),+ ]);++ const result = JSON.parse(stdout) as {+ readonly before: boolean;+ readonly childParentSpanId: string;+ readonly childParentTraceId: string;+ readonly earlyAfter: boolean;+ readonly lateAfter: boolean;+ readonly parentSpanId: string;+ readonly parentTraceId: string;+ };+ expect(result).toMatchObject({ before: false, earlyAfter: true, lateAfter: true });+ expect(result.childParentTraceId).toBe(result.parentTraceId);+ expect(result.childParentSpanId).toBe(result.parentSpanId);+ });+it("does not generate source maps for vendored packages", async () => {const entries = await readdir(COMPILED_VENDOR_ROOT, {recursive: true,@@ -143,6 +228,18 @@ describe("compiled vendor assets", () => {forwardedLogs.push(`${level}:${log.message}`);},);+ filter.onLog(+ "warn",+ {+ id: scriptFilePath,+ ids: [scriptFilePath, generatedCompiledFilePath],+ message: "mixed eve and dependency warning",+ pluginCode: generatedCompiledFilePath,+ },+ (level, log) => {+ forwardedLogs.push(`${level}:${log.message}`);+ },+ );filter.onLog("error",{@@ -156,7 +253,11 @@ describe("compiled vendor assets", () => {},);- expect(forwardedLogs).toEqual(["warn:eve vendoring warning", "error:dependency build failure"]);+ expect(forwardedLogs).toEqual([+ "warn:eve vendoring warning",+ "warn:mixed eve and dependency warning",+ "error:dependency build failure",+ ]);});it("copies @workflow/core declaration files from the installed package", async () => {diff --git a/packages/eve/test/scenarios/framework-next-build.scenario.test.ts b/packages/eve/test/scenarios/framework-next-build.scenario.test.tsindex 4c42e9afc..1398d6654 100644--- a/packages/eve/test/scenarios/framework-next-build.scenario.test.ts+++ b/packages/eve/test/scenarios/framework-next-build.scenario.test.ts@@ -129,12 +129,8 @@ async function readVercelOutputRoutes(outputRoot: string): Promise<readonly unkndescribe("framework-next build", () => {it("builds the Next.js framework fixture against the workspace eve dist", async () => {- // Runs `build:next` rather than the fixture's `build` script: `build`- // regenerates the shared workspace `dist/`, which would corrupt scenario- // files running in parallel workers. The scenario globalSetup already- // rebuilt `dist/` before any worker forked.await runPnpmCommand({- args: ["--filter", "framework-next", "build:next"],+ args: ["--filter", "framework-next", "build"],cwd: REPO_ROOT,});}, 180_000);diff --git a/packages/eve/test/scenarios/framework-nuxt-build.scenario.test.ts b/packages/eve/test/scenarios/framework-nuxt-build.scenario.test.tsindex 0ad882cb7..b03883d07 100644--- a/packages/eve/test/scenarios/framework-nuxt-build.scenario.test.ts+++ b/packages/eve/test/scenarios/framework-nuxt-build.scenario.test.ts@@ -59,12 +59,8 @@ function isFilesystemHandle(route: unknown): boolean {describe("framework-nuxt build", () => {it("builds the Nuxt framework fixture against the workspace eve dist", async () => {- // Runs `build:nuxt` rather than the fixture's `build` script: `build`- // regenerates the shared workspace `dist/`, which would corrupt scenario- // files running in parallel workers. The scenario globalSetup already- // rebuilt `dist/` before any worker forked.await runPnpmCommand({- args: ["--filter", "framework-nuxt", "build:nuxt"],+ args: ["--filter", "framework-nuxt", "build"],cwd: REPO_ROOT,});}, 300_000);diff --git a/packages/eve/test/scenarios/framework-sveltekit-build.scenario.test.ts b/packages/eve/test/scenarios/framework-sveltekit-build.scenario.test.tsindex 4e03ff05d..0a2e5202e 100644--- a/packages/eve/test/scenarios/framework-sveltekit-build.scenario.test.ts+++ b/packages/eve/test/scenarios/framework-sveltekit-build.scenario.test.ts@@ -40,12 +40,8 @@ async function readVercelOutputConfig(outputRoot: string): Promise<{describe("framework-sveltekit build", () => {it("builds the SvelteKit framework fixture against the workspace eve dist", async () => {- // Runs `build:sveltekit` rather than the fixture's `build` script: `build`- // regenerates the shared workspace `dist/`, which would corrupt scenario- // files running in parallel workers. The scenario globalSetup already- // rebuilt `dist/` before any worker forked.await runPnpmCommand({- args: ["--filter", "framework-sveltekit", "build:sveltekit"],+ args: ["--filter", "framework-sveltekit", "build"],cwd: REPO_ROOT,});}, 300_000);diff --git a/packages/eve/test/scenarios/nitro-bundle-report.scenario.test.ts b/packages/eve/test/scenarios/nitro-bundle-report.scenario.test.tsindex a9c05f6e8..b1ef141ea 100644--- a/packages/eve/test/scenarios/nitro-bundle-report.scenario.test.ts+++ b/packages/eve/test/scenarios/nitro-bundle-report.scenario.test.ts@@ -40,6 +40,10 @@ interface NitroBundleReport {baselineLabel: string;package: null | {installedDependencyBytes: ReportMetricDelta;+ installedDependencyEdgeCount?: ReportMetricDelta;+ installedDistinctPackageNameCount?: ReportMetricDelta;+ installedOptionalPeerEdgeCount?: ReportMetricDelta;+ installedPackageInstanceCount?: ReportMetricDelta;installedSizeBytes: ReportMetricDelta;packedSizeBytes: ReportMetricDelta;peerDependenciesAdded: string[];@@ -86,8 +90,12 @@ interface NitroBundleReport {internalRouteCount: number;publishedPackage: null | {installedDependencyBytes: number;+ installedDependencyEdgeCount?: number;+ installedDistinctPackageNameCount?: number;installedFileCount: number;+ installedOptionalPeerEdgeCount?: number;installedPackageBytes: number;+ installedPackageInstanceCount?: number;installedSizeBytes: number;packageLabel: string;packageName: string;@@ -355,6 +363,31 @@ async function createReportFixture(await writeSizedFile(join(packageRoot, "README.md"), 400);await writeSizedFile(join(packageRoot, "dist", "index.js"), options.packageIndexBytes ?? 1_600);await writeSizedFile(join(packageRoot, "dist", "runtime.js"), options.packageRuntimeBytes ?? 900);+ await mkdir(join(packageRoot, "dist", "embedded"), {+ recursive: true,+ });+ await writeFile(+ join(packageRoot, "dist", "embedded", "package.json"),+ `${JSON.stringify(+ {+ name: "@fixture/embedded-manifest",+ dependencies: {+ "@fixture/phantom-dependency": "1.0.0",+ },+ peerDependencies: {+ "@fixture/phantom-peer": "1.0.0",+ },+ peerDependenciesMeta: {+ "@fixture/phantom-peer": {+ optional: true,+ },+ },+ },+ null,+ 2,+ )}\n`,+ "utf8",+ );for (const dependency of bundledDependencies) {await writeBundledDependency(packageRoot, dependency);@@ -401,8 +434,12 @@ describe("nitro bundle report", () => {]);expect(report.publishedPackage).toMatchObject({installedDependencyBytes: expect.any(Number),+ installedDependencyEdgeCount: 1,+ installedDistinctPackageNameCount: 2,installedFileCount: expect.any(Number),+ installedOptionalPeerEdgeCount: 1,installedPackageBytes: expect.any(Number),+ installedPackageInstanceCount: 2,installedSizeBytes: expect.any(Number),packageLabel: "packages/eve",packageName: "eve-fixture",@@ -441,6 +478,13 @@ describe("nitro bundle report", () => {expect(markdown).toContain("**Heavy installed dependencies**");expect(markdown).toContain("Installed package size");expect(markdown).toContain("Installed footprint:");+ expect(markdown).toContain("Installed package instances: 2");+ expect(markdown).toContain("Distinct installed package names: 2");+ expect(markdown).toContain("Installed dependency edges: 1");+ expect(markdown).toContain("Installed optional peer edges: 1");+ expect(markdown).toContain(+ "Graph metrics read only `package.json` files in package directories directly beneath a `node_modules` boundary",+ );expect(markdown).toContain("Published file size");expect(markdown).toContain("Runtime dependencies (1)");expect(markdown).toContain("Peer dependencies (1)");@@ -565,6 +609,10 @@ describe("nitro bundle report", () => {expect(comparison?.package?.unpackedSizeBytes.delta).toBe(400);expect(comparison?.package?.installedSizeBytes.delta).toBeGreaterThan(0);expect(comparison?.package?.installedDependencyBytes.delta).toBe(0);+ expect(comparison?.package?.installedPackageInstanceCount?.delta).toBe(0);+ expect(comparison?.package?.installedDistinctPackageNameCount?.delta).toBe(0);+ expect(comparison?.package?.installedDependencyEdgeCount?.delta).toBe(0);+ expect(comparison?.package?.installedOptionalPeerEdgeCount?.delta).toBe(0);const serverComparison = comparison?.app.functions.find((functionEntry) => functionEntry.relativePath === "functions/__server.func",@@ -589,6 +637,10 @@ describe("nitro bundle report", () => {);expect(markdown).toContain("Add the `acknowledge-bundle-warning` label");expect(markdown).toContain("| Runtime | Total function bytes |");+ expect(markdown).toContain("| Package | Installed package instances | 2 | 2 | 0 |");+ expect(markdown).toContain("| Package | Distinct installed package names | 2 | 2 | 0 |");+ expect(markdown).toContain("| Package | Installed dependency edges | 1 | 1 | 0 |");+ expect(markdown).toContain("| Package | Installed optional peer edges | 1 | 1 | 0 |");expect(markdown).toContain("| Package | Runtime dependency added | New runtime dependency `@fixture/[email protected]` was added.",);@@ -617,6 +669,30 @@ describe("nitro bundle report", () => {expect(markdown).toContain(`| \`functions/__server.func\` | changed | ${formatReportBytes(serverComparison?.totalBytes.baseline ?? 0)} | ${formatReportBytes(serverComparison?.totalBytes.current ?? 0)} | ${formatReportSizeDelta(serverComparison?.totalBytes.delta ?? 0)} |`,);++ const legacyBaselineReport = structuredClone(baselineReport);+ if (legacyBaselineReport.publishedPackage !== null) {+ delete legacyBaselineReport.publishedPackage.installedPackageInstanceCount;+ delete legacyBaselineReport.publishedPackage.installedDistinctPackageNameCount;+ delete legacyBaselineReport.publishedPackage.installedDependencyEdgeCount;+ delete legacyBaselineReport.publishedPackage.installedOptionalPeerEdgeCount;+ }+ const legacyComparison = compareNitroBundleReports(currentReport, legacyBaselineReport, {+ baselineLabel: "main",+ });+ const legacyMarkdown = renderNitroBundleReportMarkdown({+ ...currentReport,+ comparison: legacyComparison,+ });++ expect(legacyComparison?.package?.installedPackageInstanceCount).toBeUndefined();+ expect(legacyComparison?.package?.installedDistinctPackageNameCount).toBeUndefined();+ expect(legacyComparison?.package?.installedDependencyEdgeCount).toBeUndefined();+ expect(legacyComparison?.package?.installedOptionalPeerEdgeCount).toBeUndefined();+ expect(legacyMarkdown).not.toContain("| Package | Installed package instances |");+ expect(legacyMarkdown).not.toContain("| Package | Distinct installed package names |");+ expect(legacyMarkdown).not.toContain("| Package | Installed dependency edges |");+ expect(legacyMarkdown).not.toContain("| Package | Installed optional peer edges |");}, 15_000);it("fails the warning policy when a runtime dependency is added", async () => {diff --git a/packages/eve/test/scenarios/nitro-rolldown-packed.scenario.test.ts b/packages/eve/test/scenarios/nitro-rolldown-packed.scenario.test.tsnew file mode 100644index 000000000..75d119eca--- /dev/null+++ b/packages/eve/test/scenarios/nitro-rolldown-packed.scenario.test.ts@@ -0,0 +1,90 @@+import { execFile } from "node:child_process";+import { promisify } from "node:util";++import { describe, expect, it } from "vitest";++import { useScenarioApp } from "#internal/testing/scenario-app.js";++const runFile = promisify(execFile);+const scenarioApp = useScenarioApp();++const PACKED_CONSUMER_PROBE = `+import { createRequire } from "node:module";+import { dirname, join } from "node:path";+import { pathToFileURL } from "node:url";++const consumerRequire = createRequire(import.meta.url);+const consumerManifest = consumerRequire("./package.json");+const eveManifestPath = consumerRequire.resolve("eve/package.json");+const eveManifest = consumerRequire(eveManifestPath);+const eveRequire = createRequire(eveManifestPath);+const nitroManifest = eveRequire("nitro/package.json");+const wrapperPath = join(+ dirname(eveManifestPath),+ "dist/src/internal/bundler/nitro-rolldown.js",+);+const { buildWithNitroRolldown, parseWithNitroRolldownAst } = await import(+ pathToFileURL(wrapperPath).href+);++const ast = await parseWithNitroRolldownAst(+ "entry.ts",+ "export const parsedAnswer: number = 42;",+);+const build = await buildWithNitroRolldown({+ input: "virtual:entry.js",+ output: { format: "esm" },+ plugins: [+ {+ name: "packed-consumer-entry",+ resolveId(id) {+ return id === "virtual:entry.js" ? id : null;+ },+ load(id) {+ return id === "virtual:entry.js" ? "export const bundledAnswer = 42;" : null;+ },+ },+ ],+ write: false,+});+const chunk = build.output.find((entry) => entry.type === "chunk");++console.log(+ JSON.stringify({+ bundled: chunk?.code.includes("bundledAnswer") === true,+ consumerDeclaresRolldown: typeof consumerManifest.dependencies?.rolldown === "string",+ eveDeclaresRolldown: typeof eveManifest.dependencies?.rolldown === "string",+ nitroDeclaresRolldown: typeof nitroManifest.dependencies?.rolldown === "string",+ parsed:+ ast?.type === "Program" &&+ Array.isArray(ast.body) &&+ ast.body[0]?.type === "ExportNamedDeclaration",+ }),+);+`;++describe("packed Nitro Rolldown wrapper", () => {+ it("builds and parses from Nitro's dependency tree without consumer-owned Rolldown", async () => {+ const app = await scenarioApp({+ files: {+ "probe.mjs": PACKED_CONSUMER_PROBE,+ },+ installDependencies: true,+ name: "packed-nitro-rolldown",+ packageManager: "npm",+ });++ const { stdout } = await runFile(process.execPath, ["probe.mjs"], {+ cwd: app.appRoot,+ maxBuffer: 10 * 1024 * 1024,+ });++ expect(JSON.parse(stdout.trim())).toEqual({+ bundled: true,+ consumerDeclaresRolldown: false,+ eveDeclaresRolldown: false,+ nitroDeclaresRolldown: true,+ parsed: true,+ });+ }, 120_000);+});diff --git a/research/nitro-core-integration.md b/research/nitro-core-integration.mdnew file mode 100644index 000000000..944d5fcd0--- /dev/null+++ b/research/nitro-core-integration.md@@ -0,0 +1,253 @@+---+issue: https://github.com/vercel/eve/issues/2055+status: in-progress+last_updated: "2026-08-13"+---++# Nitro-first build and runtime integration++## Decision++eve will keep Nitro as its core host dependency and make the existing integration more direct,+predictable, and testable. Nitro remains responsible for the final host build, native dependency+classification and nf3 tracing, deployment presets, schedules, server lifecycle, and supported+runtime behavior. eve will not replace those systems with an eve-owned H3, CrossWS, srvx, nf3, or+platform-adapter stack.++The current pass also keeps using the Rolldown installation resolved by Nitro. An eve-owned lazy+wrapper isolates that reach-through and enforces correct resolution behavior, but importing a+transitive dependency remains technical debt. eve will move to a public Rolldown boundary only+after Nitro publishes a physical core or build package that declares Rolldown as a compatible peer.++The dependency-graph problem remains real, but it cannot be fixed inside eve while eve installs the+current `nitro` package. The upstream requirement is a physically separate Nitro core package with+its own package manifest. A `nitro/core` export, feature flags, or lazy imports would still make a+package manager resolve the umbrella manifest.++This plan carries forward the portable findings from the+[direct build and routing system review](https://github.com/vercel/eve/blob/barba/remove-nitro-build-runtime/research/nitro-removal-review.md)+without carrying forward the decision to remove Nitro.++## Ownership boundary++eve owns the agent compiler, authored-module loading, workflow artifact generation, and the+translation from compiled agent intent into Nitro configuration. Nitro owns the host graph and the+runtime behavior around that graph.++| Area | Owner | Boundary |+| ------------------------------ | ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Agent and workflow compilation | eve | eve produces entries, transforms, route intent, and compiled artifacts for Nitro to consume. |+| Final application build | Nitro | Nitro creates the base build graph, installs its plugins, invokes the bundler, traces externals, and writes output. |+| Native dependency handling | Nitro | Nitro classifies non-bundleable packages and runs nf3 tracing; eve supplies only authored or eve-specific additions through public configuration. |+| Node and deployment output | Nitro | Nitro presets own Node and Vercel output, environment aliases, runtime error behavior, and Bun selection where the selected preset supports it. |+| HTTP and WebSocket runtime | Nitro | Nitro owns H3, CrossWS, srvx, request upgrades, and preset-specific transport behavior. |+| Schedules | Nitro | Nitro's task and schedule layer owns registration, execution, concurrency, and process integration. |+| eve development orchestration | eve | eve owns authored-source watching, immutable generations, worker replacement, and the outer draining server while delegating each worker host to Nitro. |++This boundary allows eve to improve the inputs and extension points around Nitro. It does not make+eve a second host framework.++## Current-pass improvements with umbrella Nitro++### Contain the transitive Rolldown boundary++eve invokes Rolldown directly for its published JavaScript, compiled vendor artifacts,+authored-module evaluation, workflow bundles, and parser-backed transforms. In this pass, the+eve-owned lazy wrapper continues to resolve `rolldown` and `rolldown/parseAst` from Nitro's installed+dependency tree. This avoids adding another runtime declaration before Nitro defines a public+embedding boundary, but it remains an undeclared transitive contract: a fresh consumer install can+select a different Rolldown version from the one in eve's workspace lock.++All eve code that calls Rolldown should use the runtime wrapper, and package build scripts should+use the corresponding script wrapper. Both wrappers should stay lazy and enforce the same+resolution rules so importing parser-backed helpers does not initialize the native bundler. The+compiled-vendor stamp should include the resolved Rolldown version so a lockfile update invalidates+generated artifacts. nf3 remains owned and invoked by Nitro, so eve should not declare or call nf3+directly.++Rolldown resolution should preserve its per-import standard conditions. eve may add custom+conditions such as `eve-source` and `workflow`, but must not put `node`, `import`, `require`,+`browser`, or `default` in `resolve.conditionNames`. A shared assertion should reject those standard+condition names. Conditional-export fixtures should prove that ESM import and CommonJS require+edges retain their distinct package branches.++### Simplify eve's inputs to the Nitro build++The workflow builder can generate its final entry source directly instead of emitting an+intermediate file and repairing imports, code literals, source maps, and mirrored paths afterward.+This cleanup keeps the Nitro-specific transform exclusions, side-effect rules, aliases, and+`noExternals` policy that the final host build still requires.++eve should also centralize route computation in a typed registry, then translate that registry into+Nitro handlers and preset configuration. Nitro continues to mount and emit the routes. The registry+exists to keep HTTP, WebSocket, cron, package, development, and workflow route precedence consistent+across eve's configuration steps; it is not an eve-owned runtime router.++Public assets and prerender phases may be skipped only when Nitro exposes a supported builder+sequence and eve has neither public assets nor prerender routes. eve must not reproduce private+Nitro builder phases to remove those calls.++### Strengthen correctness at existing seams++The following changes do not require a new host:++- Preserve authored warnings while filtering warnings that come only from eve's compiled vendor+ artifacts. A warning involving both authored and vendor modules must remain visible.+- Reject WebSocket upgrades unless a WebSocket handler matched, and cover an HTTP handler and a+ WebSocket handler sharing one path. Fix this through Nitro configuration or upstream Nitro rather+ than a parallel router. Nitro's current upgrade resolver falls back to empty CrossWS hooks when+ the selected HTTP response has no WebSocket hooks, and its handler model cannot distinguish a GET+ route from a WebSocket route at the same path. Nitro therefore needs protocol-typed route entries+ or a public resolver that can return either WebSocket hooks or a rejected upgrade response.+- Retain explicit development-worker shutdown and fallback termination, and test request and+ `waitUntil` draining at the eve-owned outer server boundary.+- Do not claim end-to-end shutdown draining from the worker handshake alone. The current CLI parent+ gives its server child a shorter grace period than the worker fallback, and full outer-server+ shutdown releases workers before admitted requests and transitive `waitUntil` work are proven+ drained. Reconcile those budgets and add full-shutdown coverage before making a drain guarantee.+- Keep schedule lifecycle tests around admission, overlap, and shutdown while using Nitro's task+ runtime.+- Remove nested package builds that can race the package's destructive `dist` clean.+- Test route grammar against both Nitro's runtime matching and each selected deployment preset+ before broadening the public grammar.++## Deliberate non-goals++The removal branch proved several designs, but they do not fit the chosen ownership boundary:++- Do not vendor H3, CrossWS, srvx, or a schedule runtime into private eve artifacts.+- Do not create an eve-owned final Rolldown host graph, Fetch router, Node server, nf3 tracer, or+ Vercel Build Output emitter.+- Do not replace Nitro presets with eve-maintained platform adapters.+- Do not trade Nitro's native classification for an author-maintained list of external packages.+- Do not add a direct Rolldown runtime dependency while the umbrella Nitro package supplies the+ implementation. This staging choice contains the current private reach-through; it does not make+ that reach-through a supported long-term API.+- Do not remove Nitro-supported environment aliases, development error responses, signal behavior,+ source maps, Bun output, or route syntax without an explicit public breaking-change decision.+- Do not add direct H3, CrossWS, srvx, or nf3 dependencies merely to select newer versions. Nitro+ must test and supply compatible primitive versions for the host it owns.++These choices preserve the behavior and platform maintenance that justified keeping Nitro.++## Measured limitation of the umbrella package++The reviewed alternating warm-cache npm benchmark compared `[email protected]` using+`[email protected]` with the removal branch's packed artifact. It establishes the package-graph+cost of the umbrella package, not a runtime-performance result.++| Metric | Nitro boundary | Removal branch | Change |+| --------------------------------------- | -------------: | -------------: | -----: |+| External npm-managed package instances | 34 | 17 | -50% |+| Distinct external package names | 33 | 16 | -52% |+| Installed dependency bytes | 42,104,410 | 36,597,645 | -13.1% |+| Dependency edges in installed manifests | 38 | 17 | -55% |+| Optional peer edges | 47 | 4 | -91% |+| npm lock-only median | 2.427 s | 1.052 s | -56.7% |+| Warm npm install median | 3.205 s | 1.837 s | -42.7% |++The branch's separate CI comparison against its merge base showed the same installation direction:+the packed install fell from 73.48 MB to 68.31 MB, installed files fell from 6,924 to 5,782, and an+`eve init` install fell from 121 packages to 85. That trade was not uniformly smaller: the packed+tarball grew by 70.5 kB and two sampled Vercel functions each grew by about 161.7 kB.++The benchmark used four alternating samples per artifact on Node 24.16.0, npm 11.13.0, macOS+arm64, and a shared warm cache. It shows a directional resolver and install result. It does not show+that the removal branch built applications faster, used less build memory, started faster, served+requests faster, or used less steady-state memory. No controlled comparison established those+claims, and both designs used Rolldown, H3, CrossWS, and srvx. A single shared-runner build profile+improved from 2.10 seconds to 1.54 seconds, but it was explicitly informational and too noisy to+support a build-performance claim.++The current Nitro manifest has 14 hard dependencies and eight optional peers. Its closure includes+23 optional storage-provider peers from unstorage and six database-provider peers from db0. eve+cannot remove those manifest edges with imports, aliases, overrides, dynamic loading, or feature+flags. Moving dependencies to optional peers would reduce default installed bytes but would still+leave package managers to evaluate their metadata.++## Required Nitro package architecture++The install target requires a separately published Nitro core package, not a new export in the+existing package. The final upstream name may differ, but the package must have its own minimal+manifest and stable public exports.++The selected Nitro packages for eve must:++- Keep Nitro's builder, runtime application, route contracts, nf3 integration, task system, and the+ Node and Vercel preset behavior that eve uses.+- Avoid installing storage, database, cache, proxy, generic framework-development, Vite, or Rollup+ packages unless eve selects the corresponding component.+- Expose a public build boundary for the Rolldown operations embedders invoke, with supported+ exports and types rather than access through Nitro's private dependency tree.+- Declare Rolldown as a compatible peer of the build component so eve can pin and install one exact+ version after migrating from the umbrella package, without a second native binding.+- Keep storage and database integrations in opt-in physical packages so unstorage and db0 peer+ metadata never enters eve's default consumer graph.+- Allow the umbrella `nitro` package and CLI to depend on the core and optional components, keeping+ Nitro's turnkey experience without imposing the full graph on embedders.++Stable APIs are also needed at the seams eve currently reaches through hooks and option mutation:++- A typed route manifest or injected-application boundary that represents HTTP and WebSocket+ handlers independently while leaving mounting to Nitro.+- Supported build hooks for entry generation, plugin order, aliases, externals, warnings, and+ post-build output changes without patching a plugin by name.+- Observable classification and trace results while Nitro remains responsible for running nf3 and+ writing the traced dependency tree.+- Preset extension points for routes, functions, crons, headers, and service layouts without+ rewriting Nitro's emitted Vercel output.+- A Node adapter on `srvx` 0.12 or newer, or a supported way for the host to supply that adapter.+ The current umbrella Nitro release resolves `srvx` 0.11.22, while the 0.12 line contains the+ `waitUntil` retention and Node-adapter fixes needed by eve's lifecycle contract.+- A disposable Node preset contract with bounded asynchronous shutdown across requests,+ WebSockets, schedules, lifecycle hooks, signals, and transitive `waitUntil` work.+- A published compatibility matrix for Nitro's supported Rolldown, H3, CrossWS, srvx, and nf3+ versions.++The physical package split is the gate for dependency-resolution gains. The APIs improve+integration quality, but adding them to the umbrella package alone does not shrink its manifest.++## Acceptance and validation++### Current pass++The cleanup against the umbrella Nitro package is ready when:++1. `nitro` remains an exact runtime dependency and all production host builds still enter through+ public Nitro exports.+2. `rolldown` is not an eve runtime dependency. Parser-backed and build-backed code resolves+ Nitro's installed Rolldown through the eve-owned lazy wrapper and works from a packed npm install+ outside the monorepo.+3. The vendor stamp records the resolved Rolldown version, and every direct Rolldown call in eve+ source and build scripts goes through an eve-owned wrapper with the same resolution checks.+4. Conditional-export fixtures cover ESM import edges, CommonJS require edges, custom eve+ conditions, and packages that expose different values for those paths.+5. Workflow output no longer depends on repair-only rewrites or duplicate mirrors, and existing+ workflow identity, replay, source discovery, and Vercel execution scenarios pass.+6. One typed route registry drives Nitro handler and preset configuration, with tests for+ precedence, deduplication, CORS, shared HTTP/WebSocket paths, strict upgrades, cron routes, and+ co-deployed service prefixes.+7. Nitro still owns nf3 tracing. Native packages, nested pnpm packages, author-configured+ externals, and multiple installed versions remain covered by scenario tests.+8. Node and development shutdown tests cover admitted requests, transitive `waitUntil` work,+ WebSockets, schedules, worker replacement, signals, and close hooks without replacing Nitro's+ host implementation.+9. Vercel scenarios preserve Nitro-generated functions, routes, crons, environment aliases, error+ behavior, and Bun selection where supported.+10. Bundle analysis reports the packed tarball, installed bytes and files, installed package+ instances, dependency edges, and optional peer edges. Any claimed improvement uses the same+ package manager, cache state, platform, and sampling method as its baseline.+11. Unit, integration, scenario, TUI packed-install, and CI-only fixture evals pass at the narrowest+ tier that exercises each changed boundary.++### Upstream package follow-up++Migrating to a future Nitro core or build package requires a separate change and a new+packed-install benchmark. That migration is ready when the selected Nitro package set does not+install unstorage, db0, or their provider peer metadata; the build package exposes a public+Rolldown boundary and declares a compatible Rolldown peer; eve pins that peer to one exact runtime+version; and the packed install contains one Rolldown instance. The migration must retain every+Nitro-owned behavior listed above.++Runtime-performance claims remain separate from both stages. They require controlled build,+cold-start, throughput, and memory benchmarks.diff --git a/scripts/guard-invariants.mjs b/scripts/guard-invariants.mjsindex 162fd75c1..13a370dc1 100644--- a/scripts/guard-invariants.mjs+++ b/scripts/guard-invariants.mjs@@ -98,14 +98,18 @@* `ai`: its event payloads are eve's published shape, so deriving* them from the model SDK's callback types would make an SDK* upgrade a breaking change for every provider. Map at the bridge.+ * rule 38 — Workspace build scripts must not launch a nested+ * `pnpm --filter eve build`. Turbo owns workspace dependency+ * ordering; nested builds race on eve's clean-and-publish dist+ * directory and let consumers observe a partial package.** Baselines for rules with pre-existing violations live in* `guard-invariants-baseline.json`. Counts and allowlists in that file* may only shrink (as offenders are removed) — they may never grow.*/-import { readFile, readdir, lstat } from "node:fs/promises";+import { glob, readFile, readdir, lstat } from "node:fs/promises";import { createRequire } from "node:module";-import { join, relative, resolve, sep } from "node:path";+import { dirname, join, relative, resolve, sep } from "node:path";import { fileURLToPath } from "node:url";import matter from "gray-matter";import { checkExtensionCapabilityContracts } from "./extension-capability-contracts.mjs";@@ -969,6 +973,33 @@ async function checkRule34PhaseBoundary() {return violations;}+// ---------- Rule 38: one owner for the eve package build ----------++const NESTED_EVE_BUILD_RE = /\bpnpm\s+(?:--filter(?:=|\s+)eve|-F\s+eve)\s+(?:run\s+)?build\b/;++/**+ * @returns {Promise<Violation[]>}+ */+async function checkRule38NoNestedEveBuild() {+ /** @type {Violation[]} */+ const violations = [];++ for (const dir of await readPnpmWorkspacePackageDirs()) {+ if (dir === "packages/eve") continue;+ const packageJson = await readJsonIfExists(join(REPO_ROOT, dir, "package.json"));+ for (const [scriptName, command] of Object.entries(packageJson?.scripts ?? {})) {+ if (typeof command !== "string" || !NESTED_EVE_BUILD_RE.test(command)) continue;+ violations.push({+ rule: 38,+ file: `${dir}/package.json`,+ message: `script "${scriptName}" launches a nested eve package build. Declare eve as a workspace dependency and let Turbo's ^build edge produce it once; rebuilding eve inside a consumer races its destructive dist clean against other consumers.`,+ });+ }+ }++ return violations;+}+/*** @returns {Promise<Set<string>>}*/@@ -996,6 +1027,11 @@ async function readPnpmWorkspacePackageDirs() {const excluded = rawPattern.startsWith("!");const pattern = excluded ? rawPattern.slice(1) : rawPattern;const dirs = await expandWorkspacePackagePattern(pattern);++ if (!excluded && dirs.length === 0) {+ throw new Error(`Workspace package pattern "${rawPattern}" matched no package.json files.`);+ }+const target = excluded ? excludeDirs : includeDirs;dirs.forEach((dir) => target.add(dir));@@ -1047,31 +1083,16 @@ function stripYamlString(value) {* @returns {Promise<string[]>}*/async function expandWorkspacePackagePattern(pattern) {- if (pattern.endsWith("/*")) {- const root = pattern.slice(0, -2);- let entries;- try {- entries = await readdir(join(REPO_ROOT, root), { withFileTypes: true });- } catch (error) {- if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") {- return [];- }- throw error;- }+ const normalizedPattern = pattern.replace(/\/+$/, "");+ const dirs = [];- const dirs = [];- for (const entry of entries) {- if (!entry.isDirectory()) continue;- const dir = `${root}/${entry.name}`;- if (await readJsonIfExists(join(REPO_ROOT, dir, "package.json"))) dirs.push(dir);- }- return dirs;+ for await (const manifestPath of glob(`${normalizedPattern}/package.json`, {+ cwd: REPO_ROOT,+ })) {+ dirs.push(toPosix(dirname(manifestPath)));}- if (await readJsonIfExists(join(REPO_ROOT, pattern, "package.json"))) {- return [pattern];- }- return [];+ return dirs.sort();}/**@@ -1247,6 +1268,9 @@ async function main() {// Rule 37violations.push(...state.rule37);+ // Rule 38+ violations.push(...(await checkRule38NoNestedEveBuild()));+if (violations.length === 0) {process.stdout.write("[eve:guard:invariants] ok — all mechanical lints passed.\n");return;diff --git a/scripts/nitro-bundle-report-compare.mjs b/scripts/nitro-bundle-report-compare.mjsindex bf87adc90..8adb2fae6 100644--- a/scripts/nitro-bundle-report-compare.mjs+++ b/scripts/nitro-bundle-report-compare.mjs@@ -113,6 +113,19 @@ function readMetricValue(value) {return typeof value === "number" && Number.isFinite(value) ? value : 0;}+function compareTrackedNumericMetric(currentValue, baselineValue) {+ if (+ typeof currentValue !== "number" ||+ !Number.isFinite(currentValue) ||+ typeof baselineValue !== "number" ||+ !Number.isFinite(baselineValue)+ ) {+ return null;+ }++ return compareNumericMetric(currentValue, baselineValue);+}+function readSortedRoutes(routes) {return Array.isArray(routes)? routes.filter((route) => typeof route === "string").sort(compareRoutes)@@ -310,20 +323,40 @@ function comparePublishedPackages(currentPackage, baselinePackage) {readDependencyEntries(currentPackage?.peerDependencies),readDependencyEntries(baselinePackage?.peerDependencies),);+ const installedDependencyEdgeCount = compareTrackedNumericMetric(+ currentPackage?.installedDependencyEdgeCount,+ baselinePackage?.installedDependencyEdgeCount,+ );+ const installedDistinctPackageNameCount = compareTrackedNumericMetric(+ currentPackage?.installedDistinctPackageNameCount,+ baselinePackage?.installedDistinctPackageNameCount,+ );+ const installedOptionalPeerEdgeCount = compareTrackedNumericMetric(+ currentPackage?.installedOptionalPeerEdgeCount,+ baselinePackage?.installedOptionalPeerEdgeCount,+ );+ const installedPackageInstanceCount = compareTrackedNumericMetric(+ currentPackage?.installedPackageInstanceCount,+ baselinePackage?.installedPackageInstanceCount,+ );return {installedDependencyBytes: compareNumericMetric(readMetricValue(currentPackage?.installedDependencyBytes),readMetricValue(baselinePackage?.installedDependencyBytes),),+ ...(installedDependencyEdgeCount === null ? {} : { installedDependencyEdgeCount }),+ ...(installedDistinctPackageNameCount === null ? {} : { installedDistinctPackageNameCount }),installedFileCount: compareNumericMetric(readMetricValue(currentPackage?.installedFileCount),readMetricValue(baselinePackage?.installedFileCount),),+ ...(installedOptionalPeerEdgeCount === null ? {} : { installedOptionalPeerEdgeCount }),installedPackageBytes: compareNumericMetric(readMetricValue(currentPackage?.installedPackageBytes),readMetricValue(baselinePackage?.installedPackageBytes),),+ ...(installedPackageInstanceCount === null ? {} : { installedPackageInstanceCount }),installedSizeBytes: compareNumericMetric(readMetricValue(currentPackage?.installedSizeBytes),readMetricValue(baselinePackage?.installedSizeBytes),diff --git a/scripts/nitro-bundle-report.mjs b/scripts/nitro-bundle-report.mjsindex 8c7cde532..41e2c95a6 100644--- a/scripts/nitro-bundle-report.mjs+++ b/scripts/nitro-bundle-report.mjs@@ -1053,6 +1053,18 @@ function renderComparisonSection(comparison) {lines.push(`| Package | Installed files | ${comparison.package.installedFileCount.baseline} | ${comparison.package.installedFileCount.current} | ${formatSignedCount(comparison.package.installedFileCount.delta)} |`,);+ for (const [label, metric] of [+ ["Installed package instances", comparison.package.installedPackageInstanceCount],+ ["Distinct installed package names", comparison.package.installedDistinctPackageNameCount],+ ["Installed dependency edges", comparison.package.installedDependencyEdgeCount],+ ["Installed optional peer edges", comparison.package.installedOptionalPeerEdgeCount],+ ]) {+ if (metric !== undefined) {+ lines.push(+ `| Package | ${label} | ${metric.baseline} | ${metric.current} | ${formatSignedCount(metric.delta)} |`,+ );+ }+ }}lines.push(@@ -1112,6 +1124,12 @@ function renderPublishedPackageSection(publishedPackage) {);lines.push(`- Installed root package: ${formatBytes(publishedPackage.installedPackageBytes)}`);lines.push(`- Installed dependencies: ${formatBytes(publishedPackage.installedDependencyBytes)}`);+ lines.push(`- Installed package instances: ${publishedPackage.installedPackageInstanceCount}`);+ lines.push(+ `- Distinct installed package names: ${publishedPackage.installedDistinctPackageNameCount}`,+ );+ lines.push(`- Installed dependency edges: ${publishedPackage.installedDependencyEdgeCount}`);+ lines.push(`- Installed optional peer edges: ${publishedPackage.installedOptionalPeerEdgeCount}`);lines.push(`- Runtime dependencies: ${publishedPackage.runtimeDependencies.length}`);lines.push(`- Peer dependencies: ${publishedPackage.peerDependencies.length}${publishedPackage.peerDependencies.some((dependency) => dependency.optional) ? ` (${publishedPackage.peerDependencies.filter((dependency) => dependency.optional).length} optional)` : ""}`,@@ -1119,6 +1137,7 @@ function renderPublishedPackageSection(publishedPackage) {lines.push("","_Installed footprint is measured from an isolated temporary `npm install` of the packed tarball._",+ "_Graph metrics read only `package.json` files in package directories directly beneath a `node_modules` boundary, including nested boundaries. Each directory is one package instance; distinct names come from those manifests. Dependency edges count each unique name in `dependencies` or `optionalDependencies` per instance; optional peer edges count `peerDependencies` marked optional._","",);diff --git a/scripts/package-publish-report.mjs b/scripts/package-publish-report.mjsindex a63e1d738..d71693fcb 100644--- a/scripts/package-publish-report.mjs+++ b/scripts/package-publish-report.mjs@@ -126,6 +126,109 @@ async function walkRegularFiles(root) {return files;}+function readManifestDependencyNames(manifest, field) {+ const dependencies = manifest[field];++ return dependencies && typeof dependencies === "object" && !Array.isArray(dependencies)+ ? Object.keys(dependencies)+ : [];+}++async function collectInstalledPackageGraph(nodeModulesRoot) {+ // npm package roots are direct children of a node_modules directory (or one+ // of its scope directories). Following only those roots keeps embedded+ // package.json files from becoming false package instances or graph edges.+ /** @type {{ manifest: Record<string, unknown>; root: string }[]} */+ const packageInstances = [];++ async function visitPackageRoot(packageRoot) {+ const manifest = await readJson(join(packageRoot, "package.json"));++ if (typeof manifest.name !== "string" || manifest.name.length === 0) {+ throw new Error(`Installed package at "${packageRoot}" has no package name.`);+ }++ packageInstances.push({+ manifest,+ root: packageRoot,+ });++ const nestedNodeModulesRoot = join(packageRoot, "node_modules");++ if (await pathExists(nestedNodeModulesRoot)) {+ await visitNodeModulesRoot(nestedNodeModulesRoot);+ }+ }++ async function visitNodeModulesRoot(currentNodeModulesRoot) {+ const entries = await readdir(currentNodeModulesRoot, {+ withFileTypes: true,+ });+ entries.sort((left, right) => comparePaths(left.name, right.name));++ for (const entry of entries) {+ if (!entry.isDirectory() || entry.name.startsWith(".")) {+ continue;+ }++ const entryPath = join(currentNodeModulesRoot, entry.name);++ if (!entry.name.startsWith("@")) {+ await visitPackageRoot(entryPath);+ continue;+ }++ const scopedEntries = await readdir(entryPath, {+ withFileTypes: true,+ });+ scopedEntries.sort((left, right) => comparePaths(left.name, right.name));++ for (const scopedEntry of scopedEntries) {+ if (!scopedEntry.isDirectory() || scopedEntry.name.startsWith(".")) {+ continue;+ }++ await visitPackageRoot(join(entryPath, scopedEntry.name));+ }+ }+ }++ if (await pathExists(nodeModulesRoot)) {+ await visitNodeModulesRoot(nodeModulesRoot);+ }++ const distinctPackageNames = new Set();+ let dependencyEdgeCount = 0;+ let optionalPeerEdgeCount = 0;++ for (const { manifest } of packageInstances) {+ distinctPackageNames.add(manifest.name);++ dependencyEdgeCount += new Set([+ ...readManifestDependencyNames(manifest, "dependencies"),+ ...readManifestDependencyNames(manifest, "optionalDependencies"),+ ]).size;++ const peerDependencyNames = readManifestDependencyNames(manifest, "peerDependencies");+ const peerDependenciesMeta = manifest.peerDependenciesMeta;++ optionalPeerEdgeCount += peerDependencyNames.filter(+ (name) =>+ peerDependenciesMeta &&+ typeof peerDependenciesMeta === "object" &&+ !Array.isArray(peerDependenciesMeta) &&+ peerDependenciesMeta[name]?.optional === true,+ ).length;+ }++ return {+ installedDependencyEdgeCount: dependencyEdgeCount,+ installedDistinctPackageNameCount: distinctPackageNames.size,+ installedOptionalPeerEdgeCount: optionalPeerEdgeCount,+ installedPackageInstanceCount: packageInstances.length,+ };+}+function summarizeInstalledPackages(files, options) {/** @type {Map<string, number>} */const packageSizes = new Map();@@ -418,6 +521,7 @@ async function collectInstalledPackageSnapshot(input) {const installedFiles = (await pathExists(nodeModulesRoot))? await walkRegularFiles(nodeModulesRoot): [];+ const installedPackageGraph = await collectInstalledPackageGraph(nodeModulesRoot);const installedSizeBytes = installedFiles.reduce((total, file) => total + file.size, 0);const installedPackageBytes = installedFiles.reduce((total, file) => {return readInstalledPackageName(file.relativePath) === input.packageName@@ -427,8 +531,12 @@ async function collectInstalledPackageSnapshot(input) {return {installedDependencyBytes: installedSizeBytes - installedPackageBytes,+ installedDependencyEdgeCount: installedPackageGraph.installedDependencyEdgeCount,+ installedDistinctPackageNameCount: installedPackageGraph.installedDistinctPackageNameCount,installedFileCount: installedFiles.length,+ installedOptionalPeerEdgeCount: installedPackageGraph.installedOptionalPeerEdgeCount,installedPackageBytes,+ installedPackageInstanceCount: installedPackageGraph.installedPackageInstanceCount,installedSizeBytes,topInstalledPackages: summarizeInstalledPackages(installedFiles, {maxEntries: INSTALLED_PACKAGE_BREAKDOWN_MAX_ENTRIES,@@ -473,8 +581,12 @@ export async function collectPublishedPackageReportFromPack(options) {return {installedDependencyBytes: installedSnapshot.installedDependencyBytes,+ installedDependencyEdgeCount: installedSnapshot.installedDependencyEdgeCount,+ installedDistinctPackageNameCount: installedSnapshot.installedDistinctPackageNameCount,installedFileCount: installedSnapshot.installedFileCount,+ installedOptionalPeerEdgeCount: installedSnapshot.installedOptionalPeerEdgeCount,installedPackageBytes: installedSnapshot.installedPackageBytes,+ installedPackageInstanceCount: installedSnapshot.installedPackageInstanceCount,installedSizeBytes: installedSnapshot.installedSizeBytes,packageLabel: options.packageLabel ?? basename(packageRoot),packageName,