"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var webpack_1 = __importDefault(require("webpack"));
var webpack_dev_server_1 = __importDefault(require("webpack-dev-server"));
var logger_1 = __importDefault(require("../util/logger"));
var portfinder_1 = require("portfinder");
var address_1 = __importDefault(require("address"));
function devServer(config) {
    var compiler = webpack_1.default(config);
    var devServerOptions = {
        open: true,
        host: '0.0.0.0',
        port: 8080,
        stats: 'errors-only',
        publicPath: '/',
        disableHostCheck: true,
        hot: true,
        hotOnly: true,
        inline: true,
        quiet: true,
        index: 'default.html',
        overlay: {
            warnings: true,
            errors: true
        }
    };
    portfinder_1.getPort({
        port: devServerOptions.port,
    }, function (err, port) {
        if (err) {
            console.log(err);
            return;
        }
        devServerOptions.port = port;
        logger_1.default.watch("local:  ", "http://localhost:" + port + "/");
        logger_1.default.watch("network:  ", "http://" + address_1.default.ip() + ":" + port + "/");
        var server = new webpack_dev_server_1.default(compiler, devServerOptions);
        server.listen(port, devServerOptions.host, function (err) {
            if (err)
                logger_1.default.error(err);
        });
    });
}
function build(config) {
    return new Promise(function (resolve, reject) {
        webpack_1.default(config, function (err, stats) {
            if (err || stats.hasErrors()) {
                // 在这里处理错误
                if (err) {
                    logger_1.default.error(err.stack || err);
                    if (err.details) {
                        logger_1.default.error(err.details);
                    }
                    return;
                }
                var info = stats.toJson();
                if (stats.hasErrors()) {
                    logger_1.default.error(info.errors);
                }
                if (stats.hasWarnings()) {
                    logger_1.default.warn(info.warnings);
                }
                reject(err || stats.toJson());
            }
            else {
                // 处理完成
                resolve();
            }
        });
    });
}
function compileWebPack(config) {
    switch (config.mode) {
        case 'development':
            devServer(config);
            break;
        case 'production':
            return build(config);
    }
}
exports.compileWebPack = compileWebPack;
//# sourceMappingURL=webpack.js.map