"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    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) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildBundle = void 0;
const esbuild_1 = require("esbuild");
const fs_extra_1 = require("fs-extra");
const buildIdSetFromBundle_1 = require("./buildIdSetFromBundle");
const constants_1 = require("./constants");
const build_1 = require("../script/build");
const sync_1 = require("../script/sync");
const path = require("path");
function buildBundle(unitPath, projectPath, outputFolder, watchMode = false, includeSystem = false) {
    return __awaiter(this, void 0, void 0, function* () {
        const bundlePath = path.join(projectPath, 'bundle.json');
        const bootPath = path.join(projectPath, 'system.json');
        const bootPathExists = yield (0, fs_extra_1.pathExists)(bootPath);
        const bundle = yield (0, fs_extra_1.readJSON)(bundlePath, 'utf8');
        const idSet = includeSystem ? undefined : (0, buildIdSetFromBundle_1.buildIdSetFromBundle)(bundle);
        const systemPath = path.join(unitPath, 'src', 'system');
        yield (0, sync_1.sync)(systemPath, outputFolder, idSet);
        const entrypoint = `${unitPath}/src/client/platform/web/index.ts`;
        const resolvePlugin = {
            name: 'resolve',
            setup(build) {
                build.onResolve({ filter: /.*/ }, (args) => {
                    const { resolveDir, importer } = args;
                    if (importer === entrypoint) {
                        if (args.path === './bundle.json') {
                            return { path: bundlePath };
                        }
                        if (args.path === './system.json') {
                            if (bootPathExists) {
                                return { path: bootPath };
                            }
                            else {
                                const fallbackSystemPath = path.join(unitPath, 'src/client/platform/web/system.json');
                                return { path: fallbackSystemPath };
                            }
                        }
                    }
                    if (args.path.endsWith('/system/_specs') ||
                        args.path.endsWith('/system/_components') ||
                        args.path.endsWith('/system/_ids') ||
                        args.path.endsWith('/system/_classes')) {
                        const absolutePath = path
                            .join(resolveDir, args.path)
                            .replace(`${path.join(unitPath, 'src', 'system')}`, '');
                        const otherPath = path.join(outputFolder, `${absolutePath}.ts`);
                        return { path: otherPath };
                    }
                    if (importer.endsWith('_classes.ts')) {
                        const otherPath = `${path.join(systemPath, args.path, 'index.ts')}`;
                        return { path: otherPath };
                    }
                    if (importer.endsWith('_components.ts')) {
                        const otherPath = `${path.join(systemPath, args.path)}.ts`;
                        return { path: otherPath };
                    }
                    return {};
                });
            },
        };
        const esbuildOptions = Object.assign(Object.assign({}, constants_1.DEFAULT_BUILD_OPTIONS), { entryPoints: [entrypoint], plugins: resolvePlugin ? [resolvePlugin] : [], outfile: `${outputFolder}/index.js` });
        if (watchMode) {
            yield (0, build_1.watch)(Object.assign(Object.assign({}, esbuildOptions), { minify: false, sourcemap: true }));
        }
        else {
            yield (0, esbuild_1.build)(esbuildOptions);
        }
    });
}
exports.buildBundle = buildBundle;
//# sourceMappingURL=buildBundle.js.map