import { getPackageRootPath, protocolExternalResolver, subpathExternalsResolver, tsConfigPaths, esbuild, esmShim, removeDeployer } from './chunk-KAY3R5QX.js';
import { isBareModuleSpecifier, isExternalProtocolImport, getPackageName, getNodeResolveOptions, slash } from './chunk-4SSB2KSK.js';
import { isAbsolute, join } from 'path';
import { pathToFileURL, fileURLToPath } from 'url';
import { optimizeLodashImports } from '@optimize-lodash/rollup-plugin';
import alias from '@rollup/plugin-alias';
import commonjs from '@rollup/plugin-commonjs';
import json from '@rollup/plugin-json';
import nodeResolve from '@rollup/plugin-node-resolve';
import { rollup } from 'rollup';
import { readFile } from 'fs/promises';

async function getPackageJSON(pkgName, importer) {
  const pkgRoot = await getPackageRootPath(pkgName, importer);
  if (!pkgRoot) {
    throw new Error(`Package ${pkgName} not found`);
  }
  const pkgJSON = JSON.parse(await readFile(join(pkgRoot, "package.json"), "utf-8"));
  return pkgJSON;
}
function nodeModulesExtensionResolver() {
  const nodeResolvePlugin = nodeResolve();
  return {
    name: "node-modules-extension-resolver",
    async resolveId(id, importer, options) {
      if (!importer || !isBareModuleSpecifier(id) || isExternalProtocolImport(id) || isAbsolute(id)) {
        return null;
      }
      const parts = id.split("/");
      const isScoped = id.startsWith("@");
      if (isScoped && parts.length === 2 || !isScoped && parts.length === 1) {
        return null;
      }
      const pkgName = getPackageName(id);
      if (!pkgName) {
        return null;
      }
      try {
        const packageJSON = await getPackageJSON(pkgName, importer);
        if (!!packageJSON.exports) {
          return null;
        }
        const packageRoot = await getPackageRootPath(pkgName, importer);
        const nodeResolved = await nodeResolvePlugin.resolveId?.handler?.call(this, id, importer, options);
        if (!nodeResolved?.id) {
          return null;
        }
        let filePath = nodeResolved.id;
        if (nodeResolved.resolvedBy === "commonjs--resolver") {
          filePath = filePath.substring(1).split("?")[0];
        }
        const resolvedImportPath = filePath.replace(packageRoot, pkgName);
        return {
          id: resolvedImportPath,
          external: true
        };
      } catch (err) {
        console.error(err);
        return null;
      }
    }
  };
}

// src/build/bundler.ts
async function getInputOptions(entryFile, analyzedBundleInfo, platform, env = { "process.env.NODE_ENV": JSON.stringify("production") }, {
  sourcemap = false,
  isDev = false,
  projectRoot,
  workspaceRoot = void 0,
  enableEsmShim = true,
  externalsPreset = false
}) {
  const nodeResolvePlugin = nodeResolve(getNodeResolveOptions(platform));
  const externalsCopy = new Set(analyzedBundleInfo.externalDependencies.keys());
  const externals = externalsPreset ? [] : Array.from(externalsCopy);
  const normalizedEntryFile = slash(entryFile);
  return {
    logLevel: process.env.MASTRA_BUNDLER_DEBUG === "true" ? "debug" : "silent",
    treeshake: "smallest",
    preserveSymlinks: true,
    external: externals,
    plugins: [
      protocolExternalResolver(),
      subpathExternalsResolver(externals),
      {
        name: "alias-optimized-deps",
        resolveId(id) {
          if (!analyzedBundleInfo.dependencies.has(id)) {
            return null;
          }
          const filename = analyzedBundleInfo.dependencies.get(id);
          const absolutePath = join(workspaceRoot || projectRoot, filename);
          if (isDev) {
            return {
              id: process.platform === "win32" ? pathToFileURL(absolutePath).href : absolutePath,
              external: true
            };
          }
          return {
            id: absolutePath,
            external: false
          };
        }
      },
      alias({
        entries: [
          {
            find: /^\#server$/,
            replacement: slash(fileURLToPath(import.meta.resolve("@mastra/deployer/server")))
          },
          {
            find: /^\@mastra\/server\/(.*)/,
            replacement: `@mastra/server/$1`,
            customResolver: (id) => {
              if (id.startsWith("@mastra/server")) {
                return {
                  id: fileURLToPath(import.meta.resolve(id))
                };
              }
            }
          },
          { find: /^\#mastra$/, replacement: normalizedEntryFile }
        ]
      }),
      tsConfigPaths(),
      {
        name: "tools-rewriter",
        resolveId(id) {
          if (id === "#tools") {
            return {
              id: "./tools.mjs",
              external: true
            };
          }
        }
      },
      esbuild({
        platform,
        define: env
      }),
      optimizeLodashImports({
        include: "**/*.{js,ts,mjs,cjs}"
      }),
      externalsPreset ? null : commonjs({
        extensions: [".js", ".ts"],
        transformMixedEsModules: true,
        esmExternals(id) {
          return externals.includes(id);
        }
      }),
      enableEsmShim ? esmShim() : void 0,
      externalsPreset ? nodeModulesExtensionResolver() : nodeResolvePlugin,
      // for debugging
      // {
      //   name: 'logger',
      //   //@ts-expect-error
      //   resolveId(id, ...args) {
      //     console.log({ id, args });
      //   },
      //   // @ts-expect-error
      // transform(code, id) {
      //   if (code.includes('class Duplexify ')) {
      //     console.log({ duplex: id });
      //   }
      // },
      // },
      json(),
      removeDeployer(entryFile, { sourcemap }),
      // treeshake unused imports
      esbuild({
        include: entryFile,
        platform
      })
    ].filter(Boolean)
  };
}
async function createBundler(inputOptions, outputOptions) {
  const bundler = await rollup(inputOptions);
  return {
    write: () => {
      return bundler.write({
        ...outputOptions,
        format: "esm",
        entryFileNames: "[name].mjs",
        chunkFileNames: "[name].mjs"
      });
    },
    close: () => {
      return bundler.close();
    }
  };
}

export { createBundler, getInputOptions, nodeModulesExtensionResolver };
//# sourceMappingURL=chunk-YHEVEEDG.js.map
//# sourceMappingURL=chunk-YHEVEEDG.js.map