"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.MDXCompiler = void 0;
function _path() {
  const data = require("path");
  _path = function () {
    return data;
  };
  return data;
}
function _fsExtra() {
  const data = require("fs-extra");
  _fsExtra = function () {
    return data;
  };
  return data;
}
function _mdxCompilers() {
  const data = require("@teambit/mdx.compilers.mdx-transpiler");
  _mdxCompilers = function () {
    return data;
  };
  return data;
}
function _minimatch() {
  const data = _interopRequireDefault(require("minimatch"));
  _minimatch = function () {
    return data;
  };
  return data;
}
function _compilationModules() {
  const data = require("@teambit/compilation.modules.babel-compiler");
  _compilationModules = function () {
    return data;
  };
  return data;
}
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
class MDXCompiler {
  constructor(id, config) {
    this.id = id;
    this.config = config;
    _defineProperty(this, "displayName", 'MDX');
    _defineProperty(this, "shouldCopyNonSupportedFiles", true);
    _defineProperty(this, "distDir", 'dist');
  }
  displayConfig() {
    return JSON.stringify(this.config, null, 2);
  }
  getDistDir() {
    return this.distDir;
  }
  transpileFile(fileContent, options) {
    const afterMdxCompile = (0, _mdxCompilers().compileSync)(fileContent, {
      filepath: options.filePath,
      // this compiler is not indented to compile according to the bit flavour.
      bitFlavour: false
    });
    const filePathAfterMdxCompile = this.replaceFileExtToJs(options.filePath);
    const afterBabelCompile = (0, _compilationModules().transpileFileContent)(afterMdxCompile.contents, {
      rootDir: options.componentDir,
      filePath: filePathAfterMdxCompile
    }, this.config.babelTransformOptions || {});
    return afterBabelCompile;
  }

  /**
   * compile components inside isolated capsules. this being used during tag for the release.
   * meaning, the final package of the component has the dists generated by this method.
   */
  async build(context) {
    const capsules = context.capsuleNetwork.seedersCapsules;
    const componentsResults = capsules.map(capsule => {
      const srcFiles = capsule.component.filesystem.files.filter(file => {
        return this.isFileSupported(file.relative);
      });
      const errors = srcFiles.map(srcFile => {
        try {
          const transpiled = this.transpileFile(srcFile.contents.toString('utf-8'), {
            filePath: this.replaceFileExtToJs(srcFile.relative),
            componentDir: capsule.path
          });
          if (!transpiled) {
            return undefined;
          }
          (0, _fsExtra().outputFileSync)((0, _path().join)(capsule.path, this.getDistPathBySrcPath(transpiled[0].outputPath)), transpiled[0].outputText);
          if (transpiled.length > 1) {
            (0, _fsExtra().outputFileSync)((0, _path().join)(capsule.path, this.distDir, transpiled[1].outputPath), transpiled[1].outputText);
          }
          return undefined;
        } catch (err) {
          return err;
        }
      });
      return {
        errors: errors.filter(err => !!err),
        component: capsule.component
      };
    });
    return {
      componentsResults,
      artifacts: [{
        name: 'dist',
        globPatterns: [`${this.distDir}/**`]
      }]
    };
  }

  /**
   * given a source file, return its parallel in the dists. e.g. "index.ts" => "dist/index.js"
   * both, the return path and the given path are relative paths.
   */
  getDistPathBySrcPath(srcPath) {
    const fileWithNewExt = this.replaceFileExtToJs(srcPath);
    return (0, _path().join)(this.distDir, fileWithNewExt);
  }
  replaceFileExtToJs(srcPath) {
    let fileWithNewExt = srcPath;
    if (this.isFileSupported(srcPath)) {
      fileWithNewExt = srcPath.replace('.mdx', '.mdx.js');
    }
    return fileWithNewExt;
  }

  /**
   * only supported files matching get compiled. others, are copied to the dist dir.
   */
  isFileSupported(filePath) {
    const ignoredExtensions = this.config.ignoredExtensions ?? [];
    const ignoredExt = ignoredExtensions.find(ext => filePath.endsWith(ext));
    const ignoredPatterns = this.config.ignoredPatterns ?? [];
    const ignoredPattern = ignoredPatterns.find(pattern => (0, _minimatch().default)(filePath, pattern));
    return !ignoredExt && !ignoredPattern && (filePath.endsWith('.mdx') || filePath.endsWith('.md'));
  }

  /**
   * returns the version of the current compiler instance (e.g. '4.0.1').
   */
  version() {
    return '';
  }
}
exports.MDXCompiler = MDXCompiler;

//# sourceMappingURL=mdx.compiler.js.map