eve 0.27.6 → 0.27.7

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 (64) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/dist/src/channel/session.d.ts +5 -0
  3. package/dist/src/channel/session.js +1 -1
  4. package/dist/src/channel/types.d.ts +7 -0
  5. package/dist/src/chunks/{use-eve-agent-COlXhAaF.js → use-eve-agent-JPfBHZJr.js} +36 -6
  6. package/dist/src/chunks/{use-eve-agent-DzVlKcUV.js → use-eve-agent-r5tkzjmt.js} +36 -6
  7. package/dist/src/client/open-stream.d.ts +17 -2
  8. package/dist/src/client/open-stream.js +1 -1
  9. package/dist/src/client/session.d.ts +5 -1
  10. package/dist/src/client/session.js +1 -1
  11. package/dist/src/client/types.d.ts +7 -0
  12. package/dist/src/execution/workflow-runtime.js +1 -1
  13. package/dist/src/harness/emission.js +1 -1
  14. package/dist/src/harness/input-requests.js +1 -1
  15. package/dist/src/harness/runtime-actions.d.ts +4 -0
  16. package/dist/src/harness/runtime-actions.js +1 -1
  17. package/dist/src/harness/tool-call-input-errors.d.ts +20 -0
  18. package/dist/src/harness/tool-call-input-errors.js +1 -1
  19. package/dist/src/internal/application/build-workspace.d.ts +0 -1
  20. package/dist/src/internal/application/build-workspace.js +1 -1
  21. package/dist/src/internal/application/package.js +1 -1
  22. package/dist/src/internal/application/paths.d.ts +1 -6
  23. package/dist/src/internal/application/paths.js +1 -1
  24. package/dist/src/internal/nitro/host/build-application.js +1 -1
  25. package/dist/src/internal/nitro/host/configure-nitro-routes.d.ts +4 -4
  26. package/dist/src/internal/nitro/host/configure-nitro-routes.js +2 -2
  27. package/dist/src/internal/nitro/host/create-application-nitro.d.ts +11 -7
  28. package/dist/src/internal/nitro/host/create-application-nitro.js +1 -1
  29. package/dist/src/internal/nitro/host/types.d.ts +0 -4
  30. package/dist/src/internal/nitro/host/vercel-build-output-config.d.ts +29 -1
  31. package/dist/src/internal/nitro/host/vercel-build-output-config.js +1 -1
  32. package/dist/src/internal/workflow/queue-namespace.d.ts +8 -0
  33. package/dist/src/internal/workflow/queue-namespace.js +1 -1
  34. package/dist/src/internal/workflow-bundle/builder-support.d.ts +0 -5
  35. package/dist/src/internal/workflow-bundle/builder.d.ts +0 -5
  36. package/dist/src/internal/workflow-bundle/builder.js +2 -2
  37. package/dist/src/internal/workflow-bundle/vercel-workflow-output.d.ts +0 -51
  38. package/dist/src/internal/workflow-bundle/vercel-workflow-output.js +1 -3
  39. package/dist/src/internal/workflow-bundle/workflow-builders.d.ts +0 -7
  40. package/dist/src/internal/workflow-bundle/workflow-builders.js +1 -1
  41. package/dist/src/packages/eve-catalog/src/index.js +1 -1
  42. package/dist/src/protocol/message.d.ts +1 -0
  43. package/dist/src/protocol/message.js +2 -2
  44. package/dist/src/public/channels/eve.js +2 -2
  45. package/dist/src/setup/scaffold/create/project.js +1 -1
  46. package/dist/src/svelte/index.js +1 -1
  47. package/dist/src/svelte/use-eve-agent.js +1 -1
  48. package/dist/src/vue/index.js +1 -1
  49. package/dist/src/vue/use-eve-agent.js +1 -1
  50. package/docs/README.md +21 -20
  51. package/docs/channels/custom.mdx +1 -1
  52. package/docs/channels/overview.mdx +2 -0
  53. package/docs/channels/slack.mdx +0 -1
  54. package/docs/concepts/{execution-model-and-durability.md → execution-model-and-durability.mdx} +16 -0
  55. package/docs/concepts/security-model.md +2 -0
  56. package/docs/concepts/sessions-runs-and-streaming.md +9 -0
  57. package/docs/getting-started.mdx +13 -196
  58. package/docs/guides/client/streaming.mdx +15 -0
  59. package/docs/installation.mdx +60 -0
  60. package/docs/meta.json +7 -6
  61. package/docs/project-structure.mdx +53 -0
  62. package/docs/tutorial/meta.json +1 -1
  63. package/package.json +1 -1
  64. package/docs/introduction.mdx +0 -103
@@ -1 +1 @@
1
- import{createRequire}from"node:module";import{existsSync,readFileSync,realpathSync}from"node:fs";import{basename,dirname,join}from"node:path";import{fileURLToPath}from"node:url";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";let cachedPackageInfo;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.27.6`,WORKFLOW_MODULE_ALIASES={"workflow/errors":`src/compiled/@workflow/errors/index.js`,"workflow/internal/private":`src/compiled/@workflow/core/private.js`};function resolveFallbackPackageVersion(){return BUNDLED_FALLBACK_PACKAGE_VERSION.startsWith(`__`)?`0.0.0`:BUNDLED_FALLBACK_PACKAGE_VERSION}const FALLBACK_PACKAGE_INFO={name:EVE_PACKAGE_NAME,version:resolveFallbackPackageVersion()};function resolveCurrentModulePath(){return typeof __filename==`string`?__filename:resolveCurrentModulePathFromStack()}function resolveCurrentModulePathFromStack(){let e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;let e=Error().stack?.[0]?.getFileName();if(typeof e!=`string`||e.length===0)throw Error(`Failed to resolve the current module path from the stack trace.`);return e.startsWith(`file:`)?fileURLToPath(e):e}finally{Error.prepareStackTrace=e}}const require=createRequire(resolveCurrentModulePath());function isBuildOutputPackageRoot(e){return basename(e)===`dist`&&existsSync(join(dirname(e),`package.json`))}function resolvePackageBuildRoot(){let e=dirname(realpathSync(resolveCurrentModulePath()));for(;;){if(isBuildOutputPackageRoot(e))return e;let t=dirname(e);if(t===e)return null;e=t}}function findNearestPackageRoot(e){let n=e;for(;;){if(existsSync(join(n,`package.json`))&&!isBuildOutputPackageRoot(n))return n;let r=dirname(n);if(r===n)throw Error(`Failed to resolve package root from "${e}".`);n=r}}function resolvePackageRoot(){return findNearestPackageRoot(dirname(realpathSync(resolveCurrentModulePath())))}function tryResolvePackageRoot(){try{return resolvePackageRoot()}catch{return}}function rewriteSourceFilePathForBuild(e){return e.replace(/\.[cm]?tsx?$/,`.js`)}function resolvePackageSourceFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),e):join(t,rewriteSourceFilePathForBuild(e))}function resolvePackageSourceDirectoryPath(e){let t=resolvePackageBuildRoot();return join(t===null?resolvePackageRoot():t,e)}function resolvePackageDependencyPath(e){return require.resolve(e)}function resolvePackageCompiledFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),`.generated`,`compiled`,e.replace(/^src\/compiled\//,``)):join(t,e)}function normalizeInstalledPackageInfo(e){let t=e;if(!(typeof t.name!=`string`||typeof t.version!=`string`))return{name:t.name,version:t.version}}function tryReadInstalledPackageInfo(e,t){let r=normalizeInstalledPackageInfo(JSON.parse(readFileSync(e,`utf8`)));if(r?.name===t)return r}function resolveInstalledPackageInfo(){if(cachedPackageInfo)return cachedPackageInfo;let e=tryResolvePackageRoot(),t=e===void 0?void 0:tryReadInstalledPackageInfo(join(e,`package.json`),EVE_PACKAGE_NAME);if(t)return cachedPackageInfo=t,cachedPackageInfo;try{let e=tryReadInstalledPackageInfo(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),EVE_PACKAGE_NAME);if(e)return cachedPackageInfo=e,cachedPackageInfo}catch{}return cachedPackageInfo={...FALLBACK_PACKAGE_INFO},cachedPackageInfo}function readWorkflowVersionFromManifest(e){let t=e;for(let e of[t.devDependencies,t.dependencies,t.peerDependencies]){let t=e?.[`@workflow/core`];if(typeof t==`string`&&t.trim().length>0)return t}}function resolveExpectedWorkflowVersion(){let e=tryResolvePackageRoot();if(e!==void 0)try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(join(e,`package.json`),`utf8`)))}catch{}try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),`utf8`)))}catch{return}}function resolveWorkflowModulePath(e){if(e===`workflow`)return resolvePackageSourceFilePath(`src/internal/workflow/index.ts`);if(e===`workflow/api`||e===`workflow/runtime`)return resolvePackageSourceFilePath(`src/internal/workflow/runtime.ts`);if(e===`workflow/internal/builtins`)return resolvePackageSourceFilePath(`src/internal/workflow/builtins.ts`);let t=WORKFLOW_MODULE_ALIASES[e];return t===void 0?require.resolve(e):resolvePackageCompiledFilePath(t)}export{resolveExpectedWorkflowVersion,resolveInstalledPackageInfo,resolvePackageCompiledFilePath,resolvePackageDependencyPath,resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath};
1
+ import{createRequire}from"node:module";import{existsSync,readFileSync,realpathSync}from"node:fs";import{basename,dirname,join}from"node:path";import{fileURLToPath}from"node:url";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";let cachedPackageInfo;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.27.7`,WORKFLOW_MODULE_ALIASES={"workflow/errors":`src/compiled/@workflow/errors/index.js`,"workflow/internal/private":`src/compiled/@workflow/core/private.js`};function resolveFallbackPackageVersion(){return BUNDLED_FALLBACK_PACKAGE_VERSION.startsWith(`__`)?`0.0.0`:BUNDLED_FALLBACK_PACKAGE_VERSION}const FALLBACK_PACKAGE_INFO={name:EVE_PACKAGE_NAME,version:resolveFallbackPackageVersion()};function resolveCurrentModulePath(){return typeof __filename==`string`?__filename:resolveCurrentModulePathFromStack()}function resolveCurrentModulePathFromStack(){let e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;let e=Error().stack?.[0]?.getFileName();if(typeof e!=`string`||e.length===0)throw Error(`Failed to resolve the current module path from the stack trace.`);return e.startsWith(`file:`)?fileURLToPath(e):e}finally{Error.prepareStackTrace=e}}const require=createRequire(resolveCurrentModulePath());function isBuildOutputPackageRoot(e){return basename(e)===`dist`&&existsSync(join(dirname(e),`package.json`))}function resolvePackageBuildRoot(){let e=dirname(realpathSync(resolveCurrentModulePath()));for(;;){if(isBuildOutputPackageRoot(e))return e;let t=dirname(e);if(t===e)return null;e=t}}function findNearestPackageRoot(e){let n=e;for(;;){if(existsSync(join(n,`package.json`))&&!isBuildOutputPackageRoot(n))return n;let r=dirname(n);if(r===n)throw Error(`Failed to resolve package root from "${e}".`);n=r}}function resolvePackageRoot(){return findNearestPackageRoot(dirname(realpathSync(resolveCurrentModulePath())))}function tryResolvePackageRoot(){try{return resolvePackageRoot()}catch{return}}function rewriteSourceFilePathForBuild(e){return e.replace(/\.[cm]?tsx?$/,`.js`)}function resolvePackageSourceFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),e):join(t,rewriteSourceFilePathForBuild(e))}function resolvePackageSourceDirectoryPath(e){let t=resolvePackageBuildRoot();return join(t===null?resolvePackageRoot():t,e)}function resolvePackageDependencyPath(e){return require.resolve(e)}function resolvePackageCompiledFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),`.generated`,`compiled`,e.replace(/^src\/compiled\//,``)):join(t,e)}function normalizeInstalledPackageInfo(e){let t=e;if(!(typeof t.name!=`string`||typeof t.version!=`string`))return{name:t.name,version:t.version}}function tryReadInstalledPackageInfo(e,t){let r=normalizeInstalledPackageInfo(JSON.parse(readFileSync(e,`utf8`)));if(r?.name===t)return r}function resolveInstalledPackageInfo(){if(cachedPackageInfo)return cachedPackageInfo;let e=tryResolvePackageRoot(),t=e===void 0?void 0:tryReadInstalledPackageInfo(join(e,`package.json`),EVE_PACKAGE_NAME);if(t)return cachedPackageInfo=t,cachedPackageInfo;try{let e=tryReadInstalledPackageInfo(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),EVE_PACKAGE_NAME);if(e)return cachedPackageInfo=e,cachedPackageInfo}catch{}return cachedPackageInfo={...FALLBACK_PACKAGE_INFO},cachedPackageInfo}function readWorkflowVersionFromManifest(e){let t=e;for(let e of[t.devDependencies,t.dependencies,t.peerDependencies]){let t=e?.[`@workflow/core`];if(typeof t==`string`&&t.trim().length>0)return t}}function resolveExpectedWorkflowVersion(){let e=tryResolvePackageRoot();if(e!==void 0)try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(join(e,`package.json`),`utf8`)))}catch{}try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),`utf8`)))}catch{return}}function resolveWorkflowModulePath(e){if(e===`workflow`)return resolvePackageSourceFilePath(`src/internal/workflow/index.ts`);if(e===`workflow/api`||e===`workflow/runtime`)return resolvePackageSourceFilePath(`src/internal/workflow/runtime.ts`);if(e===`workflow/internal/builtins`)return resolvePackageSourceFilePath(`src/internal/workflow/builtins.ts`);let t=WORKFLOW_MODULE_ALIASES[e];return t===void 0?require.resolve(e):resolvePackageCompiledFilePath(t)}export{resolveExpectedWorkflowVersion,resolveInstalledPackageInfo,resolvePackageCompiledFilePath,resolvePackageDependencyPath,resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath};
@@ -1,4 +1,3 @@
1
- import type { NitroBuildSurface } from "#internal/nitro/host/types.js";
2
1
  export declare const EVE_INTERNAL_BUILD_OUTPUT_DIRECTORY_ENV = "EVE_INTERNAL_BUILD_OUTPUT_DIRECTORY";
3
2
  export declare const EVE_INTERNAL_HOST_BUILD_OUTPUT_DIRECTORY_ENV = "EVE_INTERNAL_HOST_BUILD_OUTPUT_DIRECTORY";
4
3
  export interface ApplicationInfo {
@@ -21,12 +20,8 @@ export declare function isVercelBuildEnvironment(): boolean;
21
20
  /**
22
21
  * Resolves the programmatic Nitro build directory for an app.
23
22
  */
24
- export declare function resolveNitroBuildDirectory(appRoot: string, surface?: NitroBuildSurface): string;
23
+ export declare function resolveNitroBuildDirectory(appRoot: string): string;
25
24
  export declare function resolveApplicationHostArtifactsDirectory(appRoot: string): string;
26
- /**
27
- * Resolves the staged Nitro output directory for one isolated build surface.
28
- */
29
- export declare function resolveNitroSurfaceOutputDirectory(appRoot: string, surface: Exclude<NitroBuildSurface, "all">): string;
30
25
  /**
31
26
  * Resolves the package-owned Workflow DevKit bundle directory for a target app.
32
27
  *
@@ -1 +1 @@
1
- import{resolveInstalledPackageInfo,resolvePackageRoot,resolvePackageSourceDirectoryPath}from"#internal/application/package.js";import{existsSync,readFileSync,readdirSync,rmSync}from"node:fs";import{join,resolve}from"node:path";import{createHash}from"node:crypto";import{workflowEntryReference}from"#execution/workflow-runtime.js";const EVE_INTERNAL_BUILD_OUTPUT_DIRECTORY_ENV=`EVE_INTERNAL_BUILD_OUTPUT_DIRECTORY`,EVE_INTERNAL_HOST_BUILD_OUTPUT_DIRECTORY_ENV=`EVE_INTERNAL_HOST_BUILD_OUTPUT_DIRECTORY`;function resolveApplicationRoot(e=process.cwd()){return resolve(e)}function getWorkflowBuildCacheKey(e){return createHash(`sha256`).update(e).digest(`hex`).slice(0,12)}function isVercelBuildEnvironment(){return!!process.env.VERCEL}function resolveNitroBuildDirectory(e,t=`all`){let n=join(e,`.eve`,`nitro`);return t===`all`?n:join(n,t)}function resolveApplicationHostArtifactsDirectory(e){return join(e,`.eve`,`host`)}function resolveNitroSurfaceOutputDirectory(e,t){return join(e,`.eve`,`nitro-output`,t)}function resolveWorkflowBuildDirectory(e){let n=join(resolvePackageRoot(),`.eve`,`workflow-cache`);return pruneStaleWorkflowCacheSiblings(n),join(n,getWorkflowBuildCacheKey(e))}function pruneStaleWorkflowCacheSiblings(t){if(!existsSync(t))return;let n=resolveInstalledPackageInfo().version,i;try{i=readdirSync(t)}catch{return}for(let e of i){let r=join(t,e),i=join(r,`eve-cache.json`);if(existsSync(i))try{let e=JSON.parse(readFileSync(i,`utf8`));typeof e.eveVersion==`string`&&e.eveVersion!==n&&rmSync(r,{force:!0,recursive:!0})}catch{}}}function resolveSandboxCacheDirectory(e){return join(e,`.eve`,`sandbox-cache`)}function resolveOutputDirectory(e){return isVercelBuildEnvironment()?join(e,`.vercel`,`output`):join(e,`.output`)}function getApplicationInfo(e){return{appRoot:e,outputDir:resolveOutputDirectory(e),workflowId:workflowEntryReference.workflowId,workflowBuildDir:resolveWorkflowBuildDirectory(e),workflowSourceDir:resolvePackageSourceDirectoryPath(`src/execution`)}}export{EVE_INTERNAL_BUILD_OUTPUT_DIRECTORY_ENV,EVE_INTERNAL_HOST_BUILD_OUTPUT_DIRECTORY_ENV,getApplicationInfo,isVercelBuildEnvironment,resolveApplicationHostArtifactsDirectory,resolveApplicationRoot,resolveNitroBuildDirectory,resolveNitroSurfaceOutputDirectory,resolveOutputDirectory,resolveSandboxCacheDirectory,resolveWorkflowBuildDirectory};
1
+ import{resolveInstalledPackageInfo,resolvePackageRoot,resolvePackageSourceDirectoryPath}from"#internal/application/package.js";import{existsSync,readFileSync,readdirSync,rmSync}from"node:fs";import{join,resolve}from"node:path";import{createHash}from"node:crypto";import{workflowEntryReference}from"#execution/workflow-runtime.js";const EVE_INTERNAL_BUILD_OUTPUT_DIRECTORY_ENV=`EVE_INTERNAL_BUILD_OUTPUT_DIRECTORY`,EVE_INTERNAL_HOST_BUILD_OUTPUT_DIRECTORY_ENV=`EVE_INTERNAL_HOST_BUILD_OUTPUT_DIRECTORY`;function resolveApplicationRoot(e=process.cwd()){return resolve(e)}function getWorkflowBuildCacheKey(e){return createHash(`sha256`).update(e).digest(`hex`).slice(0,12)}function isVercelBuildEnvironment(){return!!process.env.VERCEL}function resolveNitroBuildDirectory(e){return join(e,`.eve`,`nitro`)}function resolveApplicationHostArtifactsDirectory(e){return join(e,`.eve`,`host`)}function resolveWorkflowBuildDirectory(e){let n=join(resolvePackageRoot(),`.eve`,`workflow-cache`);return pruneStaleWorkflowCacheSiblings(n),join(n,getWorkflowBuildCacheKey(e))}function pruneStaleWorkflowCacheSiblings(t){if(!existsSync(t))return;let n=resolveInstalledPackageInfo().version,i;try{i=readdirSync(t)}catch{return}for(let e of i){let r=join(t,e),i=join(r,`eve-cache.json`);if(existsSync(i))try{let e=JSON.parse(readFileSync(i,`utf8`));typeof e.eveVersion==`string`&&e.eveVersion!==n&&rmSync(r,{force:!0,recursive:!0})}catch{}}}function resolveSandboxCacheDirectory(e){return join(e,`.eve`,`sandbox-cache`)}function resolveOutputDirectory(e){return isVercelBuildEnvironment()?join(e,`.vercel`,`output`):join(e,`.output`)}function getApplicationInfo(e){return{appRoot:e,outputDir:resolveOutputDirectory(e),workflowId:workflowEntryReference.workflowId,workflowBuildDir:resolveWorkflowBuildDirectory(e),workflowSourceDir:resolvePackageSourceDirectoryPath(`src/execution`)}}export{EVE_INTERNAL_BUILD_OUTPUT_DIRECTORY_ENV,EVE_INTERNAL_HOST_BUILD_OUTPUT_DIRECTORY_ENV,getApplicationInfo,isVercelBuildEnvironment,resolveApplicationHostArtifactsDirectory,resolveApplicationRoot,resolveNitroBuildDirectory,resolveOutputDirectory,resolveSandboxCacheDirectory,resolveWorkflowBuildDirectory};
@@ -1 +1 @@
1
- import{resolvePackageRoot,resolvePackageSourceFilePath}from"#internal/application/package.js";import{dirname,isAbsolute,join,relative,resolve,sep}from"node:path";import{tryReadExtensionBuildConfig}from"#internal/nitro/host/build-extension.js";import{readFile}from"node:fs/promises";import{toErrorMessage}from"#shared/errors.js";import{resolveDiscoveryProject}from"#discover/project.js";import{createDiskRuntimeCompiledArtifactsSource}from"#runtime/compiled-artifacts-source.js";import{build,copyPublicAssets,prepare,prerender}from"nitro/builder";import{prepareEveVersionedCacheDirectory,writeEveVersionedCacheMetadata}from"#internal/application/cache-metadata.js";import{createApplicationBuildWorkspace,removeApplicationBuildWorkspace}from"#internal/application/build-workspace.js";import{ApplicationBuildProfiler,createApplicationBuildProfile,measureApplicationBuildOutput,writeApplicationBuildProfile}from"#internal/application/build-profile.js";import{RecoverablePublicationError,publishApplicationBuildArtifacts}from"#internal/application/output-publication.js";import{stageProductionCompilerArtifacts}from"#internal/application/production-compiler-artifacts.js";import{WorkflowBundleBuilder}from"#internal/workflow-bundle/builder.js";import{normalizeEveVercelFunctionOutput}from"#internal/workflow-bundle/vercel-workflow-output.js";import{createProductionApplicationNitro}from"#internal/nitro/host/create-application-nitro.js";import{emitVercelAgentSummary}from"#internal/nitro/host/build-vercel-agent-summary.js";import{copyHostMiddlewareFunctions}from"#internal/nitro/host/copy-host-middleware.js";import{prepareProductionApplicationHost}from"#internal/nitro/host/prepare-application-host.js";import{runVercelBuildPrewarm}from"#internal/nitro/host/vercel-build-prewarm.js";import{findClosestVercelOutputDirectory}from"#shared/vercel-output-directory.js";function trimTrailingSlash(e){return e.replace(/[\\/]+$/,``)}async function measureBuildPhase(e,t,n){return e===void 0?n():e.measure(t,n)}function isPathInside(e,t){let n=relative(e,t);return n.length===0||!n.startsWith(`..${sep}`)&&n!==`..`&&!isAbsolute(n)}function assertProfileOutputOutsideBuildOutput(e,t){if(e!==void 0&&isPathInside(t,e))throw Error(`Build profile path ${e} must be outside the published output directory ${t}.`)}async function writeOptionalApplicationBuildProfile(e){try{assertProfileOutputOutsideBuildOutput(e.profileOutputPath,e.outputDirectory);let t=e.profiler.finish(),n=await measureApplicationBuildOutput(e.outputDirectory);await writeApplicationBuildProfile(e.profileOutputPath,createApplicationBuildProfile({output:n,target:process.env.VERCEL?`vercel`:`local`,timing:t}))}catch(t){console.warn(`eve: failed to write optional build profile to ${e.profileOutputPath}; continuing with the published build output: ${toErrorMessage(t)}`)}}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function normalizeEntrypoint(e,t){return typeof t!=`string`||t.trim().length===0?null:resolve(e,t)}function normalizeServiceRoot(e,t){return typeof t.root==`string`&&t.root.trim().length>0?resolve(e,t.root):normalizeEntrypoint(e,t.entrypoint)}function normalizeServicePrefix(e){return typeof e.routePrefix==`string`?e.routePrefix.trim():typeof e.mount==`string`?e.mount.trim():isRecord(e.mount)&&typeof e.mount.path==`string`&&e.mount.path.trim().length>0?e.mount.path.trim():``}function normalizeServiceCollection(e){if(isRecord(e))return Object.values(e).filter(isRecord);if(Array.isArray(e))return e.filter(isRecord)}function resolveCoDeployedEveServicePrefix(e){if(!isRecord(e.config))return;let t=normalizeServiceCollection(e.config.experimentalServices)??normalizeServiceCollection(e.config.experimentalServicesV2)??normalizeServiceCollection(e.config.services);if(t===void 0)return;let n=!1,r;for(let i of t){if(i.framework!==`eve`){n=!0;continue}let t=normalizeServiceRoot(e.configRoot,i),a=normalizeServicePrefix(i);t!==null&&e.appRoots.includes(t)&&a.length>0&&a!==`/`&&(r=a)}return n?r:void 0}async function resolveCoDeployedEveServicePrefixForVercelFunctionOutput(e,t){let r=Array.from(new Set([resolve(e),resolve(t)])),a=await findClosestVercelOutputDirectory(e);if(a!==void 0)try{let e=JSON.parse(await readFile(join(a,`config.json`),`utf8`)),t=resolveCoDeployedEveServicePrefix({appRoots:r,configRoot:await resolveVercelOutputConfigRoot(a),config:e});if(t!==void 0)return t}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}let s=e;for(;;){for(let e of[join(s,`vercel.json`),join(s,`.vercel`,`output`,`config.json`)])try{let t=JSON.parse(await readFile(e,`utf8`)),i=resolveCoDeployedEveServicePrefix({appRoots:r,configRoot:e.endsWith(`vercel.json`)?s:await resolveVercelOutputConfigRoot(dirname(e)),config:t});if(i!==void 0)return i}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}let e=dirname(s);if(e===s)return;s=e}}async function readVercelServerRuntime(e){try{return JSON.parse(await readFile(join(e,`functions`,`__server.func`,`.vc-config.json`),`utf8`)).runtime}catch{return}}async function resolveVercelOutputConfigRoot(e){let t=dirname(dirname(e));try{let e=JSON.parse(await readFile(join(t,`.vercel`,`project.json`),`utf8`));if(isRecord(e)&&isRecord(e.settings)&&typeof e.settings.rootDirectory==`string`&&e.settings.rootDirectory.trim().length>0)return resolve(t,e.settings.rootDirectory)}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}return t}async function emitVercelWorkflowFunctions(t){let n=new WorkflowBundleBuilder({agentName:t.agentName,appRoot:t.appRoot,compiledArtifactsBootstrapPath:t.compiledArtifactsBootstrapPath,outDir:t.workflowBuildDir,publicRoutePrefix:t.publicRoutePrefix,rootDir:resolvePackageRoot(),watch:!1}),r=await readVercelServerRuntime(t.outputDir);await n.buildVercelOutput({flowNitroOutputDir:t.flowNitroOutputDir,outputDir:t.outputDir,runtime:r})}async function buildNitroOutput(e,t,n){let r=trimTrailingSlash(e.options.output.dir);return await measureBuildPhase(t,`${n}.cache.prepare`,()=>prepareEveVersionedCacheDirectory(r)),await measureBuildPhase(t,`${n}.prepare`,()=>prepare(e)),await measureBuildPhase(t,`${n}.public-assets`,()=>copyPublicAssets(e)),await measureBuildPhase(t,`${n}.prerender`,()=>prerender(e)),await measureBuildPhase(t,`${n}.bundle`,()=>build(e)),await measureBuildPhase(t,`${n}.cache.write`,()=>writeEveVersionedCacheMetadata(r)),r}async function buildVercelNitroSurface(e,t,n,r){let a=`nitro.${n}`,o=await measureBuildPhase(r,`${a}.create`,()=>createProductionApplicationNitro(e,{buildDir:join(t.nitro.buildDir,n),outputDir:join(t.nitro.surfaceOutputDir,n),surface:n}));try{return await buildNitroOutput(o,r,a)}finally{await measureBuildPhase(r,`${a}.close`,()=>o.close())}}async function buildApplication(e,t){let n=t.profileOutputPath===void 0?void 0:resolve(t.profileOutputPath),r=n===void 0?void 0:new ApplicationBuildProfiler,i=await measureBuildPhase(r,`extension.check`,()=>tryReadExtensionBuildConfig(e));if(i!==null)throw Error(`Package "${i.packageName}" is an eve extension. Run \`eve extension build\` instead of \`eve build\`.`);let a=await measureBuildPhase(r,`project.resolve`,()=>resolveDiscoveryProject(e)),s=await measureBuildPhase(r,`workspace.create`,()=>createApplicationBuildWorkspace(a.appRoot,t.vercelServiceOutput?.serviceOutputDirectory)),l=!1,u;try{u=await buildApplicationInWorkspace(s,t,r)}catch(e){throw l=e instanceof RecoverablePublicationError,e}finally{l||await measureBuildPhase(r,`workspace.remove`,()=>removeApplicationBuildWorkspace(s))}return r!==void 0&&n!==void 0&&await writeOptionalApplicationBuildProfile({outputDirectory:u,profileOutputPath:n,profiler:r}),u}async function buildApplicationInWorkspace(e,n,r){let a=await measureBuildPhase(r,`host.prepare`,()=>prepareProductionApplicationHost(e));if(!process.env.VERCEL){let t=await measureBuildPhase(r,`nitro.all.create`,()=>createProductionApplicationNitro(a,{buildDir:e.nitro.buildDir,outputDir:e.publication.output.stagedDir,surface:`all`}));try{await buildNitroOutput(t,r,`nitro.all`),await measureBuildPhase(r,`agent-summary.emit`,()=>emitVercelAgentSummary({manifest:a.compileResult.manifest,outputPath:e.publication.summary.stagedPath})),await measureBuildPhase(r,`compiler-artifacts.stage`,()=>stageProductionCompilerArtifacts({compilerArtifactsRoot:e.compiler.artifactsDir,outputDir:e.publication.output.stagedDir}))}finally{await measureBuildPhase(r,`nitro.all.close`,()=>t.close())}return await measureBuildPhase(r,`output.publish`,()=>publishCompletedApplicationBuild(e)),e.publication.output.finalDir}let o=await measureBuildPhase(r,`vercel.service-prefix.resolve`,()=>resolveCoDeployedEveServicePrefixForVercelFunctionOutput(a.appRoot,a.compileResult.project.agentRoot)),s=await measureBuildPhase(r,`nitro.app.create`,()=>createProductionApplicationNitro(a,{buildDir:join(e.nitro.buildDir,`app`),outputDir:e.publication.output.stagedDir,surface:`app`}));try{await buildNitroOutput(s,r,`nitro.app`),n.skipVercelSandboxPrewarm||await measureBuildPhase(r,`sandbox.prewarm`,()=>runVercelBuildPrewarm({appRoot:a.appRoot,compiledArtifactsSource:createDiskRuntimeCompiledArtifactsSource(e.compiler.rootDir,{moduleMapLoaderPath:resolvePackageSourceFilePath(`src/internal/authored-module-map-loader.ts`),sandboxAppRoot:a.appRoot}),log(e){console.log(e)}}));let i=await buildVercelNitroSurface(a,e,`flow`,r);await measureBuildPhase(r,`workflow.emit`,()=>emitVercelWorkflowFunctions({agentName:a.compileResult.manifest.config.name,appRoot:a.appRoot,compiledArtifactsBootstrapPath:a.compiledArtifacts.bootstrapPath,flowNitroOutputDir:i,outputDir:e.publication.output.stagedDir,publicRoutePrefix:n.publicRoutePrefix,workflowBuildDir:e.workflow.buildDir})),o!==void 0&&await measureBuildPhase(r,`vercel.functions.normalize`,()=>normalizeEveVercelFunctionOutput(e.publication.output.stagedDir,{servicePrefix:o}));let c=n.vercelServiceOutput;c!==void 0&&await measureBuildPhase(r,`vercel.host-middleware.copy`,()=>copyHostMiddlewareFunctions({hostOutputDirectory:c.hostOutputDirectory,serviceOutputDirectory:e.publication.output.stagedDir})),await measureBuildPhase(r,`agent-summary.emit`,()=>emitVercelAgentSummary({manifest:a.compileResult.manifest,outputPath:e.publication.summary.stagedPath}))}finally{await measureBuildPhase(r,`nitro.app.close`,()=>s.close())}return await measureBuildPhase(r,`output.publish`,()=>publishCompletedApplicationBuild(e)),e.publication.output.finalDir}async function publishCompletedApplicationBuild(e){await publishApplicationBuildArtifacts({appRoot:e.appRoot,finalOutputDir:e.publication.output.finalDir,finalSummaryPath:e.publication.summary.finalPath,scratchDir:e.rootDir,stagedOutputDir:e.publication.output.stagedDir,stagedSummaryPath:e.publication.summary.stagedPath})}export{buildApplication};
1
+ import{resolvePackageSourceFilePath}from"#internal/application/package.js";import{dirname,isAbsolute,join,relative,resolve,sep}from"node:path";import{tryReadExtensionBuildConfig}from"#internal/nitro/host/build-extension.js";import{readFile}from"node:fs/promises";import{toErrorMessage}from"#shared/errors.js";import{resolveDiscoveryProject}from"#discover/project.js";import{createDiskRuntimeCompiledArtifactsSource}from"#runtime/compiled-artifacts-source.js";import{build,copyPublicAssets,prepare,prerender}from"nitro/builder";import{prepareEveVersionedCacheDirectory,writeEveVersionedCacheMetadata}from"#internal/application/cache-metadata.js";import{createApplicationBuildWorkspace,removeApplicationBuildWorkspace}from"#internal/application/build-workspace.js";import{ApplicationBuildProfiler,createApplicationBuildProfile,measureApplicationBuildOutput,writeApplicationBuildProfile}from"#internal/application/build-profile.js";import{RecoverablePublicationError,publishApplicationBuildArtifacts}from"#internal/application/output-publication.js";import{stageProductionCompilerArtifacts}from"#internal/application/production-compiler-artifacts.js";import{normalizeEveVercelFunctionOutput}from"#internal/workflow-bundle/vercel-workflow-output.js";import{createProductionApplicationNitro}from"#internal/nitro/host/create-application-nitro.js";import{emitVercelAgentSummary}from"#internal/nitro/host/build-vercel-agent-summary.js";import{copyHostMiddlewareFunctions}from"#internal/nitro/host/copy-host-middleware.js";import{prepareProductionApplicationHost}from"#internal/nitro/host/prepare-application-host.js";import{runVercelBuildPrewarm}from"#internal/nitro/host/vercel-build-prewarm.js";import{findClosestVercelOutputDirectory}from"#shared/vercel-output-directory.js";function trimTrailingSlash(e){return e.replace(/[\\/]+$/,``)}async function measureBuildPhase(e,t,n){return e===void 0?n():e.measure(t,n)}function isPathInside(e,t){let r=relative(e,t);return r.length===0||!r.startsWith(`..${sep}`)&&r!==`..`&&!isAbsolute(r)}function assertProfileOutputOutsideBuildOutput(e,t){if(e!==void 0&&isPathInside(t,e))throw Error(`Build profile path ${e} must be outside the published output directory ${t}.`)}async function writeOptionalApplicationBuildProfile(e){try{assertProfileOutputOutsideBuildOutput(e.profileOutputPath,e.outputDirectory);let t=e.profiler.finish(),n=await measureApplicationBuildOutput(e.outputDirectory);await writeApplicationBuildProfile(e.profileOutputPath,createApplicationBuildProfile({output:n,target:process.env.VERCEL?`vercel`:`local`,timing:t}))}catch(t){console.warn(`eve: failed to write optional build profile to ${e.profileOutputPath}; continuing with the published build output: ${toErrorMessage(t)}`)}}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function normalizeEntrypoint(e,t){return typeof t!=`string`||t.trim().length===0?null:resolve(e,t)}function normalizeServiceRoot(e,t){return typeof t.root==`string`&&t.root.trim().length>0?resolve(e,t.root):normalizeEntrypoint(e,t.entrypoint)}function normalizeServicePrefix(e){return typeof e.routePrefix==`string`?e.routePrefix.trim():typeof e.mount==`string`?e.mount.trim():isRecord(e.mount)&&typeof e.mount.path==`string`&&e.mount.path.trim().length>0?e.mount.path.trim():``}function normalizeServiceCollection(e){if(isRecord(e))return Object.values(e).filter(isRecord);if(Array.isArray(e))return e.filter(isRecord)}function resolveCoDeployedEveServicePrefix(e){if(!isRecord(e.config))return;let t=normalizeServiceCollection(e.config.experimentalServices)??normalizeServiceCollection(e.config.experimentalServicesV2)??normalizeServiceCollection(e.config.services);if(t===void 0)return;let n=!1,r;for(let i of t){if(i.framework!==`eve`){n=!0;continue}let t=normalizeServiceRoot(e.configRoot,i),a=normalizeServicePrefix(i);t!==null&&e.appRoots.includes(t)&&a.length>0&&a!==`/`&&(r=a)}return n?r:void 0}async function resolveCoDeployedEveServicePrefixForVercelFunctionOutput(e,n){let i=Array.from(new Set([resolve(e),resolve(n)])),o=await findClosestVercelOutputDirectory(e);if(o!==void 0)try{let e=JSON.parse(await readFile(join(o,`config.json`),`utf8`)),t=resolveCoDeployedEveServicePrefix({appRoots:i,configRoot:await resolveVercelOutputConfigRoot(o),config:e});if(t!==void 0)return t}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}let s=e;for(;;){for(let e of[join(s,`vercel.json`),join(s,`.vercel`,`output`,`config.json`)])try{let n=JSON.parse(await readFile(e,`utf8`)),r=resolveCoDeployedEveServicePrefix({appRoots:i,configRoot:e.endsWith(`vercel.json`)?s:await resolveVercelOutputConfigRoot(dirname(e)),config:n});if(r!==void 0)return r}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}let e=dirname(s);if(e===s)return;s=e}}async function resolveVercelOutputConfigRoot(e){let n=dirname(dirname(e));try{let e=JSON.parse(await readFile(join(n,`.vercel`,`project.json`),`utf8`));if(isRecord(e)&&isRecord(e.settings)&&typeof e.settings.rootDirectory==`string`&&e.settings.rootDirectory.trim().length>0)return resolve(n,e.settings.rootDirectory)}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}return n}async function buildNitroOutput(e,t,n){let r=trimTrailingSlash(e.options.output.dir);return await measureBuildPhase(t,`${n}.cache.prepare`,()=>prepareEveVersionedCacheDirectory(r)),await measureBuildPhase(t,`${n}.prepare`,()=>prepare(e)),await measureBuildPhase(t,`${n}.public-assets`,()=>copyPublicAssets(e)),await measureBuildPhase(t,`${n}.prerender`,()=>prerender(e)),await measureBuildPhase(t,`${n}.bundle`,()=>build(e)),await measureBuildPhase(t,`${n}.cache.write`,()=>writeEveVersionedCacheMetadata(r)),r}async function buildApplication(e,t){let n=t.profileOutputPath===void 0?void 0:resolve(t.profileOutputPath),r=n===void 0?void 0:new ApplicationBuildProfiler,i=await measureBuildPhase(r,`extension.check`,()=>tryReadExtensionBuildConfig(e));if(i!==null)throw Error(`Package "${i.packageName}" is an eve extension. Run \`eve extension build\` instead of \`eve build\`.`);let o=await measureBuildPhase(r,`project.resolve`,()=>resolveDiscoveryProject(e)),c=await measureBuildPhase(r,`workspace.create`,()=>createApplicationBuildWorkspace(o.appRoot,t.vercelServiceOutput?.serviceOutputDirectory)),l=!1,u;try{u=await buildApplicationInWorkspace(c,t,r)}catch(e){throw l=e instanceof RecoverablePublicationError,e}finally{l||await measureBuildPhase(r,`workspace.remove`,()=>removeApplicationBuildWorkspace(c))}return r!==void 0&&n!==void 0&&await writeOptionalApplicationBuildProfile({outputDirectory:u,profileOutputPath:n,profiler:r}),u}async function buildApplicationInWorkspace(t,n,r){let i=await measureBuildPhase(r,`host.prepare`,()=>prepareProductionApplicationHost(t)),a=!!process.env.VERCEL,o=a?await measureBuildPhase(r,`vercel.service-prefix.resolve`,()=>resolveCoDeployedEveServicePrefixForVercelFunctionOutput(i.appRoot,i.compileResult.project.agentRoot)):void 0,s=await measureBuildPhase(r,`nitro.create`,()=>createProductionApplicationNitro(i,{buildDir:t.nitro.buildDir,outputDir:t.publication.output.stagedDir,publicRoutePrefix:n.publicRoutePrefix}));try{a&&!n.skipVercelSandboxPrewarm&&await measureBuildPhase(r,`sandbox.prewarm`,()=>runVercelBuildPrewarm({appRoot:i.appRoot,compiledArtifactsSource:createDiskRuntimeCompiledArtifactsSource(t.compiler.rootDir,{moduleMapLoaderPath:resolvePackageSourceFilePath(`src/internal/authored-module-map-loader.ts`),sandboxAppRoot:i.appRoot}),log(e){console.log(e)}})),await buildNitroOutput(s,r,`nitro`),o!==void 0&&await measureBuildPhase(r,`vercel.functions.normalize`,()=>normalizeEveVercelFunctionOutput(t.publication.output.stagedDir,{servicePrefix:o}));let c=n.vercelServiceOutput;c!==void 0&&await measureBuildPhase(r,`vercel.host-middleware.copy`,()=>copyHostMiddlewareFunctions({hostOutputDirectory:c.hostOutputDirectory,serviceOutputDirectory:t.publication.output.stagedDir})),await measureBuildPhase(r,`agent-summary.emit`,()=>emitVercelAgentSummary({manifest:i.compileResult.manifest,outputPath:t.publication.summary.stagedPath})),a||await measureBuildPhase(r,`compiler-artifacts.stage`,()=>stageProductionCompilerArtifacts({compilerArtifactsRoot:t.compiler.artifactsDir,outputDir:t.publication.output.stagedDir}))}finally{await measureBuildPhase(r,`nitro.close`,()=>s.close())}return await measureBuildPhase(r,`output.publish`,()=>publishCompletedApplicationBuild(t)),t.publication.output.finalDir}async function publishCompletedApplicationBuild(e){await publishApplicationBuildArtifacts({appRoot:e.appRoot,finalOutputDir:e.publication.output.finalDir,finalSummaryPath:e.publication.summary.finalPath,scratchDir:e.rootDir,stagedOutputDir:e.publication.output.stagedDir,stagedSummaryPath:e.publication.summary.stagedPath})}export{buildApplication};
@@ -1,12 +1,12 @@
1
1
  import type { Nitro } from "nitro/types";
2
- import type { NitroBuildSurface, PreparedApplicationHost } from "#internal/nitro/host/types.js";
2
+ import type { PreparedApplicationHost } from "#internal/nitro/host/types.js";
3
3
  /**
4
4
  * Wires eve's package-owned app, channel, workflow inspection, dev-control,
5
5
  * and Workflow SDK endpoints into one development Nitro candidate.
6
6
  */
7
7
  export declare function configureDevelopmentNitroRoutes(nitro: Nitro, preparedHost: PreparedApplicationHost): Promise<void>;
8
8
  /**
9
- * Wires the subset of eve's package-owned endpoints that belong to the given
10
- * build surface into a production Nitro host.
9
+ * Wires eve's package-owned app, channel, and Workflow SDK endpoints into the
10
+ * production Nitro host.
11
11
  */
12
- export declare function configureProductionNitroRoutes(nitro: Nitro, preparedHost: PreparedApplicationHost, surface: NitroBuildSurface): Promise<void>;
12
+ export declare function configureProductionNitroRoutes(nitro: Nitro, preparedHost: PreparedApplicationHost): 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{usesParentDevelopmentWorkflowWorld}from"#internal/workflow/development-world-protocol.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(`
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{usesParentDevelopmentWorkflowWorld}from"#internal/workflow/development-world-protocol.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";import{EVE_WORKFLOW_FLOW_ROUTE_PATH}from"#internal/nitro/host/vercel-build-output-config.js";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
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 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});await registerWorkflowArtifactBuildHook(e,async()=>{await i.build({nitroStepOutfile:join(n,`steps.mjs`),nitroWorkflowOutfile:join(n,`workflows.mjs`)})});let a=createDevelopmentNitroArtifactsConfig({appRoot:t.appRoot,configuredWorld:t.compileResult.manifest.config.experimental?.workflow?.world});registerApplicationRoutes(e,t,a),registerDevelopmentControlRoutes(e,a);let o=join(n,`workflows.mjs`),s=[];usesParentDevelopmentWorkflowWorld(t.compileResult.manifest.config.experimental?.workflow?.world)||s.push(createWorkflowDirectHandlerEntry(t,o)),await registerWorkflowRoute(e,t,o,s),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};
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:EVE_WORKFLOW_FLOW_ROUTE_PATH,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});await registerWorkflowArtifactBuildHook(e,async()=>{await i.build({nitroStepOutfile:join(n,`steps.mjs`),nitroWorkflowOutfile:join(n,`workflows.mjs`)})});let a=createDevelopmentNitroArtifactsConfig({appRoot:t.appRoot,configuredWorld:t.compileResult.manifest.config.experimental?.workflow?.world});registerApplicationRoutes(e,t,a),registerDevelopmentControlRoutes(e,a);let o=join(n,`workflows.mjs`),s=[];usesParentDevelopmentWorkflowWorld(t.compileResult.manifest.config.experimental?.workflow?.world)||s.push(createWorkflowDirectHandlerEntry(t,o)),await registerWorkflowRoute(e,t,o,s),e.routing.sync()}async function configureProductionNitroRoutes(e,t){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`)})}),registerApplicationRoutes(e,t,createProductionNitroArtifactsConfig());let i=join(t.workflowBuildDir,`workflows.mjs`),a=t.compileResult.manifest.config.experimental?.workflow?.world!==void 0;await registerWorkflowRoute(e,t,i,!isVercelBuildEnvironment()&&a?[createWorkflowDirectHandlerEntry(t,i)]:[]),e.routing.sync()}export{configureDevelopmentNitroRoutes,configureProductionNitroRoutes};
@@ -1,5 +1,5 @@
1
1
  import type { Nitro } from "nitro/types";
2
- import type { NitroBuildSurface, PreparedApplicationHost, PreparedDevelopmentApplicationHost } from "#internal/nitro/host/types.js";
2
+ import type { PreparedApplicationHost, PreparedDevelopmentApplicationHost } from "#internal/nitro/host/types.js";
3
3
  /**
4
4
  * Hosted Vercel builds can prune local sandbox backends only when the
5
5
  * app did not explicitly configure one. Omitted backends resolve through
@@ -17,14 +17,18 @@ export declare function createDevelopmentApplicationNitro(preparedHost: Prepared
17
17
  interface ProductionApplicationNitroOptions {
18
18
  readonly buildDir: string;
19
19
  readonly outputDir: string;
20
- readonly surface: NitroBuildSurface;
20
+ /**
21
+ * Agent's resolved public route prefix, baked into the Vercel flow
22
+ * function's environment for callback-URL minting behind a per-agent mount.
23
+ */
24
+ readonly publicRoutePrefix?: string;
21
25
  }
22
26
  /**
23
- * Creates a build-mode Nitro host for one production surface. `surface`
24
- * narrows which route groups are registered ("all" for self-hosted output;
25
- * "app"/"flow" for the separately bundled Vercel functions), and `buildDir`/
26
- * `outputDir` place all bundler state inside the invocation-owned build
27
- * workspace.
27
+ * Creates a build-mode Nitro host for one production build. Every route group
28
+ * (application, workflow, schedules) is registered in the same host; on Vercel
29
+ * the workflow flow route additionally becomes its own queue-triggered function
30
+ * through the preset's `functionRules`. `buildDir`/`outputDir` place all
31
+ * bundler state inside the invocation-owned build workspace.
28
32
  */
29
33
  export declare function createProductionApplicationNitro(preparedHost: PreparedApplicationHost, options: ProductionApplicationNitroOptions): Promise<Nitro>;
30
34
  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{fileURLToPath}from"node:url";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{createExtensionScopePlugin}from"#internal/bundler/extension-scope-plugin.js";import{createNitro}from"nitro/builder";import{prepareEveVersionedCacheDirectory,writeEveVersionedCacheMetadata}from"#internal/application/cache-metadata.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,...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=e.workspace.nitroBuildDir,r=createApplicationNitroBundlerConfiguration(e,void 0),i=createApplicationNitroPlugins(e);await prepareEveVersionedCacheDirectory(n);let a=await createNitro({_cli:{command:`dev`},buildDir:n,dev:!0,features:{websocket:!0},logLevel:1,output:{dir:e.workspace.nitroOutputDir},plugins:i,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);let s=join(a.options.buildDir,`workflow`,`steps.mjs`);configureSharedApplicationNitro(a,e,`all`);let c=configureNitroStepPlugins(a,s);return a.hooks.hook(`dev:reload`,()=>{for(let e of c)e()}),externalizeDevelopmentWorkflowBundle(a,e),await configureDevelopmentNitroRoutes(a,e),await addNitroStepNoExternals(a,s),a}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
+ 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{fileURLToPath}from"node:url";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{createExtensionScopePlugin}from"#internal/bundler/extension-scope-plugin.js";import{createNitro}from"nitro/builder";import{prepareEveVersionedCacheDirectory,writeEveVersionedCacheMetadata}from"#internal/application/cache-metadata.js";import{createProductionNitroArtifactsConfig}from"#internal/nitro/host/artifacts-config.js";import{createEveVercelOptions}from"#internal/nitro/host/vercel-build-output-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{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 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,...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){addNitroRoutingImportSpecifierPlugin(e);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=e.workspace.nitroBuildDir,r=createApplicationNitroBundlerConfiguration(e,void 0),i=createApplicationNitroPlugins(e);await prepareEveVersionedCacheDirectory(n);let a=await createNitro({_cli:{command:`dev`},buildDir:n,dev:!0,features:{websocket:!0},logLevel:1,output:{dir:e.workspace.nitroOutputDir},plugins:i,publicAssets:[],scanDirs:[resolvePackageSourceDirectoryPath(`src/execution`)],rolldownConfig:r.nitroRolldownConfig,rollupConfig:r.nitroRollupConfig,rootDir:e.appRoot,serverDir:!1,traceDeps:r.tracedAppDependencies,vercel:createEveVercelOptions({agentName:e.compileResult.manifest.config.name,enabled:!1}),watchOptions:createDevelopmentWatchOptions(e.appRoot)},{watch:!0});await writeEveVersionedCacheMetadata(n);let s=join(a.options.buildDir,`workflow`,`steps.mjs`);configureSharedApplicationNitro(a,e);let c=configureNitroStepPlugins(a,s);return a.hooks.hook(`dev:reload`,()=>{for(let e of c)e()}),externalizeDevelopmentWorkflowBundle(a,e),await configureDevelopmentNitroRoutes(a,e),await addNitroStepNoExternals(a,s),a}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:manifestHasWebSocketChannel(e.compileResult.manifest)},output:{dir:r.outputDir},preset:i,plugins:s,publicAssets:[],scanDirs:[resolvePackageSourceDirectoryPath(`src/execution`)],rolldownConfig:a.nitroRolldownConfig,rollupConfig:a.nitroRollupConfig,rootDir:e.appRoot,serverDir:!1,traceDeps:a.tracedAppDependencies,vercel:createEveVercelOptions({agentName:e.compileResult.manifest.config.name,enabled:i===`vercel`,publicRoutePrefix:r.publicRoutePrefix})});return await writeEveVersionedCacheMetadata(r.buildDir),configureSharedApplicationNitro(c,e),configureNitroStepPlugins(c,join(e.workflowBuildDir,`steps.mjs`)),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),await addNitroStepNoExternals(c,join(e.workflowBuildDir,`steps.mjs`)),c}export{createDevelopmentApplicationNitro,createProductionApplicationNitro,shouldPruneLocalSandboxBackends};
@@ -6,10 +6,6 @@ import type { DevBootProgressReporter } from "#internal/dev-boot-progress.js";
6
6
  import type { DevelopmentGeneration } from "#internal/nitro/development-generation.js";
7
7
  import type { DevelopmentHostWorkspace } from "#internal/nitro/host/dev-host-workspace.js";
8
8
  import type { DevelopmentWorkspaceExtension } from "#internal/nitro/host/dev-workspace-extensions.js";
9
- /**
10
- * Route surface included in one programmatic Nitro host build.
11
- */
12
- export type NitroBuildSurface = "all" | "app" | "flow";
13
9
  /** Options for one production application build. */
14
10
  export interface ApplicationBuildOptions {
15
11
  /** Absolute path for an optional machine-readable profile of a successful build. */
@@ -1,4 +1,19 @@
1
- export declare function createEveVercelOptions(enabled: boolean): {
1
+ /** Route Nitro's Vercel preset emits as the queue-triggered workflow function. */
2
+ export declare const EVE_WORKFLOW_FLOW_ROUTE_PATH = "/.well-known/workflow/v1/flow";
3
+ /**
4
+ * Builds eve's Vercel preset options.
5
+ *
6
+ * The flow route's `functionRules` entry makes Nitro emit a dedicated
7
+ * `flow.func` from the same build output, carrying the agent's queue trigger,
8
+ * an extended execution window, and the environment the deployed workflow
9
+ * runtime needs. Every other function setting (runtime, memory, streaming) is
10
+ * inherited from the base server function config.
11
+ */
12
+ export declare function createEveVercelOptions(input: {
13
+ agentName: string;
14
+ enabled: boolean;
15
+ publicRoutePrefix?: string;
16
+ }): {
2
17
  config: {
3
18
  version: 3;
4
19
  framework: {
@@ -6,4 +21,17 @@ export declare function createEveVercelOptions(enabled: boolean): {
6
21
  version: string;
7
22
  };
8
23
  };
24
+ functionRules: {
25
+ "/.well-known/workflow/v1/flow": {
26
+ maxDuration: "max";
27
+ experimentalTriggers: {
28
+ type: "queue/v2beta";
29
+ topic: string;
30
+ consumer: string;
31
+ retryAfterSeconds: number;
32
+ initialDelaySeconds: number;
33
+ }[];
34
+ environment: Record<string, string>;
35
+ };
36
+ };
9
37
  } | undefined;
@@ -1 +1 @@
1
- import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";function createEveVercelOptions(e){if(e)return{config:{version:3,framework:{slug:EVE_PACKAGE_NAME,version:resolveInstalledPackageInfo().version}}}}export{createEveVercelOptions};
1
+ import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{EVE_PUBLIC_ROUTE_PREFIX_ENV,normalizePublicRoutePrefix}from"#shared/public-route-prefix.js";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{createEveWorkflowQueueTrigger}from"#internal/workflow/queue-namespace.js";const EVE_WORKFLOW_FLOW_ROUTE_PATH=`/.well-known/workflow/v1/flow`;function createEveVercelOptions(e){if(!e.enabled)return;let t={WORKFLOW_PRECONDITION_GUARD:`1`},n=normalizePublicRoutePrefix(e.publicRoutePrefix);return n!==void 0&&(t[EVE_PUBLIC_ROUTE_PREFIX_ENV]=n),{config:{version:3,framework:{slug:EVE_PACKAGE_NAME,version:resolveInstalledPackageInfo().version}},functionRules:{[EVE_WORKFLOW_FLOW_ROUTE_PATH]:{maxDuration:`max`,experimentalTriggers:[createEveWorkflowQueueTrigger(e.agentName)],environment:t}}}}export{EVE_WORKFLOW_FLOW_ROUTE_PATH,createEveVercelOptions};
@@ -5,5 +5,13 @@ export declare function deriveEveWorkflowQueueNamespace(agentName: string): stri
5
5
  export declare function deriveEveWorkflowQueuePrefix(agentName: string): string;
6
6
  /** Derives the queue topic registered for an eve agent's workflow handler. */
7
7
  export declare function deriveEveWorkflowQueueTopic(agentName: string): string;
8
+ /** Builds the Vercel queue trigger that invokes an eve agent's flow function. */
9
+ export declare function createEveWorkflowQueueTrigger(agentName: string): {
10
+ type: "queue/v2beta";
11
+ topic: string;
12
+ consumer: string;
13
+ retryAfterSeconds: number;
14
+ initialDelaySeconds: number;
15
+ };
8
16
  /** Installs the agent-scoped namespace used by Workflow runtime operations. */
9
17
  export declare function installEveWorkflowQueueNamespace(agentName: string): string;
@@ -1 +1 @@
1
- const WORKFLOW_QUEUE_NAMESPACE_ENV=`WORKFLOW_QUEUE_NAMESPACE`;function deriveEveWorkflowQueueNamespace(e){return`eve${Array.from(new TextEncoder().encode(e),e=>e.toString(16).padStart(2,`0`)).join(``)}`}function deriveEveWorkflowQueuePrefix(e){return`__${deriveEveWorkflowQueueNamespace(e)}_wkf_workflow_`}function deriveEveWorkflowQueueTopic(e){return`${deriveEveWorkflowQueuePrefix(e)}*`}function installEveWorkflowQueueNamespace(t){let n=deriveEveWorkflowQueueNamespace(t);return process.env[WORKFLOW_QUEUE_NAMESPACE_ENV]=n,n}export{WORKFLOW_QUEUE_NAMESPACE_ENV,deriveEveWorkflowQueueNamespace,deriveEveWorkflowQueuePrefix,deriveEveWorkflowQueueTopic,installEveWorkflowQueueNamespace};
1
+ const WORKFLOW_QUEUE_NAMESPACE_ENV=`WORKFLOW_QUEUE_NAMESPACE`;function deriveEveWorkflowQueueNamespace(e){return`eve${Array.from(new TextEncoder().encode(e),e=>e.toString(16).padStart(2,`0`)).join(``)}`}function deriveEveWorkflowQueuePrefix(e){return`__${deriveEveWorkflowQueueNamespace(e)}_wkf_workflow_`}function deriveEveWorkflowQueueTopic(e){return`${deriveEveWorkflowQueuePrefix(e)}*`}function createEveWorkflowQueueTrigger(e){return{type:`queue/v2beta`,topic:deriveEveWorkflowQueueTopic(e),consumer:`default`,retryAfterSeconds:5,initialDelaySeconds:0}}function installEveWorkflowQueueNamespace(t){let n=deriveEveWorkflowQueueNamespace(t);return process.env[WORKFLOW_QUEUE_NAMESPACE_ENV]=n,n}export{WORKFLOW_QUEUE_NAMESPACE_ENV,createEveWorkflowQueueTrigger,deriveEveWorkflowQueueNamespace,deriveEveWorkflowQueuePrefix,deriveEveWorkflowQueueTopic,installEveWorkflowQueueNamespace};
@@ -5,11 +5,6 @@ export interface WorkflowBundleBuilderOptions {
5
5
  appRoot: string;
6
6
  compiledArtifactsBootstrapPath: string;
7
7
  outDir: string;
8
- /**
9
- * The agent's resolved public route prefix, baked into every emitted Vercel
10
- * workflow function's environment for callback-URL minting.
11
- */
12
- publicRoutePrefix?: string;
13
8
  rootDir: string;
14
9
  watch: boolean;
15
10
  /** Test-harness-only: also scans `src/internal/testing/`. */
@@ -18,9 +18,4 @@ export declare class WorkflowBundleBuilder {
18
18
  manifestDir: string;
19
19
  workflowBundlePath: string;
20
20
  }): Promise<string | undefined>;
21
- buildVercelOutput(options: {
22
- flowNitroOutputDir: string;
23
- outputDir: string;
24
- runtime?: string;
25
- }): Promise<void>;
26
21
  }
@@ -1,3 +1,3 @@
1
- import{resolvePackageSourceDirectoryPath,resolveWorkflowModulePath}from"#internal/application/package.js";import{dirname,join,relative,resolve}from"node:path";import{cp,mkdir,readFile,rm,writeFile}from"node:fs/promises";import{normalizeEsmImportSpecifier}from"#internal/application/import-specifier.js";import{atomicWriteFile}from"#shared/atomic-write-file.js";import{buildSingleRolldownChunk}from"#internal/bundler/nitro-rolldown.js";import{prepareEveVersionedCacheDirectory,writeEveVersionedCacheMetadata}from"#internal/application/cache-metadata.js";import{WORKFLOW_BUILDER_DEFERRED_PACKAGES,WORKFLOW_STEP_EXTERNAL_PACKAGES,copyNitroFunctionDirectory,createWorkflowFunctionEnvironment,retargetNitroFunctionDirectoryToWorkflowRoute}from"#internal/workflow-bundle/vercel-workflow-output.js";import{deriveEveWorkflowQueueNamespace}from"#internal/workflow/queue-namespace.js";import{createEveWorkflowQueueTrigger,detectWorkflowPatterns}from"#internal/workflow-bundle/workflow-builders.js";import{Buffer}from"node:buffer";import{runQueuedWorkflowBuild}from"#internal/workflow-bundle/build-queue.js";import{WORKFLOW_VIRTUAL_ENTRY_ID,bundleFinalWorkflowOutput,collectWorkflowInputFiles,convertClassesManifest,convertStepsManifest,convertWorkflowsManifest,createEvePackageImportsPlugin,createWorkflowImport,createWorkflowNodeBuiltinGuardPlugin,createWorkflowPseudoPackagePlugin,createWorkflowTransformPlugin,createWorkflowVirtualEntryPlugin}from"#internal/workflow-bundle/builder-support.js";import{writeNitroStepEntrypoint}from"#internal/workflow-bundle/nitro-step-entry.js";var WorkflowBundleBuilder=class{#e;#t;#n;#r;#i;config;#a=new WeakMap;constructor(t){let n=[resolvePackageSourceDirectoryPath(`src/execution`)];t.includeTestFixtures===!0&&n.push(resolvePackageSourceDirectoryPath(`src/internal/testing`)),this.config={buildTarget:`standalone`,dirs:n,externalPackages:[...WORKFLOW_STEP_EXTERNAL_PACKAGES,...WORKFLOW_BUILDER_DEFERRED_PACKAGES],projectRoot:t.appRoot,watch:t.watch,workingDir:t.rootDir},this.#e=t.agentName,this.#t=t.compiledArtifactsBootstrapPath,this.#n=t.outDir,this.#r=t.publicRoutePrefix,this.#i=deriveEveWorkflowQueueNamespace(t.agentName)}async build(e={}){await runQueuedWorkflowBuild(this.#n,async()=>this.#o(e))}async#o(i){await prepareEveVersionedCacheDirectory(this.#n);let a=await this.#s();if(a.length===0)throw Error(`Expected the execution workflow source file under "${resolvePackageSourceDirectoryPath(`src/execution`)}".`);let o=await this.findTsConfigPath();await mkdir(this.#n,{recursive:!0});let c=await this.discoverEntries(a,this.#n,o),l=join(this.#n,`workflows.mjs`),{manifest:u}=await this.createWorkflowsBundle({discoveredEntries:c,keepInterimBundleContext:!1,outfile:l,bundleFinalOutput:!1,format:`esm`,inputFiles:a,tsconfigPath:o}),d=join(this.#n,`steps.mjs`),f=await writeNitroStepEntrypoint({builtinsPath:resolveWorkflowModulePath(`workflow/internal/builtins`),discoveredEntries:c,outfile:d,preferAbsoluteFileImports:!0,projectRoot:this.config.projectRoot??this.config.workingDir,sideEffectFiles:[this.#t],workingDir:this.config.workingDir}),p=i.nitroStepOutfile;p!==void 0&&p!==d&&await writeNitroStepEntrypoint({builtinsPath:resolveWorkflowModulePath(`workflow/internal/builtins`),discoveredEntries:c,outfile:p,preferAbsoluteFileImports:!0,projectRoot:this.config.projectRoot??this.config.workingDir,sideEffectFiles:[this.#t],workingDir:this.config.workingDir}),await addStepRegistrationsImport(l,d),await rewriteWorkflowRuntimeImports(l),await rewriteWorkflowCodeLiteral(l,this.#i);let h=i.nitroWorkflowOutfile;h!==void 0&&h!==l&&(await mkdir(dirname(h),{recursive:!0}),await mirrorFileBypassingUnlink(l,h),p!==void 0&&(await addStepRegistrationsImport(h,p),await rewriteWorkflowRuntimeImports(h),await rewriteWorkflowCodeLiteral(h,this.#i))),await this.createManifest({workflowBundlePath:join(this.#n,`workflows.mjs`),manifestDir:this.#n,manifest:{steps:{...f.steps,...u.steps},workflows:{...f.workflows,...u.workflows},classes:{...f.classes,...u.classes}}}),await writeEveVersionedCacheMetadata(this.#n)}get transformProjectRoot(){return this.config.projectRoot??this.config.workingDir}async findTsConfigPath(){let e=this.config.workingDir;for(;;){for(let t of[`tsconfig.json`,`jsconfig.json`]){let n=join(e,t);try{return await readFile(n),n}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}}let t=dirname(e);if(t===e)return;e=t}}async getInputFiles(){let e=this.config.dirs.map(e=>resolve(this.config.workingDir,e));return(await Promise.all(e.map(e=>collectWorkflowInputFiles(e)))).flat()}async discoverEntries(e,t,n){let r=this.#a.get(e);if(r!==void 0)return r;let i={discoveredSerdeFiles:[],discoveredSteps:[],discoveredWorkflows:[]};for(let t of e){let e=detectWorkflowPatterns(await readFile(t,`utf8`));e.hasUseStep&&i.discoveredSteps.push(t),e.hasUseWorkflow&&i.discoveredWorkflows.push(t),e.hasSerde&&i.discoveredSerdeFiles.push(t)}return this.#a.set(e,i),i}async createWorkflowsBundle({bundleFinalOutput:e=!0,discoveredEntries:t,format:r=`cjs`,inputFiles:i,keepInterimBundleContext:a=this.config.watch,outfile:o,tsconfigPath:s}){let c=t??await this.discoverEntries(i,dirname(o),s),l=[...c.discoveredWorkflows].sort(),u=new Set(l),d=[...c.discoveredSerdeFiles].sort().filter(e=>!u.has(e)),f={},m=[...l.map(e=>createWorkflowImport(e,this.config.workingDir)),...d.map(e=>createWorkflowImport(e,this.config.workingDir))].join(`
2
- `);return await bundleFinalWorkflowOutput({bundleFinalOutput:e,code:(await buildSingleRolldownChunk(`intermediate workflow bundle for "${o}"`,{cwd:this.config.workingDir,input:WORKFLOW_VIRTUAL_ENTRY_ID,platform:`neutral`,plugins:[createWorkflowVirtualEntryPlugin(m),createWorkflowPseudoPackagePlugin(),createEvePackageImportsPlugin(this.config.workingDir,{workflowCondition:!0}),createWorkflowTransformPlugin({manifest:f,projectRoot:this.transformProjectRoot,sideEffectFiles:[...l,...d],workingDir:this.config.workingDir}),createWorkflowNodeBuiltinGuardPlugin()],resolve:{conditionNames:[`eve-source`,`workflow`,`node`,`import`,`default`],extensions:[`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`],mainFields:[`module`,`main`]},tsconfig:s??!1,output:{banner:`globalThis.__private_workflows = new Map();`,comments:!1,format:`cjs`,sourcemap:`inline`}})).code,format:r,outfile:o,queueNamespace:this.#i,workingDir:this.config.workingDir}),a?{bundleFinal:async t=>{await bundleFinalWorkflowOutput({bundleFinalOutput:e,code:t,format:r,outfile:o,queueNamespace:this.#i,workingDir:this.config.workingDir})},interimBundleCtx:void 0,manifest:f}:{manifest:f}}async createManifest({manifest:e,manifestDir:t}){let n={version:`1.0.0`,steps:convertStepsManifest(e.steps),workflows:convertWorkflowsManifest(e.workflows),classes:convertClassesManifest(e.classes)},i=JSON.stringify(n,null,2);return await mkdir(t,{recursive:!0}),await writeFile(join(t,`manifest.json`),i),i}async buildVercelOutput(e){await this.build();let t=join(this.#n,`vercel-build-output`,`functions`,`.well-known`,`workflow`,`v1`),n=join(t,`flow.func`),i=join(e.outputDir,`functions`,`.well-known`,`workflow`,`v1`),a=join(e.flowNitroOutputDir,`functions`,`__server.func`),c=join(e.flowNitroOutputDir,`functions`,`.well-known`,`workflow`,`v1`,`flow.func`),u=join(i,`flow.func`),d=join(i,`step.func`),f=join(i,`webhook`,`[token].func`);await copyNitroFunctionDirectory({fallbackPath:a,sourcePath:c,targetPath:n}),await Promise.all([this.#c(n,{experimentalTriggers:[createEveWorkflowQueueTrigger(this.#e)],maxDuration:`max`,runtime:e.runtime??null,shouldAddHelpers:!1}),cp(join(this.#n,`manifest.json`),join(t,`manifest.json`))]),await retargetNitroFunctionDirectoryToWorkflowRoute({functionDirectoryPath:n,workflowRoutePath:`/.well-known/workflow/v1/flow`}),await Promise.all([rm(u,{force:!0,recursive:!0}),rm(d,{force:!0,recursive:!0}),rm(f,{force:!0,recursive:!0})]),await mkdir(i,{recursive:!0}),await Promise.all([cp(n,u,{recursive:!0}),cp(join(t,`manifest.json`),join(i,`manifest.json`))])}async#s(){return await this.getInputFiles()}async#c(e,t){let n=join(e,`.vc-config.json`),i=await this.#l(n),a={...i};a.environment=createWorkflowFunctionEnvironment({environment:i.environment,publicRoutePrefix:this.#r}),t.runtime!==null&&(a.runtime=t.runtime),t.maxDuration!==void 0&&(a.maxDuration=t.maxDuration),t.shouldAddHelpers!==void 0&&(a.shouldAddHelpers=t.shouldAddHelpers),t.shouldAddSourcemapSupport!==void 0&&(a.shouldAddSourcemapSupport=t.shouldAddSourcemapSupport),t.experimentalTriggers!==void 0&&(a.experimentalTriggers=[...t.experimentalTriggers]),await writeFile(n,`${JSON.stringify(a,null,2)}\n`)}async#l(e){try{let t=JSON.parse(await readFile(e,`utf8`));if(typeof t==`object`&&t)return t}catch{}return{}}};async function addStepRegistrationsImport(e,t){let r=await readTextFileIfPresent(e);if(r===null||r.includes(`__eveWorkflowStepsRegistered`))return;let i=createRelativeImportSpecifier(dirname(e),t),a=[`import { __steps_registered as __eveWorkflowStepsRegistered } from ${JSON.stringify(i)};`,`void __eveWorkflowStepsRegistered;`,``].join(`
1
+ import{resolvePackageSourceDirectoryPath,resolveWorkflowModulePath}from"#internal/application/package.js";import{dirname,join,relative,resolve}from"node:path";import{mkdir,readFile,writeFile}from"node:fs/promises";import{normalizeEsmImportSpecifier}from"#internal/application/import-specifier.js";import{atomicWriteFile}from"#shared/atomic-write-file.js";import{buildSingleRolldownChunk}from"#internal/bundler/nitro-rolldown.js";import{prepareEveVersionedCacheDirectory,writeEveVersionedCacheMetadata}from"#internal/application/cache-metadata.js";import{WORKFLOW_BUILDER_DEFERRED_PACKAGES,WORKFLOW_STEP_EXTERNAL_PACKAGES}from"#internal/workflow-bundle/vercel-workflow-output.js";import{deriveEveWorkflowQueueNamespace}from"#internal/workflow/queue-namespace.js";import{detectWorkflowPatterns}from"#internal/workflow-bundle/workflow-builders.js";import{Buffer}from"node:buffer";import{runQueuedWorkflowBuild}from"#internal/workflow-bundle/build-queue.js";import{WORKFLOW_VIRTUAL_ENTRY_ID,bundleFinalWorkflowOutput,collectWorkflowInputFiles,convertClassesManifest,convertStepsManifest,convertWorkflowsManifest,createEvePackageImportsPlugin,createWorkflowImport,createWorkflowNodeBuiltinGuardPlugin,createWorkflowPseudoPackagePlugin,createWorkflowTransformPlugin,createWorkflowVirtualEntryPlugin}from"#internal/workflow-bundle/builder-support.js";import{writeNitroStepEntrypoint}from"#internal/workflow-bundle/nitro-step-entry.js";var WorkflowBundleBuilder=class{#e;#t;#n;config;#r=new WeakMap;constructor(t){let n=[resolvePackageSourceDirectoryPath(`src/execution`)];t.includeTestFixtures===!0&&n.push(resolvePackageSourceDirectoryPath(`src/internal/testing`)),this.config={buildTarget:`standalone`,dirs:n,externalPackages:[...WORKFLOW_STEP_EXTERNAL_PACKAGES,...WORKFLOW_BUILDER_DEFERRED_PACKAGES],projectRoot:t.appRoot,watch:t.watch,workingDir:t.rootDir},this.#e=t.compiledArtifactsBootstrapPath,this.#t=t.outDir,this.#n=deriveEveWorkflowQueueNamespace(t.agentName)}async build(e={}){await runQueuedWorkflowBuild(this.#t,async()=>this.#i(e))}async#i(i){await prepareEveVersionedCacheDirectory(this.#t);let a=await this.#a();if(a.length===0)throw Error(`Expected the execution workflow source file under "${resolvePackageSourceDirectoryPath(`src/execution`)}".`);let s=await this.findTsConfigPath();await mkdir(this.#t,{recursive:!0});let c=await this.discoverEntries(a,this.#t,s),l=join(this.#t,`workflows.mjs`),{manifest:u}=await this.createWorkflowsBundle({discoveredEntries:c,keepInterimBundleContext:!1,outfile:l,bundleFinalOutput:!1,format:`esm`,inputFiles:a,tsconfigPath:s}),d=join(this.#t,`steps.mjs`),m=await writeNitroStepEntrypoint({builtinsPath:resolveWorkflowModulePath(`workflow/internal/builtins`),discoveredEntries:c,outfile:d,preferAbsoluteFileImports:!0,projectRoot:this.config.projectRoot??this.config.workingDir,sideEffectFiles:[this.#e],workingDir:this.config.workingDir}),h=i.nitroStepOutfile;h!==void 0&&h!==d&&await writeNitroStepEntrypoint({builtinsPath:resolveWorkflowModulePath(`workflow/internal/builtins`),discoveredEntries:c,outfile:h,preferAbsoluteFileImports:!0,projectRoot:this.config.projectRoot??this.config.workingDir,sideEffectFiles:[this.#e],workingDir:this.config.workingDir}),await addStepRegistrationsImport(l,d),await rewriteWorkflowRuntimeImports(l),await rewriteWorkflowCodeLiteral(l,this.#n);let g=i.nitroWorkflowOutfile;g!==void 0&&g!==l&&(await mkdir(dirname(g),{recursive:!0}),await mirrorFileBypassingUnlink(l,g),h!==void 0&&(await addStepRegistrationsImport(g,h),await rewriteWorkflowRuntimeImports(g),await rewriteWorkflowCodeLiteral(g,this.#n))),await this.createManifest({workflowBundlePath:join(this.#t,`workflows.mjs`),manifestDir:this.#t,manifest:{steps:{...m.steps,...u.steps},workflows:{...m.workflows,...u.workflows},classes:{...m.classes,...u.classes}}}),await writeEveVersionedCacheMetadata(this.#t)}get transformProjectRoot(){return this.config.projectRoot??this.config.workingDir}async findTsConfigPath(){let e=this.config.workingDir;for(;;){for(let t of[`tsconfig.json`,`jsconfig.json`]){let n=join(e,t);try{return await readFile(n),n}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}}let t=dirname(e);if(t===e)return;e=t}}async getInputFiles(){let e=this.config.dirs.map(e=>resolve(this.config.workingDir,e));return(await Promise.all(e.map(e=>collectWorkflowInputFiles(e)))).flat()}async discoverEntries(e,t,n){let r=this.#r.get(e);if(r!==void 0)return r;let i={discoveredSerdeFiles:[],discoveredSteps:[],discoveredWorkflows:[]};for(let t of e){let e=detectWorkflowPatterns(await readFile(t,`utf8`));e.hasUseStep&&i.discoveredSteps.push(t),e.hasUseWorkflow&&i.discoveredWorkflows.push(t),e.hasSerde&&i.discoveredSerdeFiles.push(t)}return this.#r.set(e,i),i}async createWorkflowsBundle({bundleFinalOutput:e=!0,discoveredEntries:t,format:r=`cjs`,inputFiles:i,keepInterimBundleContext:a=this.config.watch,outfile:o,tsconfigPath:s}){let c=t??await this.discoverEntries(i,dirname(o),s),l=[...c.discoveredWorkflows].sort(),u=new Set(l),f=[...c.discoveredSerdeFiles].sort().filter(e=>!u.has(e)),p={},m=[...l.map(e=>createWorkflowImport(e,this.config.workingDir)),...f.map(e=>createWorkflowImport(e,this.config.workingDir))].join(`
2
+ `);return await bundleFinalWorkflowOutput({bundleFinalOutput:e,code:(await buildSingleRolldownChunk(`intermediate workflow bundle for "${o}"`,{cwd:this.config.workingDir,input:WORKFLOW_VIRTUAL_ENTRY_ID,platform:`neutral`,plugins:[createWorkflowVirtualEntryPlugin(m),createWorkflowPseudoPackagePlugin(),createEvePackageImportsPlugin(this.config.workingDir,{workflowCondition:!0}),createWorkflowTransformPlugin({manifest:p,projectRoot:this.transformProjectRoot,sideEffectFiles:[...l,...f],workingDir:this.config.workingDir}),createWorkflowNodeBuiltinGuardPlugin()],resolve:{conditionNames:[`eve-source`,`workflow`,`node`,`import`,`default`],extensions:[`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`],mainFields:[`module`,`main`]},tsconfig:s??!1,output:{banner:`globalThis.__private_workflows = new Map();`,comments:!1,format:`cjs`,sourcemap:`inline`}})).code,format:r,outfile:o,queueNamespace:this.#n,workingDir:this.config.workingDir}),a?{bundleFinal:async t=>{await bundleFinalWorkflowOutput({bundleFinalOutput:e,code:t,format:r,outfile:o,queueNamespace:this.#n,workingDir:this.config.workingDir})},interimBundleCtx:void 0,manifest:p}:{manifest:p}}async createManifest({manifest:e,manifestDir:t}){let n={version:`1.0.0`,steps:convertStepsManifest(e.steps),workflows:convertWorkflowsManifest(e.workflows),classes:convertClassesManifest(e.classes)},i=JSON.stringify(n,null,2);return await mkdir(t,{recursive:!0}),await writeFile(join(t,`manifest.json`),i),i}async#a(){return await this.getInputFiles()}};async function addStepRegistrationsImport(e,t){let r=await readTextFileIfPresent(e);if(r===null||r.includes(`__eveWorkflowStepsRegistered`))return;let i=createRelativeImportSpecifier(dirname(e),t),a=[`import { __steps_registered as __eveWorkflowStepsRegistered } from ${JSON.stringify(i)};`,`void __eveWorkflowStepsRegistered;`,``].join(`
3
3
  `),o=r.match(/^import\s.+?;\n/m);if(o===null||o.index===void 0){await atomicWriteFile(e,`${a}${r}`);return}let s=o.index+o[0].length;await atomicWriteFile(e,`${r.slice(0,s)}${a}${r.slice(s)}`)}async function rewriteWorkflowRuntimeImports(e){let n=await readTextFileIfPresent(e);if(n===null)return;let r=n;for(let e of[`workflow`,`workflow/api`,`workflow/internal/builtins`,`workflow/internal/private`,`workflow/runtime`]){let n=normalizeImportSpecifierPath(resolveWorkflowModulePath(e));r=replaceStringLiteralSpecifier(r,e,n)}r!==n&&await atomicWriteFile(e,r)}async function rewriteWorkflowCodeLiteral(e,t){let n=await readTextFileIfPresent(e);if(n===null)return;let r=`;\n\nexport const POST = workflowEntrypoint(workflowCode, { namespace: ${JSON.stringify(t)} });`,i=n.indexOf(`const workflowCode = `),a=n.lastIndexOf(r);if(i===-1||a===-1||a<=i)return;let o=i+21,s=n.slice(o,a);if(!s.trimStart().startsWith("`"))return;let c=decodeWorkflowCodeTemplateLiteral(s,e),l=`${n.slice(0,o)}${encodeWorkflowCodeLiteral(c)}${n.slice(a)}`;l!==n&&await atomicWriteFile(e,l)}function encodeWorkflowCodeLiteral(e){let t=Buffer.from(e,`utf8`).toString(`base64`).match(/.{1,16384}/g)??[``];return`Buffer.from(${JSON.stringify(t)}.join(""), "base64").toString("utf8")`}function decodeWorkflowCodeTemplateLiteral(e,t){let n=e.trim();if(!n.startsWith("`")||!n.endsWith("`"))throw Error(`Expected generated workflow code literal in "${t}" to be a template.`);let r=n.slice(1,-1),i=``;for(let e=0;e<r.length;e+=1){let t=r[e];if(t!==`\\`){i+=t;continue}let n=r[e+1];if(n===`\\`||n==="`"||n===`$`){i+=n,e+=1;continue}i+=t}return i}function replaceStringLiteralSpecifier(e,t,n){return e.replaceAll(JSON.stringify(t),JSON.stringify(n)).replaceAll(`'${t}'`,JSON.stringify(n))}function normalizeImportSpecifierPath(e){return normalizeEsmImportSpecifier(e)}function createRelativeImportSpecifier(e,t){let n=relative(e,t).replaceAll(`\\`,`/`);return n.startsWith(`.`)?n:`./${n}`}async function readTextFileIfPresent(e){try{return await readFile(e,`utf8`)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return null;throw e}}async function readBinaryFileIfPresent(e){try{return await readFile(e)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return null;throw e}}async function mirrorFileBypassingUnlink(e,t){let n=await readFile(e),r=await readBinaryFileIfPresent(t);r!==null&&r.equals(n)||await atomicWriteFile(t,n)}export{WorkflowBundleBuilder};
@@ -5,35 +5,6 @@ export declare const WORKFLOW_STEP_EXTERNAL_PACKAGES: readonly ["@mongodb-js/zst
5
5
  * Nitro performs the final bundling/tracing pass for hosted output.
6
6
  */
7
7
  export declare const WORKFLOW_BUILDER_DEFERRED_PACKAGES: readonly ["@chat-adapter/slack", "chat"];
8
- /**
9
- * Builds the environment block every generated Vercel workflow function needs.
10
- *
11
- * When the build input carries the agent's resolved public route prefix, it
12
- * is baked into the function environment under
13
- * {@link EVE_PUBLIC_ROUTE_PREFIX_ENV} so callback-URL minting inside the
14
- * deployed workflow functions knows the agent's public mount.
15
- */
16
- export declare function createWorkflowFunctionEnvironment(input?: {
17
- environment?: unknown;
18
- publicRoutePrefix?: string;
19
- }): Record<string, unknown>;
20
- /**
21
- * Creates an empty staging directory for one emitted Vercel function.
22
- */
23
- export declare function prepareVercelFunctionDirectory(path: string): Promise<void>;
24
- /**
25
- * Copies a Nitro-bundled Vercel function directory into one standalone
26
- * workflow function directory.
27
- *
28
- * Nitro may emit route functions as symlinks back to `__server.func`. This
29
- * helper dereferences the source path first, then copies concrete files so the
30
- * generated workflow functions do not rely on symlinks.
31
- */
32
- export declare function copyNitroFunctionDirectory(input: {
33
- fallbackPath: string;
34
- sourcePath: string;
35
- targetPath: string;
36
- }): Promise<void>;
37
8
  /**
38
9
  * Keeps only eve-owned Vercel function output and rewrites eve route function
39
10
  * symlinks to a shared eve-owned server function.
@@ -51,25 +22,3 @@ export declare function copyNitroFunctionDirectory(input: {
51
22
  export declare function normalizeEveVercelFunctionOutput(outputDir: string, options?: {
52
23
  readonly servicePrefix?: string;
53
24
  }): Promise<void>;
54
- /**
55
- * Bundles one package-owned workflow handler into a standalone Vercel function
56
- * directory without inheriting Nitro's hosted server chunks.
57
- */
58
- export declare function emitBundledWorkflowFunctionDirectory(input: {
59
- bundlePath: string;
60
- pluginPaths?: readonly string[];
61
- publicRoutePrefix?: string;
62
- targetPath: string;
63
- }): Promise<void>;
64
- /**
65
- * Rewrites one copied Nitro function directory so its handler always dispatches
66
- * to a concrete workflow route path.
67
- *
68
- * Queue-triggered workflow functions do not guarantee a request URL that
69
- * matches Nitro's original route table. This helper keeps Nitro's traced
70
- * output intact but swaps the entrypoint with a small URL-rewriting adapter.
71
- */
72
- export declare function retargetNitroFunctionDirectoryToWorkflowRoute(input: {
73
- functionDirectoryPath: string;
74
- workflowRoutePath: string;
75
- }): Promise<void>;
@@ -1,3 +1 @@
1
- import{basename,dirname,extname,join,relative}from"node:path";import{EVE_PUBLIC_ROUTE_PREFIX_ENV,normalizePublicRoutePrefix}from"#shared/public-route-prefix.js";import{cp,mkdir,readFile,readdir,realpath,rename,rm,symlink,writeFile}from"node:fs/promises";import{buildSingleRolldownChunk}from"#internal/bundler/nitro-rolldown.js";import{EVE_SHARED_SERVER_FUNCTION_PATH,isEveVercelFunctionPath,normalizeEveVercelRoutes}from"#internal/workflow-bundle/eve-service-route-output.js";const WORKFLOW_STEP_EXTERNAL_PACKAGES=[`@mongodb-js/zstd`,`just-bash`,`microsandbox`,`node-liblzma`],WORKFLOW_BUILDER_DEFERRED_PACKAGES=[`@chat-adapter/slack`,`chat`];function createWorkflowFunctionEnvironment(e={}){let t={};isRecord(e.environment)&&Object.assign(t,e.environment);let n=normalizePublicRoutePrefix(e.publicRoutePrefix);return n!==void 0&&(t[EVE_PUBLIC_ROUTE_PREFIX_ENV]=n),t.WORKFLOW_PRECONDITION_GUARD=`1`,t.NODE_OPTIONS=`--experimental-require-module`,t}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function prepareVercelFunctionDirectory(e){await rm(e,{force:!0,recursive:!0}),await mkdir(e,{recursive:!0})}async function resolveNitroFunctionDirectory(e){try{return await realpath(e.sourcePath)}catch{return await realpath(e.fallbackPath)}}async function copyNitroFunctionDirectory(e){let t=await resolveNitroFunctionDirectory({fallbackPath:e.fallbackPath,sourcePath:e.sourcePath});await prepareVercelFunctionDirectory(e.targetPath),await cp(t,e.targetPath,{dereference:!0,recursive:!0})}async function normalizeEveVercelFunctionOutput(e,t={}){let n=join(e,`functions`),i=await prepareSharedEveServerFunction(n);i!==null&&await repointEveFunctionSymlinksInDirectory(n,i),await pruneNonEveFunctionEntries(n,n),await pruneNonEveVercelRoutes(e,t.servicePrefix)}async function prepareSharedEveServerFunction(e){let n=join(e,`__server.func`),i=join(e,EVE_SHARED_SERVER_FUNCTION_PATH),a;try{a=await realpath(n)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return null;throw e}let o=`${i}.eve-staging`;return await mkdir(dirname(i),{recursive:!0}),await rm(o,{force:!0,recursive:!0}),await cp(a,o,{dereference:!0,recursive:!0}),await rm(i,{force:!0,recursive:!0}),await rename(o,i),i}async function repointEveFunctionSymlinksInDirectory(e,t,n=e){let a;try{a=await readdir(e,{withFileTypes:!0})}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}await Promise.all(a.map(async a=>{let o=join(e,a.name),s=normalizeVercelOutputPath(relative(n,o));if(a.isSymbolicLink()){a.name.endsWith(`.func`)&&isEveVercelFunctionPath(s)&&await repointFunctionSymlink(o,t);return}a.isDirectory()&&!a.name.endsWith(`.func`)&&await repointEveFunctionSymlinksInDirectory(o,t,n)}))}async function repointFunctionSymlink(e,n){await rm(e,{force:!0,recursive:!0}),await symlink(normalizeVercelOutputPath(relative(dirname(e),n)),e,`dir`)}async function pruneNonEveFunctionEntries(e,t){let n;try{n=await readdir(t,{withFileTypes:!0})}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}await Promise.all(n.map(async n=>{let a=join(t,n.name),o=normalizeVercelOutputPath(relative(e,a));if(n.name.endsWith(`.func`)){isEveVercelFunctionPath(o)||await rm(a,{force:!0,recursive:!0});return}n.isDirectory()&&await pruneNonEveFunctionEntries(e,a)}))}async function pruneNonEveVercelRoutes(e,t){let n=join(e,`config.json`),i;try{i=JSON.parse(await readFile(n,`utf8`))}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}!isRecord(i)||!Array.isArray(i.routes)||(i.routes=normalizeEveVercelRoutes(i.routes,t),await writeFile(n,`${JSON.stringify(i,null,2)}\n`))}function normalizeVercelOutputPath(e){return e.replaceAll(`\\`,`/`)}async function emitBundledWorkflowFunctionDirectory(e){await prepareVercelFunctionDirectory(e.targetPath);let n=await emitBundledWorkflowPluginModules({pluginPaths:e.pluginPaths??[],targetPath:e.targetPath}),i=join(dirname(e.bundlePath),`__eve_workflow_function_entry.js`),a=await buildSingleRolldownChunk(`Vercel workflow function for "${e.bundlePath}"`,{cwd:dirname(e.bundlePath),input:i,platform:`node`,plugins:[createVirtualModulePlugin({id:i,moduleType:`js`,source:createWorkflowFunctionEntrypointSource({bundlePath:e.bundlePath,pluginModulePaths:n})})],output:{comments:!1,format:`cjs`,sourcemap:!1}});await Promise.all([writeFile(join(e.targetPath,`index.js`),a.code),writeFile(join(e.targetPath,`package.json`),`${JSON.stringify({type:`commonjs`},null,2)}\n`),writeFile(join(e.targetPath,`.vc-config.json`),`${JSON.stringify({environment:createWorkflowFunctionEnvironment({publicRoutePrefix:e.publicRoutePrefix}),handler:`index.js`,launcherType:`Nodejs`,supportsResponseStreaming:!0},null,2)}\n`)])}async function emitBundledWorkflowPluginModules(e){return await Promise.all(e.pluginPaths.map(async(t,n)=>{let i=await buildSingleRolldownChunk(`workflow plugin for "${t}"`,{input:t,platform:`node`,output:{comments:!1,format:`esm`,sourcemap:!1}}),a=`__eve_workflow_plugin_${n}.mjs`;return await writeFile(join(e.targetPath,a),i.code),`./${a}`}))}function createVirtualModulePlugin(e){return{name:`eve-virtual-module`,resolveId(t){return t===e.id?e.id:void 0},load(t){return t===e.id?{code:e.source,moduleType:e.moduleType}:void 0}}}function toRelativeImportPath(e){let t=relative(e.fromDirectoryPath,e.toFilePath).replaceAll(`\\`,`/`);return t.startsWith(`.`)?t:`./${t}`}function normalizeImportSpecifierPath(e){return e.replaceAll(`\\`,`/`)}function createWorkflowFunctionEntrypointSource(t){let n=t.pluginModulePaths.map(e=>normalizeImportSpecifierPath(e)),r=n.length>0;return[`const { POST } = require(${JSON.stringify(`./${basename(t.bundlePath)}`)});`,...r?[`const workflowPluginModulePaths = ${JSON.stringify(n)};`,``,`let workflowPluginPromise;`,``,`async function loadWorkflowPlugins() {`,` if (workflowPluginPromise == null) {`,` workflowPluginPromise = (async () => {`,` for (const pluginPath of workflowPluginModulePaths) {`,` await import(pluginPath);`,` }`,` })();`,` }`,` return await workflowPluginPromise;`,`}`]:[],``,`const DEFAULT_WORKFLOW_REQUEST_ORIGIN = "https://workflow.invalid";`,``,`function getHeader(headers, name) {`,` if (headers === null || headers === undefined) {`,` return undefined;`,` }`,` if (typeof headers.get === "function") {`,` const value = headers.get(name);`,` return typeof value === "string" && value.length > 0 ? value : undefined;`,` }`,` if (typeof headers !== "object") {`,` return undefined;`,` }`,` const record = headers;`,` const lowerName = name.toLowerCase();`,` for (const [key, value] of Object.entries(record)) {`,` if (key.toLowerCase() !== lowerName || value === undefined) {`,` continue;`,` }`,` if (Array.isArray(value)) {`,` return value.find((item) => typeof item === "string" && item.length > 0);`,` }`,` return typeof value === "string" && value.length > 0 ? value : undefined;`,` }`,` return undefined;`,`}`,``,`function createHeaders(headers) {`,` const normalized = new Headers();`,` if (headers === null || headers === undefined) {`,` return normalized;`,` }`,` if (headers instanceof Headers) {`,` return headers;`,` }`,` if (typeof headers.forEach === "function" && typeof headers.entries === "function") {`,` for (const [key, value] of headers.entries()) {`,` normalized.append(key, value);`,` }`,` return normalized;`,` }`,` for (const [key, value] of Object.entries(headers)) {`,` if (value === undefined) {`,` continue;`,` }`,` if (Array.isArray(value)) {`,` for (const item of value) {`,` normalized.append(key, String(item));`,` }`,` continue;`,` }`,` normalized.set(key, String(value));`,` }`,` return normalized;`,`}`,``,`function toAbsoluteWorkflowUrl(request) {`,` const url = typeof request?.url === "string" ? request.url : "/";`,` if (/^https?:\\/\\//.test(url)) {`,` return url;`,` }`,` const host = getHeader(request?.headers, "x-forwarded-host") ?? getHeader(request?.headers, "host");`,` const protocolHeader = getHeader(request?.headers, "x-forwarded-proto");`,` const protocol = protocolHeader === "http" || protocolHeader === "https" ? protocolHeader : "https";`,` const origin = typeof host === "string" && host.length > 0 ? protocol + "://" + host : DEFAULT_WORKFLOW_REQUEST_ORIGIN;`,` return new URL(url, origin).toString();`,`}`,``,`function normalizeWorkflowRequest(request) {`,` if (request instanceof Request) {`,` if (/^https?:\\/\\//.test(request.url)) {`,` return request;`,` }`,` return new Request(toAbsoluteWorkflowUrl(request), request);`,` }`,` const method = typeof request?.method === "string" ? request.method : "GET";`,` const headers = createHeaders(request?.headers);`,` const init = {`,` headers,`,` method,`,` };`,` if (method !== "GET" && method !== "HEAD") {`,` const body = request?.body ?? (request !== null && typeof request === "object" && typeof request.pipe === "function" ? request : undefined);`,` if (body !== undefined) {`,` init.body = body;`,` init.duplex = "half";`,` }`,` }`,` return new Request(toAbsoluteWorkflowUrl(request), init);`,`}`,``,`module.exports = async function handleWorkflowFunctionRequest(requestContext) {`,` const request =`,` requestContext !== null && typeof requestContext === "object" && "req" in requestContext`,` ? requestContext.req`,` : requestContext;`,...r?[` await loadWorkflowPlugins();`]:[],` return await POST(normalizeWorkflowRequest(request));`,`};`,``].join(`
2
- `)}function createRoutedNitroEntrypoint(e){return[`import nitroHandler from ${JSON.stringify(e.delegateImportPath)};`,``,`function invokeNitroHandler(request, context) {`,` if (typeof nitroHandler === "function") {`,` return nitroHandler(request, context);`,` }`,``,` if (nitroHandler !== null && typeof nitroHandler === "object" && "fetch" in nitroHandler) {`,` const fetch = nitroHandler.fetch;`,` if (typeof fetch === "function") {`,` return fetch.call(nitroHandler, request, context);`,` }`,` }`,``,` throw new TypeError("Expected Nitro handler to export a function or an object with fetch(request, context).");`,`}`,``,`const workflowRoutePath = ${JSON.stringify(e.workflowRoutePath)};`,``,`function rewriteRequestToWorkflowRoute(request) {`,` const sourceUrl = new URL(request.url);`,` const routedUrl = new URL(workflowRoutePath, sourceUrl);`,` routedUrl.search = sourceUrl.search;`,` return new Request(routedUrl, request);`,`}`,``,`export default {`,` fetch(request, context) {`,` return invokeNitroHandler(rewriteRequestToWorkflowRoute(request), context);`,` },`,`};`,``].join(`
3
- `)}async function readVercelHandlerPath(e){try{let t=JSON.parse(await readFile(join(e,`.vc-config.json`),`utf8`));if(typeof t.handler==`string`&&t.handler.length>0)return t.handler}catch{}return`index.mjs`}async function retargetNitroFunctionDirectoryToWorkflowRoute(e){let i=await readVercelHandlerPath(e.functionDirectoryPath),a=join(e.functionDirectoryPath,i),o=dirname(a),s=extname(i),c=join(o,`__eve_nitro_handler__${s.length>0?s:`.mjs`}`),l=toRelativeImportPath({fromDirectoryPath:o,toFilePath:c});await rename(a,c),await writeFile(a,createRoutedNitroEntrypoint({delegateImportPath:l,workflowRoutePath:e.workflowRoutePath}))}export{WORKFLOW_BUILDER_DEFERRED_PACKAGES,WORKFLOW_STEP_EXTERNAL_PACKAGES,copyNitroFunctionDirectory,createWorkflowFunctionEnvironment,emitBundledWorkflowFunctionDirectory,normalizeEveVercelFunctionOutput,prepareVercelFunctionDirectory,retargetNitroFunctionDirectoryToWorkflowRoute};
1
+ import{dirname,join,relative}from"node:path";import{cp,mkdir,readFile,readdir,realpath,rename,rm,symlink,writeFile}from"node:fs/promises";import{EVE_SHARED_SERVER_FUNCTION_PATH,isEveVercelFunctionPath,normalizeEveVercelRoutes}from"#internal/workflow-bundle/eve-service-route-output.js";const WORKFLOW_STEP_EXTERNAL_PACKAGES=[`@mongodb-js/zstd`,`just-bash`,`microsandbox`,`node-liblzma`],WORKFLOW_BUILDER_DEFERRED_PACKAGES=[`@chat-adapter/slack`,`chat`];function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function normalizeEveVercelFunctionOutput(e,n={}){let r=join(e,`functions`),i=await prepareSharedEveServerFunction(r);i!==null&&await repointEveFunctionSymlinksInDirectory(r,i),await pruneNonEveFunctionEntries(r,r),await pruneNonEveVercelRoutes(e,n.servicePrefix)}async function prepareSharedEveServerFunction(n){let a=join(n,`__server.func`),o=join(n,EVE_SHARED_SERVER_FUNCTION_PATH),c;try{c=await realpath(a)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return null;throw e}let l=`${o}.eve-staging`;return await mkdir(dirname(o),{recursive:!0}),await rm(l,{force:!0,recursive:!0}),await cp(c,l,{dereference:!0,recursive:!0}),await rm(o,{force:!0,recursive:!0}),await rename(l,o),o}async function repointEveFunctionSymlinksInDirectory(e,r,i=e){let a;try{a=await readdir(e,{withFileTypes:!0})}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}await Promise.all(a.map(async a=>{let o=join(e,a.name),s=normalizeVercelOutputPath(relative(i,o));if(a.isSymbolicLink()){a.name.endsWith(`.func`)&&isEveVercelFunctionPath(s)&&await repointFunctionSymlink(o,r);return}a.isDirectory()&&!a.name.endsWith(`.func`)&&await repointEveFunctionSymlinksInDirectory(o,r,i)}))}async function repointFunctionSymlink(t,r){await rm(t,{force:!0,recursive:!0}),await symlink(normalizeVercelOutputPath(relative(dirname(t),r)),t,`dir`)}async function pruneNonEveFunctionEntries(e,r){let i;try{i=await readdir(r,{withFileTypes:!0})}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}await Promise.all(i.map(async i=>{let a=join(r,i.name),o=normalizeVercelOutputPath(relative(e,a));if(i.name.endsWith(`.func`)){isEveVercelFunctionPath(o)||await rm(a,{force:!0,recursive:!0});return}i.isDirectory()&&await pruneNonEveFunctionEntries(e,a)}))}async function pruneNonEveVercelRoutes(e,n){let r=join(e,`config.json`),i;try{i=JSON.parse(await readFile(r,`utf8`))}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}!isRecord(i)||!Array.isArray(i.routes)||(i.routes=normalizeEveVercelRoutes(i.routes,n),await writeFile(r,`${JSON.stringify(i,null,2)}\n`))}function normalizeVercelOutputPath(e){return e.replaceAll(`\\`,`/`)}export{WORKFLOW_BUILDER_DEFERRED_PACKAGES,WORKFLOW_STEP_EXTERNAL_PACKAGES,normalizeEveVercelFunctionOutput};
@@ -21,13 +21,6 @@ export type WorkflowManifest = {
21
21
  };
22
22
  };
23
23
  };
24
- export declare function createEveWorkflowQueueTrigger(agentName: string): {
25
- type: "queue/v2beta";
26
- topic: string;
27
- consumer: string;
28
- retryAfterSeconds: number;
29
- initialDelaySeconds: number;
30
- };
31
24
  export declare function applyWorkflowTransform(filename: string, source: string, mode: "workflow" | "step" | "client" | false, absolutePath?: string, projectRoot?: string, stableWorkflowNames?: ReadonlySet<string>): Promise<{
32
25
  code: string;
33
26
  workflowManifest: WorkflowManifest;
@@ -1 +1 @@
1
- import{transformWorkflowDirectives}from"./workflow-transformer.js";import{existsSync,readFileSync}from"node:fs";import{dirname,isAbsolute,join,relative,resolve,sep}from"node:path";import{readFile}from"node:fs/promises";import{STABLE_WORKFLOW_NAMES}from"#execution/workflow-runtime.js";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{deriveEveWorkflowQueueTopic}from"#internal/workflow/queue-namespace.js";function createEveWorkflowQueueTrigger(e){return{type:`queue/v2beta`,topic:deriveEveWorkflowQueueTopic(e),consumer:`default`,retryAfterSeconds:5,initialDelaySeconds:0}}const packageJsonCache=new Map,projectDepsCache=new Map;async function applyWorkflowTransform(t,n,r,o,s,c=STABLE_WORKFLOW_NAMES){let l=s??process.cwd(),{moduleSpecifier:u,stableModuleSpecifier:d}=resolveModuleSpecifier(o===void 0?isAbsolute(t)?t:join(l,t):o,l);return transformWorkflowDirectives({filename:t,mode:r,moduleSpecifier:u,source:n,stableModuleSpecifier:d,stableWorkflowNames:c})}function detectWorkflowPatterns(e){return{hasSerde:e.includes(`workflow.serde`)||e.includes(`@serde`)||e.includes(`workflowSerde`)||e.includes(`__workflow_serde`),hasUseStep:/["']use step["']/.test(e),hasUseWorkflow:/["']use workflow["']/.test(e)}}function getImportPath(e,t){let n=isInNodeModules(e),r=!n&&isWorkspacePackage(e,t);if(n||r){let n=findPackageJson(e);if(n!==null){let i=getProjectDependencies(t).has(n.name);if(!(r||i))return{importPath:toRelativeImportPath(e,t),isPackage:!1};let a=resolveExportSubpath(e,n);return a?{importPath:`${n.name}${a}`,isPackage:!0}:isRootEntrypointFile(e,n)?{importPath:n.name,isPackage:!0}:{importPath:toRelativeImportPath(e,t),isPackage:!1}}}return{importPath:toRelativeImportPath(e,t),isPackage:!1}}function resolveModuleSpecifier(e,t){let n=isInNodeModules(e),r=!n&&isWorkspacePackage(e,t),i=findPackageJson(e);if(!n&&!r)return{moduleSpecifier:void 0,stableModuleSpecifier:i?.name===EVE_PACKAGE_NAME?EVE_PACKAGE_NAME:void 0};if(i===null)return{moduleSpecifier:void 0,stableModuleSpecifier:void 0};let a=resolveExportSubpath(e,i),o=a?`${i.name}${a}`:i.name;return{moduleSpecifier:`${o}@${i.version}`,stableModuleSpecifier:o}}function findPackageJson(e){let i=dirname(e),o=[];for(;i!==dirname(i);){let e=packageJsonCache.get(i);if(e!==void 0){for(let t of o)packageJsonCache.set(t,e);return e}o.push(i);let s=join(i,`package.json`);if(existsSync(s))try{let e=JSON.parse(readFileSync(s,`utf8`));if(typeof e.name==`string`&&typeof e.version==`string`){let t={dir:i,exports:e.exports,main:e.main,module:e.module,name:e.name,version:e.version};packageJsonCache.set(i,t);for(let e of o)packageJsonCache.set(e,t);return t}}catch{}i=dirname(i)}for(let e of o)packageJsonCache.set(e,null);return null}function resolveExportSubpath(e,t){if(t.exports===null||typeof t.exports!=`object`||Array.isArray(t.exports))return``;let n=e.replace(/\\/g,`/`),r=t.dir.replace(/\\/g,`/`),i=n.startsWith(`${r}/`)?`./${n.substring(r.length+1)}`:null;if(i===null)return``;for(let[e,n]of Object.entries(t.exports)){let t=resolveExportTarget(n);if(t!==null&&normalizeExportPath(t)===i)return e===`.`?``:e.substring(1)}return``}function resolveExportTarget(e){if(typeof e==`string`)return e;if(Array.isArray(e)){for(let t of e){let e=resolveExportTarget(t);if(e!==null)return e}return null}if(typeof e==`object`&&e)for(let t of[`workflow`,`default`,`require`,`import`,`node`]){let n=e[t],r=resolveExportTarget(n);if(r!==null)return r}return null}function normalizeExportPath(e){return e.startsWith(`./`)?e:`./${e}`}function isInNodeModules(e){return e.split(sep).join(`/`).includes(`/node_modules/`)}function getProjectDependencies(e){let r=projectDepsCache.get(e);if(r!==void 0)return r;let i=new Set,o=join(e,`package.json`);if(existsSync(o))try{let e=JSON.parse(readFileSync(o,`utf8`));for(let t of[`dependencies`,`devDependencies`,`peerDependencies`,`optionalDependencies`]){let n=e[t];if(typeof n==`object`&&n&&!Array.isArray(n))for(let e of Object.keys(n))i.add(e)}}catch{}return projectDepsCache.set(e,i),i}function isWorkspacePackage(e,t){if(isInNodeModules(e))return!1;let n=findPackageJson(e);return n===null||resolve(n.dir)===resolve(t)?!1:getProjectDependencies(t).has(n.name)}function toRelativeImportPath(e,t){let n=t.replace(/\\/g,`/`),r=e.replace(/\\/g,`/`),i=r.startsWith(`${n}/`)?r.substring(n.length+1):relative(t,e).replace(/\\/g,`/`);return i.startsWith(`.`)||(i=`./${i}`),i}function hasRootExport(e){if(typeof e==`string`||Array.isArray(e))return!0;if(typeof e!=`object`||!e)return!1;let t=Object.keys(e);return t.length>0&&t.every(e=>!e.startsWith(`.`))?!0:`.`in e}function normalizePackageTargetPath(e){let t=e.replace(/\\/g,`/`);return t.startsWith(`./`)?t.substring(2):t.startsWith(`/`)?t.substring(1):t}function isRootEntrypointFile(e,t){let n=e.replace(/\\/g,`/`),r=t.dir.replace(/\\/g,`/`);if(!n.startsWith(`${r}/`))return!1;let i=n.substring(r.length+1);if(t.exports!==void 0){let e;if(t.exports!==null&&typeof t.exports==`object`&&`.`in t.exports)e=t.exports[`.`];else if(hasRootExport(t.exports))e=t.exports;else return!1;let n=resolveExportTarget(e);return n!==null&&normalizePackageTargetPath(n)===i}return[t.module,t.main,`index.js`,`index.mjs`,`index.cjs`,`index.ts`,`index.mts`,`index.cts`].flatMap(e=>typeof e==`string`?[normalizePackageTargetPath(e)]:[]).includes(i)}async function readSourceFile(e){return await readFile(e,`utf8`)}export{applyWorkflowTransform,createEveWorkflowQueueTrigger,detectWorkflowPatterns,getImportPath,readSourceFile};
1
+ import{transformWorkflowDirectives}from"./workflow-transformer.js";import{existsSync,readFileSync}from"node:fs";import{dirname,isAbsolute,join,relative,resolve,sep}from"node:path";import{readFile}from"node:fs/promises";import{STABLE_WORKFLOW_NAMES}from"#execution/workflow-runtime.js";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";const packageJsonCache=new Map,projectDepsCache=new Map;async function applyWorkflowTransform(t,n,r,o,s,c=STABLE_WORKFLOW_NAMES){let l=s??process.cwd(),{moduleSpecifier:u,stableModuleSpecifier:d}=resolveModuleSpecifier(o===void 0?isAbsolute(t)?t:join(l,t):o,l);return transformWorkflowDirectives({filename:t,mode:r,moduleSpecifier:u,source:n,stableModuleSpecifier:d,stableWorkflowNames:c})}function detectWorkflowPatterns(e){return{hasSerde:e.includes(`workflow.serde`)||e.includes(`@serde`)||e.includes(`workflowSerde`)||e.includes(`__workflow_serde`),hasUseStep:/["']use step["']/.test(e),hasUseWorkflow:/["']use workflow["']/.test(e)}}function getImportPath(e,t){let n=isInNodeModules(e),r=!n&&isWorkspacePackage(e,t);if(n||r){let n=findPackageJson(e);if(n!==null){let i=getProjectDependencies(t).has(n.name);if(!(r||i))return{importPath:toRelativeImportPath(e,t),isPackage:!1};let a=resolveExportSubpath(e,n);return a?{importPath:`${n.name}${a}`,isPackage:!0}:isRootEntrypointFile(e,n)?{importPath:n.name,isPackage:!0}:{importPath:toRelativeImportPath(e,t),isPackage:!1}}}return{importPath:toRelativeImportPath(e,t),isPackage:!1}}function resolveModuleSpecifier(e,t){let n=isInNodeModules(e),r=!n&&isWorkspacePackage(e,t),i=findPackageJson(e);if(!n&&!r)return{moduleSpecifier:void 0,stableModuleSpecifier:i?.name===EVE_PACKAGE_NAME?EVE_PACKAGE_NAME:void 0};if(i===null)return{moduleSpecifier:void 0,stableModuleSpecifier:void 0};let a=resolveExportSubpath(e,i),o=a?`${i.name}${a}`:i.name;return{moduleSpecifier:`${o}@${i.version}`,stableModuleSpecifier:o}}function findPackageJson(e){let i=dirname(e),o=[];for(;i!==dirname(i);){let e=packageJsonCache.get(i);if(e!==void 0){for(let t of o)packageJsonCache.set(t,e);return e}o.push(i);let s=join(i,`package.json`);if(existsSync(s))try{let e=JSON.parse(readFileSync(s,`utf8`));if(typeof e.name==`string`&&typeof e.version==`string`){let t={dir:i,exports:e.exports,main:e.main,module:e.module,name:e.name,version:e.version};packageJsonCache.set(i,t);for(let e of o)packageJsonCache.set(e,t);return t}}catch{}i=dirname(i)}for(let e of o)packageJsonCache.set(e,null);return null}function resolveExportSubpath(e,t){if(t.exports===null||typeof t.exports!=`object`||Array.isArray(t.exports))return``;let n=e.replace(/\\/g,`/`),r=t.dir.replace(/\\/g,`/`),i=n.startsWith(`${r}/`)?`./${n.substring(r.length+1)}`:null;if(i===null)return``;for(let[e,n]of Object.entries(t.exports)){let t=resolveExportTarget(n);if(t!==null&&normalizeExportPath(t)===i)return e===`.`?``:e.substring(1)}return``}function resolveExportTarget(e){if(typeof e==`string`)return e;if(Array.isArray(e)){for(let t of e){let e=resolveExportTarget(t);if(e!==null)return e}return null}if(typeof e==`object`&&e)for(let t of[`workflow`,`default`,`require`,`import`,`node`]){let n=e[t],r=resolveExportTarget(n);if(r!==null)return r}return null}function normalizeExportPath(e){return e.startsWith(`./`)?e:`./${e}`}function isInNodeModules(e){return e.split(sep).join(`/`).includes(`/node_modules/`)}function getProjectDependencies(e){let r=projectDepsCache.get(e);if(r!==void 0)return r;let i=new Set,o=join(e,`package.json`);if(existsSync(o))try{let e=JSON.parse(readFileSync(o,`utf8`));for(let t of[`dependencies`,`devDependencies`,`peerDependencies`,`optionalDependencies`]){let n=e[t];if(typeof n==`object`&&n&&!Array.isArray(n))for(let e of Object.keys(n))i.add(e)}}catch{}return projectDepsCache.set(e,i),i}function isWorkspacePackage(e,t){if(isInNodeModules(e))return!1;let n=findPackageJson(e);return n===null||resolve(n.dir)===resolve(t)?!1:getProjectDependencies(t).has(n.name)}function toRelativeImportPath(e,t){let n=t.replace(/\\/g,`/`),r=e.replace(/\\/g,`/`),i=r.startsWith(`${n}/`)?r.substring(n.length+1):relative(t,e).replace(/\\/g,`/`);return i.startsWith(`.`)||(i=`./${i}`),i}function hasRootExport(e){if(typeof e==`string`||Array.isArray(e))return!0;if(typeof e!=`object`||!e)return!1;let t=Object.keys(e);return t.length>0&&t.every(e=>!e.startsWith(`.`))?!0:`.`in e}function normalizePackageTargetPath(e){let t=e.replace(/\\/g,`/`);return t.startsWith(`./`)?t.substring(2):t.startsWith(`/`)?t.substring(1):t}function isRootEntrypointFile(e,t){let n=e.replace(/\\/g,`/`),r=t.dir.replace(/\\/g,`/`);if(!n.startsWith(`${r}/`))return!1;let i=n.substring(r.length+1);if(t.exports!==void 0){let e;if(t.exports!==null&&typeof t.exports==`object`&&`.`in t.exports)e=t.exports[`.`];else if(hasRootExport(t.exports))e=t.exports;else return!1;let n=resolveExportTarget(e);return n!==null&&normalizePackageTargetPath(n)===i}return[t.module,t.main,`index.js`,`index.mjs`,`index.cjs`,`index.ts`,`index.mts`,`index.cts`].flatMap(e=>typeof e==`string`?[normalizePackageTargetPath(e)]:[]).includes(i)}async function readSourceFile(e){return await readFile(e,`utf8`)}export{applyWorkflowTransform,detectWorkflowPatterns,getImportPath,readSourceFile};