"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.HtmlAppIconPlugin = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
// @ts-expect-error
const webpack_sources_1 = require("webpack-sources");
const util_1 = require("./util");
class HtmlAppIconPlugin {
    constructor(options) {
        this.name = 'HtmlAppIconPlugin';
        this.distDir = options.distDir;
        this.iconPath = options.iconPath;
        this.HtmlPlugin = options.HtmlPlugin;
    }
    apply(compiler) {
        if (!fs_1.default.existsSync(this.iconPath)) {
            throw new Error(`[${this.name}] Can not find the app icon, please check if the '${this.iconPath}' file exists'.`);
        }
        const iconRelativePath = path_1.default.join(this.distDir, path_1.default.basename(this.iconPath));
        // add html asset tags
        compiler.hooks.compilation.tap(this.name, (compilation) => {
            this.HtmlPlugin.getHooks(compilation).alterAssetTagGroups.tap(this.name, data => {
                const { publicPath } = compiler.options.output;
                data.headTags.unshift({
                    tagName: 'link',
                    voidTag: true,
                    attributes: {
                        rel: 'apple-touch-icon',
                        sizes: '180*180',
                        href: `${publicPath}${iconRelativePath}`,
                    },
                    meta: {},
                });
                return data;
            });
        });
        // copy icon to dist
        compiler.hooks.thisCompilation.tap(this.name, (compilation) => {
            compilation.hooks.processAssets.tap({
                name: this.name,
                stage: util_1.COMPILATION_PROCESS_STAGE.PROCESS_ASSETS_STAGE_PRE_PROCESS,
            }, assets => {
                const source = fs_1.default.readFileSync(this.iconPath);
                assets[iconRelativePath] = new webpack_sources_1.RawSource(source, false);
            });
        });
    }
}
exports.HtmlAppIconPlugin = HtmlAppIconPlugin;
