"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.errorMiddleware = exports.prepareError = void 0;
const chalk_1 = __importDefault(require("chalk"));
const utils_1 = require("../../utils");
const strip_ansi_1 = __importDefault(require("strip-ansi"));
function prepareError(err) {
    // only copy the information we need and avoid serializing unnecessary
    // properties, since some errors may attach full objects (e.g. PostCSS)
    return {
        message: strip_ansi_1.default(err.message),
        stack: strip_ansi_1.default(err.stack || ''),
        id: err.id,
        frame: strip_ansi_1.default(err.frame || ''),
        plugin: err.plugin,
        pluginCode: err.pluginCode,
        loc: err.loc
    };
}
exports.prepareError = prepareError;
function errorMiddleware(server) {
    // note the 4 args must be kept for connect to treat this as error middleware
    return (err, _req, res, _next) => {
        const args = [chalk_1.default.red(`Internal server error:`)];
        if (err.plugin)
            args.push(`  Plugin: ${chalk_1.default.magenta(err.plugin)}`);
        if (err.id)
            args.push(`  File: ${chalk_1.default.cyan(err.id)}`);
        if (err.frame)
            args.push(chalk_1.default.yellow(utils_1.pad(err.frame)));
        if (err.stack)
            args.push(utils_1.pad(err.stack));
        server.config.logger.error(args.join('\n'), {
            clear: true,
            timestamp: true
        });
        res.statusCode = 500;
        res.end(() => {
            server.ws.send({
                type: 'error',
                err: prepareError(err)
            });
        });
    };
}
exports.errorMiddleware = errorMiddleware;
//# sourceMappingURL=error.js.map