if (typeof process === 'object' && process !== null &&
    process.env !== null && typeof process.env === 'object') {
  process.env.DD_GIT_REPOSITORY_URL = 'https://token@github.com/superblocksteam/superblocks.git';
  process.env.DD_GIT_COMMIT_SHA = '71329cb2a26133447acee36261ec5a5145024e84';
}
import { createRequire as $dd_createRequire } from 'module';
import { fileURLToPath as $dd_fileURLToPath } from 'url';
import { dirname as $dd_dirname } from 'path';
globalThis.require ??= $dd_createRequire(import.meta.url);
globalThis.__filename ??= $dd_fileURLToPath(import.meta.url);
globalThis.__dirname ??= $dd_dirname(globalThis.__filename);

import {
  init_cjs_shims
} from "../chunk-MTQ2JLIW.js";

// src/commands/dev-parent.mts
init_cjs_shims();
import * as child_process from "node:child_process";
import * as fs2 from "node:fs";
import * as os from "node:os";
import { resolve } from "node:path";

// src/commands/restart-template-env.mts
init_cjs_shims();
import fs from "node:fs";
import path from "node:path";
var RESTART_SUPERVISED_ENV = "SUPERBLOCKS_RESTART_SUPERVISED";
var RESTART_REASON_ENV = "SUPERBLOCKS_RESTART_REASON";
var RESTART_REASON_FLIP_RESTART = "flip_restart";
function readTemplateMarker(appRootDir) {
  try {
    const value = fs.readFileSync(path.join(appRootDir, ".sb_template"), "utf-8").trim();
    return value || null;
  } catch {
    return null;
  }
}
function resolveRestartChildEnv(baseEnv, templateName) {
  const next = { ...baseEnv };
  const currentTemplate = baseEnv.SUPERBLOCKS_APP_TEMPLATE_NAME ?? baseEnv.TEMPLATE_NAME;
  if (templateName && templateName !== currentTemplate) {
    next.SUPERBLOCKS_APP_TEMPLATE_NAME = templateName;
    next.TEMPLATE_NAME = templateName;
    delete next.SUPERBLOCKS_APP_ENTRY_POINT;
  }
  return next;
}

// src/commands/parent-otlp-metric.mts
init_cjs_shims();
import * as http from "node:http";
import * as https from "node:https";
var SERVICE_NAME = "sdk-dev-server";
var SCOPE_NAME = "superblocks.cli.dev-parent";
var DEV_SERVER_RESTART_COMPLETED_METRIC = "dev_server_child_respawn_completed_total";
var DEV_SERVER_RESTART_COMPLETED_DESCRIPTION = "Count of dev-server child respawns that reached boot after an in-place restart, by reason.";
var DEFAULT_TIMEOUT_MS = 1e3;
function resolveOtlpMetricsUrl(env = process.env) {
  const collector = env.SUPERBLOCKS_OTEL_COLLECTOR_URL;
  if (collector) {
    const base = collector.replace(/\/v1\/(traces|metrics|logs)$/, "").replace(/\/+$/, "");
    return `${base}/v1/metrics`;
  }
  const baseUrl = env.SUPERBLOCKS_BASE_URL;
  if (baseUrl) {
    try {
      return `${new URL(baseUrl).origin}/api/v1/metrics`;
    } catch {
      return null;
    }
  }
  return null;
}
function deploymentEnvironmentFromBaseUrl(env = process.env) {
  const baseUrl = env.SUPERBLOCKS_BASE_URL;
  if (!baseUrl) {
    return "other";
  }
  let hostname;
  try {
    hostname = new URL(baseUrl).hostname;
  } catch {
    return "other";
  }
  if (hostname.match(/^app\.superblocks(?:hq)?\.com/)) return "prod";
  if (hostname.match(/^eu\.superblocks(?:hq)?\.com/)) return "prod-eu";
  if (hostname.match(/^staging\.superblocks(?:hq)?\.com/)) return "staging";
  if (hostname.match(/^dev\.superblocks(?:hq)?\.com/)) return "dev";
  if (hostname.match(/^pr-[0-9]+\.superblocks(?:hq)?\.dev/)) return "ephemeral";
  if (hostname.match(/^localhost/)) return "local";
  return "other";
}
function toAttributeArray(attributes) {
  return Object.entries(attributes).map(([key, value]) => ({
    key,
    value: { stringValue: value }
  }));
}
function buildDeltaCounterPayload(opts) {
  const nowNano = BigInt(opts.nowMs ?? Date.now()) * 1000000n;
  const startNano = nowNano - 1000000n;
  return {
    resourceMetrics: [
      {
        resource: {
          attributes: toAttributeArray({
            "service.name": opts.serviceName ?? SERVICE_NAME,
            "deployment.environment.name": opts.environment
          })
        },
        scopeMetrics: [
          {
            scope: { name: opts.scopeName ?? SCOPE_NAME },
            metrics: [
              {
                name: opts.name,
                description: opts.description,
                sum: {
                  aggregationTemporality: 1,
                  // AGGREGATION_TEMPORALITY_DELTA
                  isMonotonic: true,
                  dataPoints: [
                    {
                      attributes: toAttributeArray(opts.attributes),
                      startTimeUnixNano: startNano.toString(),
                      timeUnixNano: nowNano.toString(),
                      asInt: "1"
                    }
                  ]
                }
              }
            ]
          }
        ]
      }
    ]
  };
}
function emitOtlpCounter(opts) {
  const env = opts.env ?? process.env;
  const url = resolveOtlpMetricsUrl(env);
  if (!url) {
    return Promise.resolve();
  }
  let parsed;
  try {
    parsed = new URL(url);
  } catch {
    return Promise.resolve();
  }
  const body = JSON.stringify(
    buildDeltaCounterPayload({
      name: opts.name,
      description: opts.description,
      attributes: opts.attributes,
      environment: deploymentEnvironmentFromBaseUrl(env)
    })
  );
  const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
  const unref = opts.unref ?? true;
  const transport = parsed.protocol === "https:" ? https : http;
  return new Promise((resolve2) => {
    let settled = false;
    const done = () => {
      if (settled) return;
      settled = true;
      resolve2();
    };
    const req = transport.request(
      {
        protocol: parsed.protocol,
        hostname: parsed.hostname,
        port: parsed.port,
        path: parsed.pathname + parsed.search,
        method: "POST",
        headers: {
          "content-type": "application/json",
          "content-length": Buffer.byteLength(body)
        }
      },
      (res) => {
        res.on("data", () => {
        });
        res.on("end", done);
        res.on("error", done);
      }
    );
    req.on("error", done);
    req.setTimeout(timeoutMs, () => {
      req.destroy();
      done();
    });
    if (unref) {
      req.on("socket", (socket) => socket.unref());
    }
    req.end(body);
  });
}
function emitFlipRestartCompletedMetric(opts) {
  return emitOtlpCounter({
    name: DEV_SERVER_RESTART_COMPLETED_METRIC,
    description: DEV_SERVER_RESTART_COMPLETED_DESCRIPTION,
    attributes: { reason: RESTART_REASON_FLIP_RESTART },
    env: opts?.env,
    timeoutMs: opts?.timeoutMs,
    unref: opts?.unref
  });
}

// src/commands/dev-parent.mts
var RESTART_EXIT_CODE = 98;
var AUTO_UPGRADE_EXIT_CODE = 99;
var signalHandlers = {};
var isCSB = process.env.SUPERBLOCKS_IS_CSB === "true";
var PARENT_INFO_LOG = {
  childReadyForToken: "Child is ready to receive token",
  childBootedAfterRestart: "Dev server child booted after in-place restart",
  devServerCompletedAutoUpgrade: "Dev server completed: auto-upgrade",
  devServerCompletedExit: "Dev server completed: exit",
  devServerCompletedFailure: "Dev server completed: failure",
  devServerCompletedRestart: "Dev server completed: restart",
  devServerExitedForAutoUpgrade: "Dev server exited due to automatic upgrade",
  devServerExitedWithFailure: "Dev server exited with failure",
  devServerExitedSuccessfully: "Dev server exited successfully",
  devServerRestarting: "Dev server restarting",
  devServerRestartingWithoutTemplateOverride: "Dev server restarting \u2014 .sb_template not found, pod env unchanged",
  noTokenAwaitAuthHotReload: "No token available, child will need to wait for auth hot-reload",
  sendingInitialTokenToChild: "Sending initial token to child",
  tokenUpdatedFromChild: "Token updated from child process"
};
var PARENT_ERROR_LOG = {
  errorInParentProcess: "Error in parent process:",
  errorMissingUploadOrDownloadFirst: "Error: This command requires either the --upload-first or --download-first flag",
  errorSkipAndForceAutoUpgrade: "Error: Use either --skip-auto-upgrade or --force-auto-upgrade flag, but not both",
  failedToSpawnChildProcess: "Failed to spawn child process"
};
function log(message) {
  if (isCSB) {
    console.log(
      JSON.stringify({
        level: "info",
        message: `[dev] ${message}`,
        timestamp: (/* @__PURE__ */ new Date()).toISOString(),
        process: "parent"
      })
    );
  } else {
    console.log(`[dev] ${message}`);
  }
}
function logError(message, error) {
  if (isCSB) {
    console.error(
      JSON.stringify({
        level: "error",
        message,
        timestamp: (/* @__PURE__ */ new Date()).toISOString(),
        process: "parent"
      })
    );
  } else if (typeof error !== "undefined") {
    console.error(message, error);
  } else {
    console.error(message);
  }
}
function logDevServerCompleted(result) {
  switch (result) {
    case "auto-upgrade":
      log(PARENT_INFO_LOG.devServerCompletedAutoUpgrade);
      return;
    case "exit":
      log(PARENT_INFO_LOG.devServerCompletedExit);
      return;
    case "failure":
      log(PARENT_INFO_LOG.devServerCompletedFailure);
      return;
    case "restart":
      log(PARENT_INFO_LOG.devServerCompletedRestart);
      return;
    default:
      result;
  }
}
function classifyChildExit(code) {
  if (code === RESTART_EXIT_CODE) {
    return "restart";
  }
  if (code === AUTO_UPGRADE_EXIT_CODE) {
    return "auto-upgrade";
  }
  if (code === 0) {
    return "exit";
  }
  return "failure";
}
function setupSignalHandlers(child) {
  for (const [signal, handler] of Object.entries(signalHandlers)) {
    process.off(signal, handler);
  }
  signalHandlers = {
    SIGINT: () => child.kill("SIGINT"),
    SIGHUP: () => child.kill("SIGHUP"),
    SIGTERM: () => child.kill("SIGTERM"),
    SIGQUIT: () => child.kill("SIGQUIT"),
    SIGABRT: () => child.kill("SIGABRT")
  };
  for (const [signal, handler] of Object.entries(signalHandlers)) {
    process.on(signal, handler);
  }
}
function cleanupSignalHandlers() {
  for (const [signal, handler] of Object.entries(signalHandlers)) {
    process.off(signal, handler);
  }
  signalHandlers = {};
}
function getParentAuthFilePath() {
  return process.env.SUPERBLOCKS_AUTH_FILE ? resolve(process.env.SUPERBLOCKS_AUTH_FILE) : resolve(os.homedir(), ".superblocks", "auth.json");
}
function readTokenFromAuthFile() {
  try {
    const authFilePath = getParentAuthFilePath();
    if (fs2.existsSync(authFilePath)) {
      const authData = JSON.parse(fs2.readFileSync(authFilePath, "utf-8"));
      return authData.token || "";
    }
  } catch {
  }
  return "";
}
async function spawnAndWaitForChild(previousRunResult, previousRestartReason, options, currentToken) {
  let token = currentToken;
  let childRestartReason = null;
  const isFlipRespawn = previousRunResult === "restart" && previousRestartReason === RESTART_REASON_FLIP_RESTART;
  return new Promise((resolvePromise) => {
    const originalArgs = process.argv.slice(1);
    let processArgs;
    if (previousRunResult === "restart") {
      const sliceUntil = originalArgs.findIndex((arg) => arg === "dev");
      if (sliceUntil === -1) {
        throw new Error("dev command not found in args");
      }
      const baseArgs = originalArgs.slice(0, sliceUntil + 1);
      processArgs = [
        ...baseArgs,
        "--child",
        "--download-first",
        ...typeof options.port === "number" && !Number.isNaN(options.port) ? [`--port=${options.port}`] : []
      ];
    } else if (previousRunResult === "auto-upgrade") {
      processArgs = [
        ...originalArgs.filter((arg) => arg !== "--child"),
        "--child",
        "--skip-auto-upgrade"
      ];
    } else {
      processArgs = [...originalArgs, "--child"];
    }
    const templateMarker = readTemplateMarker(process.cwd());
    if (isFlipRespawn && templateMarker === null) {
      log(PARENT_INFO_LOG.devServerRestartingWithoutTemplateOverride);
    }
    const supervisedEnv = {
      ...process.env,
      [RESTART_SUPERVISED_ENV]: "1"
    };
    if (isFlipRespawn) {
      supervisedEnv[RESTART_REASON_ENV] = RESTART_REASON_FLIP_RESTART;
    } else {
      delete supervisedEnv[RESTART_REASON_ENV];
    }
    const childEnv = resolveRestartChildEnv(supervisedEnv, templateMarker);
    const child = child_process.spawn(process.execPath, processArgs, {
      detached: false,
      stdio: ["inherit", "inherit", "inherit", "ipc"],
      env: childEnv
    });
    let spawnErrorOccurred = false;
    child.on("error", (error) => {
      spawnErrorOccurred = true;
      cleanupSignalHandlers();
      logError(PARENT_ERROR_LOG.failedToSpawnChildProcess, error);
      resolvePromise({ result: "failure", token, restartReason: null });
    });
    child.on("message", (message) => {
      if (message.type === "ready") {
        log(PARENT_INFO_LOG.childReadyForToken);
        if (token) {
          log(PARENT_INFO_LOG.sendingInitialTokenToChild);
          child.send({
            type: "initialToken",
            token
          });
        } else {
          log(PARENT_INFO_LOG.noTokenAwaitAuthHotReload);
          child.send({ type: "noToken" });
        }
      } else if (message.type === "tokenUpdate" && message.token) {
        token = message.token;
        log(PARENT_INFO_LOG.tokenUpdatedFromChild);
      } else if (message.type === "devServerStarted") {
        if (isFlipRespawn) {
          log(PARENT_INFO_LOG.childBootedAfterRestart);
          void emitFlipRestartCompletedMetric();
        }
      } else if (message.type === "restartReason" && message.reason) {
        childRestartReason = message.reason;
      }
    });
    setupSignalHandlers(child);
    child.on("exit", (code) => {
      cleanupSignalHandlers();
      if (spawnErrorOccurred) {
        return;
      }
      const result = classifyChildExit(code);
      if (result === "restart") {
        log(PARENT_INFO_LOG.devServerRestarting);
        resolvePromise({
          result: "restart",
          token,
          restartReason: childRestartReason
        });
      } else if (result === "auto-upgrade") {
        log(PARENT_INFO_LOG.devServerExitedForAutoUpgrade);
        resolvePromise({ result: "auto-upgrade", token, restartReason: null });
      } else if (result === "exit") {
        log(PARENT_INFO_LOG.devServerExitedSuccessfully);
        resolvePromise({ result: "exit", token, restartReason: null });
      } else {
        log(PARENT_INFO_LOG.devServerExitedWithFailure);
        resolvePromise({ result: "failure", token, restartReason: null });
      }
    });
  });
}
async function runAsLightweightParent(options) {
  if (!options.uploadFirst && !options.downloadFirst) {
    logError(PARENT_ERROR_LOG.errorMissingUploadOrDownloadFirst);
    process.exitCode = 1;
    return;
  }
  if (options.skipAutoUpgrade && options.forceAutoUpgrade) {
    logError(PARENT_ERROR_LOG.errorSkipAndForceAutoUpgrade);
    process.exitCode = 1;
    return;
  }
  let currentToken = readTokenFromAuthFile();
  let previousRunResult = null;
  let previousRestartReason = null;
  do {
    try {
      const { result, token, restartReason } = await spawnAndWaitForChild(
        previousRunResult,
        previousRestartReason,
        options,
        currentToken
      );
      logDevServerCompleted(result);
      previousRunResult = result;
      previousRestartReason = restartReason;
      currentToken = token;
    } catch (error) {
      logError(PARENT_ERROR_LOG.errorInParentProcess, error);
      previousRunResult = "failure";
      previousRestartReason = null;
    }
  } while (previousRunResult === "restart" || previousRunResult === "auto-upgrade");
  if (previousRunResult === "failure") {
    process.exitCode = 1;
  }
}
export {
  RESTART_EXIT_CODE,
  classifyChildExit,
  runAsLightweightParent
};
//# sourceMappingURL=dev-parent.js.map
