import{dirname,relative}from"node:path";import{mkdir,readFile,writeFile}from"node:fs/promises";import{normalizeEsmImportSpecifier}from"#internal/application/import-specifier.js";import{applyWorkflowTransform}from"#internal/workflow-bundle/workflow-builders.js";async function writeNitroStepEntrypoint(t){let r=[...t.discoveredEntries.discoveredSteps].sort(),a=new Set(r),o=[...t.discoveredEntries.discoveredSerdeFiles].sort().filter(e=>!a.has(e)),s=await collectNitroStepManifest({projectRoot:t.projectRoot,stepFiles:r,serdeOnlyFiles:o,workingDir:t.workingDir}),c=dirname(t.outfile),l=[`// Generated by Eve. Do not edit by hand.`,...createEntrypointImportLines({builtinsImportSpecifier:t.builtinsPath===void 0?`workflow/internal/builtins`:createFileImportSpecifier({outfileDirectory:c,preferAbsoluteFileImports:t.preferAbsoluteFileImports??!1,targetPath:t.builtinsPath}),outfileDirectory:c,preferAbsoluteFileImports:t.preferAbsoluteFileImports??!1,serdeOnlyFiles:o,stepFiles:r}),`export const __steps_registered = true;`,``].join(`
`);return await mkdir(c,{recursive:!0}),await readTextFileIfPresent(t.outfile)!==l&&await writeFile(t.outfile,l),s}function createEntrypointImportLines(e){return[e.builtinsImportSpecifier,...e.stepFiles.map(t=>createFileImportSpecifier({outfileDirectory:e.outfileDirectory,preferAbsoluteFileImports:e.preferAbsoluteFileImports,targetPath:t})),...e.serdeOnlyFiles.map(t=>createFileImportSpecifier({outfileDirectory:e.outfileDirectory,preferAbsoluteFileImports:e.preferAbsoluteFileImports,targetPath:t}))].map(e=>`import ${JSON.stringify(e)};`)}function createFileImportSpecifier(e){return e.preferAbsoluteFileImports?normalizeEsmImportSpecifier(e.targetPath):createRelativeImportSpecifier(e.outfileDirectory,e.targetPath)}async function collectNitroStepManifest(e){let t={},n=[...e.stepFiles,...e.serdeOnlyFiles];for(let i of n){let n=await readFile(i,`utf8`);mergeWorkflowManifest(t,(await applyWorkflowTransform(createManifestRelativeFilepath(e.workingDir,i),n,`step`,i,e.projectRoot)).workflowManifest)}return 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,n){let r=n.replaceAll(`\\`,`/`),i=relative(e.replaceAll(`\\`,`/`),r).replaceAll(`\\`,`/`);return i.startsWith(`../`)&&(i=i.split(`/`).filter(e=>e!==`..`).join(`/`)),i}function createRelativeImportSpecifier(e,n){let r=relative(e,n).replaceAll(`\\`,`/`);return r.startsWith(`.`)?r:`./${r}`}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}}export{writeNitroStepEntrypoint};