"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _path = _interopRequireDefault(require("path"));

var _webpackSources = require("webpack-sources");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

let filenameParser = filename => {
  let filepaths = filename.split('/');
  let hashedName = filepaths[filepaths.length - 1];

  let {
    name,
    ext
  } = _path.default.parse(hashedName);

  let nameparts = name.split('.');

  if (ext === '.css' && /^(rtl|ltr)$/.test(nameparts[nameparts.length - 1])) {
    return {
      name: nameparts.slice(0, nameparts.length - 2).join('.') + ext,
      hashedName
    };
  }

  return {
    name: nameparts.slice(0, nameparts.length - 1).join('.') + ext,
    hashedName
  };
};

class ManifestPlugin {
  constructor(options) {
    this.options = options;
  }

  apply(compiler) {
    compiler.hooks.emit.tap('PublicPathChangePlugin', compilation => {
      let stats = compilation.getStats().toJson();
      let manifest = compilation.chunks.reduce((files, chunk) => chunk.files.reduce((files, name) => {
        let {
          name: filename,
          hashedName
        } = filenameParser(name);

        if (chunk.canBeInitial()) {
          if (!files.entryFiles) {
            files.entryFiles = {};
          }

          files.entryFiles[filename] = hashedName;
        }

        files[filename] = hashedName;
        return files;
      }, files), {});
      manifest = stats.assets.reduce((files, asset) => {
        let isEntryAsset = asset.chunks.length > 0;

        if (isEntryAsset) {
          return files;
        }

        let {
          name: filename
        } = asset;
        let {
          name,
          hashedName
        } = filenameParser(filename);
        files[name] = hashedName;
        return files;
      }, manifest);
      compilation.assets[this.options.fileName] = new _webpackSources.RawSource(JSON.stringify(manifest));
    });
  }

}

exports.default = ManifestPlugin;