import {
  aiSDKConfigs,
  anthropicConfigs,
  claudeAgentSDKConfigs,
  googleGenAIConfigs,
  openRouterConfigs,
  openaiConfigs
} from "./chunk-F7WAXFNM.mjs";

// src/auto-instrumentations/bundler/plugin.ts
import { createUnplugin } from "unplugin";
import {
  create
} from "@apm-js-collab/code-transformer";
import { extname, join, sep } from "path";
import { readFileSync } from "fs";
import { fileURLToPath } from "url";
import moduleDetailsFromPath from "module-details-from-path";
function getModuleVersion(basedir) {
  try {
    const packageJsonPath = join(basedir, "package.json");
    const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf8"));
    if (packageJson.version) {
      return packageJson.version;
    }
  } catch (error) {
  }
  return void 0;
}
var unplugin = createUnplugin((options = {}) => {
  const allInstrumentations = [
    ...openaiConfigs,
    ...anthropicConfigs,
    ...aiSDKConfigs,
    ...claudeAgentSDKConfigs,
    ...googleGenAIConfigs,
    ...openRouterConfigs,
    ...options.instrumentations || []
  ];
  const dcModule = options.browser === false ? void 0 : "dc-browser";
  const instrumentationMatcher = create(allInstrumentations, dcModule);
  return {
    name: "code-transformer",
    enforce: "pre",
    transform(code, id) {
      const filePath = id.startsWith("file:") ? fileURLToPath(id) : id;
      const ext = extname(filePath);
      let isModule = ext === ".mjs" || ext === ".ts" || ext === ".tsx";
      if (ext === ".js") {
        isModule = code.includes("export ") || code.includes("import ");
      }
      const normalizedForPlatform = filePath.split("/").join(sep);
      const moduleDetails = moduleDetailsFromPath(normalizedForPlatform);
      if (!moduleDetails) {
        return null;
      }
      const moduleName = moduleDetails.name;
      const moduleVersion = getModuleVersion(moduleDetails.basedir);
      if (!moduleVersion) {
        console.warn(
          `No 'package.json' version found for module ${moduleName} at ${moduleDetails.basedir}. Skipping transformation.`
        );
        return null;
      }
      const normalizedModulePath = moduleDetails.path.replace(/\\/g, "/");
      const transformer = instrumentationMatcher.getTransformer(
        moduleName,
        moduleVersion,
        normalizedModulePath
      );
      if (!transformer) {
        return null;
      }
      try {
        const moduleType = isModule ? "esm" : "cjs";
        const result = transformer.transform(code, moduleType);
        return {
          code: result.code,
          map: result.map
        };
      } catch (error) {
        console.warn(`Code transformation failed for ${id}: ${error}`);
        return null;
      }
    }
  };
});

export {
  unplugin
};
