#!/usr/bin/env bun
// @bun
var __defProp = Object.defineProperty;
var __returnValue = (v) => v;
function __exportSetter(name, newValue) {
  this[name] = __returnValue.bind(null, newValue);
}
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, {
      get: all[name],
      enumerable: true,
      configurable: true,
      set: __exportSetter.bind(all, name)
    });
};
var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
var __require = import.meta.require;

// src/constants.ts
var ANSI_ESCAPE_LENGTH = 3, ASCII_SPACE = 32, BASE_36_RADIX = 36, BYTES_PER_KILOBYTE = 1024, CLI_ARGS_OFFSET = 3, DEFAULT_PORT = 3000, HOURS_IN_DAY = 24, HOURS_IN_HALF_DAY = 12, MAX_ERROR_LENGTH = 200, MILLISECONDS_IN_A_SECOND = 1000, MINUTES_IN_AN_HOUR = 60, SECONDS_IN_A_MINUTE = 60, MILLISECONDS_IN_A_MINUTE, MILLISECONDS_IN_A_DAY, SIGINT_EXIT_CODE = 130, SIGTERM_EXIT_CODE = 143, TIME_PRECISION = 2, TWO_THIRDS, UNFOUND_INDEX = -1;
var init_constants = __esm(() => {
  MILLISECONDS_IN_A_MINUTE = MILLISECONDS_IN_A_SECOND * SECONDS_IN_A_MINUTE;
  MILLISECONDS_IN_A_DAY = MILLISECONDS_IN_A_SECOND * SECONDS_IN_A_MINUTE * MINUTES_IN_AN_HOUR * HOURS_IN_DAY;
  TWO_THIRDS = 2 / 3;
});

// src/utils/getDurationString.ts
var getDurationString = (duration) => {
  let durationString;
  if (duration < MILLISECONDS_IN_A_SECOND) {
    durationString = `${duration.toFixed(TIME_PRECISION)}ms`;
  } else if (duration < MILLISECONDS_IN_A_MINUTE) {
    durationString = `${(duration / MILLISECONDS_IN_A_SECOND).toFixed(TIME_PRECISION)}s`;
  } else {
    durationString = `${(duration / MILLISECONDS_IN_A_MINUTE).toFixed(TIME_PRECISION)}m`;
  }
  return durationString;
};
var init_getDurationString = __esm(() => {
  init_constants();
});

// src/utils/startupBanner.ts
var MONTHS, formatTimestamp = () => {
  const now = new Date;
  const month = MONTHS[now.getMonth()];
  const day = now.getDate().toString().padStart(2, "0");
  let hours = now.getHours();
  const minutes = now.getMinutes().toString().padStart(2, "0");
  const seconds = now.getSeconds().toString().padStart(2, "0");
  const ampm = hours >= HOURS_IN_HALF_DAY ? "PM" : "AM";
  hours = hours % HOURS_IN_HALF_DAY || HOURS_IN_HALF_DAY;
  return `${month} ${day} ${hours}:${minutes}:${seconds} ${ampm}`;
};
var init_startupBanner = __esm(() => {
  init_constants();
  init_getDurationString();
  MONTHS = [
    "Jan",
    "Feb",
    "Mar",
    "Apr",
    "May",
    "Jun",
    "Jul",
    "Aug",
    "Sep",
    "Oct",
    "Nov",
    "Dec"
  ];
});

// src/cli/scripts/telemetry.ts
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
import { homedir } from "os";
import { join } from "path";
var configDir, configPath, getTelemetryConfig = () => {
  try {
    if (!existsSync(configPath))
      return null;
    const raw = readFileSync(configPath, "utf-8");
    const config = JSON.parse(raw);
    return config;
  } catch {
    return null;
  }
}, saveTelemetryConfig = (config) => {
  mkdirSync(configDir, { recursive: true });
  writeFileSync(configPath, `${JSON.stringify(config, null, "\t")}
`);
}, enable = () => {
  const existing = getTelemetryConfig();
  const config = {
    anonymousId: existing?.anonymousId ?? crypto.randomUUID(),
    createdAt: existing?.createdAt ?? new Date().toISOString(),
    enabled: true
  };
  saveTelemetryConfig(config);
  console.log("Telemetry enabled.");
  console.log(`Anonymous ID: ${config.anonymousId}`);
}, disable = () => {
  const existing = getTelemetryConfig();
  if (existing) {
    saveTelemetryConfig({ ...existing, enabled: false });
  }
  console.log("Telemetry disabled.");
}, status = () => {
  const config = getTelemetryConfig();
  if (!config || !config.enabled) {
    console.log("Telemetry is disabled.");
  } else {
    console.log("Telemetry is enabled.");
    console.log(`Anonymous ID: ${config.anonymousId}`);
  }
}, telemetry = (args) => {
  const [subcommand] = args;
  if (subcommand === "enable") {
    enable();
    return;
  }
  if (subcommand === "disable") {
    disable();
    return;
  }
  if (subcommand === "status") {
    status();
    return;
  }
  if (!subcommand) {
    status();
    console.log("");
    console.log("Usage: absolute telemetry <command>");
    console.log("Commands:");
    console.log("  enable    Enable anonymous telemetry");
    console.log("  disable   Disable telemetry");
    console.log("  status    Show current telemetry status");
    return;
  }
  console.error(`Unknown telemetry command: ${subcommand}`);
  console.error("Usage: absolute telemetry <enable|disable|status>");
  process.exit(1);
};
var init_telemetry = __esm(() => {
  configDir = join(homedir(), ".absolutejs");
  configPath = join(configDir, "telemetry.json");
});

// src/cli/telemetryEvent.ts
import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
import { arch, platform } from "os";
import { dirname, join as join2, parse } from "path";
var checkCandidate = (candidate) => {
  if (!existsSync2(candidate)) {
    return null;
  }
  const pkg = JSON.parse(readFileSync2(candidate, "utf-8"));
  if (pkg.name === "@absolutejs/absolute") {
    const ver = pkg.version;
    return ver;
  }
  return null;
}, getVersion = () => {
  try {
    return findPackageVersion();
  } catch {
    return "unknown";
  }
}, findPackageVersion = () => {
  let { dir } = import.meta;
  while (dir !== parse(dir).root) {
    const candidate = join2(dir, "package.json");
    const version = checkCandidate(candidate);
    if (version) {
      return version;
    }
    dir = dirname(dir);
  }
  return "unknown";
}, sendTelemetryEvent = (event, payload) => {
  try {
    if (process.env.TELEMETRY_OFF === "1")
      return;
    const config = getTelemetryConfig();
    if (!config?.enabled)
      return;
    const body = {
      anonymousId: config.anonymousId,
      arch: arch(),
      bunVersion: Bun.version,
      event,
      os: platform(),
      payload,
      timestamp: new Date().toISOString(),
      version: getVersion()
    };
    fetch("https://absolutejs.com/api/telemetry", {
      body: JSON.stringify(body),
      headers: { "Content-Type": "application/json" },
      method: "POST"
    }).catch(() => {
      return;
    });
  } catch {}
};
var init_telemetryEvent = __esm(() => {
  init_telemetry();
});

// src/utils/loadConfig.ts
import { resolve } from "path";
var loadConfig = async (configPath2) => {
  const resolved = resolve(configPath2 ?? process.env.ABSOLUTE_CONFIG ?? "absolute.config.ts");
  const mod = await import(resolved);
  const config = mod.default ?? mod.config;
  if (!config) {
    throw new Error(`Config file "${resolved}" does not export a valid configuration.
Expected: export default defineConfig({ ... })`);
  }
  return config;
};
var init_loadConfig = () => {};

// src/cli/utils.ts
var {$ } = globalThis.Bun;
import { execSync } from "child_process";
import { existsSync as existsSync3, readFileSync as readFileSync3 } from "fs";
import { resolve as resolve2 } from "path";
var COMPOSE_PATH = "db/docker-compose.db.yml", DEFAULT_SERVER_ENTRY = "src/backend/server.ts", isWSLEnvironment = () => {
  try {
    const release = readFileSync3("/proc/version", "utf-8");
    return /microsoft|wsl/i.test(release);
  } catch {
    return false;
  }
}, safeKill = (pid) => {
  try {
    process.kill(pid, "SIGTERM");
  } catch {}
}, killStaleProcesses = (port) => {
  let output;
  try {
    output = execSync(`lsof -ti tcp:${port} -sTCP:LISTEN 2>/dev/null`, {
      encoding: "utf-8"
    }).trim();
  } catch {
    return;
  }
  if (!output) {
    return;
  }
  const pids = output.split(`
`).map(Number).filter((pid) => pid !== process.pid && pid > 0);
  if (pids.length === 0) {
    return;
  }
  pids.forEach(safeKill);
  console.log(`\x1B[2m${formatTimestamp()}\x1B[0m \x1B[33m[cli]\x1B[0m \x1B[33mKilled ${pids.length} stale ${pids.length === 1 ? "process" : "processes"} on port ${port}.\x1B[0m`);
}, printHelp = () => {
  console.log("");
  console.log("\x1B[1mShortcuts:\x1B[0m");
  console.log("  \x1B[36mr\x1B[0m / restart  \u2014 Restart server");
  console.log("  \x1B[36mp\x1B[0m / pause    \u2014 Pause/resume server");
  console.log("  \x1B[36mo\x1B[0m / open     \u2014 Open in browser");
  console.log("  \x1B[36mc\x1B[0m / clear    \u2014 Clear terminal");
  console.log("  \x1B[36mq\x1B[0m / quit     \u2014 Graceful shutdown");
  console.log("  \x1B[36mh\x1B[0m / help     \u2014 Show this help");
  console.log("  \x1B[36m$\x1B[0m            \u2014 Run a shell command");
  console.log("  \x1B[36m\u2191\x1B[0m / \x1B[36m\u2193\x1B[0m        \u2014 Command history");
  console.log("");
}, printHint = () => {
  console.log("\x1B[90mpress h + enter to show shortcuts\x1B[0m");
}, readDbScripts = async () => {
  const pkgPath = resolve2("package.json");
  if (!existsSync3(pkgPath))
    return null;
  const pkg = await Bun.file(pkgPath).json();
  const upCommand = pkg.scripts?.["db:up"];
  const downCommand = pkg.scripts?.["db:down"];
  if (!upCommand || !downCommand)
    return null;
  return { downCommand, upCommand };
}, startDatabase = async (scripts) => {
  await timed("Starting database container...", async () => {
    const { exitCode } = await $`${{ raw: scripts.upCommand }}`.quiet().nothrow();
    if (exitCode !== 0)
      process.exit(exitCode);
  });
}, stopDatabase = async (scripts) => {
  console.log(`
Stopping database container...`);
  await $`${{ raw: scripts.downCommand }}`.quiet().nothrow();
}, timed = async (label, task) => {
  process.stdout.write(label);
  const start = performance.now();
  await task();
  const duration = ((performance.now() - start) / MILLISECONDS_IN_A_SECOND).toFixed(2);
  process.stdout.write(` \x1B[90m${duration}s\x1B[0m
`);
};
var init_utils = __esm(() => {
  init_constants();
  init_startupBanner();
});

// src/dev/devCert.ts
var exports_devCert = {};
__export(exports_devCert, {
  setupMkcert: () => setupMkcert,
  loadDevCert: () => loadDevCert,
  hasMkcert: () => hasMkcert,
  hasCert: () => hasCert,
  ensureDevCert: () => ensureDevCert
});
import { existsSync as existsSync4, mkdirSync as mkdirSync2, readFileSync as readFileSync4, rmSync } from "fs";
import { platform as platform2 } from "os";
import { join as join3 } from "path";
var CERT_DIR, CERT_PATH, KEY_PATH, CERT_VALIDITY_DAYS = 365, devLog = (msg) => console.log(`\x1B[2m${new Date().toLocaleTimeString()}\x1B[0m \x1B[36m[dev]\x1B[0m ${msg}`), devWarn = (msg) => console.log(`\x1B[2m${new Date().toLocaleTimeString()}\x1B[0m \x1B[33m[dev]\x1B[0m \x1B[33m${msg}\x1B[0m`), certFilesExist = () => existsSync4(CERT_PATH) && existsSync4(KEY_PATH), isCertExpired = () => {
  try {
    const certPem = readFileSync4(CERT_PATH, "utf-8");
    const proc = Bun.spawnSync(["openssl", "x509", "-enddate", "-noout"], {
      stdin: new TextEncoder().encode(certPem)
    });
    const output = new TextDecoder().decode(proc.stdout).trim();
    const dateStr = output.replace("notAfter=", "");
    const expiryDate = new Date(dateStr);
    return expiryDate.getTime() < Date.now();
  } catch {
    return true;
  }
}, hasMkcert = () => {
  try {
    const result = Bun.spawnSync(["mkcert", "-version"], {
      stderr: "pipe",
      stdout: "pipe"
    });
    return result.exitCode === 0;
  } catch {
    return false;
  }
}, generateWithMkcert = () => {
  const result = Bun.spawnSync([
    "mkcert",
    "-cert-file",
    CERT_PATH,
    "-key-file",
    KEY_PATH,
    "localhost",
    "127.0.0.1",
    "::1"
  ], { stderr: "pipe", stdout: "pipe" });
  if (result.exitCode !== 0) {
    const err = new TextDecoder().decode(result.stderr);
    throw new Error(`mkcert failed: ${err}`);
  }
}, generateSelfSigned = () => {
  const proc = Bun.spawnSync([
    "openssl",
    "req",
    "-x509",
    "-newkey",
    "ec",
    "-pkeyopt",
    "ec_paramgen_curve:prime256v1",
    "-days",
    String(CERT_VALIDITY_DAYS),
    "-nodes",
    "-keyout",
    KEY_PATH,
    "-out",
    CERT_PATH,
    "-subj",
    "/CN=localhost",
    "-addext",
    "subjectAltName=DNS:localhost,IP:127.0.0.1,IP:::1"
  ], { stderr: "pipe", stdout: "pipe" });
  if (proc.exitCode !== 0) {
    const err = new TextDecoder().decode(proc.stderr);
    throw new Error(`openssl failed: ${err}`);
  }
  devLog("Using self-signed certificate \u2014 browser will show a one-time warning");
}, generateCert = () => {
  if (hasMkcert()) {
    generateWithMkcert();
  } else {
    generateSelfSigned();
  }
}, ensureDevCert = () => {
  mkdirSync2(CERT_DIR, { recursive: true });
  if (hasCert()) {
    return { cert: CERT_PATH, key: KEY_PATH };
  }
  if (certFilesExist()) {
    devLog("Certificate expired, regenerating...");
  }
  try {
    generateCert();
  } catch (err) {
    devWarn(`Failed to generate certificate: ${err instanceof Error ? err.message : err}`);
    return null;
  }
  return { cert: CERT_PATH, key: KEY_PATH };
}, hasCert = () => certFilesExist() && !isCertExpired(), loadDevCert = () => {
  const paths = ensureDevCert();
  if (!paths)
    return null;
  try {
    return {
      cert: readFileSync4(paths.cert, "utf-8"),
      key: readFileSync4(paths.key, "utf-8")
    };
  } catch {
    return null;
  }
}, commandExists = (cmd) => {
  try {
    const check = platform2() === "win32" ? ["where", cmd] : ["which", cmd];
    const result = Bun.spawnSync(check, {
      stderr: "pipe",
      stdout: "pipe"
    });
    return result.exitCode === 0;
  } catch {
    return false;
  }
}, installMkcertDarwin = () => {
  if (!commandExists("brew")) {
    devWarn("Install Homebrew first: https://brew.sh");
    return false;
  }
  devLog("Installing mkcert with Homebrew...");
  const result = Bun.spawnSync(["brew", "install", "mkcert"], {
    stderr: "pipe",
    stdout: "pipe"
  });
  return result.exitCode === 0;
}, installMkcertLinux = () => {
  const sudoOpts = {
    stderr: "inherit",
    stdin: "inherit",
    stdout: "pipe"
  };
  if (commandExists("apt-get")) {
    devLog("Installing mkcert (may prompt for password)...");
    const result = Bun.spawnSync(["sudo", "apt-get", "install", "-y", "mkcert", "libnss3-tools"], sudoOpts);
    if (result.exitCode === 0)
      return true;
  }
  if (commandExists("dnf")) {
    devLog("Installing mkcert (may prompt for password)...");
    const result = Bun.spawnSync(["sudo", "dnf", "install", "-y", "mkcert"], sudoOpts);
    if (result.exitCode === 0)
      return true;
  }
  if (commandExists("pacman")) {
    devLog("Installing mkcert (may prompt for password)...");
    const result = Bun.spawnSync(["sudo", "pacman", "-S", "--noconfirm", "mkcert"], sudoOpts);
    if (result.exitCode === 0)
      return true;
  }
  devWarn("Could not install mkcert automatically.");
  console.log("  See: https://github.com/FiloSottile/mkcert#installation");
  return false;
}, installMkcertWin32 = () => {
  if (commandExists("choco")) {
    devLog("Installing mkcert with Chocolatey...");
    const result = Bun.spawnSync(["choco", "install", "-y", "mkcert"], {
      stderr: "pipe",
      stdout: "pipe"
    });
    if (result.exitCode === 0)
      return true;
  }
  if (commandExists("winget")) {
    devLog("Installing mkcert with winget...");
    const result = Bun.spawnSync(["winget", "install", "--id", "FiloSottile.mkcert", "-e"], { stderr: "pipe", stdout: "pipe" });
    if (result.exitCode === 0)
      return true;
  }
  devWarn("Could not install mkcert automatically.");
  console.log("  See: https://github.com/FiloSottile/mkcert#installation");
  return false;
}, installMkcert = () => {
  const osPlatform = platform2();
  if (osPlatform === "darwin")
    return installMkcertDarwin();
  if (osPlatform === "linux")
    return installMkcertLinux();
  if (osPlatform === "win32")
    return installMkcertWin32();
  return false;
}, ensureMkcert = () => {
  if (hasMkcert())
    return true;
  if (!installMkcert())
    return false;
  if (!hasMkcert()) {
    devWarn("mkcert installed but not found in PATH. Restart your terminal and try again.");
    return false;
  }
  return true;
}, setupMkcert = () => {
  if (!ensureMkcert())
    return false;
  const installResult = Bun.spawnSync(["mkcert", "-install"], {
    stderr: "pipe",
    stdin: "inherit",
    stdout: "pipe"
  });
  if (installResult.exitCode !== 0) {
    devWarn("Failed to install local CA");
    return false;
  }
  rmSync(CERT_PATH, { force: true });
  rmSync(KEY_PATH, { force: true });
  mkdirSync2(CERT_DIR, { recursive: true });
  generateWithMkcert();
  console.log("");
  devLog("mkcert installed \u2014 HTTPS certificates are now locally trusted");
  return true;
};
var init_devCert = __esm(() => {
  CERT_DIR = join3(process.cwd(), ".absolutejs");
  CERT_PATH = join3(CERT_DIR, "cert.pem");
  KEY_PATH = join3(CERT_DIR, "key.pem");
});

// src/core/prerender.ts
var exports_prerender = {};
__export(exports_prerender, {
  routeToFilename: () => routeToFilename,
  rerenderRoute: () => rerenderRoute,
  readTimestamp: () => readTimestamp,
  prerenderWithServer: () => prerenderWithServer,
  prerender: () => prerender,
  PRERENDER_BYPASS_HEADER: () => PRERENDER_BYPASS_HEADER
});
import { mkdirSync as mkdirSync3, readFileSync as readFileSync6 } from "fs";
import { join as join5 } from "path";
var MAX_STARTUP_ATTEMPTS = 50, STARTUP_POLL_INTERVAL_MS = 100, PRERENDER_BYPASS_HEADER = "X-Absolute-Prerender-Bypass", routeToFilename = (route) => route === "/" ? "index.html" : `${route.slice(1).replace(/\//g, "-")}.html`, writeTimestamp = async (htmlPath) => {
  const metaPath = htmlPath.replace(/\.html$/, ".meta");
  await Bun.write(metaPath, String(Date.now()));
}, readTimestamp = (htmlPath) => {
  const metaPath = htmlPath.replace(/\.html$/, ".meta");
  try {
    const content = readFileSync6(metaPath, "utf-8");
    return Number(content) || 0;
  } catch {
    return 0;
  }
}, extractLinks = (html, visited) => {
  const links = [];
  const linkRegex = /href=["'](\/[^"']*?)["']/g;
  let match;
  while ((match = linkRegex.exec(html)) !== null) {
    const href = match[1] ?? "";
    if (!href || href.includes(".") || href.includes("#") || visited.has(href))
      continue;
    links.push(href);
  }
  return links;
}, fetchRoute = async (baseUrl, path) => {
  const res = await fetch(`${baseUrl}${path}`);
  if (!res.ok)
    return null;
  const contentType = res.headers.get("content-type") ?? "";
  if (!contentType.includes("text/html"))
    return null;
  return res.text();
}, crawlRoutes = async (baseUrl) => {
  const visited = new Set;
  const queue = ["/"];
  const routes = [];
  while (queue.length > 0) {
    const path = queue.shift();
    if (!path || visited.has(path))
      continue;
    visited.add(path);
    const html = await fetchRoute(baseUrl, path).catch(() => null);
    if (!html)
      continue;
    routes.push(path);
    queue.push(...extractLinks(html, visited));
  }
  return routes;
}, rerenderRoute = async (route, port, prerenderDir) => {
  try {
    const res = await fetch(`http://localhost:${port}${route}`, {
      headers: { [PRERENDER_BYPASS_HEADER]: "1" }
    });
    if (!res.ok)
      return false;
    const html = await res.text();
    const fileName = routeToFilename(route);
    const filePath = join5(prerenderDir, fileName);
    await Bun.write(filePath, html);
    await writeTimestamp(filePath);
    return true;
  } catch {
    return false;
  }
}, prerenderRoute = async (baseUrl, route, prerenderDir, result, log) => {
  const res = await fetch(`${baseUrl}${route}`).catch(() => null);
  if (!res) {
    log?.(`  Failed to pre-render ${route}`);
    return;
  }
  if (!res.ok) {
    log?.(`  Skipped ${route} (HTTP ${res.status})`);
    return;
  }
  const html = await res.text();
  const fileName = routeToFilename(route);
  const filePath = join5(prerenderDir, fileName);
  await Bun.write(filePath, html);
  await writeTimestamp(filePath);
  result.routes.set(route, filePath);
  log?.(`  Pre-rendered ${route} \u2192 ${fileName} (${html.length} bytes)`);
}, prerender = async (port, outDir, staticConfig, log) => {
  const prerenderDir = join5(outDir, "_prerendered");
  mkdirSync3(prerenderDir, { recursive: true });
  const baseUrl = `http://localhost:${port}`;
  let routes;
  if (staticConfig.routes === "all") {
    log?.("Crawling routes...");
    routes = await crawlRoutes(baseUrl);
  } else {
    ({ routes } = staticConfig);
  }
  const result = {
    dir: prerenderDir,
    routes: new Map
  };
  for (const route of routes) {
    await prerenderRoute(baseUrl, route, prerenderDir, result, log);
  }
  return result;
}, waitForServerReady = async (port) => {
  for (let attempt = 0;attempt < MAX_STARTUP_ATTEMPTS; attempt++) {
    const res = await fetch(`http://localhost:${port}/`).catch(() => null);
    if (res?.ok)
      return true;
    await Bun.sleep(STARTUP_POLL_INTERVAL_MS);
  }
  return false;
}, prerenderWithServer = async (serverBundlePath, port, outDir, staticConfig, env2, log) => {
  const serverProcess = Bun.spawn(["bun", "run", serverBundlePath], {
    cwd: process.cwd(),
    env: { ...process.env, ...env2, PORT: String(port) },
    stderr: "pipe",
    stdout: "pipe"
  });
  const ready = await waitForServerReady(port);
  if (!ready) {
    serverProcess.kill();
    throw new Error("Server failed to start for pre-rendering");
  }
  const result = await prerender(port, outDir, staticConfig, log);
  serverProcess.kill();
  await serverProcess.exited;
  return result;
};
var init_prerender = () => {};

// src/cli/scripts/compile.ts
var exports_compile = {};
__export(exports_compile, {
  compile: () => compile
});
var {env: env3 } = globalThis.Bun;
import { existsSync as existsSync8, readdirSync, readFileSync as readFileSync8, unlinkSync } from "fs";
import { basename as basename2, join as join6, relative, resolve as resolve6 } from "path";
var cliTag3 = (color, message) => `\x1B[2m${formatTimestamp()}\x1B[0m ${color}[cli]\x1B[0m ${color}${message}\x1B[0m`, collectFiles2 = (dir) => {
  const result = [];
  let pending = readdirSync(dir, { withFileTypes: true });
  while (pending.length > 0) {
    const entry = pending.pop();
    if (!entry)
      continue;
    const fullPath = join6(entry.parentPath, entry.name);
    if (entry.isDirectory())
      pending = pending.concat(readdirSync(fullPath, { withFileTypes: true }));
    else
      result.push(fullPath);
  }
  return result;
}, readPackageVersion2 = (candidate) => {
  try {
    const pkg = JSON.parse(readFileSync8(candidate, "utf-8"));
    if (pkg.name !== "@absolutejs/absolute")
      return null;
    const ver = pkg.version;
    return ver;
  } catch {
    return null;
  }
}, resolvePackageVersion2 = (candidates) => {
  for (const candidate of candidates) {
    const version2 = readPackageVersion2(candidate);
    if (version2)
      return version2;
  }
  return "";
}, tryImportBuild2 = async (candidate) => {
  try {
    const mod = await import(candidate);
    const buildFn = mod.build;
    return buildFn;
  } catch {
    return null;
  }
}, resolveBuildModule2 = async (candidates) => {
  for (const candidate of candidates) {
    const mod = await tryImportBuild2(candidate);
    if (mod)
      return mod;
  }
  return;
}, generateEntrypoint = (distDir, serverEntry, prerenderMap, version2) => {
  const allFiles = collectFiles2(distDir);
  const serverBundleName = `${basename2(serverEntry).replace(/\.[^.]+$/, "")}.js`;
  const skip = new Set([
    serverBundleName,
    "manifest.json",
    "_compile_entrypoint.ts"
  ]);
  const clientFiles = allFiles.filter((file) => {
    const rel = relative(distDir, file);
    if (skip.has(rel))
      return false;
    if (rel.includes(".generated"))
      return false;
    if (rel.includes("/server/"))
      return false;
    return true;
  });
  const imports = [];
  const mappings = [];
  clientFiles.forEach((filePath, idx) => {
    const rel = relative(distDir, filePath).replace(/\\/g, "/");
    const varName = `__a${idx}`;
    const urlPath = `/${rel}`;
    imports.push(`import ${varName} from "./${rel}" with { type: "file" };`);
    mappings.push(`	"${urlPath}": ${varName},`);
    const workerParts = rel.startsWith("workers/") && rel.endsWith(".js") ? rel.match(/^(workers\/[^.]+\.worker)\.[a-z0-9]+\.js$/) : null;
    if (workerParts) {
      mappings.push(`	"/${workerParts[1]}.js": ${varName},`);
    }
  });
  const pageVarMap = new Map;
  const prerenderEntries = Array.from(prerenderMap.entries());
  prerenderEntries.forEach(([route, filePath]) => {
    const rel = relative(distDir, filePath).replace(/\\/g, "/");
    const idx = clientFiles.findIndex((file) => relative(distDir, file).replace(/\\/g, "/") === rel);
    if (idx >= 0)
      pageVarMap.set(route, `__a${idx}`);
  });
  const routeEntries = Array.from(pageVarMap.entries()).map(([route, varName]) => `	"${route}": ${varName},`).join(`
`);
  return `// Auto-generated compile entrypoint
import { Elysia } from "elysia";

// \u2500\u2500 Embedded asset imports \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
${imports.join(`
`)}

// \u2500\u2500 Asset URL \u2192 embedded path map \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
const ASSETS: Record<string, string> = {
${mappings.join(`
`)}
};

// \u2500\u2500 Pre-rendered page routes \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
const PAGES: Record<string, string> = {
${routeEntries}
};

// \u2500\u2500 MIME types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
const MIME: Record<string, string> = {
	".js": "application/javascript; charset=utf-8",
	".css": "text/css; charset=utf-8",
	".html": "text/html; charset=utf-8",
	".json": "application/json",
	".png": "image/png",
	".jpg": "image/jpeg",
	".svg": "image/svg+xml",
	".ico": "image/x-icon",
	".woff": "font/woff",
	".woff2": "font/woff2",
	".ttf": "font/ttf",
	".webp": "image/webp",
	".avif": "image/avif",
};

const getMime = (p: string) =>
	MIME[p.substring(p.lastIndexOf("."))] ?? "application/octet-stream";

// \u2500\u2500 Server \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
const port = Number(process.env.PORT) || ${DEFAULT_PORT};

const servePage = (path: string) =>
	new Response(Bun.file(path), {
		headers: { "content-type": "text/html; charset=utf-8" },
	});

const app = new Elysia()
	// Static assets from embedded filesystem
	.onRequest(({ request, set }) => {
		const url = new URL(request.url);

		// Check for pre-rendered page
		const page = PAGES[url.pathname];
		if (page) return servePage(page);

		// Check for embedded asset
		const embedded = ASSETS[url.pathname];
		if (!embedded) return;
		set.headers["content-type"] = getMime(url.pathname);
		set.headers["cache-control"] = "public, max-age=31536000, immutable";
		return new Response(Bun.file(embedded));
	})
	.listen(port);

const assetCount = Object.keys(ASSETS).length;
const pageCount = Object.keys(PAGES).length;
console.log(\`
  \\x1b[36m\\x1b[1mABSOLUTEJS\\x1b[0m \\x1b[2mv${version2}\\x1b[0m  \\x1b[2mcompiled executable\\x1b[0m

  \\x1b[32m\u279C\\x1b[0m  \\x1b[1mLocal:\\x1b[0m   http://localhost:\${port}/

  \\x1b[2m\${pageCount} pre-rendered pages, \${assetCount} embedded assets\\x1b[0m
\`);
`;
}, stubPlugin, FRAMEWORK_EXTERNALS, compile = async (serverEntry, outdir, outfile, configPath2) => {
  const prerenderPort = Number(env3.COMPILE_PORT) || Number(env3.PORT) || DEFAULT_PORT + 1;
  killStaleProcesses(prerenderPort);
  const entryName = basename2(serverEntry).replace(/\.[^.]+$/, "");
  const resolvedOutdir = resolve6(outdir ?? "dist");
  const resolvedOutfile = resolve6(outfile ?? "compiled-server");
  const absoluteVersion = resolvePackageVersion2([
    resolve6(import.meta.dir, "..", "..", "..", "package.json"),
    resolve6(import.meta.dir, "..", "..", "package.json")
  ]);
  const totalStart = performance.now();
  const buildStart = performance.now();
  process.stdout.write(cliTag3("\x1B[36m", "Building assets"));
  const buildConfig = await loadConfig(configPath2);
  buildConfig.buildDirectory = resolvedOutdir;
  buildConfig.mode = "production";
  try {
    const build = await resolveBuildModule2([
      resolve6(import.meta.dir, "..", "..", "core", "build"),
      resolve6(import.meta.dir, "..", "build")
    ]);
    if (!build)
      throw new Error("Could not locate build module");
    await build(buildConfig);
  } catch (err) {
    console.error(cliTag3("\x1B[31m", "Build step failed."));
    console.error(err);
    process.exit(1);
  }
  console.log(` \x1B[2m(${getDurationString(performance.now() - buildStart)})\x1B[0m`);
  const bundleStart = performance.now();
  process.stdout.write(cliTag3("\x1B[36m", "Bundling production server"));
  const serverBundle = await Bun.build({
    define: { "process.env.NODE_ENV": '"production"' },
    entrypoints: [resolve6(serverEntry)],
    external: FRAMEWORK_EXTERNALS,
    outdir: resolvedOutdir,
    plugins: [stubPlugin],
    target: "bun"
  });
  if (!serverBundle.success) {
    serverBundle.logs.forEach((log) => console.error(log));
    console.error(cliTag3("\x1B[31m", "Server bundle failed."));
    process.exit(1);
  }
  const outputPath = resolve6(resolvedOutdir, `${entryName}.js`);
  if (!existsSync8(outputPath)) {
    console.error(cliTag3("\x1B[31m", `Expected output not found: ${outputPath}`));
    process.exit(1);
  }
  console.log(` \x1B[2m(${getDurationString(performance.now() - bundleStart)})\x1B[0m`);
  const prerenderStart = performance.now();
  process.stdout.write(cliTag3("\x1B[36m", "Pre-rendering pages"));
  const staticConfig = buildConfig.static ?? { routes: "all" };
  const prerenderResult = await prerenderWithServer(outputPath, prerenderPort, resolvedOutdir, staticConfig, {
    ABSOLUTE_BUILD_DIR: resolvedOutdir,
    ABSOLUTE_VERSION: absoluteVersion,
    FORCE_COLOR: "0",
    NODE_ENV: "production",
    ...configPath2 ? { ABSOLUTE_CONFIG: configPath2 } : {}
  });
  const prerenderMap = prerenderResult.routes;
  console.log(` \x1B[2m(${prerenderMap.size} pages, ${getDurationString(performance.now() - prerenderStart)})\x1B[0m`);
  const compileStart = performance.now();
  process.stdout.write(cliTag3("\x1B[36m", "Compiling standalone executable"));
  const entrypointCode = generateEntrypoint(resolvedOutdir, serverEntry, prerenderMap, absoluteVersion);
  const entrypointPath = join6(resolvedOutdir, "_compile_entrypoint.ts");
  await Bun.write(entrypointPath, entrypointCode);
  const result = await Bun.build({
    compile: { outfile: resolvedOutfile },
    define: { "process.env.NODE_ENV": '"production"' },
    entrypoints: [entrypointPath],
    target: "bun"
  });
  if (!result.success) {
    result.logs.forEach((log) => console.error(log));
    console.error(cliTag3("\x1B[31m", "Compilation failed."));
    process.exit(1);
  }
  console.log(` \x1B[2m(${getDurationString(performance.now() - compileStart)})\x1B[0m`);
  try {
    unlinkSync(entrypointPath);
  } catch {}
  const BYTES_PER_MB = 1048576;
  const size = (Bun.file(resolvedOutfile).size / BYTES_PER_MB).toFixed(0);
  const totalDuration = getDurationString(performance.now() - totalStart);
  console.log(cliTag3("\x1B[32m", `Compiled to ${resolvedOutfile} (${size}MB) in ${totalDuration}`));
  console.log(cliTag3("\x1B[2m", `Run with: ./${basename2(resolvedOutfile)}`));
  sendTelemetryEvent("compile:complete", {
    durationMs: Math.round(performance.now() - totalStart),
    entry: serverEntry,
    pages: prerenderMap.size
  });
};
var init_compile = __esm(() => {
  init_constants();
  init_prerender();
  init_getDurationString();
  init_loadConfig();
  init_startupBanner();
  init_telemetryEvent();
  init_utils();
  stubPlugin = {
    name: "stub-framework-sources",
    setup(bld) {
      bld.onLoad({ filter: /\.(svelte|vue)$/ }, () => ({
        contents: "export default {}",
        loader: "js"
      }));
      bld.onLoad({ filter: /devBuild\.ts$/ }, () => ({
        contents: "export const devBuild = () => {}",
        loader: "js"
      }));
      bld.onLoad({ filter: /core\/build\.ts$/ }, () => ({
        contents: "export const build = () => ({})",
        loader: "js"
      }));
      bld.onLoad({ filter: /src\/build\.ts$/ }, () => ({
        contents: "export const build = () => ({}); export const devBuild = () => {};",
        loader: "js"
      }));
      bld.onLoad({ filter: /plugins\/hmr\.ts$/ }, () => ({
        contents: "export const hmr = () => (app) => app;",
        loader: "js"
      }));
      bld.onLoad({
        filter: /dev\/(assetStore|clientManager|webSocket|moduleVersionTracker|buildHMRClient)\.ts$/
      }, () => ({ contents: "export {};", loader: "js" }));
      bld.onLoad({ filter: /cli\/(telemetryEvent|scripts\/telemetry)\.ts$/ }, () => ({
        contents: "export const sendTelemetryEvent = () => {}; export const getTelemetryConfig = () => null; export const telemetry = () => {};",
        loader: "js"
      }));
      bld.onLoad({
        filter: /react-dom-server-legacy\.browser\.(production|development)\.js$/
      }, () => ({
        contents: "exports.renderToString = undefined; exports.renderToStaticMarkup = undefined;",
        loader: "js"
      }));
      bld.onLoad({ filter: /node_modules\/debug/ }, () => ({
        contents: "module.exports = () => { const noop = () => {}; noop.enabled = false; return noop; }; module.exports.enable = () => {}; module.exports.disable = () => {}; module.exports.enabled = () => false;",
        loader: "js"
      }));
      bld.onLoad({ filter: /\.ts$/ }, async (args) => {
        if (args.path.includes("node_modules"))
          return;
        const text = await Bun.file(args.path).text();
        const stripped = text.replace(/`(?:[^`\\]|\\.)*`/gs, "").replace(/'(?:[^'\\]|\\.)*'/g, "").replace(/"(?:[^"\\]|\\.)*"/g, "");
        if (stripped.includes("@Component")) {
          return { contents: "export default {}", loader: "js" };
        }
        return;
      });
    }
  };
  FRAMEWORK_EXTERNALS = [
    "react",
    "react/*",
    "react-dom",
    "react-dom/*",
    "vue",
    "vue/*",
    "@vue/compiler-sfc",
    "@vue/server-renderer",
    "svelte",
    "svelte/*",
    "@angular/compiler",
    "@angular/compiler-cli",
    "@angular/core",
    "@angular/common",
    "@angular/platform-browser",
    "@angular/platform-server"
  ];
});

// src/cli/scripts/typecheck.ts
var exports_typecheck = {};
__export(exports_typecheck, {
  typecheck: () => typecheck
});
import { resolve as resolve7, join as join7 } from "path";
import { existsSync as existsSync9 } from "fs";
import { mkdir as mkdir2, writeFile } from "fs/promises";
var run = async (name, command) => {
  const proc = Bun.spawn(command, {
    stderr: "pipe",
    stdout: "pipe"
  });
  const [stdout, stderr] = await Promise.all([
    new Response(proc.stdout).text(),
    new Response(proc.stderr).text()
  ]);
  const exitCode = await proc.exited;
  return { exitCode, name, output: (stdout + stderr).trim() };
}, findBin = (name) => {
  const local = resolve7("node_modules", ".bin", name);
  return existsSync9(local) ? local : null;
}, stripAnsi = (str) => str.replace(/\x1b\[[0-9;]*m/g, ""), formatSvelteOutput = (output) => {
  const cwd = `${process.cwd()}/`;
  const summaryMatch = stripAnsi(output).match(/svelte-check found (\d+) error/);
  const errorCount = summaryMatch ? parseInt(summaryMatch[1] ?? "0", 10) : 0;
  const formatted = output.split(`
`).filter((line) => {
    const plain = stripAnsi(line);
    return !plain.startsWith("Loading svelte-check") && !plain.startsWith("Getting Svelte") && !plain.startsWith("====") && !plain.startsWith("svelte-check found") && !/^\d+ (START|COMPLETED)/.test(plain) && plain.trim() !== "";
  }).flatMap((line) => {
    const result = line.replaceAll(cwd, "");
    const plain = stripAnsi(result);
    const pathMatch = plain.match(/^(\S+\.svelte):(\d+:\d+)$/);
    if (pathMatch) {
      return [
        `\x1B[96m${pathMatch[1]}\x1B[0m:\x1B[93m${pathMatch[2]}\x1B[0m`
      ];
    }
    if (result.includes("\x1B[35m")) {
      const plainLine = stripAnsi(result);
      const before = stripAnsi(result.split("\x1B[35m")[0] ?? "");
      const token = stripAnsi((result.split("\x1B[35m")[1] ?? "").split(/\x1b\[3[69]m/)[0] ?? "");
      if (!token)
        return [result];
      const expanded = before.replace(/\t/g, "        ");
      const expandedLine = plainLine.replace(/\t/g, "        ");
      const underline = "~".repeat(token.length);
      return [
        `\x1B[0m${expandedLine}`,
        `${" ".repeat(expanded.length)}\x1B[91m${underline}\x1B[0m`
      ];
    }
    if (/^\x1b\[36m|\t/.test(result) && !result.includes("Error") && !result.includes("\x1B[35m")) {
      return [];
    }
    return [result];
  }).join(`
`);
  if (errorCount > 0) {
    const suffix = errorCount === 1 ? "" : "s";
    return `${formatted}

Found ${errorCount} error${suffix}.`;
  }
  return formatted;
}, buildVueTscCheck = (cacheDir) => {
  const vueTscBin = findBin("vue-tsc");
  if (!vueTscBin) {
    console.error("\x1B[31m\u2717\x1B[0m vue-tsc is required for Vue type checking. Install it: bun add -d vue-tsc");
    process.exit(1);
  }
  const vueTsconfigPath = join7(cacheDir, "tsconfig.vue-check.json");
  const exclude = [
    "../**/.absolutejs/**/*",
    "../**/build/**/*",
    "../**/dist/**/*",
    "../**/generated/**/*"
  ];
  return writeFile(vueTsconfigPath, JSON.stringify({
    exclude,
    extends: resolve7("tsconfig.json")
  }, null, "\t")).then(() => run("vue-tsc", [
    vueTscBin,
    "--noEmit",
    "--project",
    resolve7(vueTsconfigPath),
    "--incremental",
    "--tsBuildInfoFile",
    join7(cacheDir, "vue-tsc.tsbuildinfo"),
    "--pretty"
  ]));
}, buildTscCheck = (cacheDir) => {
  const tscBin = findBin("tsc");
  if (!tscBin) {
    console.error("\x1B[31m\u2717\x1B[0m typescript is required for type checking. Install it: bun add -d typescript");
    process.exit(1);
  }
  const tscConfigPath = join7(cacheDir, "tsconfig.typecheck.json");
  const exclude = [
    "../**/.absolutejs/**/*",
    "../**/build/**/*",
    "../**/dist/**/*",
    "../**/generated/**/*"
  ];
  return writeFile(tscConfigPath, JSON.stringify({
    exclude,
    extends: resolve7("tsconfig.json")
  }, null, "\t")).then(() => run("tsc", [
    tscBin,
    "--noEmit",
    "--project",
    resolve7(tscConfigPath),
    "--incremental",
    "--tsBuildInfoFile",
    join7(cacheDir, "tsc.tsbuildinfo"),
    "--pretty"
  ]));
}, buildSvelteCheck = async (cacheDir, svelteDir) => {
  const svelteBin = findBin("svelte-check");
  if (!svelteBin) {
    console.error("\x1B[31m\u2717\x1B[0m svelte-check is required for Svelte type checking. Install it: bun add -d svelte-check");
    process.exit(1);
  }
  const svelteTsconfigPath = join7(cacheDir, "tsconfig.svelte-check.json");
  await writeFile(svelteTsconfigPath, JSON.stringify({
    extends: resolve7("tsconfig.json"),
    include: [`../${svelteDir}/**/*`]
  }, null, "\t"));
  return run("svelte-check", [
    svelteBin,
    "--tsconfig",
    resolve7(svelteTsconfigPath),
    "--threshold",
    "error",
    "--compiler-warnings",
    "css-unused-selector:ignore",
    "--output",
    "human-verbose",
    "--color"
  ]);
}, typecheck = async (configPath2) => {
  const config = await loadConfig(configPath2);
  const hasSvelte = Boolean(config.svelteDirectory);
  const hasVue = Boolean(config.vueDirectory);
  const cacheDir = ".absolutejs";
  await mkdir2(cacheDir, { recursive: true });
  const checks = [];
  checks.push(hasVue ? buildVueTscCheck(cacheDir) : buildTscCheck(cacheDir));
  if (hasSvelte) {
    checks.push(buildSvelteCheck(cacheDir, config.svelteDirectory ?? ""));
  }
  const results = await Promise.all(checks);
  const failed = results.filter((res) => res.exitCode !== 0);
  if (failed.length === 0) {
    console.log("\x1B[32m\u2713\x1B[0m Typecheck passed");
    return;
  }
  for (const result of failed) {
    console.error(`
\x1B[31m[${result.name}]\x1B[0m`);
    const output = result.name === "svelte-check" ? formatSvelteOutput(result.output) : result.output;
    console.error(output);
  }
  console.error(`
\x1B[31m\u2717\x1B[0m Typecheck failed: ${failed.map((res) => res.name).join(", ")}`);
  process.exit(1);
};
var init_typecheck = __esm(() => {
  init_loadConfig();
});

// src/cli/scripts/dev.ts
init_constants();
init_startupBanner();
var {$: $2, env } = globalThis.Bun;
import { existsSync as existsSync5 } from "fs";
import { resolve as resolve3 } from "path";

// src/cli/interactive.ts
init_constants();
import { openSync } from "fs";
import { ReadStream } from "tty";
var SHORTCUTS = {
  c: "clear",
  h: "help",
  o: "open",
  p: "pause",
  q: "quit",
  r: "restart"
};
var WORD_COMMANDS = {
  clear: "clear",
  help: "help",
  open: "open",
  pause: "pause",
  quit: "quit",
  restart: "restart",
  resume: "pause"
};
var trySetRawMode = () => {
  if (typeof process.stdin.setRawMode !== "function") {
    return null;
  }
  try {
    process.stdin.setRawMode(true);
  } catch {
    return null;
  }
  return process.stdin;
};
var openTtyStream = () => {
  const fromStdin = trySetRawMode();
  if (fromStdin) {
    return fromStdin;
  }
  try {
    const ttyStream = new ReadStream(openSync("/dev/tty", "r"));
    ttyStream.setRawMode(true);
    return ttyStream;
  } catch {
    return null;
  }
};
var runShellCommand = async (actions, cmd) => {
  try {
    await actions.shell(cmd);
  } catch {}
};
var handleActionResult = (action, renderLine, setNeedsPrompt) => {
  if (action === "restart") {
    setNeedsPrompt(true);
    return;
  }
  renderLine("");
};
var createInteractiveHandler = (actions) => {
  let buffer = "";
  let shellMode = false;
  let needsPrompt = true;
  let escapeSeq = "";
  const history = [];
  let historyIndex = UNFOUND_INDEX;
  const setNeedsPrompt = (value) => {
    needsPrompt = value;
  };
  const renderLine = (value) => {
    const prefix = shellMode ? "\x1B[33m$ \x1B[0m" : "\x1B[90m> \x1B[0m";
    process.stdout.write(`\r\x1B[2K${prefix}${value}`);
    buffer = value;
    needsPrompt = false;
  };
  const handleLine = async (line) => {
    const trimmed = line.trim();
    if (trimmed === "") {
      renderLine("");
      return;
    }
    if (trimmed === "$") {
      shellMode = true;
      renderLine("");
      return;
    }
    if (trimmed.startsWith("$")) {
      const cmd = trimmed.slice(1).trim();
      if (cmd.length === 0) {
        return;
      }
      await runShellCommand(actions, cmd);
      renderLine("");
      return;
    }
    const wordAction = WORD_COMMANDS[trimmed.toLowerCase()];
    if (wordAction) {
      await actions[wordAction]();
      handleActionResult(wordAction, renderLine, setNeedsPrompt);
      return;
    }
    if (trimmed.length !== 1) {
      console.log(`\x1B[31mUnknown command: ${trimmed}\x1B[0m (press h + enter for help)`);
      renderLine("");
      return;
    }
    const shortcutAction = SHORTCUTS[trimmed];
    if (!shortcutAction) {
      console.log(`\x1B[31mUnknown command: ${trimmed}\x1B[0m (press h + enter for help)`);
      renderLine("");
      return;
    }
    await actions[shortcutAction]();
    handleActionResult(shortcutAction, renderLine, setNeedsPrompt);
  };
  const handleShellLine = async (line) => {
    const trimmed = line.trim();
    if (trimmed === "") {
      shellMode = false;
      renderLine("");
      return;
    }
    try {
      await actions.shell(trimmed);
    } catch {}
    shellMode = false;
    renderLine("");
  };
  const navigateHistoryUp = () => {
    if (history.length === 0) {
      return;
    }
    if (historyIndex < history.length - 1) {
      historyIndex++;
    }
    const entry = history[history.length - 1 - historyIndex];
    if (entry)
      renderLine(entry);
  };
  const navigateHistoryDown = () => {
    if (historyIndex <= 0) {
      historyIndex = UNFOUND_INDEX;
      renderLine("");
      return;
    }
    historyIndex--;
    const entry = history[history.length - 1 - historyIndex];
    if (entry)
      renderLine(entry);
  };
  const handleArrow = (arrow) => {
    if (arrow === "A")
      navigateHistoryUp();
    if (arrow === "B")
      navigateHistoryDown();
  };
  const handleCtrlC = () => {
    const wasShellMode = shellMode;
    shellMode = false;
    buffer = "";
    historyIndex = UNFOUND_INDEX;
    process.stdout.write(`
`);
    if (wasShellMode) {
      needsPrompt = true;
      return;
    }
    actions.quit();
  };
  const handleEnter = () => {
    process.stdout.write(`
`);
    const line = buffer;
    buffer = "";
    historyIndex = UNFOUND_INDEX;
    if (line.trim().length > 0)
      history.push(line);
    if (shellMode)
      handleShellLine(line);
    else
      handleLine(line);
  };
  const handleChar = (char) => {
    if (char === "\x03") {
      handleCtrlC();
      return;
    }
    if (char === "\x7F" || char === "\b") {
      if (buffer.length > 0)
        renderLine(buffer.slice(0, UNFOUND_INDEX));
      return;
    }
    if (char === "\r" || char === `
`) {
      handleEnter();
      return;
    }
    if (char.charCodeAt(0) < ASCII_SPACE) {
      return;
    }
    if (needsPrompt) {
      process.stdout.write(`
`);
    }
    renderLine(buffer + char);
  };
  const processEscapeChar = (char) => {
    escapeSeq += char;
    if (escapeSeq.length === 2 && char !== "[") {
      escapeSeq = "";
      return;
    }
    if (escapeSeq.length === ANSI_ESCAPE_LENGTH) {
      handleArrow(char);
      escapeSeq = "";
    }
  };
  const processChar = (char) => {
    if (escapeSeq.length > 0) {
      processEscapeChar(char);
      return;
    }
    if (char === "\x1B") {
      escapeSeq = "\x1B";
      return;
    }
    handleChar(char);
  };
  const onData = (data) => {
    const str = data.toString();
    for (let idx = 0;idx < str.length; idx++) {
      processChar(str.charAt(idx));
    }
  };
  const ttyStream = openTtyStream();
  const input = ttyStream ?? process.stdin;
  input.resume();
  input.on("data", onData);
  const disposeTtyStream = () => {
    if (!ttyStream) {
      return;
    }
    try {
      ttyStream.setRawMode(false);
    } catch {}
    if (ttyStream !== process.stdin) {
      ttyStream.destroy();
    }
  };
  const dispose = () => {
    input.removeListener("data", onData);
    disposeTtyStream();
    process.stdin.pause();
  };
  const clearPrompt = () => {
    process.stdout.write("\r\x1B[2K");
  };
  const showPrompt = () => {
    renderLine(buffer);
  };
  return { clearPrompt, dispose, showPrompt };
};

// src/cli/scripts/dev.ts
init_telemetryEvent();
init_loadConfig();
init_utils();
var cliTag = (color, message) => `\x1B[2m${formatTimestamp()}\x1B[0m ${color}[cli]\x1B[0m ${color}${message}\x1B[0m`;
var confirmPrompt = (message, defaultYes = true) => new Promise((_resolve) => {
  let selected = defaultYes;
  const render = () => {
    const yes = selected ? "\x1B[36m\u25CF\x1B[0m Yes" : "\x1B[2m\u25CB Yes\x1B[0m";
    const noLabel = !selected ? "\x1B[36m\u25CF\x1B[0m No" : "\x1B[2m\u25CB No\x1B[0m";
    process.stdout.write(`\x1B[2K\x1B[36m\u25C6\x1B[0m ${message}
\x1B[2K  ${yes}  ${noLabel}\x1B[A\r`);
  };
  process.stdout.write("\x1B[?25l");
  process.stdin.setRawMode(true);
  process.stdin.resume();
  render();
  const onData = (data) => {
    const key = data.toString();
    if (key === "\x1B[D" || key === "\x1B[C" || key === "\t") {
      selected = !selected;
      render();
    } else if (key === "\r" || key === `
`) {
      process.stdin.setRawMode(false);
      process.stdin.pause();
      process.stdin.removeListener("data", onData);
      const label = selected ? "Yes" : "No";
      process.stdout.write(`\x1B[2K\x1B[32m\u25C7\x1B[0m ${message}
\x1B[2K  \x1B[2m${label}\x1B[0m
\x1B[?25h`);
      _resolve(selected);
    } else if (key === "\x03") {
      process.stdout.write("\x1B[?25h");
      process.stdin.setRawMode(false);
      process.exit(0);
    }
  };
  process.stdin.on("data", onData);
});
var setupCertWithPrompt = async (ensureDevCert2, setupMkcert2) => {
  const install = await confirmPrompt("Install mkcert for trusted HTTPS? (no browser warning)");
  if (install) {
    setupMkcert2();
  } else {
    ensureDevCert2();
  }
};
var setupHttpsCert = async () => {
  const { hasCert: hasCert2, hasMkcert: hasMkcert2, ensureDevCert: ensureDevCert2, setupMkcert: setupMkcert2 } = await Promise.resolve().then(() => (init_devCert(), exports_devCert));
  if (hasCert2()) {
    ensureDevCert2();
    return;
  }
  if (hasMkcert2()) {
    ensureDevCert2();
    return;
  }
  await setupCertWithPrompt(ensureDevCert2, setupMkcert2);
};
var dev = async (serverEntry, configPath2) => {
  const port = Number(env.PORT) || DEFAULT_PORT;
  killStaleProcesses(port);
  let httpsEnabled = false;
  try {
    const config = await loadConfig(configPath2);
    httpsEnabled = config?.dev?.https === true;
    if (httpsEnabled)
      await setupHttpsCert();
  } catch {}
  const usesDocker = existsSync5(resolve3(COMPOSE_PATH));
  const scripts = usesDocker ? await readDbScripts() : null;
  if (scripts)
    await startDatabase(scripts);
  let paused = false;
  let cleaning = false;
  let interactive = null;
  let serverReady = false;
  const checkServerReady = (value) => {
    const chunk = Buffer.from(value).toString();
    if (!chunk.includes("Local:"))
      return;
    serverReady = true;
    interactive?.showPrompt();
  };
  const handleChunk = (value) => {
    if (!serverReady) {
      checkServerReady(value);
      return;
    }
    interactive?.showPrompt();
  };
  const spawnServer = () => {
    const proc = Bun.spawn(["bun", "--hot", "--no-clear-screen", serverEntry], {
      cwd: process.cwd(),
      env: {
        ...process.env,
        FORCE_COLOR: "1",
        NODE_ENV: "development",
        ...configPath2 ? { ABSOLUTE_CONFIG: configPath2 } : {},
        ...httpsEnabled ? { ABSOLUTE_HTTPS: "true" } : {}
      },
      stderr: "pipe",
      stdin: "ignore",
      stdout: "pipe"
    });
    const forward = (stream, dest) => {
      const reader = stream.getReader();
      const pump = () => {
        reader.read().then(({ done, value }) => {
          if (done)
            return;
          if (serverReady)
            interactive?.clearPrompt();
          dest.write(value);
          handleChunk(value);
          pump();
          return;
        }).catch(() => {});
      };
      pump();
    };
    forward(proc.stdout, process.stdout);
    forward(proc.stderr, process.stderr);
    return proc;
  };
  let serverProcess = spawnServer();
  const sessionStart = Date.now();
  let frameworks = [];
  try {
    const cfg = await loadConfig(configPath2);
    frameworks = [
      cfg.reactDirectory && "react",
      cfg.htmlDirectory && "html",
      cfg.htmxDirectory && "htmx",
      cfg.svelteDirectory && "svelte",
      cfg.vueDirectory && "vue",
      cfg.angularDirectory && "angular"
    ].filter((val) => Boolean(val));
  } catch {}
  sendTelemetryEvent("dev:start", { entry: serverEntry, frameworks });
  const cleanup = async (exitCode = 0) => {
    if (cleaning)
      return;
    cleaning = true;
    sendTelemetryEvent("dev:session-duration", {
      duration: Math.round((Date.now() - sessionStart) / MILLISECONDS_IN_A_SECOND),
      entry: serverEntry
    });
    if (interactive)
      interactive.dispose();
    if (paused)
      sendSignal("SIGCONT");
    try {
      serverProcess.kill();
    } catch {}
    await serverProcess.exited;
    if (scripts)
      await stopDatabase(scripts);
    process.exit(exitCode);
  };
  const restartServer = async () => {
    serverReady = false;
    console.log(cliTag("\x1B[36m", "Restarting server..."));
    sendTelemetryEvent("dev:restart", { entry: serverEntry });
    const old = serverProcess;
    if (paused) {
      sendSignal("SIGCONT");
      paused = false;
    }
    try {
      old.kill();
    } catch {}
    serverProcess = spawnServer();
    await old.exited;
    console.log(cliTag("\x1B[32m", "Server restarted."));
  };
  const sendSignalToGroup = (signal) => {
    try {
      process.kill(-serverProcess.pid, signal);
      return true;
    } catch {
      return false;
    }
  };
  const sendSignal = (signal) => {
    if (sendSignalToGroup(signal))
      return;
    try {
      process.kill(serverProcess.pid, signal);
    } catch {}
  };
  const togglePause = () => {
    if (paused) {
      sendSignal("SIGCONT");
      paused = false;
      console.log(cliTag("\x1B[32m", "Server resumed."));
    } else {
      sendSignal("SIGSTOP");
      paused = true;
      console.log(`${cliTag("\x1B[33m", "Server paused.")} \x1B[90m[paused]\x1B[0m`);
    }
  };
  const runShellCommand2 = async (command) => {
    await $2`${{ raw: command }}`.env({ ...process.env, FORCE_COLOR: "1" }).nothrow();
  };
  const openInBrowser = async () => {
    const url = `http://localhost:${port}`;
    const { platform: platform3 } = process;
    const isWSL = platform3 === "linux" && isWSLEnvironment();
    let cmd;
    if (isWSL) {
      cmd = "cmd.exe";
    } else if (platform3 === "darwin") {
      cmd = "open";
    } else if (platform3 === "win32") {
      cmd = "start";
    } else {
      cmd = "xdg-open";
    }
    const args = isWSL ? ["/c", "start", url] : [url];
    try {
      Bun.spawn([cmd, ...args], {
        stderr: "ignore",
        stdout: "ignore"
      });
      console.log(cliTag("\x1B[36m", `Opening ${url}`));
    } catch {
      console.log(cliTag("\x1B[33m", `Could not open browser. Visit ${url}`));
    }
  };
  interactive = createInteractiveHandler({
    shell: runShellCommand2,
    clear: () => {
      process.stdout.write("\x1Bc");
    },
    help: () => {
      printHelp();
    },
    open: () => openInBrowser(),
    pause: () => {
      togglePause();
    },
    quit: () => {
      cleanup(0);
    },
    restart: () => restartServer()
  });
  process.on("SIGINT", () => cleanup(0));
  process.on("SIGTERM", () => cleanup(0));
  printHint();
  const handleServerExit = async (exitCode) => {
    if (exitCode === SIGINT_EXIT_CODE || exitCode === SIGTERM_EXIT_CODE) {
      await cleanup(0);
      return false;
    }
    console.error(cliTag("\x1B[31m", `Server exited (code ${exitCode}), restarting...`));
    sendTelemetryEvent("dev:server-crash", {
      entry: serverEntry,
      exitCode
    });
    serverProcess = spawnServer();
    return true;
  };
  const monitorServer = async () => {
    while (!cleaning) {
      const current = serverProcess;
      const exitCode = await current.exited;
      if (cleaning || serverProcess !== current)
        continue;
      const shouldContinue = await handleServerExit(exitCode);
      if (!shouldContinue)
        return;
    }
  };
  await monitorServer();
};

// src/cli/scripts/eslint.ts
var eslint = async (args) => {
  const command = [
    "bun",
    "eslint",
    "--cache",
    "--cache-location",
    ".absolutejs/eslint-cache",
    ...args,
    "."
  ];
  const proc = Bun.spawn(command, {
    stderr: "inherit",
    stdout: "inherit"
  });
  const exitCode = await proc.exited;
  if (exitCode !== 0)
    process.exit(exitCode);
  console.log("\x1B[32m\u2713\x1B[0m Passed");
};

// src/cli/scripts/info.ts
init_constants();
init_utils();
import { execSync as execSync2 } from "child_process";
import { existsSync as existsSync6, readFileSync as readFileSync5 } from "fs";
import { arch as arch2, cpus, platform as platform3, totalmem, version } from "os";
import { resolve as resolve4 } from "path";
var __dirname = "/home/alexkahn/abs/absolutejs/src/cli/scripts";
var bold = (str) => `\x1B[1m${str}\x1B[0m`;
var getBinaryVersion = (binary, flag = "--version") => {
  try {
    const raw = execSync2(`${binary} ${flag}`, {
      encoding: "utf-8",
      stdio: ["pipe", "pipe", "pipe"],
      timeout: 5000
    }).trim();
    const match = /(\d+\.\d+\.\d+[\w.-]*)/.exec(raw);
    return match !== null ? match[1] ?? raw.replace(/^v/, "") : raw.replace(/^v/, "");
  } catch {
    return "N/A";
  }
};
var getPackageVersion = (packageName) => {
  try {
    const pkgPath = __require.resolve(`${packageName}/package.json`, {
      paths: [process.cwd()]
    });
    const pkg = JSON.parse(readFileSync5(pkgPath, "utf-8"));
    const ver = pkg.version;
    return ver;
  } catch {
    return "N/A";
  }
};
var getAbsoluteVersion = () => {
  try {
    const pkgPath = resolve4(__dirname, "../../../package.json");
    const pkg = JSON.parse(readFileSync5(pkgPath, "utf-8"));
    const ver = pkg.version;
    return ver;
  } catch {
    return getPackageVersion("@absolutejs/absolute");
  }
};
var detectCI = () => {
  const { env: env2 } = process;
  if (env2.GITHUB_ACTIONS)
    return "GitHub Actions";
  if (env2.GITLAB_CI)
    return "GitLab CI";
  if (env2.CIRCLECI)
    return "CircleCI";
  if (env2.JENKINS_URL)
    return "Jenkins";
  if (env2.TRAVIS)
    return "Travis CI";
  if (env2.BUILDKITE)
    return "Buildkite";
  if (env2.CODEBUILD_BUILD_ID)
    return "AWS CodeBuild";
  if (env2.TF_BUILD)
    return "Azure Pipelines";
  if (env2.VERCEL)
    return "Vercel";
  if (env2.NETLIFY)
    return "Netlify";
  if (env2.CI)
    return "Yes (unknown provider)";
  return "No";
};
var isDockerEnvironment = () => {
  try {
    return existsSync6("/.dockerenv");
  } catch {
    return false;
  }
};
var getMemoryMB = () => Math.round(totalmem() / BYTES_PER_KILOBYTE / BYTES_PER_KILOBYTE);
var getGlibcVersion = () => {
  if (platform3() !== "linux")
    return null;
  try {
    const output = execSync2("ldd --version 2>&1 || true", {
      encoding: "utf-8",
      timeout: 5000
    });
    const match = /(\d+\.\d+)/.exec(output);
    return match !== null ? match[1] ?? "N/A" : "N/A";
  } catch {
    return "N/A";
  }
};
var info = () => {
  const lines = [];
  const section = (title) => {
    lines.push(`${bold(title)}`);
  };
  const field = (key, val) => {
    lines.push(`  ${key}: ${val}`);
  };
  section("Operating System:");
  field("Platform", platform3());
  field("Arch", arch2());
  field("Version", version());
  field("Available memory (MB)", String(getMemoryMB()));
  field("Available CPU cores", String(cpus().length));
  const glibc = getGlibcVersion();
  if (glibc)
    field("glibc", glibc);
  lines.push("");
  section("Environment:");
  field("WSL", isWSLEnvironment() ? "Yes" : "No");
  field("Docker", isDockerEnvironment() ? "Yes" : "No");
  field("CI", detectCI());
  lines.push("");
  section("Binaries:");
  field("Bun", getBinaryVersion("bun"));
  field("Node", getBinaryVersion("node"));
  field("npm", getBinaryVersion("npm"));
  field("Yarn", getBinaryVersion("yarn"));
  field("pnpm", getBinaryVersion("pnpm"));
  field("Docker", getBinaryVersion("docker", "--version"));
  field("docker-compose", getBinaryVersion("docker-compose", "--version"));
  lines.push("");
  section("Relevant Packages:");
  field("@absolutejs/absolute", getAbsoluteVersion());
  field("elysia", getPackageVersion("elysia"));
  field("react", getPackageVersion("react"));
  field("react-dom", getPackageVersion("react-dom"));
  field("svelte", getPackageVersion("svelte"));
  field("vue", getPackageVersion("vue"));
  field("typescript", getPackageVersion("typescript"));
  field("tailwindcss", getPackageVersion("tailwindcss"));
  field("@tailwindcss/cli", getPackageVersion("@tailwindcss/cli"));
  lines.push("");
  console.log("");
  console.log(lines.join(`
`));
};

// src/cli/cache.ts
init_constants();
import { mkdir } from "fs/promises";
import { join as join4 } from "path";
var {Glob } = globalThis.Bun;
var CACHE_DIR = ".absolutejs";
var MAX_FILES_PER_BATCH = 200;
var isIgnored = (file, ignorePatterns) => ignorePatterns.some((pat) => new Glob(pat).match(file));
var collectFiles = async (pattern, ignorePatterns) => {
  const files = [];
  const glob = new Glob(pattern);
  for await (const file of glob.scan({
    cwd: ".",
    dot: false
  })) {
    if (!isIgnored(file, ignorePatterns))
      files.push(file);
  }
  return files;
};
var getChangedFiles = async (adapter) => {
  const results = await Promise.all(adapter.fileGlobs.map((pattern) => collectFiles(pattern, adapter.ignorePatterns)));
  const allFiles = results.flat().filter((file) => Boolean(file));
  const [fileHashes, configHash, existing] = await Promise.all([
    hashFiles(allFiles),
    hashConfigs(adapter.configFiles),
    loadCache(adapter.name)
  ]);
  const newCache = { configHash, files: fileHashes };
  if (!existing || existing.configHash !== configHash) {
    return { cache: newCache, changed: allFiles };
  }
  const changed = allFiles.filter((file) => fileHashes[file] !== existing.files[file]);
  return { cache: newCache, changed };
};
var hashConfigs = async (configFiles) => {
  const hashes = await Promise.all(configFiles.map(async (file) => {
    try {
      return await hashFile(file);
    } catch {
      return "missing";
    }
  }));
  return hashes.join(":");
};
var hashFile = async (path) => {
  const buffer = await Bun.file(path).arrayBuffer();
  return Bun.hash(buffer).toString(BASE_36_RADIX);
};
var hashFiles = async (paths) => {
  const entries = await Promise.all(paths.map(async (path) => [path, await hashFile(path)]));
  return Object.fromEntries(entries);
};
var loadCache = async (tool) => {
  try {
    const path = join4(CACHE_DIR, `${tool}.cache.json`);
    const data = await Bun.file(path).json();
    const result = data;
    return result;
  } catch {
    return null;
  }
};
var runBatch = async (adapter, batch, args, failedFiles) => {
  const command = adapter.buildCommand(batch, args);
  const proc = Bun.spawn(command, {
    stderr: "inherit",
    stdout: "inherit"
  });
  const exitCode = await proc.exited;
  if (exitCode !== 0) {
    batch.forEach((file) => failedFiles.add(file));
  }
};
var runTool = async (adapter, args) => {
  const { changed, cache } = await getChangedFiles(adapter);
  const totalFiles = Object.keys(cache.files).length;
  if (changed.length === 0) {
    console.log("\x1B[32m\u2713\x1B[0m All files passed (cached)");
    return;
  }
  console.log(`Checking ${changed.length}/${totalFiles} file(s)...`);
  const batches = [];
  for (let idx = 0;idx < changed.length; idx += MAX_FILES_PER_BATCH) {
    batches.push(changed.slice(idx, idx + MAX_FILES_PER_BATCH));
  }
  const failedFiles = new Set;
  for (const batch of batches) {
    await runBatch(adapter, batch, args, failedFiles);
  }
  for (const file of failedFiles) {
    delete cache.files[file];
  }
  const successFiles = changed.filter((file) => !failedFiles.has(file));
  const updatedHashes = await hashFiles(successFiles);
  Object.assign(cache.files, updatedHashes);
  await saveCache(adapter.name, cache);
  if (failedFiles.size > 0) {
    process.exit(1);
  }
  console.log("\x1B[32m\u2713\x1B[0m Passed");
};
var saveCache = async (tool, data) => {
  await mkdir(CACHE_DIR, { recursive: true });
  const path = join4(CACHE_DIR, `${tool}.cache.json`);
  await Bun.write(path, JSON.stringify(data, null, "\t"));
};

// src/cli/scripts/prettier.ts
var prettierAdapter = {
  configFiles: [".prettierrc.json"],
  fileGlobs: [
    "**/*.ts",
    "**/*.tsx",
    "**/*.js",
    "**/*.mjs",
    "**/*.json",
    "**/*.svelte",
    "**/*.vue",
    "**/*.html",
    "**/*.css"
  ],
  ignorePatterns: [
    "**/node_modules/**",
    "**/dist/**",
    "**/build/**",
    "**/.absolutejs/**",
    "**/*.min.js"
  ],
  name: "prettier",
  buildCommand: (files, args) => ["bun", "prettier", ...args, ...files]
};
var prettier = async (args) => {
  await runTool(prettierAdapter, args);
};

// src/cli/scripts/start.ts
init_constants();
init_getDurationString();
init_loadConfig();
init_startupBanner();
init_telemetryEvent();
init_utils();
var {env: env2 } = globalThis.Bun;
import { existsSync as existsSync7, readFileSync as readFileSync7 } from "fs";
import { basename, resolve as resolve5 } from "path";
var cliTag2 = (color, message) => `\x1B[2m${formatTimestamp()}\x1B[0m ${color}[cli]\x1B[0m ${color}${message}\x1B[0m`;
var resolvePackageVersion = (candidates) => {
  for (const candidate of candidates) {
    const version2 = readPackageVersion(candidate);
    if (version2) {
      return version2;
    }
  }
  return "";
};
var readPackageVersion = (candidate) => {
  try {
    const pkg = JSON.parse(readFileSync7(candidate, "utf-8"));
    if (pkg.name !== "@absolutejs/absolute")
      return null;
    const ver = pkg.version;
    return ver;
  } catch {}
  return null;
};
var resolveBuildModule = async (candidates) => {
  for (const candidate of candidates) {
    const mod = await tryImportBuild(candidate);
    if (mod) {
      return mod;
    }
  }
  return;
};
var tryImportBuild = async (candidate) => {
  try {
    const mod = await import(candidate);
    const buildFn = mod.build;
    return buildFn;
  } catch {
    return null;
  }
};
var handleBundleFailure = (serverBundle, bundleStart, serverEntry) => {
  serverBundle.logs.forEach((log) => {
    console.error(log);
  });
  sendTelemetryEvent("start:bundle-error", {
    durationMs: Math.round(performance.now() - bundleStart),
    entry: serverEntry,
    message: serverBundle.logs.find((log) => log.level === "error")?.message?.toString().slice(0, MAX_ERROR_LENGTH) ?? "Unknown error"
  });
  console.error(cliTag2("\x1B[31m", "Server bundle failed."));
  process.exit(1);
};
var prerenderStaticPages = async (outputPath, prerenderPort, resolvedOutdir, staticConfig, absoluteVersion, configPath2) => {
  const prerenderStart = performance.now();
  process.stdout.write(cliTag2("\x1B[36m", "Pre-rendering static pages"));
  const { prerenderWithServer: prerenderWithServer2 } = await Promise.resolve().then(() => (init_prerender(), exports_prerender));
  try {
    killStaleProcesses(prerenderPort);
    const result = await prerenderWithServer2(outputPath, prerenderPort, resolvedOutdir, staticConfig, {
      ABSOLUTE_BUILD_DIR: resolvedOutdir,
      ABSOLUTE_VERSION: absoluteVersion,
      FORCE_COLOR: "0",
      NODE_ENV: "production",
      ...configPath2 ? { ABSOLUTE_CONFIG: configPath2 } : {}
    });
    const prerenderDuration = getDurationString(performance.now() - prerenderStart);
    console.log(` \x1B[2m(${result.routes.size} pages, ${prerenderDuration})\x1B[0m`);
  } catch (err) {
    console.error(cliTag2("\x1B[33m", "Pre-rendering failed, pages will use SSR."));
    console.error(err);
  }
};
var start = async (serverEntry, outdir, configPath2) => {
  const port = Number(env2.PORT) || DEFAULT_PORT;
  killStaleProcesses(port);
  const entryName = basename(serverEntry).replace(/\.[^.]+$/, "");
  const resolvedOutdir = resolve5(outdir ?? "dist");
  const absoluteVersion = resolvePackageVersion([
    resolve5(import.meta.dir, "..", "..", "..", "package.json"),
    resolve5(import.meta.dir, "..", "..", "package.json")
  ]);
  const buildStepStart = performance.now();
  process.stdout.write(cliTag2("\x1B[36m", `Building assets`));
  const buildConfig = await loadConfig(configPath2);
  buildConfig.buildDirectory = resolvedOutdir;
  buildConfig.mode = "production";
  const frameworks = [
    buildConfig.reactDirectory && "react",
    buildConfig.htmlDirectory && "html",
    buildConfig.htmxDirectory && "htmx",
    buildConfig.svelteDirectory && "svelte",
    buildConfig.vueDirectory && "vue",
    buildConfig.angularDirectory && "angular"
  ].filter((val) => Boolean(val));
  try {
    const build = await resolveBuildModule([
      resolve5(import.meta.dir, "..", "..", "core", "build"),
      resolve5(import.meta.dir, "..", "build")
    ]);
    if (!build)
      throw new Error("Could not locate build module");
    await build(buildConfig);
  } catch (err) {
    console.error(cliTag2("\x1B[31m", "Build step failed."));
    console.error(err);
    process.exit(1);
  }
  const buildStepDuration = getDurationString(performance.now() - buildStepStart);
  console.log(` \x1B[2m(${buildStepDuration})\x1B[0m`);
  const bundleStart = performance.now();
  process.stdout.write(cliTag2("\x1B[36m", `Bundling production server`));
  const stubPlugin = {
    name: "stub-framework-sources",
    setup(bld) {
      bld.onLoad({ filter: /\.(svelte|vue)$/ }, () => ({
        contents: "export default {}",
        loader: "js"
      }));
      bld.onLoad({ filter: /devBuild\.ts$/ }, () => ({
        contents: "export const devBuild = () => {}",
        loader: "js"
      }));
      bld.onLoad({ filter: /core\/build\.ts$/ }, () => ({
        contents: "export const build = () => ({})",
        loader: "js"
      }));
      bld.onLoad({ filter: /src\/build\.ts$/ }, () => ({
        contents: "export const build = () => ({}); export const devBuild = () => {};",
        loader: "js"
      }));
      bld.onLoad({ filter: /plugins\/hmr\.ts$/ }, () => ({
        contents: "export const hmr = () => (app) => app;",
        loader: "js"
      }));
      bld.onLoad({
        filter: /dev\/(assetStore|clientManager|webSocket|moduleVersionTracker|buildHMRClient)\.ts$/
      }, () => ({
        contents: "export {};",
        loader: "js"
      }));
      bld.onLoad({ filter: /cli\/(telemetryEvent|scripts\/telemetry)\.ts$/ }, () => ({
        contents: "export const sendTelemetryEvent = () => {}; export const getTelemetryConfig = () => null; export const telemetry = () => {};",
        loader: "js"
      }));
      bld.onLoad({
        filter: /react-dom-server-legacy\.browser\.(production|development)\.js$/
      }, () => ({
        contents: "exports.renderToString = undefined; exports.renderToStaticMarkup = undefined;",
        loader: "js"
      }));
      bld.onLoad({ filter: /node_modules\/debug/ }, () => ({
        contents: "module.exports = () => { const noop = () => {}; noop.enabled = false; return noop; }; module.exports.enable = () => {}; module.exports.disable = () => {}; module.exports.enabled = () => false;",
        loader: "js"
      }));
      bld.onLoad({ filter: /\.ts$/ }, async (args) => {
        if (args.path.includes("node_modules"))
          return;
        const text = await Bun.file(args.path).text();
        const stripped = text.replace(/`(?:[^`\\]|\\.)*`/gs, "").replace(/'(?:[^'\\]|\\.)*'/g, "").replace(/"(?:[^"\\]|\\.)*"/g, "");
        if (stripped.includes("@Component")) {
          return {
            contents: "export default {}",
            loader: "js"
          };
        }
        return;
      });
    }
  };
  const serverBundle = await Bun.build({
    define: { "process.env.NODE_ENV": '"production"' },
    entrypoints: [resolve5(serverEntry)],
    external: [
      "react",
      "react/*",
      "react-dom",
      "react-dom/*",
      "vue",
      "vue/*",
      "@vue/compiler-sfc",
      "@vue/server-renderer",
      "svelte",
      "svelte/*",
      "@angular/compiler",
      "@angular/compiler-cli",
      "@angular/core",
      "@angular/common",
      "@angular/platform-browser",
      "@angular/platform-server"
    ],
    outdir: resolvedOutdir,
    plugins: [stubPlugin],
    target: "bun"
  });
  if (!serverBundle.success) {
    handleBundleFailure(serverBundle, bundleStart, serverEntry);
  }
  const outputPath = resolve5(resolvedOutdir, `${entryName}.js`);
  if (!existsSync7(outputPath)) {
    console.error(cliTag2("\x1B[31m", `Expected output not found: ${outputPath}`));
    process.exit(1);
  }
  const bundleDurationMs = Math.round(performance.now() - bundleStart);
  const bundleDuration = getDurationString(performance.now() - bundleStart);
  console.log(` \x1B[2m(${bundleDuration})\x1B[0m`);
  sendTelemetryEvent("start:bundle-complete", {
    durationMs: bundleDurationMs,
    entry: serverEntry
  });
  if (buildConfig.static) {
    await prerenderStaticPages(outputPath, port + 1, resolvedOutdir, buildConfig.static, absoluteVersion, configPath2);
  }
  const usesDocker = existsSync7(resolve5(COMPOSE_PATH));
  const scripts = usesDocker ? await readDbScripts() : null;
  if (scripts)
    await startDatabase(scripts);
  let cleaning = false;
  const sessionStart = Date.now();
  const totalDuration = performance.now() - buildStepStart;
  sendTelemetryEvent("start:start", {
    buildDurationMs: Math.round(performance.now() - buildStepStart) - bundleDurationMs,
    bundleDurationMs,
    entry: serverEntry,
    frameworks,
    totalDurationMs: Math.round(totalDuration)
  });
  const serverProcess = Bun.spawn(["bun", "run", outputPath], {
    cwd: process.cwd(),
    env: {
      ...process.env,
      ABSOLUTE_BUILD_DIR: resolvedOutdir,
      ABSOLUTE_BUILD_DURATION: String(Math.round(totalDuration)),
      ABSOLUTE_VERSION: absoluteVersion,
      FORCE_COLOR: "1",
      NODE_ENV: "production",
      ...configPath2 ? { ABSOLUTE_CONFIG: configPath2 } : {}
    },
    stderr: "inherit",
    stdin: "inherit",
    stdout: "inherit"
  });
  const cleanup = async (exitCode2 = 0) => {
    if (cleaning)
      return;
    cleaning = true;
    sendTelemetryEvent("start:session-duration", {
      duration: Math.round((Date.now() - sessionStart) / MILLISECONDS_IN_A_SECOND),
      entry: serverEntry
    });
    try {
      serverProcess.kill();
    } catch {}
    await serverProcess.exited;
    if (scripts)
      await stopDatabase(scripts);
    process.exit(exitCode2);
  };
  process.on("SIGINT", () => cleanup(0));
  process.on("SIGTERM", () => cleanup(0));
  const exitCode = await serverProcess.exited;
  if (cleaning) {
    return;
  }
  console.error(cliTag2("\x1B[31m", `Server exited with code ${exitCode}.`));
  sendTelemetryEvent("start:server-exit", {
    entry: serverEntry,
    exitCode
  });
  if (scripts)
    await stopDatabase(scripts);
  process.exit(exitCode);
};

// src/cli/index.ts
init_telemetry();
init_telemetryEvent();
init_constants();
init_utils();
var [command] = process.argv.slice(2);
var args = process.argv.slice(CLI_ARGS_OFFSET);
var parseNamedArg = (flag) => {
  const idx = args.indexOf(flag);
  if (idx === UNFOUND_INDEX)
    return;
  return args[idx + 1];
};
var stripNamedArgs = (...flags) => args.filter((_, idx) => flags.every((flag) => {
  const flagIdx = args.indexOf(flag);
  if (flagIdx === UNFOUND_INDEX)
    return true;
  return idx !== flagIdx && idx !== flagIdx + 1;
}));
if (command === "dev") {
  sendTelemetryEvent("cli:command", { command });
  const configPath2 = parseNamedArg("--config");
  const positionalArgs = stripNamedArgs("--config");
  const serverEntry = positionalArgs[0] ?? DEFAULT_SERVER_ENTRY;
  await dev(serverEntry, configPath2);
} else if (command === "start") {
  sendTelemetryEvent("cli:command", { command });
  const outdir = parseNamedArg("--outdir");
  const configPath2 = parseNamedArg("--config");
  const positionalArgs = stripNamedArgs("--outdir", "--config");
  const serverEntry = positionalArgs[0] ?? DEFAULT_SERVER_ENTRY;
  await start(serverEntry, outdir, configPath2);
} else if (command === "eslint") {
  sendTelemetryEvent("cli:command", { command });
  await eslint(args);
} else if (command === "prettier") {
  sendTelemetryEvent("cli:command", { command });
  await prettier(args);
} else if (command === "info") {
  sendTelemetryEvent("cli:command", { command });
  info();
} else if (command === "telemetry") {
  sendTelemetryEvent("cli:command", { command });
  telemetry(args);
} else if (command === "compile") {
  sendTelemetryEvent("cli:command", { command });
  const outdir = parseNamedArg("--outdir");
  const outfile = parseNamedArg("--outfile");
  const configPath2 = parseNamedArg("--config");
  const positionalArgs = stripNamedArgs("--outdir", "--outfile", "--config");
  const serverEntry = positionalArgs[0] ?? DEFAULT_SERVER_ENTRY;
  const { compile: compile2 } = await Promise.resolve().then(() => (init_compile(), exports_compile));
  await compile2(serverEntry, outdir, outfile, configPath2);
} else if (command === "typecheck") {
  sendTelemetryEvent("cli:command", { command });
  const configPath2 = parseNamedArg("--config");
  const { typecheck: typecheck2 } = await Promise.resolve().then(() => (init_typecheck(), exports_typecheck));
  await typecheck2(configPath2);
} else if (command === "mkcert") {
  sendTelemetryEvent("cli:command", { command });
  const { setupMkcert: setupMkcert2 } = await Promise.resolve().then(() => (init_devCert(), exports_devCert));
  setupMkcert2();
} else {
  const message = command ? `Unknown command: ${command}` : "No command specified";
  console.error(message);
  console.error("Usage: absolute <command>");
  console.error("Commands:");
  console.error("  dev [entry]   Start development server");
  console.error("  start [entry] [--outdir dir] Start production server");
  console.error("  compile [entry] [--outdir dir] [--outfile path] Compile standalone executable");
  console.error("  eslint        Run ESLint (cached)");
  console.error("  info          Print system info for bug reports");
  console.error("  prettier      Run Prettier check (cached)");
  console.error("  typecheck     Run type checkers for all frameworks");
  console.error("  telemetry     Manage anonymous telemetry");
  process.exit(1);
}
