eve 0.24.0 → 0.24.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/dist/src/cli/run.js +2 -2
  3. package/dist/src/cli/vercel-service-output.d.ts +4 -0
  4. package/dist/src/cli/vercel-service-output.js +1 -0
  5. package/dist/src/compiled/.vendor-stamp.json +11 -11
  6. package/dist/src/compiled/@ai-sdk/anthropic/index.d.ts +1 -1
  7. package/dist/src/compiled/@ai-sdk/anthropic/index.js +2 -2
  8. package/dist/src/compiled/@ai-sdk/google/index.d.ts +7 -0
  9. package/dist/src/compiled/@ai-sdk/google/index.js +6 -6
  10. package/dist/src/compiled/@ai-sdk/mcp/index.d.ts +42 -1
  11. package/dist/src/compiled/@ai-sdk/mcp/index.js +1 -1
  12. package/dist/src/compiled/@ai-sdk/openai/index.d.ts +34 -6
  13. package/dist/src/compiled/@ai-sdk/openai/index.js +2 -2
  14. package/dist/src/compiled/@ai-sdk/otel/index.js +1 -1
  15. package/dist/src/compiled/@ai-sdk/provider/index.d.ts +245 -3
  16. package/dist/src/compiled/@ai-sdk/provider-utils/index.d.ts +273 -15
  17. package/dist/src/compiled/@workflow/core/index.js +1 -1
  18. package/dist/src/compiled/@workflow/core/runtime/start.d.ts +12 -0
  19. package/dist/src/compiled/@workflow/core/runtime.js +1 -1
  20. package/dist/src/compiled/@workflow/core/version.d.ts +1 -1
  21. package/dist/src/compiled/@workflow/core/workflow.js +1 -1
  22. package/dist/src/compiled/@workflow/world/analytics.d.ts +56 -21
  23. package/dist/src/compiled/@workflow/world/index.d.ts +1 -1
  24. package/dist/src/compiled/@workflow/world/interfaces.d.ts +46 -0
  25. package/dist/src/compiled/@workflow/world/queue.d.ts +12 -0
  26. package/dist/src/compiled/@workflow/world-local/index.js +3 -3
  27. package/dist/src/compiled/@workflow/world-vercel/index.js +16 -16
  28. package/dist/src/compiled/_chunks/workflow/attribute-changes-MGTOG_uX.js +20 -0
  29. package/dist/src/compiled/_chunks/workflow/{dist-CQenixFf.js → dist-Blxnyb7-.js} +2 -2
  30. package/dist/src/compiled/_chunks/workflow/dist-zLevmMyU.js +77 -0
  31. package/dist/src/compiled/_chunks/workflow/{resume-hook-BH01MfRF.js → resume-hook-DHP5ql3-.js} +1 -1
  32. package/dist/src/compiled/_chunks/workflow/run-D8hv1ptT.js +1 -0
  33. package/dist/src/compiled/_chunks/workflow/{sleep-BkAHCD_s.js → sleep-uA9pS-PT.js} +1 -1
  34. package/dist/src/compiler/artifacts.d.ts +7 -6
  35. package/dist/src/compiler/artifacts.js +1 -1
  36. package/dist/src/compiler/compile-agent.d.ts +15 -2
  37. package/dist/src/compiler/compile-agent.js +3 -3
  38. package/dist/src/execution/sandbox/prewarm.d.ts +1 -0
  39. package/dist/src/execution/sandbox/prewarm.js +1 -1
  40. package/dist/src/harness/compaction-prompt.d.ts +16 -0
  41. package/dist/src/harness/compaction-prompt.js +24 -0
  42. package/dist/src/harness/compaction.d.ts +2 -1
  43. package/dist/src/harness/compaction.js +1 -4
  44. package/dist/src/harness/input-requests.d.ts +1 -0
  45. package/dist/src/harness/input-requests.js +1 -1
  46. package/dist/src/harness/instrumentation-runtime-context.d.ts +1 -1
  47. package/dist/src/harness/tool-loop.js +3 -1
  48. package/dist/src/internal/application/build-workspace.d.ts +36 -0
  49. package/dist/src/internal/application/build-workspace.js +1 -0
  50. package/dist/src/internal/application/compiled-artifacts.d.ts +5 -0
  51. package/dist/src/internal/application/compiled-artifacts.js +4 -3
  52. package/dist/src/internal/application/output-publication-artifacts.d.ts +7 -0
  53. package/dist/src/internal/application/output-publication-artifacts.js +1 -0
  54. package/dist/src/internal/application/output-publication-journal.d.ts +30 -0
  55. package/dist/src/internal/application/output-publication-journal.js +1 -0
  56. package/dist/src/internal/application/output-publication-lock.d.ts +10 -0
  57. package/dist/src/internal/application/output-publication-lock.js +1 -0
  58. package/dist/src/internal/application/output-publication.d.ts +33 -0
  59. package/dist/src/internal/application/output-publication.js +1 -0
  60. package/dist/src/internal/application/package.js +1 -1
  61. package/dist/src/internal/application/paths.d.ts +2 -0
  62. package/dist/src/internal/application/paths.js +1 -1
  63. package/dist/src/internal/application/production-compiler-artifacts.d.ts +4 -0
  64. package/dist/src/internal/application/production-compiler-artifacts.js +1 -0
  65. package/dist/src/internal/application/tsconfig-dependencies.js +1 -1
  66. package/dist/src/internal/authored-directive-prologue.d.ts +4 -0
  67. package/dist/src/internal/authored-directive-prologue.js +1 -0
  68. package/dist/src/internal/authored-module-loader.d.ts +15 -5
  69. package/dist/src/internal/authored-module-loader.js +4 -2
  70. package/dist/src/internal/authored-module-map-loader.js +1 -1
  71. package/dist/src/internal/authored-package-boundary.d.ts +25 -0
  72. package/dist/src/internal/authored-package-boundary.js +1 -0
  73. package/dist/src/internal/authored-package-tsconfig-paths.js +1 -1
  74. package/dist/src/internal/bundler/nitro-node-file-trace.d.ts +10 -0
  75. package/dist/src/internal/bundler/nitro-node-file-trace.js +1 -0
  76. package/dist/src/internal/materialize-authored-external-dependencies.d.ts +10 -0
  77. package/dist/src/internal/materialize-authored-external-dependencies.js +2 -0
  78. package/dist/src/internal/materialized-authored-modules.d.ts +15 -0
  79. package/dist/src/internal/materialized-authored-modules.js +1 -0
  80. package/dist/src/internal/nitro/dev-runtime-artifacts.d.ts +1 -9
  81. package/dist/src/internal/nitro/dev-runtime-artifacts.js +1 -1
  82. package/dist/src/internal/nitro/development-generation.d.ts +12 -0
  83. package/dist/src/internal/nitro/development-generation.js +1 -0
  84. package/dist/src/internal/nitro/host/artifacts-config.d.ts +9 -11
  85. package/dist/src/internal/nitro/host/artifacts-config.js +1 -1
  86. package/dist/src/internal/nitro/host/build-application.js +1 -1
  87. package/dist/src/internal/nitro/host/build-vercel-agent-summary.d.ts +1 -7
  88. package/dist/src/internal/nitro/host/build-vercel-agent-summary.js +1 -1
  89. package/dist/src/internal/nitro/host/channel-routes.d.ts +3 -3
  90. package/dist/src/internal/nitro/host/configure-nitro-routes.d.ts +9 -5
  91. package/dist/src/internal/nitro/host/configure-nitro-routes.js +3 -3
  92. package/dist/src/internal/nitro/host/copy-host-middleware.d.ts +12 -0
  93. package/dist/src/internal/nitro/host/copy-host-middleware.js +1 -0
  94. package/dist/src/internal/nitro/host/create-application-nitro.d.ts +18 -10
  95. package/dist/src/internal/nitro/host/create-application-nitro.js +1 -1
  96. package/dist/src/internal/nitro/host/dev-authored-source-watcher.js +1 -1
  97. package/dist/src/internal/nitro/host/dispatch-schedule-in-dev.d.ts +2 -2
  98. package/dist/src/internal/nitro/host/dispatch-schedule-in-dev.js +1 -1
  99. package/dist/src/internal/nitro/host/prepare-application-host.d.ts +13 -5
  100. package/dist/src/internal/nitro/host/prepare-application-host.js +1 -1
  101. package/dist/src/internal/nitro/host/schedule-task-routes.d.ts +3 -3
  102. package/dist/src/internal/nitro/host/start-development-server.js +2 -2
  103. package/dist/src/internal/nitro/host/types.d.ts +4 -0
  104. package/dist/src/internal/nitro/routes/agent-info/load-agent-info-data.d.ts +3 -6
  105. package/dist/src/internal/nitro/routes/agent-info/load-agent-info-data.js +1 -1
  106. package/dist/src/internal/nitro/routes/channel-dispatch.js +1 -1
  107. package/dist/src/internal/nitro/routes/dev-schedule-dispatch.d.ts +2 -2
  108. package/dist/src/internal/nitro/routes/info.d.ts +1 -6
  109. package/dist/src/internal/nitro/routes/info.js +1 -1
  110. package/dist/src/internal/nitro/routes/runtime-artifacts.d.ts +9 -5
  111. package/dist/src/internal/nitro/routes/runtime-artifacts.js +1 -1
  112. package/dist/src/internal/workflow-bundle/build-queue.d.ts +1 -0
  113. package/dist/src/internal/workflow-bundle/build-queue.js +1 -0
  114. package/dist/src/internal/workflow-bundle/builder-support.d.ts +0 -1
  115. package/dist/src/internal/workflow-bundle/builder-support.js +2 -2
  116. package/dist/src/internal/workflow-bundle/builder.js +2 -2
  117. package/dist/src/internal/workflow-bundle/nitro-step-entry.d.ts +1 -0
  118. package/dist/src/internal/workflow-bundle/nitro-step-entry.js +2 -2
  119. package/dist/src/public/instrumentation/index.d.ts +3 -3
  120. package/dist/src/public/next/vercel-output-config.js +1 -1
  121. package/dist/src/setup/scaffold/create/add-to-project.js +1 -1
  122. package/dist/src/setup/scaffold/create/project.js +2 -2
  123. package/dist/src/setup/scaffold/update/channels.js +1 -1
  124. package/dist/src/shared/atomic-write-file.d.ts +11 -0
  125. package/dist/src/shared/atomic-write-file.js +1 -0
  126. package/dist/src/shared/guards.d.ts +7 -0
  127. package/dist/src/shared/guards.js +1 -1
  128. package/dist/src/shared/path-exists.d.ts +9 -0
  129. package/dist/src/shared/path-exists.js +1 -0
  130. package/docs/agent-config.md +1 -1
  131. package/docs/concepts/default-harness.md +1 -1
  132. package/docs/reference/cli.md +4 -2
  133. package/package.json +14 -14
  134. package/dist/src/compiled/_chunks/workflow/attribute-changes-Dmf_myUv.js +0 -20
  135. package/dist/src/compiled/_chunks/workflow/dist-D7CzPkf8.js +0 -77
  136. package/dist/src/compiled/_chunks/workflow/run-CL3mguvM.js +0 -1
@@ -1,9 +1,13 @@
1
1
  import type { Nitro } from "nitro/types";
2
2
  import type { NitroBuildSurface, PreparedApplicationHost } from "#internal/nitro/host/types.js";
3
3
  /**
4
- * Wires eve's package-owned app, channel, workflow inspection, and Workflow
5
- * SDK endpoints into one Nitro host instance.
4
+ * Wires eve's package-owned app, channel, workflow inspection, dev-control,
5
+ * and Workflow SDK endpoints into the watch-mode Nitro host, rebuilding
6
+ * workflow bundles on reload.
6
7
  */
7
- export declare function configureNitroRoutes(nitro: Nitro, preparedHost: PreparedApplicationHost, input: {
8
- surface: NitroBuildSurface;
9
- }): Promise<void>;
8
+ export declare function configureDevelopmentNitroRoutes(nitro: Nitro, preparedHost: PreparedApplicationHost): Promise<void>;
9
+ /**
10
+ * Wires the subset of eve's package-owned endpoints that belong to the given
11
+ * build surface into a production Nitro host.
12
+ */
13
+ export declare function configureProductionNitroRoutes(nitro: Nitro, preparedHost: PreparedApplicationHost, surface: NitroBuildSurface): Promise<void>;
@@ -1,4 +1,4 @@
1
- import{EVE_DEV_DISPATCH_SCHEDULE_ROUTE_PATTERN,EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH,EVE_HEALTH_ROUTE_PATH}from"#protocol/routes.js";import{resolvePackageRoot,resolvePackageSourceFilePath,resolveWorkflowModulePath}from"#internal/application/package.js";import{dirname,join,relative}from"node:path";import{mkdir,writeFile}from"node:fs/promises";import{isVercelBuildEnvironment}from"#internal/application/paths.js";import{normalizeEsmImportSpecifier,stringifyEsmImportSpecifier}from"#internal/application/import-specifier.js";import{WorkflowBundleBuilder}from"#internal/workflow-bundle/builder.js";import{createNitroArtifactsConfig}from"#internal/nitro/host/artifacts-config.js";import{deriveEveWorkflowQueuePrefix}from"#internal/workflow/queue-namespace.js";import{computeChannelRouteRegistrations,registerChannelVirtualHandlers}from"#internal/nitro/host/channel-routes.js";function includesApplicationRoutes(e){return e===`all`||e===`app`}function includesWorkflowBundles(e){return includesWorkflowRoute(e)}function includesWorkflowRoute(e){return e===`all`||e===`flow`}function registerHandler(e,t){let n=`#eve-route-handler/${t.method??`ALL`} ${t.route}`,r=stringifyEsmImportSpecifier(t.handlerPath);e.options.handlers.push({handler:n,method:t.method,route:t.route}),e.options.virtual[n]=[`import handler from ${r};`,`export default handler;`].join(`
2
- `)}function resolveNitroWorkflowBuildDirectory(e){return join(e.options.buildDir,`workflow`)}function createRelativeImportSpecifier(e,t){let n=relative(e,t).replaceAll(`\\`,`/`);return n.startsWith(`.`)?n:`./${n}`}async function addWorkflowFileHandler(e,t){let n=join(resolveNitroWorkflowBuildDirectory(e),`${t.bundleName}-handler.mjs`),r=dirname(n),i=createRelativeImportSpecifier(r,t.bundlePath),a=t.directHandlers??[],s=a.length>0&&t.workflowWorldPluginPath!==void 0?createRelativeImportSpecifier(r,t.workflowWorldPluginPath):void 0,u=a.map(e=>{let t=createRelativeImportSpecifier(r,e.bundlePath);return{importSpecifier:t,isOwnBundle:t===i,queuePrefix:e.queuePrefix}});await mkdir(r,{recursive:!0}),await writeFile(n,buildWorkflowFileHandlerSource({bundlePath:i,directHandlers:u,runtimeImportSpecifier:t.runtimeImportSpecifier,workflowWorldPluginImportSpecifier:s})),e.options.handlers.push({handler:n,route:t.route})}function buildWorkflowFileHandlerSource(e){let t=[`// Generated by eve. Do not edit by hand.`,`import { POST } from ${JSON.stringify(e.bundlePath)};`];if(e.directHandlers.length>0&&e.runtimeImportSpecifier!==void 0){let n=0,r=e.directHandlers.map(e=>{if(e.isOwnBundle)return{...e,binding:`POST`};let t=`__eveWorkflowDirectHandler${n}`;return n+=1,{...e,binding:t}});for(let e of r)e.isOwnBundle||t.push(`import { POST as ${e.binding} } from ${JSON.stringify(e.importSpecifier)};`);e.workflowWorldPluginImportSpecifier!==void 0&&t.push(`import ${JSON.stringify(e.workflowWorldPluginImportSpecifier)};`),t.push(`import { getWorld as __eveGetWorkflowWorld } from ${JSON.stringify(e.runtimeImportSpecifier)};`,``,`try {`,` const __eveWorkflowWorld = await __eveGetWorkflowWorld();`,` if (typeof __eveWorkflowWorld?.registerHandler === "function") {`);for(let e of r)t.push(` __eveWorkflowWorld.registerHandler(${JSON.stringify(e.queuePrefix)}, ${e.binding});`);t.push(` }`,`} catch (err) {`,` console.warn("[eve] Failed to register direct workflow queue handlers:", err);`,`}`)}return t.push(``,`export default async ({ req }) => {`,` return await POST(req);`,`};`,``),t.join(`
1
+ import{EVE_DEV_DISPATCH_SCHEDULE_ROUTE_PATTERN,EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH,EVE_HEALTH_ROUTE_PATH}from"#protocol/routes.js";import{resolvePackageRoot,resolvePackageSourceFilePath,resolveWorkflowModulePath}from"#internal/application/package.js";import{dirname,join,relative}from"node:path";import{mkdir,writeFile}from"node:fs/promises";import{isVercelBuildEnvironment}from"#internal/application/paths.js";import{normalizeEsmImportSpecifier,stringifyEsmImportSpecifier}from"#internal/application/import-specifier.js";import{WorkflowBundleBuilder}from"#internal/workflow-bundle/builder.js";import{createDevelopmentNitroArtifactsConfig,createProductionNitroArtifactsConfig}from"#internal/nitro/host/artifacts-config.js";import{deriveEveWorkflowQueuePrefix}from"#internal/workflow/queue-namespace.js";import{computeChannelRouteRegistrations,registerChannelVirtualHandlers}from"#internal/nitro/host/channel-routes.js";function includesApplicationRoutes(e){return e===`all`||e===`app`}function includesWorkflowBundles(e){return includesWorkflowRoute(e)}function includesWorkflowRoute(e){return e===`all`||e===`flow`}function registerHandler(e,t){let n=`#eve-route-handler/${t.method??`ALL`} ${t.route}`,r=stringifyEsmImportSpecifier(t.handlerPath);e.options.handlers.push({handler:n,method:t.method,route:t.route}),e.options.virtual[n]=[`import handler from ${r};`,`export default handler;`].join(`
2
+ `)}function resolveNitroWorkflowBuildDirectory(e){return join(e.options.buildDir,`workflow`)}function createRelativeImportSpecifier(e,t){let n=relative(e,t).replaceAll(`\\`,`/`);return n.startsWith(`.`)?n:`./${n}`}async function addWorkflowFileHandler(e,t){let n=join(resolveNitroWorkflowBuildDirectory(e),`${t.bundleName}-handler.mjs`),r=dirname(n),i=createRelativeImportSpecifier(r,t.bundlePath),a=t.directHandlers??[],s=a.length>0&&t.workflowWorldPluginPath!==void 0?createRelativeImportSpecifier(r,t.workflowWorldPluginPath):void 0,c=a.map(e=>{let t=createRelativeImportSpecifier(r,e.bundlePath);return{importSpecifier:t,isOwnBundle:t===i,queuePrefix:e.queuePrefix}});await mkdir(r,{recursive:!0}),await writeFile(n,buildWorkflowFileHandlerSource({bundlePath:i,directHandlers:c,runtimeImportSpecifier:t.runtimeImportSpecifier,workflowWorldPluginImportSpecifier:s})),e.options.handlers.push({handler:n,route:t.route})}function buildWorkflowFileHandlerSource(e){let t=[`// Generated by eve. Do not edit by hand.`,`import { POST } from ${JSON.stringify(e.bundlePath)};`];if(e.directHandlers.length>0&&e.runtimeImportSpecifier!==void 0){let n=0,r=e.directHandlers.map(e=>{if(e.isOwnBundle)return{...e,binding:`POST`};let t=`__eveWorkflowDirectHandler${n}`;return n+=1,{...e,binding:t}});for(let e of r)e.isOwnBundle||t.push(`import { POST as ${e.binding} } from ${JSON.stringify(e.importSpecifier)};`);e.workflowWorldPluginImportSpecifier!==void 0&&t.push(`import ${JSON.stringify(e.workflowWorldPluginImportSpecifier)};`),t.push(`import { getWorld as __eveGetWorkflowWorld } from ${JSON.stringify(e.runtimeImportSpecifier)};`,``,`try {`,` const __eveWorkflowWorld = await __eveGetWorkflowWorld();`,` if (typeof __eveWorkflowWorld?.registerHandler === "function") {`);for(let e of r)t.push(` __eveWorkflowWorld.registerHandler(${JSON.stringify(e.queuePrefix)}, ${e.binding});`);t.push(` }`,`} catch (err) {`,` console.warn("[eve] Failed to register direct workflow queue handlers:", err);`,`}`)}return t.push(``,`export default async ({ req }) => {`,` return await POST(req);`,`};`,``),t.join(`
3
3
  `)}function addFrameworkVirtualHandler(e,t){let n=`#eve-route${t.route}`,r=stringifyEsmImportSpecifier(t.modulePath);e.options.handlers.push({handler:n,method:t.method,route:t.route}),e.options.virtual[n]=[`import { ${t.handlerExport} } from ${r};`,`export default async (event) => ${t.handlerExport}(${t.args}, event.req);`].join(`
4
- `)}async function configureNitroRoutes(o,s,c){if(includesWorkflowBundles(c.surface)){let e=resolvePackageRoot(),t=new WorkflowBundleBuilder({agentName:s.compileResult.manifest.config.name,appRoot:s.appRoot,compiledArtifactsBootstrapPath:s.compiledArtifacts.bootstrapPath,outDir:s.workflowBuildDir,rootDir:e,watch:o.options.dev}),n=Promise.resolve(),buildWorkflowArtifacts=async()=>{await t.build({nitroStepOutfile:includesWorkflowRoute(c.surface)?join(resolveNitroWorkflowBuildDirectory(o),`steps.mjs`):void 0,nitroWorkflowOutfile:o.options.dev&&includesWorkflowRoute(c.surface)?join(resolveNitroWorkflowBuildDirectory(o),`workflows.mjs`):void 0})},syncWorkflowArtifacts=async()=>{let e=n.then(buildWorkflowArtifacts);n=e.catch(()=>{}),await e},i=!0;await syncWorkflowArtifacts(),o.hooks.hook(`build:before`,async()=>{if(i){i=!1;return}await syncWorkflowArtifacts()}),o.options.dev&&o.hooks.hook(`dev:reload`,async()=>{await syncWorkflowArtifacts()})}let l=createNitroArtifactsConfig({appRoot:s.appRoot,dev:o.options.dev});if(includesApplicationRoutes(c.surface)){addFrameworkVirtualHandler(o,{args:JSON.stringify({agentName:s.compileResult.manifest.config.name}),handlerExport:`handleHomePageRequest`,method:`GET`,modulePath:resolvePackageSourceFilePath(`src/internal/nitro/routes/index.ts`),route:`/`});for(let e of[`GET`,`HEAD`])registerHandler(o,{handlerPath:resolvePackageSourceFilePath(`src/internal/nitro/routes/health.ts`),method:e,route:EVE_HEALTH_ROUTE_PATH});registerChannelVirtualHandlers(o,{artifactsConfig:l,registrations:computeChannelRouteRegistrations(s)}),o.options.dev&&(addFrameworkVirtualHandler(o,{args:JSON.stringify({appRoot:l.appRoot}),handlerExport:`handleDevRuntimeArtifactsRequest`,method:`GET`,modulePath:resolvePackageSourceFilePath(`src/internal/nitro/routes/dev-runtime-artifacts.ts`),route:EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH}),addFrameworkVirtualHandler(o,{args:JSON.stringify(l),handlerExport:`handleDevScheduleDispatchRequest`,method:`POST`,modulePath:resolvePackageSourceFilePath(`src/internal/nitro/routes/dev-schedule-dispatch.ts`),route:EVE_DEV_DISPATCH_SCHEDULE_ROUTE_PATTERN}))}let d=resolveNitroWorkflowBuildDirectory(o),f=includesWorkflowRoute(c.surface)?o.options.dev?join(d,`workflows.mjs`):join(s.workflowBuildDir,`workflows.mjs`):void 0,p=s.compileResult.manifest.config.experimental?.workflow?.world!==void 0,m=(o.options.dev||!isVercelBuildEnvironment()&&p)&&f!==void 0?[{bundlePath:f,queuePrefix:deriveEveWorkflowQueuePrefix(s.compileResult.manifest.config.name)}]:[],h=m.length>0?normalizeEsmImportSpecifier(resolveWorkflowModulePath(`workflow/runtime`)):void 0;f&&await addWorkflowFileHandler(o,{bundleName:`workflows`,bundlePath:f,directHandlers:m,route:`/.well-known/workflow/v1/flow`,runtimeImportSpecifier:h,workflowWorldPluginPath:s.compiledArtifacts.workflowWorldPluginPath}),o.routing.sync()}export{configureNitroRoutes};
4
+ `)}async function registerWorkflowArtifactBuildHook(e,t){let n=!0;await t(),e.hooks.hook(`build:before`,async()=>{if(n){n=!1;return}await t()})}function registerApplicationRoutes(e,t,r){addFrameworkVirtualHandler(e,{args:JSON.stringify({agentName:t.compileResult.manifest.config.name}),handlerExport:`handleHomePageRequest`,method:`GET`,modulePath:resolvePackageSourceFilePath(`src/internal/nitro/routes/index.ts`),route:`/`});for(let t of[`GET`,`HEAD`])registerHandler(e,{handlerPath:resolvePackageSourceFilePath(`src/internal/nitro/routes/health.ts`),method:t,route:EVE_HEALTH_ROUTE_PATH});registerChannelVirtualHandlers(e,{artifactsConfig:r,registrations:computeChannelRouteRegistrations(t)})}function registerDevelopmentControlRoutes(n,r){addFrameworkVirtualHandler(n,{args:JSON.stringify({appRoot:r.appRoot}),handlerExport:`handleDevRuntimeArtifactsRequest`,method:`GET`,modulePath:resolvePackageSourceFilePath(`src/internal/nitro/routes/dev-runtime-artifacts.ts`),route:EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH}),addFrameworkVirtualHandler(n,{args:JSON.stringify(r),handlerExport:`handleDevScheduleDispatchRequest`,method:`POST`,modulePath:resolvePackageSourceFilePath(`src/internal/nitro/routes/dev-schedule-dispatch.ts`),route:EVE_DEV_DISPATCH_SCHEDULE_ROUTE_PATTERN})}function createWorkflowDirectHandlerEntry(e,t){return{bundlePath:t,queuePrefix:deriveEveWorkflowQueuePrefix(e.compileResult.manifest.config.name)}}async function registerWorkflowRoute(e,t,n,r){await addWorkflowFileHandler(e,{bundleName:`workflows`,bundlePath:n,directHandlers:r,route:`/.well-known/workflow/v1/flow`,runtimeImportSpecifier:r.length===0?void 0:normalizeEsmImportSpecifier(resolveWorkflowModulePath(`workflow/runtime`)),workflowWorldPluginPath:t.compiledArtifacts.workflowWorldPluginPath})}async function configureDevelopmentNitroRoutes(e,t){let n=resolveNitroWorkflowBuildDirectory(e),i=new WorkflowBundleBuilder({agentName:t.compileResult.manifest.config.name,appRoot:t.appRoot,compiledArtifactsBootstrapPath:t.compiledArtifacts.bootstrapPath,outDir:t.workflowBuildDir,rootDir:resolvePackageRoot(),watch:!0}),syncWorkflowArtifacts=async()=>{await i.build({nitroStepOutfile:join(n,`steps.mjs`),nitroWorkflowOutfile:join(n,`workflows.mjs`)})};await registerWorkflowArtifactBuildHook(e,syncWorkflowArtifacts),e.hooks.hook(`dev:reload`,syncWorkflowArtifacts);let a=createDevelopmentNitroArtifactsConfig({appRoot:t.appRoot});registerApplicationRoutes(e,t,a),registerDevelopmentControlRoutes(e,a);let o=join(n,`workflows.mjs`);await registerWorkflowRoute(e,t,o,[createWorkflowDirectHandlerEntry(t,o)]),e.routing.sync()}async function configureProductionNitroRoutes(e,t,n){if(includesWorkflowBundles(n)){let n=new WorkflowBundleBuilder({agentName:t.compileResult.manifest.config.name,appRoot:t.appRoot,compiledArtifactsBootstrapPath:t.compiledArtifacts.bootstrapPath,outDir:t.workflowBuildDir,rootDir:resolvePackageRoot(),watch:!1});await registerWorkflowArtifactBuildHook(e,async()=>{await n.build({nitroStepOutfile:join(resolveNitroWorkflowBuildDirectory(e),`steps.mjs`)})})}if(includesApplicationRoutes(n)&&registerApplicationRoutes(e,t,createProductionNitroArtifactsConfig()),includesWorkflowRoute(n)){let n=join(t.workflowBuildDir,`workflows.mjs`),r=t.compileResult.manifest.config.experimental?.workflow?.world!==void 0;await registerWorkflowRoute(e,t,n,!isVercelBuildEnvironment()&&r?[createWorkflowDirectHandlerEntry(t,n)]:[])}e.routing.sync()}export{configureDevelopmentNitroRoutes,configureProductionNitroRoutes};
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Copies host middleware functions into a generated service Build Output.
3
+ *
4
+ * Vercel validates generated-service routes against each service builder's
5
+ * function map. The host remains the runtime owner of these functions; this
6
+ * copy makes that same opaque Build Output function available while Vercel
7
+ * collects the generated service.
8
+ */
9
+ export declare function copyHostMiddlewareFunctions(input: {
10
+ readonly hostOutputDirectory: string;
11
+ readonly serviceOutputDirectory: string;
12
+ }): Promise<void>;
@@ -0,0 +1 @@
1
+ import{dirname,join,posix,resolve,sep}from"node:path";import{access,cp,mkdir,readFile}from"node:fs/promises";function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const NEXT_MIDDLEWARE_PATH=`/_middleware`;function resolveMiddlewareFunctionDirectory(e,t){let a=posix.normalize(t.replace(/^\/+/,``));if(a.length===0||a===`.`||a===`..`||a.startsWith(`../`)||a.includes(`\\`)||a.includes(`\0`))throw Error(`Invalid Vercel middlewarePath: ${JSON.stringify(t)}.`);let o=resolve(e,`functions`),s=resolve(o,`${a}.func`);if(!s.startsWith(`${o}${sep}`))throw Error(`Vercel middlewarePath escapes the functions directory: ${t}.`);return s}async function copyHostMiddlewareFunctions(n){let r=JSON.parse(await readFile(join(n.hostOutputDirectory,`config.json`),`utf8`));if(!isRecord(r))return;let i=new Set;if(Array.isArray(r.routes))for(let e of r.routes)isRecord(e)&&typeof e.middlewarePath==`string`&&i.add(e.middlewarePath);let c=resolveMiddlewareFunctionDirectory(n.hostOutputDirectory,NEXT_MIDDLEWARE_PATH);try{await access(c),i.add(NEXT_MIDDLEWARE_PATH)}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}for(let t of i){let r=resolveMiddlewareFunctionDirectory(n.hostOutputDirectory,t),i=resolveMiddlewareFunctionDirectory(n.serviceOutputDirectory,t);await mkdir(dirname(i),{recursive:!0}),await cp(r,i,{force:!0,recursive:!0})}}export{copyHostMiddlewareFunctions};
@@ -11,14 +11,22 @@ export declare function shouldPruneLocalSandboxBackends(input: {
11
11
  readonly preset: "vercel" | undefined;
12
12
  }): boolean;
13
13
  /**
14
- * Creates one configured Nitro instance for either production build or dev
15
- * hosting of an eve application.
16
- *
17
- * `surface` narrows the mounted routes for isolated production builds.
18
- * `outputDir` lets callers stage those isolated builds into separate Nitro
19
- * output roots before assembling the final hosted deployment.
14
+ * Creates the watch-mode Nitro host for `eve dev`: all route surfaces on one
15
+ * instance, live virtual modules, and hot-reload hooks wired to the authored
16
+ * source.
20
17
  */
21
- export declare function createApplicationNitro(preparedHost: PreparedApplicationHost, dev: boolean, options?: {
22
- outputDir?: string;
23
- surface?: NitroBuildSurface;
24
- }): Promise<Nitro>;
18
+ export declare function createDevelopmentApplicationNitro(preparedHost: PreparedApplicationHost): Promise<Nitro>;
19
+ interface ProductionApplicationNitroOptions {
20
+ readonly buildDir: string;
21
+ readonly outputDir: string;
22
+ readonly surface: NitroBuildSurface;
23
+ }
24
+ /**
25
+ * Creates a build-mode Nitro host for one production surface. `surface`
26
+ * narrows which route groups are registered ("all" for self-hosted output;
27
+ * "app"/"flow" for the separately bundled Vercel functions), and `buildDir`/
28
+ * `outputDir` place all bundler state inside the invocation-owned build
29
+ * workspace.
30
+ */
31
+ export declare function createProductionApplicationNitro(preparedHost: PreparedApplicationHost, options: ProductionApplicationNitroOptions): Promise<Nitro>;
32
+ export {};
@@ -1 +1 @@
1
- import{resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath}from"#internal/application/package.js";import{dirname,isAbsolute,join,relative,resolve}from"node:path";import{readFile}from"node:fs/promises";import{resolveNitroBuildDirectory}from"#internal/application/paths.js";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{fileURLToPath}from"node:url";import{createExtensionScopePlugin}from"#internal/bundler/extension-scope-plugin.js";import{SERVER_EXTERNAL_PACKAGES}from"#internal/nitro/host/server-external-packages.js";import{createNitro}from"nitro/builder";import{prepareEveVersionedCacheDirectory,writeEveVersionedCacheMetadata}from"#internal/application/cache-metadata.js";import{captureDevLiveVirtualModules}from"#internal/nitro/host/dev-live-virtual-modules.js";import{createNitroArtifactsConfig}from"#internal/nitro/host/artifacts-config.js";import{createCompiledSandboxBackendPrunePlugin}from"#internal/nitro/host/compiled-sandbox-backend-prune-plugin.js";import{configureNitroRoutes}from"#internal/nitro/host/configure-nitro-routes.js";import{applyEveCronHandlerRoute}from"#internal/nitro/host/cron-handler-route.js";import{createNitroBundlerConfig}from"#internal/nitro/host/nitro-bundler-config.js";import{OPTIONAL_ENGINE_PACKAGES_BY_BACKEND_NAME,createOptionalEngineDependencyPlugin}from"#internal/nitro/host/optional-engine-dependency-plugin.js";import{addNitroRoutingImportSpecifierPlugin}from"#internal/nitro/host/nitro-routing-import-specifier-plugin.js";import{registerScheduleTaskHandlers}from"#internal/nitro/host/schedule-task-routes.js";import{createEveVercelOptions}from"#internal/nitro/host/vercel-build-output-config.js";import{applyWorkflowTransform}from"#internal/workflow-bundle/workflow-builders.js";import{transformDynamicToolExecute}from"#internal/workflow-bundle/dynamic-tool-transform.js";const WORKFLOW_ALIAS_SPECIFIERS=[`workflow`,`workflow/api`,`workflow/errors`,`workflow/internal/builtins`,`workflow/internal/private`,`workflow/runtime`],WORKFLOW_TRANSFORM_PATCHED=Symbol(`eve.workflow-transform-patched`),FRAMEWORK_HOSTED_EXTERNAL_PACKAGES=[`@napi-rs/keyring`],LOCAL_SANDBOX_BACKEND_NAMES=new Set([`docker`,...Object.keys(OPTIONAL_ENGINE_PACKAGES_BY_BACKEND_NAME)]);function resolveWorkflowAliases(){let e={};for(let t of WORKFLOW_ALIAS_SPECIFIERS)e[t]=resolveWorkflowModulePath(t);return e}function resolveNitroPreset(e){if(!e&&process.env.VERCEL)return`vercel`}function includesApplicationSurface(e){return e===`all`||e===`app`}function includesWorkflowSurface(e){return e===`all`||e===`flow`}function includesWorkflowStepRegistrations(e){return includesWorkflowSurface(e)}function manifestEnablesWorkflow(e){return[e,...e.subagents.map(e=>e.agent)].some(e=>e.workflowTool!==void 0)}function manifestHasWebSocketChannel(e){return e.channels.some(e=>e.kind===`channel`&&e.method===`WEBSOCKET`)}function resolveWorkflowStepEntrypointPath(e,t){return e.options.dev?join(e.options.buildDir,`workflow`,`steps.mjs`):join(t.workflowBuildDir,`steps.mjs`)}function collectHostedTraceDependencies(e,t){let n=[e.compileResult.manifest,...e.compileResult.manifest.subagents.map(e=>e.agent)].flatMap(e=>e.config.build?.externalDependencies??[]);return[...new Set([...FRAMEWORK_HOSTED_EXTERNAL_PACKAGES,...t,...SERVER_EXTERNAL_PACKAGES,...n])].filter(e=>e!==EVE_PACKAGE_NAME)}function collectConfiguredSandboxBackendNames(e){let t=[e,...e.subagents.map(e=>e.agent)];return new Set(t.map(e=>e.sandbox?.backendName).filter(e=>typeof e==`string`))}function shouldPruneLocalSandboxBackends(e){return e.preset===`vercel`&&![...e.configuredBackendNames].some(e=>LOCAL_SANDBOX_BACKEND_NAMES.has(e))}function createDevelopmentWatchOptions(e){if(e.length!==0)return{ignored:[e,join(e,`**`)]}}function normalizePath(e){return e.replaceAll(`\\`,`/`)}function stripPathQueryAndHash(e){let t=e.indexOf(`?`),n=e.indexOf(`#`),r=t===-1?n:n===-1?t:Math.min(t,n);return r===-1?e:e.slice(0,r)}function stripFileSystemPrefix(e){return e.startsWith(`/@fs/`)?e.slice(4):e}function resolveNitroModuleComparisonPath(e,t){return t.startsWith(`file://`)?normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(fileURLToPath(t)))):isAbsolute(t)?normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(t))):normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(resolve(e,t))))}function isWorkflowBundlePath(e,t){let n=normalizePath(e);return n.startsWith(t)||n.includes(`/.eve/workflow-cache/`)}function normalizeStepTransformComparisonPath(e){let t=normalizePath(e);return process.platform===`win32`?t.toLowerCase():t}function parseImportedModuleSpecifiers(e){let t=/^\s*import\s+(?:.+?\s+from\s+)?["']([^"']+)["'];?\s*$/gm,n=[];for(let r of e.matchAll(t)){let e=r[1];e!==void 0&&n.push(e)}return n}function resolveNitroImportPath(e,t,n){return t.startsWith(`workflow`)?resolveWorkflowModulePath(t):t.startsWith(`.`)||t.startsWith(`/`)||t.startsWith(`file://`)?resolveNitroModuleComparisonPath(n===void 0?e:dirname(resolveNitroModuleComparisonPath(e,n)),t):null}async function collectNitroStepTransformTargets(e,t){let n=await readFile(e,`utf8`),r=new Set;for(let i of parseImportedModuleSpecifiers(n)){let n=resolveNitroImportPath(t,i,e);n!==null&&r.add(normalizeStepTransformComparisonPath(n))}return r}async function addNitroStepNoExternals(e,t){if(e.options.noExternals===!0)return;let n;try{n=await collectNitroStepTransformTargets(t,e.options.rootDir)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}let r=Array.isArray(e.options.noExternals)?[...e.options.noExternals]:[];e.options.noExternals=[...new Set([...r,...n])]}function createRelativeTransformFilename(e,t){let n=createPackageRelativeTransformFilename(t);if(n!==void 0)return n;let r=normalizePath(e).replace(/\/$/,``),i=normalizePath(t),a=r.toLowerCase(),o=i.toLowerCase();if(o.startsWith(`${a}/`))return i.slice(r.length+1);if(o===a)return`.`;let c=relative(r,i).replaceAll(`\\`,`/`);if(c.startsWith(`../`)&&(c=c.split(`/`).filter(e=>e!==`..`).join(`/`)),c.includes(`:`)||c.startsWith(`/`)){let e=i.split(`/`).pop();return e===void 0||e.length===0?`unknown.ts`:e}return c}function createPackageRelativeTransformFilename(t){let n=normalizePath(resolvePackageRoot()).replace(/\/$/,``),r=normalizePath(t),i=n.toLowerCase(),a=r.toLowerCase(),o=`${n}/src/`,s=`${i}/src/`,c=`${n}/dist/src/`,l=`${i}/dist/src/`;if(a.startsWith(s))return`src/${r.slice(o.length)}`;if(a.startsWith(l))return`src/${r.slice(c.length)}`}function addWorkflowModuleSideEffectsPlugin(e,t){let n=[t,join(e.options.buildDir,`workflow`)].map(t=>resolveNitroModuleComparisonPath(e.options.rootDir,t));e.hooks.hook(`rollup:before`,(t,r)=>{Array.isArray(r.plugins)&&r.plugins.unshift({name:`eve:workflow-module-side-effects`,resolveId(t,r){let i=resolveNitroImportPath(e.options.rootDir,t,r)??resolveNitroModuleComparisonPath(e.options.rootDir,t);return n.some(e=>isWorkflowBundlePath(i,e))?{id:i,moduleSideEffects:`no-treeshake`}:null}})})}function addNitroStepModuleSideEffectsPlugin(e,t){let n=null,getStepTransformTargets=async()=>(n===null&&(n=await collectNitroStepTransformTargets(t.stepEntrypointPath,e.options.rootDir)),n);e.hooks.hook(`build:before`,()=>{n=null}),e.options.dev&&e.hooks.hook(`dev:reload`,()=>{n=null}),e.hooks.hook(`rollup:before`,(t,n)=>{Array.isArray(n.plugins)&&n.plugins.unshift({name:`eve:workflow-step-module-side-effects`,async resolveId(t,n){let r=resolveNitroImportPath(e.options.rootDir,t,n);return r===null||!(await getStepTransformTargets()).has(normalizeStepTransformComparisonPath(r))?null:{id:r,moduleSideEffects:`no-treeshake`}}})})}function addNitroStepTransformPlugin(e,t){let n=null,getStepTransformTargets=async()=>(n===null&&(n=await collectNitroStepTransformTargets(t.stepEntrypointPath,e.options.rootDir)),n);e.hooks.hook(`build:before`,()=>{n=null}),e.options.dev&&e.hooks.hook(`dev:reload`,()=>{n=null}),e.hooks.hook(`rollup:before`,(t,n)=>{Array.isArray(n.plugins)&&n.plugins.unshift({async transform(t,n){let r=await getStepTransformTargets(),i=resolveNitroModuleComparisonPath(e.options.rootDir,n);return r.has(normalizeStepTransformComparisonPath(i))?{code:(await applyWorkflowTransform(createRelativeTransformFilename(e.options.rootDir,i),t,`step`,i,e.options.rootDir)).code,map:null}:null},name:`eve:workflow-step-transform`})})}function addDynamicToolTransformPlugin(e){e.hooks.hook(`rollup:before`,(e,t)=>{Array.isArray(t.plugins)&&t.plugins.unshift({async transform(e,t){if(!t.includes(`/tools/`))return null;let n=await transformDynamicToolExecute(t,e);return n===null?null:{code:n.code,map:null}},name:`eve:dynamic-tool-transform`})})}function addInstrumentationModuleSideEffectsPlugin(e,t){let n=normalizePath(t);e.hooks.hook(`rollup:before`,(e,t)=>{Array.isArray(t.plugins)&&t.plugins.unshift({name:`eve:instrumentation-module-side-effects`,resolveId(e){return normalizePath(e)===n?{id:e,moduleSideEffects:`no-treeshake`}:null}})})}function patchWorkflowTransformExcludePath(e,t){let n=normalizePath(t);e.hooks.hook(`rollup:before`,(e,t)=>{if(Array.isArray(t.plugins))for(let e of t.plugins){if(typeof e!=`object`||!e)continue;let t=e;if(t.name!==`workflow:transform`||t[WORKFLOW_TRANSFORM_PATCHED]===!0||typeof t.transform!=`function`)continue;let r=t.transform;t.transform=function(e,t,...i){return isWorkflowBundlePath(t,n)?null:r.call(this,e,t,...i)},t[WORKFLOW_TRANSFORM_PATCHED]=!0}})}async function createApplicationNitro(e,r,i={}){let a=i.surface??`all`,s=!r&&includesApplicationSurface(a)&&e.scheduleRegistrations.length>0,c=resolveNitroPreset(r),l=collectConfiguredSandboxBackendNames(e.compileResult.manifest),u=shouldPruneLocalSandboxBackends({configuredBackendNames:l,preset:c})?createCompiledSandboxBackendPrunePlugin():null,d=[],f=[];for(let[e,t]of Object.entries(OPTIONAL_ENGINE_PACKAGES_BY_BACKEND_NAME))(l.has(e)?d:f).push(t);let p=createExtensionScopePlugin((e.compileResult.manifest.extensionMounts??[]).map(e=>({sourceRoot:e.sourceRoot,packageNamespace:e.packageNamespace}))),m=[u,createOptionalEngineDependencyPlugin(f),p].filter(e=>e!==null),h=createNitroBundlerConfig(m),g=createNitroBundlerConfig(m),_=collectHostedTraceDependencies(e,d),v=resolveNitroBuildDirectory(e.appRoot,a),y=includesApplicationSurface(a)&&(r||manifestHasWebSocketChannel(e.compileResult.manifest)),b=[];b.push(e.compiledArtifacts.bootstrapPath),b.push(e.compiledArtifacts.workflowWorldPluginPath),r||b.push(resolvePackageSourceFilePath(`src/internal/nitro/host/sandbox-shutdown-plugin.ts`)),manifestEnablesWorkflow(e.compileResult.manifest)&&b.push(resolvePackageSourceFilePath(`src/internal/nitro/host/workflow-sandbox-runtime-plugin.ts`)),e.compiledArtifacts.instrumentationPluginPath!==void 0&&b.push(e.compiledArtifacts.instrumentationPluginPath),await prepareEveVersionedCacheDirectory(v);let x=await createNitro({_cli:{command:r?`dev`:`build`},buildDir:v,dev:r,features:{websocket:y},logLevel:r?1:void 0,output:i.outputDir===void 0?void 0:{dir:i.outputDir},preset:c,plugins:b,publicAssets:[],scanDirs:includesWorkflowStepRegistrations(a)?[resolvePackageSourceDirectoryPath(`src/execution`)]:void 0,rolldownConfig:h,rollupConfig:g,rootDir:e.appRoot,serverDir:!1,traceDeps:_,vercel:createEveVercelOptions(c===`vercel`&&includesApplicationSurface(a)),watchOptions:r?createDevelopmentWatchOptions(e.appRoot):void 0},r?{watch:!0}:void 0);if(await writeEveVersionedCacheMetadata(v),addNitroRoutingImportSpecifierPlugin(x),r&&captureDevLiveVirtualModules(x),includesWorkflowSurface(a)){let t=resolveWorkflowAliases();for(let[e,n]of Object.entries(t))x.options.alias[e]=n;addWorkflowModuleSideEffectsPlugin(x,e.workflowBuildDir),patchWorkflowTransformExcludePath(x,e.workflowBuildDir)}if(includesWorkflowStepRegistrations(a)){let t=resolveWorkflowStepEntrypointPath(x,e);addNitroStepModuleSideEffectsPlugin(x,{stepEntrypointPath:t}),addNitroStepTransformPlugin(x,{stepEntrypointPath:t})}if(addDynamicToolTransformPlugin(x),e.compiledArtifacts.instrumentationSourcePath!==void 0&&addInstrumentationModuleSideEffectsPlugin(x,e.compiledArtifacts.instrumentationSourcePath),r&&includesWorkflowSurface(a)){let t=e.workflowBuildDir,n=new Set([normalizePath(join(t,`workflows.mjs`))]);x.hooks.hook(`rollup:before`,(e,t)=>{let r=t.external;t.external=(e,...t)=>{if(n.has(normalizePath(e)))return!0;if(typeof r==`function`)return r(e,...t)}})}return s&&(applyEveCronHandlerRoute(x),registerScheduleTaskHandlers(x,{artifactsConfig:createNitroArtifactsConfig({appRoot:e.appRoot,dev:x.options.dev}),dispatchModulePath:resolvePackageSourceFilePath(`src/internal/nitro/routes/schedule-task.ts`),registrations:e.scheduleRegistrations})),await configureNitroRoutes(x,e,{surface:a}),includesWorkflowStepRegistrations(a)&&await addNitroStepNoExternals(x,resolveWorkflowStepEntrypointPath(x,e)),x}export{createApplicationNitro,shouldPruneLocalSandboxBackends};
1
+ import{resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath}from"#internal/application/package.js";import{dirname,isAbsolute,join,relative,resolve}from"node:path";import{readFile}from"node:fs/promises";import{resolveNitroBuildDirectory}from"#internal/application/paths.js";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{fileURLToPath}from"node:url";import{createExtensionScopePlugin}from"#internal/bundler/extension-scope-plugin.js";import{SERVER_EXTERNAL_PACKAGES}from"#internal/nitro/host/server-external-packages.js";import{createNitro}from"nitro/builder";import{prepareEveVersionedCacheDirectory,writeEveVersionedCacheMetadata}from"#internal/application/cache-metadata.js";import{captureDevLiveVirtualModules}from"#internal/nitro/host/dev-live-virtual-modules.js";import{createProductionNitroArtifactsConfig}from"#internal/nitro/host/artifacts-config.js";import{createCompiledSandboxBackendPrunePlugin}from"#internal/nitro/host/compiled-sandbox-backend-prune-plugin.js";import{configureDevelopmentNitroRoutes,configureProductionNitroRoutes}from"#internal/nitro/host/configure-nitro-routes.js";import{applyEveCronHandlerRoute}from"#internal/nitro/host/cron-handler-route.js";import{createNitroBundlerConfig}from"#internal/nitro/host/nitro-bundler-config.js";import{OPTIONAL_ENGINE_PACKAGES_BY_BACKEND_NAME,createOptionalEngineDependencyPlugin}from"#internal/nitro/host/optional-engine-dependency-plugin.js";import{addNitroRoutingImportSpecifierPlugin}from"#internal/nitro/host/nitro-routing-import-specifier-plugin.js";import{registerScheduleTaskHandlers}from"#internal/nitro/host/schedule-task-routes.js";import{createEveVercelOptions}from"#internal/nitro/host/vercel-build-output-config.js";import{applyWorkflowTransform}from"#internal/workflow-bundle/workflow-builders.js";import{transformDynamicToolExecute}from"#internal/workflow-bundle/dynamic-tool-transform.js";const WORKFLOW_ALIAS_SPECIFIERS=[`workflow`,`workflow/api`,`workflow/errors`,`workflow/internal/builtins`,`workflow/internal/private`,`workflow/runtime`],WORKFLOW_TRANSFORM_PATCHED=Symbol(`eve.workflow-transform-patched`),FRAMEWORK_HOSTED_EXTERNAL_PACKAGES=[`@napi-rs/keyring`],LOCAL_SANDBOX_BACKEND_NAMES=new Set([`docker`,...Object.keys(OPTIONAL_ENGINE_PACKAGES_BY_BACKEND_NAME)]);function resolveWorkflowAliases(){let e={};for(let t of WORKFLOW_ALIAS_SPECIFIERS)e[t]=resolveWorkflowModulePath(t);return e}function resolveProductionNitroPreset(){return process.env.VERCEL?`vercel`:void 0}function includesApplicationSurface(e){return e===`all`||e===`app`}function includesWorkflowSurface(e){return e===`all`||e===`flow`}function includesWorkflowStepRegistrations(e){return includesWorkflowSurface(e)}function manifestEnablesWorkflow(e){return[e,...e.subagents.map(e=>e.agent)].some(e=>e.workflowTool!==void 0)}function manifestHasWebSocketChannel(e){return e.channels.some(e=>e.kind===`channel`&&e.method===`WEBSOCKET`)}function collectHostedTraceDependencies(e,t){let n=[e.compileResult.manifest,...e.compileResult.manifest.subagents.map(e=>e.agent)].flatMap(e=>e.config.build?.externalDependencies??[]);return[...new Set([...FRAMEWORK_HOSTED_EXTERNAL_PACKAGES,...t,...SERVER_EXTERNAL_PACKAGES,...n])].filter(e=>e!==EVE_PACKAGE_NAME)}function collectConfiguredSandboxBackendNames(e){let t=[e,...e.subagents.map(e=>e.agent)];return new Set(t.map(e=>e.sandbox?.backendName).filter(e=>typeof e==`string`))}function shouldPruneLocalSandboxBackends(e){return e.preset===`vercel`&&![...e.configuredBackendNames].some(e=>LOCAL_SANDBOX_BACKEND_NAMES.has(e))}function createDevelopmentWatchOptions(e){return{ignored:[e,join(e,`**`)]}}function normalizePath(e){return e.replaceAll(`\\`,`/`)}function stripPathQueryAndHash(e){let t=e.indexOf(`?`),n=e.indexOf(`#`),r=t===-1?n:n===-1?t:Math.min(t,n);return r===-1?e:e.slice(0,r)}function stripFileSystemPrefix(e){return e.startsWith(`/@fs/`)?e.slice(4):e}function resolveNitroModuleComparisonPath(e,t){return t.startsWith(`file://`)?normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(fileURLToPath(t)))):isAbsolute(t)?normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(t))):normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(resolve(e,t))))}function isWorkflowBundlePath(e,t){let n=normalizePath(e);return n.startsWith(t)||n.includes(`/.eve/workflow-cache/`)}function normalizeStepTransformComparisonPath(e){let t=normalizePath(e);return process.platform===`win32`?t.toLowerCase():t}function parseImportedModuleSpecifiers(e){let t=/^\s*import\s+(?:.+?\s+from\s+)?["']([^"']+)["'];?\s*$/gm,n=[];for(let r of e.matchAll(t)){let e=r[1];e!==void 0&&n.push(e)}return n}function resolveNitroImportPath(e,t,n){return t.startsWith(`workflow`)?resolveWorkflowModulePath(t):t.startsWith(`.`)||t.startsWith(`/`)||t.startsWith(`file://`)?resolveNitroModuleComparisonPath(n===void 0?e:dirname(resolveNitroModuleComparisonPath(e,n)),t):null}async function collectNitroStepTransformTargets(e,t){let n=await readFile(e,`utf8`),r=new Set;for(let i of parseImportedModuleSpecifiers(n)){let n=resolveNitroImportPath(t,i,e);n!==null&&r.add(normalizeStepTransformComparisonPath(n))}return r}async function addNitroStepNoExternals(e,t){if(e.options.noExternals===!0)return;let n;try{n=await collectNitroStepTransformTargets(t,e.options.rootDir)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}let r=Array.isArray(e.options.noExternals)?[...e.options.noExternals]:[];e.options.noExternals=[...new Set([...r,...n])]}function createRelativeTransformFilename(e,t){let n=createPackageRelativeTransformFilename(t);if(n!==void 0)return n;let r=normalizePath(e).replace(/\/$/,``),i=normalizePath(t),a=r.toLowerCase(),o=i.toLowerCase();if(o.startsWith(`${a}/`))return i.slice(r.length+1);if(o===a)return`.`;let c=relative(r,i).replaceAll(`\\`,`/`);if(c.startsWith(`../`)&&(c=c.split(`/`).filter(e=>e!==`..`).join(`/`)),c.includes(`:`)||c.startsWith(`/`)){let e=i.split(`/`).pop();return e===void 0||e.length===0?`unknown.ts`:e}return c}function createPackageRelativeTransformFilename(t){let n=normalizePath(resolvePackageRoot()).replace(/\/$/,``),r=normalizePath(t),i=n.toLowerCase(),a=r.toLowerCase(),o=`${n}/src/`,s=`${i}/src/`,c=`${n}/dist/src/`,l=`${i}/dist/src/`;if(a.startsWith(s))return`src/${r.slice(o.length)}`;if(a.startsWith(l))return`src/${r.slice(c.length)}`}function addWorkflowModuleSideEffectsPlugin(e,t){let n=[t,join(e.options.buildDir,`workflow`)].map(t=>resolveNitroModuleComparisonPath(e.options.rootDir,t));e.hooks.hook(`rollup:before`,(t,r)=>{Array.isArray(r.plugins)&&r.plugins.unshift({name:`eve:workflow-module-side-effects`,resolveId(t,r){let i=resolveNitroImportPath(e.options.rootDir,t,r)??resolveNitroModuleComparisonPath(e.options.rootDir,t);return n.some(e=>isWorkflowBundlePath(i,e))?{id:i,moduleSideEffects:`no-treeshake`}:null}})})}function addNitroStepModuleSideEffectsPlugin(e,t){let n=null,getStepTransformTargets=async()=>(n===null&&(n=await collectNitroStepTransformTargets(t.stepEntrypointPath,e.options.rootDir)),n),clearCachedStepTransformTargets=()=>{n=null};return e.hooks.hook(`build:before`,clearCachedStepTransformTargets),e.hooks.hook(`rollup:before`,(t,n)=>{Array.isArray(n.plugins)&&n.plugins.unshift({name:`eve:workflow-step-module-side-effects`,async resolveId(t,n){let r=resolveNitroImportPath(e.options.rootDir,t,n);return r===null||!(await getStepTransformTargets()).has(normalizeStepTransformComparisonPath(r))?null:{id:r,moduleSideEffects:`no-treeshake`}}})}),clearCachedStepTransformTargets}function addNitroStepTransformPlugin(e,t){let n=null,getStepTransformTargets=async()=>(n===null&&(n=await collectNitroStepTransformTargets(t.stepEntrypointPath,e.options.rootDir)),n),clearCachedStepTransformTargets=()=>{n=null};return e.hooks.hook(`build:before`,clearCachedStepTransformTargets),e.hooks.hook(`rollup:before`,(t,n)=>{Array.isArray(n.plugins)&&n.plugins.unshift({async transform(t,n){let r=await getStepTransformTargets(),i=resolveNitroModuleComparisonPath(e.options.rootDir,n);return r.has(normalizeStepTransformComparisonPath(i))?{code:(await applyWorkflowTransform(createRelativeTransformFilename(e.options.rootDir,i),t,`step`,i,e.options.rootDir)).code,map:null}:null},name:`eve:workflow-step-transform`})}),clearCachedStepTransformTargets}function addDynamicToolTransformPlugin(e){e.hooks.hook(`rollup:before`,(e,t)=>{Array.isArray(t.plugins)&&t.plugins.unshift({async transform(e,t){if(!t.includes(`/tools/`))return null;let n=await transformDynamicToolExecute(t,e);return n===null?null:{code:n.code,map:null}},name:`eve:dynamic-tool-transform`})})}function addInstrumentationModuleSideEffectsPlugin(e,t){let n=normalizePath(t);e.hooks.hook(`rollup:before`,(e,t)=>{Array.isArray(t.plugins)&&t.plugins.unshift({name:`eve:instrumentation-module-side-effects`,resolveId(e){return normalizePath(e)===n?{id:e,moduleSideEffects:`no-treeshake`}:null}})})}function patchWorkflowTransformExcludePath(e,t){let n=normalizePath(t);e.hooks.hook(`rollup:before`,(e,t)=>{if(Array.isArray(t.plugins))for(let e of t.plugins){if(typeof e!=`object`||!e)continue;let t=e;if(t.name!==`workflow:transform`||t[WORKFLOW_TRANSFORM_PATCHED]===!0||typeof t.transform!=`function`)continue;let r=t.transform;t.transform=function(e,t,...i){return isWorkflowBundlePath(t,n)?null:r.call(this,e,t,...i)},t[WORKFLOW_TRANSFORM_PATCHED]=!0}})}function createApplicationNitroBundlerConfiguration(e,t){let n=collectConfiguredSandboxBackendNames(e.compileResult.manifest),r=shouldPruneLocalSandboxBackends({configuredBackendNames:n,preset:t})?createCompiledSandboxBackendPrunePlugin():null,i=[],a=[];for(let[e,t]of Object.entries(OPTIONAL_ENGINE_PACKAGES_BY_BACKEND_NAME))(n.has(e)?i:a).push(t);let o=createExtensionScopePlugin((e.compileResult.manifest.extensionMounts??[]).map(e=>({sourceRoot:e.sourceRoot,packageNamespace:e.packageNamespace}))),s=[r,createOptionalEngineDependencyPlugin(a),o].filter(e=>e!==null);return{nitroRolldownConfig:createNitroBundlerConfig(s),nitroRollupConfig:createNitroBundlerConfig(s),tracedAppDependencies:collectHostedTraceDependencies(e,i)}}function createApplicationNitroPlugins(e){let t=[e.compiledArtifacts.bootstrapPath,e.compiledArtifacts.workflowWorldPluginPath];return manifestEnablesWorkflow(e.compileResult.manifest)&&t.push(resolvePackageSourceFilePath(`src/internal/nitro/host/workflow-sandbox-runtime-plugin.ts`)),e.compiledArtifacts.instrumentationPluginPath!==void 0&&t.push(e.compiledArtifacts.instrumentationPluginPath),t}function configureSharedApplicationNitro(e,t,n){if(addNitroRoutingImportSpecifierPlugin(e),includesWorkflowSurface(n)){let n=resolveWorkflowAliases();for(let[t,r]of Object.entries(n))e.options.alias[t]=r;addWorkflowModuleSideEffectsPlugin(e,t.workflowBuildDir),patchWorkflowTransformExcludePath(e,t.workflowBuildDir)}addDynamicToolTransformPlugin(e),t.compiledArtifacts.instrumentationSourcePath!==void 0&&addInstrumentationModuleSideEffectsPlugin(e,t.compiledArtifacts.instrumentationSourcePath)}function configureNitroStepPlugins(e,t){return[addNitroStepModuleSideEffectsPlugin(e,{stepEntrypointPath:t}),addNitroStepTransformPlugin(e,{stepEntrypointPath:t})]}function externalizeDevelopmentWorkflowBundle(e,t){let n=new Set([normalizePath(join(t.workflowBuildDir,`workflows.mjs`))]);e.hooks.hook(`rollup:before`,(e,t)=>{let r=t.external;t.external=(e,...t)=>{if(n.has(normalizePath(e)))return!0;if(typeof r==`function`)return r(e,...t)}})}async function createDevelopmentApplicationNitro(e){let n=resolveNitroBuildDirectory(e.appRoot),r=createApplicationNitroBundlerConfiguration(e,void 0);await prepareEveVersionedCacheDirectory(n);let i=await createNitro({_cli:{command:`dev`},buildDir:n,dev:!0,features:{websocket:!0},logLevel:1,plugins:createApplicationNitroPlugins(e),publicAssets:[],scanDirs:[resolvePackageSourceDirectoryPath(`src/execution`)],rolldownConfig:r.nitroRolldownConfig,rollupConfig:r.nitroRollupConfig,rootDir:e.appRoot,serverDir:!1,traceDeps:r.tracedAppDependencies,vercel:createEveVercelOptions(!1),watchOptions:createDevelopmentWatchOptions(e.appRoot)},{watch:!0});await writeEveVersionedCacheMetadata(n),captureDevLiveVirtualModules(i);let a=join(i.options.buildDir,`workflow`,`steps.mjs`);configureSharedApplicationNitro(i,e,`all`);let s=configureNitroStepPlugins(i,a);return i.hooks.hook(`dev:reload`,()=>{for(let e of s)e()}),externalizeDevelopmentWorkflowBundle(i,e),await configureDevelopmentNitroRoutes(i,e),await addNitroStepNoExternals(i,a),i}async function createProductionApplicationNitro(e,r){let i=resolveProductionNitroPreset(),a=createApplicationNitroBundlerConfiguration(e,i),s=createApplicationNitroPlugins(e);s.push(resolvePackageSourceFilePath(`src/internal/nitro/host/sandbox-shutdown-plugin.ts`)),await prepareEveVersionedCacheDirectory(r.buildDir);let c=await createNitro({_cli:{command:`build`},buildDir:r.buildDir,dev:!1,features:{websocket:includesApplicationSurface(r.surface)&&manifestHasWebSocketChannel(e.compileResult.manifest)},output:{dir:r.outputDir},preset:i,plugins:s,publicAssets:[],scanDirs:includesWorkflowStepRegistrations(r.surface)?[resolvePackageSourceDirectoryPath(`src/execution`)]:void 0,rolldownConfig:a.nitroRolldownConfig,rollupConfig:a.nitroRollupConfig,rootDir:e.appRoot,serverDir:!1,traceDeps:a.tracedAppDependencies,vercel:createEveVercelOptions(i===`vercel`&&includesApplicationSurface(r.surface))});return await writeEveVersionedCacheMetadata(r.buildDir),configureSharedApplicationNitro(c,e,r.surface),includesWorkflowStepRegistrations(r.surface)&&configureNitroStepPlugins(c,join(e.workflowBuildDir,`steps.mjs`)),includesApplicationSurface(r.surface)&&e.scheduleRegistrations.length>0&&(applyEveCronHandlerRoute(c),registerScheduleTaskHandlers(c,{artifactsConfig:createProductionNitroArtifactsConfig(),dispatchModulePath:resolvePackageSourceFilePath(`src/internal/nitro/routes/schedule-task.ts`),registrations:e.scheduleRegistrations})),await configureProductionNitroRoutes(c,e,r.surface),includesWorkflowStepRegistrations(r.surface)&&await addNitroStepNoExternals(c,join(e.workflowBuildDir,`steps.mjs`)),c}export{createDevelopmentApplicationNitro,createProductionApplicationNitro,shouldPruneLocalSandboxBackends};
@@ -1 +1 @@
1
- import{existsSync}from"node:fs";import{dirname,join,relative,resolve}from"node:path";import{toErrorMessage}from"#shared/errors.js";import{getDevelopmentEnvironmentFilePaths,loadDevelopmentEnvironmentFiles}from"#cli/dev/environment.js";import{startDevelopmentSandboxPrewarmInBackground}from"#execution/sandbox/development-prewarm.js";import{AUTHORED_ARTIFACTS_UPDATED_LOG_LINE,STRUCTURAL_RELOAD_LOG_LINE,formatChangeDetectedLogLine}from"#internal/nitro/host/dev-watcher-log.js";import{clearCompiledRuntimeAgentBundleCache}from"#runtime/sessions/compiled-agent-cache.js";import{resolveDevelopmentSourceSnapshotWatchPaths}from"#internal/nitro/dev-runtime-source-snapshot.js";import{resolveTsConfigDependencyPaths}from"#internal/application/tsconfig-dependencies.js";import{pruneDevelopmentRuntimeArtifactsSnapshotsInBackground}from"#internal/nitro/dev-runtime-artifacts.js";import{prepareApplicationHost}from"#internal/nitro/host/prepare-application-host.js";import{createNitroArtifactsConfig}from"#internal/nitro/host/artifacts-config.js";import{computeChannelRouteRegistrations,syncChannelVirtualHandlers}from"#internal/nitro/host/channel-routes.js";import{watch}from"#compiled/chokidar/index.js";import{resolveNitroCompiledArtifactsSource}from"#internal/nitro/routes/runtime-artifacts.js";const WATCHED_LOCKFILE_NAMES=[`pnpm-lock.yaml`,`package-lock.json`,`yarn.lock`,`bun.lock`,`bun.lockb`],WATCH_ROOT_MARKER_NAMES=[`.git`,`pnpm-workspace.yaml`],WATCHER_IGNORED_DIRECTORY_NAMES=new Set([`.generated`,`.eve`,`.git`,`.next`,`.output`,`.turbo`,`.vercel`,`.workflow-data`,`build`,`dist`,`node_modules`]);async function startAuthoredSourceWatcher(e){let t=e.preparedHost,n=!1,r=Promise.resolve(),i,o=!1,s=new Map,c=new Set,u=await resolveAuthoredWatchPaths(t),d=createWatchPathMap(u),f=watch(u,{awaitWriteFinish:{pollInterval:50,stabilityThreshold:160},followSymlinks:!1,ignoreInitial:!0,ignored:shouldIgnoreWatcherPath}),p=waitForWatcherReady(f),rebuild=async i=>{n||(r=r.then(async()=>{if(n)return;let r=[...s.values()];if(!i&&r.length===0)return;let o=[...c];s.clear(),c.clear();let l=t,u=hasSandboxRelatedChange(l.compileResult.project.agentRoot,o),p=hasDevelopmentEnvironmentFileChange(l.appRoot,o);r.length>0&&console.log(formatChangeDetectedLogLine(l.appRoot,r));try{p&&loadDevelopmentEnvironmentFiles(l.appRoot);let n=await prepareApplicationHost(l.appRoot,{dev:e.nitro.options.dev===!0});e.nitro.options.dev===!0&&pruneDevelopmentRuntimeArtifactsSnapshotsInBackground(n.appRoot);let r=createNitroArtifactsConfig({appRoot:n.appRoot,dev:e.nitro.options.dev===!0});u&&startDevelopmentSandboxPrewarmInBackground({appRoot:n.appRoot,compiledArtifactsSource:resolveNitroCompiledArtifactsSource(r),log:e=>console.log(e)});let i=syncChannelVirtualHandlers(e.nitro,{artifactsConfig:r,next:computeChannelRouteRegistrations(n),previous:computeChannelRouteRegistrations(l)});clearCompiledRuntimeAgentBundleCache(),t=n,i||p?(console.log(STRUCTURAL_RELOAD_LOG_LINE),await e.nitro.hooks.callHook(`rollup:reload`)):console.log(AUTHORED_ARTIFACTS_UPDATED_LOG_LINE),d=syncWatcherPaths({nextWatchPaths:await resolveAuthoredWatchPaths(n),previousWatchPathsByKey:d,watcher:f})}catch(e){console.error(`[eve:dev] rebuild failed: ${toErrorMessage(e)}`)}}).catch(e=>{console.error(`[eve:dev] rebuild queue error: ${toErrorMessage(e)}`)}),await r)},flush=async()=>{i!==void 0&&(clearTimeout(i),i=void 0),await rebuild(!1)};return f.on(`all`,(e,t)=>{n||!o||(s.set(`${e}:${t}`,{event:e,path:t}),c.add(t),i!==void 0&&clearTimeout(i),i=setTimeout(()=>{i=void 0,flush()},120))}),await p,o=!0,{async close(){n=!0,i!==void 0&&(clearTimeout(i),i=void 0),await f.close(),await r},flush,rebuild:async()=>{i!==void 0&&(clearTimeout(i),i=void 0),await rebuild(!0)}}}async function waitForWatcherReady(e){await new Promise((t,n)=>{e.on(`ready`,()=>{t()}),e.on(`error`,e=>{n(e)})})}async function resolveAuthoredWatchPaths(e){let t=new Set([e.compileResult.project.agentRoot,join(e.appRoot,`package.json`),join(e.appRoot,`jsconfig.json`),join(e.appRoot,`tsconfig.json`),join(e.appRoot,`tsconfig.*.json`)]),r=await resolveTsConfigWatchPaths(e.appRoot),i=await resolveDevelopmentSourceSnapshotWatchPaths(e.appRoot);for(let n of getDevelopmentEnvironmentFilePaths(e.appRoot))t.add(n);for(let e of i)t.add(e);for(let e of r)t.add(e);for(let r of resolveLockfileSearchDirectories(e.appRoot))for(let e of WATCHED_LOCKFILE_NAMES)t.add(join(r,e));return[...t].sort((e,t)=>e.localeCompare(t))}function createWatchPathMap(e){let t=new Map;for(let n of e)t.set(toWatchPathKey(n),n);return t}function syncWatcherPaths(e){let t=createWatchPathMap(e.nextWatchPaths),n=[],r=[];for(let[r,i]of t)e.previousWatchPathsByKey.has(r)||n.push(i);for(let[n,i]of e.previousWatchPathsByKey)t.has(n)||r.push(i);return n.length>0&&e.watcher.add(n),r.length>0&&e.watcher.unwatch(r),t}function toWatchPathKey(e){return e.replaceAll(`\\`,`/`)}function hasDevelopmentEnvironmentFileChange(e,t){let n=new Set(getDevelopmentEnvironmentFilePaths(e).map(e=>toWatchPathKey(resolve(e))));return t.some(e=>n.has(toWatchPathKey(resolve(e))))}function hasSandboxRelatedChange(e,t){return t.some(t=>{let n=toAgentRelativePath(e,t);return n===`sandbox.ts`||n.startsWith(`sandbox/`)||n===`workspace`||n.startsWith(`workspace/`)||n===`skills`||n.startsWith(`skills/`)})}function toAgentRelativePath(e,t){let n=toWatchPathKey(relative(resolve(e),resolve(t)));return n===`..`||n.startsWith(`../`)||n===``?``:n}function resolveLockfileSearchDirectories(e){let n=resolve(e),r=[n],a=n;for(;;){if(hasWatchRootMarker(a))return r;let e=dirname(a);if(e===a)return[n];a=e,r.push(a)}}function hasWatchRootMarker(t){return WATCH_ROOT_MARKER_NAMES.some(r=>existsSync(join(t,r)))}async function resolveTsConfigWatchPaths(e){return await resolveTsConfigDependencyPaths(e)}function shouldIgnoreWatcherPath(e){return e.replaceAll(`\\`,`/`).split(`/`).filter(Boolean).some(e=>WATCHER_IGNORED_DIRECTORY_NAMES.has(e))}export{startAuthoredSourceWatcher};
1
+ import{existsSync}from"node:fs";import{dirname,join,relative,resolve}from"node:path";import{toErrorMessage}from"#shared/errors.js";import{getDevelopmentEnvironmentFilePaths,loadDevelopmentEnvironmentFiles}from"#cli/dev/environment.js";import{startDevelopmentSandboxPrewarmInBackground}from"#execution/sandbox/development-prewarm.js";import{AUTHORED_ARTIFACTS_UPDATED_LOG_LINE,STRUCTURAL_RELOAD_LOG_LINE,formatChangeDetectedLogLine}from"#internal/nitro/host/dev-watcher-log.js";import{clearCompiledRuntimeAgentBundleCache}from"#runtime/sessions/compiled-agent-cache.js";import{resolveDevelopmentSourceSnapshotWatchPaths}from"#internal/nitro/dev-runtime-source-snapshot.js";import{resolveTsConfigDependencyPaths}from"#internal/application/tsconfig-dependencies.js";import{prepareDevelopmentApplicationHost}from"#internal/nitro/host/prepare-application-host.js";import{createDevelopmentNitroArtifactsConfig}from"#internal/nitro/host/artifacts-config.js";import{computeChannelRouteRegistrations,syncChannelVirtualHandlers}from"#internal/nitro/host/channel-routes.js";import{watch as watch$1}from"#compiled/chokidar/index.js";import{resolveNitroCompiledArtifactsSource}from"#internal/nitro/routes/runtime-artifacts.js";const WATCHED_LOCKFILE_NAMES=[`pnpm-lock.yaml`,`package-lock.json`,`yarn.lock`,`bun.lock`,`bun.lockb`],WATCH_ROOT_MARKER_NAMES=[`.git`,`pnpm-workspace.yaml`],WATCHER_IGNORED_DIRECTORY_NAMES=new Set([`.generated`,`.eve`,`.git`,`.next`,`.output`,`.turbo`,`.vercel`,`.workflow-data`,`build`,`dist`,`node_modules`]);async function startAuthoredSourceWatcher(e){let t=e.preparedHost,n=!1,r=Promise.resolve(),i,o=!1,s=new Map,c=new Set,u=await resolveAuthoredWatchPaths(t),d=createWatchPathMap(u),f=watch$1(u,{awaitWriteFinish:{pollInterval:50,stabilityThreshold:160},followSymlinks:!1,ignoreInitial:!0,ignored:shouldIgnoreWatcherPath}),p=waitForWatcherReady(f),rebuild=async i=>{n||(r=r.then(async()=>{if(n)return;let r=[...s.values()];if(!i&&r.length===0)return;let o=[...c];s.clear(),c.clear();let l=t,u=hasSandboxRelatedChange(l.compileResult.project.agentRoot,o),p=hasDevelopmentEnvironmentFileChange(l.appRoot,o);r.length>0&&console.log(formatChangeDetectedLogLine(l.appRoot,r));try{p&&loadDevelopmentEnvironmentFiles(l.appRoot);let n=await prepareDevelopmentApplicationHost(l.appRoot),r=createDevelopmentNitroArtifactsConfig({appRoot:n.appRoot});u&&startDevelopmentSandboxPrewarmInBackground({appRoot:n.appRoot,compiledArtifactsSource:resolveNitroCompiledArtifactsSource(r),log:e=>console.log(e)});let i=syncChannelVirtualHandlers(e.nitro,{artifactsConfig:r,next:computeChannelRouteRegistrations(n),previous:computeChannelRouteRegistrations(l)});clearCompiledRuntimeAgentBundleCache(),t=n,i||p?(console.log(STRUCTURAL_RELOAD_LOG_LINE),await e.nitro.hooks.callHook(`rollup:reload`)):console.log(AUTHORED_ARTIFACTS_UPDATED_LOG_LINE),d=syncWatcherPaths({nextWatchPaths:await resolveAuthoredWatchPaths(n),previousWatchPathsByKey:d,watcher:f})}catch(e){console.error(`[eve:dev] rebuild failed: ${toErrorMessage(e)}`)}}).catch(e=>{console.error(`[eve:dev] rebuild queue error: ${toErrorMessage(e)}`)}),await r)},flush=async()=>{i!==void 0&&(clearTimeout(i),i=void 0),await rebuild(!1)};return f.on(`all`,(e,t)=>{n||!o||(s.set(`${e}:${t}`,{event:e,path:t}),c.add(t),i!==void 0&&clearTimeout(i),i=setTimeout(()=>{i=void 0,flush()},120))}),await p,o=!0,{async close(){n=!0,i!==void 0&&(clearTimeout(i),i=void 0),await f.close(),await r},flush,rebuild:async()=>{i!==void 0&&(clearTimeout(i),i=void 0),await rebuild(!0)}}}async function waitForWatcherReady(e){await new Promise((t,n)=>{e.on(`ready`,()=>{t()}),e.on(`error`,e=>{n(e)})})}async function resolveAuthoredWatchPaths(e){let t=new Set([e.compileResult.project.agentRoot,join(e.appRoot,`package.json`),join(e.appRoot,`jsconfig.json`),join(e.appRoot,`tsconfig.json`),join(e.appRoot,`tsconfig.*.json`)]),r=await resolveTsConfigWatchPaths(e.appRoot),i=await resolveDevelopmentSourceSnapshotWatchPaths(e.appRoot);for(let n of getDevelopmentEnvironmentFilePaths(e.appRoot))t.add(n);for(let e of i)t.add(e);for(let e of r)t.add(e);for(let r of resolveLockfileSearchDirectories(e.appRoot))for(let e of WATCHED_LOCKFILE_NAMES)t.add(join(r,e));return[...t].sort((e,t)=>e.localeCompare(t))}function createWatchPathMap(e){let t=new Map;for(let n of e)t.set(toWatchPathKey(n),n);return t}function syncWatcherPaths(e){let t=createWatchPathMap(e.nextWatchPaths),n=[],r=[];for(let[r,i]of t)e.previousWatchPathsByKey.has(r)||n.push(i);for(let[n,i]of e.previousWatchPathsByKey)t.has(n)||r.push(i);return n.length>0&&e.watcher.add(n),r.length>0&&e.watcher.unwatch(r),t}function toWatchPathKey(e){return e.replaceAll(`\\`,`/`)}function hasDevelopmentEnvironmentFileChange(e,t){let n=new Set(getDevelopmentEnvironmentFilePaths(e).map(e=>toWatchPathKey(resolve(e))));return t.some(e=>n.has(toWatchPathKey(resolve(e))))}function hasSandboxRelatedChange(e,t){return t.some(t=>{let n=toAgentRelativePath(e,t);return n===`sandbox.ts`||n.startsWith(`sandbox/`)||n===`workspace`||n.startsWith(`workspace/`)||n===`skills`||n.startsWith(`skills/`)})}function toAgentRelativePath(e,t){let n=toWatchPathKey(relative(resolve(e),resolve(t)));return n===`..`||n.startsWith(`../`)||n===``?``:n}function resolveLockfileSearchDirectories(e){let n=resolve(e),r=[n],a=n;for(;;){if(hasWatchRootMarker(a))return r;let e=dirname(a);if(e===a)return[n];a=e,r.push(a)}}function hasWatchRootMarker(t){return WATCH_ROOT_MARKER_NAMES.some(r=>existsSync(join(t,r)))}async function resolveTsConfigWatchPaths(e){return await resolveTsConfigDependencyPaths(e)}function shouldIgnoreWatcherPath(e){return e.replaceAll(`\\`,`/`).split(`/`).filter(Boolean).some(e=>WATCHER_IGNORED_DIRECTORY_NAMES.has(e))}export{startAuthoredSourceWatcher};
@@ -1,4 +1,4 @@
1
- import type { NitroArtifactsConfigInput } from "#internal/nitro/host/artifacts-config.js";
1
+ import type { DevelopmentNitroArtifactsConfig } from "#internal/nitro/routes/runtime-artifacts.js";
2
2
  /**
3
3
  * Result of dispatching one authored schedule via the dev-only HTTP route.
4
4
  */
@@ -41,6 +41,6 @@ export declare class UnknownDevScheduleError extends Error {
41
41
  * resolve relative to the app instead of the installed eve package.
42
42
  */
43
43
  export declare function dispatchScheduleInDev(input: {
44
- readonly artifactsConfig: NitroArtifactsConfigInput;
44
+ readonly artifactsConfig: DevelopmentNitroArtifactsConfig;
45
45
  readonly scheduleId: string;
46
46
  }): Promise<DispatchScheduleInDevResult>;
@@ -1 +1 @@
1
- import{createDiskRuntimeCompiledArtifactsSource}from"#runtime/compiled-artifacts-source.js";import{createScheduleRegistrations}from"#runtime/schedules/register.js";import{loadResolvedCompiledSchedules}from"#runtime/schedules/resolve-schedule.js";var UnknownDevScheduleError=class extends Error{availableScheduleIds;scheduleId;constructor(e,t){let n=t.length===0?`No schedules are defined in this app.`:`Available schedules: ${t.map(e=>`"${e}"`).join(`, `)}.`;super(`Unknown schedule "${e}". ${n}`),this.name=`UnknownDevScheduleError`,this.scheduleId=e,this.availableScheduleIds=t}};async function dispatchScheduleInDev(r){let{appRoot:i,moduleMapLoaderPath:a}=r.artifactsConfig;if(i===void 0||a===void 0)throw Error(`Dev schedule dispatch requires "appRoot" and "moduleMapLoaderPath" in the artifacts config.`);let o=createScheduleRegistrations(await loadResolvedCompiledSchedules({compiledArtifactsSource:createDiskRuntimeCompiledArtifactsSource(i,{moduleMapLoaderPath:a})})),s=o.find(e=>e.scheduleId===r.scheduleId);if(s===void 0)throw new UnknownDevScheduleError(r.scheduleId,o.map(e=>e.scheduleId));let{dispatchScheduleTask:c}=await import(`#internal/nitro/routes/schedule-task.js`),l=await c(s.taskName,r.artifactsConfig);return{scheduleId:l.scheduleId,sessionIds:[...l.sessionIds]}}export{UnknownDevScheduleError,dispatchScheduleInDev};
1
+ import{createDiskRuntimeCompiledArtifactsSource}from"#runtime/compiled-artifacts-source.js";import{createScheduleRegistrations}from"#runtime/schedules/register.js";import{loadResolvedCompiledSchedules}from"#runtime/schedules/resolve-schedule.js";var UnknownDevScheduleError=class extends Error{availableScheduleIds;scheduleId;constructor(e,t){let n=t.length===0?`No schedules are defined in this app.`:`Available schedules: ${t.map(e=>`"${e}"`).join(`, `)}.`;super(`Unknown schedule "${e}". ${n}`),this.name=`UnknownDevScheduleError`,this.scheduleId=e,this.availableScheduleIds=t}};async function dispatchScheduleInDev(r){let{appRoot:i,moduleMapLoaderPath:a}=r.artifactsConfig;if(!i||!a)throw Error(`Dev schedule dispatch requires "appRoot" and "moduleMapLoaderPath" in the artifacts config.`);let o=createScheduleRegistrations(await loadResolvedCompiledSchedules({compiledArtifactsSource:createDiskRuntimeCompiledArtifactsSource(i,{moduleMapLoaderPath:a})})),s=o.find(e=>e.scheduleId===r.scheduleId);if(s===void 0)throw new UnknownDevScheduleError(r.scheduleId,o.map(e=>e.scheduleId));let{dispatchScheduleTask:c}=await import(`#internal/nitro/routes/schedule-task.js`),l=await c(s.taskName,r.artifactsConfig);return{scheduleId:l.scheduleId,sessionIds:[...l.sessionIds]}}export{UnknownDevScheduleError,dispatchScheduleInDev};
@@ -1,8 +1,16 @@
1
+ import type { ApplicationBuildWorkspace } from "#internal/application/build-workspace.js";
1
2
  import type { PreparedApplicationHost } from "#internal/nitro/host/types.js";
2
3
  /**
3
- * Compiles one authored app and stages the package-owned artifacts needed by
4
- * the Nitro host.
4
+ * Compiles one authored app in place and stages the package-owned artifacts
5
+ * the dev-server Nitro host needs, activating a fresh runtime-artifacts
6
+ * snapshot for hot reload.
5
7
  */
6
- export declare function prepareApplicationHost(startPath: string, options?: {
7
- readonly dev?: boolean;
8
- }): Promise<PreparedApplicationHost>;
8
+ export declare function prepareDevelopmentApplicationHost(startPath: string): Promise<PreparedApplicationHost>;
9
+ /**
10
+ * Compiles one authored app into an invocation-owned build workspace and
11
+ * stages the package-owned artifacts the production Nitro build needs.
12
+ * Compiler artifacts are written inside the workspace but their recorded
13
+ * locations point at the published output (`<finalDir>/.eve`), where
14
+ * publication later installs them.
15
+ */
16
+ export declare function prepareProductionApplicationHost(workspace: ApplicationBuildWorkspace): Promise<PreparedApplicationHost>;
@@ -1 +1 @@
1
- import{resolveApplicationHostArtifactsDirectory,resolveWorkflowBuildDirectory}from"#internal/application/paths.js";import{createAuthoredSourceRuntimeCompiledArtifactsSource}from"#internal/application/runtime-compiled-artifacts-source.js";import{activateDevelopmentRuntimeArtifactsSnapshot,stageDevelopmentRuntimeArtifactsSnapshot}from"#internal/nitro/dev-runtime-artifacts.js";import{createScheduleRegistrations}from"#runtime/schedules/register.js";import{loadResolvedCompiledSchedules}from"#runtime/schedules/resolve-schedule.js";import{compileAgent}from"#compiler/compile-agent.js";import{writeCompiledArtifactsFiles}from"#internal/application/compiled-artifacts.js";async function prepareApplicationHost(t,n={}){let r=await compileAgent({startPath:t}),i=await loadResolvedCompiledSchedules({compiledArtifactsSource:createAuthoredSourceRuntimeCompiledArtifactsSource(r.project.appRoot)}),a=createScheduleRegistrations(i),o=resolveWorkflowBuildDirectory(r.project.appRoot),s=n.dev===!0?await stageDevelopmentRuntimeArtifactsSnapshot(r):void 0,c=await writeCompiledArtifactsFiles({compileResult:r,defaultWorkflowWorld:resolveDefaultWorkflowWorld(n),outDir:resolveApplicationHostArtifactsDirectory(r.project.appRoot)});return s!==void 0&&await activateDevelopmentRuntimeArtifactsSnapshot({appRoot:r.project.appRoot,snapshot:s}),{appRoot:r.project.appRoot,compileResult:r,compiledArtifacts:c,scheduleRegistrations:a,schedules:i,workflowBuildDir:o}}function resolveDefaultWorkflowWorld(e){return e.dev===!0?`local`:process.env.VERCEL?`vercel`:`local`}export{prepareApplicationHost};
1
+ import{join}from"node:path";import{resolveApplicationHostArtifactsDirectory,resolveWorkflowBuildDirectory}from"#internal/application/paths.js";import{createAuthoredSourceRuntimeCompiledArtifactsSource}from"#internal/application/runtime-compiled-artifacts-source.js";import{createScheduleRegistrations}from"#runtime/schedules/register.js";import{loadResolvedCompiledSchedules,resolveSchedules}from"#runtime/schedules/resolve-schedule.js";import{compileAgent,compileAgentInBuildWorkspace}from"#compiler/compile-agent.js";import{writeCompiledArtifactsFiles,writeDevelopmentCompiledArtifactsFiles}from"#internal/application/compiled-artifacts.js";import{activateDevelopmentGeneration,discardDevelopmentGeneration,stageDevelopmentGeneration}from"#internal/nitro/development-generation.js";async function prepareDevelopmentApplicationHost(e){let i=await compileAgent({startPath:e}),a=await loadResolvedCompiledSchedules({compiledArtifactsSource:createAuthoredSourceRuntimeCompiledArtifactsSource(i.project.appRoot)}),o=await stageDevelopmentGeneration(i);try{let e=await writeDevelopmentCompiledArtifactsFiles({compileResult:i,outDir:resolveApplicationHostArtifactsDirectory(i.project.appRoot),runtimeAppRoot:o.runtimeAppRoot});return await activateDevelopmentGeneration({appRoot:i.project.appRoot,generation:o}),createPreparedApplicationHost({compileResult:i,compiledArtifacts:e,schedules:a,workflowBuildDir:resolveWorkflowBuildDirectory(i.project.appRoot)})}catch(e){throw await discardDevelopmentGeneration(o),e}}async function prepareProductionApplicationHost(t){let n=await compileAgentInBuildWorkspace({artifactLocations:{publishedRoot:join(t.publication.output.finalDir,`.eve`),writeRoot:t.compiler.artifactsDir},startPath:t.appRoot}),r=await resolveSchedules({manifest:n.manifest});return createPreparedApplicationHost({compileResult:n,compiledArtifacts:await writeCompiledArtifactsFiles({compileResult:n,defaultWorkflowWorld:resolveProductionWorkflowWorldTarget(),outDir:t.host.artifactsDir}),schedules:r,workflowBuildDir:t.workflow.buildDir})}function createPreparedApplicationHost(e){return{appRoot:e.compileResult.project.appRoot,compileResult:e.compileResult,compiledArtifacts:e.compiledArtifacts,scheduleRegistrations:createScheduleRegistrations(e.schedules),schedules:e.schedules,workflowBuildDir:e.workflowBuildDir}}function resolveProductionWorkflowWorldTarget(){return process.env.VERCEL?`vercel`:`local`}export{prepareDevelopmentApplicationHost,prepareProductionApplicationHost};
@@ -1,6 +1,6 @@
1
1
  import type { Nitro } from "nitro/types";
2
2
  import { type ScheduleRegistration } from "#runtime/schedules/register.js";
3
- import type { NitroArtifactsConfigInput } from "#internal/nitro/host/artifacts-config.js";
3
+ import type { NitroArtifactsConfig } from "#internal/nitro/routes/runtime-artifacts.js";
4
4
  interface ScheduleTaskNitro {
5
5
  options: Pick<Nitro["options"], "experimental" | "scheduledTasks" | "tasks" | "virtual">;
6
6
  }
@@ -13,7 +13,7 @@ interface ScheduleTaskNitro {
13
13
  * along with the baked-in artifacts config.
14
14
  */
15
15
  export interface RegisterScheduleTaskHandlersInput {
16
- readonly artifactsConfig: NitroArtifactsConfigInput;
16
+ readonly artifactsConfig: NitroArtifactsConfig;
17
17
  readonly dispatchModulePath: string;
18
18
  readonly registrations: readonly ScheduleRegistration[];
19
19
  }
@@ -22,7 +22,7 @@ export interface RegisterScheduleTaskHandlersInput {
22
22
  * change in dev mode.
23
23
  */
24
24
  export interface SyncScheduleTaskHandlersInput {
25
- readonly artifactsConfig: NitroArtifactsConfigInput;
25
+ readonly artifactsConfig: NitroArtifactsConfig;
26
26
  readonly dispatchModulePath: string;
27
27
  readonly next: readonly ScheduleRegistration[];
28
28
  readonly previous: readonly ScheduleRegistration[];
@@ -1,2 +1,2 @@
1
- import{EVE_DEV_RUNTIME_ARTIFACTS_REBUILD_ROUTE_PATH}from"#protocol/routes.js";import{isLoopbackServerUrl}from"#shared/network-address.js";import{detectPackageManager}from"#setup/package-manager.js";import{eveDevArguments}from"#setup/primitives/index.js";import{toErrorMessage}from"#shared/errors.js";import{loadDevelopmentEnvironmentFiles}from"#cli/dev/environment.js";import{startDevelopmentSandboxPrewarmInBackground}from"#execution/sandbox/development-prewarm.js";import{devBootPhase}from"#internal/dev-boot-progress.js";import{resolveDiscoveryProject}from"#discover/project.js";import{EVE_DEV_ENV_FLAG}from"#internal/application/optional-package-install.js";import{EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV,clearInitializedDevelopmentSandboxBackendNames,createDevelopmentSandboxRunId,getInitializedDevelopmentSandboxBackendNames}from"#execution/sandbox/development-run.js";import{pruneDevelopmentRuntimeArtifactsSnapshotsInBackground}from"#internal/nitro/dev-runtime-artifacts.js";import{build,createDevServer,prepare}from"nitro/builder";import{createApplicationNitro}from"#internal/nitro/host/create-application-nitro.js";import{prepareApplicationHost}from"#internal/nitro/host/prepare-application-host.js";import{createNitroArtifactsConfig}from"#internal/nitro/host/artifacts-config.js";import{resolveNitroCompiledArtifactsSource}from"#internal/nitro/routes/runtime-artifacts.js";import{DevelopmentServerState}from"#internal/nitro/host/dev-server-state.js";import{isEveServerHealthy}from"#shared/eve-server-health.js";import{handleDevRuntimeArtifactsRequest}from"#internal/nitro/routes/dev-runtime-artifacts.js";import{pruneLocalSandboxTemplatesInBackground,stopDevelopmentSandboxResources}from"#execution/sandbox/bindings/local.js";import{DEFAULT_DEVELOPMENT_SERVER_PORT,MAX_DEVELOPMENT_SERVER_PORT_ATTEMPTS}from"#internal/nitro/host/ports.js";const MAX_ALLOWED_DEVELOPMENT_SERVER_PORT=65535,WORKFLOW_LOCAL_BASE_URL_ENV=`WORKFLOW_LOCAL_BASE_URL`,PORT_ENV=`PORT`,DEFAULT_DEVELOPMENT_SERVER_HOST=`127.0.0.1`,IPV6_WILDCARD_LISTEN_HOSTNAMES=new Set([`[::]`,`::`]);function normalizeDevelopmentServerClientUrl(e){let t=new URL(e);return IPV6_WILDCARD_LISTEN_HOSTNAMES.has(t.hostname)?(t.hostname=`[::1]`,t.toString()):t.hostname===`0.0.0.0`?(t.hostname=DEFAULT_DEVELOPMENT_SERVER_HOST,t.toString()):e}async function isActiveDevelopmentServerForApp(e){try{let n=await new DevelopmentServerState(await resolveDiscoveryProject(e.appRoot)).read();return n===void 0||!isLoopbackServerUrl(n)||!await isEveServerHealthy(n)?!1:new URL(n).origin===new URL(normalizeDevelopmentServerClientUrl(e.serverUrl)).origin}catch{return!1}}function isAddressInUseError(e){return e instanceof Error&&`code`in e&&e.code===`EADDRINUSE`}function resolveDevelopmentServerPort(e){let t=typeof e==`string`?Number(e):e??DEFAULT_DEVELOPMENT_SERVER_PORT;if(!Number.isInteger(t)||t<0||t>MAX_ALLOWED_DEVELOPMENT_SERVER_PORT)throw Error(`Invalid development server port "${String(e)}". Expected an integer between 0 and ${MAX_ALLOWED_DEVELOPMENT_SERVER_PORT}.`);return t}function readEnvironmentPort(){let e=process.env[PORT_ENV];if(e===void 0||e.trim()===``)return;let t=Number(e);if(!Number.isInteger(t)||t<0||t>MAX_ALLOWED_DEVELOPMENT_SERVER_PORT)throw Error(`Invalid ${PORT_ENV} environment variable "${e}". Expected an integer between 0 and ${MAX_ALLOWED_DEVELOPMENT_SERVER_PORT}.`);return t}async function detectDevelopmentCommandPackageManager(e){try{return(await detectPackageManager(e)).kind}catch{return`pnpm`}}async function formatDevelopmentServerConnectCommand(e,t){let n=await detectDevelopmentCommandPackageManager(e);return[n,...eveDevArguments(n),t].join(` `)}async function createDevelopmentServerAlreadyRunningError(e,t){let n=await formatDevelopmentServerConnectCommand(e,t);return Error([`A dev server is already running for this eve agent.`,`To connect to the existing instance, run: ${n}`].join(`
2
- `))}function resolveDevelopmentServerPorts(e){let t=resolveDevelopmentServerPort(e.port);if(t===0||!e.retryOnAddressInUse)return[t];let n=[];for(let e=0;e<MAX_DEVELOPMENT_SERVER_PORT_ATTEMPTS;e+=1){let r=t+e;if(r>65535)break;n.push(r)}return n}function installWorkflowLocalQueueEnvironment(e){let t=process.env[WORKFLOW_LOCAL_BASE_URL_ENV],n=process.env[PORT_ENV],r=new URL(normalizeDevelopmentServerClientUrl(e));return process.env[WORKFLOW_LOCAL_BASE_URL_ENV]=r.origin,r.port&&(process.env[PORT_ENV]=r.port),()=>{t===void 0?delete process.env[WORKFLOW_LOCAL_BASE_URL_ENV]:process.env[WORKFLOW_LOCAL_BASE_URL_ENV]=t,n===void 0?delete process.env[PORT_ENV]:process.env[PORT_ENV]=n}}function attachTemporarySocketErrorHandler(e){let onSocketError=()=>{};return e.once(`error`,onSocketError),()=>{e.off(`error`,onSocketError)}}function shouldProxyDevelopmentServerWebSocketUpgrades(e){return e.options.features.websocket===!0||e.options.experimental.websocket===!0}function guardDevelopmentServerWebSocketUpgrades(e,t){let n=t.upgrade.bind(t),r=shouldProxyDevelopmentServerWebSocketUpgrades(e);t.upgrade=async(e,t,i)=>{if(!r){t.destroyed||t.destroy();return}let a=attachTemporarySocketErrorHandler(t);try{await n(e,t,i)}catch{t.destroyed||t.destroy()}finally{a()}}}function addDevelopmentRuntimeArtifactsRebuildHandler(t){t.nitro.options.devHandlers.push({route:EVE_DEV_RUNTIME_ARTIFACTS_REBUILD_ROUTE_PATH,handler:async e=>{let n=e.node?.req.url??``;return new URL(n,`http://localhost`).searchParams.get(`force`)===`1`?await t.watcher.rebuild():await t.watcher.flush(),handleDevRuntimeArtifactsRequest({appRoot:t.appRoot})}})}async function closeDevelopmentServerResources(e){let t=[],attempt=async e=>{try{return await e(),!0}catch(e){return t.push(e),!1}},n=e.authoredSourceWatcher;n!==void 0&&await attempt(()=>n.close());let r=e.devServer,i=r===void 0?!0:await attempt(()=>r.close()),a=e.nitro;return a!==void 0&&await attempt(()=>a.close()),await attempt(()=>stopDevelopmentSandboxResources({backendNames:getInitializedDevelopmentSandboxBackendNames(e.developmentSandboxRunId),devRunId:e.developmentSandboxRunId,log:e=>console.warn(`[eve:dev] ${e}`)})),{errors:t,listenerClosed:i}}function createDevelopmentServerCleanupError(e){if(e.length!==0){if(e.length===1){let t=e[0];return t instanceof Error?t:Error(`Failed to close the development server: ${toErrorMessage(t)}`,{cause:t})}return AggregateError(e,`Multiple development-server resources failed to close.`)}}function createDevelopmentServerStartupCleanupError(e,t){return AggregateError([e,...t],`${toErrorMessage(e)} Cleanup also failed.`,{cause:e})}async function listenForDevelopmentServer(e){let t=resolveDevelopmentServerPorts({port:e.port,retryOnAddressInUse:e.retryOnAddressInUse}),n;for(let r of t){let t=e.devServer.listen({hostname:e.host,port:r,silent:!0});try{return await t.ready(),t}catch(r){if(n=r,await t.close().catch(()=>{}),!isAddressInUseError(r)||!e.retryOnAddressInUse)throw r}}throw Error(`Failed to start Nitro dev server after ${t.length} attempts. Tried ports ${t.join(`, `)}.`,{cause:n})}async function startNitroDevelopmentServer(e,n){process.env[EVE_DEV_ENV_FLAG]??=`1`;let r=await resolveDiscoveryProject(e);loadDevelopmentEnvironmentFiles(r.appRoot);let i=readEnvironmentPort(),u=n.port??i,p=n.host!==void 0||n.port!==void 0||i!==void 0,m=new DevelopmentServerState(r),h=await m.read();if(h!==void 0&&isLoopbackServerUrl(h)&&await isEveServerHealthy(h)){if(n.existing===`attach-if-unconfigured`&&!p)return{handle:{kind:`existing`,appRoot:r.appRoot,url:h},close:void 0};throw await createDevelopmentServerAlreadyRunningError(r.appRoot,h)}let g=process.env[EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV],_=createDevelopmentSandboxRunId();process.env[EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV]=_;let v,y,b,x;try{let e=await devBootPhase(`compiling agent`,()=>prepareApplicationHost(r.appRoot,{dev:!0}),n.onBootProgress);pruneDevelopmentRuntimeArtifactsSnapshotsInBackground(e.appRoot);let t=resolveNitroCompiledArtifactsSource(createNitroArtifactsConfig({appRoot:e.appRoot,dev:!0}));startDevelopmentSandboxPrewarmInBackground({appRoot:e.appRoot,compiledArtifactsSource:t}),pruneLocalSandboxTemplatesInBackground(e.appRoot);let i=await devBootPhase(`creating dev server`,()=>createApplicationNitro(e,!0),n.onBootProgress);v=i,y=createDevServer(i);let a=y;guardDevelopmentServerWebSocketUpgrades(i,y);let o=n.host??i.options.devServer.hostname??DEFAULT_DEVELOPMENT_SERVER_HOST,s=u===void 0,c=await devBootPhase(`binding port`,()=>listenForDevelopmentServer({devServer:a,host:o,port:u,retryOnAddressInUse:s}),n.onBootProgress);if(!c.url)throw Error(`Nitro dev server did not expose a URL.`);let l=normalizeDevelopmentServerClientUrl(c.url);b=installWorkflowLocalQueueEnvironment(l),await devBootPhase(`building dev bundle`,async()=>{await prepare(i),await build(i)},n.onBootProgress),x=await devBootPhase(`starting file watcher`,async()=>{let{startAuthoredSourceWatcher:t}=await import(`#internal/nitro/host/dev-authored-source-watcher.js`);return t({nitro:i,preparedHost:e})},n.onBootProgress),addDevelopmentRuntimeArtifactsRebuildHandler({appRoot:r.appRoot,nitro:i,watcher:x}),await m.write(l);let d=b;if(d===void 0)throw Error(`Workflow local queue environment was not initialized.`);let f=x,p=y,h=i,S;return{handle:{kind:`started`,appRoot:r.appRoot,url:l},close:()=>(S??=(async()=>{let e=await closeDevelopmentServerResources({authoredSourceWatcher:f,devServer:p,developmentSandboxRunId:_,nitro:h});e.listenerClosed&&await m.remove().catch(()=>{});try{let t=createDevelopmentServerCleanupError(e.errors);if(t!==void 0)throw t}finally{clearInitializedDevelopmentSandboxBackendNames(_),d(),restoreDevelopmentSandboxRunId(g)}})(),S)}}catch(e){let t=await closeDevelopmentServerResources({authoredSourceWatcher:x,devServer:y,developmentSandboxRunId:_,nitro:v}),n=[...t.errors];throw b?.(),clearInitializedDevelopmentSandboxBackendNames(_),t.listenerClosed&&await m.remove().catch(()=>{}),restoreDevelopmentSandboxRunId(g),n.length>0?createDevelopmentServerStartupCleanupError(e,n):e}}function createDevelopmentServer(e,t={}){let n,r;return{start(){if(n!==void 0)throw Error(`DevelopmentServer.start() was already called.`);return n=startNitroDevelopmentServer(e,t).then(({handle:e,close:t})=>(r=t,e)),n},async close(){n!==void 0&&(await n.catch(()=>void 0),await r?.())}}}function restoreDevelopmentSandboxRunId(e){if(e===void 0){delete process.env[EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV];return}process.env[EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV]=e}export{createDevelopmentServer,isActiveDevelopmentServerForApp,normalizeDevelopmentServerClientUrl};
1
+ import{EVE_DEV_RUNTIME_ARTIFACTS_REBUILD_ROUTE_PATH}from"#protocol/routes.js";import{isLoopbackServerUrl}from"#shared/network-address.js";import{detectPackageManager}from"#setup/package-manager.js";import{eveDevArguments}from"#setup/primitives/index.js";import{toErrorMessage}from"#shared/errors.js";import{loadDevelopmentEnvironmentFiles}from"#cli/dev/environment.js";import{startDevelopmentSandboxPrewarmInBackground}from"#execution/sandbox/development-prewarm.js";import{devBootPhase}from"#internal/dev-boot-progress.js";import{resolveDiscoveryProject}from"#discover/project.js";import{EVE_DEV_ENV_FLAG}from"#internal/application/optional-package-install.js";import{EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV,clearInitializedDevelopmentSandboxBackendNames,createDevelopmentSandboxRunId,getInitializedDevelopmentSandboxBackendNames}from"#execution/sandbox/development-run.js";import{build,createDevServer,prepare}from"nitro/builder";import{createDevelopmentApplicationNitro}from"#internal/nitro/host/create-application-nitro.js";import{prepareDevelopmentApplicationHost}from"#internal/nitro/host/prepare-application-host.js";import{createDevelopmentNitroArtifactsConfig}from"#internal/nitro/host/artifacts-config.js";import{resolveNitroCompiledArtifactsSource}from"#internal/nitro/routes/runtime-artifacts.js";import{DevelopmentServerState}from"#internal/nitro/host/dev-server-state.js";import{isEveServerHealthy}from"#shared/eve-server-health.js";import{handleDevRuntimeArtifactsRequest}from"#internal/nitro/routes/dev-runtime-artifacts.js";import{pruneLocalSandboxTemplatesInBackground,stopDevelopmentSandboxResources}from"#execution/sandbox/bindings/local.js";import{DEFAULT_DEVELOPMENT_SERVER_PORT,MAX_DEVELOPMENT_SERVER_PORT_ATTEMPTS}from"#internal/nitro/host/ports.js";const MAX_ALLOWED_DEVELOPMENT_SERVER_PORT=65535,WORKFLOW_LOCAL_BASE_URL_ENV=`WORKFLOW_LOCAL_BASE_URL`,PORT_ENV=`PORT`,DEFAULT_DEVELOPMENT_SERVER_HOST=`127.0.0.1`,IPV6_WILDCARD_LISTEN_HOSTNAMES=new Set([`[::]`,`::`]);function normalizeDevelopmentServerClientUrl(e){let t=new URL(e);return IPV6_WILDCARD_LISTEN_HOSTNAMES.has(t.hostname)?(t.hostname=`[::1]`,t.toString()):t.hostname===`0.0.0.0`?(t.hostname=DEFAULT_DEVELOPMENT_SERVER_HOST,t.toString()):e}async function isActiveDevelopmentServerForApp(e){try{let n=await new DevelopmentServerState(await resolveDiscoveryProject(e.appRoot)).read();return n===void 0||!isLoopbackServerUrl(n)||!await isEveServerHealthy(n)?!1:new URL(n).origin===new URL(normalizeDevelopmentServerClientUrl(e.serverUrl)).origin}catch{return!1}}function isAddressInUseError(e){return e instanceof Error&&`code`in e&&e.code===`EADDRINUSE`}function resolveDevelopmentServerPort(e){let t=typeof e==`string`?Number(e):e??DEFAULT_DEVELOPMENT_SERVER_PORT;if(!Number.isInteger(t)||t<0||t>MAX_ALLOWED_DEVELOPMENT_SERVER_PORT)throw Error(`Invalid development server port "${String(e)}". Expected an integer between 0 and ${MAX_ALLOWED_DEVELOPMENT_SERVER_PORT}.`);return t}function readEnvironmentPort(){let e=process.env[PORT_ENV];if(e===void 0||e.trim()===``)return;let t=Number(e);if(!Number.isInteger(t)||t<0||t>MAX_ALLOWED_DEVELOPMENT_SERVER_PORT)throw Error(`Invalid ${PORT_ENV} environment variable "${e}". Expected an integer between 0 and ${MAX_ALLOWED_DEVELOPMENT_SERVER_PORT}.`);return t}async function detectDevelopmentCommandPackageManager(e){try{return(await detectPackageManager(e)).kind}catch{return`pnpm`}}async function formatDevelopmentServerConnectCommand(e,t){let n=await detectDevelopmentCommandPackageManager(e);return[n,...eveDevArguments(n),t].join(` `)}async function createDevelopmentServerAlreadyRunningError(e,t){let n=await formatDevelopmentServerConnectCommand(e,t);return Error([`A dev server is already running for this eve agent.`,`To connect to the existing instance, run: ${n}`].join(`
2
+ `))}function resolveDevelopmentServerPorts(e){let t=resolveDevelopmentServerPort(e.port);if(t===0||!e.retryOnAddressInUse)return[t];let n=[];for(let e=0;e<MAX_DEVELOPMENT_SERVER_PORT_ATTEMPTS;e+=1){let r=t+e;if(r>65535)break;n.push(r)}return n}function installWorkflowLocalQueueEnvironment(e){let t=process.env[WORKFLOW_LOCAL_BASE_URL_ENV],n=process.env[PORT_ENV],r=new URL(normalizeDevelopmentServerClientUrl(e));return process.env[WORKFLOW_LOCAL_BASE_URL_ENV]=r.origin,r.port&&(process.env[PORT_ENV]=r.port),()=>{t===void 0?delete process.env[WORKFLOW_LOCAL_BASE_URL_ENV]:process.env[WORKFLOW_LOCAL_BASE_URL_ENV]=t,n===void 0?delete process.env[PORT_ENV]:process.env[PORT_ENV]=n}}function attachTemporarySocketErrorHandler(e){let onSocketError=()=>{};return e.once(`error`,onSocketError),()=>{e.off(`error`,onSocketError)}}function shouldProxyDevelopmentServerWebSocketUpgrades(e){return e.options.features.websocket===!0||e.options.experimental.websocket===!0}function guardDevelopmentServerWebSocketUpgrades(e,t){let n=t.upgrade.bind(t),r=shouldProxyDevelopmentServerWebSocketUpgrades(e);t.upgrade=async(e,t,i)=>{if(!r){t.destroyed||t.destroy();return}let a=attachTemporarySocketErrorHandler(t);try{await n(e,t,i)}catch{t.destroyed||t.destroy()}finally{a()}}}function addDevelopmentRuntimeArtifactsRebuildHandler(t){t.nitro.options.devHandlers.push({route:EVE_DEV_RUNTIME_ARTIFACTS_REBUILD_ROUTE_PATH,handler:async e=>{let n=e.node?.req.url??``;return new URL(n,`http://localhost`).searchParams.get(`force`)===`1`?await t.watcher.rebuild():await t.watcher.flush(),handleDevRuntimeArtifactsRequest({appRoot:t.appRoot})}})}async function closeDevelopmentServerResources(e){let t=[],attempt=async e=>{try{return await e(),!0}catch(e){return t.push(e),!1}},n=e.authoredSourceWatcher;n!==void 0&&await attempt(()=>n.close());let r=e.devServer,i=r===void 0?!0:await attempt(()=>r.close()),a=e.nitro;return a!==void 0&&await attempt(()=>a.close()),await attempt(()=>stopDevelopmentSandboxResources({backendNames:getInitializedDevelopmentSandboxBackendNames(e.developmentSandboxRunId),devRunId:e.developmentSandboxRunId,log:e=>console.warn(`[eve:dev] ${e}`)})),{errors:t,listenerClosed:i}}function createDevelopmentServerCleanupError(e){if(e.length!==0){if(e.length===1){let t=e[0];return t instanceof Error?t:Error(`Failed to close the development server: ${toErrorMessage(t)}`,{cause:t})}return AggregateError(e,`Multiple development-server resources failed to close.`)}}function createDevelopmentServerStartupCleanupError(e,t){return AggregateError([e,...t],`${toErrorMessage(e)} Cleanup also failed.`,{cause:e})}async function listenForDevelopmentServer(e){let t=resolveDevelopmentServerPorts({port:e.port,retryOnAddressInUse:e.retryOnAddressInUse}),n;for(let r of t){let t=e.devServer.listen({hostname:e.host,port:r,silent:!0});try{return await t.ready(),t}catch(r){if(n=r,await t.close().catch(()=>{}),!isAddressInUseError(r)||!e.retryOnAddressInUse)throw r}}throw Error(`Failed to start Nitro dev server after ${t.length} attempts. Tried ports ${t.join(`, `)}.`,{cause:n})}async function startNitroDevelopmentServer(e,n){process.env[EVE_DEV_ENV_FLAG]??=`1`;let r=await resolveDiscoveryProject(e);loadDevelopmentEnvironmentFiles(r.appRoot);let i=readEnvironmentPort(),u=n.port??i,p=n.host!==void 0||n.port!==void 0||i!==void 0,m=new DevelopmentServerState(r),h=await m.read();if(h!==void 0&&isLoopbackServerUrl(h)&&await isEveServerHealthy(h)){if(n.existing===`attach-if-unconfigured`&&!p)return{handle:{kind:`existing`,appRoot:r.appRoot,url:h},close:void 0};throw await createDevelopmentServerAlreadyRunningError(r.appRoot,h)}let g=process.env[EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV],_=createDevelopmentSandboxRunId();process.env[EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV]=_;let v,y,b,x;try{let e=await devBootPhase(`compiling agent`,()=>prepareDevelopmentApplicationHost(r.appRoot),n.onBootProgress),t=resolveNitroCompiledArtifactsSource(createDevelopmentNitroArtifactsConfig({appRoot:e.appRoot}));startDevelopmentSandboxPrewarmInBackground({appRoot:e.appRoot,compiledArtifactsSource:t}),pruneLocalSandboxTemplatesInBackground(e.appRoot);let i=await devBootPhase(`creating dev server`,()=>createDevelopmentApplicationNitro(e),n.onBootProgress);v=i,y=createDevServer(i);let a=y;guardDevelopmentServerWebSocketUpgrades(i,y);let o=n.host??i.options.devServer.hostname??DEFAULT_DEVELOPMENT_SERVER_HOST,s=u===void 0,c=await devBootPhase(`binding port`,()=>listenForDevelopmentServer({devServer:a,host:o,port:u,retryOnAddressInUse:s}),n.onBootProgress);if(!c.url)throw Error(`Nitro dev server did not expose a URL.`);let l=normalizeDevelopmentServerClientUrl(c.url);b=installWorkflowLocalQueueEnvironment(l),await devBootPhase(`building dev bundle`,async()=>{await prepare(i),await build(i)},n.onBootProgress),x=await devBootPhase(`starting file watcher`,async()=>{let{startAuthoredSourceWatcher:t}=await import(`#internal/nitro/host/dev-authored-source-watcher.js`);return t({nitro:i,preparedHost:e})},n.onBootProgress),addDevelopmentRuntimeArtifactsRebuildHandler({appRoot:r.appRoot,nitro:i,watcher:x}),await m.write(l);let d=b;if(d===void 0)throw Error(`Workflow local queue environment was not initialized.`);let f=x,p=y,h=i,S;return{handle:{kind:`started`,appRoot:r.appRoot,url:l},close:()=>(S??=(async()=>{let e=await closeDevelopmentServerResources({authoredSourceWatcher:f,devServer:p,developmentSandboxRunId:_,nitro:h});e.listenerClosed&&await m.remove().catch(()=>{});try{let t=createDevelopmentServerCleanupError(e.errors);if(t!==void 0)throw t}finally{clearInitializedDevelopmentSandboxBackendNames(_),d(),restoreDevelopmentSandboxRunId(g)}})(),S)}}catch(e){let t=await closeDevelopmentServerResources({authoredSourceWatcher:x,devServer:y,developmentSandboxRunId:_,nitro:v}),n=[...t.errors];throw b?.(),clearInitializedDevelopmentSandboxBackendNames(_),t.listenerClosed&&await m.remove().catch(()=>{}),restoreDevelopmentSandboxRunId(g),n.length>0?createDevelopmentServerStartupCleanupError(e,n):e}}function createDevelopmentServer(e,t={}){let n,r;return{start(){if(n!==void 0)throw Error(`DevelopmentServer.start() was already called.`);return n=startNitroDevelopmentServer(e,t).then(({handle:e,close:t})=>(r=t,e)),n},async close(){n!==void 0&&(await n.catch(()=>void 0),await r?.())}}}function restoreDevelopmentSandboxRunId(e){if(e===void 0){delete process.env[EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV];return}process.env[EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV]=e}export{createDevelopmentServer,isActiveDevelopmentServerForApp,normalizeDevelopmentServerClientUrl};
@@ -10,6 +10,10 @@ export type NitroBuildSurface = "all" | "app" | "flow";
10
10
  /** Options for one production application build. */
11
11
  export interface ApplicationBuildOptions {
12
12
  readonly skipVercelSandboxPrewarm: boolean;
13
+ readonly vercelServiceOutput?: {
14
+ readonly hostOutputDirectory: string;
15
+ readonly serviceOutputDirectory: string;
16
+ };
13
17
  }
14
18
  /** Outcome of starting a Nitro development server the current process owns. */
15
19
  export interface StartedDevelopmentServer {
@@ -1,5 +1,6 @@
1
1
  import type { CompiledAgentManifest, CompiledSubagentNode } from "#compiler/manifest.js";
2
- import { type RuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
2
+ import type { RuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
3
+ import { type NitroArtifactsConfig } from "#internal/nitro/routes/runtime-artifacts.js";
3
4
  import type { ResolvedAgent, ResolvedSandboxDefinition, ResolvedScheduleDefinition, ResolvedSkillDefinition, ResolvedInstructionsDefinition } from "#runtime/types.js";
4
5
  /**
5
6
  * Runtime data needed to build the package-owned `GET /eve/v1/info`
@@ -31,9 +32,5 @@ export declare function loadAgentInfoManifestData(input: {
31
32
  * Resolves the explicit runtime artifact source used by the package-owned
32
33
  * `GET /eve/v1/info` handler.
33
34
  */
34
- export declare function resolveAgentInfoCompiledArtifactsSource(input?: {
35
- readonly appRoot?: string;
36
- readonly dev?: boolean;
37
- readonly devRuntimeArtifactsPointerPath?: string;
38
- }): RuntimeCompiledArtifactsSource;
35
+ export declare function resolveAgentInfoCompiledArtifactsSource(input: NitroArtifactsConfig): RuntimeCompiledArtifactsSource;
39
36
  export type { CompiledAgentManifest, CompiledSubagentNode, ResolvedSandboxDefinition, ResolvedScheduleDefinition, ResolvedSkillDefinition, ResolvedInstructionsDefinition, };
@@ -1 +1 @@
1
- import{createBundledRuntimeCompiledArtifactsSource,createDiskRuntimeCompiledArtifactsSource}from"#runtime/compiled-artifacts-source.js";import{readBundledCompiledArtifacts}from"#runtime/loaders/bundled-artifacts.js";import{loadCompiledManifest}from"#runtime/loaders/manifest.js";import{readDevelopmentRuntimeArtifactsSnapshotRoot}from"#internal/nitro/dev-runtime-artifacts.js";import{resolveSchedules}from"#runtime/schedules/resolve-schedule.js";import{loadCompiledModuleMap}from"#runtime/loaders/module-map.js";import{resolveAgent}from"#runtime/resolve-agent.js";async function loadAgentInfoData(e){return await loadAgentInfoDataFromArtifacts(e.compiledArtifactsSource)}async function loadAgentInfoManifestData(e){let t=await loadCompiledManifest({compiledArtifactsSource:e.compiledArtifactsSource});return{manifest:t,schedules:await resolveSchedules({manifest:t})}}function resolveAgentInfoCompiledArtifactsSource(r={}){if(r.dev===!0&&r.appRoot!==void 0)return createDiskRuntimeCompiledArtifactsSource(readDevelopmentRuntimeArtifactsSnapshotRoot(r.devRuntimeArtifactsPointerPath)??r.appRoot);if(readBundledCompiledArtifacts()!==null)return createBundledRuntimeCompiledArtifactsSource();if(r.appRoot!==void 0)return createDiskRuntimeCompiledArtifactsSource(r.appRoot);throw Error(`eve agent info runtime data requires bundled artifacts or an app root.`)}async function loadAgentInfoDataFromArtifacts(e){let[t,n]=await Promise.all([loadCompiledManifest({compiledArtifactsSource:e}),loadCompiledModuleMap({compiledArtifactsSource:e})]),i=await resolveSchedules({manifest:t});return{agent:await resolveAgent({manifest:t,moduleMap:n}),manifest:t,schedules:i}}export{loadAgentInfoData,loadAgentInfoManifestData,resolveAgentInfoCompiledArtifactsSource};
1
+ import{loadCompiledManifest}from"#runtime/loaders/manifest.js";import{resolveNitroCompiledArtifactsSource}from"#internal/nitro/routes/runtime-artifacts.js";import{resolveSchedules}from"#runtime/schedules/resolve-schedule.js";import{loadCompiledModuleMap}from"#runtime/loaders/module-map.js";import{resolveAgent}from"#runtime/resolve-agent.js";async function loadAgentInfoData(e){return await loadAgentInfoDataFromArtifacts(e.compiledArtifactsSource)}async function loadAgentInfoManifestData(t){let n=await loadCompiledManifest({compiledArtifactsSource:t.compiledArtifactsSource});return{manifest:n,schedules:await resolveSchedules({manifest:n})}}function resolveAgentInfoCompiledArtifactsSource(e){return resolveNitroCompiledArtifactsSource(e)}async function loadAgentInfoDataFromArtifacts(t){let[r,i]=await Promise.all([loadCompiledManifest({compiledArtifactsSource:t}),loadCompiledModuleMap({compiledArtifactsSource:t})]),a=await resolveSchedules({manifest:r});return{agent:await resolveAgent({manifest:r,moduleMap:i}),manifest:r,schedules:a}}export{loadAgentInfoData,loadAgentInfoManifestData,resolveAgentInfoCompiledArtifactsSource};
@@ -1 +1 @@
1
- import{createGetSessionFn}from"#channel/session.js";import{createLogger,logError}from"#internal/logging.js";import{createSendFn}from"#channel/send.js";import{createCrossChannelReceiveFn,toCrossChannelTargets}from"#channel/cross-channel-receive.js";import{attachAgentInfoRouteResponse}from"#internal/nitro/routes/channel-route-context.js";import{resolveNitroChannelRuntimeBundle}from"#internal/nitro/routes/runtime-stack.js";import{readVercelProjectLink}from"#internal/vercel/project-link.js";import{withVercelOidcProjectResolver}from"#runtime/governance/auth/vercel-oidc-project.js";const log=createLogger(`channel.dispatch`);async function dispatchChannelRequest(e,t,r){let i=await resolveNitroChannelRuntimeBundle(r),a=i.channels.find(e=>`${e.method.toUpperCase()} ${e.urlPath}`===t);if(a===void 0)return Response.json({error:`No matching channel for this request.`,ok:!1},{status:404});let o=buildRouteArgs(e,i,a.name,r),c;try{c=await withDevelopmentVercelOidcContext(r,e.req,async()=>{if(a.handler)return await a.handler(e.req,o.args);let t={agent:o.agent,waitUntil:o.args.waitUntil,params:o.args.params,requestIp:o.args.requestIp};return await a.fetch(e.req,t)})}catch(r){let i=logError(log,`channel handler threw`,r,{routeKey:t,channel:a.name});return flushBackgroundTasks(e,o.backgroundTasks,t,a.name),Response.json({error:`Channel handler failed.`,errorId:i,ok:!1},{status:500})}return flushBackgroundTasks(e,o.backgroundTasks,t,a.name),c}async function dispatchChannelWebSocketRequest(e,t,r){let i=await resolveNitroChannelRuntimeBundle(r),a=i.channels.find(e=>`${e.method.toUpperCase()} ${e.urlPath}`===t);if(a===void 0||a.websocket===void 0)return rejectWebSocketUpgrade({error:`No matching websocket channel for this request.`,ok:!1},404);let o=a.websocket,c=buildRouteArgs(e,i,a.name,r);try{let n=await withDevelopmentVercelOidcContext(r,e.req,async()=>await o(e.req,c.args));return flushBackgroundTasks(e,c.backgroundTasks,t,a.name),n}catch(r){let i=logError(log,`channel websocket handler threw`,r,{routeKey:t,channel:a.name});return flushBackgroundTasks(e,c.backgroundTasks,t,a.name),rejectWebSocketUpgrade({error:`Channel websocket handler failed.`,errorId:i,ok:!1},500)}}async function withDevelopmentVercelOidcContext(e,t,n){let r=e.appRoot;return e.dev!==!0||r===void 0?await n():await withVercelOidcProjectResolver({request:t,resolveCurrentProject:async()=>{let e=await readVercelProjectLink(r);return e===void 0?void 0:{environment:`development`,projectId:e.projectId}}},n)}function buildRouteArgs(t,n,s,c){let l=readVercelRequestId(t.req.headers),u=extractSocketIp(t),d=[],f=t.context.params??{},p={};for(let[e,t]of Object.entries(f))p[e]=decodeURIComponent(t);let waitUntil=e=>{d.push(e)},m=n.channels.find(e=>e.name===s)?.adapter??{kind:`channel`};return{agent:createRouteAgent(n.runtime,l),args:attachAgentInfoRouteResponse({send:createSendFn(n.runtime,m,s,{requestId:l}),getSession:createGetSessionFn(n.runtime),receive:createCrossChannelReceiveFn(n.runtime,toCrossChannelTargets(n.channels)),params:p,waitUntil,requestIp:u},async()=>{let{handleAgentInfoRequest:e}=await import(`#internal/nitro/routes/info.js`);return await e(c)}),backgroundTasks:d}}function createRouteAgent(e,t){return{async deliver(n){let r={...n,requestId:t};return await e.deliver(r)},async getEventStream(t,n){return await e.getEventStream(t,n)},async run(n){let r={...n,requestId:t};return await e.run(r)}}}function readVercelRequestId(e){let t=e.get(`x-vercel-id`)?.trim();return t===``?void 0:t}function rejectWebSocketUpgrade(e,t){return{upgrade(){throw Response.json(e,{status:t})}}}function flushBackgroundTasks(e,t,r,i){t.length!==0&&e.waitUntil(Promise.allSettled(t).then(e=>{for(let t of e)t.status===`rejected`&&logError(log,`channel background task failed`,t.reason,{routeKey:r,channel:i})}))}function extractSocketIp(e){let t=e.req.ip;return typeof t==`string`&&t.length>0?t:null}export{dispatchChannelRequest,dispatchChannelWebSocketRequest};
1
+ import{createGetSessionFn}from"#channel/session.js";import{createLogger,logError}from"#internal/logging.js";import{createSendFn}from"#channel/send.js";import{createCrossChannelReceiveFn,toCrossChannelTargets}from"#channel/cross-channel-receive.js";import{attachAgentInfoRouteResponse}from"#internal/nitro/routes/channel-route-context.js";import{resolveNitroChannelRuntimeBundle}from"#internal/nitro/routes/runtime-stack.js";import{readVercelProjectLink}from"#internal/vercel/project-link.js";import{withVercelOidcProjectResolver}from"#runtime/governance/auth/vercel-oidc-project.js";const log=createLogger(`channel.dispatch`);async function dispatchChannelRequest(e,t,r){let i=await resolveNitroChannelRuntimeBundle(r),a=i.channels.find(e=>`${e.method.toUpperCase()} ${e.urlPath}`===t);if(a===void 0)return Response.json({error:`No matching channel for this request.`,ok:!1},{status:404});let o=buildRouteArgs(e,i,a.name,r),c;try{c=await withDevelopmentVercelOidcContext(r,e.req,async()=>{if(a.handler)return await a.handler(e.req,o.args);let t={agent:o.agent,waitUntil:o.args.waitUntil,params:o.args.params,requestIp:o.args.requestIp};return await a.fetch(e.req,t)})}catch(r){let i=logError(log,`channel handler threw`,r,{routeKey:t,channel:a.name});return flushBackgroundTasks(e,o.backgroundTasks,t,a.name),Response.json({error:`Channel handler failed.`,errorId:i,ok:!1},{status:500})}return flushBackgroundTasks(e,o.backgroundTasks,t,a.name),c}async function dispatchChannelWebSocketRequest(e,t,r){let i=await resolveNitroChannelRuntimeBundle(r),a=i.channels.find(e=>`${e.method.toUpperCase()} ${e.urlPath}`===t);if(a===void 0||a.websocket===void 0)return rejectWebSocketUpgrade({error:`No matching websocket channel for this request.`,ok:!1},404);let o=a.websocket,c=buildRouteArgs(e,i,a.name,r);try{let n=await withDevelopmentVercelOidcContext(r,e.req,async()=>await o(e.req,c.args));return flushBackgroundTasks(e,c.backgroundTasks,t,a.name),n}catch(r){let i=logError(log,`channel websocket handler threw`,r,{routeKey:t,channel:a.name});return flushBackgroundTasks(e,c.backgroundTasks,t,a.name),rejectWebSocketUpgrade({error:`Channel websocket handler failed.`,errorId:i,ok:!1},500)}}async function withDevelopmentVercelOidcContext(e,t,n){return e.kind===`development`?await withVercelOidcProjectResolver({request:t,resolveCurrentProject:async()=>{let t=await readVercelProjectLink(e.appRoot);return t===void 0?void 0:{environment:`development`,projectId:t.projectId}}},n):await n()}function buildRouteArgs(t,n,s,c){let l=readVercelRequestId(t.req.headers),u=extractSocketIp(t),d=[],f=t.context.params??{},p={};for(let[e,t]of Object.entries(f))p[e]=decodeURIComponent(t);let waitUntil=e=>{d.push(e)},m=n.channels.find(e=>e.name===s)?.adapter??{kind:`channel`};return{agent:createRouteAgent(n.runtime,l),args:attachAgentInfoRouteResponse({send:createSendFn(n.runtime,m,s,{requestId:l}),getSession:createGetSessionFn(n.runtime),receive:createCrossChannelReceiveFn(n.runtime,toCrossChannelTargets(n.channels)),params:p,waitUntil,requestIp:u},async()=>{let{handleAgentInfoRequest:e}=await import(`#internal/nitro/routes/info.js`);return await e(c)}),backgroundTasks:d}}function createRouteAgent(e,t){return{async deliver(n){let r={...n,requestId:t};return await e.deliver(r)},async getEventStream(t,n){return await e.getEventStream(t,n)},async run(n){let r={...n,requestId:t};return await e.run(r)}}}function readVercelRequestId(e){let t=e.get(`x-vercel-id`)?.trim();return t===``?void 0:t}function rejectWebSocketUpgrade(e,t){return{upgrade(){throw Response.json(e,{status:t})}}}function flushBackgroundTasks(e,t,r,i){t.length!==0&&e.waitUntil(Promise.allSettled(t).then(e=>{for(let t of e)t.status===`rejected`&&logError(log,`channel background task failed`,t.reason,{routeKey:r,channel:i})}))}function extractSocketIp(e){let t=e.req.ip;return typeof t==`string`&&t.length>0?t:null}export{dispatchChannelRequest,dispatchChannelWebSocketRequest};
@@ -1,4 +1,4 @@
1
- import type { NitroArtifactsConfigInput } from "#internal/nitro/host/artifacts-config.js";
1
+ import type { DevelopmentNitroArtifactsConfig } from "#internal/nitro/routes/runtime-artifacts.js";
2
2
  /**
3
3
  * Builds the dev-only dispatch response for one authored schedule.
4
4
  *
@@ -11,4 +11,4 @@ import type { NitroArtifactsConfigInput } from "#internal/nitro/host/artifacts-c
11
11
  *
12
12
  * Auth: none. The dev server is local-only and the route is dev-only.
13
13
  */
14
- export declare function handleDevScheduleDispatchRequest(input: NitroArtifactsConfigInput, request: Request): Promise<Response>;
14
+ export declare function handleDevScheduleDispatchRequest(input: DevelopmentNitroArtifactsConfig, request: Request): Promise<Response>;
@@ -1,10 +1,5 @@
1
1
  import type { NitroArtifactsConfig } from "#internal/nitro/routes/runtime-artifacts.js";
2
- type AgentInfoRouteMode = "development" | "production";
3
- export interface AgentInfoRouteInput extends NitroArtifactsConfig {
4
- readonly mode?: AgentInfoRouteMode;
5
- }
6
2
  /**
7
3
  * Builds the package-owned JSON inspection response for the current agent.
8
4
  */
9
- export declare function handleAgentInfoRequest(input: AgentInfoRouteInput): Promise<Response>;
10
- export {};
5
+ export declare function handleAgentInfoRequest(input: NitroArtifactsConfig): Promise<Response>;
@@ -1 +1 @@
1
- import{getVercelOidcToken}from"#compiled/@vercel/oidc/index.js";import{buildAgentInfoResponseFromManifest}from"#internal/nitro/routes/agent-info/build-agent-info-response-from-manifest.js";import{loadAgentInfoManifestData,resolveAgentInfoCompiledArtifactsSource}from"#internal/nitro/routes/agent-info/load-agent-info-data.js";async function createAgentInfoPayload(e){let r=await loadAgentInfoManifestData({compiledArtifactsSource:resolveAgentInfoCompiledArtifactsSource(e)});return buildAgentInfoResponseFromManifest(r,{mode:e.mode??(e.dev===!1?`production`:`development`),gatewayCredentials:await resolveGatewayCredentialPresence(r.manifest.config.model.routing)})}function hasEnvValue(e){return e!==void 0&&e.trim()!==``}async function resolveGatewayCredentialPresence(t){let n=hasEnvValue(process.env.AI_GATEWAY_API_KEY);if(t.kind===`external`||n)return{apiKey:n,oidc:!1};try{return await getVercelOidcToken(),{apiKey:!1,oidc:!0}}catch{return{apiKey:!1,oidc:!1}}}async function handleAgentInfoRequest(e){return new Response(JSON.stringify(await createAgentInfoPayload(e)),{headers:{"cache-control":`no-store`,"content-type":`application/json; charset=utf-8`}})}export{handleAgentInfoRequest};
1
+ import{getVercelOidcToken}from"#compiled/@vercel/oidc/index.js";import{buildAgentInfoResponseFromManifest}from"#internal/nitro/routes/agent-info/build-agent-info-response-from-manifest.js";import{loadAgentInfoManifestData,resolveAgentInfoCompiledArtifactsSource}from"#internal/nitro/routes/agent-info/load-agent-info-data.js";async function createAgentInfoPayload(e){let r=await loadAgentInfoManifestData({compiledArtifactsSource:resolveAgentInfoCompiledArtifactsSource(e)});return buildAgentInfoResponseFromManifest(r,{mode:e.kind,gatewayCredentials:await resolveGatewayCredentialPresence(r.manifest.config.model.routing)})}function hasEnvValue(e){return e!==void 0&&e.trim()!==``}async function resolveGatewayCredentialPresence(t){let n=hasEnvValue(process.env.AI_GATEWAY_API_KEY);if(t.kind===`external`||n)return{apiKey:n,oidc:!1};try{return await getVercelOidcToken(),{apiKey:!1,oidc:!0}}catch{return{apiKey:!1,oidc:!1}}}async function handleAgentInfoRequest(e){return new Response(JSON.stringify(await createAgentInfoPayload(e)),{headers:{"cache-control":`no-store`,"content-type":`application/json; charset=utf-8`}})}export{handleAgentInfoRequest};
@@ -4,12 +4,16 @@ import { type RuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts
4
4
  * package-owned Nitro routes. Passed explicitly from virtual handlers
5
5
  * rather than read from a global runtime configuration store.
6
6
  */
7
- export interface NitroArtifactsConfig {
8
- readonly appRoot?: string;
9
- readonly dev?: boolean;
10
- readonly devRuntimeArtifactsPointerPath?: string;
11
- readonly moduleMapLoaderPath?: string;
7
+ export interface DevelopmentNitroArtifactsConfig {
8
+ readonly appRoot: string;
9
+ readonly devRuntimeArtifactsPointerPath: string;
10
+ readonly kind: "development";
11
+ readonly moduleMapLoaderPath: string;
12
12
  }
13
+ export interface ProductionNitroArtifactsConfig {
14
+ readonly kind: "production";
15
+ }
16
+ export type NitroArtifactsConfig = DevelopmentNitroArtifactsConfig | ProductionNitroArtifactsConfig;
13
17
  /**
14
18
  * Resolves the compiled-artifact source available to package-owned Nitro
15
19
  * routes.
@@ -1 +1 @@
1
- import{createBundledRuntimeCompiledArtifactsSource,createDiskRuntimeCompiledArtifactsSource}from"#runtime/compiled-artifacts-source.js";import{readBundledCompiledArtifacts}from"#runtime/loaders/bundled-artifacts.js";import{readDevelopmentRuntimeArtifactsSnapshotRoot}from"#internal/nitro/dev-runtime-artifacts.js";function resolveNitroCompiledArtifactsSource(e){let{appRoot:t,dev:n}=e;if(n&&t!==void 0){if(e.moduleMapLoaderPath===void 0)throw Error(`eve Nitro development routes require "moduleMapLoaderPath" in the artifacts config.`);return createDiskRuntimeCompiledArtifactsSource(readDevelopmentRuntimeArtifactsSnapshotRoot(e.devRuntimeArtifactsPointerPath)??t,{moduleMapLoaderPath:e.moduleMapLoaderPath,sandboxAppRoot:t})}if(readBundledCompiledArtifacts()!==null)return createBundledRuntimeCompiledArtifactsSource();if(t!==void 0)return createDiskRuntimeCompiledArtifactsSource(t);throw Error(`eve Nitro route requires bundled artifacts or an eve Nitro runtime configuration app root.`)}export{resolveNitroCompiledArtifactsSource};
1
+ import{createBundledRuntimeCompiledArtifactsSource,createDiskRuntimeCompiledArtifactsSource}from"#runtime/compiled-artifacts-source.js";import{readBundledCompiledArtifacts}from"#runtime/loaders/bundled-artifacts.js";import{readDevelopmentRuntimeArtifactsSnapshotRoot}from"#internal/nitro/dev-runtime-artifacts.js";function resolveNitroCompiledArtifactsSource(e){if(e.kind===`development`)return createDiskRuntimeCompiledArtifactsSource(readDevelopmentRuntimeArtifactsSnapshotRoot(e.devRuntimeArtifactsPointerPath)??e.appRoot,{moduleMapLoaderPath:e.moduleMapLoaderPath,sandboxAppRoot:e.appRoot});if(readBundledCompiledArtifacts()!==null)return createBundledRuntimeCompiledArtifactsSource();throw Error(`eve Nitro production requires bundled artifacts.`)}export{resolveNitroCompiledArtifactsSource};
@@ -0,0 +1 @@
1
+ export declare function runQueuedWorkflowBuild(outputDirectory: string, build: () => Promise<void>): Promise<void>;
@@ -0,0 +1 @@
1
+ const activeBuilds=new Map;async function runQueuedWorkflowBuild(e,t){let n=(activeBuilds.get(e)??Promise.resolve()).then(t,t);activeBuilds.set(e,n);try{await n}finally{activeBuilds.get(e)===n&&activeBuilds.delete(e)}}export{runQueuedWorkflowBuild};
@@ -78,5 +78,4 @@ export declare function bundleFinalWorkflowOutput(input: {
78
78
  export declare function convertStepsManifest(steps: WorkflowManifest["steps"]): Record<string, unknown>;
79
79
  export declare function convertWorkflowsManifest(workflows: WorkflowManifest["workflows"]): Record<string, unknown>;
80
80
  export declare function convertClassesManifest(classes: WorkflowManifest["classes"]): Record<string, unknown>;
81
- export declare function atomicWriteFile(targetPath: string, contents: string | Buffer | Uint8Array): Promise<void>;
82
81
  export {};
@@ -1,4 +1,4 @@
1
- import{builtinModules}from"node:module";import{resolveWorkflowModulePath}from"#internal/application/package.js";import{existsSync}from"node:fs";import{dirname,join,relative,resolve}from"node:path";import{mkdir,readFile,readdir,rename,writeFile}from"node:fs/promises";import{buildWithNitroRolldown,getSingleRolldownChunk}from"#internal/bundler/nitro-rolldown.js";import{WORKFLOW_STEP_EXTERNAL_PACKAGES}from"#internal/workflow-bundle/vercel-workflow-output.js";import{applyWorkflowTransform,getImportPath}from"#internal/workflow-bundle/workflow-builders.js";const WORKFLOW_VIRTUAL_ENTRY_ID=`\0eve-workflow-entry`,PSEUDO_PACKAGES=new Set([`server-only`,`client-only`,`next/dist/compiled/server-only`,`next/dist/compiled/client-only`]),NODE_BUILTIN_MODULES=new Set([...builtinModules,...builtinModules.map(e=>`node:${e}`)]),WORKFLOW_INPUT_EXTENSIONS=new Set([`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`]),IGNORED_INPUT_DIRECTORIES=new Set([`node_modules`,`.git`,`.next`,`.nuxt`,`.output`,`.vercel`,`.workflow-data`,`.workflow-vitest`,`.well-known`,`.svelte-kit`,`.turbo`,`.cache`,`.yarn`,`.pnpm-store`]);async function collectWorkflowInputFiles(e){let t=[];async function visit(e){let n;try{n=await readdir(e,{withFileTypes:!0})}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}for(let r of n){if(r.isDirectory()){IGNORED_INPUT_DIRECTORIES.has(r.name)||await visit(join(e,r.name));continue}if(!r.isFile())continue;let n=r.name.match(/\.[^.]+$/)?.[0];n!==void 0&&WORKFLOW_INPUT_EXTENSIONS.has(n)&&t.push(join(e,r.name))}}return await visit(e),t}function createWorkflowImport(e,t){let{importPath:n,isPackage:r}=getImportPath(e,t);return r?`import ${JSON.stringify(n)};`:`import ${JSON.stringify(toRelativeImportSpecifier(t,e))};`}function createWorkflowVirtualEntryPlugin(e){return{name:`eve-workflow-virtual-entry`,resolveId(e){if(e===`\0eve-workflow-entry`)return{id:e}},load(t){if(t===`\0eve-workflow-entry`)return{code:e,moduleSideEffects:!0,moduleType:`js`}}}}function createWorkflowPseudoPackagePlugin(){return{name:`eve-workflow-pseudo-packages`,resolveId(e){if(PSEUDO_PACKAGES.has(e))return{id:`\0eve-workflow-pseudo-package:${e}`}},load(e){if(e.startsWith(`\0eve-workflow-pseudo-package:`))return{code:``,moduleType:`js`}}}}function createWorkflowRuntimeAliasPlugin(){return{name:`eve-workflow-runtime-aliases`,resolveId(e){if(!(e!==`workflow`&&!e.startsWith(`workflow/`)))return resolveWorkflowModulePath(e)}}}function createEvePackageImportsPlugin(e,t={}){return{name:`eve-package-imports`,resolveId(n){let r=n.match(/^#compiled\/(.+)$/)?.[1];if(r!==void 0)return t.workflowCondition===!0&&r===`@workflow/core/index.js`?resolveFirstExistingPath([join(e,`src`,`internal`,`workflow-bundle`,`workflow-core-shim.ts`),join(e,`dist`,`src`,`internal`,`workflow-bundle`,`workflow-core-shim.js`)]):resolveFirstExistingPath([join(e,`.generated`,`compiled`,r),join(e,`dist`,`src`,`compiled`,r)]);let a=n.match(/^#(.+)\.js$/)?.[1];if(a!==void 0)return resolveFirstExistingPath([`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`].flatMap(t=>[join(e,`src`,`${a}${t}`),join(e,`dist`,`src`,`${a}${t}`)]))}}}function createWorkflowTransformPlugin(e){let t=new Set(e.sideEffectFiles?.map(e=>e.replaceAll(`\\`,`/`))??[]);return{name:`eve-workflow-transform`,async load(n){if(!isJavaScriptLikePath(n))return;let r=await readFile(n,`utf8`),i=await applyWorkflowTransform(createManifestRelativeFilepath(e.workingDir,n),r.replace(/require\(\s*(['"])server-only\1\s*\)/g,`void 0`).replace(/require\(\s*(['"])client-only\1\s*\)/g,`void 0`),e.mode??`workflow`,n,e.projectRoot);return mergeWorkflowManifest(e.manifest,i.workflowManifest),{code:i.code,map:null,moduleSideEffects:t.has(n.replaceAll(`\\`,`/`))||void 0}}}}async function bundleWorkflowStepRegistrations(e){let t=[...e.discoveredEntries.discoveredSteps].sort(),n=new Set(t),r=[...e.discoveredEntries.discoveredSerdeFiles].sort().filter(e=>!n.has(e)),i={},a=[createWorkflowImport(e.builtinsPath,e.workingDir),...t.map(t=>createWorkflowImport(t,e.workingDir)),...r.map(t=>createWorkflowImport(t,e.workingDir)),`export const __steps_registered = true;`].join(`
1
+ import{builtinModules}from"node:module";import{resolveWorkflowModulePath}from"#internal/application/package.js";import{existsSync}from"node:fs";import{dirname,join,relative,resolve}from"node:path";import{mkdir,readFile,readdir}from"node:fs/promises";import{atomicWriteFile}from"#shared/atomic-write-file.js";import{buildWithNitroRolldown,getSingleRolldownChunk}from"#internal/bundler/nitro-rolldown.js";import{WORKFLOW_STEP_EXTERNAL_PACKAGES}from"#internal/workflow-bundle/vercel-workflow-output.js";import{applyWorkflowTransform,getImportPath}from"#internal/workflow-bundle/workflow-builders.js";const WORKFLOW_VIRTUAL_ENTRY_ID=`\0eve-workflow-entry`,PSEUDO_PACKAGES=new Set([`server-only`,`client-only`,`next/dist/compiled/server-only`,`next/dist/compiled/client-only`]),NODE_BUILTIN_MODULES=new Set([...builtinModules,...builtinModules.map(e=>`node:${e}`)]),WORKFLOW_INPUT_EXTENSIONS=new Set([`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`]),IGNORED_INPUT_DIRECTORIES=new Set([`node_modules`,`.git`,`.next`,`.nuxt`,`.output`,`.vercel`,`.workflow-data`,`.workflow-vitest`,`.well-known`,`.svelte-kit`,`.turbo`,`.cache`,`.yarn`,`.pnpm-store`]);async function collectWorkflowInputFiles(e){let t=[];async function visit(e){let n;try{n=await readdir(e,{withFileTypes:!0})}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}for(let r of n){if(r.isDirectory()){IGNORED_INPUT_DIRECTORIES.has(r.name)||await visit(join(e,r.name));continue}if(!r.isFile())continue;let n=r.name.match(/\.[^.]+$/)?.[0];n!==void 0&&WORKFLOW_INPUT_EXTENSIONS.has(n)&&t.push(join(e,r.name))}}return await visit(e),t}function createWorkflowImport(e,t){let{importPath:n,isPackage:r}=getImportPath(e,t);return r?`import ${JSON.stringify(n)};`:`import ${JSON.stringify(toRelativeImportSpecifier(t,e))};`}function createWorkflowVirtualEntryPlugin(e){return{name:`eve-workflow-virtual-entry`,resolveId(e){if(e===`\0eve-workflow-entry`)return{id:e}},load(t){if(t===`\0eve-workflow-entry`)return{code:e,moduleSideEffects:!0,moduleType:`js`}}}}function createWorkflowPseudoPackagePlugin(){return{name:`eve-workflow-pseudo-packages`,resolveId(e){if(PSEUDO_PACKAGES.has(e))return{id:`\0eve-workflow-pseudo-package:${e}`}},load(e){if(e.startsWith(`\0eve-workflow-pseudo-package:`))return{code:``,moduleType:`js`}}}}function createWorkflowRuntimeAliasPlugin(){return{name:`eve-workflow-runtime-aliases`,resolveId(e){if(!(e!==`workflow`&&!e.startsWith(`workflow/`)))return resolveWorkflowModulePath(e)}}}function createEvePackageImportsPlugin(e,t={}){return{name:`eve-package-imports`,resolveId(n){let r=n.match(/^#compiled\/(.+)$/)?.[1];if(r!==void 0)return t.workflowCondition===!0&&r===`@workflow/core/index.js`?resolveFirstExistingPath([join(e,`src`,`internal`,`workflow-bundle`,`workflow-core-shim.ts`),join(e,`dist`,`src`,`internal`,`workflow-bundle`,`workflow-core-shim.js`)]):resolveFirstExistingPath([join(e,`.generated`,`compiled`,r),join(e,`dist`,`src`,`compiled`,r)]);let a=n.match(/^#(.+)\.js$/)?.[1];if(a!==void 0)return resolveFirstExistingPath([`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`].flatMap(t=>[join(e,`src`,`${a}${t}`),join(e,`dist`,`src`,`${a}${t}`)]))}}}function createWorkflowTransformPlugin(e){let t=new Set(e.sideEffectFiles?.map(e=>e.replaceAll(`\\`,`/`))??[]);return{name:`eve-workflow-transform`,async load(n){if(!isJavaScriptLikePath(n))return;let r=await readFile(n,`utf8`),i=await applyWorkflowTransform(createManifestRelativeFilepath(e.workingDir,n),r.replace(/require\(\s*(['"])server-only\1\s*\)/g,`void 0`).replace(/require\(\s*(['"])client-only\1\s*\)/g,`void 0`),e.mode??`workflow`,n,e.projectRoot);return mergeWorkflowManifest(e.manifest,i.workflowManifest),{code:i.code,map:null,moduleSideEffects:t.has(n.replaceAll(`\\`,`/`))||void 0}}}}async function bundleWorkflowStepRegistrations(e){let t=[...e.discoveredEntries.discoveredSteps].sort(),n=new Set(t),r=[...e.discoveredEntries.discoveredSerdeFiles].sort().filter(e=>!n.has(e)),i={},a=[createWorkflowImport(e.builtinsPath,e.workingDir),...t.map(t=>createWorkflowImport(t,e.workingDir)),...r.map(t=>createWorkflowImport(t,e.workingDir)),`export const __steps_registered = true;`].join(`
2
2
  `),o=getSingleRolldownChunk(await buildWithNitroRolldown({cwd:e.workingDir,input:WORKFLOW_VIRTUAL_ENTRY_ID,external:isWorkflowStepExternalPackage,platform:`node`,plugins:[createWorkflowVirtualEntryPlugin(a),createWorkflowPseudoPackagePlugin(),createWorkflowRuntimeAliasPlugin(),createEvePackageImportsPlugin(e.workingDir),createWorkflowTransformPlugin({manifest:i,mode:`step`,projectRoot:e.projectRoot,sideEffectFiles:[...t,...r],workingDir:e.workingDir})],resolve:{conditionNames:[`eve-source`,`node`,`import`,`default`],extensions:[`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`],mainFields:[`module`,`main`]},tsconfig:e.tsconfigPath??!1,write:!1,output:{codeSplitting:!1,comments:!1,format:`esm`,sourcemap:`inline`}}),`step registrations bundle for "${e.outfile}"`);await writeWorkflowBundleAtomically(e.outfile,o.code)}function isWorkflowStepExternalPackage(e){return WORKFLOW_STEP_EXTERNAL_PACKAGES.some(t=>e===t||e.startsWith(`${t}/`))}function createWorkflowNodeBuiltinGuardPlugin(){return{name:`eve-workflow-node-builtins`,resolveId(e,t){let n=e.startsWith(`node:`)?e.slice(5):e;if(!NODE_BUILTIN_MODULES.has(e)&&!NODE_BUILTIN_MODULES.has(n))return;let r=t?` (imported by "${t}")`:``;throw Error(`Workflow bundle cannot import Node.js builtin "${e}"${r}. Move Node.js APIs behind a "use step" function, or keep the importing module out of the workflow driver body (only reachable through a "use step").`)}}}async function bundleFinalWorkflowOutput(e){let n=e.code.endsWith(`
3
3
  `)?e.code:`${e.code}\n`,r=resolveWorkflowModulePath(`workflow/runtime`).replaceAll(`\\`,`/`),i=`// biome-ignore-all lint: generated file
4
4
  /* eslint-disable */
@@ -6,4 +6,4 @@ import { workflowEntrypoint } from ${JSON.stringify(r)};
6
6
 
7
7
  const workflowCode = \`${n.replace(/[\\`$]/g,`\\$&`)}\`;
8
8
 
9
- export const POST = workflowEntrypoint(workflowCode, { namespace: ${JSON.stringify(e.queueNamespace)} });`;if(!e.bundleFinalOutput){await writeWorkflowBundleAtomically(e.outfile,i);return}let a=getSingleRolldownChunk(await buildWithNitroRolldown({cwd:e.workingDir,input:WORKFLOW_VIRTUAL_ENTRY_ID,external:e=>e===`@aws-sdk/credential-provider-web-identity`,platform:`node`,plugins:[createWorkflowVirtualEntryPlugin(i)],write:!1,output:{comments:!1,format:e.format,sourcemap:!1}}),`final workflow bundle for "${e.outfile}"`);await writeWorkflowBundleAtomically(e.outfile,a.code)}function convertStepsManifest(e){let t={};for(let[n,r]of Object.entries(e??{})){t[n]={};for(let[e,i]of Object.entries(r))t[n][e]={stepId:i.stepId}}return t}function convertWorkflowsManifest(e){let t={};for(let[n,r]of Object.entries(e??{})){t[n]={};for(let[e,i]of Object.entries(r))t[n][e]={graph:{edges:[],nodes:[]},workflowId:i.workflowId}}return t}function convertClassesManifest(e){let t={};for(let[n,r]of Object.entries(e??{})){t[n]={};for(let[e,i]of Object.entries(r))t[n][e]={classId:i.classId}}return t}function toRelativeImportSpecifier(e,t){let n=relative(e,t).replaceAll(`\\`,`/`);return n.startsWith(`./`)||n.startsWith(`../`)?n:`./${n}`}function resolveFirstExistingPath(e){for(let t of e)if(existsSync(t))return{id:resolve(t)}}async function writeWorkflowBundleAtomically(e,t){await mkdir(dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${Date.now()}.tmp`;await writeFile(n,t),await rename(n,e)}function mergeWorkflowManifest(e,t){e.steps=mergeWorkflowManifestSection(e.steps,t.steps),e.workflows=mergeWorkflowManifestSection(e.workflows,t.workflows),e.classes=mergeWorkflowManifestSection(e.classes,t.classes)}function mergeWorkflowManifestSection(e,t){if(t===void 0)return e;let n={...e};for(let[e,r]of Object.entries(t))n[e]={...n[e],...r};return n}function createManifestRelativeFilepath(e,t){let n=t.replaceAll(`\\`,`/`),r=relative(e.replaceAll(`\\`,`/`),n).replaceAll(`\\`,`/`);return r.startsWith(`../`)&&(r=r.split(`/`).filter(e=>e!==`..`).join(`/`)),r}function isJavaScriptLikePath(e){return/\.(?:[cm]?[jt]sx?)$/.test(e)}async function atomicWriteFile(e,t){let n=`${e}.tmp-${process.pid}-${Date.now().toString(36)}`;await writeFile(n,t),await rename(n,e)}export{WORKFLOW_VIRTUAL_ENTRY_ID,atomicWriteFile,bundleFinalWorkflowOutput,bundleWorkflowStepRegistrations,collectWorkflowInputFiles,convertClassesManifest,convertStepsManifest,convertWorkflowsManifest,createEvePackageImportsPlugin,createWorkflowImport,createWorkflowNodeBuiltinGuardPlugin,createWorkflowPseudoPackagePlugin,createWorkflowRuntimeAliasPlugin,createWorkflowTransformPlugin,createWorkflowVirtualEntryPlugin};
9
+ export const POST = workflowEntrypoint(workflowCode, { namespace: ${JSON.stringify(e.queueNamespace)} });`;if(!e.bundleFinalOutput){await writeWorkflowBundleAtomically(e.outfile,i);return}let a=getSingleRolldownChunk(await buildWithNitroRolldown({cwd:e.workingDir,input:WORKFLOW_VIRTUAL_ENTRY_ID,external:e=>e===`@aws-sdk/credential-provider-web-identity`,platform:`node`,plugins:[createWorkflowVirtualEntryPlugin(i)],write:!1,output:{comments:!1,format:e.format,sourcemap:!1}}),`final workflow bundle for "${e.outfile}"`);await writeWorkflowBundleAtomically(e.outfile,a.code)}function convertStepsManifest(e){let t={};for(let[n,r]of Object.entries(e??{})){t[n]={};for(let[e,i]of Object.entries(r))t[n][e]={stepId:i.stepId}}return t}function convertWorkflowsManifest(e){let t={};for(let[n,r]of Object.entries(e??{})){t[n]={};for(let[e,i]of Object.entries(r))t[n][e]={graph:{edges:[],nodes:[]},workflowId:i.workflowId}}return t}function convertClassesManifest(e){let t={};for(let[n,r]of Object.entries(e??{})){t[n]={};for(let[e,i]of Object.entries(r))t[n][e]={classId:i.classId}}return t}function toRelativeImportSpecifier(e,t){let n=relative(e,t).replaceAll(`\\`,`/`);return n.startsWith(`./`)||n.startsWith(`../`)?n:`./${n}`}function resolveFirstExistingPath(e){for(let t of e)if(existsSync(t))return{id:resolve(t)}}async function writeWorkflowBundleAtomically(e,t){await mkdir(dirname(e),{recursive:!0}),await atomicWriteFile(e,t)}function mergeWorkflowManifest(e,t){e.steps=mergeWorkflowManifestSection(e.steps,t.steps),e.workflows=mergeWorkflowManifestSection(e.workflows,t.workflows),e.classes=mergeWorkflowManifestSection(e.classes,t.classes)}function mergeWorkflowManifestSection(e,t){if(t===void 0)return e;let n={...e};for(let[e,r]of Object.entries(t))n[e]={...n[e],...r};return n}function createManifestRelativeFilepath(e,t){let n=t.replaceAll(`\\`,`/`),r=relative(e.replaceAll(`\\`,`/`),n).replaceAll(`\\`,`/`);return r.startsWith(`../`)&&(r=r.split(`/`).filter(e=>e!==`..`).join(`/`)),r}function isJavaScriptLikePath(e){return/\.(?:[cm]?[jt]sx?)$/.test(e)}export{WORKFLOW_VIRTUAL_ENTRY_ID,bundleFinalWorkflowOutput,bundleWorkflowStepRegistrations,collectWorkflowInputFiles,convertClassesManifest,convertStepsManifest,convertWorkflowsManifest,createEvePackageImportsPlugin,createWorkflowImport,createWorkflowNodeBuiltinGuardPlugin,createWorkflowPseudoPackagePlugin,createWorkflowRuntimeAliasPlugin,createWorkflowTransformPlugin,createWorkflowVirtualEntryPlugin};