import{expectObjectRecord}from"#internal/authored-module.js";import{dirname,join,resolve,sep}from"node:path";import{existsSync,mkdirSync,writeFileSync}from"node:fs";import{createHash}from"node:crypto";import{createAuthoredAssetImportPlugin}from"#internal/authored-asset-import-plugin.js";import{createAuthoredModuleBundleError}from"#internal/authored-module-bundle.js";import{createAuthoredPackageTsConfigPathsPlugin}from"#internal/authored-package-tsconfig-paths.js";import{buildWithNitroRolldown,getSingleRolldownChunk}from"#internal/bundler/nitro-rolldown.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`),RESOLVE_EXTENSIONS=[`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`,`.json`],CHANNEL_MODULE_CACHE_KEY=`__eveChannelModuleCache__`,CACHED_CHANNEL_PREFIX=`eve-cached-channel:`;function getChannelModuleCache(){return globalThis[CHANNEL_MODULE_CACHE_KEY]}const inFlightModuleLoads=new Map;function loadAuthoredModuleNamespace(e){let t=resolve(e),n=inFlightModuleLoads.get(t);if(n!==void 0)return n;let i=(async()=>{try{return await doLoadAuthoredModuleNamespace(e)}finally{inFlightModuleLoads.delete(t)}})();return inFlightModuleLoads.set(t,i),i}async function doLoadAuthoredModuleNamespace(t){return expectObjectRecord(AUTHORED_BUNDLED_MODULE_EXTENSION.test(t)?await loadBundledAuthoredModule(t):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 loadBundledAuthoredModule(e){let t=getChannelModuleCache(),i=resolveAuthoredPackageRoot(e),s=resolveAuthoredTsConfigPath(i),c=t&&t.size>0?{name:`eve-channel-identity`,async resolveId(e,n,i){if(!/channels[/\\]/.test(e)||i.kind!==`import-statement`)return;let a=await this.resolve(e,n,{kind:i.kind,skipSelf:!0});if(a===null||typeof a.id!=`string`)return;let o=resolve(a.id);if(t.has(o))return{id:`${CACHED_CHANNEL_PREFIX}${o}`}},load(e){if(!e.startsWith(CACHED_CHANNEL_PREFIX))return;let t=e.slice(19);return{code:[`const cache = globalThis["${CHANNEL_MODULE_CACHE_KEY}"];`,`export default cache.get(${JSON.stringify(t)});`].join(`
`),moduleType:`js`}}}:null,l=[createAuthoredAssetImportPlugin(),createAuthoredPackageTsConfigPathsPlugin({appPackageRoot:i,extensions:RESOLVE_EXTENSIONS}),createNodeEsmCompatBannerPlugin({includeRequire:!0}),createPackageBoundaryPlugin(i),c].filter(e=>e!==null),u;try{u=getSingleRolldownChunk(await buildWithNitroRolldown({cwd:i,input:e,platform:`node`,plugins:l,resolve:{extensions:[...RESOLVE_EXTENSIONS]},tsconfig:s,write:!1,output:{comments:!1,format:`esm`,sourcemap:`inline`}}),`authored module for "${e}"`)}catch(t){throw createAuthoredModuleBundleError(e,t)}let d=createHash(`sha1`).update(e).update(`\0`).update(u.code).digest(`hex`),f=join(i,AUTHORED_MODULE_BUNDLE_DIRECTORY_PATH),p=join(f,`${d}.mjs`);return existsSync(p)||(mkdirSync(f,{recursive:!0}),writeFileSync(p,u.code)),await import(`${createFileImportSpecifier(p)}?v=${d}`)}function createPackageBoundaryPlugin(e){return{name:`eve-package-boundary`,async resolveId(t,n,i){if(!isPackageImport(t))return;if(isEveFrameworkImport(t))return{external:!0,id:t};let a=n===void 0||n.startsWith(`\0`)||n.startsWith(CACHED_CHANNEL_PREFIX)?void 0:resolve(n);if(a!==void 0&&isPathInsideOrEqual(a,e)){let e=await this.resolve(t,n,{kind:i.kind,skipSelf:!0});if(e===null||typeof e.id!=`string`||isNodeModulesPath(e.id))return{external:!0,id:t}}}}}function isPackageImport(e){return e.startsWith(`.`)||e.startsWith(`/`)||/^[A-Za-z]:[\\/]/.test(e)||/^(?:node|data|file):/.test(e)||e.startsWith(`@/`)?!1:!e.startsWith(CACHED_CHANNEL_PREFIX)}function isEveFrameworkImport(e){return e===`eve`||e.startsWith(`eve/`)}function isNodeModulesPath(e){return e.replaceAll(`\\`,`/`).includes(`/node_modules/`)}function isPathInsideOrEqual(e,t){let n=resolve(e),a=resolve(t);return n===a||n.startsWith(`${a}${sep}`)}function resolveAuthoredTsConfigPath(e){for(let t of[`tsconfig.json`,`jsconfig.json`]){let r=join(e,t);if(existsSync(r))return r}return!1}function resolveAuthoredPackageRoot(e){let r=dirname(e);for(;;){if(existsSync(join(r,`package.json`)))return r;let i=dirname(r);if(i===r)throw Error(`Failed to resolve the authored package root for "${e}".`);r=i}}export{loadAuthoredModuleNamespace};