"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
/* eslint-disable */
const child_process_1 = __importDefault(require("child_process"));
const ejs_1 = __importDefault(require("ejs"));
const fs_extra_1 = __importDefault(require("fs-extra"));
const glob_1 = __importDefault(require("glob"));
const lodash_template_1 = __importDefault(require("lodash.template"));
const path_1 = __importDefault(require("path"));
const emitComponentEvent_1 = require("./emitComponentEvent");
const require_1 = require("./require");
const utils_1 = __importDefault(require("./utils"));
const symlinkDir = require('symlink-dir');
class ReactBuild {
    constructor(opts) {
        this.generateActionImport = (action) => {
            if (emitComponentEvent_1.isEmitComponentEventActionId(action.id)) {
                const action_key = '__impage__inject_materials_emitComponentEventAction';
                if (this.importMap.has(action_key)) {
                    return;
                }
                this.templateData.actionImports.push(`import { emitComponentEvent as emitComponentEventAction } from '../handlers/emitComponentEvent'`);
                return this.importMap.set(action_key, true);
            }
            const { id } = action;
            const action_key = `${this.opts.paths.libName}-${id}`;
            if (this.importMap.has(action_key)) {
                return;
            }
            const actionName = this.getName('action', id);
            this.templateData.actionImports.push(`import ${actionName} from '../libraries/${this.opts.paths.libName}/actions/${actionName}'`);
            this.importMap.set(action_key, true);
        };
        this.generateActionInstanceItem = ({ id, key, data, trigger, maxTimeout, target }) => {
            const actionName = this.getName('action', id);
            if (!this.templateData.actions[id]) {
                if (emitComponentEvent_1.isEmitComponentEventActionId(id)) {
                    this.templateData.actions[id] = emitComponentEvent_1.emitComponentEventAction;
                }
                else {
                    const iAction = {
                        id,
                        projId: this.opts.paths.libName,
                        projKey: this.opts.paths.libName,
                        name: actionName,
                        info: {
                            name: actionName,
                            author: 'action author',
                        },
                    };
                    if (maxTimeout) {
                        iAction.maxTimeout = maxTimeout;
                    }
                    this.templateData.actions[id] = iAction;
                }
            }
            return {
                key,
                action: id,
                data,
                trigger,
                target,
            };
        };
        this.cwd = process.cwd();
        this.opts = opts;
        this.materialsPath = path_1.default.resolve(process.cwd(), 'dist');
        this.workspacePath = path_1.default.join(opts.paths.tempPath, 'workspace');
        this.workspaceCompilePath = path_1.default.resolve(this.workspacePath, 'compile', opts.activity.act_key);
        this.containerPath = path_1.default.resolve(process.cwd(), 'src/containers', this.opts.container);
        this.webpackConfigPath = path_1.default.resolve(this.workspaceCompilePath, 'webpack/webpack.dev.js');
        this.webpackSsrConfigPath = path_1.default.resolve(this.workspaceCompilePath, 'webpack/webpack.ssr.js');
        this.indexEjsPath = path_1.default.resolve(this.workspaceCompilePath, 'preview/index.ejs');
        this.indexHtmlPath = path_1.default.resolve(this.workspaceCompilePath, 'preview/index.html');
        this.previewPath = path_1.default.resolve(this.workspaceCompilePath, 'preview');
        this.publicPath = path_1.default.resolve(this.materialsPath, 'preview', `${opts.activity.act_key}`);
    }
    build(ssr = true) {
        return __awaiter(this, void 0, void 0, function* () {
            // const { mainProject, activity } = this.opts;
            yield this.cleanPath();
            console.log('Clean path success');
            yield this.copyContainer();
            console.log('Copy container success');
            yield this.copyWebpackConfig();
            console.log('Copy webpack config success');
            yield this.createNodeModulesSoftLink();
            console.log('Create node_modules soft-link success');
            yield this.copyComponents();
            console.log('Copy components success');
            yield this.copyActions();
            console.log('Copy actions success');
            yield this.copyPlugins();
            console.log('Copy plugins success');
            yield this.copyLibs();
            console.log('Copy libs success');
            yield this.copyAssets();
            console.log('Copy assets success');
            yield this.copyHandler();
            console.log('Copy handler success');
            const libMap = yield this.generateJsx();
            console.log('Generate JSX success');
            const resolveModulesPath = (v) => {
                return path_1.default.resolve(__dirname, `../../../../workspace/libraries/materials-${v}/node_modules`);
            };
            this.resolveModules = Array.from(libMap).map(resolveModulesPath);
            const [params, ssrParams] = yield this.generateBuildParamsFile();
            console.log('Generate BuildParams success: ', params, ssrParams);
            yield Promise.all([
                this.compile(this.webpackConfigPath, params),
                ssr ? this.compile(this.webpackSsrConfigPath, ssrParams) : null,
            ]);
            console.log('Webpack compile success');
            const cjsOptions = { ssrHtml: '' };
            if (ssr) {
                try {
                    cjsOptions.ssrHtml = yield this.ssrRender();
                }
                catch (err) {
                    console.log(err);
                    console.log('ssr failed, go with client render only');
                }
            }
            yield this.injectHtml(this.indexEjsPath, this.indexHtmlPath, cjsOptions);
            console.log('Ssr inject finished');
            yield this.copyFilesToPublic();
            console.log('Copy files to public finished');
            const files = yield this.getFiles();
            return {
                files,
                srcPath: this.previewPath,
                url: `/preview/${this.opts.activity.act_key}/index.html`,
            };
        });
    }
    // getCheckCdn(files) {
    //   const cdnRelatePaths = _.filter(files, f => {
    //     return /main.*js/.test(f);
    //   });
    //   const cdnRelatePath =
    //     (cdnRelatePaths[0] && cdnRelatePaths[0].replace(`${this.previewPath}/`, '')) || '';
    //   const key = `${this.opts.activity.act_key}-${this.opts.mainProject.proj_key}`;
    //   return [
    //     tools.getAssetCdn(this.opts.mainProject.proj_cdn_domain, this.opts.mainProject.proj_key),
    //     key,
    //     cdnRelatePath,
    //   ].join('/');
    // }
    getFiles() {
        return __awaiter(this, void 0, void 0, function* () {
            const finalFolder = 'preview';
            const pattern = `workspace/compile/${this.opts.activity.act_key}/${finalFolder}/**/*`;
            return new Promise((resolve, reject) => {
                glob_1.default(pattern, { dot: false, realpath: true }, (err, files) => {
                    if (err) {
                        console.error(err);
                        reject(err);
                    }
                    resolve(files);
                });
            });
        });
    }
    copyFilesToPublic() {
        return __awaiter(this, void 0, void 0, function* () {
            return new Promise((resolve, reject) => {
                fs_extra_1.default.copy(this.previewPath, this.publicPath, err => {
                    if (err) {
                        reject(err);
                    }
                    resolve();
                });
            });
        });
    }
    injectHtml(indexEjsPath, indexHtmlPath, options) {
        return __awaiter(this, void 0, void 0, function* () {
            return new Promise((resolve, reject) => {
                console.log('ejs>>>>>>>>>', JSON.stringify(options));
                ejs_1.default.renderFile(indexEjsPath, options, { delimiter: '?' }, (err, str) => {
                    if (err) {
                        console.error('ejs render failed');
                        reject(err);
                    }
                    fs_extra_1.default.outputFile(indexHtmlPath, str, err1 => {
                        if (err1) {
                            console.error('generate final html file failed');
                            reject(err1);
                        }
                        resolve();
                    });
                });
            });
        });
    }
    ssrRender() {
        return __awaiter(this, void 0, void 0, function* () {
            const ssrFilePath = path_1.default.resolve(this.workspaceCompilePath, 'ssr/ssr-bundle.js');
            require_1.purgeCache(ssrFilePath);
            const App = require(ssrFilePath).default; //eslint-disable-line
            const { renderToString } = require(ssrFilePath); //eslint-disable-line
            console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>');
            console.log(renderToString);
            const html = renderToString();
            if (!html) {
                throw new Error('server render failed');
            }
            return html;
        });
    }
    compile(configPath, params) {
        return __awaiter(this, void 0, void 0, function* () {
            console.log(params);
            const command = `./node_modules/.bin/webpack --config ${configPath}`;
            console.log('Run webpack command>>>>>>>>>>>>> ', command, '\n>>>>>>>>>>at: ', this.workspaceCompilePath);
            return new Promise((resolve, reject) => {
                const process = child_process_1.default.exec(command, { cwd: this.workspaceCompilePath }, (err, stdout, stderr) => {
                    if (stdout) {
                        console.log(stdout);
                    }
                    if (stderr) {
                        console.error(stderr);
                    }
                    if (err) {
                        console.error('Fatal webpack errors:', err.stack || err);
                        return reject(err);
                    }
                });
                process.on('exit', resolve);
            });
        });
    }
    generateComponentImport(comp) {
        const { compName, actions, __implementHotArea, data, children } = comp;
        const key = `${this.opts.paths.libName}-${compName}`;
        if (!this.importMap.has(key)) {
            this.templateData.componentImports.push(`import ${compName} from '../libraries/${this.opts.paths.libName}/components/${compName}'`);
            this.importMap.set(key, true);
        }
        if (children && children.length > 0) {
            children.forEach((childComp) => {
                const finalChild = this.generateFinalComponent(childComp);
                this.generateComponentImport(finalChild);
            });
        }
        if (actions && actions.length > 0) {
            actions.forEach(this.generateActionImport);
        }
        if (__implementHotArea && data.hotAreas && data.hotAreas.length) {
            console.log('start to handle hotareas', data.hotAreas);
            data.hotAreas.forEach((h) => {
                if (h.actions && h.actions.length) {
                    h.actions.forEach(this.generateActionImport);
                }
            });
        }
    }
    getMetaData() {
        if (this.actMetaData) {
            return this.actMetaData;
        }
        const { act_id, act_name, act_description, act_key, act_start_time, act_end_time, act_is_base, } = this.opts.activity.dataValues;
        this.actMetaData = {
            title: act_name,
            desc: act_description,
            start: act_start_time,
            end: act_end_time,
            actId: act_id,
            actKey: act_key,
            containerType: this.opts.container.container_type || '*',
            isTemplate: !!act_is_base,
            isEditor: false,
            isTestEnv: true,
        };
        return this.actMetaData;
    }
    getGlobalData() {
        if (this.actGlobalData) {
            return this.actGlobalData;
        }
        if (this.opts.historyExt && this.opts.historyExt.global) {
            this.actGlobalData = this.opts.historyExt.global;
        }
        else {
            this.actGlobalData = {};
        }
        return this.actGlobalData;
    }
    getJimuVars() {
        const { act_key, act_start_time, act_end_time } = this.opts.activity.dataValues;
        let vars = {
            key: act_key,
            actStartTime: act_start_time,
            actEndTime: act_end_time,
            isJimu: false,
        };
        if (this.opts.historyExt && this.opts.historyExt.global) {
            vars = Object.assign({}, vars, this.opts.historyExt.global);
        }
        return vars;
    }
    generateJsx() {
        return __awaiter(this, void 0, void 0, function* () {
            this.importMap = new Map();
            this.libSet = new Set();
            this.templateData = {
                componentImports: [],
                components: {},
                componentInstances: [],
                pluginImports: [],
                plugins: {},
                pluginInstances: [],
                actionImports: [],
                actions: {},
                injectedStyle: [],
                globalStyle: this.opts.historyExt.style,
                meta: this.getMetaData(),
                global: this.getGlobalData(),
                jimuVars: this.getJimuVars(),
            };
            this.generatePluginInstances();
            this.generateComponentInstances();
            // console.log(JSON.stringify(this.templateData, null, 4));
            const data = utils_1.default.formatTemplateData(this.templateData);
            console.log('templateData>>>>>>', data);
            const dest = path_1.default.resolve(this.workspaceCompilePath, 'src/app.jsx');
            const template = fs_extra_1.default.readFileSync(path_1.default.resolve(__dirname, './template/app.tpl'), {
                encoding: 'utf-8',
            });
            const jsx = lodash_template_1.default(template)(data);
            console.log('final jsx>>>>>', jsx);
            yield fs_extra_1.default.outputFile(dest, jsx);
            return this.libSet;
        });
    }
    generatePluginInstances() {
        const { plugins = [] } = this.opts.historyContent || {};
        plugins.forEach((plug) => {
            const finalPlug = this.generateFinalPlugin(plug);
            console.log('>>>>>>>>>>>>>>>>>>>finalPlug', finalPlug);
            this.generatePluginImport(finalPlug);
            this.templateData.pluginInstances.push(this.generatePluginInstanceItem(finalPlug));
        });
    }
    generatePluginInstanceItem(plug) {
        const { data, key, pluginName } = plug;
        if (!this.templateData.plugins[plug.id]) {
            this.templateData.plugins[plug.id] = {
                id: plug.id,
                projId: plug.projId || this.opts.paths.libName,
                name: pluginName,
                info: {
                    name: plug.pluginName,
                    desc: plug.plugin_description || '',
                    author: plug.plugin_create_user || '',
                },
            };
        }
        return {
            key,
            plugin: plug.id,
            data,
        };
    }
    generateFinalPlugin(plug) {
        const pluginName = this.getName('plugin', plug.id);
        // const plugin = this.opts.projPluginsMap[plug.id];
        const finalPlug = Object.assign({}, plug, { pluginName });
        if (!this.libSet.has(this.opts.paths.libName)) {
            this.libSet.add(this.opts.paths.libName);
        }
        return finalPlug;
    }
    generatePluginImport(plugin) {
        const { pluginName } = plugin;
        const key = `${this.opts.paths.libName}-${pluginName}`;
        if (!this.importMap.has(key)) {
            this.templateData.pluginImports.push(`import ${pluginName} from '../libraries/${this.opts.paths.libName}/plugins/${pluginName}'`);
            this.importMap.set(key, true);
        }
    }
    generateComponentInstances() {
        const { components = [] } = this.opts.historyContent || {};
        console.log(components);
        components.forEach((comp) => {
            const finalComp = this.generateFinalComponent(comp);
            console.log('>>>>>>>>>>>>>>>>>>>finalCom', finalComp);
            this.generateComponentImport(finalComp);
            this.templateData.componentInstances.push(this.generateComponentInstanceItem(finalComp));
            this.templateData.injectedStyle.push(this.generateComponentInjectedStyle(finalComp));
        });
    }
    getName(type, value) {
        const nameLower = value.replace(`${type}/`, '');
        return nameLower.charAt(0).toUpperCase() + nameLower.substr(1);
    }
    generateFinalComponent(comp) {
        const compName = this.getName('component', comp.id);
        // const component = this.opts.projComponentsMap[compName];
        const finalCom = Object.assign({}, comp, { compName });
        if (!this.libSet.has(this.opts.paths.libName)) {
            this.libSet.add(this.opts.paths.libName);
        }
        return finalCom;
    }
    generateComponentInjectedStyle(comp) {
        const { key, style, com_path } = comp;
        const schemaPath = path_1.default.resolve(this.materialsPath, `styleSchema.js`);
        if (!fs_extra_1.default.existsSync(schemaPath)) {
            return null;
        }
        // eslint-disable-next-line
        const schemaMap = require(schemaPath);
        const schema = schemaMap[com_path];
        if (!schema) {
            return null;
        }
        const id = `__impage-component-wrapper-${key}`;
        return utils_1.default.formatInjectStyles(id, style, schema);
    }
    generateComponentInstanceItem(comp) {
        const { data, key, style, commonStyle, wrapperStyle, actions, children, position } = comp;
        if (!this.templateData.components[comp.id]) {
            this.templateData.components[comp.id] = {
                id: comp.id,
                projId: comp.proj_id || this.opts.paths.libName,
                projKey: this.opts.paths.libName,
                name: comp.compName,
                info: {
                    name: comp.compName,
                    desc: comp.com_description || '',
                    author: comp.com_create_user || '',
                },
                runtime: comp.runtime,
                __implementHotArea: comp.__implementHotArea,
            };
        }
        const instance = {
            key,
            component: comp.id,
            data,
            style,
            position,
            commonStyle,
            wrapperStyle,
            actions: [],
        };
        if (actions && actions.length > 0) {
            actions.forEach((a) => instance.actions.push(this.generateActionInstanceItem(a)));
        }
        const { hotAreas } = data;
        if (comp.__implementHotArea && hotAreas && hotAreas.length) {
            instance.data.hotAreas = [];
            hotAreas.forEach((hotArea) => {
                if (!hotArea.actions.length) {
                    return;
                }
                instance.data.hotAreas.push(Object.assign({}, hotArea, { actions: hotArea.actions.map((action) => this.generateActionInstanceItem(action)) }));
            });
        }
        if (children && children.length) {
            instance.children = children.map((child) => {
                const finalChild = this.generateFinalComponent(child);
                return this.generateComponentInstanceItem(finalChild);
            });
        }
        return instance;
    }
    cleanPath() {
        return __awaiter(this, void 0, void 0, function* () {
            yield fs_extra_1.default.remove(this.workspaceCompilePath);
        });
    }
    copyActions() {
        return __awaiter(this, void 0, void 0, function* () {
            return new Promise((resolve, reject) => {
                const libPath = path_1.default.resolve(this.cwd, 'src/actions');
                if (!fs_extra_1.default.existsSync(libPath)) {
                    console.log(`Skip copy actions: project with empty materials`);
                    resolve();
                }
                const destPath = path_1.default.resolve(this.workspaceCompilePath, 'libraries', this.opts.paths.libName, 'actions');
                fs_extra_1.default.copy(libPath, destPath, err => {
                    if (err) {
                        console.log(`copy actions from project failed`);
                        reject(err);
                    }
                    resolve();
                });
            });
        });
    }
    copyPlugins() {
        return __awaiter(this, void 0, void 0, function* () {
            return new Promise((resolve, reject) => {
                const libPath = path_1.default.resolve(process.cwd(), 'src/plugins');
                if (!fs_extra_1.default.existsSync(libPath)) {
                    console.log(`Skip copy plugins: project with empty materials`);
                    resolve();
                }
                const destPath = path_1.default.resolve(this.workspaceCompilePath, 'libraries', this.opts.paths.libName, 'plugins');
                fs_extra_1.default.copy(libPath, destPath, err => {
                    if (err) {
                        console.log(`copy plugins from project failed`);
                        reject(err);
                    }
                    resolve();
                });
            });
        });
    }
    copyComponents() {
        return __awaiter(this, void 0, void 0, function* () {
            return new Promise((resolve, reject) => {
                const libPath = path_1.default.resolve(this.cwd, 'src/components');
                if (!fs_extra_1.default.existsSync(libPath)) {
                    console.log(`Skip copy components: project with empty materials`);
                    resolve();
                }
                const destPath = path_1.default.resolve(this.workspaceCompilePath, 'libraries', this.opts.paths.libName, 'components');
                fs_extra_1.default.copy(libPath, destPath, err => {
                    if (err) {
                        console.error(`copy components from project failed`);
                        reject(err);
                    }
                    resolve();
                });
            });
        });
    }
    copyLibs() {
        return __awaiter(this, void 0, void 0, function* () {
            return new Promise((resolve, reject) => {
                const libPath = path_1.default.resolve(this.cwd, 'src/lib');
                if (!fs_extra_1.default.existsSync(libPath)) {
                    console.log(`Skip copy libs: project with empty materials`);
                    resolve();
                }
                const destPath = path_1.default.resolve(this.workspaceCompilePath, 'libraries', this.opts.paths.libName, 'lib');
                fs_extra_1.default.copy(libPath, destPath, err => {
                    if (err) {
                        console.log(`copy libs from project failed`);
                        reject(err);
                    }
                    resolve();
                });
            });
        });
    }
    copyAssets() {
        return __awaiter(this, void 0, void 0, function* () {
            return new Promise((resolve, reject) => {
                const libPath = path_1.default.resolve(this.cwd, 'src/assets');
                if (!fs_extra_1.default.existsSync(libPath)) {
                    console.log(`Skip copy assets: project with empty materials`);
                    resolve();
                }
                const destPath = path_1.default.resolve(this.workspaceCompilePath, 'libraries', this.opts.paths.libName, 'assets');
                fs_extra_1.default.copy(libPath, destPath, err => {
                    if (err) {
                        console.log(`copy assets from project failed`);
                        reject(err);
                    }
                    resolve();
                });
            });
        });
    }
    copyContainer() {
        return __awaiter(this, void 0, void 0, function* () {
            try {
                console.log('this.workspaceCompilePath>>>>>>', this.containerPath, this.workspaceCompilePath);
                yield fs_extra_1.default.copy(this.containerPath, this.workspaceCompilePath);
            }
            catch (err) {
                if (err) {
                    console.error(`copy container ${this.opts.container.container_path} from project ${this.opts.paths.libName} failed`);
                }
                throw err;
            }
        });
    }
    createNodeModulesSoftLink() {
        const modulesPath = path_1.default.resolve(this.cwd, './node_modules');
        const dest = path_1.default.resolve(this.workspaceCompilePath, './node_modules/');
        return symlinkDir(modulesPath, dest)
            .then(() => console.log(`Create soft-link from ${modulesPath} to ${dest} success.`))
            .catch((err) => {
            if (err) {
                console.error(`Create soft-link from ${modulesPath} to ${dest} failed: `, err);
            }
            return Promise.reject(err);
        });
    }
    copyWebpackConfig() {
        return __awaiter(this, void 0, void 0, function* () {
            const configPath = path_1.default.resolve(process.cwd(), 'webpack');
            const dest = path_1.default.resolve(this.workspaceCompilePath, './webpack');
            try {
                console.log('copy webpack config >>>>>>', configPath, dest);
                yield fs_extra_1.default.copy(configPath, dest);
            }
            catch (err) {
                if (err) {
                    console.error('copy webpack config from project failed');
                }
                throw err;
            }
        });
    }
    getBaseBuildParams(ssr = false) {
        const { activity } = this.opts;
        return {
            libName: this.opts.paths.libName,
            context: this.workspaceCompilePath,
            entry: path_1.default.resolve(this.workspaceCompilePath, ssr ? './src/app.jsx' : './index.jsx'),
            output: {
                path: path_1.default.join(this.workspaceCompilePath, './preview'),
                filename: '[name].[contenthash].bundle.js',
                chunkFilename: '[name].[contenthash].chunk.js',
                publicPath: `/preview/${activity.act_key}/`,
            },
            externals: {},
            modules: [...this.resolveModules, path_1.default.resolve(process.cwd(), './node_modules')],
            paths: {
                libSrcPath: path_1.default.resolve(this.workspaceCompilePath, `./libraries/${this.opts.paths.libName}`),
                libModulesPath: path_1.default.resolve(__dirname, `../../../../workspace/libraries/materials-${this.opts.paths.libName}/node_modules`),
                containerPath: this.containerPath,
            },
            templateData: {
                global: this.getGlobalData(),
                meta: this.getMetaData(),
            },
        };
    }
    generateDevBuildParamsFile() {
        return __awaiter(this, void 0, void 0, function* () {
            const params = this.getBaseBuildParams();
            const configPath = path_1.default.resolve(this.workspaceCompilePath, './webpack');
            yield fs_extra_1.default.writeFile(path_1.default.resolve(configPath, `./webpack.dev.js`), `const params = ${JSON.stringify(params, null, 4)};\n\nmodule.exports = require('./dev.js')(params);`);
            return params;
        });
    }
    // async generateProdBuildParamsFile() {
    //   const params = this.getBaseBuildParams();
    //   const configPath = path.resolve(this.workspaceCompilePath, './webpack');
    //   await fs.writeFile(
    //     path.resolve(configPath, `./webpack.prod.js`),
    //     `const params = ${JSON.stringify(
    //       params,
    //       null,
    //       4
    //     )};\n\nmodule.exports = require('./prod.js')(params);`
    //   );
    //   return params;
    // }
    generateSsrBuildParamsFile() {
        return __awaiter(this, void 0, void 0, function* () {
            const devParams = this.getBaseBuildParams(true);
            const params = Object.assign({}, devParams, { output: Object.assign({}, devParams.output, { path: path_1.default.resolve(this.workspaceCompilePath, './ssr'), filename: 'ssr-bundle.js', libraryTarget: 'commonjs2' }), externals: Object.assign({}, devParams.externals, { react: 'react', 'react-dom': 'react-dom' }) });
            const configPath = path_1.default.resolve(this.workspaceCompilePath, './webpack');
            yield fs_extra_1.default.writeFile(path_1.default.resolve(configPath, `./webpack.ssr.js`), `const params = ${JSON.stringify(params, null, 4)};\n\nmodule.exports = require('./ssr.js')(params);`);
            return params;
        });
    }
    generateBuildParamsFile() {
        return __awaiter(this, void 0, void 0, function* () {
            return Promise.all([this.generateDevBuildParamsFile(), this.generateSsrBuildParamsFile()]);
        });
    }
    copyHandler() {
        return __awaiter(this, void 0, void 0, function* () {
            return new Promise((resolve, reject) => {
                const handlerPath = path_1.default.resolve(__dirname, 'handlers');
                const destPath = path_1.default.resolve(this.workspaceCompilePath, 'handlers');
                fs_extra_1.default.copy(handlerPath, destPath, err => {
                    if (err) {
                        console.log('copy handler failed');
                        reject(err);
                    }
                    resolve();
                });
            });
        });
    }
}
exports.default = ReactBuild;
/* eslint-enable */
//# sourceMappingURL=builder.js.map