/**
 * BaseEngine과 EsbuildClientEngine의 공통 watch 이벤트 처리를 설정한다.
 *
 * buildStart → RebuildManager.registerBuild() 호출
 * build → ResultCollector.add() + resolver 호출
 * error → ResultCollector.add() + resolver 호출
 *
 * @returns waitForInitialBuild - 첫 build/error 이벤트에서 resolve되는 Promise 반환 함수
 * @returns resolveInitialBuild - 수동으로 초기 빌드를 resolve (startWatch 실패 시 사용)
 */
export function setupWatchEvents(worker, options) {
    const { name, target, resultCollector, rebuildManager, normalizeBuild } = options;
    const workerKey = `${name}:build`;
    let resolver;
    let isInitialBuild = true;
    let initialBuildResolve;
    worker.on("buildStart", () => {
        if (rebuildManager != null) {
            resolver = rebuildManager.registerBuild(workerKey, `${name} (${target})`);
        }
    });
    worker.on("build", (data) => {
        const info = normalizeBuild(data);
        const buildResult = {
            name,
            target,
            type: "build",
            status: info.success ? "success" : "error",
            message: info.errors?.join("\n"),
            warnings: info.warnings != null && info.warnings.length > 0
                ? info.warnings.join("\n")
                : undefined,
        };
        resultCollector?.add(buildResult);
        resolver?.();
        resolver = undefined;
        if (isInitialBuild) {
            isInitialBuild = false;
            initialBuildResolve?.();
        }
    });
    worker.on("error", (data) => {
        const event = data;
        const buildResult = {
            name,
            target,
            type: "build",
            status: "error",
            message: event.message,
        };
        resultCollector?.add(buildResult);
        resolver?.();
        resolver = undefined;
        if (isInitialBuild) {
            isInitialBuild = false;
            initialBuildResolve?.();
        }
    });
    function resolveInitialBuild() {
        if (isInitialBuild) {
            isInitialBuild = false;
            initialBuildResolve?.();
        }
    }
    function waitForInitialBuild() {
        if (!isInitialBuild) {
            return Promise.resolve();
        }
        return new Promise((resolve) => {
            initialBuildResolve = resolve;
        });
    }
    return { waitForInitialBuild, resolveInitialBuild };
}
//# sourceMappingURL=engine-watch-events.js.map