"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.clearFiles = clearFiles;
exports.getFiles = getFiles;
exports.register = register;
exports.restore = restore;
var _path = require("path");
var _pirates = require("../compiled/pirates");
const COMPILE_EXTS = ['.ts', '.tsx', '.js', '.jsx'];
const HOOK_EXTS = [...COMPILE_EXTS, '.mjs'];
let registered = false;
let files = [];
let revert = () => {};
function transform(opts) {
  const {
    code,
    filename,
    implementor
  } = opts;
  files.push(filename);
  const ext = (0, _path.extname)(filename);
  try {
    return implementor.transformSync(code, {
      sourcefile: filename,
      loader: ext.slice(1),
      // consistent with `tsconfig.base.json`
      // https://github.com/YeWills/psky-next/pull/729
      target: 'es2019',
      format: 'cjs',
      logLevel: 'error'
    }).code;
  } catch (e) {
    // @ts-ignore
    throw new Error(`Parse file failed: [${filename}]`, {
      cause: e
    });
  }
}
function register(opts) {
  files = [];
  if (!registered) {
    revert = (0, _pirates.addHook)((code, filename) => transform({
      code,
      filename,
      implementor: opts.implementor
    }), {
      ext: opts.exts || HOOK_EXTS,
      ignoreNodeModules: true
    });
    registered = true;
  }
}
function getFiles() {
  return files;
}
function clearFiles() {
  files = [];
}
function restore() {
  revert();
  registered = false;
}