import "../../../../shared/src/dotenv.js";
import { resolver } from "@rocicorp/resolver";
import { PROTOCOL_VERSION } from "../../../../zero-protocol/src/protocol-version.js";
import { normalizeZeroConfig } from "../../config/normalize.js";
import { getZeroConfig, getServerVersion } from "../../config/zero-config.js";
import { ProcessManager, runUntilKilled } from "../../services/life-cycle.js";
import { childWorker } from "../../types/processes.js";
import { createLogContext } from "../logging.js";
import { MAIN_URL } from "../worker-urls.js";
import { getTaskID } from "./runtime.js";
import { ZeroDispatcher } from "./zero-dispatcher.js";
async function runWorker(parent, env) {
  const cfg = getZeroConfig({ env, emitDeprecationWarnings: true });
  const lc = createLogContext(cfg, { worker: "runner" });
  const defaultTaskID = await getTaskID(lc);
  const config = normalizeZeroConfig(lc, cfg, env, defaultTaskID);
  const processes = new ProcessManager(lc, parent ?? process);
  const { port, lazyStartup } = config;
  const serverVersion = getServerVersion(config);
  lc.info?.(`starting server${!serverVersion ? "" : `@${serverVersion}`} `, {
    protocolVersion: PROTOCOL_VERSION,
    taskID: config.taskID,
    app: config.app,
    shard: config.shard,
    port: config.port
  });
  let zeroCache;
  function startZeroCache() {
    if (zeroCache === void 0) {
      const startMs = performance.now();
      lc.info?.("starting zero-cache");
      const r = zeroCache = resolver();
      const w = childWorker(MAIN_URL, env).once("message", () => {
        r.resolve(w);
        lc.info?.(`zero-cache ready (${performance.now() - startMs} ms)`);
      }).once("error", r.reject);
      processes.addWorker(w, "user-facing", "zero-cache");
    }
    return zeroCache.promise;
  }
  if (!lazyStartup) {
    void startZeroCache();
  }
  await processes.allWorkersReady();
  parent?.send(["ready", { ready: true }]);
  try {
    await runUntilKilled(
      lc,
      parent ?? process,
      new ZeroDispatcher(config, lc, { port }, startZeroCache)
    );
  } catch (err) {
    processes.logErrorAndExit(err, "main");
  }
  await processes.done();
}
export {
  runWorker
};
//# sourceMappingURL=run-worker.js.map
