'use strict';

var chunkYW7AIVNG_cjs = require('./chunk-YW7AIVNG.cjs');
var chunk3T7FP546_cjs = require('./chunk-3T7FP546.cjs');
var path = require('path');
var url = require('url');
var rollupPlugin = require('@optimize-lodash/rollup-plugin');
var alias = require('@rollup/plugin-alias');
var commonjs = require('@rollup/plugin-commonjs');
var json = require('@rollup/plugin-json');
var nodeResolve = require('@rollup/plugin-node-resolve');
var rollup = require('rollup');
var promises = require('fs/promises');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var alias__default = /*#__PURE__*/_interopDefault(alias);
var commonjs__default = /*#__PURE__*/_interopDefault(commonjs);
var json__default = /*#__PURE__*/_interopDefault(json);
var nodeResolve__default = /*#__PURE__*/_interopDefault(nodeResolve);

async function getPackageJSON(pkgName, importer) {
  const pkgRoot = await chunkYW7AIVNG_cjs.getPackageRootPath(pkgName, importer);
  if (!pkgRoot) {
    throw new Error(`Package ${pkgName} not found`);
  }
  const pkgJSON = JSON.parse(await promises.readFile(path.join(pkgRoot, "package.json"), "utf-8"));
  return pkgJSON;
}
function nodeModulesExtensionResolver() {
  const nodeResolvePlugin = nodeResolve__default.default();
  return {
    name: "node-modules-extension-resolver",
    async resolveId(id, importer, options) {
      if (!importer || !chunk3T7FP546_cjs.isBareModuleSpecifier(id) || chunk3T7FP546_cjs.isExternalProtocolImport(id) || path.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 = chunk3T7FP546_cjs.getPackageName(id);
      if (!pkgName) {
        return null;
      }
      try {
        const packageJSON = await getPackageJSON(pkgName, importer);
        if (!!packageJSON.exports) {
          return null;
        }
        const packageRoot = await chunkYW7AIVNG_cjs.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__default.default(chunk3T7FP546_cjs.getNodeResolveOptions(platform));
  const externalsCopy = new Set(analyzedBundleInfo.externalDependencies.keys());
  const externals = externalsPreset ? [] : Array.from(externalsCopy);
  const normalizedEntryFile = chunk3T7FP546_cjs.slash(entryFile);
  return {
    logLevel: process.env.MASTRA_BUNDLER_DEBUG === "true" ? "debug" : "silent",
    treeshake: "smallest",
    preserveSymlinks: true,
    external: externals,
    plugins: [
      chunkYW7AIVNG_cjs.protocolExternalResolver(),
      chunkYW7AIVNG_cjs.subpathExternalsResolver(externals),
      {
        name: "alias-optimized-deps",
        resolveId(id) {
          if (!analyzedBundleInfo.dependencies.has(id)) {
            return null;
          }
          const filename = analyzedBundleInfo.dependencies.get(id);
          const absolutePath = path.join(workspaceRoot || projectRoot, filename);
          if (isDev) {
            return {
              id: process.platform === "win32" ? url.pathToFileURL(absolutePath).href : absolutePath,
              external: true
            };
          }
          return {
            id: absolutePath,
            external: false
          };
        }
      },
      alias__default.default({
        entries: [
          {
            find: /^\#server$/,
            replacement: chunk3T7FP546_cjs.slash(url.fileURLToPath(undefined("@mastra/deployer/server")))
          },
          {
            find: /^\@mastra\/server\/(.*)/,
            replacement: `@mastra/server/$1`,
            customResolver: (id) => {
              if (id.startsWith("@mastra/server")) {
                return {
                  id: url.fileURLToPath(undefined(id))
                };
              }
            }
          },
          { find: /^\#mastra$/, replacement: normalizedEntryFile }
        ]
      }),
      chunkYW7AIVNG_cjs.tsConfigPaths(),
      {
        name: "tools-rewriter",
        resolveId(id) {
          if (id === "#tools") {
            return {
              id: "./tools.mjs",
              external: true
            };
          }
        }
      },
      chunkYW7AIVNG_cjs.esbuild({
        platform,
        define: env
      }),
      rollupPlugin.optimizeLodashImports({
        include: "**/*.{js,ts,mjs,cjs}"
      }),
      externalsPreset ? null : commonjs__default.default({
        extensions: [".js", ".ts"],
        transformMixedEsModules: true,
        esmExternals(id) {
          return externals.includes(id);
        }
      }),
      enableEsmShim ? chunkYW7AIVNG_cjs.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__default.default(),
      chunkYW7AIVNG_cjs.removeDeployer(entryFile, { sourcemap }),
      // treeshake unused imports
      chunkYW7AIVNG_cjs.esbuild({
        include: entryFile,
        platform
      })
    ].filter(Boolean)
  };
}
async function createBundler(inputOptions, outputOptions) {
  const bundler = await rollup.rollup(inputOptions);
  return {
    write: () => {
      return bundler.write({
        ...outputOptions,
        format: "esm",
        entryFileNames: "[name].mjs",
        chunkFileNames: "[name].mjs"
      });
    },
    close: () => {
      return bundler.close();
    }
  };
}

exports.createBundler = createBundler;
exports.getInputOptions = getInputOptions;
exports.nodeModulesExtensionResolver = nodeModulesExtensionResolver;
//# sourceMappingURL=chunk-AQL6MQFJ.cjs.map
//# sourceMappingURL=chunk-AQL6MQFJ.cjs.map