import CJS_COMPAT_NODE_URL_fkaa0x0zihe from 'node:url';
import CJS_COMPAT_NODE_PATH_fkaa0x0zihe from 'node:path';
import CJS_COMPAT_NODE_MODULE_fkaa0x0zihe from "node:module";

var __filename = CJS_COMPAT_NODE_URL_fkaa0x0zihe.fileURLToPath(import.meta.url);
var __dirname = CJS_COMPAT_NODE_PATH_fkaa0x0zihe.dirname(__filename);
var require = CJS_COMPAT_NODE_MODULE_fkaa0x0zihe.createRequire(import.meta.url);

// ------------------------------------------------------------
// end of CJS compatibility banner, injected by Storybook's esbuild configuration
// ------------------------------------------------------------
import {
  babelParser,
  extractMockCalls,
  getIsExternal,
  resolveExternalModule,
  resolveWithExtensions
} from "./chunk-S3OHEWCH.js";
import "./chunk-QUBI53SI.js";
import "./chunk-4ILNNMLG.js";

// src/core-server/presets/webpack/plugins/webpack-mock-plugin.ts
import { createRequire } from "node:module";
import { dirname, isAbsolute } from "node:path";
import { fileURLToPath } from "node:url";
var require2 = createRequire(import.meta.url), PLUGIN_NAME = "storybook-mock-plugin", WebpackMockPlugin = class {
  constructor(options) {
    this.mockMap = /* @__PURE__ */ new Map();
    if (!options.previewConfigPath)
      throw new Error(`[${PLUGIN_NAME}] \`previewConfigPath\` is required.`);
    this.options = options;
  }
  /**
   * The main entry point for the Webpack plugin.
   *
   * @param {Compiler} compiler The Webpack compiler instance.
   */
  apply(compiler) {
    let logger = compiler.getInfrastructureLogger(PLUGIN_NAME), updateMocks = () => {
      this.mockMap = new Map(
        this.extractAndResolveMocks(compiler).flatMap((mock) => [
          // first one, full path
          [mock.absolutePath, mock],
          // second one, without the extension
          [mock.absolutePath.replace(/\.[^.]+$/, ""), mock]
        ])
      ), logger.info(`Mock map updated with ${this.mockMap.size / 2} mocks.`);
    };
    compiler.hooks.beforeRun.tap(PLUGIN_NAME, updateMocks), compiler.hooks.watchRun.tap(PLUGIN_NAME, updateMocks), new compiler.webpack.NormalModuleReplacementPlugin(/.*/, (resource) => {
      try {
        let path = resource.request, importer = resource.context, absolutePath = getIsExternal(path, importer) ? resolveExternalModule(path, importer) : resolveWithExtensions(path, importer);
        this.mockMap.has(absolutePath) && (resource.request = this.mockMap.get(absolutePath).replacementResource);
      } catch {
        logger.debug(`Could not resolve mock for "${resource.request}".`);
      }
    }).apply(compiler), compiler.hooks.afterCompile.tap(PLUGIN_NAME, (compilation) => {
      compilation.fileDependencies.add(this.options.previewConfigPath);
      for (let mock of this.mockMap.values())
        isAbsolute(mock.replacementResource) && mock.replacementResource.includes("__mocks__") && compilation.contextDependencies.add(dirname(mock.replacementResource));
    });
  }
  /**
   * Reads the preview config, parses it to find all `sb.mock()` calls, and resolves their
   * corresponding mock implementations.
   *
   * @param {Compiler} compiler The Webpack compiler instance.
   * @returns {ResolvedMock[]} An array of fully processed mocks.
   */
  extractAndResolveMocks(compiler) {
    let { previewConfigPath } = this.options, logger = compiler.getInfrastructureLogger(PLUGIN_NAME), mocks = extractMockCalls(
      { previewConfigPath, configDir: dirname(previewConfigPath) },
      babelParser,
      compiler.context
    ), resolvedMocks = [];
    for (let mock of mocks)
      try {
        let { absolutePath, redirectPath } = mock, replacementResource;
        redirectPath ? replacementResource = redirectPath : replacementResource = `${fileURLToPath(
          import.meta.resolve("storybook/webpack/loaders/webpack-automock-loader")
        )}?spy=${mock.spy}!${absolutePath}`, resolvedMocks.push({
          ...mock,
          replacementResource
        });
      } catch {
        logger.warn(`Could not resolve mock for "${mock.path}". It will be ignored.`);
      }
    return resolvedMocks;
  }
};
export {
  WebpackMockPlugin
};
