259 lines
12 KiB
TypeScript
259 lines
12 KiB
TypeScript
import { randomBytes } from "node:crypto";
|
|
import { parseEnabledLocales } from "@hivegrid/i18n";
|
|
import { Hono, type Context } from "hono";
|
|
import type { ApiEnv } from "../api-types.js";
|
|
import { getApiRuntimeConfig } from "../config.js";
|
|
import { createOpenApiDocument } from "../openapi.js";
|
|
import { apiLogger } from "../logger.js";
|
|
import { escapeHtml } from "./shared.js";
|
|
import { checkCachedApiReadiness } from "../readiness-cache.js";
|
|
import { getApiDocsCopy } from "./api-docs-i18n.js";
|
|
|
|
function apiHealthResponse(c: Context<ApiEnv>) {
|
|
return c.json({
|
|
status: "ok",
|
|
service: "api",
|
|
revision: getApiRuntimeConfig().revision,
|
|
requestId: c.get("requestId"),
|
|
});
|
|
}
|
|
|
|
export function registerSystemRoutes(app: Hono<ApiEnv>) {
|
|
app.get("/healthz", apiHealthResponse);
|
|
app.get("/v1/health", apiHealthResponse);
|
|
|
|
app.get("/readyz", async (c) => {
|
|
try {
|
|
await checkCachedApiReadiness();
|
|
return c.json({
|
|
status: "ready",
|
|
service: "api",
|
|
revision: getApiRuntimeConfig().revision,
|
|
requestId: c.get("requestId"),
|
|
});
|
|
} catch (error) {
|
|
const code = error && typeof error === "object" && "code" in error && typeof error.code === "string" ? error.code : undefined;
|
|
apiLogger.error(
|
|
{ dependency: "database", error: { name: error instanceof Error ? error.name : "Error", ...(code ? { code } : {}) } },
|
|
"API readiness dependency unavailable"
|
|
);
|
|
return c.json(
|
|
{
|
|
status: "not_ready",
|
|
service: "api",
|
|
requestId: c.get("requestId"),
|
|
error: {
|
|
code: "dependency_unavailable",
|
|
message: "A required dependency is unavailable.",
|
|
},
|
|
},
|
|
503
|
|
);
|
|
}
|
|
});
|
|
|
|
app.get("/v1/openapi.json", (c) => {
|
|
return c.json(createOpenApiDocument(getApiRuntimeConfig()));
|
|
});
|
|
|
|
app.get("/v1/docs", (c) => {
|
|
const runtimeConfig = getApiRuntimeConfig();
|
|
const appName = runtimeConfig.appName;
|
|
const enabledLocales = parseEnabledLocales(process.env.I18N_ENABLED_LOCALES, {
|
|
allowReviewLocales: runtimeConfig.nodeEnv !== "production" || process.env.SENTRY_ENVIRONMENT?.trim().toLowerCase() === "staging",
|
|
});
|
|
const { locale, copy } = getApiDocsCopy(c.req.header("accept-language"), enabledLocales);
|
|
const browserCopy = JSON.stringify(copy).replaceAll("<", "\\u003c");
|
|
const nonce = randomBytes(18).toString("base64url");
|
|
c.header("cache-control", "no-store");
|
|
c.header("content-language", locale);
|
|
c.header(
|
|
"content-security-policy",
|
|
[
|
|
"default-src 'none'",
|
|
"base-uri 'none'",
|
|
"connect-src 'self'",
|
|
"font-src 'self'",
|
|
"form-action 'none'",
|
|
"frame-ancestors 'none'",
|
|
"img-src 'self' data:",
|
|
`script-src 'nonce-${nonce}' 'strict-dynamic'`,
|
|
"script-src-attr 'none'",
|
|
`style-src 'nonce-${nonce}'`,
|
|
"style-src-attr 'none'",
|
|
].join("; ")
|
|
);
|
|
|
|
return c.html(`<!doctype html>
|
|
<html lang="${locale}">
|
|
<head>
|
|
<meta charset="utf-8">
|
|
<title>${escapeHtml(copy.pageTitle)} | ${escapeHtml(appName)}</title>
|
|
<meta property="og:title" content="${escapeHtml(copy.pageTitle)} | ${escapeHtml(appName)}">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
<style nonce="${nonce}">
|
|
:root { color-scheme: dark; }
|
|
body { margin: 0; background: #0f172a; color: #e2e8f0; font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; }
|
|
header { border-bottom: 1px solid #334155; padding: 20px 24px; }
|
|
main { display: grid; grid-template-columns: minmax(220px, 320px) minmax(0, 1fr); gap: 24px; padding: 24px; }
|
|
a { color: #93c5fd; }
|
|
button { border: 1px solid #475569; border-radius: 8px; background: #1e293b; color: #e2e8f0; cursor: pointer; font: inherit; padding: 8px 10px; text-align: left; }
|
|
button:hover, button[aria-current="true"] { border-color: #38bdf8; background: #0c4a6e; }
|
|
code, pre { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace; }
|
|
pre { margin: 0; overflow: auto; border: 1px solid #334155; border-radius: 8px; background: #020617; padding: 16px; line-height: 1.5; }
|
|
.toolbar { display: flex; align-items: center; gap: 16px; flex-wrap: wrap; }
|
|
.muted { color: #94a3b8; }
|
|
.nav { display: grid; gap: 8px; align-content: start; }
|
|
.operation { border: 1px solid #334155; border-radius: 8px; background: #111827; overflow: hidden; }
|
|
.operation-header { display: flex; align-items: center; gap: 10px; border-bottom: 1px solid #334155; padding: 14px 16px; }
|
|
.method { border-radius: 999px; background: #0284c7; color: white; font-size: 12px; font-weight: 700; letter-spacing: .04em; padding: 4px 8px; }
|
|
.path { font-size: 18px; font-weight: 700; }
|
|
.section { padding: 16px; }
|
|
.grid { display: grid; gap: 10px; }
|
|
.row { display: grid; grid-template-columns: 180px minmax(0, 1fr); gap: 12px; border-top: 1px solid #1f2937; padding-top: 10px; }
|
|
.row:first-child { border-top: 0; padding-top: 0; }
|
|
.badge { display: inline-flex; width: fit-content; border-radius: 999px; background: #1e293b; color: #bae6fd; padding: 2px 8px; font-size: 12px; }
|
|
.try-grid { display: grid; gap: 10px; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) auto; align-items: end; }
|
|
label { display: grid; gap: 6px; color: #cbd5e1; font-size: 13px; }
|
|
input { border: 1px solid #475569; border-radius: 8px; background: #020617; color: #e2e8f0; font: inherit; padding: 9px 10px; }
|
|
#try-result { min-height: 120px; }
|
|
#raw-panel { margin-top: 16px; }
|
|
@media (max-width: 780px) { main { grid-template-columns: 1fr; } .row, .try-grid { grid-template-columns: 1fr; } }
|
|
</style>
|
|
</head>
|
|
<body>
|
|
<header>
|
|
<h1>${escapeHtml(copy.heading)}</h1>
|
|
<div class="toolbar">
|
|
<span class="muted">${escapeHtml(copy.description)}</span>
|
|
<a href="/v1/openapi.json">OpenAPI JSON</a>
|
|
</div>
|
|
</header>
|
|
<main>
|
|
<nav class="nav" id="operation-nav" aria-label="${escapeHtml(copy.operationsLabel)}">
|
|
<span class="muted">${escapeHtml(copy.loadingSpec)}</span>
|
|
</nav>
|
|
<section>
|
|
<div id="operation-detail" class="operation"></div>
|
|
<details id="raw-panel">
|
|
<summary>${escapeHtml(copy.rawSpec)}</summary>
|
|
<pre id="openapi-json"></pre>
|
|
</details>
|
|
</section>
|
|
</main>
|
|
<script nonce="${nonce}">
|
|
const copy = ${browserCopy};
|
|
const nav = document.getElementById("operation-nav");
|
|
const detail = document.getElementById("operation-detail");
|
|
const raw = document.getElementById("openapi-json");
|
|
let currentEntry = null;
|
|
|
|
function escapeText(value) {
|
|
return String(value ?? "").replace(/[&<>"']/g, (character) => ({
|
|
"&": "&",
|
|
"<": "<",
|
|
">": ">",
|
|
'"': """,
|
|
"'": "'",
|
|
}[character]));
|
|
}
|
|
|
|
function operationEntries(spec) {
|
|
return Object.entries(spec.paths ?? {}).flatMap(([path, pathItem]) =>
|
|
Object.entries(pathItem ?? {})
|
|
.filter(([method]) => ["get", "post", "put", "patch", "delete"].includes(method))
|
|
.map(([method, operation]) => ({ path, method: method.toUpperCase(), operation }))
|
|
);
|
|
}
|
|
|
|
function renderNav(entries) {
|
|
nav.innerHTML = "";
|
|
for (const entry of entries) {
|
|
const button = document.createElement("button");
|
|
button.type = "button";
|
|
button.dataset.path = entry.path;
|
|
button.dataset.method = entry.method;
|
|
button.innerHTML = '<span class="method">' + escapeText(entry.method) + '</span> ' + escapeText(entry.path);
|
|
button.addEventListener("click", () => renderOperation(entry, button));
|
|
nav.appendChild(button);
|
|
}
|
|
}
|
|
|
|
function renderOperation(entry, activeButton) {
|
|
currentEntry = entry;
|
|
for (const button of nav.querySelectorAll("button")) {
|
|
button.removeAttribute("aria-current");
|
|
}
|
|
activeButton?.setAttribute("aria-current", "true");
|
|
const parameters = entry.operation.parameters ?? [];
|
|
const responses = Object.entries(entry.operation.responses ?? {});
|
|
detail.innerHTML = '<div class="operation-header"><span class="method">' + escapeText(entry.method) + '</span><span class="path">' + escapeText(entry.path) + '</span></div>'
|
|
+ '<div class="section grid">'
|
|
+ '<span class="badge">' + escapeText(entry.operation.operationId ?? copy.operationFallback) + '</span>'
|
|
+ '<p>' + escapeText(entry.operation.description ?? copy.noDescription) + '</p>'
|
|
+ '<h2>' + escapeText(copy.parameters) + '</h2>'
|
|
+ (parameters.length ? parameters.map((parameter) => '<div class="row"><code>' + escapeText(parameter.in) + ' ' + escapeText(parameter.name) + '</code><span>' + escapeText(parameter.description ?? "") + '</span></div>').join("") : '<p class="muted">' + escapeText(copy.noParameters) + '</p>')
|
|
+ '<h2>' + escapeText(copy.responses) + '</h2>'
|
|
+ (responses.length ? responses.map(([status, response]) => '<div class="row"><code>' + escapeText(status) + '</code><span>' + escapeText(response.description ?? "") + '</span></div>').join("") : '<p class="muted">' + escapeText(copy.noResponses) + '</p>')
|
|
+ '<h2>' + escapeText(copy.tryRequest) + '</h2>'
|
|
+ '<div class="try-grid">'
|
|
+ '<label>' + escapeText(copy.apiKeyLabel) + '<input id="try-api-key" type="password" autocomplete="off" placeholder="' + escapeText(copy.apiKeyPlaceholder) + '"></label>'
|
|
+ '<label>' + escapeText(copy.queryLabel) + '<input id="try-query" type="text" placeholder="' + escapeText(copy.queryPlaceholder) + '"></label>'
|
|
+ '<button id="try-button" type="button">' + escapeText(copy.sendRequest) + '</button>'
|
|
+ '</div>'
|
|
+ '<pre id="try-result" aria-live="polite">' + escapeText(copy.responsePlaceholder) + '</pre>'
|
|
+ '</div>';
|
|
document.getElementById("try-button")?.addEventListener("click", sendTryRequest);
|
|
}
|
|
|
|
function buildTryRequestUrl(entry) {
|
|
const query = document.getElementById("try-query")?.value.trim() ?? "";
|
|
if (!query) {
|
|
return entry.path;
|
|
}
|
|
return entry.path + (query.startsWith("?") ? query : "?" + query);
|
|
}
|
|
|
|
function sendTryRequest() {
|
|
if (!currentEntry) {
|
|
return;
|
|
}
|
|
const result = document.getElementById("try-result");
|
|
const apiKey = document.getElementById("try-api-key")?.value.trim() ?? "";
|
|
result.textContent = copy.loading;
|
|
fetch(buildTryRequestUrl(currentEntry), {
|
|
method: currentEntry.method,
|
|
headers: apiKey ? { "x-api-key": apiKey } : {},
|
|
})
|
|
.then(async (response) => {
|
|
const text = await response.text();
|
|
try {
|
|
result.textContent = response.status + " " + response.statusText + "\\n" + JSON.stringify(JSON.parse(text), null, 2);
|
|
} catch {
|
|
result.textContent = response.status + " " + response.statusText + "\\n" + text;
|
|
}
|
|
})
|
|
.catch((error) => {
|
|
result.textContent = error.message;
|
|
});
|
|
}
|
|
|
|
fetch("/v1/openapi.json")
|
|
.then((response) => response.json())
|
|
.then((spec) => {
|
|
const entries = operationEntries(spec);
|
|
raw.textContent = JSON.stringify(spec, null, 2);
|
|
renderNav(entries);
|
|
if (entries[0]) {
|
|
renderOperation(entries[0], nav.querySelector("button"));
|
|
}
|
|
})
|
|
.catch((error) => {
|
|
nav.innerHTML = '<span class="muted">' + escapeText(error.message) + '</span>';
|
|
});
|
|
</script>
|
|
</body>
|
|
</html>`);
|
|
});
|
|
}
|