eve 0.24.3 → 0.24.4

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 (91) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/dist/src/channel/adapter.d.ts +4 -2
  3. package/dist/src/channel/adapter.js +1 -1
  4. package/dist/src/channel/session.d.ts +5 -1
  5. package/dist/src/channel/types.d.ts +7 -6
  6. package/dist/src/chunks/{use-eve-agent-CFBTHlPx.js → use-eve-agent-BP9FpQsJ.js} +15 -4
  7. package/dist/src/chunks/{use-eve-agent-dEGV09g_.js → use-eve-agent-Dwa2j1wE.js} +15 -4
  8. package/dist/src/cli/dev/tui/runner.d.ts +2 -2
  9. package/dist/src/cli/dev/tui/runner.js +1 -1
  10. package/dist/src/client/index.d.ts +1 -1
  11. package/dist/src/client/message-reducer.js +1 -1
  12. package/dist/src/client/open-stream.js +1 -1
  13. package/dist/src/client/session-utils.js +1 -1
  14. package/dist/src/client/session.d.ts +4 -2
  15. package/dist/src/client/session.js +1 -1
  16. package/dist/src/client/types.d.ts +3 -2
  17. package/dist/src/discover/filesystem.js +1 -1
  18. package/dist/src/execution/durable-session-migrations/turn-workflow.d.ts +1 -0
  19. package/dist/src/execution/durable-session-migrations/turn-workflow.js +1 -1
  20. package/dist/src/execution/next-driver-action.d.ts +7 -0
  21. package/dist/src/execution/settle-cancelled-turn-step.d.ts +16 -0
  22. package/dist/src/execution/settle-cancelled-turn-step.js +1 -0
  23. package/dist/src/execution/subagent-hitl-proxy.js +1 -1
  24. package/dist/src/execution/terminal-session-failure-step.d.ts +6 -0
  25. package/dist/src/execution/terminal-session-failure-step.js +1 -0
  26. package/dist/src/execution/turn-cancellation-control.d.ts +40 -0
  27. package/dist/src/execution/turn-cancellation-control.js +1 -0
  28. package/dist/src/execution/turn-dispatch.d.ts +14 -1
  29. package/dist/src/execution/turn-dispatch.js +1 -1
  30. package/dist/src/execution/turn-execution-cursor.d.ts +2 -1
  31. package/dist/src/execution/turn-execution-cursor.js +1 -1
  32. package/dist/src/execution/turn-workflow.d.ts +9 -1
  33. package/dist/src/execution/turn-workflow.js +1 -1
  34. package/dist/src/execution/workflow-entry.js +1 -1
  35. package/dist/src/execution/workflow-steps.d.ts +8 -6
  36. package/dist/src/execution/workflow-steps.js +1 -1
  37. package/dist/src/harness/active-turn-id.d.ts +11 -0
  38. package/dist/src/harness/active-turn-id.js +1 -0
  39. package/dist/src/harness/cancelled-turn-emission.d.ts +11 -0
  40. package/dist/src/harness/cancelled-turn-emission.js +1 -0
  41. package/dist/src/harness/emission.d.ts +4 -2
  42. package/dist/src/harness/emission.js +1 -1
  43. package/dist/src/harness/proxy-input-requests.d.ts +5 -0
  44. package/dist/src/harness/proxy-input-requests.js +1 -1
  45. package/dist/src/harness/session-limit-enforcement.js +1 -1
  46. package/dist/src/harness/tool-loop.js +2 -2
  47. package/dist/src/internal/application/compiled-artifacts.js +3 -2
  48. package/dist/src/internal/application/package.js +1 -1
  49. package/dist/src/internal/authored-module-loader.js +2 -2
  50. package/dist/src/internal/bundler/nitro-rolldown.d.ts +18 -2
  51. package/dist/src/internal/bundler/nitro-rolldown.js +1 -1
  52. package/dist/src/internal/nitro/dev-runtime-source-snapshot-copy.js +1 -1
  53. package/dist/src/internal/nitro/host/dev-authored-source-watcher.js +1 -1
  54. package/dist/src/internal/workflow/development-world-client.js +1 -1
  55. package/dist/src/internal/workflow/development-world-server.js +1 -1
  56. package/dist/src/internal/workflow/local-world-data-directory.d.ts +2 -0
  57. package/dist/src/internal/workflow/local-world-data-directory.js +1 -0
  58. package/dist/src/internal/workflow-bundle/builder-support.js +3 -3
  59. package/dist/src/internal/workflow-bundle/builder.js +2 -2
  60. package/dist/src/internal/workflow-bundle/vercel-workflow-output.js +1 -1
  61. package/dist/src/protocol/message.d.ts +23 -3
  62. package/dist/src/protocol/message.js +2 -2
  63. package/dist/src/public/channels/discord/discordChannel.d.ts +1 -0
  64. package/dist/src/public/channels/eve.js +1 -1
  65. package/dist/src/public/channels/github/githubChannel.d.ts +1 -0
  66. package/dist/src/public/channels/linear/linearChannel.d.ts +1 -0
  67. package/dist/src/public/channels/slack/slackChannel.d.ts +1 -0
  68. package/dist/src/public/channels/teams/teamsChannel.d.ts +1 -0
  69. package/dist/src/public/channels/telegram/telegramChannel.d.ts +1 -0
  70. package/dist/src/public/channels/twilio/twilioChannel.d.ts +1 -0
  71. package/dist/src/public/definitions/channel.d.ts +5 -4
  72. package/dist/src/public/definitions/channel.js +1 -1
  73. package/dist/src/runtime/agent/mock-model-adapter.js +1 -1
  74. package/dist/src/services/dev-client/runtime-artifacts.d.ts +2 -2
  75. package/dist/src/services/dev-client.d.ts +10 -18
  76. package/dist/src/services/dev-client.js +1 -1
  77. package/dist/src/setup/scaffold/create/extension.js +0 -1
  78. package/dist/src/setup/scaffold/create/project.js +1 -3
  79. package/dist/src/shared/continuation-token.d.ts +2 -0
  80. package/dist/src/shared/continuation-token.js +1 -0
  81. package/dist/src/svelte/index.js +1 -1
  82. package/dist/src/svelte/use-eve-agent.js +1 -1
  83. package/dist/src/vue/index.js +1 -1
  84. package/dist/src/vue/use-eve-agent.js +1 -1
  85. package/docs/concepts/execution-model-and-durability.md +1 -1
  86. package/docs/concepts/sessions-runs-and-streaming.md +13 -4
  87. package/docs/guides/client/continuations.mdx +14 -1
  88. package/docs/guides/client/streaming.mdx +14 -1
  89. package/docs/guides/deployment.md +1 -1
  90. package/docs/reference/cli.md +1 -1
  91. package/package.json +1 -1
@@ -1,7 +1,8 @@
1
- import{getWorldImport}from"../../node_modules/.pnpm/@workflow_utils@5.0.0-beta.6/node_modules/@workflow/utils/dist/world-target.js";import"../../node_modules/.pnpm/@workflow_utils@5.0.0-beta.6/node_modules/@workflow/utils/dist/index.js";import{resolvePackageCompiledFilePath,resolvePackageSourceFilePath}from"#internal/application/package.js";import{existsSync}from"node:fs";import{join}from"node:path";import{copyFile,mkdir,writeFile}from"node:fs/promises";import{createCompiledModuleMapSource}from"#compiler/module-map.js";import{stringifyEsmImportSpecifier}from"#internal/application/import-specifier.js";import{readMaterializedAuthoredModuleIndex}from"#internal/materialized-authored-modules.js";import{usesParentDevelopmentWorkflowWorld}from"#internal/workflow/development-world-protocol.js";async function writeCompiledArtifactsFiles(e){let t=join(e.outDir,`compiled-artifacts-bootstrap.mjs`),r=join(e.outDir,`compiled-artifacts-instrumentation.mjs`),a=join(e.outDir,`compiled-artifacts-workflow-world.mjs`),c=resolveInstrumentationModule(e.compileResult.manifest.agentRoot);await mkdir(e.outDir,{recursive:!0}),await writeFile(t,await createCompiledArtifactsBootstrapSource({compileResult:e.compileResult,installModulePath:resolvePackageSourceFilePath(`src/runtime/loaders/bundled-artifacts.ts`),moduleMapPath:t,metadata:e.compileResult.metadata})),await writeFile(a,createWorkflowWorldPluginSource({compiledArtifactsBootstrapPath:t,configuredWorld:e.compileResult.manifest.config.experimental?.workflow?.world,defaultWorld:e.defaultWorkflowWorld})),c!==void 0&&await writeFile(r,createInstrumentationPluginSource({agentName:e.compileResult.manifest.config.name,instrumentationPath:c,registerConfigPath:resolvePackageSourceFilePath(`src/harness/instrumentation-config.ts`)}));let l={bootstrapPath:t,workflowWorldPluginPath:a};return c!==void 0&&(l.instrumentationPluginPath=r,l.instrumentationSourcePath=c),l}async function writeDevelopmentCompiledArtifactsFiles(e){let t=join(e.outDir,`compiled-artifacts-bootstrap.mjs`),r=join(e.outDir,`compiled-artifacts-instrumentation.mjs`),c=join(e.outDir,`compiled-artifacts-instrumentation-source.mjs`),l=join(e.outDir,`compiled-artifacts-workflow-world.mjs`),u=await readMaterializedAuthoredModuleIndex(e.runtimeAppRoot);if(u===void 0)throw Error(`Development generation at "${e.runtimeAppRoot}" is not materialized.`);await mkdir(e.outDir,{recursive:!0}),await writeFile(t,createDevelopmentCompiledArtifactsBootstrapSource(e.compileResult.manifest.config.name)),await writeFile(l,createDevelopmentWorkflowWorldPluginSource({compiledArtifactsBootstrapPath:t,configuredWorld:e.compileResult.manifest.config.experimental?.workflow?.world}));let d={bootstrapPath:t,workflowWorldPluginPath:l};return u.instrumentation!==void 0&&(await copyFile(join(e.runtimeAppRoot,`.eve`,`compile`,u.instrumentation),c),await writeFile(r,createInstrumentationPluginSource({agentName:e.compileResult.manifest.config.name,instrumentationPath:c,registerConfigPath:resolvePackageSourceFilePath(`src/harness/instrumentation-config.ts`)})),d.instrumentationPluginPath=r,d.instrumentationSourcePath=c),d}function createDevelopmentCompiledArtifactsBootstrapSource(e){return[`// Generated by eve. Do not edit by hand.`,`import { installEveWorkflowQueueNamespace } from ${stringifyEsmImportSpecifier(resolvePackageSourceFilePath(`src/internal/workflow/queue-namespace.ts`))};`,``,`installEveWorkflowQueueNamespace(${JSON.stringify(e)});`,``,`export default function installDevelopmentCompiledArtifactsPlugin() {}`,``].join(`
1
+ import{getWorldImport}from"../../node_modules/.pnpm/@workflow_utils@5.0.0-beta.6/node_modules/@workflow/utils/dist/world-target.js";import"../../node_modules/.pnpm/@workflow_utils@5.0.0-beta.6/node_modules/@workflow/utils/dist/index.js";import{resolvePackageCompiledFilePath,resolvePackageSourceFilePath}from"#internal/application/package.js";import{existsSync}from"node:fs";import{join}from"node:path";import{copyFile,mkdir,writeFile}from"node:fs/promises";import{createCompiledModuleMapSource}from"#compiler/module-map.js";import{stringifyEsmImportSpecifier}from"#internal/application/import-specifier.js";import{readMaterializedAuthoredModuleIndex}from"#internal/materialized-authored-modules.js";import{usesParentDevelopmentWorkflowWorld}from"#internal/workflow/development-world-protocol.js";async function writeCompiledArtifactsFiles(e){let t=join(e.outDir,`compiled-artifacts-bootstrap.mjs`),r=join(e.outDir,`compiled-artifacts-instrumentation.mjs`),a=join(e.outDir,`compiled-artifacts-workflow-world.mjs`),c=resolveInstrumentationModule(e.compileResult.manifest.agentRoot);await mkdir(e.outDir,{recursive:!0}),await writeFile(t,await createCompiledArtifactsBootstrapSource({compileResult:e.compileResult,installModulePath:resolvePackageSourceFilePath(`src/runtime/loaders/bundled-artifacts.ts`),moduleMapPath:t,metadata:e.compileResult.metadata})),await writeFile(a,createWorkflowWorldPluginSource({compiledArtifactsBootstrapPath:t,configuredWorld:e.compileResult.manifest.config.experimental?.workflow?.world,defaultWorld:e.defaultWorkflowWorld})),c!==void 0&&await writeFile(r,createInstrumentationPluginSource({agentName:e.compileResult.manifest.config.name,instrumentationPath:c,registerConfigPath:resolvePackageSourceFilePath(`src/harness/instrumentation-config.ts`)}));let l={bootstrapPath:t,workflowWorldPluginPath:a};return c!==void 0&&(l.instrumentationPluginPath=r,l.instrumentationSourcePath=c),l}async function writeDevelopmentCompiledArtifactsFiles(e){let t=join(e.outDir,`compiled-artifacts-bootstrap.mjs`),r=join(e.outDir,`compiled-artifacts-instrumentation.mjs`),c=join(e.outDir,`compiled-artifacts-instrumentation-source.mjs`),l=join(e.outDir,`compiled-artifacts-workflow-world.mjs`),d=await readMaterializedAuthoredModuleIndex(e.runtimeAppRoot);if(d===void 0)throw Error(`Development generation at "${e.runtimeAppRoot}" is not materialized.`);await mkdir(e.outDir,{recursive:!0}),await writeFile(t,createDevelopmentCompiledArtifactsBootstrapSource(e.compileResult.manifest.config.name)),await writeFile(l,createDevelopmentWorkflowWorldPluginSource({compiledArtifactsBootstrapPath:t,configuredWorld:e.compileResult.manifest.config.experimental?.workflow?.world}));let f={bootstrapPath:t,workflowWorldPluginPath:l};return d.instrumentation!==void 0&&(await copyFile(join(e.runtimeAppRoot,`.eve`,`compile`,d.instrumentation),c),await writeFile(r,createInstrumentationPluginSource({agentName:e.compileResult.manifest.config.name,instrumentationPath:c,registerConfigPath:resolvePackageSourceFilePath(`src/harness/instrumentation-config.ts`)})),f.instrumentationPluginPath=r,f.instrumentationSourcePath=c),f}function createDevelopmentCompiledArtifactsBootstrapSource(e){return[`// Generated by eve. Do not edit by hand.`,`import { installEveWorkflowQueueNamespace } from ${stringifyEsmImportSpecifier(resolvePackageSourceFilePath(`src/internal/workflow/queue-namespace.ts`))};`,``,`installEveWorkflowQueueNamespace(${JSON.stringify(e)});`,``,`export default function installDevelopmentCompiledArtifactsPlugin() {}`,``].join(`
2
2
  `)}const INSTRUMENTATION_EXTENSIONS=[`.ts`,`.mts`,`.js`,`.mjs`];function resolveInstrumentationModule(e){for(let t of INSTRUMENTATION_EXTENSIONS){let n=join(e,`instrumentation${t}`);if(existsSync(n))return n}}function stripCompiledModuleMapExports(e){return e.replace(/^export const moduleMap = /m,`const moduleMap = `).replace(/\nexport default moduleMap;\n?$/,`
3
3
  `)}async function createCompiledArtifactsBootstrapSource(e){let t=e.compileResult.manifest.config.name,r=stripCompiledModuleMapExports(createCompiledModuleMapSource({importSpecifierStyle:`absolute`,manifest:e.compileResult.manifest,moduleMapPath:e.moduleMapPath})).trim();return[`// Generated by eve. Do not edit by hand.`,`import { installBundledCompiledArtifacts } from ${stringifyEsmImportSpecifier(e.installModulePath)};`,`import { installEveWorkflowQueueNamespace } from ${stringifyEsmImportSpecifier(resolvePackageSourceFilePath(`src/internal/workflow/queue-namespace.ts`))};`,``,`installEveWorkflowQueueNamespace(${JSON.stringify(t)});`,``,r,``,`const metadata = ${JSON.stringify(e.metadata,null,2)};`,``,`const manifest = ${JSON.stringify(e.compileResult.manifest,null,2)};`,``,`export function installCompiledArtifactsBootstrap() {`,` installBundledCompiledArtifacts({`,` manifest,`,` metadata,`,` moduleMap,`,` });`,`}`,``,`installCompiledArtifactsBootstrap();`,``,`// Default export satisfies the Nitro plugin contract so this file`,`// can be used directly as a Nitro plugin without a separate wrapper.`,`export default function installCompiledArtifactsPlugin() {`,` // Already installed on import above.`,`}`,``].join(`
4
- `)}function createWorkflowWorldPluginSource(r){let i=getWorldImport({WORKFLOW_TARGET_WORLD:r.configuredWorld??r.defaultWorld}),a=i===`@workflow/world-local`||i===`@workflow/world-vercel`?resolvePackageCompiledFilePath(`src/compiled/${i}/index.js`):i,o=resolvePackageCompiledFilePath(`src/compiled/@workflow/core/runtime.js`),s=resolvePackageSourceFilePath(`src/internal/workflow/validate-world.ts`);return[`// Generated by eve. Do not edit by hand.`,`import ${stringifyEsmImportSpecifier(r.compiledArtifactsBootstrapPath)};`,`import * as workflowWorldModule from ${stringifyEsmImportSpecifier(a)};`,`import { createWorldFromModule, getWorld, setWorld } from ${stringifyEsmImportSpecifier(o)};`,`import { validateWorkflowWorld } from ${stringifyEsmImportSpecifier(s)};`,``,`const workflowWorld = await createWorldFromModule(workflowWorldModule);`,`validateWorkflowWorld({ packageName: ${JSON.stringify(r.configuredWorld)}, world: workflowWorld });`,`setWorld(workflowWorld);`,`await getWorld();`,`await workflowWorld.start?.();`,``,`export default function installWorkflowWorldPlugin() {}`,``].join(`
4
+ `)}function createWorkflowWorldPluginSource(r){let i=getWorldImport({WORKFLOW_TARGET_WORLD:r.configuredWorld??r.defaultWorld}),a=i===`@workflow/world-local`||i===`@workflow/world-vercel`?resolvePackageCompiledFilePath(`src/compiled/${i}/index.js`):i,o=resolvePackageCompiledFilePath(`src/compiled/@workflow/core/runtime.js`),s=resolvePackageSourceFilePath(`src/internal/workflow/validate-world.ts`),c=i===`@workflow/world-local`?resolvePackageSourceFilePath(`src/internal/workflow/local-world-data-directory.ts`):void 0,u=c===void 0?`const workflowWorld = await createWorldFromModule(workflowWorldModule);`:[`const workflowWorld = await workflowWorldModule.createWorld({`,` dataDir: resolveLocalWorkflowWorldDataDirectory(process.cwd()),`,`});`].join(`
5
+ `),d=c===void 0?`createWorldFromModule, getWorld, setWorld`:`getWorld, setWorld`;return[`// Generated by eve. Do not edit by hand.`,`import ${stringifyEsmImportSpecifier(r.compiledArtifactsBootstrapPath)};`,`import * as workflowWorldModule from ${stringifyEsmImportSpecifier(a)};`,...c===void 0?[]:[`import { resolveLocalWorkflowWorldDataDirectory } from ${stringifyEsmImportSpecifier(c)};`],`import { ${d} } from ${stringifyEsmImportSpecifier(o)};`,`import { validateWorkflowWorld } from ${stringifyEsmImportSpecifier(s)};`,``,u,`validateWorkflowWorld({ packageName: ${JSON.stringify(r.configuredWorld)}, world: workflowWorld });`,`setWorld(workflowWorld);`,`await getWorld();`,`await workflowWorld.start?.();`,``,`export default function installWorkflowWorldPlugin() {}`,``].join(`
5
6
  `)}function createDevelopmentWorkflowWorldPluginSource(e){if(!usesParentDevelopmentWorkflowWorld(e.configuredWorld))return createWorkflowWorldPluginSource({...e,defaultWorld:`local`});let r=resolvePackageCompiledFilePath(`src/compiled/@workflow/core/runtime.js`),i=resolvePackageSourceFilePath(`src/internal/workflow/development-world-client.ts`);return[`// Generated by eve. Do not edit by hand.`,`import ${stringifyEsmImportSpecifier(e.compiledArtifactsBootstrapPath)};`,`import { getWorld, setWorld } from ${stringifyEsmImportSpecifier(r)};`,`import { createDevelopmentWorkflowWorld } from ${stringifyEsmImportSpecifier(i)};`,``,`setWorld(createDevelopmentWorkflowWorld());`,`await getWorld();`,``,`export default function installDevelopmentWorkflowWorldPlugin() {}`,``].join(`
6
7
  `)}function createInstrumentationPluginSource(e){return[`// Generated by eve. Do not edit by hand.`,`import * as instrumentationModule from ${stringifyEsmImportSpecifier(e.instrumentationPath)};`,`import { registerInstrumentationConfig } from ${stringifyEsmImportSpecifier(e.registerConfigPath)};`,``,`if (instrumentationModule.default != null) {`,` registerInstrumentationConfig(instrumentationModule.default, { agentName: ${JSON.stringify(e.agentName)} });`,`}`,``,`// Default export satisfies the Nitro plugin contract so this file`,`// can be used directly as a Nitro plugin without a separate wrapper.`,`export default function installInstrumentationPlugin() {}`,``].join(`
7
8
  `)}export{createCompiledArtifactsBootstrapSource,createDevelopmentWorkflowWorldPluginSource,createWorkflowWorldPluginSource,writeCompiledArtifactsFiles,writeDevelopmentCompiledArtifactsFiles};
@@ -1 +1 @@
1
- import{createRequire}from"node:module";import{existsSync,readFileSync,realpathSync}from"node:fs";import{basename,dirname,join}from"node:path";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{fileURLToPath}from"node:url";let cachedPackageInfo;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.24.3`,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{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{fileURLToPath}from"node:url";let cachedPackageInfo;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.24.4`,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,4 @@
1
- import{expectObjectRecord}from"#internal/authored-module.js";import{existsSync,mkdirSync,statSync,writeFileSync}from"node:fs";import{dirname,isAbsolute,join,resolve}from"node:path";import{createHash}from"node:crypto";import{buildWithNitroRolldown,getSingleRolldownChunk}from"#internal/bundler/nitro-rolldown.js";import{createAuthoredAssetImportPlugin}from"#internal/authored-asset-import-plugin.js";import{assertNoWorkflowDirectivePrologue}from"#internal/authored-directive-prologue.js";import{createAuthoredModuleBundleError}from"#internal/authored-module-bundle.js";import{createAuthoredPackageTsConfigPathsPlugin}from"#internal/authored-package-tsconfig-paths.js";import{createFixedNamespaceScopePlugin}from"#internal/bundler/extension-scope-plugin.js";import{CACHED_CHANNEL_PREFIX,RESOLVE_EXTENSIONS,createGenerationPackageBoundaryPlugin,createRuntimeLoaderPackageBoundaryPlugin,isNodeModulesPath,isPathImport,normalizeExternalDependencies}from"#internal/authored-package-boundary.js";import{createNodeEsmCompatBannerPlugin}from"#internal/node-esm-compat-banner.js";const AUTHORED_BUNDLED_MODULE_EXTENSION=/\.[cm]?[jt]sx?$/,AUTHORED_MODULE_BUNDLE_DIRECTORY_PATH=join(`node_modules`,`.cache`,`eve`,`authored-modules`),CHANNEL_MODULE_CACHE_KEY=`__eveChannelModuleCache__`;function getChannelModuleCache(){return globalThis[CHANNEL_MODULE_CACHE_KEY]}const inFlightModuleLoads=new Map;function loadAuthoredModuleNamespace(e,t={}){let n=createInFlightModuleLoadKey(resolve(e),t),r=inFlightModuleLoads.get(n);if(r!==void 0)return r;let i=(async()=>{try{return await doLoadAuthoredModuleNamespace(e,t)}finally{inFlightModuleLoads.delete(n)}})();return inFlightModuleLoads.set(n,i),i}async function doLoadAuthoredModuleNamespace(t,n){return expectObjectRecord(AUTHORED_BUNDLED_MODULE_EXTENSION.test(t)?await loadBundledAuthoredModule(t,n):await import(createFileImportSpecifier(t)),`Expected "${t}" to export a module namespace object.`)}function createFileImportSpecifier(e){let t=e.replaceAll(`\\`,`/`);return/^[A-Za-z]:\//.test(t)?`file:///${encodeURI(t)}`:t.startsWith(`/`)?`file://${encodeURI(t)}`:t}async function bundleAuthoredModuleCode(e,t={}){return await buildAuthoredModuleBundle(e,t,{channelIdentity:!0,packageBoundaryPlugin:createRuntimeLoaderPackageBoundaryPlugin({externalDependencies:normalizeExternalDependencies(t.externalDependencies),packageRoot:resolveAuthoredPackageRoot(e)}),plugins:[],sourcemap:`inline`})}async function bundleAuthoredModuleForGeneration(e,t={}){return removeRolldownModuleRegionComments(await buildAuthoredModuleBundle(e,t,{channelIdentity:!1,packageBoundaryPlugin:createGenerationPackageBoundaryPlugin({externalDependencies:normalizeExternalDependencies(t.externalDependencies),packageRoot:resolveAuthoredPackageRoot(e)}),plugins:[createAuthoredDirectiveGuardPlugin()],sourcemap:!1}))}async function buildAuthoredModuleBundle(e,t,n){let r=n.channelIdentity?getChannelModuleCache():void 0,i=resolveAuthoredPackageRoot(e),a=resolveAuthoredTsConfigPath(i),o=[r&&r.size>0?{name:`eve-channel-identity`,async resolveId(e,t,n){if(!/channels[/\\]/.test(e)||n.kind!==`import-statement`)return;let i=await this.resolve(e,t,{kind:n.kind,skipSelf:!0});if(i===null||typeof i.id!=`string`)return;let a=resolve(i.id);if(r.has(a))return{id:`${CACHED_CHANNEL_PREFIX}${a}`}},load(e){if(!e.startsWith(CACHED_CHANNEL_PREFIX))return;let t=e.slice(CACHED_CHANNEL_PREFIX.length);return{code:[`const cache = globalThis["${CHANNEL_MODULE_CACHE_KEY}"];`,`export default cache.get(${JSON.stringify(t)});`].join(`
2
- `),moduleType:`js`}}}:null,...n.plugins,t.extensionScopeNamespace===void 0?null:createFixedNamespaceScopePlugin(t.extensionScopeNamespace),createAuthoredRelativeExtensionResolverPlugin({extensions:RESOLVE_EXTENSIONS}),createAuthoredAssetImportPlugin(),createAuthoredPackageTsConfigPathsPlugin({appPackageRoot:i,extensions:RESOLVE_EXTENSIONS}),createNodeEsmCompatBannerPlugin({includeRequire:!0}),n.packageBoundaryPlugin].filter(e=>e!==null);try{return getSingleRolldownChunk(await buildWithNitroRolldown({cwd:i,input:e,platform:`node`,plugins:o,resolve:{extensions:[...RESOLVE_EXTENSIONS]},tsconfig:a,write:!1,output:{codeSplitting:!1,comments:!1,format:`esm`,sourcemap:n.sourcemap}}),`authored module for "${e}"`).code}catch(t){throw createAuthoredModuleBundleError(e,t)}}function createAuthoredDirectiveGuardPlugin(){return{name:`eve-authored-directive-guard`,async transform(e,t){!AUTHORED_BUNDLED_MODULE_EXTENSION.test(t)||isNodeModulesPath(t)||await assertNoWorkflowDirectivePrologue({filePath:t,source:e})}}}function removeRolldownModuleRegionComments(e){return e.split(`
1
+ import{expectObjectRecord}from"#internal/authored-module.js";import{existsSync,mkdirSync,statSync,writeFileSync}from"node:fs";import{dirname,isAbsolute,join,resolve}from"node:path";import{createHash}from"node:crypto";import{buildSingleRolldownChunk}from"#internal/bundler/nitro-rolldown.js";import{createAuthoredAssetImportPlugin}from"#internal/authored-asset-import-plugin.js";import{assertNoWorkflowDirectivePrologue}from"#internal/authored-directive-prologue.js";import{createAuthoredModuleBundleError}from"#internal/authored-module-bundle.js";import{createAuthoredPackageTsConfigPathsPlugin}from"#internal/authored-package-tsconfig-paths.js";import{createFixedNamespaceScopePlugin}from"#internal/bundler/extension-scope-plugin.js";import{CACHED_CHANNEL_PREFIX,RESOLVE_EXTENSIONS,createGenerationPackageBoundaryPlugin,createRuntimeLoaderPackageBoundaryPlugin,isNodeModulesPath,isPathImport,normalizeExternalDependencies}from"#internal/authored-package-boundary.js";import{createNodeEsmCompatBannerPlugin}from"#internal/node-esm-compat-banner.js";const AUTHORED_BUNDLED_MODULE_EXTENSION=/\.[cm]?[jt]sx?$/,AUTHORED_MODULE_BUNDLE_DIRECTORY_PATH=join(`node_modules`,`.cache`,`eve`,`authored-modules`),CHANNEL_MODULE_CACHE_KEY=`__eveChannelModuleCache__`;function getChannelModuleCache(){return globalThis[CHANNEL_MODULE_CACHE_KEY]}const inFlightModuleLoads=new Map;function loadAuthoredModuleNamespace(e,t={}){let n=createInFlightModuleLoadKey(resolve(e),t),r=inFlightModuleLoads.get(n);if(r!==void 0)return r;let i=(async()=>{try{return await doLoadAuthoredModuleNamespace(e,t)}finally{inFlightModuleLoads.delete(n)}})();return inFlightModuleLoads.set(n,i),i}async function doLoadAuthoredModuleNamespace(t,n){return expectObjectRecord(AUTHORED_BUNDLED_MODULE_EXTENSION.test(t)?await loadBundledAuthoredModule(t,n):await import(createFileImportSpecifier(t)),`Expected "${t}" to export a module namespace object.`)}function createFileImportSpecifier(e){let t=e.replaceAll(`\\`,`/`);return/^[A-Za-z]:\//.test(t)?`file:///${encodeURI(t)}`:t.startsWith(`/`)?`file://${encodeURI(t)}`:t}async function bundleAuthoredModuleCode(e,t={}){return await buildAuthoredModuleBundle(e,t,{channelIdentity:!0,packageBoundaryPlugin:createRuntimeLoaderPackageBoundaryPlugin({externalDependencies:normalizeExternalDependencies(t.externalDependencies),packageRoot:resolveAuthoredPackageRoot(e)}),plugins:[],sourcemap:`inline`})}async function bundleAuthoredModuleForGeneration(e,t={}){return removeRolldownModuleRegionComments(await buildAuthoredModuleBundle(e,t,{channelIdentity:!1,packageBoundaryPlugin:createGenerationPackageBoundaryPlugin({externalDependencies:normalizeExternalDependencies(t.externalDependencies),packageRoot:resolveAuthoredPackageRoot(e)}),plugins:[createAuthoredDirectiveGuardPlugin()],sourcemap:!1}))}async function buildAuthoredModuleBundle(e,t,n){let r=n.channelIdentity?getChannelModuleCache():void 0,i=resolveAuthoredPackageRoot(e),a=resolveAuthoredTsConfigPath(i),o=[r&&r.size>0?{name:`eve-channel-identity`,async resolveId(e,t,n){if(!/channels[/\\]/.test(e)||n.kind!==`import-statement`)return;let i=await this.resolve(e,t,{kind:n.kind,skipSelf:!0});if(i===null||typeof i.id!=`string`)return;let a=resolve(i.id);if(r.has(a))return{id:`${CACHED_CHANNEL_PREFIX}${a}`}},load(e){if(!e.startsWith(CACHED_CHANNEL_PREFIX))return;let t=e.slice(CACHED_CHANNEL_PREFIX.length);return{code:[`const cache = globalThis["${CHANNEL_MODULE_CACHE_KEY}"];`,`export default cache.get(${JSON.stringify(t)});`].join(`
2
+ `),moduleType:`js`}}}:null,...n.plugins,t.extensionScopeNamespace===void 0?null:createFixedNamespaceScopePlugin(t.extensionScopeNamespace),createAuthoredRelativeExtensionResolverPlugin({extensions:RESOLVE_EXTENSIONS}),createAuthoredAssetImportPlugin(),createAuthoredPackageTsConfigPathsPlugin({appPackageRoot:i,extensions:RESOLVE_EXTENSIONS}),createNodeEsmCompatBannerPlugin({includeRequire:!0}),n.packageBoundaryPlugin].filter(e=>e!==null);try{return(await buildSingleRolldownChunk(`authored module for "${e}"`,{cwd:i,input:e,platform:`node`,plugins:o,resolve:{extensions:[...RESOLVE_EXTENSIONS]},tsconfig:a,output:{comments:!1,format:`esm`,sourcemap:n.sourcemap}})).code}catch(t){throw createAuthoredModuleBundleError(e,t)}}function createAuthoredDirectiveGuardPlugin(){return{name:`eve-authored-directive-guard`,async transform(e,t){!AUTHORED_BUNDLED_MODULE_EXTENSION.test(t)||isNodeModulesPath(t)||await assertNoWorkflowDirectivePrologue({filePath:t,source:e})}}}function removeRolldownModuleRegionComments(e){return e.split(`
3
3
  `).filter(e=>!e.startsWith(`//#region `)&&e!==`//#endregion`).join(`
4
4
  `)}async function loadBundledAuthoredModule(e,r){let a=await bundleAuthoredModuleCode(e,r),o=normalizeExternalDependencies(r.externalDependencies),s=createHash(`sha1`).update(e).update(`\0`).update(o.join(`\0`)).update(`\0`).update(r.extensionScopeNamespace??``).update(`\0`).update(a).digest(`hex`),c=join(resolveAuthoredPackageRoot(e),AUTHORED_MODULE_BUNDLE_DIRECTORY_PATH),l=join(c,`${s}.mjs`);return existsSync(l)||(mkdirSync(c,{recursive:!0}),writeFileSync(l,a)),await import(`${createFileImportSpecifier(l)}?v=${s}`)}function createAuthoredRelativeExtensionResolverPlugin(e){return{name:`eve-authored-relative-extension-resolver`,resolveId(t,n){if(n===void 0||n.startsWith(`\0`)||n.startsWith(CACHED_CHANNEL_PREFIX)||!isPathImport(t))return;let r=resolveExistingImportPath(isAbsolute(t)?t:resolve(dirname(n),t),e.extensions);if(r!==void 0)return{id:r}}}}function createInFlightModuleLoadKey(e,t){return`${e}\0${normalizeExternalDependencies(t.externalDependencies).join(`\0`)}\0${t.extensionScopeNamespace??``}`}function resolveExistingImportPath(e,t){if(isFile(e))return e;for(let n of t){let t=`${e}${n}`;if(isFile(t))return t}for(let n of t){let t=join(e,`index${n}`);if(isFile(t))return t}}function isFile(e){try{return statSync(e).isFile()}catch{return!1}}function resolveAuthoredTsConfigPath(e){for(let n of[`tsconfig.json`,`jsconfig.json`]){let r=join(e,n);if(existsSync(r))return r}return!1}function resolveAuthoredPackageRoot(e){let n=dirname(e);for(;;){if(existsSync(join(n,`package.json`)))return n;let r=dirname(n);if(r===n)throw Error(`Failed to resolve the authored package root for "${e}".`);n=r}}export{bundleAuthoredModuleCode,bundleAuthoredModuleForGeneration,loadAuthoredModuleNamespace};
@@ -11,7 +11,6 @@ type RolldownOutputAsset = {
11
11
  type RolldownOutput = {
12
12
  readonly output: readonly [RolldownOutputChunk, ...(RolldownOutputChunk | RolldownOutputAsset)[]];
13
13
  };
14
- export type RolldownBuild = (options: Record<string, unknown>) => Promise<RolldownOutput>;
15
14
  type RolldownParseAst = (sourceText: string, options?: Record<string, unknown> | null, filename?: string) => unknown;
16
15
  export type RolldownParserLanguage = "js" | "jsx" | "ts" | "tsx";
17
16
  type RolldownParseAstModule = {
@@ -24,6 +23,23 @@ type RolldownParseAstModule = {
24
23
  export declare function loadNitroRolldownParseAst(): Promise<RolldownParseAstModule>;
25
24
  export declare function inferRolldownParserLanguage(filename: string): RolldownParserLanguage;
26
25
  export declare function parseWithNitroRolldownAst(filename: string, sourceText: string): Promise<unknown>;
26
+ /**
27
+ * Runs a raw Rolldown build. Prefer {@link buildSingleRolldownChunk} for any
28
+ * bundle whose consumer expects one in-memory file; use this directly only
29
+ * for multi-file, written-to-disk output.
30
+ */
27
31
  export declare function buildWithNitroRolldown(options: Record<string, unknown>): Promise<RolldownOutput>;
28
- export declare function getSingleRolldownChunk(output: RolldownOutput, description: string): RolldownOutputChunk;
32
+ /**
33
+ * Runs a Rolldown build whose contract is exactly one in-memory chunk:
34
+ * code splitting is disabled and the result is asserted to contain a
35
+ * single JavaScript chunk, so dynamic imports are inlined rather than
36
+ * split into lazy chunks. Every eve single-file bundle (the authored-module
37
+ * evaluator, immutable development generations, and workflow step/function
38
+ * bundles) goes through this helper so the single-file policy and its
39
+ * assertion cannot drift apart. The final Nitro production server build
40
+ * does not use it and keeps code splitting enabled.
41
+ */
42
+ export declare function buildSingleRolldownChunk(description: string, options: Record<string, unknown> & {
43
+ readonly output?: Record<string, unknown>;
44
+ }): Promise<RolldownOutputChunk>;
29
45
  export {};
@@ -1 +1 @@
1
- import{createRequire}from"node:module";import{pathToFileURL}from"node:url";let rolldownPromise,rolldownParseAstPromise;function loadNitroRolldown(){return rolldownPromise??=(async()=>await import(pathToFileURL(createRequire(createRequire(import.meta.url).resolve(`nitro/package.json`)).resolve(`rolldown`)).href))(),rolldownPromise}function loadNitroRolldownParseAst(){return rolldownParseAstPromise??=(async()=>await import(pathToFileURL(createRequire(createRequire(import.meta.url).resolve(`nitro/package.json`)).resolve(`rolldown/parseAst`)).href))(),rolldownParseAstPromise}function inferRolldownParserLanguage(e){return e.endsWith(`.tsx`)?`tsx`:e.endsWith(`.jsx`)?`jsx`:/\.[cm]?ts$/.test(e)?`ts`:`js`}async function parseWithNitroRolldownAst(e,t){let{parseAst:n}=await loadNitroRolldownParseAst();return n(t,{astType:`ts`,lang:inferRolldownParserLanguage(e),range:!0,sourceType:`module`},e)}async function buildWithNitroRolldown(e){let{build:t}=await loadNitroRolldown();return await t(e)}function getSingleRolldownChunk(e,t){let n=e.output.filter(e=>e.type===`chunk`),r=n[0];if(r===void 0||n.length!==1)throw Error(`Expected one bundled ${t}.`);return r}export{buildWithNitroRolldown,getSingleRolldownChunk,inferRolldownParserLanguage,loadNitroRolldownParseAst,parseWithNitroRolldownAst};
1
+ import{createRequire}from"node:module";import{pathToFileURL}from"node:url";let rolldownPromise,rolldownParseAstPromise;function loadNitroRolldown(){return rolldownPromise??=(async()=>await import(pathToFileURL(createRequire(createRequire(import.meta.url).resolve(`nitro/package.json`)).resolve(`rolldown`)).href))(),rolldownPromise}function loadNitroRolldownParseAst(){return rolldownParseAstPromise??=(async()=>await import(pathToFileURL(createRequire(createRequire(import.meta.url).resolve(`nitro/package.json`)).resolve(`rolldown/parseAst`)).href))(),rolldownParseAstPromise}function inferRolldownParserLanguage(e){return e.endsWith(`.tsx`)?`tsx`:e.endsWith(`.jsx`)?`jsx`:/\.[cm]?ts$/.test(e)?`ts`:`js`}async function parseWithNitroRolldownAst(e,t){let{parseAst:n}=await loadNitroRolldownParseAst();return n(t,{astType:`ts`,lang:inferRolldownParserLanguage(e),range:!0,sourceType:`module`},e)}async function buildWithNitroRolldown(e){let{build:t}=await loadNitroRolldown();return await t(e)}async function buildSingleRolldownChunk(e,t){return getSingleRolldownChunk(await buildWithNitroRolldown({...t,write:!1,output:{...t.output,codeSplitting:!1}}),e)}function getSingleRolldownChunk(e,t){let n=e.output.filter(e=>e.type===`chunk`),r=n[0];if(r===void 0||n.length!==1)throw Error(`Expected one bundled ${t}.`);return r}export{buildSingleRolldownChunk,buildWithNitroRolldown,inferRolldownParserLanguage,loadNitroRolldownParseAst,parseWithNitroRolldownAst};
@@ -1 +1 @@
1
- import{constants,existsSync}from"node:fs";import{dirname,join,relative,resolve,sep}from"node:path";import{cp,lstat,mkdir,readFile,readdir,symlink,writeFile}from"node:fs/promises";import{DevelopmentRuntimeSourceSnapshotError,toDevelopmentSourceSnapshotPath}from"#internal/nitro/dev-runtime-source-snapshot.js";import{extractTsConfigExtendsSpecifiers,isTsConfigFilePath,parseTsConfigObject,readTextFileIfExists,resolveFirstExistingTsConfigExtendsTarget,resolveTsConfigExtendsTargetPaths}from"#internal/application/tsconfig-dependencies.js";const SNAPSHOT_SKIP_NAMES=new Set([`.generated`,`.eve`,`.git`,`.next`,`.output`,`.turbo`,`.vercel`,`.workflow-data`,`node_modules`]),SNAPSHOT_APP_ROOT_SKIP_NAMES=new Set([`build`,`dist`]),SNAPSHOT_COPY_MODE=constants.COPYFILE_FICLONE;async function copyDevelopmentSourceSnapshot(e){await mkdir(e.snapshotSourceRoot,{recursive:!0});for(let t of e.copyRoots)await copySnapshotPath({plan:e,sourcePath:t,targetPath:toSnapshotPathForPlan(e,t)});for(let n of e.copyFiles)existsSync(n)&&await copySnapshotPath({plan:e,sourcePath:n,targetPath:toSnapshotPathForPlan(e,n)});await rewriteSnapshotTsConfigAbsoluteExtends(e),await createSnapshotSymlinks(e),await ensureRuntimePackageJson(e),await validateDevelopmentSourceSnapshot(e)}async function copySnapshotPath(e){try{if((await lstat(e.sourcePath)).isDirectory()){await copySnapshotDirectory(e);return}await mkdir(dirname(e.targetPath),{recursive:!0}),await cp(e.sourcePath,e.targetPath,{mode:SNAPSHOT_COPY_MODE,recursive:!0})}catch(t){throw new DevelopmentRuntimeSourceSnapshotError(`Failed to copy development runtime source snapshot path "${e.sourcePath}" to "${e.targetPath}": ${formatErrorMessage(t)}`)}}async function copySnapshotDirectory(e){await mkdir(e.targetPath,{recursive:!0});for(let t of await readdir(e.sourcePath,{withFileTypes:!0})){let n=join(e.sourcePath,t.name);shouldSkipSnapshotSource(e.plan,n)||await cp(n,join(e.targetPath,t.name),{filter:t=>!shouldSkipSnapshotSource(e.plan,t),mode:SNAPSHOT_COPY_MODE,recursive:!0})}}function shouldSkipSnapshotSource(e,n){let i=relative(e.sourceRoot,n);return i.length===0?!1:i.split(/[\\/]/).some(e=>SNAPSHOT_SKIP_NAMES.has(e)||e.startsWith(`.env`))||existsSync(join(n,`.git`))?!0:isDirectAppRootSkipPath({appRoot:e.appRoot,sourcePath:n})}function isDirectAppRootSkipPath(e){if(!isPathInsideOrEqual(e.sourcePath,e.appRoot))return!1;let t=relative(e.appRoot,e.sourcePath);if(t.length===0)return!1;let n=t.split(/[\\/]/)[0];return n!==void 0&&SNAPSHOT_APP_ROOT_SKIP_NAMES.has(n)}async function rewriteSnapshotTsConfigAbsoluteExtends(e){for(let t of e.tsconfigPaths){let n=await readTextFileIfExists(t);if(n===void 0)continue;let r=rewriteTsConfigAbsoluteExtends({configPath:t,snapshotConfigPath:toSnapshotPathForPlan(e,t),snapshotSourceRoot:e.snapshotSourceRoot,source:n,sourceRoot:e.sourceRoot});r!==void 0&&await writeFile(toSnapshotPathForPlan(e,t),r)}}function rewriteTsConfigAbsoluteExtends(e){let t=parseTsConfigObject(e.source);if(t===void 0)return;let n=rewriteTsConfigExtendsValue({configPath:e.configPath,snapshotConfigPath:e.snapshotConfigPath,snapshotSourceRoot:e.snapshotSourceRoot,sourceRoot:e.sourceRoot,value:t.extends});if(n.changed===!0)return`${JSON.stringify({...t,extends:n.value},null,2)}\n`}function rewriteTsConfigExtendsValue(e){if(typeof e.value==`string`){let t=rewriteTsConfigExtendsSpecifier({configPath:e.configPath,snapshotConfigPath:e.snapshotConfigPath,snapshotSourceRoot:e.snapshotSourceRoot,sourceRoot:e.sourceRoot,value:e.value});return t===void 0?{changed:!1,value:e.value}:{changed:!0,value:t}}if(!Array.isArray(e.value))return{changed:!1,value:e.value};let t=!1,n=e.value.map(n=>{if(typeof n!=`string`)return n;let r=rewriteTsConfigExtendsSpecifier({configPath:e.configPath,snapshotConfigPath:e.snapshotConfigPath,snapshotSourceRoot:e.snapshotSourceRoot,sourceRoot:e.sourceRoot,value:n});return r===void 0?n:(t=!0,r)});return{changed:t,value:n}}function rewriteTsConfigExtendsSpecifier(e){if(!isTsConfigFilePath(e.value)||!isAbsoluteFilePath(e.value))return;let t=resolveFirstExistingTsConfigExtendsTarget({configPath:e.configPath,extendsSpecifier:e.value});if(!(t===void 0||!isPathInsideOrEqual(t,e.sourceRoot)))return toDevelopmentSourceSnapshotPath({snapshotSourceRoot:e.snapshotSourceRoot,sourcePath:t,sourceRoot:e.sourceRoot})}async function createSnapshotSymlinks(e){for(let t of e.symlinks){let r=toSnapshotPathForPlan(e,t.linkPath),i=t.targetKind===`local`?toSnapshotPathForPlan(e,t.targetPath):t.targetPath,a=t.targetKind===`local`?relative(dirname(r),i)||`.`:i;await mkdir(dirname(r),{recursive:!0}),await symlink(a,r,`junction`)}}async function ensureRuntimePackageJson(e){let n=join(e.runtimeAppRoot,`package.json`);existsSync(n)||(await mkdir(e.runtimeAppRoot,{recursive:!0}),await writeFile(n,`${JSON.stringify({private:!0,type:`module`},null,2)}\n`))}async function validateDevelopmentSourceSnapshot(e){let n=join(e.runtimeAppRoot,`package.json`);if(!existsSync(n))throw new DevelopmentRuntimeSourceSnapshotError(`Development runtime source snapshot is missing the runtime app package.json at "${n}".`);for(let n of e.tsconfigPaths){let r=toSnapshotPathForPlan(e,n);if(!existsSync(r))throw new DevelopmentRuntimeSourceSnapshotError(`Development runtime source snapshot is missing tsconfig dependency "${r}".`);await validateSnapshotTsConfigExtends(r)}}async function validateSnapshotTsConfigExtends(e){let n=extractTsConfigExtendsSpecifiers(await readFile(e,`utf8`));for(let r of n)if(!(!isTsConfigFilePath(r)||resolveTsConfigExtendsTargetPaths({configPath:e,extendsSpecifier:r}).some(e=>existsSync(e))))throw new DevelopmentRuntimeSourceSnapshotError(`Development runtime source snapshot cannot resolve tsconfig extends "${r}" from "${e}".`)}function toSnapshotPathForPlan(e,t){return toDevelopmentSourceSnapshotPath({snapshotSourceRoot:e.snapshotSourceRoot,sourcePath:t,sourceRoot:e.sourceRoot})}function isPathInsideOrEqual(e,t){let n=resolve(e),r=resolve(t);return n===r||n.startsWith(`${r}${sep}`)}function isAbsoluteFilePath(e){return e.startsWith(`/`)||/^[A-Za-z]:[\\/]/.test(e)}function formatErrorMessage(e){return e instanceof Error?e.message:String(e)}export{copyDevelopmentSourceSnapshot};
1
+ import{constants,existsSync}from"node:fs";import{dirname,join,relative,resolve,sep}from"node:path";import{cp,lstat,mkdir,readFile,readdir,symlink,writeFile}from"node:fs/promises";import{DevelopmentRuntimeSourceSnapshotError,toDevelopmentSourceSnapshotPath}from"#internal/nitro/dev-runtime-source-snapshot.js";import{extractTsConfigExtendsSpecifiers,isTsConfigFilePath,parseTsConfigObject,readTextFileIfExists,resolveFirstExistingTsConfigExtendsTarget,resolveTsConfigExtendsTargetPaths}from"#internal/application/tsconfig-dependencies.js";const SNAPSHOT_SKIP_NAMES=new Set([`.generated`,`.eve`,`.git`,`.next`,`.output`,`.turbo`,`.vercel`,`node_modules`]),SNAPSHOT_APP_ROOT_SKIP_NAMES=new Set([`build`,`dist`]),SNAPSHOT_COPY_MODE=constants.COPYFILE_FICLONE;async function copyDevelopmentSourceSnapshot(e){await mkdir(e.snapshotSourceRoot,{recursive:!0});for(let t of e.copyRoots)await copySnapshotPath({plan:e,sourcePath:t,targetPath:toSnapshotPathForPlan(e,t)});for(let n of e.copyFiles)existsSync(n)&&await copySnapshotPath({plan:e,sourcePath:n,targetPath:toSnapshotPathForPlan(e,n)});await rewriteSnapshotTsConfigAbsoluteExtends(e),await createSnapshotSymlinks(e),await ensureRuntimePackageJson(e),await validateDevelopmentSourceSnapshot(e)}async function copySnapshotPath(e){try{if((await lstat(e.sourcePath)).isDirectory()){await copySnapshotDirectory(e);return}await mkdir(dirname(e.targetPath),{recursive:!0}),await cp(e.sourcePath,e.targetPath,{mode:SNAPSHOT_COPY_MODE,recursive:!0})}catch(t){throw new DevelopmentRuntimeSourceSnapshotError(`Failed to copy development runtime source snapshot path "${e.sourcePath}" to "${e.targetPath}": ${formatErrorMessage(t)}`)}}async function copySnapshotDirectory(e){await mkdir(e.targetPath,{recursive:!0});for(let t of await readdir(e.sourcePath,{withFileTypes:!0})){let n=join(e.sourcePath,t.name);shouldSkipSnapshotSource(e.plan,n)||await cp(n,join(e.targetPath,t.name),{filter:t=>!shouldSkipSnapshotSource(e.plan,t),mode:SNAPSHOT_COPY_MODE,recursive:!0})}}function shouldSkipSnapshotSource(e,n){let i=relative(e.sourceRoot,n);return i.length===0?!1:i.split(/[\\/]/).some(e=>SNAPSHOT_SKIP_NAMES.has(e)||e.startsWith(`.env`))||existsSync(join(n,`.git`))?!0:isDirectAppRootSkipPath({appRoot:e.appRoot,sourcePath:n})}function isDirectAppRootSkipPath(e){if(!isPathInsideOrEqual(e.sourcePath,e.appRoot))return!1;let t=relative(e.appRoot,e.sourcePath);if(t.length===0)return!1;let n=t.split(/[\\/]/)[0];return n!==void 0&&SNAPSHOT_APP_ROOT_SKIP_NAMES.has(n)}async function rewriteSnapshotTsConfigAbsoluteExtends(e){for(let t of e.tsconfigPaths){let n=await readTextFileIfExists(t);if(n===void 0)continue;let r=rewriteTsConfigAbsoluteExtends({configPath:t,snapshotConfigPath:toSnapshotPathForPlan(e,t),snapshotSourceRoot:e.snapshotSourceRoot,source:n,sourceRoot:e.sourceRoot});r!==void 0&&await writeFile(toSnapshotPathForPlan(e,t),r)}}function rewriteTsConfigAbsoluteExtends(e){let t=parseTsConfigObject(e.source);if(t===void 0)return;let n=rewriteTsConfigExtendsValue({configPath:e.configPath,snapshotConfigPath:e.snapshotConfigPath,snapshotSourceRoot:e.snapshotSourceRoot,sourceRoot:e.sourceRoot,value:t.extends});if(n.changed===!0)return`${JSON.stringify({...t,extends:n.value},null,2)}\n`}function rewriteTsConfigExtendsValue(e){if(typeof e.value==`string`){let t=rewriteTsConfigExtendsSpecifier({configPath:e.configPath,snapshotConfigPath:e.snapshotConfigPath,snapshotSourceRoot:e.snapshotSourceRoot,sourceRoot:e.sourceRoot,value:e.value});return t===void 0?{changed:!1,value:e.value}:{changed:!0,value:t}}if(!Array.isArray(e.value))return{changed:!1,value:e.value};let t=!1,n=e.value.map(n=>{if(typeof n!=`string`)return n;let r=rewriteTsConfigExtendsSpecifier({configPath:e.configPath,snapshotConfigPath:e.snapshotConfigPath,snapshotSourceRoot:e.snapshotSourceRoot,sourceRoot:e.sourceRoot,value:n});return r===void 0?n:(t=!0,r)});return{changed:t,value:n}}function rewriteTsConfigExtendsSpecifier(e){if(!isTsConfigFilePath(e.value)||!isAbsoluteFilePath(e.value))return;let t=resolveFirstExistingTsConfigExtendsTarget({configPath:e.configPath,extendsSpecifier:e.value});if(!(t===void 0||!isPathInsideOrEqual(t,e.sourceRoot)))return toDevelopmentSourceSnapshotPath({snapshotSourceRoot:e.snapshotSourceRoot,sourcePath:t,sourceRoot:e.sourceRoot})}async function createSnapshotSymlinks(e){for(let t of e.symlinks){let r=toSnapshotPathForPlan(e,t.linkPath),i=t.targetKind===`local`?toSnapshotPathForPlan(e,t.targetPath):t.targetPath,a=t.targetKind===`local`?relative(dirname(r),i)||`.`:i;await mkdir(dirname(r),{recursive:!0}),await symlink(a,r,`junction`)}}async function ensureRuntimePackageJson(e){let n=join(e.runtimeAppRoot,`package.json`);existsSync(n)||(await mkdir(e.runtimeAppRoot,{recursive:!0}),await writeFile(n,`${JSON.stringify({private:!0,type:`module`},null,2)}\n`))}async function validateDevelopmentSourceSnapshot(e){let n=join(e.runtimeAppRoot,`package.json`);if(!existsSync(n))throw new DevelopmentRuntimeSourceSnapshotError(`Development runtime source snapshot is missing the runtime app package.json at "${n}".`);for(let n of e.tsconfigPaths){let r=toSnapshotPathForPlan(e,n);if(!existsSync(r))throw new DevelopmentRuntimeSourceSnapshotError(`Development runtime source snapshot is missing tsconfig dependency "${r}".`);await validateSnapshotTsConfigExtends(r)}}async function validateSnapshotTsConfigExtends(e){let n=extractTsConfigExtendsSpecifiers(await readFile(e,`utf8`));for(let r of n)if(!(!isTsConfigFilePath(r)||resolveTsConfigExtendsTargetPaths({configPath:e,extendsSpecifier:r}).some(e=>existsSync(e))))throw new DevelopmentRuntimeSourceSnapshotError(`Development runtime source snapshot cannot resolve tsconfig extends "${r}" from "${e}".`)}function toSnapshotPathForPlan(e,t){return toDevelopmentSourceSnapshotPath({snapshotSourceRoot:e.snapshotSourceRoot,sourcePath:t,sourceRoot:e.sourceRoot})}function isPathInsideOrEqual(e,t){let n=resolve(e),r=resolve(t);return n===r||n.startsWith(`${r}${sep}`)}function isAbsoluteFilePath(e){return e.startsWith(`/`)||/^[A-Za-z]:[\\/]/.test(e)}function formatErrorMessage(e){return e instanceof Error?e.message:String(e)}export{copyDevelopmentSourceSnapshot};
@@ -1 +1 @@
1
- import{existsSync}from"node:fs";import{dirname,join,normalize,resolve,sep}from"node:path";import{toErrorMessage}from"#shared/errors.js";import{getDevelopmentEnvironmentFilePaths}from"#cli/dev/environment.js";import{AUTHORED_ARTIFACTS_UPDATED_LOG_LINE,STRUCTURAL_RELOAD_LOG_LINE,formatChangeDetectedLogLine}from"#internal/nitro/host/dev-watcher-log.js";import{resolveDevelopmentSourceSnapshotWatchPaths}from"#internal/nitro/dev-runtime-source-snapshot.js";import{resolveTsConfigDependencyPaths}from"#internal/application/tsconfig-dependencies.js";import{watch as watch$1}from"#compiled/chokidar/index.js";const WATCHED_LOCKFILE_NAMES=[`pnpm-lock.yaml`,`package-lock.json`,`yarn.lock`,`bun.lock`,`bun.lockb`],WATCH_ROOT_MARKER_NAMES=[`.git`,`pnpm-workspace.yaml`],WATCHER_IGNORED_DIRECTORY_NAMES=new Set([`.generated`,`.eve`,`.git`,`.next`,`.output`,`.turbo`,`.vercel`,`.workflow-data`,`build`,`dist`,`node_modules`]);async function startAuthoredSourceWatcher(e){let t=e.preparedHost,n=!1,r=Promise.resolve(),i,a=!1,o=new Map,s=new Set,c=await resolveAuthoredWatchPaths(t),l=createWatchPathMap(c),u=watch$1(c,{awaitWriteFinish:{pollInterval:50,stabilityThreshold:160},followSymlinks:!1,ignoreInitial:!0,ignored:shouldIgnoreWatcherPath}),d=waitForWatcherReady(u),rebuild=async i=>{n||(r=r.then(async()=>{if(n)return;let r=[...o.values()];if(!i&&r.length===0)return;let a=[...s];o.clear(),s.clear();let c=t;r.length>0&&console.log(formatChangeDetectedLogLine(c.appRoot,r));try{let n=await e.coordinator.rebuild({changedPaths:a});t=n.host,n.kind===`structural`?console.log(STRUCTURAL_RELOAD_LOG_LINE):console.log(AUTHORED_ARTIFACTS_UPDATED_LOG_LINE),l=syncWatcherPaths({nextWatchPaths:await resolveAuthoredWatchPaths(t),previousWatchPathsByKey:l,watcher:u})}catch(e){console.error(`[eve:dev] rebuild failed: ${toErrorMessage(e)}`)}}).catch(e=>{console.error(`[eve:dev] rebuild queue error: ${toErrorMessage(e)}`)}),await r)},flush=async()=>{i!==void 0&&(clearTimeout(i),i=void 0),await rebuild(!1)};return u.on(`all`,(e,t)=>{n||!a||e===`addDir`||e===`unlinkDir`||(o.set(`${e}:${t}`,{event:e,path:t}),s.add(t),i!==void 0&&clearTimeout(i),i=setTimeout(()=>{i=void 0,flush()},120))}),await d,a=!0,{async close(){n=!0,i!==void 0&&(clearTimeout(i),i=void 0),await u.close(),await r},flush,rebuild:async()=>{i!==void 0&&(clearTimeout(i),i=void 0),await rebuild(!0)}}}async function waitForWatcherReady(e){await new Promise((t,n)=>{e.on(`ready`,()=>{t()}),e.on(`error`,e=>{n(e)})})}async function resolveAuthoredWatchPaths(e){let t=new Set([e.compileResult.project.agentRoot,join(e.appRoot,`package.json`),join(e.appRoot,`jsconfig.json`),join(e.appRoot,`tsconfig.json`),join(e.appRoot,`tsconfig.*.json`)]),r=await resolveTsConfigWatchPaths(e.appRoot),i=await resolveDevelopmentSourceSnapshotWatchPaths(e.appRoot);for(let n of getDevelopmentEnvironmentFilePaths(e.appRoot))t.add(n);for(let e of i)t.add(e);for(let e of r)t.add(e);for(let r of resolveLockfileSearchDirectories(e.appRoot))for(let e of WATCHED_LOCKFILE_NAMES)t.add(join(r,e));return[...t].sort((e,t)=>e.localeCompare(t))}function createWatchPathMap(e){let t=new Map;for(let n of e)t.set(toWatchPathKey(n),n);return t}function syncWatcherPaths(e){let t=createWatchPathMap(e.nextWatchPaths),n=[],r=[];for(let[r,i]of t)e.previousWatchPathsByKey.has(r)||n.push(i);for(let[n,i]of e.previousWatchPathsByKey)t.has(n)||r.push(i);return n.length>0&&e.watcher.add(n),r.length>0&&e.watcher.unwatch(r),t}function toWatchPathKey(e){return normalize(resolve(e))}function resolveLockfileSearchDirectories(e){let n=resolve(e),r=[n],a=n;for(;;){if(hasWatchRootMarker(a))return r;let e=dirname(a);if(e===a)return[n];a=e,r.push(a)}}function hasWatchRootMarker(t){return WATCH_ROOT_MARKER_NAMES.some(r=>existsSync(join(t,r)))}async function resolveTsConfigWatchPaths(e){return await resolveTsConfigDependencyPaths(e)}function shouldIgnoreWatcherPath(e){return normalize(e).split(sep).filter(Boolean).some(e=>WATCHER_IGNORED_DIRECTORY_NAMES.has(e))}export{startAuthoredSourceWatcher};
1
+ import{existsSync}from"node:fs";import{dirname,join,normalize,resolve,sep}from"node:path";import{toErrorMessage}from"#shared/errors.js";import{getDevelopmentEnvironmentFilePaths}from"#cli/dev/environment.js";import{AUTHORED_ARTIFACTS_UPDATED_LOG_LINE,STRUCTURAL_RELOAD_LOG_LINE,formatChangeDetectedLogLine}from"#internal/nitro/host/dev-watcher-log.js";import{resolveDevelopmentSourceSnapshotWatchPaths}from"#internal/nitro/dev-runtime-source-snapshot.js";import{resolveTsConfigDependencyPaths}from"#internal/application/tsconfig-dependencies.js";import{watch as watch$1}from"#compiled/chokidar/index.js";const WATCHED_LOCKFILE_NAMES=[`pnpm-lock.yaml`,`package-lock.json`,`yarn.lock`,`bun.lock`,`bun.lockb`],WATCH_ROOT_MARKER_NAMES=[`.git`,`pnpm-workspace.yaml`],WATCHER_IGNORED_DIRECTORY_NAMES=new Set([`.generated`,`.eve`,`.git`,`.next`,`.output`,`.turbo`,`.vercel`,`build`,`dist`,`node_modules`]);async function startAuthoredSourceWatcher(e){let t=e.preparedHost,n=!1,r=Promise.resolve(),i,a=!1,o=new Map,s=new Set,c=await resolveAuthoredWatchPaths(t),l=createWatchPathMap(c),u=watch$1(c,{awaitWriteFinish:{pollInterval:50,stabilityThreshold:160},followSymlinks:!1,ignoreInitial:!0,ignored:shouldIgnoreWatcherPath}),d=waitForWatcherReady(u),rebuild=async i=>{n||(r=r.then(async()=>{if(n)return;let r=[...o.values()];if(!i&&r.length===0)return;let a=[...s];o.clear(),s.clear();let c=t;r.length>0&&console.log(formatChangeDetectedLogLine(c.appRoot,r));try{let n=await e.coordinator.rebuild({changedPaths:a});t=n.host,n.kind===`structural`?console.log(STRUCTURAL_RELOAD_LOG_LINE):console.log(AUTHORED_ARTIFACTS_UPDATED_LOG_LINE),l=syncWatcherPaths({nextWatchPaths:await resolveAuthoredWatchPaths(t),previousWatchPathsByKey:l,watcher:u})}catch(e){console.error(`[eve:dev] rebuild failed: ${toErrorMessage(e)}`)}}).catch(e=>{console.error(`[eve:dev] rebuild queue error: ${toErrorMessage(e)}`)}),await r)},flush=async()=>{i!==void 0&&(clearTimeout(i),i=void 0),await rebuild(!1)};return u.on(`all`,(e,t)=>{n||!a||e===`addDir`||e===`unlinkDir`||(o.set(`${e}:${t}`,{event:e,path:t}),s.add(t),i!==void 0&&clearTimeout(i),i=setTimeout(()=>{i=void 0,flush()},120))}),await d,a=!0,{async close(){n=!0,i!==void 0&&(clearTimeout(i),i=void 0),await u.close(),await r},flush,rebuild:async()=>{i!==void 0&&(clearTimeout(i),i=void 0),await rebuild(!0)}}}async function waitForWatcherReady(e){await new Promise((t,n)=>{e.on(`ready`,()=>{t()}),e.on(`error`,e=>{n(e)})})}async function resolveAuthoredWatchPaths(e){let t=new Set([e.compileResult.project.agentRoot,join(e.appRoot,`package.json`),join(e.appRoot,`jsconfig.json`),join(e.appRoot,`tsconfig.json`),join(e.appRoot,`tsconfig.*.json`)]),r=await resolveTsConfigWatchPaths(e.appRoot),i=await resolveDevelopmentSourceSnapshotWatchPaths(e.appRoot);for(let n of getDevelopmentEnvironmentFilePaths(e.appRoot))t.add(n);for(let e of i)t.add(e);for(let e of r)t.add(e);for(let r of resolveLockfileSearchDirectories(e.appRoot))for(let e of WATCHED_LOCKFILE_NAMES)t.add(join(r,e));return[...t].sort((e,t)=>e.localeCompare(t))}function createWatchPathMap(e){let t=new Map;for(let n of e)t.set(toWatchPathKey(n),n);return t}function syncWatcherPaths(e){let t=createWatchPathMap(e.nextWatchPaths),n=[],r=[];for(let[r,i]of t)e.previousWatchPathsByKey.has(r)||n.push(i);for(let[n,i]of e.previousWatchPathsByKey)t.has(n)||r.push(i);return n.length>0&&e.watcher.add(n),r.length>0&&e.watcher.unwatch(r),t}function toWatchPathKey(e){return normalize(resolve(e))}function resolveLockfileSearchDirectories(e){let n=resolve(e),r=[n],a=n;for(;;){if(hasWatchRootMarker(a))return r;let e=dirname(a);if(e===a)return[n];a=e,r.push(a)}}function hasWatchRootMarker(t){return WATCH_ROOT_MARKER_NAMES.some(r=>existsSync(join(t,r)))}async function resolveTsConfigWatchPaths(e){return await resolveTsConfigDependencyPaths(e)}function shouldIgnoreWatcherPath(e){return normalize(e).split(sep).filter(Boolean).some(e=>WATCHER_IGNORED_DIRECTORY_NAMES.has(e))}export{startAuthoredSourceWatcher};
@@ -1 +1 @@
1
- import{resolvePackageSourceFilePath}from"#internal/application/package.js";import{basename,join}from"node:path";import{readFile}from"node:fs/promises";import{turnWorkflowReference}from"#execution/workflow-runtime.js";import{createDiskRuntimeCompiledArtifactsSource}from"#runtime/compiled-artifacts-source.js";import{DEVELOPMENT_WORKER_APP_ROOT_ENV,DEVELOPMENT_WORKFLOW_DELIVERY_HEADER,DEVELOPMENT_WORKFLOW_SECRET_ENV,DEVELOPMENT_WORKFLOW_STREAM_ROUTE,DEVELOPMENT_WORKFLOW_TRANSPORT_HEADER,DEVELOPMENT_WORKFLOW_WORLD_ROUTE,DEVELOPMENT_WORLD_OPERATIONS}from"#internal/workflow/development-world-protocol.js";import{timingSafeEqualStrings}from"#internal/nitro/dev-client-address.js";import{decodeDevelopmentWorldJson,decodeDevelopmentWorldValue,deserializeDevelopmentWorldError,encodeDevelopmentWorldValue}from"#internal/workflow/development-world-codec.js";import{getDevelopmentWorkflowGeneration,withDevelopmentWorkflowGeneration}from"#internal/workflow/development-generation-context.js";var MissingDevelopmentGenerationError=class extends Error{constructor(e,t){super(`Workflow run references missing development generation "${e}". Remove ".workflow-data" to discard the app's active local Workflow runs.`,t===void 0?void 0:{cause:t}),this.name=`MissingDevelopmentGenerationError`}};async function call(e,t=[]){return decodeDevelopmentWorldValue(await(await fetchDevelopmentWorld(DEVELOPMENT_WORKFLOW_WORLD_ROUTE,{body:encodeDevelopmentWorldValue({arguments:t,operation:e}),method:`POST`})).text())}function createDevelopmentWorkflowWorld(){let e=buildForwardedOperations();return{specVersion:5,processExitTriggersQueueRedelivery:!1,async getDeploymentId(){return getDevelopmentWorkflowGeneration()?.generationId??await call(`getDeploymentId`)},resolveLatestDeploymentId:e.topLevel.resolveLatestDeploymentId,queue:e.topLevel.queue,createQueueHandler,runs:e.groups.runs,steps:e.groups.steps,events:e.groups.events,hooks:e.groups.hooks,streams:{...e.groups.streams,get:async(e,t,n)=>{let r=new URL(resolveDevelopmentWorldBaseUrl());r.pathname=DEVELOPMENT_WORKFLOW_STREAM_ROUTE,r.searchParams.set(`runId`,e),r.searchParams.set(`name`,t),n!==void 0&&r.searchParams.set(`startIndex`,String(n));let i=await fetchDevelopmentWorld(r,{method:`GET`});if(i.body===null)throw Error(`Development Workflow stream response had no body.`);return i.body}},async start(){},async close(){}}}function buildForwardedOperations(){let e={},t={};for(let n of DEVELOPMENT_WORLD_OPERATIONS){let forward=async(...e)=>await call(n,e),r=n.indexOf(`.`);r===-1?t[n]=forward:(e[n.slice(0,r)]??={})[n.slice(r+1)]=forward}return{groups:e,topLevel:t}}function createQueueHandler(t,n){return async r=>{let i=readRequiredEnvironment(DEVELOPMENT_WORKFLOW_SECRET_ENV),c=r.headers.get(DEVELOPMENT_WORKFLOW_DELIVERY_HEADER);if(c===null||!timingSafeEqualStrings(c,i))return Response.json({error:`Workflow delivery is not trusted.`},{status:401});let l=r.headers.get(`x-vqs-queue-name`),u=r.headers.get(`x-vqs-message-id`),d=Number(r.headers.get(`x-vqs-message-attempt`));if(l===null||!l.startsWith(t)||u===null||!Number.isInteger(d)||d<1||r.body===null)return Response.json({error:`Workflow delivery is malformed.`},{status:400});let f=decodeDevelopmentWorldJson(await r.text());try{let t=readRequiredEnvironment(DEVELOPMENT_WORKER_APP_ROOT_ENV),r=await resolveDeliveryGenerationId(f),i=await withDevelopmentWorkflowGeneration({generationId:r,source:createDiskRuntimeCompiledArtifactsSource(await readGenerationRuntimeAppRoot(t,r),{durableReference:`development-generation`,moduleMapLoaderPath:resolvePackageSourceFilePath(`src/internal/authored-module-map-loader.ts`),sandboxAppRoot:t})},async()=>await n(f,{attempt:d,messageId:u,queueName:l}));return Response.json(i===void 0?{ok:!0}:{timeoutSeconds:i.timeoutSeconds})}catch(e){return e instanceof MissingDevelopmentGenerationError?(console.error(`[eve:dev] ${e.message}`),Response.json({ok:!0})):Response.json(String(e),{status:500})}}}async function resolveDeliveryGenerationId(e){if(!isRecord(e))return await call(`resolveLatestDeploymentId`);let t=isRecord(e.runInput)?e.runInput:void 0;if(t!==void 0)return t.workflowName===turnWorkflowReference.workflowId&&typeof t.deploymentId==`string`?t.deploymentId:await call(`resolveLatestDeploymentId`);let n=typeof e.runId==`string`?e.runId:typeof e.workflowRunId==`string`?e.workflowRunId:void 0;if(n===void 0)return await call(`resolveLatestDeploymentId`);let r=await call(`runs.get`,[n,{resolveData:`none`}]);return r.workflowName===turnWorkflowReference.workflowId?r.deploymentId:await call(`resolveLatestDeploymentId`)}async function readGenerationRuntimeAppRoot(e,i){if(i.length===0||i===`.`||i===`..`||basename(i)!==i)throw Error(`Workflow run references invalid development generation "${i}".`);let a=join(e,`.eve`,`dev-runtime`,`snapshots`,i,`generation.json`),o;try{o=await readFile(a,`utf8`)}catch(e){throw isFileNotFoundError(e)?new MissingDevelopmentGenerationError(i,e):e}let s;try{s=JSON.parse(o)}catch(e){throw Error(`Development generation "${i}" has invalid metadata.`,{cause:e})}if(!isRecord(s)||typeof s.runtimeAppRoot!=`string`)throw Error(`Development generation "${i}" has invalid metadata.`);return s.runtimeAppRoot}function isFileNotFoundError(e){return e instanceof Error&&`code`in e&&e.code===`ENOENT`}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function fetchDevelopmentWorld(e,t){let n=e instanceof URL?e:new URL(e,resolveDevelopmentWorldBaseUrl()),r=new Headers(t.headers);r.set(DEVELOPMENT_WORKFLOW_TRANSPORT_HEADER,readRequiredEnvironment(DEVELOPMENT_WORKFLOW_SECRET_ENV));let i=await fetch(n,{...t,headers:r});if(!i.ok){let e=await i.text(),t=readDevelopmentWorldError(e);throw t===void 0?Error(`Development Workflow World request failed (${String(i.status)}): ${e}`):t}return i}function readDevelopmentWorldError(e){try{return deserializeDevelopmentWorldError(decodeDevelopmentWorldValue(e))}catch{return}}function resolveDevelopmentWorldBaseUrl(){return readRequiredEnvironment(`WORKFLOW_LOCAL_BASE_URL`)}function readRequiredEnvironment(e){let t=process.env[e];if(t===void 0||t.length===0)throw Error(`Development Workflow transport is missing ${e}.`);return t}export{MissingDevelopmentGenerationError,createDevelopmentWorkflowWorld};
1
+ import{resolvePackageSourceFilePath}from"#internal/application/package.js";import{basename,join}from"node:path";import{readFile}from"node:fs/promises";import{turnWorkflowReference}from"#execution/workflow-runtime.js";import{createDiskRuntimeCompiledArtifactsSource}from"#runtime/compiled-artifacts-source.js";import{DEVELOPMENT_WORKER_APP_ROOT_ENV,DEVELOPMENT_WORKFLOW_DELIVERY_HEADER,DEVELOPMENT_WORKFLOW_SECRET_ENV,DEVELOPMENT_WORKFLOW_STREAM_ROUTE,DEVELOPMENT_WORKFLOW_TRANSPORT_HEADER,DEVELOPMENT_WORKFLOW_WORLD_ROUTE,DEVELOPMENT_WORLD_OPERATIONS}from"#internal/workflow/development-world-protocol.js";import{timingSafeEqualStrings}from"#internal/nitro/dev-client-address.js";import{decodeDevelopmentWorldJson,decodeDevelopmentWorldValue,deserializeDevelopmentWorldError,encodeDevelopmentWorldValue}from"#internal/workflow/development-world-codec.js";import{getDevelopmentWorkflowGeneration,withDevelopmentWorkflowGeneration}from"#internal/workflow/development-generation-context.js";import{LOCAL_WORKFLOW_WORLD_DATA_DIRECTORY_RELATIVE_PATH}from"#internal/workflow/local-world-data-directory.js";var MissingDevelopmentGenerationError=class extends Error{constructor(e,t){super(`Workflow run references missing development generation "${e}". Remove "${LOCAL_WORKFLOW_WORLD_DATA_DIRECTORY_RELATIVE_PATH}" to discard the app's active local Workflow runs.`,t===void 0?void 0:{cause:t}),this.name=`MissingDevelopmentGenerationError`}};async function call(e,t=[]){return decodeDevelopmentWorldValue(await(await fetchDevelopmentWorld(DEVELOPMENT_WORKFLOW_WORLD_ROUTE,{body:encodeDevelopmentWorldValue({arguments:t,operation:e}),method:`POST`})).text())}function createDevelopmentWorkflowWorld(){let e=buildForwardedOperations();return{specVersion:5,processExitTriggersQueueRedelivery:!1,async getDeploymentId(){return getDevelopmentWorkflowGeneration()?.generationId??await call(`getDeploymentId`)},resolveLatestDeploymentId:e.topLevel.resolveLatestDeploymentId,queue:e.topLevel.queue,createQueueHandler,runs:e.groups.runs,steps:e.groups.steps,events:e.groups.events,hooks:e.groups.hooks,streams:{...e.groups.streams,get:async(e,t,n)=>{let r=new URL(resolveDevelopmentWorldBaseUrl());r.pathname=DEVELOPMENT_WORKFLOW_STREAM_ROUTE,r.searchParams.set(`runId`,e),r.searchParams.set(`name`,t),n!==void 0&&r.searchParams.set(`startIndex`,String(n));let i=await fetchDevelopmentWorld(r,{method:`GET`});if(i.body===null)throw Error(`Development Workflow stream response had no body.`);return i.body}},async start(){},async close(){}}}function buildForwardedOperations(){let e={},t={};for(let n of DEVELOPMENT_WORLD_OPERATIONS){let forward=async(...e)=>await call(n,e),r=n.indexOf(`.`);r===-1?t[n]=forward:(e[n.slice(0,r)]??={})[n.slice(r+1)]=forward}return{groups:e,topLevel:t}}function createQueueHandler(t,n){return async r=>{let i=readRequiredEnvironment(DEVELOPMENT_WORKFLOW_SECRET_ENV),c=r.headers.get(DEVELOPMENT_WORKFLOW_DELIVERY_HEADER);if(c===null||!timingSafeEqualStrings(c,i))return Response.json({error:`Workflow delivery is not trusted.`},{status:401});let l=r.headers.get(`x-vqs-queue-name`),u=r.headers.get(`x-vqs-message-id`),d=Number(r.headers.get(`x-vqs-message-attempt`));if(l===null||!l.startsWith(t)||u===null||!Number.isInteger(d)||d<1||r.body===null)return Response.json({error:`Workflow delivery is malformed.`},{status:400});let f=decodeDevelopmentWorldJson(await r.text());try{let t=readRequiredEnvironment(DEVELOPMENT_WORKER_APP_ROOT_ENV),r=await resolveDeliveryGenerationId(f),i=await withDevelopmentWorkflowGeneration({generationId:r,source:createDiskRuntimeCompiledArtifactsSource(await readGenerationRuntimeAppRoot(t,r),{durableReference:`development-generation`,moduleMapLoaderPath:resolvePackageSourceFilePath(`src/internal/authored-module-map-loader.ts`),sandboxAppRoot:t})},async()=>await n(f,{attempt:d,messageId:u,queueName:l}));return Response.json(i===void 0?{ok:!0}:{timeoutSeconds:i.timeoutSeconds})}catch(e){return e instanceof MissingDevelopmentGenerationError?(console.error(`[eve:dev] ${e.message}`),Response.json({ok:!0})):Response.json(String(e),{status:500})}}}async function resolveDeliveryGenerationId(e){if(!isRecord(e))return await call(`resolveLatestDeploymentId`);let t=isRecord(e.runInput)?e.runInput:void 0;if(t!==void 0)return t.workflowName===turnWorkflowReference.workflowId&&typeof t.deploymentId==`string`?t.deploymentId:await call(`resolveLatestDeploymentId`);let n=typeof e.runId==`string`?e.runId:typeof e.workflowRunId==`string`?e.workflowRunId:void 0;if(n===void 0)return await call(`resolveLatestDeploymentId`);let r=await call(`runs.get`,[n,{resolveData:`none`}]);return r.workflowName===turnWorkflowReference.workflowId?r.deploymentId:await call(`resolveLatestDeploymentId`)}async function readGenerationRuntimeAppRoot(e,i){if(i.length===0||i===`.`||i===`..`||basename(i)!==i)throw Error(`Workflow run references invalid development generation "${i}".`);let a=join(e,`.eve`,`dev-runtime`,`snapshots`,i,`generation.json`),o;try{o=await readFile(a,`utf8`)}catch(e){throw isFileNotFoundError(e)?new MissingDevelopmentGenerationError(i,e):e}let s;try{s=JSON.parse(o)}catch(e){throw Error(`Development generation "${i}" has invalid metadata.`,{cause:e})}if(!isRecord(s)||typeof s.runtimeAppRoot!=`string`)throw Error(`Development generation "${i}" has invalid metadata.`);return s.runtimeAppRoot}function isFileNotFoundError(e){return e instanceof Error&&`code`in e&&e.code===`ENOENT`}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function fetchDevelopmentWorld(e,t){let n=e instanceof URL?e:new URL(e,resolveDevelopmentWorldBaseUrl()),r=new Headers(t.headers);r.set(DEVELOPMENT_WORKFLOW_TRANSPORT_HEADER,readRequiredEnvironment(DEVELOPMENT_WORKFLOW_SECRET_ENV));let i=await fetch(n,{...t,headers:r});if(!i.ok){let e=await i.text(),t=readDevelopmentWorldError(e);throw t===void 0?Error(`Development Workflow World request failed (${String(i.status)}): ${e}`):t}return i}function readDevelopmentWorldError(e){try{return deserializeDevelopmentWorldError(decodeDevelopmentWorldValue(e))}catch{return}}function resolveDevelopmentWorldBaseUrl(){return readRequiredEnvironment(`WORKFLOW_LOCAL_BASE_URL`)}function readRequiredEnvironment(e){let t=process.env[e];if(t===void 0||t.length===0)throw Error(`Development Workflow transport is missing ${e}.`);return t}export{MissingDevelopmentGenerationError,createDevelopmentWorkflowWorld};
@@ -1 +1 @@
1
- import{existsSync}from"node:fs";import{basename,join}from"node:path";import{turnWorkflowReference}from"#execution/workflow-runtime.js";import{DEVELOPMENT_WORKFLOW_DELIVERY_HEADER,DEVELOPMENT_WORKFLOW_STREAM_ROUTE,DEVELOPMENT_WORKFLOW_TRANSPORT_HEADER,DEVELOPMENT_WORKFLOW_WORLD_ROUTE,DEVELOPMENT_WORLD_OPERATIONS}from"#internal/workflow/development-world-protocol.js";import{deriveEveWorkflowQueuePrefix}from"#internal/workflow/queue-namespace.js";import{timingSafeEqualStrings}from"#internal/nitro/dev-client-address.js";import{decodeDevelopmentWorldValue,encodeDevelopmentWorldValue,serializeDevelopmentWorldError}from"#internal/workflow/development-world-codec.js";import{createWorld}from"#compiled/@workflow/world-local/index.js";function createParentDevelopmentWorkflowWorld(e){return new LocalParentDevelopmentWorkflowWorld(e)}var LocalParentDevelopmentWorkflowWorld=class{#e;#t;#n;#r;#i;#a=!1;#o=!1;constructor(e){if(e.transportSecret.length<16)throw Error(`Development Workflow transport secret is too short to be trusted.`);this.#e=e.agentName,this.#t=e.appRoot,this.#n=e.resolveActiveGenerationId,this.#r=e.transportSecret,this.#i=createWorld({dataDir:join(e.appRoot,`.workflow-data`),recoverActiveRuns:!1})}async start(){if(this.#o)return;let e=await this.#s(),t=new Set;for(let n of e)this.#p(n)||t.add(n);t.size>0&&console.error(`[eve:dev] ${String(t.size)} active local Workflow run(s) reference development generations that no longer exist (${[...t].join(`, `)}). Their deliveries are quarantined; remove ".workflow-data" to discard the app's active local Workflow runs.`),await this.#i.start?.(),this.#o=!0,await reenqueueActiveDevelopmentRuns({enqueue:this.#u.bind(this),prefix:deriveEveWorkflowQueuePrefix(this.#e),quarantinedGenerationIds:t,world:this.#i})}async close(){this.#a||(this.#a=!0,this.#o=!1,await this.#i.close?.())}async handleRequest(e){let t=new URL(e.url);if(t.pathname===DEVELOPMENT_WORKFLOW_WORLD_ROUTE)return await this.#c(e);if(t.pathname===DEVELOPMENT_WORKFLOW_STREAM_ROUTE)return await this.#l(e,t)}async#s(){let e=new Set;for(let t of[`pending`,`running`]){let n;do{let i;try{i=await this.#i.runs.list({pagination:{cursor:n,limit:1e3},resolveData:`none`,status:t})}catch(e){throw Error(`Failed to read the app's active local Workflow runs. Remove ".workflow-data" to discard them.`,{cause:e})}for(let t of i.data)t.workflowName===turnWorkflowReference.workflowId&&e.add(t.deploymentId);n=i.hasMore?i.cursor??void 0:void 0}while(n!==void 0)}return e}async#c(e){if(!this.#f(e)||e.method!==`POST`)return Response.json({error:`Workflow World request is not trusted.`},{status:401});try{let t=decodeDevelopmentWorldValue(await e.text()),n=await this.#d(t);return new Response(encodeDevelopmentWorldValue(n))}catch(e){return new Response(encodeDevelopmentWorldValue(serializeDevelopmentWorldError(e)),{status:500})}}async#l(e,t){if(!this.#f(e)||e.method!==`GET`)return Response.json({error:`Workflow World request is not trusted.`},{status:401});let n=t.searchParams.get(`runId`),r=t.searchParams.get(`name`),i=t.searchParams.get(`startIndex`);if(n===null||r===null)return Response.json({error:`Workflow stream request is malformed.`},{status:400});let a=i===null||i===``?void 0:Number(i);if(i===``||a!==void 0&&!Number.isInteger(a))return Response.json({error:`Workflow stream start index is invalid.`},{status:400});try{return new Response(await this.#i.streams.get(n,r,a))}catch(e){return new Response(encodeDevelopmentWorldValue(serializeDevelopmentWorldError(e)),{status:500})}}async#u(...e){let[t,n,r]=e;return await this.#i.queue(t,n,{...r,headers:{...r?.headers,[DEVELOPMENT_WORKFLOW_DELIVERY_HEADER]:this.#r}})}async#d(e){if(!isDevelopmentWorldCall(e))throw Error(`Development Workflow World call is malformed.`);let t=[...e.arguments];if(e.operation===`getDeploymentId`||e.operation===`resolveLatestDeploymentId`)return this.#n();if(e.operation===`queue`)return await this.#u(...t);if(e.operation===`streams.writeMulti`&&this.#i.streams.writeMulti===void 0){for(let e of t[2])await this.#i.streams.write(t[0],t[1],e);return}let n=e.operation.indexOf(`.`),r=this.#i[e.operation.slice(0,n)],i=typeof r==`object`&&r?r[e.operation.slice(n+1)]:void 0;if(typeof i==`function`)return await Reflect.apply(i,r,t)}#f(e){let t=e.headers.get(DEVELOPMENT_WORKFLOW_TRANSPORT_HEADER);return t!==null&&timingSafeEqualStrings(t,this.#r)}#p(t){return isValidGenerationId(t)?existsSync(join(this.#t,`.eve`,`dev-runtime`,`snapshots`,t,`generation.json`)):!1}};function isValidGenerationId(e){return e.length>0&&e!==`.`&&e!==`..`&&basename(e)===e}const DEVELOPMENT_WORLD_OPERATION_SET=new Set(DEVELOPMENT_WORLD_OPERATIONS);function isDevelopmentWorldCall(e){return isObject(e)&&typeof e.operation==`string`&&DEVELOPMENT_WORLD_OPERATION_SET.has(e.operation)&&Array.isArray(e.arguments)}function isObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function reenqueueActiveDevelopmentRuns(e){for(let t of[`pending`,`running`]){let n;do{let r;try{r=await e.world.runs.list({pagination:{cursor:n},resolveData:`none`,status:t})}catch(e){throw Error(`Failed to read the app's active local Workflow runs. Remove ".workflow-data" to discard them.`,{cause:e})}for(let t of r.data)e.quarantinedGenerationIds.has(t.deploymentId)||await e.enqueue(`${e.prefix}${t.workflowName}`,{runId:t.runId});n=r.hasMore?r.cursor??void 0:void 0}while(n!==void 0)}}export{createParentDevelopmentWorkflowWorld};
1
+ import{existsSync}from"node:fs";import{basename,join}from"node:path";import{turnWorkflowReference}from"#execution/workflow-runtime.js";import{DEVELOPMENT_WORKFLOW_DELIVERY_HEADER,DEVELOPMENT_WORKFLOW_STREAM_ROUTE,DEVELOPMENT_WORKFLOW_TRANSPORT_HEADER,DEVELOPMENT_WORKFLOW_WORLD_ROUTE,DEVELOPMENT_WORLD_OPERATIONS}from"#internal/workflow/development-world-protocol.js";import{deriveEveWorkflowQueuePrefix}from"#internal/workflow/queue-namespace.js";import{timingSafeEqualStrings}from"#internal/nitro/dev-client-address.js";import{decodeDevelopmentWorldValue,encodeDevelopmentWorldValue,serializeDevelopmentWorldError}from"#internal/workflow/development-world-codec.js";import{LOCAL_WORKFLOW_WORLD_DATA_DIRECTORY_RELATIVE_PATH,resolveLocalWorkflowWorldDataDirectory}from"#internal/workflow/local-world-data-directory.js";import{createWorld}from"#compiled/@workflow/world-local/index.js";function createParentDevelopmentWorkflowWorld(e){return new LocalParentDevelopmentWorkflowWorld(e)}var LocalParentDevelopmentWorkflowWorld=class{#e;#t;#n;#r;#i;#a=!1;#o=!1;constructor(e){if(e.transportSecret.length<16)throw Error(`Development Workflow transport secret is too short to be trusted.`);this.#e=e.agentName,this.#t=e.appRoot,this.#n=e.resolveActiveGenerationId,this.#r=e.transportSecret,this.#i=createWorld({dataDir:resolveLocalWorkflowWorldDataDirectory(e.appRoot),recoverActiveRuns:!1})}async start(){if(this.#o)return;let e=await this.#s(),t=new Set;for(let n of e)this.#p(n)||t.add(n);t.size>0&&console.error(`[eve:dev] ${String(t.size)} active local Workflow run(s) reference development generations that no longer exist (${[...t].join(`, `)}). Their deliveries are quarantined; remove "${LOCAL_WORKFLOW_WORLD_DATA_DIRECTORY_RELATIVE_PATH}" to discard the app's active local Workflow runs.`),await this.#i.start?.(),this.#o=!0,await reenqueueActiveDevelopmentRuns({enqueue:this.#u.bind(this),prefix:deriveEveWorkflowQueuePrefix(this.#e),quarantinedGenerationIds:t,world:this.#i})}async close(){this.#a||(this.#a=!0,this.#o=!1,await this.#i.close?.())}async handleRequest(e){let t=new URL(e.url);if(t.pathname===DEVELOPMENT_WORKFLOW_WORLD_ROUTE)return await this.#c(e);if(t.pathname===DEVELOPMENT_WORKFLOW_STREAM_ROUTE)return await this.#l(e,t)}async#s(){let e=new Set;for(let t of[`pending`,`running`]){let n;do{let i;try{i=await this.#i.runs.list({pagination:{cursor:n,limit:1e3},resolveData:`none`,status:t})}catch(e){throw Error(`Failed to read the app's active local Workflow runs. Remove "${LOCAL_WORKFLOW_WORLD_DATA_DIRECTORY_RELATIVE_PATH}" to discard them.`,{cause:e})}for(let t of i.data)t.workflowName===turnWorkflowReference.workflowId&&e.add(t.deploymentId);n=i.hasMore?i.cursor??void 0:void 0}while(n!==void 0)}return e}async#c(e){if(!this.#f(e)||e.method!==`POST`)return Response.json({error:`Workflow World request is not trusted.`},{status:401});try{let t=decodeDevelopmentWorldValue(await e.text()),n=await this.#d(t);return new Response(encodeDevelopmentWorldValue(n))}catch(e){return new Response(encodeDevelopmentWorldValue(serializeDevelopmentWorldError(e)),{status:500})}}async#l(e,t){if(!this.#f(e)||e.method!==`GET`)return Response.json({error:`Workflow World request is not trusted.`},{status:401});let n=t.searchParams.get(`runId`),r=t.searchParams.get(`name`),i=t.searchParams.get(`startIndex`);if(n===null||r===null)return Response.json({error:`Workflow stream request is malformed.`},{status:400});let a=i===null||i===``?void 0:Number(i);if(i===``||a!==void 0&&!Number.isInteger(a))return Response.json({error:`Workflow stream start index is invalid.`},{status:400});try{return new Response(await this.#i.streams.get(n,r,a))}catch(e){return new Response(encodeDevelopmentWorldValue(serializeDevelopmentWorldError(e)),{status:500})}}async#u(...e){let[t,n,r]=e;return await this.#i.queue(t,n,{...r,headers:{...r?.headers,[DEVELOPMENT_WORKFLOW_DELIVERY_HEADER]:this.#r}})}async#d(e){if(!isDevelopmentWorldCall(e))throw Error(`Development Workflow World call is malformed.`);let t=[...e.arguments];if(e.operation===`getDeploymentId`||e.operation===`resolveLatestDeploymentId`)return this.#n();if(e.operation===`queue`)return await this.#u(...t);if(e.operation===`streams.writeMulti`&&this.#i.streams.writeMulti===void 0){for(let e of t[2])await this.#i.streams.write(t[0],t[1],e);return}let n=e.operation.indexOf(`.`),r=this.#i[e.operation.slice(0,n)],i=typeof r==`object`&&r?r[e.operation.slice(n+1)]:void 0;if(typeof i==`function`)return await Reflect.apply(i,r,t)}#f(e){let t=e.headers.get(DEVELOPMENT_WORKFLOW_TRANSPORT_HEADER);return t!==null&&timingSafeEqualStrings(t,this.#r)}#p(t){return isValidGenerationId(t)?existsSync(join(this.#t,`.eve`,`dev-runtime`,`snapshots`,t,`generation.json`)):!1}};function isValidGenerationId(e){return e.length>0&&e!==`.`&&e!==`..`&&basename(e)===e}const DEVELOPMENT_WORLD_OPERATION_SET=new Set(DEVELOPMENT_WORLD_OPERATIONS);function isDevelopmentWorldCall(e){return isObject(e)&&typeof e.operation==`string`&&DEVELOPMENT_WORLD_OPERATION_SET.has(e.operation)&&Array.isArray(e.arguments)}function isObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function reenqueueActiveDevelopmentRuns(e){for(let t of[`pending`,`running`]){let n;do{let r;try{r=await e.world.runs.list({pagination:{cursor:n},resolveData:`none`,status:t})}catch(e){throw Error(`Failed to read the app's active local Workflow runs. Remove "${LOCAL_WORKFLOW_WORLD_DATA_DIRECTORY_RELATIVE_PATH}" to discard them.`,{cause:e})}for(let t of r.data)e.quarantinedGenerationIds.has(t.deploymentId)||await e.enqueue(`${e.prefix}${t.workflowName}`,{runId:t.runId});n=r.hasMore?r.cursor??void 0:void 0}while(n!==void 0)}}export{createParentDevelopmentWorkflowWorld};
@@ -0,0 +1,2 @@
1
+ export declare const LOCAL_WORKFLOW_WORLD_DATA_DIRECTORY_RELATIVE_PATH = ".eve/.workflow-data";
2
+ export declare function resolveLocalWorkflowWorldDataDirectory(appRoot: string): string;
@@ -0,0 +1 @@
1
+ import{join}from"node:path";const LOCAL_WORKFLOW_WORLD_DATA_DIRECTORY_RELATIVE_PATH=`.eve/.workflow-data`;function resolveLocalWorkflowWorldDataDirectory(e){return join(e,LOCAL_WORKFLOW_WORLD_DATA_DIRECTORY_RELATIVE_PATH)}export{LOCAL_WORKFLOW_WORLD_DATA_DIRECTORY_RELATIVE_PATH,resolveLocalWorkflowWorldDataDirectory};
@@ -1,9 +1,9 @@
1
- import{builtinModules}from"node:module";import{resolveWorkflowModulePath}from"#internal/application/package.js";import{existsSync}from"node:fs";import{dirname,join,relative,resolve}from"node:path";import{mkdir,readFile,readdir}from"node:fs/promises";import{atomicWriteFile}from"#shared/atomic-write-file.js";import{buildWithNitroRolldown,getSingleRolldownChunk}from"#internal/bundler/nitro-rolldown.js";import{WORKFLOW_STEP_EXTERNAL_PACKAGES}from"#internal/workflow-bundle/vercel-workflow-output.js";import{applyWorkflowTransform,getImportPath}from"#internal/workflow-bundle/workflow-builders.js";const WORKFLOW_VIRTUAL_ENTRY_ID=`\0eve-workflow-entry`,PSEUDO_PACKAGES=new Set([`server-only`,`client-only`,`next/dist/compiled/server-only`,`next/dist/compiled/client-only`]),NODE_BUILTIN_MODULES=new Set([...builtinModules,...builtinModules.map(e=>`node:${e}`)]),WORKFLOW_INPUT_EXTENSIONS=new Set([`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`]),IGNORED_INPUT_DIRECTORIES=new Set([`node_modules`,`.git`,`.next`,`.nuxt`,`.output`,`.vercel`,`.workflow-data`,`.workflow-vitest`,`.well-known`,`.svelte-kit`,`.turbo`,`.cache`,`.yarn`,`.pnpm-store`]);async function collectWorkflowInputFiles(e){let t=[];async function visit(e){let n;try{n=await readdir(e,{withFileTypes:!0})}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}for(let r of n){if(r.isDirectory()){IGNORED_INPUT_DIRECTORIES.has(r.name)||await visit(join(e,r.name));continue}if(!r.isFile())continue;let n=r.name.match(/\.[^.]+$/)?.[0];n!==void 0&&WORKFLOW_INPUT_EXTENSIONS.has(n)&&t.push(join(e,r.name))}}return await visit(e),t}function createWorkflowImport(e,t){let{importPath:n,isPackage:r}=getImportPath(e,t);return r?`import ${JSON.stringify(n)};`:`import ${JSON.stringify(toRelativeImportSpecifier(t,e))};`}function createWorkflowVirtualEntryPlugin(e){return{name:`eve-workflow-virtual-entry`,resolveId(e){if(e===`\0eve-workflow-entry`)return{id:e}},load(t){if(t===`\0eve-workflow-entry`)return{code:e,moduleSideEffects:!0,moduleType:`js`}}}}function createWorkflowPseudoPackagePlugin(){return{name:`eve-workflow-pseudo-packages`,resolveId(e){if(PSEUDO_PACKAGES.has(e))return{id:`\0eve-workflow-pseudo-package:${e}`}},load(e){if(e.startsWith(`\0eve-workflow-pseudo-package:`))return{code:``,moduleType:`js`}}}}function createWorkflowRuntimeAliasPlugin(){return{name:`eve-workflow-runtime-aliases`,resolveId(e){if(!(e!==`workflow`&&!e.startsWith(`workflow/`)))return resolveWorkflowModulePath(e)}}}function createEvePackageImportsPlugin(e,t={}){return{name:`eve-package-imports`,resolveId(n){let r=n.match(/^#compiled\/(.+)$/)?.[1];if(r!==void 0)return t.workflowCondition===!0&&r===`@workflow/core/index.js`?resolveFirstExistingPath([join(e,`src`,`internal`,`workflow-bundle`,`workflow-core-shim.ts`),join(e,`dist`,`src`,`internal`,`workflow-bundle`,`workflow-core-shim.js`)]):resolveFirstExistingPath([join(e,`.generated`,`compiled`,r),join(e,`dist`,`src`,`compiled`,r)]);let a=n.match(/^#(.+)\.js$/)?.[1];if(a!==void 0)return resolveFirstExistingPath([`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`].flatMap(t=>[join(e,`src`,`${a}${t}`),join(e,`dist`,`src`,`${a}${t}`)]))}}}function createWorkflowTransformPlugin(e){let t=new Set(e.sideEffectFiles?.map(e=>e.replaceAll(`\\`,`/`))??[]);return{name:`eve-workflow-transform`,async load(n){if(!isJavaScriptLikePath(n))return;let r=await readFile(n,`utf8`),i=await applyWorkflowTransform(createManifestRelativeFilepath(e.workingDir,n),r.replace(/require\(\s*(['"])server-only\1\s*\)/g,`void 0`).replace(/require\(\s*(['"])client-only\1\s*\)/g,`void 0`),e.mode??`workflow`,n,e.projectRoot);return mergeWorkflowManifest(e.manifest,i.workflowManifest),{code:i.code,map:null,moduleSideEffects:t.has(n.replaceAll(`\\`,`/`))||void 0}}}}async function bundleWorkflowStepRegistrations(e){let t=[...e.discoveredEntries.discoveredSteps].sort(),n=new Set(t),r=[...e.discoveredEntries.discoveredSerdeFiles].sort().filter(e=>!n.has(e)),i={},a=[createWorkflowImport(e.builtinsPath,e.workingDir),...t.map(t=>createWorkflowImport(t,e.workingDir)),...r.map(t=>createWorkflowImport(t,e.workingDir)),`export const __steps_registered = true;`].join(`
2
- `),o=getSingleRolldownChunk(await buildWithNitroRolldown({cwd:e.workingDir,input:WORKFLOW_VIRTUAL_ENTRY_ID,external:isWorkflowStepExternalPackage,platform:`node`,plugins:[createWorkflowVirtualEntryPlugin(a),createWorkflowPseudoPackagePlugin(),createWorkflowRuntimeAliasPlugin(),createEvePackageImportsPlugin(e.workingDir),createWorkflowTransformPlugin({manifest:i,mode:`step`,projectRoot:e.projectRoot,sideEffectFiles:[...t,...r],workingDir:e.workingDir})],resolve:{conditionNames:[`eve-source`,`node`,`import`,`default`],extensions:[`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`],mainFields:[`module`,`main`]},tsconfig:e.tsconfigPath??!1,write:!1,output:{codeSplitting:!1,comments:!1,format:`esm`,sourcemap:`inline`}}),`step registrations bundle for "${e.outfile}"`);await writeWorkflowBundleAtomically(e.outfile,o.code)}function isWorkflowStepExternalPackage(e){return WORKFLOW_STEP_EXTERNAL_PACKAGES.some(t=>e===t||e.startsWith(`${t}/`))}function createWorkflowNodeBuiltinGuardPlugin(){return{name:`eve-workflow-node-builtins`,resolveId(e,t){let n=e.startsWith(`node:`)?e.slice(5):e;if(!NODE_BUILTIN_MODULES.has(e)&&!NODE_BUILTIN_MODULES.has(n))return;let r=t?` (imported by "${t}")`:``;throw Error(`Workflow bundle cannot import Node.js builtin "${e}"${r}. Move Node.js APIs behind a "use step" function, or keep the importing module out of the workflow driver body (only reachable through a "use step").`)}}}async function bundleFinalWorkflowOutput(e){let n=e.code.endsWith(`
1
+ import{builtinModules}from"node:module";import{resolveWorkflowModulePath}from"#internal/application/package.js";import{existsSync}from"node:fs";import{dirname,join,relative,resolve}from"node:path";import{mkdir,readFile,readdir}from"node:fs/promises";import{atomicWriteFile}from"#shared/atomic-write-file.js";import{buildSingleRolldownChunk}from"#internal/bundler/nitro-rolldown.js";import{WORKFLOW_STEP_EXTERNAL_PACKAGES}from"#internal/workflow-bundle/vercel-workflow-output.js";import{applyWorkflowTransform,getImportPath}from"#internal/workflow-bundle/workflow-builders.js";const WORKFLOW_VIRTUAL_ENTRY_ID=`\0eve-workflow-entry`,PSEUDO_PACKAGES=new Set([`server-only`,`client-only`,`next/dist/compiled/server-only`,`next/dist/compiled/client-only`]),NODE_BUILTIN_MODULES=new Set([...builtinModules,...builtinModules.map(e=>`node:${e}`)]),WORKFLOW_INPUT_EXTENSIONS=new Set([`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`]),IGNORED_INPUT_DIRECTORIES=new Set([`node_modules`,`.git`,`.next`,`.nuxt`,`.output`,`.vercel`,`.workflow-vitest`,`.well-known`,`.svelte-kit`,`.turbo`,`.cache`,`.yarn`,`.pnpm-store`]);async function collectWorkflowInputFiles(e){let t=[];async function visit(e){let n;try{n=await readdir(e,{withFileTypes:!0})}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}for(let r of n){if(r.isDirectory()){IGNORED_INPUT_DIRECTORIES.has(r.name)||await visit(join(e,r.name));continue}if(!r.isFile())continue;let n=r.name.match(/\.[^.]+$/)?.[0];n!==void 0&&WORKFLOW_INPUT_EXTENSIONS.has(n)&&t.push(join(e,r.name))}}return await visit(e),t}function createWorkflowImport(e,t){let{importPath:n,isPackage:r}=getImportPath(e,t);return r?`import ${JSON.stringify(n)};`:`import ${JSON.stringify(toRelativeImportSpecifier(t,e))};`}function createWorkflowVirtualEntryPlugin(e){return{name:`eve-workflow-virtual-entry`,resolveId(e){if(e===`\0eve-workflow-entry`)return{id:e}},load(t){if(t===`\0eve-workflow-entry`)return{code:e,moduleSideEffects:!0,moduleType:`js`}}}}function createWorkflowPseudoPackagePlugin(){return{name:`eve-workflow-pseudo-packages`,resolveId(e){if(PSEUDO_PACKAGES.has(e))return{id:`\0eve-workflow-pseudo-package:${e}`}},load(e){if(e.startsWith(`\0eve-workflow-pseudo-package:`))return{code:``,moduleType:`js`}}}}function createWorkflowRuntimeAliasPlugin(){return{name:`eve-workflow-runtime-aliases`,resolveId(e){if(!(e!==`workflow`&&!e.startsWith(`workflow/`)))return resolveWorkflowModulePath(e)}}}function createEvePackageImportsPlugin(e,t={}){return{name:`eve-package-imports`,resolveId(n){let r=n.match(/^#compiled\/(.+)$/)?.[1];if(r!==void 0)return t.workflowCondition===!0&&r===`@workflow/core/index.js`?resolveFirstExistingPath([join(e,`src`,`internal`,`workflow-bundle`,`workflow-core-shim.ts`),join(e,`dist`,`src`,`internal`,`workflow-bundle`,`workflow-core-shim.js`)]):resolveFirstExistingPath([join(e,`.generated`,`compiled`,r),join(e,`dist`,`src`,`compiled`,r)]);let a=n.match(/^#(.+)\.js$/)?.[1];if(a!==void 0)return resolveFirstExistingPath([`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`].flatMap(t=>[join(e,`src`,`${a}${t}`),join(e,`dist`,`src`,`${a}${t}`)]))}}}function createWorkflowTransformPlugin(e){let t=new Set(e.sideEffectFiles?.map(e=>e.replaceAll(`\\`,`/`))??[]);return{name:`eve-workflow-transform`,async load(n){if(!isJavaScriptLikePath(n))return;let r=await readFile(n,`utf8`),i=await applyWorkflowTransform(createManifestRelativeFilepath(e.workingDir,n),r.replace(/require\(\s*(['"])server-only\1\s*\)/g,`void 0`).replace(/require\(\s*(['"])client-only\1\s*\)/g,`void 0`),e.mode??`workflow`,n,e.projectRoot);return mergeWorkflowManifest(e.manifest,i.workflowManifest),{code:i.code,map:null,moduleSideEffects:t.has(n.replaceAll(`\\`,`/`))||void 0}}}}async function bundleWorkflowStepRegistrations(e){let t=[...e.discoveredEntries.discoveredSteps].sort(),n=new Set(t),r=[...e.discoveredEntries.discoveredSerdeFiles].sort().filter(e=>!n.has(e)),i={},a=[createWorkflowImport(e.builtinsPath,e.workingDir),...t.map(t=>createWorkflowImport(t,e.workingDir)),...r.map(t=>createWorkflowImport(t,e.workingDir)),`export const __steps_registered = true;`].join(`
2
+ `),o=await buildSingleRolldownChunk(`step registrations bundle for "${e.outfile}"`,{cwd:e.workingDir,input:WORKFLOW_VIRTUAL_ENTRY_ID,external:isWorkflowStepExternalPackage,platform:`node`,plugins:[createWorkflowVirtualEntryPlugin(a),createWorkflowPseudoPackagePlugin(),createWorkflowRuntimeAliasPlugin(),createEvePackageImportsPlugin(e.workingDir),createWorkflowTransformPlugin({manifest:i,mode:`step`,projectRoot:e.projectRoot,sideEffectFiles:[...t,...r],workingDir:e.workingDir})],resolve:{conditionNames:[`eve-source`,`node`,`import`,`default`],extensions:[`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`],mainFields:[`module`,`main`]},tsconfig:e.tsconfigPath??!1,output:{comments:!1,format:`esm`,sourcemap:`inline`}});await writeWorkflowBundleAtomically(e.outfile,o.code)}function isWorkflowStepExternalPackage(e){return WORKFLOW_STEP_EXTERNAL_PACKAGES.some(t=>e===t||e.startsWith(`${t}/`))}function createWorkflowNodeBuiltinGuardPlugin(){return{name:`eve-workflow-node-builtins`,resolveId(e,t){let n=e.startsWith(`node:`)?e.slice(5):e;if(!NODE_BUILTIN_MODULES.has(e)&&!NODE_BUILTIN_MODULES.has(n))return;let r=t?` (imported by "${t}")`:``;throw Error(`Workflow bundle cannot import Node.js builtin "${e}"${r}. Move Node.js APIs behind a "use step" function, or keep the importing module out of the workflow driver body (only reachable through a "use step").`)}}}async function bundleFinalWorkflowOutput(e){let n=e.code.endsWith(`
3
3
  `)?e.code:`${e.code}\n`,r=resolveWorkflowModulePath(`workflow/runtime`).replaceAll(`\\`,`/`),i=`// biome-ignore-all lint: generated file
4
4
  /* eslint-disable */
5
5
  import { workflowEntrypoint } from ${JSON.stringify(r)};
6
6
 
7
7
  const workflowCode = \`${n.replace(/[\\`$]/g,`\\$&`)}\`;
8
8
 
9
- export const POST = workflowEntrypoint(workflowCode, { namespace: ${JSON.stringify(e.queueNamespace)} });`;if(!e.bundleFinalOutput){await writeWorkflowBundleAtomically(e.outfile,i);return}let a=getSingleRolldownChunk(await buildWithNitroRolldown({cwd:e.workingDir,input:WORKFLOW_VIRTUAL_ENTRY_ID,external:e=>e===`@aws-sdk/credential-provider-web-identity`,platform:`node`,plugins:[createWorkflowVirtualEntryPlugin(i)],write:!1,output:{comments:!1,format:e.format,sourcemap:!1}}),`final workflow bundle for "${e.outfile}"`);await writeWorkflowBundleAtomically(e.outfile,a.code)}function convertStepsManifest(e){let t={};for(let[n,r]of Object.entries(e??{})){t[n]={};for(let[e,i]of Object.entries(r))t[n][e]={stepId:i.stepId}}return t}function convertWorkflowsManifest(e){let t={};for(let[n,r]of Object.entries(e??{})){t[n]={};for(let[e,i]of Object.entries(r))t[n][e]={graph:{edges:[],nodes:[]},workflowId:i.workflowId}}return t}function convertClassesManifest(e){let t={};for(let[n,r]of Object.entries(e??{})){t[n]={};for(let[e,i]of Object.entries(r))t[n][e]={classId:i.classId}}return t}function toRelativeImportSpecifier(e,t){let n=relative(e,t).replaceAll(`\\`,`/`);return n.startsWith(`./`)||n.startsWith(`../`)?n:`./${n}`}function resolveFirstExistingPath(e){for(let t of e)if(existsSync(t))return{id:resolve(t)}}async function writeWorkflowBundleAtomically(e,t){await mkdir(dirname(e),{recursive:!0}),await atomicWriteFile(e,t)}function mergeWorkflowManifest(e,t){e.steps=mergeWorkflowManifestSection(e.steps,t.steps),e.workflows=mergeWorkflowManifestSection(e.workflows,t.workflows),e.classes=mergeWorkflowManifestSection(e.classes,t.classes)}function mergeWorkflowManifestSection(e,t){if(t===void 0)return e;let n={...e};for(let[e,r]of Object.entries(t))n[e]={...n[e],...r};return n}function createManifestRelativeFilepath(e,t){let n=t.replaceAll(`\\`,`/`),r=relative(e.replaceAll(`\\`,`/`),n).replaceAll(`\\`,`/`);return r.startsWith(`../`)&&(r=r.split(`/`).filter(e=>e!==`..`).join(`/`)),r}function isJavaScriptLikePath(e){return/\.(?:[cm]?[jt]sx?)$/.test(e)}export{WORKFLOW_VIRTUAL_ENTRY_ID,bundleFinalWorkflowOutput,bundleWorkflowStepRegistrations,collectWorkflowInputFiles,convertClassesManifest,convertStepsManifest,convertWorkflowsManifest,createEvePackageImportsPlugin,createWorkflowImport,createWorkflowNodeBuiltinGuardPlugin,createWorkflowPseudoPackagePlugin,createWorkflowRuntimeAliasPlugin,createWorkflowTransformPlugin,createWorkflowVirtualEntryPlugin};
9
+ export const POST = workflowEntrypoint(workflowCode, { namespace: ${JSON.stringify(e.queueNamespace)} });`;if(!e.bundleFinalOutput){await writeWorkflowBundleAtomically(e.outfile,i);return}let a=await buildSingleRolldownChunk(`final workflow bundle for "${e.outfile}"`,{cwd:e.workingDir,input:WORKFLOW_VIRTUAL_ENTRY_ID,external:e=>e===`@aws-sdk/credential-provider-web-identity`,platform:`node`,plugins:[createWorkflowVirtualEntryPlugin(i)],output:{comments:!1,format:e.format,sourcemap:!1}});await writeWorkflowBundleAtomically(e.outfile,a.code)}function convertStepsManifest(e){let t={};for(let[n,r]of Object.entries(e??{})){t[n]={};for(let[e,i]of Object.entries(r))t[n][e]={stepId:i.stepId}}return t}function convertWorkflowsManifest(e){let t={};for(let[n,r]of Object.entries(e??{})){t[n]={};for(let[e,i]of Object.entries(r))t[n][e]={graph:{edges:[],nodes:[]},workflowId:i.workflowId}}return t}function convertClassesManifest(e){let t={};for(let[n,r]of Object.entries(e??{})){t[n]={};for(let[e,i]of Object.entries(r))t[n][e]={classId:i.classId}}return t}function toRelativeImportSpecifier(e,t){let n=relative(e,t).replaceAll(`\\`,`/`);return n.startsWith(`./`)||n.startsWith(`../`)?n:`./${n}`}function resolveFirstExistingPath(e){for(let t of e)if(existsSync(t))return{id:resolve(t)}}async function writeWorkflowBundleAtomically(e,t){await mkdir(dirname(e),{recursive:!0}),await atomicWriteFile(e,t)}function mergeWorkflowManifest(e,t){e.steps=mergeWorkflowManifestSection(e.steps,t.steps),e.workflows=mergeWorkflowManifestSection(e.workflows,t.workflows),e.classes=mergeWorkflowManifestSection(e.classes,t.classes)}function mergeWorkflowManifestSection(e,t){if(t===void 0)return e;let n={...e};for(let[e,r]of Object.entries(t))n[e]={...n[e],...r};return n}function createManifestRelativeFilepath(e,t){let n=t.replaceAll(`\\`,`/`),r=relative(e.replaceAll(`\\`,`/`),n).replaceAll(`\\`,`/`);return r.startsWith(`../`)&&(r=r.split(`/`).filter(e=>e!==`..`).join(`/`)),r}function isJavaScriptLikePath(e){return/\.(?:[cm]?[jt]sx?)$/.test(e)}export{WORKFLOW_VIRTUAL_ENTRY_ID,bundleFinalWorkflowOutput,bundleWorkflowStepRegistrations,collectWorkflowInputFiles,convertClassesManifest,convertStepsManifest,convertWorkflowsManifest,createEvePackageImportsPlugin,createWorkflowImport,createWorkflowNodeBuiltinGuardPlugin,createWorkflowPseudoPackagePlugin,createWorkflowRuntimeAliasPlugin,createWorkflowTransformPlugin,createWorkflowVirtualEntryPlugin};
@@ -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{buildWithNitroRolldown,getSingleRolldownChunk}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;config;#i=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=deriveEveWorkflowQueueNamespace(t.agentName)}async build(e={}){await runQueuedWorkflowBuild(this.#n,async()=>this.#a(e))}async#a(i){await prepareEveVersionedCacheDirectory(this.#n);let a=await this.#o();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.#r);let m=i.nitroWorkflowOutfile;m!==void 0&&m!==l&&(await mkdir(dirname(m),{recursive:!0}),await mirrorFileBypassingUnlink(l,m),p!==void 0&&(await addStepRegistrationsImport(m,p),await rewriteWorkflowRuntimeImports(m),await rewriteWorkflowCodeLiteral(m,this.#r))),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.#i.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.#i.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={},h=[...l.map(e=>createWorkflowImport(e,this.config.workingDir)),...d.map(e=>createWorkflowImport(e,this.config.workingDir))].join(`
2
- `);return await bundleFinalWorkflowOutput({bundleFinalOutput:e,code:getSingleRolldownChunk(await buildWithNitroRolldown({cwd:this.config.workingDir,input:WORKFLOW_VIRTUAL_ENTRY_ID,platform:`neutral`,plugins:[createWorkflowVirtualEntryPlugin(h),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,write:!1,output:{banner:`globalThis.__private_workflows = new Map();`,codeSplitting:!1,comments:!1,format:`cjs`,sourcemap:`inline`}}),`intermediate workflow bundle for "${o}"`).code,format:r,outfile:o,queueNamespace:this.#r,workingDir:this.config.workingDir}),a?{bundleFinal:async t=>{await bundleFinalWorkflowOutput({bundleFinalOutput:e,code:t,format:r,outfile:o,queueNamespace:this.#r,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.#s(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#o(){return await this.getInputFiles()}async#s(e,t){let n=join(e,`.vc-config.json`),i=await this.#c(n),a={...i};a.environment=createWorkflowFunctionEnvironment(i.environment),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#c(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{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;config;#i=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=deriveEveWorkflowQueueNamespace(t.agentName)}async build(e={}){await runQueuedWorkflowBuild(this.#n,async()=>this.#a(e))}async#a(i){await prepareEveVersionedCacheDirectory(this.#n);let a=await this.#o();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.#r);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.#r))),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.#i.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.#i.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.#r,workingDir:this.config.workingDir}),a?{bundleFinal:async t=>{await bundleFinalWorkflowOutput({bundleFinalOutput:e,code:t,format:r,outfile:o,queueNamespace:this.#r,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.#s(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#o(){return await this.getInputFiles()}async#s(e,t){let n=join(e,`.vc-config.json`),i=await this.#c(n),a={...i};a.environment=createWorkflowFunctionEnvironment(i.environment),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#c(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(`
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};
@@ -1,3 +1,3 @@
1
- import{basename,dirname,extname,join,relative}from"node:path";import{cp,mkdir,readFile,readdir,realpath,rename,rm,symlink,writeFile}from"node:fs/promises";import{buildWithNitroRolldown,getSingleRolldownChunk}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={};return isRecord(e)&&Object.assign(t,e),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),s;try{s=await realpath(n)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return null;throw e}let c=`${i}.eve-staging`;return await mkdir(dirname(i),{recursive:!0}),await rm(c,{force:!0,recursive:!0}),await cp(s,c,{dereference:!0,recursive:!0}),await rm(i,{force:!0,recursive:!0}),await rename(c,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({build:buildWithNitroRolldown,pluginPaths:e.pluginPaths??[],targetPath:e.targetPath}),i=join(dirname(e.bundlePath),`__eve_workflow_function_entry.js`),a=getSingleRolldownChunk(await buildWithNitroRolldown({cwd:dirname(e.bundlePath),input:i,platform:`node`,plugins:[createVirtualModulePlugin({id:i,moduleType:`js`,source:createWorkflowFunctionEntrypointSource({bundlePath:e.bundlePath,pluginModulePaths:n})})],write:!1,output:{codeSplitting:!1,comments:!1,format:`cjs`,sourcemap:!1}}),`Vercel workflow function for "${e.bundlePath}"`);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(),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=getSingleRolldownChunk(await e.build({input:t,platform:`node`,write:!1,output:{codeSplitting:!1,comments:!1,format:`esm`,sourcemap:!1}}),`workflow plugin for "${t}"`),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(`
1
+ import{basename,dirname,extname,join,relative}from"node:path";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={};return isRecord(e)&&Object.assign(t,e),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),s;try{s=await realpath(n)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return null;throw e}let c=`${i}.eve-staging`;return await mkdir(dirname(i),{recursive:!0}),await rm(c,{force:!0,recursive:!0}),await cp(s,c,{dereference:!0,recursive:!0}),await rm(i,{force:!0,recursive:!0}),await rename(c,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(),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
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
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};
@@ -8,7 +8,7 @@ export declare const EVE_STREAM_FORMAT_HEADER = "x-eve-stream-format";
8
8
  export declare const EVE_STREAM_VERSION_HEADER = "x-eve-stream-version";
9
9
  export declare const EVE_MESSAGE_STREAM_CONTENT_TYPE = "application/x-ndjson; charset=utf-8";
10
10
  export declare const EVE_MESSAGE_STREAM_FORMAT = "ndjson";
11
- export declare const EVE_MESSAGE_STREAM_VERSION = "18";
11
+ export declare const EVE_MESSAGE_STREAM_VERSION = "19";
12
12
  /**
13
13
  * eve-owned finish reason for one completed assistant step.
14
14
  *
@@ -397,6 +397,19 @@ export interface TurnFailedStreamEvent {
397
397
  };
398
398
  type: "turn.failed";
399
399
  }
400
+ /**
401
+ * Stream event emitted when one turn is cancelled before reaching a
402
+ * terminal outcome. Cancellation is not failure: the turn ends without
403
+ * `turn.failed`/`session.failed`, is followed by `session.waiting`, and
404
+ * the session accepts the next message normally.
405
+ */
406
+ export interface TurnCancelledStreamEvent {
407
+ data: {
408
+ sequence: number;
409
+ turnId: string;
410
+ };
411
+ type: "turn.cancelled";
412
+ }
400
413
  /**
401
414
  * Stream event emitted when the workflow decides to compact the current
402
415
  * visible session history before the next model fragment runs.
@@ -480,6 +493,8 @@ export interface AuthorizationCompletedStreamEvent {
480
493
  */
481
494
  export interface SessionWaitingStreamEvent {
482
495
  data: {
496
+ /** Channel-owned resume handle for the next user turn. */
497
+ continuationToken: string;
483
498
  wait: "next-user-message";
484
499
  };
485
500
  type: "session.waiting";
@@ -505,7 +520,7 @@ export interface SessionCompletedStreamEvent {
505
520
  /**
506
521
  * Serializable stream event union for the durable message session flow.
507
522
  */
508
- export type HandleMessageStreamEvent = (CompactionCompletedStreamEvent | CompactionRequestedStreamEvent | AuthorizationCompletedStreamEvent | AuthorizationRequiredStreamEvent | MessageAppendedStreamEvent | MessageCompletedStreamEvent | MessageReceivedStreamEvent | ReasoningAppendedStreamEvent | SessionCompletedStreamEvent | SessionFailedStreamEvent | SessionStartedStreamEvent | SessionWaitingStreamEvent | ResultCompletedStreamEvent | SubagentCalledStreamEvent | SubagentChildEventStreamEvent | SubagentCompletedStreamEvent | SubagentStartedStreamEvent | ActionsRequestedStreamEvent | InputRequestedStreamEvent | ActionResultStreamEvent | ReasoningCompletedStreamEvent | StepCompletedStreamEvent | StepFailedStreamEvent | StepStartedStreamEvent | TurnCompletedStreamEvent | TurnFailedStreamEvent | TurnStartedStreamEvent) & {
523
+ export type HandleMessageStreamEvent = (CompactionCompletedStreamEvent | CompactionRequestedStreamEvent | AuthorizationCompletedStreamEvent | AuthorizationRequiredStreamEvent | MessageAppendedStreamEvent | MessageCompletedStreamEvent | MessageReceivedStreamEvent | ReasoningAppendedStreamEvent | SessionCompletedStreamEvent | SessionFailedStreamEvent | SessionStartedStreamEvent | SessionWaitingStreamEvent | ResultCompletedStreamEvent | SubagentCalledStreamEvent | SubagentChildEventStreamEvent | SubagentCompletedStreamEvent | SubagentStartedStreamEvent | ActionsRequestedStreamEvent | InputRequestedStreamEvent | ActionResultStreamEvent | ReasoningCompletedStreamEvent | StepCompletedStreamEvent | StepFailedStreamEvent | StepStartedStreamEvent | TurnCancelledStreamEvent | TurnCompletedStreamEvent | TurnFailedStreamEvent | TurnStartedStreamEvent) & {
509
524
  readonly meta?: HandleMessageStreamEventMeta;
510
525
  };
511
526
  /**
@@ -739,6 +754,11 @@ export declare function createTurnFailedEvent(input: {
739
754
  readonly sequence: number;
740
755
  readonly turnId: string;
741
756
  }): TurnFailedStreamEvent;
757
+ /** Creates the `turn.cancelled` event for one cancelled turn. */
758
+ export declare function createTurnCancelledEvent(input: {
759
+ readonly sequence: number;
760
+ readonly turnId: string;
761
+ }): TurnCancelledStreamEvent;
742
762
  /**
743
763
  * Creates the `compaction.requested` event for one runtime compaction pass.
744
764
  */
@@ -762,7 +782,7 @@ export declare function createCompactionCompletedEvent(input: {
762
782
  * Creates the `session.waiting` event for the only supported between-turn
763
783
  * wait.
764
784
  */
765
- export declare function createSessionWaitingEvent(): SessionWaitingStreamEvent;
785
+ export declare function createSessionWaitingEvent(namespacedContinuationToken: string): SessionWaitingStreamEvent;
766
786
  /**
767
787
  * Creates the `session.failed` event for one terminal session failure.
768
788
  */
@@ -1,2 +1,2 @@
1
- import{deserializeUrlFilePart,hasInternalRefScheme,isSerializedUrlFilePart}from"#internal/attachments/url-refs.js";import{decodeSandboxRef,isSandboxRefUrl}from"#internal/attachments/sandbox-refs.js";const EVE_SESSION_ID_HEADER=`x-eve-session-id`,EVE_STREAM_FORMAT_HEADER=`x-eve-stream-format`,EVE_STREAM_VERSION_HEADER=`x-eve-stream-version`,EVE_MESSAGE_STREAM_CONTENT_TYPE=`application/x-ndjson; charset=utf-8`,EVE_MESSAGE_STREAM_FORMAT=`ndjson`,EVE_MESSAGE_STREAM_VERSION=`18`,textEncoder=new TextEncoder;function isCurrentTurnBoundaryEvent(e){return e.type===`session.completed`||e.type===`session.failed`||e.type===`session.waiting`}function isTurnFailureEvent(e){return e.type===`session.failed`||e.type===`step.failed`||e.type===`turn.failed`}function createSessionStartedEvent(e){let t={};return e?.invocation!==void 0&&(t.invocation=e.invocation),e?.runtime!==void 0&&(t.runtime=e.runtime),{data:t,type:`session.started`}}function createTurnStartedEvent(e){return{data:{sequence:e.sequence,turnId:e.turnId},type:`turn.started`}}function createMessageReceivedEvent(e){return{data:{message:summarizeUserContent(e.message),parts:projectUserContentParts(e.message),sequence:e.sequence,turnId:e.turnId},type:`message.received`}}function summarizeUserContent(e){if(typeof e==`string`)return e;let t=[];for(let n of e)if(n.type===`text`)t.push(n.text);else if(n.type===`file`){let e=n.filename??n.mediaType;t.push(`[file: ${e} (${n.mediaType})]`)}else n.type===`image`&&t.push(`[image: ${n.mediaType??`image`}]`);return t.join(`
2
- `)}function projectUserContentParts(e){if(typeof e==`string`)return[{text:e,type:`text`}];let t=[];for(let n of e)n.type===`text`?t.push({text:n.text,type:`text`}):n.type===`file`?t.push(projectFileLikePart(n.data,n.mediaType,n.filename)):n.type===`image`&&t.push(projectFileLikePart(n.image,n.mediaType??`application/octet-stream`,void 0));return t}function projectFileLikePart(e,t,n){if(isSandboxRefUrl(e)){let t=decodeSandboxRef(e);return createProjectedFilePart({filename:basenameOf(n??t.path),mediaType:t.mediaType,size:t.size})}let i=projectTaggedFileData(e,t,n);if(i!==void 0)return i;let a=byteLengthOf(e);return createProjectedFilePart(a===void 0?{filename:n,mediaType:t,...clientUrlFragment(e)}:{filename:n,mediaType:t,size:a})}function projectTaggedFileData(e,t,n){if(isTaggedFileData(e))switch(e.type){case`data`:{let r=byteLengthOf(e.data);return createProjectedFilePart(r===void 0?{filename:n,mediaType:t}:{filename:n,mediaType:t,size:r})}case`reference`:case`text`:return createProjectedFilePart({filename:n,mediaType:t});case`url`:return createProjectedFilePart({filename:n,mediaType:t,...clientUrlFragment(e.url)})}}function createProjectedFilePart(e){let t={mediaType:e.mediaType,type:`file`};return e.filename!==void 0&&(t.filename=e.filename),e.size!==void 0&&(t.size=e.size),e.url!==void 0&&(t.url=e.url),t}function isTaggedFileData(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`data`||t===`reference`||t===`text`||t===`url`}function byteLengthOf(e){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return e.byteLength}function clientUrlFragment(r){if(isSerializedUrlFilePart(r))try{let t=deserializeUrlFilePart(r);return isClientResolvableUrl(t)?{url:t.href}:{}}catch{return{}}if(r instanceof URL)return isClientResolvableUrl(r)?{url:r.href}:{};if(typeof r!=`string`||hasInternalRefScheme(r))return{};if(r.startsWith(`data:`))return{url:r};try{let e=new URL(r);return isClientResolvableUrl(e)?{url:e.href}:{}}catch{return{}}}function isClientResolvableUrl(e){return e.protocol===`http:`||e.protocol===`https:`||e.protocol===`data:`}function basenameOf(e){let t=e.replaceAll(`\\`,`/`),n=t.slice(t.lastIndexOf(`/`)+1);return n.length>0?n:e}function createActionsRequestedEvent(e){return{data:{actions:e.actions,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId},type:`actions.requested`}}function createAuthorizationRequiredEvent(e){let t={description:e.description,name:e.name,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId};return e.authorization!==void 0&&(t.authorization=e.authorization),e.webhookUrl!==void 0&&(t.webhookUrl=e.webhookUrl),{data:t,type:`authorization.required`}}function createAuthorizationCompletedEvent(e){let t={name:e.name,outcome:e.outcome,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId};return e.authorization!==void 0&&(t.authorization=e.authorization),e.reason!==void 0&&(t.reason=e.reason),{data:t,type:`authorization.completed`}}function createInputRequestedEvent(e){return{data:{requests:e.requests,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId},type:`input.requested`}}function createActionResultEvent(e){let t=e.rejected===!0?{error:buildActionResultError(e.result),status:`rejected`}:normalizeActionResultOutcome(e.result);return{data:{error:t.error,result:e.result,sequence:e.sequence,stepIndex:e.stepIndex,status:t.status,turnId:e.turnId},type:`action.result`}}function createSubagentCalledEvent(e){return{data:{callId:e.callId,childSessionId:e.childSessionId,sessionId:e.sessionId,sequence:e.sequence,name:e.name,remote:e.remote,toolName:e.toolName,turnId:e.turnId,workflowId:e.workflowId},type:`subagent.called`}}function createMessageAppendedEvent(e){return{data:{messageDelta:e.messageDelta,messageSoFar:e.messageSoFar,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId},type:`message.appended`}}function createReasoningAppendedEvent(e){return{data:{reasoningDelta:e.reasoningDelta,reasoningSoFar:e.reasoningSoFar,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId},type:`reasoning.appended`}}function createMessageCompletedEvent(e){return{data:{finishReason:e.finishReason??`stop`,message:e.message,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId},type:`message.completed`}}function createReasoningCompletedEvent(e){return{data:{reasoning:e.reasoning,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId},type:`reasoning.completed`}}function createResultCompletedEvent(e){return{data:{result:e.result,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId},type:`result.completed`}}function createStepStartedEvent(e){return{data:{sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId},type:`step.started`}}function createStepCompletedEvent(e){let t={finishReason:e.finishReason,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId};return e.usage!==void 0&&(t.usage=e.usage),e.providerMetadata!==void 0&&(t.providerMetadata=e.providerMetadata),{data:t,type:`step.completed`}}function createStepFailedEvent(e){return{data:{code:e.code,details:e.details,message:e.message,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId},type:`step.failed`}}function createTurnCompletedEvent(e){return{data:{sequence:e.sequence,turnId:e.turnId},type:`turn.completed`}}function createTurnFailedEvent(e){return{data:{code:e.code,details:e.details,message:e.message,sequence:e.sequence,turnId:e.turnId},type:`turn.failed`}}function createCompactionRequestedEvent(e){return{data:{modelId:e.modelId,sequence:e.sequence,sessionId:e.sessionId,turnId:e.turnId,usageInputTokens:e.usageInputTokens??null},type:`compaction.requested`}}function createCompactionCompletedEvent(e){return{data:{modelId:e.modelId,sequence:e.sequence,sessionId:e.sessionId,turnId:e.turnId},type:`compaction.completed`}}function createSessionWaitingEvent(){return{data:{wait:`next-user-message`},type:`session.waiting`}}function createSessionFailedEvent(e){return{data:{code:e.code,details:e.details,message:e.message,sessionId:e.sessionId},type:`session.failed`}}function createSessionCompletedEvent(){return{type:`session.completed`}}function timestampHandleMessageStreamEvent(e,t=new Date().toISOString()){return{...e,meta:{at:t}}}function encodeMessageStreamEvent(e){return textEncoder.encode(`${JSON.stringify(e)}\n`)}function normalizeActionResultOutcome(e){if(e.isError===!0)return{error:buildActionResultError(e),status:`failed`};let t=readActionResultOutputError(e.output);return t===void 0?{status:`completed`}:{error:t,status:`failed`}}function buildActionResultError(e){let t=readActionResultOutputError(e.output);return t===void 0?{code:`ACTION_RESULT_FAILED`,message:formatActionResultOutput(e.output)}:t}function readActionResultOutputError(e){let t=parseActionResultOutputRecord(e);if(t===void 0)return;let n=typeof t.code==`string`&&t.code.length>0?t.code:void 0,r=typeof t.message==`string`&&t.message.length>0?t.message:void 0;if(!(n===void 0||r===void 0))return{code:n,message:r}}function parseActionResultOutputRecord(e){if(typeof e==`object`&&e)return e;if(typeof e!=`string`)return;let t=e.trim();if(t.length!==0)try{let e=JSON.parse(t);if(typeof e==`object`&&e)return e}catch{return}}function formatActionResultOutput(e){if(typeof e==`string`)return e;let t=JSON.stringify(e);return typeof t==`string`&&t.length>0?t:`Action failed.`}export{EVE_MESSAGE_STREAM_CONTENT_TYPE,EVE_MESSAGE_STREAM_FORMAT,EVE_MESSAGE_STREAM_VERSION,EVE_SESSION_ID_HEADER,EVE_STREAM_FORMAT_HEADER,EVE_STREAM_VERSION_HEADER,createActionResultEvent,createActionsRequestedEvent,createAuthorizationCompletedEvent,createAuthorizationRequiredEvent,createCompactionCompletedEvent,createCompactionRequestedEvent,createInputRequestedEvent,createMessageAppendedEvent,createMessageCompletedEvent,createMessageReceivedEvent,createReasoningAppendedEvent,createReasoningCompletedEvent,createResultCompletedEvent,createSessionCompletedEvent,createSessionFailedEvent,createSessionStartedEvent,createSessionWaitingEvent,createStepCompletedEvent,createStepFailedEvent,createStepStartedEvent,createSubagentCalledEvent,createTurnCompletedEvent,createTurnFailedEvent,createTurnStartedEvent,encodeMessageStreamEvent,isCurrentTurnBoundaryEvent,isTurnFailureEvent,timestampHandleMessageStreamEvent};
1
+ import{toChannelLocalContinuationToken}from"#shared/continuation-token.js";import{deserializeUrlFilePart,hasInternalRefScheme,isSerializedUrlFilePart}from"#internal/attachments/url-refs.js";import{decodeSandboxRef,isSandboxRefUrl}from"#internal/attachments/sandbox-refs.js";const EVE_SESSION_ID_HEADER=`x-eve-session-id`,EVE_STREAM_FORMAT_HEADER=`x-eve-stream-format`,EVE_STREAM_VERSION_HEADER=`x-eve-stream-version`,EVE_MESSAGE_STREAM_CONTENT_TYPE=`application/x-ndjson; charset=utf-8`,EVE_MESSAGE_STREAM_FORMAT=`ndjson`,EVE_MESSAGE_STREAM_VERSION=`19`,textEncoder=new TextEncoder;function isCurrentTurnBoundaryEvent(e){return e.type===`session.completed`||e.type===`session.failed`||e.type===`session.waiting`}function isTurnFailureEvent(e){return e.type===`session.failed`||e.type===`step.failed`||e.type===`turn.failed`}function createSessionStartedEvent(e){let t={};return e?.invocation!==void 0&&(t.invocation=e.invocation),e?.runtime!==void 0&&(t.runtime=e.runtime),{data:t,type:`session.started`}}function createTurnStartedEvent(e){return{data:{sequence:e.sequence,turnId:e.turnId},type:`turn.started`}}function createMessageReceivedEvent(e){return{data:{message:summarizeUserContent(e.message),parts:projectUserContentParts(e.message),sequence:e.sequence,turnId:e.turnId},type:`message.received`}}function summarizeUserContent(e){if(typeof e==`string`)return e;let t=[];for(let n of e)if(n.type===`text`)t.push(n.text);else if(n.type===`file`){let e=n.filename??n.mediaType;t.push(`[file: ${e} (${n.mediaType})]`)}else n.type===`image`&&t.push(`[image: ${n.mediaType??`image`}]`);return t.join(`
2
+ `)}function projectUserContentParts(e){if(typeof e==`string`)return[{text:e,type:`text`}];let t=[];for(let n of e)n.type===`text`?t.push({text:n.text,type:`text`}):n.type===`file`?t.push(projectFileLikePart(n.data,n.mediaType,n.filename)):n.type===`image`&&t.push(projectFileLikePart(n.image,n.mediaType??`application/octet-stream`,void 0));return t}function projectFileLikePart(e,t,n){if(isSandboxRefUrl(e)){let t=decodeSandboxRef(e);return createProjectedFilePart({filename:basenameOf(n??t.path),mediaType:t.mediaType,size:t.size})}let r=projectTaggedFileData(e,t,n);if(r!==void 0)return r;let i=byteLengthOf(e);return createProjectedFilePart(i===void 0?{filename:n,mediaType:t,...clientUrlFragment(e)}:{filename:n,mediaType:t,size:i})}function projectTaggedFileData(e,t,n){if(isTaggedFileData(e))switch(e.type){case`data`:{let r=byteLengthOf(e.data);return createProjectedFilePart(r===void 0?{filename:n,mediaType:t}:{filename:n,mediaType:t,size:r})}case`reference`:case`text`:return createProjectedFilePart({filename:n,mediaType:t});case`url`:return createProjectedFilePart({filename:n,mediaType:t,...clientUrlFragment(e.url)})}}function createProjectedFilePart(e){let t={mediaType:e.mediaType,type:`file`};return e.filename!==void 0&&(t.filename=e.filename),e.size!==void 0&&(t.size=e.size),e.url!==void 0&&(t.url=e.url),t}function isTaggedFileData(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`data`||t===`reference`||t===`text`||t===`url`}function byteLengthOf(e){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return e.byteLength}function clientUrlFragment(e){if(isSerializedUrlFilePart(e))try{let n=deserializeUrlFilePart(e);return isClientResolvableUrl(n)?{url:n.href}:{}}catch{return{}}if(e instanceof URL)return isClientResolvableUrl(e)?{url:e.href}:{};if(typeof e!=`string`||hasInternalRefScheme(e))return{};if(e.startsWith(`data:`))return{url:e};try{let t=new URL(e);return isClientResolvableUrl(t)?{url:t.href}:{}}catch{return{}}}function isClientResolvableUrl(e){return e.protocol===`http:`||e.protocol===`https:`||e.protocol===`data:`}function basenameOf(e){let t=e.replaceAll(`\\`,`/`),n=t.slice(t.lastIndexOf(`/`)+1);return n.length>0?n:e}function createActionsRequestedEvent(e){return{data:{actions:e.actions,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId},type:`actions.requested`}}function createAuthorizationRequiredEvent(e){let t={description:e.description,name:e.name,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId};return e.authorization!==void 0&&(t.authorization=e.authorization),e.webhookUrl!==void 0&&(t.webhookUrl=e.webhookUrl),{data:t,type:`authorization.required`}}function createAuthorizationCompletedEvent(e){let t={name:e.name,outcome:e.outcome,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId};return e.authorization!==void 0&&(t.authorization=e.authorization),e.reason!==void 0&&(t.reason=e.reason),{data:t,type:`authorization.completed`}}function createInputRequestedEvent(e){return{data:{requests:e.requests,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId},type:`input.requested`}}function createActionResultEvent(e){let t=e.rejected===!0?{error:buildActionResultError(e.result),status:`rejected`}:normalizeActionResultOutcome(e.result);return{data:{error:t.error,result:e.result,sequence:e.sequence,stepIndex:e.stepIndex,status:t.status,turnId:e.turnId},type:`action.result`}}function createSubagentCalledEvent(e){return{data:{callId:e.callId,childSessionId:e.childSessionId,sessionId:e.sessionId,sequence:e.sequence,name:e.name,remote:e.remote,toolName:e.toolName,turnId:e.turnId,workflowId:e.workflowId},type:`subagent.called`}}function createMessageAppendedEvent(e){return{data:{messageDelta:e.messageDelta,messageSoFar:e.messageSoFar,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId},type:`message.appended`}}function createReasoningAppendedEvent(e){return{data:{reasoningDelta:e.reasoningDelta,reasoningSoFar:e.reasoningSoFar,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId},type:`reasoning.appended`}}function createMessageCompletedEvent(e){return{data:{finishReason:e.finishReason??`stop`,message:e.message,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId},type:`message.completed`}}function createReasoningCompletedEvent(e){return{data:{reasoning:e.reasoning,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId},type:`reasoning.completed`}}function createResultCompletedEvent(e){return{data:{result:e.result,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId},type:`result.completed`}}function createStepStartedEvent(e){return{data:{sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId},type:`step.started`}}function createStepCompletedEvent(e){let t={finishReason:e.finishReason,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId};return e.usage!==void 0&&(t.usage=e.usage),e.providerMetadata!==void 0&&(t.providerMetadata=e.providerMetadata),{data:t,type:`step.completed`}}function createStepFailedEvent(e){return{data:{code:e.code,details:e.details,message:e.message,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId},type:`step.failed`}}function createTurnCompletedEvent(e){return{data:{sequence:e.sequence,turnId:e.turnId},type:`turn.completed`}}function createTurnFailedEvent(e){return{data:{code:e.code,details:e.details,message:e.message,sequence:e.sequence,turnId:e.turnId},type:`turn.failed`}}function createTurnCancelledEvent(e){return{data:{sequence:e.sequence,turnId:e.turnId},type:`turn.cancelled`}}function createCompactionRequestedEvent(e){return{data:{modelId:e.modelId,sequence:e.sequence,sessionId:e.sessionId,turnId:e.turnId,usageInputTokens:e.usageInputTokens??null},type:`compaction.requested`}}function createCompactionCompletedEvent(e){return{data:{modelId:e.modelId,sequence:e.sequence,sessionId:e.sessionId,turnId:e.turnId},type:`compaction.completed`}}function createSessionWaitingEvent(t){return{data:{continuationToken:toChannelLocalContinuationToken(t),wait:`next-user-message`},type:`session.waiting`}}function createSessionFailedEvent(e){return{data:{code:e.code,details:e.details,message:e.message,sessionId:e.sessionId},type:`session.failed`}}function createSessionCompletedEvent(){return{type:`session.completed`}}function timestampHandleMessageStreamEvent(e,t=new Date().toISOString()){return{...e,meta:{at:t}}}function encodeMessageStreamEvent(e){return textEncoder.encode(`${JSON.stringify(e)}\n`)}function normalizeActionResultOutcome(e){if(e.isError===!0)return{error:buildActionResultError(e),status:`failed`};let t=readActionResultOutputError(e.output);return t===void 0?{status:`completed`}:{error:t,status:`failed`}}function buildActionResultError(e){let t=readActionResultOutputError(e.output);return t===void 0?{code:`ACTION_RESULT_FAILED`,message:formatActionResultOutput(e.output)}:t}function readActionResultOutputError(e){let t=parseActionResultOutputRecord(e);if(t===void 0)return;let n=typeof t.code==`string`&&t.code.length>0?t.code:void 0,r=typeof t.message==`string`&&t.message.length>0?t.message:void 0;if(!(n===void 0||r===void 0))return{code:n,message:r}}function parseActionResultOutputRecord(e){if(typeof e==`object`&&e)return e;if(typeof e!=`string`)return;let t=e.trim();if(t.length!==0)try{let e=JSON.parse(t);if(typeof e==`object`&&e)return e}catch{return}}function formatActionResultOutput(e){if(typeof e==`string`)return e;let t=JSON.stringify(e);return typeof t==`string`&&t.length>0?t:`Action failed.`}export{EVE_MESSAGE_STREAM_CONTENT_TYPE,EVE_MESSAGE_STREAM_FORMAT,EVE_MESSAGE_STREAM_VERSION,EVE_SESSION_ID_HEADER,EVE_STREAM_FORMAT_HEADER,EVE_STREAM_VERSION_HEADER,createActionResultEvent,createActionsRequestedEvent,createAuthorizationCompletedEvent,createAuthorizationRequiredEvent,createCompactionCompletedEvent,createCompactionRequestedEvent,createInputRequestedEvent,createMessageAppendedEvent,createMessageCompletedEvent,createMessageReceivedEvent,createReasoningAppendedEvent,createReasoningCompletedEvent,createResultCompletedEvent,createSessionCompletedEvent,createSessionFailedEvent,createSessionStartedEvent,createSessionWaitingEvent,createStepCompletedEvent,createStepFailedEvent,createStepStartedEvent,createSubagentCalledEvent,createTurnCancelledEvent,createTurnCompletedEvent,createTurnFailedEvent,createTurnStartedEvent,encodeMessageStreamEvent,isCurrentTurnBoundaryEvent,isTurnFailureEvent,timestampHandleMessageStreamEvent};
@@ -78,6 +78,7 @@ export interface DiscordChannelEvents {
78
78
  readonly "input.requested"?: DiscordEventHandler<"input.requested">;
79
79
  readonly "turn.failed"?: DiscordEventHandler<"turn.failed">;
80
80
  readonly "turn.completed"?: DiscordEventHandler<"turn.completed">;
81
+ readonly "turn.cancelled"?: DiscordEventHandler<"turn.cancelled">;
81
82
  readonly "session.failed"?: DiscordSessionFailedHandler;
82
83
  readonly "session.completed"?: DiscordEventHandler<"session.completed">;
83
84
  readonly "session.waiting"?: DiscordEventHandler<"session.waiting">;