import {
  findPort
} from "./chunk-OWLPHMUA.js";
import {
  DEFAULT_INSPECTOR_PORT,
  H2O_BINDING_NAME,
  SUBREQUEST_PROFILER_ENDPOINT,
  createLogRequestEvent,
  getUtilityBannerlines,
  handleDebugNetworkRequest,
  handleMiniOxygenImportFail,
  importLocal,
  logRequestLine,
  setConstructors
} from "./chunk-Y4KCGQM6.js";
import "./chunk-VWQVIT6Y.js";
import "./chunk-AYF3ZRJK.js";
import "./chunk-CYLLL62Y.js";
import "./chunk-RW2IZVDS.js";
import "./chunk-H2THLNWN.js";
import "./chunk-VSLR7ET4.js";
import "./chunk-SESNEAMK.js";
import "./chunk-RBFRN253.js";
import "./chunk-BYPQXSAL.js";
import "./chunk-O5K4AU7Q.js";
import "./chunk-E4UK3DDW.js";
import "./chunk-NLUGD7PZ.js";
import {
  AbortError,
  outputNewline,
  readFile,
  renderSuccess,
  source_default
} from "./chunk-BGM7BTJW.js";
import "./chunk-XEDHKQZA.js";
import "./chunk-27ILOE3X.js";
import "./chunk-SNOECVP4.js";
import "./chunk-6XKWVDB6.js";
import "./chunk-UBB7JKND.js";
import "./chunk-T2GATXSP.js";
import "./chunk-XVNW332R.js";
import "./chunk-A3JXD7N7.js";
import "./chunk-7Q3MMWAC.js";
import "./chunk-MX4RJDBM.js";
import "./chunk-NB4NLOEJ.js";
import "./chunk-522OB3EU.js";
import "./chunk-PNN7RS7Y.js";
import {
  init_cjs_shims
} from "./chunk-POZ5MGPT.js";

// ../../node_modules/.pnpm/@shopify+cli-hydrogen@9.0.2_@graphql-codegen+cli@5.0.2_react-dom@17.0.2_react@17.0.2/node_modules/@shopify/cli-hydrogen/dist/lib/mini-oxygen/node.js
init_cjs_shims();
import { AsyncLocalStorage } from "node:async_hooks";
async function startNodeServer({
  appPort,
  watch = !1,
  buildPathWorkerFile,
  buildPathClient,
  env,
  debug = !1,
  inspectorPort,
  root
}) {
  let { startServer, Request, Response } = await importLocal(
    "@shopify/mini-oxygen/node",
    root
  ).catch(handleMiniOxygenImportFail);
  setConstructors({ Response });
  let logRequestEvent = createLogRequestEvent(), asyncLocalStorage = new AsyncLocalStorage(), serviceBindings = {
    [H2O_BINDING_NAME]: {
      fetch: async (request) => logRequestEvent(
        new Request(request.url, {
          method: "POST",
          body: JSON.stringify({
            ...asyncLocalStorage.getStore(),
            ...await request.json()
          })
        })
      )
    }
  };
  debug && (inspectorPort || (inspectorPort = await findPort(DEFAULT_INSPECTOR_PORT)), (await import("node:inspector")).open(inspectorPort));
  let readWorkerFile = () => readFile(buildPathWorkerFile).catch((error) => {
    throw new AbortError(
      `Could not read worker file.

` + error.stack,
      "Did you build the project?"
    );
  }), miniOxygen = await startServer({
    script: await readWorkerFile(),
    workerFile: buildPathWorkerFile,
    assetsDir: buildPathClient,
    publicPath: "",
    port: appPort,
    watch,
    autoReload: watch,
    modules: !0,
    env: {
      ...env,
      ...process.env,
      ...serviceBindings
    },
    log: () => {
    },
    async onRequest(request, defaultDispatcher) {
      if (new URL(request.url).pathname === SUBREQUEST_PROFILER_ENDPOINT)
        return handleDebugNetworkRequest(request);
      let requestId = request.headers.get("request-id"), startTimeMs = Date.now(), response = await asyncLocalStorage.run(
        { requestId, purpose: request.headers.get("purpose") },
        () => defaultDispatcher(request)
      ), endTimeMs = Date.now();
      return logRequestLine({
        request: {
          url: request.url,
          method: request.method,
          headers: Object.fromEntries(request.headers.entries())
        },
        response: {
          status: response.status,
          statusText: response.statusText,
          headers: Object.fromEntries(response.headers.entries())
        },
        meta: {
          startTimeMs,
          endTimeMs,
          durationMs: startTimeMs > 0 ? endTimeMs - startTimeMs : 0
        }
      }), response;
    }
  }), listeningAt = `http://localhost:${miniOxygen.port}`;
  return {
    listeningAt,
    port: miniOxygen.port,
    async reload(options) {
      let nextOptions = {};
      options?.env && (nextOptions.env = {
        ...options.env,
        ...process.env
      }), nextOptions.script = await readWorkerFile(), await miniOxygen.reload(nextOptions);
    },
    showBanner(options) {
      outputNewline();
      let customSections = [];
      options?.host && customSections.push({ body: getUtilityBannerlines(options.host) }), debug && inspectorPort && customSections.push({
        body: { warn: `Debugger listening on ws://localhost:${inspectorPort}` }
      }), renderSuccess({
        headline: `${options?.headlinePrefix ?? ""}MiniOxygen (Node Sandbox) ${options?.mode ?? "development"} server running.`,
        body: [
          `View ${options?.appName ? source_default.cyan(options?.appName) : "Hydrogen"} app:`,
          { link: { url: options?.host || listeningAt } }
        ],
        customSections
      }), console.log("");
    },
    async close() {
      await miniOxygen.close();
    }
  };
}
export {
  startNodeServer
};
//# sourceMappingURL=node-WGQ75Q7F.js.map
