import {
  getPackageName,
  getPackageVersion
} from "../chunk-VLEJ5AEK.mjs";

// src/auto-instrumentations/loader/cjs-patch.ts
import {
  create
} from "@apm-js-collab/code-transformer";
import * as Module from "module";
import { sep } from "path";
import moduleDetailsFromPath from "module-details-from-path";
var ModulePatch = class {
  packages;
  instrumentator;
  originalCompile;
  constructor({
    instrumentations = []
  } = {}) {
    this.packages = new Set(instrumentations.map((i) => i.module.name));
    this.instrumentator = create(instrumentations);
    this.originalCompile = Module.prototype._compile;
  }
  /**
   * Patches the Node.js module class method that is responsible for compiling code.
   * If a module is found that has an instrumentator, it will transform the code before compiling it
   * with tracing channel methods.
   */
  patch() {
    const self = this;
    Module.prototype._compile = function wrappedCompile(...args) {
      const [content, filename] = args;
      const normalizedForPlatform = filename.split("/").join(sep);
      const resolvedModule = moduleDetailsFromPath(normalizedForPlatform);
      if (resolvedModule) {
        const packageName = getPackageName(resolvedModule.basedir) ?? resolvedModule.name;
        if (!self.packages.has(packageName)) {
          return self.originalCompile.apply(this, args);
        }
        const version = getPackageVersion(resolvedModule.basedir);
        const normalizedModulePath = resolvedModule.path.replace(/\\/g, "/");
        const transformer = self.instrumentator.getTransformer(
          packageName,
          version,
          normalizedModulePath
        );
        if (transformer) {
          try {
            const transformedCode = transformer.transform(content, "unknown");
            args[0] = transformedCode?.code;
          } catch (error) {
            console.warn(`Error transforming module ${filename}:`, error);
          } finally {
            transformer.free();
          }
        }
      }
      return self.originalCompile.apply(this, args);
    };
  }
  /**
   * Restores the original Module.prototype._compile method
   * **Note**: This is intended to be used in testing only.
   */
  unpatch() {
    Module.prototype._compile = this.originalCompile;
  }
};
export {
  ModulePatch
};
