import "./chunk-AQ2CLRU3.js";

// ../@emulators/resend/dist/index.js
import { AsyncLocalStorage } from "async_hooks";
import { readFileSync } from "fs";
import { fileURLToPath } from "url";
import { dirname, join } from "path";
import { randomUUID } from "crypto";
import { randomBytes } from "crypto";
var tenantContext = new AsyncLocalStorage();
function createErrorHandler(documentationUrl) {
  return async (c, next) => {
    if (documentationUrl) {
      c.set("docsUrl", documentationUrl);
    }
    await next();
  };
}
var errorHandler = createErrorHandler();
var isDebug = typeof process !== "undefined" && (process.env.DEBUG === "1" || process.env.DEBUG === "true" || process.env.EMULATE_DEBUG === "1");
function authLax() {
  const v = process.env.EMULATE_AUTH_LAX;
  return v === "1" || v === "true";
}
function authFlagEnabled(...flags) {
  return flags.some((f) => {
    const v = process.env[f];
    return v === "1" || v === "true";
  });
}
function requireAuthWhen(...flags) {
  return async (c, next) => {
    if (!authLax() && authFlagEnabled(...flags) && !c.get("authUser")) {
      const docsUrl = c.get("docsUrl") ?? "https://github.com/Vinniai/agent-emulate#readme";
      return c.json({ message: "Requires authentication", documentation_url: docsUrl }, 401);
    }
    await next();
  };
}
var __dirname = dirname(fileURLToPath(import.meta.url));
var FONTS = {
  "geist-sans.woff2": readFileSync(join(__dirname, "fonts", "geist-sans.woff2")),
  "GeistPixel-Square.woff2": readFileSync(join(__dirname, "fonts", "GeistPixel-Square.woff2"))
};
var FAVICON = readFileSync(join(__dirname, "fonts", "favicon.ico"));
var DEFAULT_THEME = {
  slug: "default",
  name: "Emulator",
  scheme: "dark",
  bg: "oklch(0.145 0 0)",
  surface: "oklch(0.205 0 0)",
  border: "oklch(1 0 0 / 10%)",
  text: "oklch(0.985 0 0)",
  muted: "oklch(0.708 0 0)",
  accent: "oklch(0.922 0 0)",
  accentText: "oklch(0.205 0 0)",
  font: "'Geist',-apple-system,BlinkMacSystemFont,sans-serif",
  radius: "0.625rem"
};
var THEMES = {
  google: {
    slug: "google",
    name: "Google",
    scheme: "light",
    bg: "#ffffff",
    surface: "#ffffff",
    border: "#dadce0",
    text: "#202124",
    muted: "#5f6368",
    accent: "#1a73e8",
    accentText: "#ffffff",
    font: "'Google Sans',Roboto,Arial,sans-serif",
    radius: "4px"
  },
  microsoft: {
    slug: "microsoft",
    name: "Microsoft",
    scheme: "light",
    bg: "#ffffff",
    surface: "#ffffff",
    border: "#d1d1d1",
    text: "#1b1b1b",
    muted: "#605e5c",
    accent: "#0067b8",
    accentText: "#ffffff",
    font: "'Segoe UI',-apple-system,sans-serif",
    radius: "2px"
  },
  apple: {
    slug: "apple",
    name: "Apple",
    scheme: "light",
    bg: "#ffffff",
    surface: "#ffffff",
    border: "#d2d2d7",
    text: "#1d1d1f",
    muted: "#6e6e73",
    accent: "#0066cc",
    accentText: "#ffffff",
    font: "-apple-system,'SF Pro Text',Helvetica,sans-serif",
    radius: "12px"
  },
  github: {
    slug: "github",
    name: "GitHub",
    scheme: "light",
    bg: "#ffffff",
    surface: "#ffffff",
    border: "#d1d9e0",
    text: "#1f2328",
    muted: "#59636e",
    accent: "#1f883d",
    accentText: "#ffffff",
    font: "-apple-system,'Mona Sans','Segoe UI',Helvetica,sans-serif",
    radius: "6px"
  },
  okta: {
    slug: "okta",
    name: "Okta",
    scheme: "light",
    bg: "#f9f9f9",
    surface: "#ffffff",
    border: "#e1e1e1",
    text: "#1d1d21",
    muted: "#6e6e78",
    accent: "#3f59e4",
    accentText: "#ffffff",
    font: "'Aeonik',-apple-system,sans-serif",
    radius: "4px"
  },
  slack: {
    slug: "slack",
    name: "Slack",
    scheme: "light",
    bg: "#ffffff",
    surface: "#ffffff",
    border: "#dddddd",
    text: "#1d1c1d",
    muted: "#616061",
    accent: "#4a154b",
    accentText: "#ffffff",
    font: "Lato,-apple-system,sans-serif",
    radius: "8px"
  },
  salesforce: {
    slug: "salesforce",
    name: "Salesforce",
    scheme: "light",
    bg: "#f4f6f9",
    surface: "#ffffff",
    border: "#c9c9c9",
    text: "#080707",
    muted: "#54698d",
    accent: "#0070d2",
    accentText: "#ffffff",
    font: "'Salesforce Sans',-apple-system,sans-serif",
    radius: "4px"
  },
  workos: {
    slug: "workos",
    name: "WorkOS",
    scheme: "light",
    bg: "#ffffff",
    surface: "#ffffff",
    border: "#e4e4e7",
    text: "#18181b",
    muted: "#6b7280",
    accent: "#6363f1",
    accentText: "#ffffff",
    font: "'Inter',-apple-system,sans-serif",
    radius: "8px"
  },
  clerk: {
    slug: "clerk",
    name: "Clerk",
    scheme: "light",
    bg: "#ffffff",
    surface: "#ffffff",
    border: "#eeeef0",
    text: "#212126",
    muted: "#747686",
    accent: "#6c47ff",
    accentText: "#ffffff",
    font: "'Inter',-apple-system,sans-serif",
    radius: "8px"
  },
  hubspot: {
    slug: "hubspot",
    name: "HubSpot",
    scheme: "light",
    bg: "#f5f8fa",
    surface: "#ffffff",
    border: "#cbd6e2",
    text: "#33475b",
    muted: "#516f90",
    accent: "#ff7a59",
    accentText: "#ffffff",
    font: "'Lexend Deca',-apple-system,sans-serif",
    radius: "6px"
  },
  stripe: {
    slug: "stripe",
    name: "Stripe",
    scheme: "light",
    bg: "#ffffff",
    surface: "#ffffff",
    border: "#e6e6e6",
    text: "#1a1f36",
    muted: "#697386",
    accent: "#635bff",
    accentText: "#ffffff",
    font: "-apple-system,'Helvetica Neue',sans-serif",
    radius: "8px"
  },
  vercel: {
    slug: "vercel",
    name: "Vercel",
    scheme: "light",
    bg: "#ffffff",
    surface: "#ffffff",
    border: "#eaeaea",
    text: "#171717",
    muted: "#888888",
    accent: "#171717",
    accentText: "#ffffff",
    font: "'Geist',-apple-system,sans-serif",
    radius: "6px"
  },
  resend: {
    slug: "resend",
    name: "Resend",
    scheme: "dark",
    bg: "#000000",
    surface: "#0c0c0c",
    border: "#262626",
    text: "#fafafa",
    muted: "#a3a3a3",
    accent: "#ffffff",
    accentText: "#000000",
    font: "-apple-system,'Inter',sans-serif",
    radius: "8px"
  },
  nango: {
    slug: "nango",
    name: "Nango",
    scheme: "light",
    bg: "#ffffff",
    surface: "#ffffff",
    border: "#e5e7eb",
    text: "#111827",
    muted: "#6b7280",
    accent: "#467df4",
    accentText: "#ffffff",
    font: "'Inter',-apple-system,sans-serif",
    radius: "8px"
  },
  simpro: {
    slug: "simpro",
    name: "Simpro",
    scheme: "light",
    bg: "#ffffff",
    surface: "#ffffff",
    border: "#dde3ea",
    text: "#1f2d3d",
    muted: "#5b6b7b",
    accent: "#0a8a3f",
    accentText: "#ffffff",
    font: "-apple-system,'Open Sans',sans-serif",
    radius: "4px"
  }
};
function getTheme(service) {
  if (!service) return DEFAULT_THEME;
  return THEMES[service.toLowerCase()] ?? DEFAULT_THEME;
}
function themeOverrideCss(theme) {
  if (theme.slug === "default") return "";
  return `
body{background:${theme.bg};color:${theme.text};font-family:${theme.font};}
.emu-bar{background:${theme.scheme === "dark" ? "#000" : "#1b1b1f"};border-bottom-color:rgba(255,255,255,.08);color:#ffd166;}
.emu-bar-title{color:#fff;font-family:${theme.font};}
.emu-bar-links a{color:#bdbdbd;}
.emu-bar-links a:hover{color:#fff;}
.content-inner{background:${theme.surface};border:1px solid ${theme.border};border-radius:${theme.radius};padding:32px 28px;box-shadow:0 1px 3px rgba(0,0,0,.08);}
.card-title{color:${theme.text};font-family:${theme.font};font-weight:600;}
.card-subtitle{color:${theme.muted};}
.user-btn{background:${theme.surface};border:1px solid ${theme.border};color:${theme.text};border-radius:${theme.radius};}
.user-btn:hover{border-color:${theme.accent};background:${theme.scheme === "dark" ? "rgba(255,255,255,.04)" : "rgba(0,0,0,.02)"};}
.avatar{background:${theme.accent};color:${theme.accentText};font-family:${theme.font};}
.user-login{color:${theme.text};}
.user-meta{color:${theme.muted};}
.user-email{color:${theme.muted};opacity:.8;}
.powered-by{color:${theme.muted};}
.powered-by a{color:${theme.accent};}
.error-title{font-family:${theme.font};}
.error-msg{color:${theme.muted};}
`.trim();
}
var google = `<svg viewBox="0 0 48 48" width="42" height="42" aria-hidden="true"><path fill="#EA4335" d="M24 9.5c3.54 0 6.71 1.22 9.21 3.6l6.85-6.85C35.9 2.38 30.47 0 24 0 14.62 0 6.51 5.38 2.56 13.22l7.98 6.19C12.43 13.72 17.74 9.5 24 9.5z"/><path fill="#4285F4" d="M46.98 24.55c0-1.57-.15-3.09-.38-4.55H24v9.02h12.94c-.58 2.96-2.26 5.48-4.78 7.18l7.73 6c4.51-4.18 7.09-10.36 7.09-17.65z"/><path fill="#FBBC05" d="M10.53 28.59c-.48-1.45-.76-2.99-.76-4.59s.27-3.14.76-4.59l-7.98-6.19C.92 16.46 0 20.12 0 24c0 3.88.92 7.54 2.56 10.78l7.97-6.19z"/><path fill="#34A853" d="M24 48c6.48 0 11.93-2.13 15.89-5.81l-7.73-6c-2.15 1.45-4.92 2.3-8.16 2.3-6.26 0-11.57-4.22-13.47-9.91l-7.98 6.19C6.51 42.62 14.62 48 24 48z"/></svg>`;
var microsoft = `<svg viewBox="0 0 23 23" width="36" height="36" aria-hidden="true"><path fill="#f25022" d="M1 1h10v10H1z"/><path fill="#7fba00" d="M12 1h10v10H12z"/><path fill="#00a4ef" d="M1 12h10v10H1z"/><path fill="#ffb900" d="M12 12h10v10H12z"/></svg>`;
var apple = `<svg viewBox="0 0 24 24" width="40" height="40" fill="#000" aria-hidden="true"><path d="M12.152 6.896c-.948 0-2.415-1.078-3.96-1.04-2.04.027-3.91 1.183-4.961 3.014-2.117 3.675-.546 9.103 1.519 12.09 1.013 1.454 2.208 3.09 3.792 3.039 1.52-.065 2.09-.987 3.935-.987 1.831 0 2.35.987 3.96.948 1.637-.026 2.676-1.48 3.676-2.948 1.156-1.688 1.636-3.325 1.662-3.415-.039-.013-3.182-1.221-3.22-4.857-.026-3.04 2.48-4.494 2.597-4.559-1.429-2.09-3.623-2.324-4.39-2.376-2-.156-3.675 1.09-4.61 1.09zM15.53 3.83c.843-1.012 1.4-2.427 1.245-3.83-1.207.052-2.662.805-3.532 1.818-.78.896-1.454 2.338-1.273 3.714 1.338.104 2.715-.688 3.559-1.701"/></svg>`;
var github = `<svg viewBox="0 0 24 24" width="40" height="40" fill="#1f2328" aria-hidden="true"><path d="M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12"/></svg>`;
var okta = `<svg viewBox="0 0 24 24" width="38" height="38" fill="#00297a" aria-hidden="true"><path d="M12 0C5.385 0 0 5.385 0 12s5.385 12 12 12 12-5.385 12-12S18.615 0 12 0zm0 18c-3.309 0-6-2.691-6-6s2.691-6 6-6 6 2.691 6 6-2.691 6-6 6z"/></svg>`;
var slack = `<svg viewBox="0 0 122.8 122.8" width="36" height="36" aria-hidden="true"><path d="M25.8 77.6c0 7.1-5.8 12.9-12.9 12.9S0 84.7 0 77.6s5.8-12.9 12.9-12.9h12.9v12.9zm6.5 0c0-7.1 5.8-12.9 12.9-12.9s12.9 5.8 12.9 12.9v32.3c0 7.1-5.8 12.9-12.9 12.9s-12.9-5.8-12.9-12.9V77.6z" fill="#36C5F0"/><path d="M45.2 25.8c-7.1 0-12.9-5.8-12.9-12.9S38.1 0 45.2 0s12.9 5.8 12.9 12.9v12.9H45.2zm0 6.5c7.1 0 12.9 5.8 12.9 12.9s-5.8 12.9-12.9 12.9H12.9C5.8 58.1 0 52.3 0 45.2s5.8-12.9 12.9-12.9h32.3z" fill="#2EB67D"/><path d="M97 45.2c0-7.1 5.8-12.9 12.9-12.9s12.9 5.8 12.9 12.9-5.8 12.9-12.9 12.9H97V45.2zm-6.5 0c0 7.1-5.8 12.9-12.9 12.9s-12.9-5.8-12.9-12.9V12.9C64.7 5.8 70.5 0 77.6 0s12.9 5.8 12.9 12.9v32.3z" fill="#ECB22E"/><path d="M77.6 97c7.1 0 12.9 5.8 12.9 12.9s-5.8 12.9-12.9 12.9-12.9-5.8-12.9-12.9V97h12.9zm0-6.5c-7.1 0-12.9-5.8-12.9-12.9s5.8-12.9 12.9-12.9h32.3c7.1 0 12.9 5.8 12.9 12.9s-5.8 12.9-12.9 12.9H77.6z" fill="#E01E5A"/></svg>`;
var salesforce = `<svg viewBox="0 0 24 24" width="46" height="46" fill="#00A1E0" aria-hidden="true"><path d="M9.9 6.2c.72-.78 1.79-1.3 2.96-1.3 1.55 0 2.92.86 3.64 2.16.62-.28 1.31-.43 2.03-.43 2.3 0 4.17 1.88 4.17 4.2s-1.87 4.2-4.17 4.2c-.28 0-.56-.03-.83-.08-.62 1.11-1.81 1.86-3.17 1.86-.5 0-.98-.1-1.42-.29-.63 1.4-2.03 2.38-3.66 2.38-1.66 0-3.1-1.01-3.71-2.46-.23.05-.47.07-.71.07C1.55 16.61 0 15.04 0 13.11c0-1.29.69-2.42 1.72-3.04-.13-.39-.2-.81-.2-1.24 0-2.2 1.79-3.99 4-3.99 1.29 0 2.45.62 3.18 1.57.04-.07.08-.14.2-.21z"/></svg>`;
var hubspot = `<svg viewBox="0 0 24 24" width="40" height="40" fill="#FF7A59" aria-hidden="true"><path d="M18 7.32V5.13a1.74 1.74 0 1 0-1.16 0v2.19a5.05 5.05 0 0 0-2.4.98L7.97 3.43a1.95 1.95 0 1 0-.92 1.21l6.32 4.91a5.06 5.06 0 0 0 .08 5.71l-1.92 1.92a1.63 1.63 0 0 0-.47-.07 1.65 1.65 0 1 0 1.65 1.65 1.63 1.63 0 0 0-.07-.47l1.9-1.9a5.06 5.06 0 1 0 3.46-9.07zm-1.55 7.6a2.64 2.64 0 1 1 2.64-2.64 2.64 2.64 0 0 1-2.64 2.64z"/></svg>`;
var vercel = `<svg viewBox="0 0 24 24" width="34" height="34" fill="#000" aria-hidden="true"><path d="M12 2 24 22H0z"/></svg>`;
var clerk = `<svg viewBox="0 0 40 40" width="40" height="40" aria-hidden="true"><rect width="40" height="40" rx="9" fill="#6C47FF"/><circle cx="20" cy="16.5" r="4.2" fill="#fff"/><path d="M13 28a7.6 7.6 0 0 1 14 0z" fill="#fff"/></svg>`;
var workos = `<svg viewBox="0 0 40 40" width="40" height="40" aria-hidden="true"><rect width="40" height="40" rx="9" fill="#6363F1"/><path d="M10 14l3 12 3-9 3 9 3-12" fill="none" stroke="#fff" stroke-width="2.2" stroke-linejoin="round" stroke-linecap="round"/><path d="M25 20a4.5 4.5 0 1 0 4.5 4.5" fill="none" stroke="#fff" stroke-width="2.2" stroke-linecap="round"/></svg>`;
var LOGOS = {
  google,
  microsoft,
  apple,
  github,
  okta,
  slack,
  salesforce,
  hubspot,
  vercel,
  clerk,
  workos
};
function getLogo(service) {
  if (!service) return null;
  return LOGOS[service.toLowerCase()] ?? null;
}
function escapeHtml(s) {
  return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
}
function escapeAttr(s) {
  return escapeHtml(s).replace(/'/g, "&#39;");
}
var CSS = `
@font-face{
  font-family:'Geist';font-style:normal;font-weight:100 900;font-display:swap;
  src:url('/_emulate/fonts/geist-sans.woff2') format('woff2');
}
:root{
  color-scheme:dark;
  /* ElevenLabs UI \u2014 neutral dark (OKLCH). Values already avoid pure #000/#fff. */
  --bg:oklch(0.145 0 0);
  --fg:oklch(0.985 0 0);
  --card:oklch(0.205 0 0);
  --elevated:oklch(0.269 0 0);
  --muted:oklch(0.269 0 0);
  --muted-fg:oklch(0.708 0 0);
  --faint-fg:oklch(0.556 0 0);
  --border:oklch(1 0 0 / 10%);
  --border-strong:oklch(1 0 0 / 16%);
  --ring:oklch(0.556 0 0);
  --primary:oklch(0.922 0 0);
  --primary-fg:oklch(0.205 0 0);
  --danger:oklch(0.704 0.191 22.216);
  --radius:0.625rem;
  --radius-sm:0.375rem;
  --radius-lg:0.875rem;
  --radius-pill:999px;
  --space-xs:0.25rem;--space-sm:0.5rem;--space-md:0.75rem;
  --space-lg:1rem;--space-xl:1.5rem;--space-2xl:2rem;--space-3xl:3rem;
  --text-xs:0.75rem;--text-sm:0.8125rem;--text-md:0.875rem;
  --text-base:1rem;--text-lg:1.25rem;--text-xl:1.5rem;
  --font-sans:'Geist',-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;
  --font-mono:ui-monospace,'SF Mono',SFMono-Regular,Menlo,Consolas,monospace;
}
*{box-sizing:border-box;margin:0;padding:0}
body{
  font-family:var(--font-sans);font-size:var(--text-md);line-height:1.55;
  background:var(--bg);color:var(--fg);min-height:100vh;
  -webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;
}
::selection{background:var(--primary);color:var(--primary-fg);}

.emu-bar{
  border-bottom:1px solid var(--border);padding:var(--space-md) var(--space-xl);
  display:flex;align-items:center;gap:var(--space-md);
  font-size:var(--text-sm);color:var(--muted-fg);
}
.emu-bar-title{font-weight:600;color:var(--fg);letter-spacing:-0.01em;}
.emu-badge{
  display:inline-flex;align-items:center;gap:var(--space-xs);
  font-size:var(--text-xs);font-weight:600;letter-spacing:.06em;text-transform:uppercase;
  padding:3px 10px;border-radius:var(--radius-pill);
  background:var(--primary);color:var(--primary-fg);
  white-space:nowrap;flex-shrink:0;
}
.emu-badge::before{content:"";width:5px;height:5px;border-radius:50%;background:currentColor;}
.emu-watermark{
  position:fixed;bottom:var(--space-lg);right:var(--space-lg);z-index:9999;pointer-events:none;
  font-size:var(--text-xs);font-weight:600;letter-spacing:.1em;text-transform:uppercase;
  padding:5px 11px;border-radius:var(--radius-sm);
  background:color-mix(in oklch,var(--bg) 72%,transparent);
  color:var(--muted-fg);border:1px solid var(--border-strong);
  backdrop-filter:blur(6px);
}
.emu-bar-links{margin-left:auto;display:flex;gap:var(--space-xl);}
.emu-bar-links a{
  color:var(--muted-fg);font-size:var(--text-sm);text-decoration:none;transition:color .15s;
}
.emu-bar-links a:hover{color:var(--fg);}
.emu-bar-links a .full{display:inline;}
.emu-bar-links a .short{display:none;}
@media(max-width:600px){
  .emu-bar-links a .full{display:none;}
  .emu-bar-links a .short{display:inline;}
}

.content{
  display:flex;align-items:center;justify-content:center;
  min-height:calc(100vh - 50px);padding:var(--space-2xl) var(--space-lg);
}
.content-inner{width:100%;max-width:420px;}
.brand-logo{display:flex;justify-content:center;margin-bottom:var(--space-xl);}
.brand-logo svg{display:block;}
.card-branded{text-align:center;}
.card-branded .card-title{text-align:center;}
.card-branded .card-subtitle{text-align:center;}
.card-branded .user-form{text-align:left;}
.card-title{
  font-size:var(--text-lg);font-weight:600;letter-spacing:-0.02em;
  margin-bottom:var(--space-xs);color:var(--fg);
}
.card-subtitle{color:var(--muted-fg);font-size:var(--text-sm);margin-bottom:var(--space-xl);line-height:1.5;}
.powered-by{
  position:fixed;bottom:0;left:0;right:0;
  text-align:center;padding:var(--space-md);font-size:var(--text-xs);color:var(--faint-fg);
}
.powered-by a{color:var(--muted-fg);text-decoration:none;transition:color .15s;}
.powered-by a:hover{color:var(--fg);}

.error-title{color:var(--danger);font-size:var(--text-lg);font-weight:600;margin-bottom:var(--space-sm);letter-spacing:-0.01em;}
.error-msg{color:var(--muted-fg);font-size:var(--text-md);line-height:1.5;}
.error-card{text-align:center;}

.user-form{margin-bottom:var(--space-sm);}
.user-form:last-of-type{margin-bottom:0;}
.user-btn{
  width:100%;display:flex;align-items:center;gap:var(--space-md);
  padding:var(--space-md);border:1px solid var(--border);border-radius:var(--radius);
  background:var(--card);color:inherit;cursor:pointer;text-align:left;
  font:inherit;transition:border-color .15s,background .15s;
}
.user-btn:hover{border-color:var(--border-strong);background:var(--elevated);}
.avatar{
  width:36px;height:36px;border-radius:50%;
  background:var(--elevated);color:var(--fg);font-weight:600;font-size:var(--text-md);
  display:flex;align-items:center;justify-content:center;flex-shrink:0;
}
.user-text{min-width:0;}
.user-login{font-weight:600;font-size:var(--text-md);display:block;color:var(--fg);}
.user-meta{color:var(--muted-fg);font-size:var(--text-xs);margin-top:1px;}
.user-email{font-size:var(--text-xs);color:var(--faint-fg);word-break:break-all;margin-top:1px;}

.settings-layout{
  max-width:920px;margin:0 auto;padding:var(--space-3xl) var(--space-xl);
  display:flex;gap:var(--space-3xl);
}
.settings-sidebar{width:200px;flex-shrink:0;}
.settings-sidebar a{
  display:block;padding:6px 10px;border-radius:var(--radius-sm);color:var(--muted-fg);
  text-decoration:none;font-size:var(--text-sm);transition:color .15s,background .15s;
}
.settings-sidebar a:hover{color:var(--fg);background:var(--muted);}
.settings-sidebar a.active{color:var(--fg);font-weight:600;background:var(--muted);}
.settings-main{flex:1;min-width:0;}

.s-card{
  padding:var(--space-xl) 0;margin-bottom:var(--space-lg);border-bottom:1px solid var(--border);
}
.s-card:last-child{border-bottom:none;}
.s-card-header{display:flex;align-items:center;gap:var(--space-md);margin-bottom:var(--space-lg);}
.s-icon{
  width:40px;height:40px;border-radius:var(--radius);
  background:var(--elevated);display:flex;align-items:center;justify-content:center;
  font-size:var(--text-base);font-weight:600;color:var(--muted-fg);flex-shrink:0;
}
.s-title{font-size:var(--text-lg);font-weight:600;color:var(--fg);letter-spacing:-0.01em;}
.s-subtitle{font-size:var(--text-xs);color:var(--muted-fg);margin-top:2px;}
.section-heading{
  font-size:var(--text-md);font-weight:600;margin-bottom:var(--space-md);color:var(--fg);
  display:flex;align-items:center;justify-content:space-between;
}
.perm-list{list-style:none;}
.perm-list li{padding:5px 0;font-size:var(--text-sm);display:flex;align-items:center;gap:var(--space-sm);color:var(--muted-fg);}
.check{color:var(--fg);}
.org-row{
  display:flex;align-items:center;gap:var(--space-sm);padding:7px 0;
  border-bottom:1px solid var(--border);font-size:var(--text-sm);
}
.org-row:last-child{border-bottom:none;}
.org-icon{
  width:22px;height:22px;border-radius:var(--radius-sm);background:var(--elevated);
  display:flex;align-items:center;justify-content:center;
  font-size:var(--text-xs);font-weight:600;color:var(--muted-fg);flex-shrink:0;
}
.org-name{font-weight:600;color:var(--fg);}
.badge{
  font-size:var(--text-xs);padding:2px 8px;border-radius:var(--radius-sm);font-weight:500;
  background:var(--muted);color:var(--muted-fg);border:1px solid var(--border);
}
.badge-granted{background:var(--elevated);color:var(--fg);}
.badge-denied{background:color-mix(in oklch,var(--danger) 18%,var(--bg));color:var(--danger);border-color:color-mix(in oklch,var(--danger) 30%,transparent);}
.badge-requested{background:var(--muted);color:var(--muted-fg);}
.btn-revoke{
  display:inline-block;padding:5px 14px;border-radius:var(--radius-sm);
  border:1px solid var(--border);background:transparent;color:var(--danger);
  font-size:var(--text-xs);font-weight:600;cursor:pointer;transition:border-color .15s;
}
.btn-revoke:hover{border-color:var(--danger);}
.info-text{color:var(--muted-fg);font-size:var(--text-xs);line-height:1.5;margin-top:var(--space-md);}
.app-link{
  display:flex;align-items:center;gap:var(--space-md);padding:var(--space-md);
  border:1px solid var(--border);border-radius:var(--radius);background:var(--card);
  text-decoration:none;color:inherit;margin-bottom:var(--space-sm);transition:border-color .15s,background .15s;
}
.app-link:hover{border-color:var(--border-strong);background:var(--elevated);}
.app-link-name{font-weight:600;font-size:var(--text-md);color:var(--fg);}
.app-link-scopes{font-size:var(--text-xs);color:var(--muted-fg);margin-top:1px;}
.empty{color:var(--muted-fg);text-align:center;padding:var(--space-3xl) 0;font-size:var(--text-md);}

.inspector-layout{max-width:960px;margin:0 auto;padding:var(--space-3xl) var(--space-xl);}
.inspector-tabs{
  display:flex;flex-wrap:wrap;gap:var(--space-xs);margin-bottom:var(--space-2xl);
  padding:var(--space-xs);background:var(--card);border:1px solid var(--border);
  border-radius:var(--radius);width:fit-content;max-width:100%;
}
.inspector-tabs a{
  padding:6px 14px;border-radius:var(--radius-sm);text-decoration:none;
  font-size:var(--text-sm);color:var(--muted-fg);transition:color .15s,background .15s;
}
.inspector-tabs a:hover{color:var(--fg);}
.inspector-tabs a.active{color:var(--fg);font-weight:600;background:var(--elevated);}
.inspector-section{margin-bottom:var(--space-2xl);}
.inspector-section h2{
  font-size:var(--text-lg);font-weight:600;color:var(--fg);
  margin-bottom:var(--space-md);letter-spacing:-0.01em;
}
.inspector-section h3{
  font-size:var(--text-md);font-weight:600;color:var(--muted-fg);
  margin:var(--space-xl) 0 var(--space-sm);
}
.inspector-table{width:100%;border-collapse:collapse;margin-bottom:var(--space-md);}
.inspector-table th,.inspector-table td{
  text-align:left;padding:var(--space-sm) var(--space-md);border-bottom:1px solid var(--border);
  font-size:var(--text-sm);
}
.inspector-table th{color:var(--faint-fg);font-weight:600;font-size:var(--text-xs);text-transform:uppercase;letter-spacing:.06em;}
.inspector-table td{color:var(--fg);}
.inspector-table tbody tr{transition:background .12s;}
.inspector-table tbody tr:hover{background:var(--card);}
.inspector-empty{color:var(--muted-fg);text-align:center;padding:var(--space-xl) 0;font-size:var(--text-sm);}

/* Live activity feed (renderActivityCard) \u2014 token-driven so it stays cohesive
   with the dark control plane instead of the old hard-coded light values. */
.act-pulse{
  width:9px;height:9px;border-radius:50%;background:var(--fg);flex-shrink:0;
  position:relative;
}
.act-pulse::after{
  content:"";position:absolute;inset:-4px;border-radius:50%;
  border:1px solid var(--fg);opacity:.5;animation:act-ping 1.8s ease-out infinite;
}
@keyframes act-ping{0%{transform:scale(.6);opacity:.5}80%,100%{transform:scale(1.6);opacity:0}}
@media(prefers-reduced-motion:reduce){.act-pulse::after{animation:none;}}
.act-status.is-live{color:var(--fg);}
.act-status.is-error{color:var(--danger);}
.act-mono{font-family:var(--font-mono);font-size:var(--text-xs);color:var(--muted-fg);white-space:nowrap;}
.act-fields{font-size:var(--text-xs);color:var(--muted-fg);}
.act-json-btn{
  font:inherit;font-size:var(--text-xs);padding:2px 9px;border:1px solid var(--border);
  border-radius:var(--radius-sm);background:transparent;color:var(--muted-fg);
  cursor:pointer;transition:border-color .15s,color .15s;
}
.act-json-btn:hover{border-color:var(--border-strong);color:var(--fg);}
.act-detail-cell{background:var(--card);padding:var(--space-sm) var(--space-md);}
.act-detail-cell pre{
  margin:0;font-family:var(--font-mono);font-size:var(--text-xs);line-height:1.5;
  color:var(--muted-fg);white-space:pre-wrap;word-break:break-word;max-height:300px;overflow:auto;
}
.inspector-table tbody tr.act-row-new td{background:color-mix(in oklch,var(--elevated) 80%,transparent);transition:background .9s;}

.checkout-layout{display:flex;min-height:calc(100vh - 50px);}
.checkout-summary{
  flex:1;background:var(--card);padding:var(--space-3xl) var(--space-2xl) var(--space-3xl) 10%;
  display:flex;flex-direction:column;justify-content:center;border-right:1px solid var(--border);
}
.checkout-form-side{
  flex:1;background:var(--bg);padding:var(--space-3xl) 10% var(--space-3xl) var(--space-2xl);
  display:flex;flex-direction:column;justify-content:center;
}
.checkout-merchant{display:flex;align-items:center;gap:var(--space-md);margin-bottom:6px;}
.checkout-merchant-name{font-size:var(--text-md);font-weight:600;color:var(--fg);}
.checkout-test-badge{
  font-size:var(--text-xs);font-weight:600;letter-spacing:.04em;text-transform:uppercase;
  background:var(--muted);color:var(--muted-fg);padding:2px 8px;border-radius:var(--radius-sm);
}
.checkout-total{font-size:var(--text-xl);font-weight:700;color:var(--fg);margin:var(--space-sm) 0 var(--space-2xl);letter-spacing:-0.02em;}
.checkout-line-item{display:flex;align-items:center;gap:var(--space-md);padding:var(--space-lg) 0;border-bottom:1px solid var(--border);}
.checkout-line-item:first-child{border-top:1px solid var(--border);}
.checkout-item-icon{
  width:40px;height:40px;border-radius:var(--radius-sm);background:var(--elevated);
  display:flex;align-items:center;justify-content:center;flex-shrink:0;
  font-size:var(--text-md);font-weight:600;color:var(--muted-fg);
}
.checkout-item-details{flex:1;min-width:0;}
.checkout-item-name{font-size:var(--text-md);font-weight:600;color:var(--fg);}
.checkout-item-qty{font-size:var(--text-xs);color:var(--muted-fg);margin-top:2px;}
.checkout-item-price{font-size:var(--text-md);font-weight:600;color:var(--fg);text-align:right;white-space:nowrap;}
.checkout-item-unit{font-size:var(--text-xs);color:var(--muted-fg);text-align:right;margin-top:2px;}
.checkout-totals{margin-top:var(--space-xl);}
.checkout-totals-row{display:flex;justify-content:space-between;padding:6px 0;font-size:var(--text-sm);color:var(--muted-fg);}
.checkout-totals-row.total{border-top:1px solid var(--border);margin-top:var(--space-sm);padding-top:var(--space-lg);font-size:var(--text-md);font-weight:600;color:var(--fg);}
.checkout-form-section{margin-bottom:var(--space-xl);}
.checkout-form-label{font-size:var(--text-sm);font-weight:600;color:var(--fg);margin-bottom:var(--space-sm);display:block;}
.checkout-input{
  width:100%;padding:var(--space-md);border:1px solid var(--border);border-radius:var(--radius-sm);
  background:var(--card);color:var(--fg);font:inherit;font-size:var(--text-md);
  transition:border-color .15s;outline:none;
}
.checkout-input:focus{border-color:var(--ring);}
.checkout-input::placeholder{color:var(--faint-fg);}
.checkout-card-box{border:1px solid var(--border);border-radius:var(--radius-sm);padding:var(--space-lg);background:var(--card);}
.checkout-card-row{display:flex;gap:var(--space-md);margin-top:var(--space-md);}
.checkout-card-row .checkout-input{flex:1;}
.checkout-sim-note{font-size:var(--text-xs);color:var(--muted-fg);margin-top:var(--space-md);text-align:center;font-style:italic;}
.checkout-pay-btn{
  width:100%;padding:var(--space-lg);border:none;border-radius:var(--radius);
  background:var(--primary);color:var(--primary-fg);font:inherit;font-size:var(--text-md);font-weight:600;
  cursor:pointer;transition:opacity .15s;
}
.checkout-pay-btn:hover{opacity:.9;}
.checkout-cancel{text-align:center;margin-top:var(--space-lg);}
.checkout-cancel a{color:var(--muted-fg);text-decoration:none;font-size:var(--text-sm);transition:color .15s;}
.checkout-cancel a:hover{color:var(--fg);}
@media(max-width:768px){
  .checkout-layout{flex-direction:column;}
  .checkout-summary{padding:var(--space-2xl) var(--space-xl);border-right:none;border-bottom:1px solid var(--border);}
  .checkout-form-side{padding:var(--space-2xl) var(--space-xl);}
}
`;
var POWERED_BY = `<div class="powered-by">Powered by <a href="https://github.com/Vinniai/agent-emulate#readme" target="_blank" rel="noopener">agent-emulate</a></div>`;
var WATERMARK = `<div class="emu-watermark" aria-hidden="true">agent-emulate</div>`;
function emuBar(service) {
  const title = service ? `${escapeHtml(service)} Emulator` : "Emulator";
  return `<div class="emu-bar">
  <span class="emu-bar-title">${title}</span>
  <span class="emu-badge" title="This is a local emulator, not the real provider">Emulated</span>
  <nav class="emu-bar-links">
    <a href="https://github.com/Vinniai/agent-emulate/issues" target="_blank" rel="noopener"><span class="full">Report Issue</span><span class="short">Report</span></a>
    <a href="https://github.com/Vinniai/agent-emulate" target="_blank" rel="noopener"><span class="full">Source Code</span><span class="short">Source</span></a>
    <a href="https://github.com/Vinniai/agent-emulate#readme" target="_blank" rel="noopener"><span class="full">Learn More</span><span class="short">Learn</span></a>
  </nav>
</div>`;
}
function head(title, service) {
  const themeCss = themeOverrideCss(getTheme(service));
  const themeStyle = themeCss ? `<style>${themeCss}</style>` : "";
  return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width,initial-scale=1"/>
<link rel="icon" href="/_emulate/favicon.ico"/>
<title>${escapeHtml(title)} | agent-emulate</title>
<style>${CSS}</style>${themeStyle}
</head>`;
}
function renderCardPage(title, subtitle, body, service) {
  const logo = getLogo(service);
  const logoHtml = logo ? `<div class="brand-logo">${logo}</div>` : "";
  return `${head(title, service)}
<body>
${emuBar(service)}
<div class="content">
  <div class="content-inner${logo ? " card-branded" : ""}">
    ${logoHtml}
    <div class="card-title">${escapeHtml(title)}</div>
    <div class="card-subtitle">${subtitle}</div>
    ${body}
  </div>
</div>
${POWERED_BY}
${WATERMARK}
</body></html>`;
}
var RING_SIZE = 200;
var ActivityBus = class {
  buffer = [];
  subscribers = /* @__PURE__ */ new Set();
  publish(event) {
    this.buffer.push(event);
    if (this.buffer.length > RING_SIZE) this.buffer.splice(0, this.buffer.length - RING_SIZE);
    for (const cb of this.subscribers) {
      try {
        cb(event);
      } catch {
      }
    }
  }
  subscribe(cb) {
    this.subscribers.add(cb);
    return () => this.subscribers.delete(cb);
  }
  recent(limit = 50, service) {
    const filtered = service ? this.buffer.filter((e) => e.service === service) : this.buffer;
    return filtered.slice(-limit).reverse();
  }
};
var activityBus = globalThis.__emulate_activity_bus__ ?? (globalThis.__emulate_activity_bus__ = new ActivityBus());
function getResendStore(store) {
  return {
    emails: store.collection("resend.emails", ["uuid"]),
    domains: store.collection("resend.domains", ["uuid", "name"]),
    apiKeys: store.collection("resend.api_keys", ["uuid"]),
    audiences: store.collection("resend.audiences", ["uuid"]),
    contacts: store.collection("resend.contacts", ["uuid", "audience_id"])
  };
}
function generateUuid() {
  return randomUUID();
}
function resendError(c, statusCode, name, message) {
  return c.json({ statusCode, name, message }, statusCode);
}
function resendList(data) {
  return { object: "list", data };
}
async function parseResendBody(c) {
  const contentType = c.req.header("content-type") ?? "";
  if (contentType.includes("application/x-www-form-urlencoded")) {
    const text = await c.req.text();
    const params = new URLSearchParams(text);
    const result = {};
    for (const [key, value] of params.entries()) {
      result[key] = value;
    }
    return result;
  }
  try {
    const body = await c.req.json();
    if (body && typeof body === "object" && !Array.isArray(body)) {
      return body;
    }
    return {};
  } catch {
    return {};
  }
}
function emailRoutes(ctx) {
  const { app, store, webhooks } = ctx;
  const rs = () => getResendStore(store);
  app.post("/emails/batch", async (c) => {
    let emails;
    try {
      const raw = await c.req.json();
      if (!Array.isArray(raw)) {
        return resendError(c, 422, "validation_error", "Request body must be an array");
      }
      emails = raw;
    } catch {
      return resendError(c, 422, "validation_error", "Request body must be an array");
    }
    if (emails.length > 100) {
      return resendError(c, 422, "validation_error", "Batch size cannot exceed 100 emails");
    }
    for (const emailData of emails) {
      if (!emailData.from) return resendError(c, 422, "validation_error", "Missing required field: from");
      if (!emailData.to) return resendError(c, 422, "validation_error", "Missing required field: to");
      if (!emailData.subject) return resendError(c, 422, "validation_error", "Missing required field: subject");
    }
    const results = [];
    for (const emailData of emails) {
      const from = emailData.from;
      const to = emailData.to;
      const subject = emailData.subject;
      const toArray = Array.isArray(to) ? to : [to];
      const uuid = generateUuid();
      const scheduledAt = emailData.scheduled_at;
      const status = scheduledAt ? "scheduled" : "delivered";
      rs().emails.insert({
        uuid,
        from,
        to: toArray,
        subject,
        html: emailData.html ?? null,
        text: emailData.text ?? null,
        cc: normalizeStringArray(emailData.cc),
        bcc: normalizeStringArray(emailData.bcc),
        reply_to: normalizeStringArray(emailData.reply_to),
        headers: emailData.headers ?? {},
        tags: emailData.tags ?? [],
        status,
        scheduled_at: scheduledAt ?? null,
        last_event: status === "scheduled" ? "email.scheduled" : "email.delivered"
      });
      if (!scheduledAt) {
        await webhooks.dispatch(
          "email.sent",
          void 0,
          { type: "email.sent", data: { email_id: uuid, to: toArray, from, subject } },
          "resend"
        );
        await webhooks.dispatch(
          "email.delivered",
          void 0,
          { type: "email.delivered", data: { email_id: uuid, to: toArray, from, subject } },
          "resend"
        );
      }
      results.push({ id: uuid });
    }
    return c.json({ data: results }, 200);
  });
  app.post("/emails", async (c) => {
    const body = await parseResendBody(c);
    const from = body.from;
    const to = body.to;
    const subject = body.subject;
    if (!from) return resendError(c, 422, "validation_error", "Missing required field: from");
    if (!to) return resendError(c, 422, "validation_error", "Missing required field: to");
    if (!subject) return resendError(c, 422, "validation_error", "Missing required field: subject");
    const toArray = Array.isArray(to) ? to : [to];
    const uuid = generateUuid();
    const scheduledAt = body.scheduled_at;
    const status = scheduledAt ? "scheduled" : "delivered";
    rs().emails.insert({
      uuid,
      from,
      to: toArray,
      subject,
      html: body.html ?? null,
      text: body.text ?? null,
      cc: normalizeStringArray(body.cc),
      bcc: normalizeStringArray(body.bcc),
      reply_to: normalizeStringArray(body.reply_to),
      headers: body.headers ?? {},
      tags: body.tags ?? [],
      status,
      scheduled_at: scheduledAt ?? null,
      last_event: status === "scheduled" ? "email.scheduled" : "email.delivered"
    });
    if (!scheduledAt) {
      await webhooks.dispatch(
        "email.sent",
        void 0,
        { type: "email.sent", data: { email_id: uuid, to: toArray, from, subject } },
        "resend"
      );
      await webhooks.dispatch(
        "email.delivered",
        void 0,
        { type: "email.delivered", data: { email_id: uuid, to: toArray, from, subject } },
        "resend"
      );
    }
    return c.json({ id: uuid }, 200);
  });
  app.get("/emails", (c) => {
    const allEmails = rs().emails.all();
    return c.json(resendList(allEmails.map(formatEmail)));
  });
  app.get("/emails/:id", (c) => {
    const id = c.req.param("id");
    const email = rs().emails.findOneBy("uuid", id);
    if (!email) return resendError(c, 404, "not_found", "Email not found");
    return c.json(formatEmail(email));
  });
  app.post("/emails/:id/cancel", (c) => {
    const id = c.req.param("id");
    const email = rs().emails.findOneBy("uuid", id);
    if (!email) return resendError(c, 404, "not_found", "Email not found");
    if (email.status !== "scheduled") {
      return resendError(c, 422, "validation_error", "Only scheduled emails can be canceled");
    }
    rs().emails.update(email.id, {
      status: "canceled",
      last_event: "email.canceled"
    });
    return c.json({ id: email.uuid, object: "email", canceled: true });
  });
}
function normalizeStringArray(value) {
  if (!value) return [];
  if (Array.isArray(value)) return value.map(String);
  if (typeof value === "string") return [value];
  return [];
}
function formatEmail(email) {
  return {
    id: email.uuid,
    object: "email",
    from: email.from,
    to: email.to,
    subject: email.subject,
    html: email.html,
    text: email.text,
    cc: email.cc,
    bcc: email.bcc,
    reply_to: email.reply_to,
    headers: email.headers,
    tags: email.tags,
    status: email.status,
    scheduled_at: email.scheduled_at,
    last_event: email.last_event,
    created_at: email.created_at
  };
}
function domainRoutes(ctx) {
  const { app, store, webhooks } = ctx;
  const rs = () => getResendStore(store);
  app.post("/domains", async (c) => {
    const body = await parseResendBody(c);
    const name = body.name;
    if (!name) return resendError(c, 422, "validation_error", "Missing required field: name");
    const region = body.region ?? "us-east-1";
    const uuid = generateUuid();
    const records = [
      {
        record: "SPF",
        name,
        type: "MX",
        ttl: "Auto",
        status: "pending",
        value: `feedback-smtp.${region}.amazonses.com`,
        priority: 10
      },
      {
        record: "SPF",
        name,
        type: "TXT",
        ttl: "Auto",
        status: "pending",
        value: "v=spf1 include:amazonses.com ~all"
      },
      {
        record: "DKIM",
        name: `resend._domainkey.${name}`,
        type: "CNAME",
        ttl: "Auto",
        status: "pending",
        value: `resend.domainkey.${region}.amazonses.com`
      }
    ];
    const domain = rs().domains.insert({
      uuid,
      name,
      status: "pending",
      region,
      records
    });
    await webhooks.dispatch(
      "domain.created",
      void 0,
      { type: "domain.created", data: { id: uuid, name } },
      "resend"
    );
    return c.json(formatDomain(domain), 200);
  });
  app.get("/domains", (c) => {
    const allDomains = rs().domains.all();
    return c.json(resendList(allDomains.map(formatDomain)));
  });
  app.get("/domains/:id", (c) => {
    const id = c.req.param("id");
    const domain = rs().domains.findOneBy("uuid", id);
    if (!domain) return resendError(c, 404, "not_found", "Domain not found");
    return c.json(formatDomain(domain));
  });
  app.delete("/domains/:id", async (c) => {
    const id = c.req.param("id");
    const domain = rs().domains.findOneBy("uuid", id);
    if (!domain) return resendError(c, 404, "not_found", "Domain not found");
    rs().domains.delete(domain.id);
    await webhooks.dispatch(
      "domain.deleted",
      void 0,
      { type: "domain.deleted", data: { id: domain.uuid, name: domain.name } },
      "resend"
    );
    return c.json({ object: "domain", id: domain.uuid, deleted: true });
  });
  app.post("/domains/:id/verify", (c) => {
    const id = c.req.param("id");
    const domain = rs().domains.findOneBy("uuid", id);
    if (!domain) return resendError(c, 404, "not_found", "Domain not found");
    const verifiedRecords = domain.records.map((r) => ({ ...r, status: "verified" }));
    rs().domains.update(domain.id, {
      status: "verified",
      records: verifiedRecords
    });
    return c.json({ object: "domain", id: domain.uuid, status: "verified" });
  });
}
function formatDomain(domain) {
  return {
    id: domain.uuid,
    object: "domain",
    name: domain.name,
    status: domain.status,
    region: domain.region,
    records: domain.records,
    created_at: domain.created_at
  };
}
function apiKeyRoutes(ctx) {
  const { app, store } = ctx;
  const rs = () => getResendStore(store);
  app.post("/api-keys", async (c) => {
    const body = await parseResendBody(c);
    const name = body.name;
    if (!name) return resendError(c, 422, "validation_error", "Missing required field: name");
    const uuid = generateUuid();
    const token = `re_${randomBytes(16).toString("hex")}`;
    const apiKey = rs().apiKeys.insert({
      uuid,
      name,
      token
    });
    return c.json(
      {
        id: apiKey.uuid,
        token: apiKey.token
      },
      200
    );
  });
  app.get("/api-keys", (c) => {
    const allKeys = rs().apiKeys.all();
    return c.json(
      resendList(
        allKeys.map((key) => ({
          id: key.uuid,
          name: key.name,
          created_at: key.created_at
        }))
      )
    );
  });
  app.delete("/api-keys/:id", (c) => {
    const id = c.req.param("id");
    const apiKey = rs().apiKeys.findOneBy("uuid", id);
    if (!apiKey) return resendError(c, 404, "not_found", "API key not found");
    rs().apiKeys.delete(apiKey.id);
    return c.json({ deleted: true });
  });
}
function contactRoutes(ctx) {
  const { app, store, webhooks } = ctx;
  const rs = () => getResendStore(store);
  app.post("/audiences", async (c) => {
    const body = await parseResendBody(c);
    const name = body.name;
    if (!name) return resendError(c, 422, "validation_error", "Missing required field: name");
    const uuid = generateUuid();
    const audience = rs().audiences.insert({ uuid, name });
    return c.json(
      {
        id: audience.uuid,
        object: "audience",
        name: audience.name,
        created_at: audience.created_at
      },
      200
    );
  });
  app.get("/audiences", (c) => {
    const allAudiences = rs().audiences.all();
    return c.json(
      resendList(
        allAudiences.map((a) => ({
          id: a.uuid,
          object: "audience",
          name: a.name,
          created_at: a.created_at
        }))
      )
    );
  });
  app.delete("/audiences/:id", (c) => {
    const id = c.req.param("id");
    const audience = rs().audiences.findOneBy("uuid", id);
    if (!audience) return resendError(c, 404, "not_found", "Audience not found");
    rs().audiences.delete(audience.id);
    return c.json({ object: "audience", id: audience.uuid, deleted: true });
  });
  app.post("/audiences/:audience_id/contacts", async (c) => {
    const audienceId = c.req.param("audience_id");
    const audience = rs().audiences.findOneBy("uuid", audienceId);
    if (!audience) return resendError(c, 404, "not_found", "Audience not found");
    const body = await parseResendBody(c);
    const email = body.email;
    if (!email) return resendError(c, 422, "validation_error", "Missing required field: email");
    const uuid = generateUuid();
    const contact = rs().contacts.insert({
      uuid,
      audience_id: audienceId,
      email,
      first_name: body.first_name ?? null,
      last_name: body.last_name ?? null,
      unsubscribed: body.unsubscribed ?? false
    });
    await webhooks.dispatch(
      "contact.created",
      void 0,
      { type: "contact.created", data: { id: uuid, email, audience_id: audienceId } },
      "resend"
    );
    return c.json(
      {
        id: contact.uuid,
        object: "contact",
        email: contact.email
      },
      200
    );
  });
  app.get("/audiences/:audience_id/contacts", (c) => {
    const audienceId = c.req.param("audience_id");
    const audience = rs().audiences.findOneBy("uuid", audienceId);
    if (!audience) return resendError(c, 404, "not_found", "Audience not found");
    const contacts = rs().contacts.findBy("audience_id", audienceId);
    return c.json(
      resendList(
        contacts.map((ct) => ({
          id: ct.uuid,
          object: "contact",
          email: ct.email,
          first_name: ct.first_name,
          last_name: ct.last_name,
          unsubscribed: ct.unsubscribed,
          created_at: ct.created_at
        }))
      )
    );
  });
  app.delete("/audiences/:audience_id/contacts/:id", async (c) => {
    const audienceId = c.req.param("audience_id");
    const contactId = c.req.param("id");
    const contact = rs().contacts.findOneBy("uuid", contactId);
    if (!contact || contact.audience_id !== audienceId) {
      return resendError(c, 404, "not_found", "Contact not found");
    }
    rs().contacts.delete(contact.id);
    await webhooks.dispatch(
      "contact.deleted",
      void 0,
      { type: "contact.deleted", data: { id: contact.uuid, email: contact.email, audience_id: audienceId } },
      "resend"
    );
    return c.json({ object: "contact", id: contact.uuid, deleted: true });
  });
}
var SERVICE_LABEL = "Resend";
function inboxRoutes(ctx) {
  const { app, store } = ctx;
  const rs = () => getResendStore(store);
  app.get("/inbox", (c) => {
    const emails = rs().emails.all().reverse();
    let body = "";
    if (emails.length === 0) {
      body = `<div class="empty">No emails sent yet. Use POST /emails to send one.</div>`;
    } else {
      for (const email of emails) {
        const letter = (email.from?.[0] ?? "?").toUpperCase();
        const statusClass = email.status === "delivered" ? "badge-granted" : email.status === "bounced" ? "badge-denied" : "badge-requested";
        body += `<a href="/inbox/${escapeAttr(email.uuid)}" class="app-link">
  <span class="org-icon">${escapeHtml(letter)}</span>
  <span class="user-text">
    <span class="org-name">${escapeHtml(email.subject)}</span>
    <span class="user-meta">${escapeHtml(email.from)} &rarr; ${escapeHtml(email.to.join(", "))}</span>
  </span>
  <span class="badge ${statusClass}">${escapeHtml(email.status)}</span>
</a>`;
      }
    }
    const html = renderCardPage(
      "Inbox",
      `${emails.length} email${emails.length !== 1 ? "s" : ""} sent`,
      body,
      SERVICE_LABEL
    );
    return c.html(html);
  });
  app.get("/inbox/:id", (c) => {
    const id = c.req.param("id");
    const email = rs().emails.findOneBy("uuid", id);
    if (!email) {
      const html2 = renderCardPage(
        "Not Found",
        "The requested email was not found.",
        `<div class="empty">Email not found</div>`,
        SERVICE_LABEL
      );
      return c.html(html2, 404);
    }
    const statusClass = email.status === "delivered" ? "badge-granted" : email.status === "bounced" ? "badge-denied" : "badge-requested";
    let tagsHtml = "";
    if (email.tags.length > 0) {
      tagsHtml = `<div class="info-text">`;
      for (const tag of email.tags) {
        tagsHtml += `<span class="badge badge-requested">${escapeHtml(tag.name)}: ${escapeHtml(tag.value)}</span> `;
      }
      tagsHtml += `</div>`;
    }
    const recipientLines = [];
    recipientLines.push(`<strong>To:</strong> ${escapeHtml(email.to.join(", "))}`);
    if (email.cc.length > 0) {
      recipientLines.push(`<strong>Cc:</strong> ${escapeHtml(email.cc.join(", "))}`);
    }
    if (email.bcc.length > 0) {
      recipientLines.push(`<strong>Bcc:</strong> ${escapeHtml(email.bcc.join(", "))}`);
    }
    const srcdocHtml = email.html ? escapeAttr(`<base target="_blank">${email.html}`) : null;
    const previewContent = srcdocHtml ? `<iframe
  sandbox="allow-popups allow-popups-to-escape-sandbox"
  srcdoc="${srcdocHtml}"
  class="s-card"
  style="width:100%;min-height:300px;border:1px solid #0a3300;border-radius:8px;background:#fff;"
></iframe>` : email.text ? `<div class="s-card"><pre class="info-text">${escapeHtml(email.text)}</pre></div>` : `<div class="empty">No content</div>`;
    const body = `
<div class="org-row">
  <span class="badge ${statusClass}">${escapeHtml(email.status)}</span>
  <span class="user-meta">${escapeHtml(email.created_at)}</span>
</div>
<div class="s-card">
  <div class="perm-list">
    <li><strong>From:</strong> ${escapeHtml(email.from)}</li>
    ${recipientLines.map((line) => `<li>${line}</li>`).join("\n    ")}
  </div>
</div>
${tagsHtml}
<div class="section-heading">Preview</div>
${previewContent}
<div class="info-text">
  <strong>Last event:</strong> ${escapeHtml(email.last_event)}
  ${email.scheduled_at ? ` | <strong>Scheduled:</strong> ${escapeHtml(email.scheduled_at)}` : ""}
</div>`;
    const html = renderCardPage(email.subject, `Email ${escapeHtml(email.uuid)}`, body, SERVICE_LABEL);
    return c.html(html);
  });
}
function seedFromConfig(store, _baseUrl, config) {
  const rs = getResendStore(store);
  if (config.domains) {
    for (const d of config.domains) {
      const existing = rs.domains.findOneBy("name", d.name);
      if (existing) continue;
      const region = d.region ?? "us-east-1";
      rs.domains.insert({
        uuid: generateUuid(),
        name: d.name,
        status: "verified",
        region,
        records: [
          {
            record: "SPF",
            name: d.name,
            type: "MX",
            ttl: "Auto",
            status: "verified",
            value: `feedback-smtp.${region}.amazonses.com`,
            priority: 10
          },
          {
            record: "SPF",
            name: d.name,
            type: "TXT",
            ttl: "Auto",
            status: "verified",
            value: "v=spf1 include:amazonses.com ~all"
          },
          {
            record: "DKIM",
            name: `resend._domainkey.${d.name}`,
            type: "CNAME",
            ttl: "Auto",
            status: "verified",
            value: `resend.domainkey.${region}.amazonses.com`
          }
        ]
      });
    }
  }
  if (config.contacts) {
    let defaultAudience = rs.audiences.findOneBy("name", "Default");
    if (!defaultAudience) {
      defaultAudience = rs.audiences.insert({ uuid: generateUuid(), name: "Default" });
    }
    for (const ct of config.contacts) {
      let audienceId = defaultAudience.uuid;
      if (ct.audience) {
        let audience = rs.audiences.findOneBy("name", ct.audience);
        if (!audience) {
          audience = rs.audiences.insert({ uuid: generateUuid(), name: ct.audience });
        }
        audienceId = audience.uuid;
      }
      rs.contacts.insert({
        uuid: generateUuid(),
        audience_id: audienceId,
        email: ct.email,
        first_name: ct.first_name ?? null,
        last_name: ct.last_name ?? null,
        unsubscribed: false
      });
    }
  }
}
var resendPlugin = {
  name: "resend",
  register(app, store, webhooks, baseUrl, tokenMap) {
    const ctx = { app, store, webhooks, baseUrl, tokenMap };
    inboxRoutes(ctx);
    app.use("*", requireAuthWhen("EMULATE_RESEND_REQUIRE_AUTH", "EMULATE_REQUIRE_AUTH"));
    emailRoutes(ctx);
    domainRoutes(ctx);
    apiKeyRoutes(ctx);
    contactRoutes(ctx);
  },
  seed(_store, _baseUrl) {
  }
};
var index_default = resendPlugin;
export {
  index_default as default,
  getResendStore,
  resendPlugin,
  seedFromConfig
};
//# sourceMappingURL=dist-LCZCBSMN.js.map