"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
const MODULE_TYPE = 'css/mini-extract';

class PublicPathCallbackPlugin {
  constructor({
    callback
  }) {
    this.publicPathCallback = callback;
  }

  getCssChunkObject(mainChunk) {
    const obj = {};

    for (const chunk of mainChunk.getAllAsyncChunks()) {
      for (const module of chunk.modulesIterable) {
        if (module.type === MODULE_TYPE) {
          obj[chunk.id] = 1;
          break;
        }
      }
    }

    return obj;
  }

  needChunkOnDemandLoadingCode(chunk) {
    for (const chunkGroup of chunk.groupsIterable) {
      if (chunkGroup.getNumberOfChildren() > 0) {
        return true;
      }
    }

    return false;
  }

  apply(compiler) {
    compiler.hooks.thisCompilation.tap('PublicPathCallbackPlugin', compilation => {
      compilation.mainTemplate.hooks.requireEnsure.tap('PublicPathCallbackPlugin', (source, chunk) => {
        const chunkMap = this.getCssChunkObject(chunk);

        if (Object.keys(chunkMap).length > 0) {
          return source.replace('__webpack_require__.p', `${this.publicPathCallback}("css")`);
        }
      });
    });
    compiler.hooks.compilation.tap('PublicPathCallbackPlugin', compilation => {
      compilation.mainTemplate.hooks.localVars.tap('PublicPathCallbackPlugin', (source, chunk) => {
        if (this.needChunkOnDemandLoadingCode(chunk)) {
          return source.replace('__webpack_require__.p', `${this.publicPathCallback}("js")`);
        }
      });
    });
  }

}

var _default = PublicPathCallbackPlugin;
exports.default = _default;