"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CheckSyntaxPlugin = void 0;
const path_1 = require("path");
const acorn_1 = require("acorn");
const utils_1 = require("@modern-js/utils");
const helpers_1 = require("./helpers");
const HTML_REGEX = /\.html$/;
const JS_REGEX = /\.js$/;
class CheckSyntaxPlugin {
    constructor(options) {
        this.errors = [];
        this.targets = options.targets;
        this.exclude = options.exclude;
        this.ecmaVersion = (0, helpers_1.getEcmaVersion)(this.targets);
    }
    apply(complier) {
        complier.hooks.afterEmit.tapPromise(CheckSyntaxPlugin.name, async (compilation) => {
            const outputPath = compilation.outputOptions.path || 'dist';
            // not support compilation.emittedAssets in Rspack
            const emittedAssets = compilation
                .getAssets()
                .filter(a => a.source)
                .map(a => a.name)
                .map(p => (0, path_1.resolve)(outputPath, p));
            const files = emittedAssets.filter(assets => HTML_REGEX.test(assets) || JS_REGEX.test(assets));
            await Promise.all(files.map(async (file) => {
                await this.check(file);
            }));
            (0, helpers_1.printErrors)(this.errors);
        });
    }
    async check(filepath) {
        if (HTML_REGEX.test(filepath)) {
            const htmlScripts = await (0, helpers_1.generateHtmlScripts)(filepath);
            await Promise.all(htmlScripts.map(async (script) => {
                if (!(0, helpers_1.checkIsExcludeSource)(filepath, this.exclude)) {
                    await this.tryParse(filepath, script);
                }
            }));
        }
        if (JS_REGEX.test(filepath)) {
            const jsScript = await utils_1.fs.readFile(filepath, 'utf-8');
            await this.tryParse(filepath, jsScript);
        }
    }
    async tryParse(filepath, code) {
        try {
            (0, acorn_1.parse)(code, { ecmaVersion: this.ecmaVersion });
        }
        catch (_) {
            const err = _;
            const error = await (0, helpers_1.generateError)({
                err,
                code,
                filepath,
                exclude: this.exclude,
            });
            if (error) {
                this.errors.push(error);
            }
        }
    }
}
exports.CheckSyntaxPlugin = CheckSyntaxPlugin;
