import { existsSync, readFileSync } from 'fs';

export default function customLoaderPlugin() {
  return {
    name: 'custom-loader-plugin',
    transform(source: string, id: string) {
      // 替换路径1
      const newPath = id.replace(/\/engines\/(.+?)\//, '/');
      if (existsSync(newPath)) {
        const result = readFileSync(newPath, 'utf-8');
        return {
          code: result,
        };
      }

      // 替换路径2
      const newPath2 = id.replace(/\/engines\//, '/');
      if (existsSync(newPath2)) {
        const result = readFileSync(newPath2, 'utf-8');
        return {
          code: result,
        };
      }

      // 如果没有匹配到，返回原始 source
      return source;
    },
  };
}
