Skip to content

🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.

feat(docs): enhance documentation workflow and add agent readiness tests

Bill Yang04da28fbc770
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index 071e81dde..b78a5e350 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -8,7 +8,6 @@ on:
branches:
- master
paths-ignore:
- - "docs/**"
- "**.md"
# A newer push to the same branch makes an in-flight run obsolete.
@@ -23,6 +22,34 @@ env:
TZ: UTC
jobs:
+ docs:
+ name: Docs and agent HTTP
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 24
+ cache: npm
+ cache-dependency-path: docs/package-lock.json
+
+ - name: Install docs dependencies
+ working-directory: docs
+ run: npm ci
+
+ - name: Run agent-readiness tests
+ working-directory: docs
+ run: npm run test:agent-readiness
+
+ - name: Build docs
+ working-directory: docs
+ run: npm run build
+
+ - name: Verify production HTTP behavior
+ working-directory: docs
+ run: npm run test:agent-http
+
server:
name: Server
runs-on: ubuntu-latest
diff --git a/docs/package-lock.json b/docs/package-lock.json
index adb95b081..9882e8d9c 100644
--- a/docs/package-lock.json
+++ b/docs/package-lock.json
@@ -31,6 +31,7 @@
"next": "^16.2.9",
"next-intl": "^4.13.0",
"next-themes": "^0.4.6",
+ "parse5": "^7.3.0",
"react": "^19.2.7",
"react-dom": "^19.2.7",
"react-easy-crop": "^6.0.2",
@@ -49,6 +50,7 @@
"@types/react-dom": "^19.2.2",
"eslint": "^9.39.4",
"eslint-config-next": "16.2.9",
+ "jiti": "^2.7.0",
"postcss": "^8.5.15",
"tailwindcss": "^4.3.1",
"typescript": "^6.0.3"
diff --git a/docs/package.json b/docs/package.json
index 2d16e09a9..e315d91d7 100644
--- a/docs/package.json
+++ b/docs/package.json
@@ -3,9 +3,11 @@
"version": "0.0.0",
"private": true,
"scripts": {
- "build": "next build",
+ "build": "next build --webpack",
"dev": "next dev --turbo --port 3003",
"start": "next start",
+ "test:agent-readiness": "jiti src/lib/agent-readiness.test.ts",
+ "test:agent-http": "node scripts/test-agent-http.mjs",
"postinstall": "fumadocs-mdx",
"extract": "node scripts/extract-messages.mjs"
},
@@ -32,6 +34,7 @@
"next": "^16.2.9",
"next-intl": "^4.13.0",
"next-themes": "^0.4.6",
+ "parse5": "^7.3.0",
"react": "^19.2.7",
"react-dom": "^19.2.7",
"react-easy-crop": "^6.0.2",
@@ -50,6 +53,7 @@
"@types/react-dom": "^19.2.2",
"eslint": "^9.39.4",
"eslint-config-next": "16.2.9",
+ "jiti": "^2.7.0",
"postcss": "^8.5.15",
"tailwindcss": "^4.3.1",
"typescript": "^6.0.3"
diff --git a/docs/scripts/test-agent-http.mjs b/docs/scripts/test-agent-http.mjs
new file mode 100644
index 000000000..b689de694
--- /dev/null
+++ b/docs/scripts/test-agent-http.mjs
@@ -0,0 +1,202 @@
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { readFileSync } from "node:fs";
+import { createServer } from "node:http";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const docsRoot = dirname(dirname(fileURLToPath(import.meta.url)));
+const nextBin = join(docsRoot, "node_modules/next/dist/bin/next");
+
+async function availablePort() {
+ const server = createServer();
+ await new Promise((resolve, reject) => server.listen(0, "127.0.0.1", resolve).once("error", reject));
+ const address = server.address();
+ assert.ok(address && typeof address === "object");
+ await new Promise(resolve => server.close(resolve));
+ return address.port;
+}
+
+async function waitForServer(origin, child) {
+ for (let attempt = 0; attempt < 100; attempt += 1) {
+ if (child.exitCode !== null) throw new Error(`Next server exited with code ${child.exitCode}`);
+ try {
+ const response = await fetch(`${origin}/robots.txt`);
+ if (response.ok) return;
+ } catch {}
+ await new Promise(resolve => setTimeout(resolve, 100));
+ }
+ throw new Error("Timed out waiting for the Next production server.");
+}
+
+async function stop(child) {
+ if (child.exitCode !== null) return;
+ child.kill("SIGTERM");
+ await new Promise(resolve => {
+ const timer = setTimeout(() => {
+ if (child.exitCode === null) {
+ child.kill("SIGKILL");
+ }
+ resolve();
+ }, 5_000);
+ child.once("exit", () => {
+ clearTimeout(timer);
+ resolve();
+ });
+ });
+}
+
+const port = await availablePort();
+const origin = `http://localhost:${port}`;
+let victimHits = 0;
+const victim = createServer((_request, response) => {
+ victimHits += 1;
+ response.writeHead(200, { "Content-Type": "text/html" });
+ response.end("<main><h1>Internal secret</h1><p>Do not expose this response.</p></main>");
+});
+await new Promise((resolve, reject) => victim.listen(0, "127.0.0.1", resolve).once("error", reject));
+const victimAddress = victim.address();
+assert.ok(victimAddress && typeof victimAddress === "object");
+
+const child = spawn(process.execPath, [nextBin, "start", "--hostname", "localhost", "--port", String(port)], {
+ cwd: docsRoot,
+ env: { ...process.env, NEXT_TELEMETRY_DISABLED: "1" },
+ stdio: ["ignore", "pipe", "pipe"],
+});
+let serverOutput = "";
+child.stdout.on("data", chunk => (serverOutput += chunk));
+child.stderr.on("data", chunk => (serverOutput += chunk));
+
+try {
+ await waitForServer(origin, child);
+
+ const html = await fetch(`${origin}/`, { headers: { Accept: "text/html" }, redirect: "manual" });
+ assert.equal(html.status, 200);
+ const htmlVary = html.headers.get("vary") ?? "";
+ const htmlCacheControl = html.headers.get("cache-control") ?? "";
+ const htmlBody = await html.text();
+ assert.ok(htmlBody.length >= 500, "The server-rendered homepage must contain substantial raw HTML.");
+ assert.match(htmlBody, /<h1(?:\s|>)/i);
+ assert.match(htmlBody, /<h2(?:\s|>)/i);
+ assert.match(htmlBody, /<h3(?:\s|>)/i);
+ assert.ok(
+ /(?:^|,)\s*Accept\s*(?:,|$)/i.test(htmlVary) || /(?:private|no-store)/i.test(htmlCacheControl),
+ "The local HTML variant must either vary on Accept or be unavailable to shared caches."
+ );
+
+ const vercelConfig = JSON.parse(readFileSync(join(docsRoot, "vercel.json"), "utf8"));
+ const deployedVary = vercelConfig.headers?.[0]?.headers?.find(header => header.key.toLowerCase() === "vary")?.value;
+ for (const token of [
+ "Accept",
+ "Accept-Encoding",
+ "RSC",
+ "Next-Router-State-Tree",
+ "Next-Router-Prefetch",
+ "Next-Router-Segment-Prefetch",
+ ]) {
+ assert.match(deployedVary ?? "", new RegExp(`(?:^|,)\\s*${token}\\s*(?:,|$)`, "i"));
+ }
+
+ const markdown = await fetch(`${origin}/`, { headers: { Accept: "text/markdown" } });
+ assert.equal(markdown.status, 200);
+ assert.match(markdown.headers.get("content-type") ?? "", /^text\/markdown/);
+ assert.match(markdown.headers.get("vary") ?? "", /(?:^|,)\s*Accept\s*(?:,|$)/i);
+ assert.match(await markdown.text(), /^# Rybbit/m);
+
+ const markdownHead = await fetch(`${origin}/`, { method: "HEAD", headers: { Accept: "text/markdown" } });
+ assert.equal(markdownHead.status, 200);
+ assert.match(markdownHead.headers.get("content-type") ?? "", /^text\/markdown/);
+ assert.equal(await markdownHead.text(), "");
+
+ const docsMarkdown = await fetch(`${origin}/docs/api/getting-started`, {
+ headers: { Accept: "text/markdown" },
+ });
+ assert.equal(docsMarkdown.status, 200);
+ assert.match(docsMarkdown.headers.get("content-type") ?? "", /^text\/markdown/);
+ assert.match(await docsMarkdown.text(), /^# /m);
+
+ const unacceptable = await fetch(`${origin}/`, { headers: { Accept: "application/pdf" } });
+ assert.equal(unacceptable.status, 406);
+ assert.match(unacceptable.headers.get("vary") ?? "", /(?:^|,)\s*Accept\s*(?:,|$)/i);
+
+ const hostilePath = `//127.0.0.1:${victimAddress.port}/internal`;
+ const ssrf = await fetch(`${origin}/api/agent/markdown?path=${encodeURIComponent(hostilePath)}`);
+ assert.equal(ssrf.status, 400);
+ assert.match(ssrf.headers.get("content-type") ?? "", /^application\/json/);
+ assert.equal((await ssrf.json()).code, "INVALID_MARKDOWN_PATH");
+ assert.equal(victimHits, 0);
+
+ const newline = await fetch(`${origin}/api/agent/markdown?path=${encodeURIComponent("/bad\npath")}`);
+ assert.equal(newline.status, 400);
+ assert.equal((await newline.json()).code, "INVALID_MARKDOWN_PATH");
+
+ const recursive = await fetch(
+ `${origin}/api/agent/markdown?path=${encodeURIComponent("/api/agent/markdown")}`
+ );
+ assert.equal(recursive.status, 400);
+ assert.equal((await recursive.json()).code, "INVALID_MARKDOWN_PATH");
+
+ const redirect = await fetch(`${origin}/tools/instagram-logo-generator`, {
+ headers: { Accept: "text/markdown" },
+ redirect: "manual",
+ });
+ assert.equal(redirect.status, 308);
+ assert.equal(new URL(redirect.headers.get("location"), origin).pathname, "/tools");
+
+ const missing = await fetch(`${origin}/agent-http-test-missing`, {
+ headers: { Accept: "text/markdown" },
+ });
+ assert.equal(missing.status, 404);
+ assert.match(await missing.text(), /^# Page not found/m);
+
+ const htmlMissing = await fetch(`${origin}/agent-http-test-missing`, {
+ headers: { Accept: "text/html" },
+ redirect: "manual",
+ });
+ assert.equal(htmlMissing.status, 404);
+ assert.match(await htmlMissing.text(), /Page not found/);
+
+ const openapi = await fetch(`${origin}/openapi.json`);
+ assert.equal(openapi.status, 200);
+ assert.match(openapi.headers.get("content-type") ?? "", /^application\/json/);
+ const openapiDocument = await openapi.json();
+ assert.equal(openapiDocument.openapi, "3.1.1");
+
+ const openapiAlias = await fetch(`${origin}/api/openapi.json`);
+ assert.equal(openapiAlias.status, 200);
+ assert.deepEqual(await openapiAlias.json(), openapiDocument);
+
+ const openapiHead = await fetch(`${origin}/openapi.json`, { method: "HEAD" });
+ assert.equal(openapiHead.status, 200);
+ assert.match(openapiHead.headers.get("content-type") ?? "", /^application\/json/);
+ assert.equal(await openapiHead.text(), "");
+
+ const llms = await fetch(`${origin}/llms.txt`);
+ assert.equal(llms.status, 200);
+ assert.match(llms.headers.get("content-type") ?? "", /^text\/plain/);
+ assert.match(await llms.text(), /OpenAPI specification/);
+
+ const llmsFull = await fetch(`${origin}/llms-full.txt`);
+ assert.equal(llmsFull.status, 200);
+ assert.match(llmsFull.headers.get("content-type") ?? "", /^text\/plain/);
+
+ const sitemap = await fetch(`${origin}/sitemap.xml`);
+ assert.equal(sitemap.status, 200);
+ assert.match(sitemap.headers.get("content-type") ?? "", /xml/);
+
+ const robots = await fetch(`${origin}/robots.txt`);
+ assert.equal(robots.status, 200);
+ assert.match(await robots.text(), /Allow: \/api\/openapi\.json/);
+
+ const apiMissing = await fetch(`${origin}/api/agent-http-test-missing`);
+ assert.equal(apiMissing.status, 404);
+ assert.equal((await apiMissing.json()).code, "API_ROUTE_NOT_FOUND");
+
+ console.log("Agent HTTP integration checks passed.");
+} catch (error) {
+ if (serverOutput) console.error(serverOutput);
+ throw error;
+} finally {
+ await stop(child);
+ await new Promise(resolve => victim.close(resolve));
+}
diff --git a/docs/src/app/api/[[...path]]/route.ts b/docs/src/app/api/[[...path]]/route.ts
new file mode 100644
index 000000000..c9eec884d
--- /dev/null
+++ b/docs/src/app/api/[[...path]]/route.ts
@@ -0,0 +1,22 @@
+import { createApiError, jsonError } from "@/lib/api-error";
+
+interface RouteContext {
+ params: Promise<{ path?: string[] }>;
+}
+
+async function notFound(request: Request, context: RouteContext): Promise<Response> {
+ const { path = [] } = await context.params;
+ const pathname = `/api/${path.join("/")}`.replace(/\/$/, "") || "/api";
+
+ return jsonError(
+ 404,
+ createApiError({
+ code: "API_ROUTE_NOT_FOUND",
+ message: `No API route matches ${request.method} ${pathname}.`,
+ resolution: "Read https://rybbit.com/openapi.json and choose a documented operation.",
+ details: { method: request.method, path: pathname },
+ })
+ );
+}
+
+export { notFound as DELETE, notFound as GET, notFound as PATCH, notFound as POST, notFound as PUT };
diff --git a/docs/src/app/api/agent/markdown/route.ts b/docs/src/app/api/agent/markdown/route.ts
new file mode 100644
index 000000000..8b81499d5
--- /dev/null
+++ b/docs/src/app/api/agent/markdown/route.ts
@@ -0,0 +1,112 @@
+import { getLLMText } from "@/lib/get-llm-text";
+import {
+ getMarkdownRepresentation,
+ isSafeMarkdownPath,
+ markdownResponse,
+ markdownSourceUrl,
+} from "@/lib/agent-markdown";
+import { createApiError, jsonError } from "@/lib/api-error";
+import { source } from "@/lib/source";
+
+export const runtime = "nodejs";
+
+const supportedLocales = new Set(["en", "de", "fr", "zh", "es", "pl", "it", "ko", "pt", "ja"]);
+
+function validConfiguredOrigin(value: string | undefined): string | undefined {
+ if (!value) return undefined;
+ try {
+ const url = new URL(value.startsWith("http://") || value.startsWith("https://") ? value : `https://${value}`);
+ if (url.protocol !== "http:" && url.protocol !== "https:") return undefined;
+ return url.origin;
+ } catch {
+ return undefined;
+ }
+}
+
+function sourceOrigin(requestUrl: URL): string {
+ const hostname = requestUrl.hostname.toLowerCase();
+ // Self-hosted deployments can opt in to their own trusted rendering origin.
+ // Unrecognised Host headers deliberately fall back to the public site.
+ const configured = validConfiguredOrigin(process.env.RYBBIT_SITE_ORIGIN);
+ if (configured) return configured;
+
+ if (hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1") {
+ return requestUrl.origin;
+ }
+
+ if (hostname === "rybbit.com" || hostname === "www.rybbit.com") return requestUrl.origin;
+
+ const vercelHostname = validConfiguredOrigin(process.env.VERCEL_URL);
+ if (vercelHostname && hostname === new URL(vercelHostname).hostname.toLowerCase()) return requestUrl.origin;
+
+ return "https://rybbit.com";
+}
+
+function docsSlug(pathname: string): string[] | undefined {
+ const segments = pathname.split("/").filter(Boolean);
+ if (supportedLocales.has(segments[0])) segments.shift();
+ if (segments[0] !== "docs") return undefined;
+ return segments.slice(1);
+}
+
+async function markdownRequest(request: Request): Promise<Response> {
+ const requestUrl = new URL(request.url);
+ const pathname = request.headers.get("X-Rybbit-Markdown-Path") || requestUrl.searchParams.get("path") || "/";
+ const originalSearch = request.headers.get("X-Rybbit-Markdown-Query") || requestUrl.searchParams.get("query") || "";
+ if (!isSafeMarkdownPath(pathname)) {
+ return jsonError(
+ 400,
+ createApiError({
+ code: "INVALID_MARKDOWN_PATH",
+ message: "The Markdown source path is invalid.",
+ resolution: "Provide a root-relative website path such as /docs.",
+ })
+ );
+ }
+
+ let sourceUrl: URL;
+ try {
+ sourceUrl = markdownSourceUrl(sourceOrigin(requestUrl), pathname, originalSearch);
+ } catch {
+ return jsonError(
+ 400,
+ createApiError({
+ code: "INVALID_MARKDOWN_TARGET",
+ message: "The Markdown source path or query is invalid.",
+ resolution: "Provide a valid root-relative website path and query.",
+ })
+ );
+ }
+
+ const slug = docsSlug(pathname);
+
+ if (slug) {
+ const page = source.getPage(slug);
+ if (page) {
+ return markdownResponse(await getLLMText(page), 200, {
+ "Cache-Control": "public, s-maxage=3600, stale-while-revalidate=86400",
+ "Content-Location": pathname,
+ });
+ }
+ }
+
+ return getMarkdownRepresentation(pathname, async () => {
+ return fetch(sourceUrl, {
+ headers: {
+ Accept: "text/html",
+ "X-Rybbit-Markdown-Source": "1",
+ },
+ redirect: "manual",
+ signal: AbortSignal.timeout(10_000),
+ });
+ });
+}
+
+export async function GET(request: Request) {
+ return markdownRequest(request);
+}
+
+export async function HEAD(request: Request) {
+ const response = await markdownRequest(request);
+ return new Response(null, response);
+}
diff --git a/docs/src/app/api/openapi.json/route.ts b/docs/src/app/api/openapi.json/route.ts
new file mode 100644
index 000000000..2a1e81275
--- /dev/null
+++ b/docs/src/app/api/openapi.json/route.ts
@@ -0,0 +1,12 @@
+import { openApiResponse } from "@/lib/openapi";
+
+export const dynamic = "force-static";
+export const revalidate = false;
+
+export function GET() {
+ return openApiResponse();
+}
+
+export function HEAD() {
+ return openApiResponse(false);
+}
diff --git a/docs/src/app/llms.txt/route.ts b/docs/src/app/llms.txt/route.ts
index 67a88083b..856eff621 100644
--- a/docs/src/app/llms.txt/route.ts
+++ b/docs/src/app/llms.txt/route.ts
@@ -1,13 +1,29 @@
-import { source } from '@/lib/source';
-import { llms } from 'fumadocs-core/source';
+import { source } from "@/lib/source";
+import { llms } from "fumadocs-core/source";
// cached forever
export const revalidate = false;
export function GET() {
- return new Response(llms(source).index(), {
+ const navigation = `# Rybbit
+
+> Open-source, cookieless web and product analytics.
+
+## Machine-readable resources
+
+- [OpenAPI specification](https://rybbit.com/openapi.json): Complete discoverable REST API surface
+- [Sitemap](https://rybbit.com/sitemap.xml): Public website URL index
+- [Full documentation](https://rybbit.com/llms-full.txt): Documentation in one text response
+- [API getting started](https://rybbit.com/docs/api/getting-started): Authentication, time ranges, filters, and rate limits
+
+## Documentation index
+
+`;
+
+ return new Response(`${navigation}${llms(source).index()}`, {
headers: {
- 'Content-Type': 'text/plain; charset=utf-8',
+ "Content-Type": "text/plain; charset=utf-8",
+ "X-Content-Type-Options": "nosniff",
},
});
}
diff --git a/docs/src/app/not-found.tsx b/docs/src/app/not-found.tsx
new file mode 100644
index 000000000..6931b5a76
--- /dev/null
+++ b/docs/src/app/not-found.tsx
@@ -0,0 +1,47 @@
+import type { Metadata } from "next";
+import Link from "next/link";
+
+export const metadata: Metadata = {
+ title: "Page not found",
+ description: "The requested page does not exist. Use the Rybbit sitemap, documentation, or agent index to continue.",
+ robots: { index: false, follow: true },
+};
+
+const recoveryLinks = [
+ { href: "/docs", label: "Documentation" },
+ { href: "/sitemap.xml", label: "Sitemap" },
+ { href: "/llms.txt", label: "Agent index" },
+ { href: "/openapi.json", label: "API specification" },
+];
+
+export default function NotFound() {
+ return (
+ <main className="flex min-h-screen items-center justify-center bg-white px-5 text-neutral-950 dark:bg-neutral-950 dark:text-neutral-50">
+ <section className="w-full max-w-2xl border-y border-neutral-200 py-12 dark:border-neutral-800 sm:py-16">
+ <p className="text-sm font-medium text-neutral-500 dark:text-neutral-400">404</p>
+ <h1 className="mt-3 text-4xl font-semibold tracking-[-0.035em] text-balance sm:text-5xl">Page not found</h1>
+ <p className="mt-5 max-w-xl text-base leading-7 text-neutral-600 dark:text-neutral-300">
+ The requested path does not exist on Rybbit. Try the documentation or use one of the machine-readable indexes
+ below to find the right page.
+ </p>
+ <nav className="mt-8 flex flex-wrap gap-x-6 gap-y-3" aria-label="404 recovery links">
+ {recoveryLinks.map(link => (
+ <a
+ key={link.href}
+ href={link.href}
+ className="text-sm font-medium text-emerald-700 underline decoration-emerald-300 underline-offset-4 transition-colors hover:text-emerald-600 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-500 dark:text-emerald-400 dark:decoration-emerald-800 dark:hover:text-emerald-300"
+ >
+ {link.label}
+ </a>
+ ))}
+ </nav>
+ <Link
+ href="/"
+ className="mt-10 inline-flex h-9 items-center justify-center rounded-md bg-emerald-600 px-4 text-sm font-medium text-white transition-colors hover:bg-emerald-500 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-500 focus-visible:ring-offset-2 focus-visible:ring-offset-white dark:focus-visible:ring-offset-neutral-950"
+ >
+ Return home
+ </Link>
+ </section>
+ </main>
+ );
+}
diff --git a/docs/src/app/openapi.json/route.ts b/docs/src/app/openapi.json/route.ts
new file mode 100644
index 000000000..2a1e81275
--- /dev/null
+++ b/docs/src/app/openapi.json/route.ts
@@ -0,0 +1,12 @@
+import { openApiResponse } from "@/lib/openapi";
+
+export const dynamic = "force-static";
+export const revalidate = false;
+
+export function GET() {
+ return openApiResponse();
+}
+
+export function HEAD() {
+ return openApiResponse(false);
+}
diff --git a/docs/src/app/robots.ts b/docs/src/app/robots.ts
index f3d4813fa..91b4e5e38 100644
--- a/docs/src/app/robots.ts
+++ b/docs/src/app/robots.ts
@@ -7,7 +7,7 @@ export default function robots(): MetadataRoute.Robots {
rules: [
{
userAgent: "*",
- allow: "/",
+ allow: ["/", "/openapi.json", "/api/openapi.json", "/llms.txt", "/llms-full.txt", "/sitemap.xml"],
disallow: [
"/api/",
"/_next/",
diff --git a/docs/src/lib/agent-markdown.ts b/docs/src/lib/agent-markdown.ts
new file mode 100644
index 000000000..a964fc852
--- /dev/null
+++ b/docs/src/lib/agent-markdown.ts
@@ -0,0 +1,308 @@
+import { parse, type DefaultTreeAdapterMap } from "parse5";
+
+import { appendVary } from "./content-negotiation";
+
+type HtmlNode = DefaultTreeAdapterMap["node"];
+type HtmlElement = DefaultTreeAdapterMap["element"];
+
+const SITE_ORIGIN = "https://rybbit.com";
+const MAX_MARKDOWN_SOURCE_BYTES = 2_000_000;
+const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
+
+export const homepageMarkdown = `# Rybbit
+
+Rybbit is an open-source, cookieless web and product analytics platform. It replaces Google Analytics with one readable dashboard and a lightweight 18 KB tracking script. Rybbit is designed for privacy-conscious teams: no cookies, no consent banner, GDPR and CCPA compliant, and available as managed EU-hosted cloud or a self-hosted deployment.
+
+## What Rybbit helps you understand
+
+### Web and product analytics
+
+Measure pageviews, sessions, users, bounce rate, traffic sources, campaigns, countries, devices, and live visitors. Autocapture can record clicks, form submissions, copied text, outbound links, and browser errors without requiring separate instrumentation for every interaction.
+
+### Behavior and conversion
+
+Use session replay to watch the visits behind the numbers, user journeys to see common navigation paths, funnels to locate conversion drop-off, goals to track outcomes, and retention reports to understand whether people return. User profiles connect identified users with their sessions and events.
+
+### Performance and reliability
+
+Rybbit records Core Web Vitals from real visits and breaks performance down by route, country, browser, operating system, and device. Error tracking connects JavaScript failures to affected sessions so teams can move from a trend to the visits that explain it.
+
+## Built for people and agents
+
+Rybbit exposes a REST API and a hosted MCP server. Agents can read analytics, investigate errors and funnels, and manage goals with the same permissions as a teammate. API requests use a Bearer token, and the published OpenAPI document describes the available operations.
+
+## Start here
+
+- [Documentation](${SITE_ORIGIN}/docs)
+- [API documentation](${SITE_ORIGIN}/docs/api/getting-started)
+- [OpenAPI specification](${SITE_ORIGIN}/openapi.json)
+- [MCP setup](${SITE_ORIGIN}/docs/mcp)
+- [Pricing](${SITE_ORIGIN}/pricing)
+- [Live demo](https://demo.rybbit.com)
+- [Source code](https://github.com/rybbit-io/rybbit)
+- [Sitemap](${SITE_ORIGIN}/sitemap.xml)
+- [Full agent documentation](${SITE_ORIGIN}/llms-full.txt)
+`;
+
+const notFoundMarkdown = `# Page not found
+
+The requested path does not exist on Rybbit.
+
+## Where to look next
+
+- [Rybbit home](${SITE_ORIGIN}/)
+- [Documentation](${SITE_ORIGIN}/docs)
+- [Sitemap](${SITE_ORIGIN}/sitemap.xml)
+- [Agent index](${SITE_ORIGIN}/llms.txt)
+- [API specification](${SITE_ORIGIN}/openapi.json)
+`;
+
+function isElement(node: HtmlNode): node is HtmlElement {
+ return "tagName" in node;
+}
+
+function textContent(node: HtmlNode): string {
+ if ("value" in node) return node.value;
+ if (!("childNodes" in node)) return "";
+ return node.childNodes.map(textContent).join("");
+}
+
+function attribute(element: HtmlElement, name: string): string | undefined {
+ return element.attrs.find(item => item.name === name)?.value;
+}
+
+function absoluteUrl(value: string): string {
+ try {
+ return new URL(value, SITE_ORIGIN).toString();
+ } catch {
+ return value;
+ }
+}
+
+function renderChildren(node: HtmlNode): string {
+ if (!("childNodes" in node)) return "";
+ return node.childNodes.map(renderNode).join("");
+}
+
+function renderNode(node: HtmlNode): string {
+ if ("value" in node) return node.value;
+ if (!isElement(node)) return renderChildren(node);
+
+ const tag = node.tagName;
+ if (
+ ["script", "style", "svg", "template"].includes(tag) ||
+ attribute(node, "hidden") !== undefined ||
+ attribute(node, "aria-hidden") === "true"
+ ) {
+ return "";
+ }
+
+ const children = renderChildren(node);
+ if (/^h[1-6]$/.test(tag)) return `\n\n${"#".repeat(Number(tag[1]))} ${children.trim()}\n\n`;
+ if (tag === "p") return `\n\n${children.trim()}\n\n`;
+ if (tag === "br") return "\n";
+ if (tag === "hr") return "\n\n---\n\n";
+ if (tag === "strong" || tag === "b") return children.trim() ? `**${children.trim()}**` : "";
+ if (tag === "em" || tag === "i") return children.trim() ? `_${children.trim()}_` : "";
+ if (tag === "code" && node.parentNode && isElement(node.parentNode) && node.parentNode.tagName === "pre") {
+ return children;
+ }
+ if (tag === "code") return children.trim() ? `\`${children.trim().replaceAll("`", "\\`")}\`` : "";
+ if (tag === "pre") return `\n\n\`\`\`\n${textContent(node).trim()}\n\`\`\`\n\n`;
+ if (tag === "blockquote")
+ return `\n\n${children
+ .trim()
+ .split("\n")
+ .map(line => `> ${line}`)
+ .join("\n")}\n\n`;
+ if (tag === "li") {
+ const parent = node.parentNode;
+ if (parent && isElement(parent) && parent.tagName === "ol") {
+ const siblings = parent.childNodes.filter(isElement).filter(child => child.tagName === "li");
+ return `\n${siblings.indexOf(node) + 1}. ${children.trim()}`;
+ }
+ return `\n- ${children.trim()}`;
+ }
+ if (tag === "ul" || tag === "ol") return `\n${children.trim()}\n`;
+ if (tag === "a") {
+ const href = attribute(node, "href");
+ const label = children.trim();
+ return href && label ? `[${label}](${absoluteUrl(href)})` : label;
+ }
+ if (tag === "img") {
+ const source = attribute(node, "src");
+ const alt = attribute(node, "alt")?.trim();
+ return source && alt ? `![${alt}](${absoluteUrl(source)})` : "";
+ }
+ if (["article", "aside", "div", "main", "nav", "section"].includes(tag)) return `\n${children}\n`;
+ return children;
+}
+
+function findMain(node: HtmlNode): HtmlNode | undefined {
+ if (isElement(node) && node.tagName === "main") return node;
+ if (!("childNodes" in node)) return undefined;
+ for (const child of node.childNodes) {
+ const match = findMain(child);
+ if (match) return match;
+ }
+ return undefined;
+}
+
+export function htmlToMarkdown(html: string): string {
+ const document = parse(html) as HtmlNode;
+ const root = findMain(document) ?? document;
+ return renderNode(root)
+ .split(/(```[\s\S]*?```)/g)
+ .map((part, index) =>
+ index % 2 === 1
+ ? part
+ : part
+ .replace(/[ \t]+/g, " ")
+ .replace(/ *\n */g, "\n")
+ .replace(/\n{3,}/g, "\n\n")
+ )
+ .join("")
+ .trim();
+}
+
+function hasUnsafePathCharacters(value: string): boolean {
+ if (value.includes("\\") || /[\u0000-\u001f\u007f]/.test(value)) return true;
+ try {
+ const decoded = decodeURIComponent(value);
+ return decoded.includes("\\") || /[\u0000-\u001f\u007f]/.test(decoded) || decoded.startsWith("//");
+ } catch {
+ return true;
+ }
+}
+
+export function isSafeMarkdownPath(pathname: string): boolean {
+ return (
+ pathname.length > 0 &&
+ pathname.length <= 2_048 &&
+ pathname.startsWith("/") &&
+ !pathname.startsWith("//") &&
+ pathname !== "/api" &&
+ !pathname.startsWith("/api/") &&
+ pathname !== "/_next" &&
+ !pathname.startsWith("/_next/") &&
+ !hasUnsafePathCharacters(pathname)
+ );
+}
+
+export function markdownSourceUrl(origin: string, pathname: string, search: string): URL {
+ if (!isSafeMarkdownPath(pathname)) throw new TypeError("Invalid Markdown source path.");
+ if (search && (!search.startsWith("?") || search.length > 8_192 || hasUnsafePathCharacters(search))) {
+ throw new TypeError("Invalid Markdown source query.");
+ }
+
+ const source = new URL(origin);
+ source.pathname = pathname;
+ source.search = search;
+ return source;
+}
+
+async function readLimitedText(response: Response): Promise<string> {
+ const declaredLength = Number(response.headers.get("Content-Length"));
+ if (Number.isFinite(declaredLength) && declaredLength > MAX_MARKDOWN_SOURCE_BYTES) {
+ throw new RangeError("Markdown source response is too large.");
+ }
+ if (!response.body) return "";
+
+ const reader = response.body.getReader();
+ const decoder = new TextDecoder();
+ let bytes = 0;
+ let text = "";
+
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ bytes += value.byteLength;
+ if (bytes > MAX_MARKDOWN_SOURCE_BYTES) {
+ await reader.cancel();
+ throw new RangeError("Markdown source response is too large.");
+ }
+ text += decoder.decode(value, { stream: true });
+ }
+
+ return text + decoder.decode();
+}
+
+export function markdownResponse(body: string, status = 200, headers?: HeadersInit): Response {
+ const responseHeaders = new Headers(headers);
+ responseHeaders.set("Content-Type", "text/markdown; charset=utf-8");
+ responseHeaders.set("X-Content-Type-Options", "nosniff");
+ appendVary(responseHeaders, "Accept", "Accept-Encoding");
+
+ return new Response(`${body.trim()}\n`, { status, headers: responseHeaders });
+}
+
+export async function getMarkdownRepresentation(
+ pathname: string,
+ fetchHtml: () => Promise<Response>
+): Promise<Response> {
+ if (pathname === "/") {
+ return markdownResponse(homepageMarkdown, 200, {
+ "Cache-Control": "public, s-maxage=300, stale-while-revalidate=86400",
+ "Content-Location": "/",
+ });
+ }
+
+ let source: Response;
+ try {
+ source = await fetchHtml();
+ } catch {
+ return markdownResponse(
+ "# Upstream page unavailable\n\nThe HTML representation could not be rendered. Try the [documentation](https://rybbit.com/docs) or retry this request.",
+ 502,
+ { "Cache-Control": "no-store" }
+ );
+ }
+
+ if (source.status === 404) {
+ return markdownResponse(notFoundMarkdown, 404, { "Cache-Control": "public, s-maxage=60" });
+ }
+
+ if (REDIRECT_STATUSES.has(source.status)) {
+ const location = source.headers.get("Location");
+ if (!location) {
+ return markdownResponse("# Invalid redirect\n\nThe upstream response did not include a destination.", 502, {
+ "Cache-Control": "no-store",
+ });
+ }
+ return markdownResponse(`# Redirect\n\nContinue at: ${location}`, source.status, {
+ "Cache-Control": "no-store",
+ "Content-Location": pathname,
+ Location: location,
+ });
+ }
+
+ const contentType = source.headers.get("Content-Type") ?? "";
+ if (!contentType.toLowerCase().includes("text/html")) {
+ return markdownResponse("# Not acceptable\n\nA Markdown representation is not available for this resource.", 406, {
+ "Cache-Control": "no-store",
+ });
+ }
+
+ let markdown: string;
+ try {
+ markdown = htmlToMarkdown(await readLimitedText(source));
+ } catch {
+ return markdownResponse(
+ "# Representation unavailable\n\nThe rendered page exceeded the safe conversion limit. See the [agent index](https://rybbit.com/llms.txt).",
+ 502,
+ { "Cache-Control": "no-store" }
+ );
+ }
+ if (!markdown) {
+ return markdownResponse(
+ "# Representation unavailable\n\nThe page did not contain readable main content. See the [agent index](https://rybbit.com/llms.txt).",
+ 502,
+ { "Cache-Control": "no-store" }
+ );
+ }
+
+ return markdownResponse(markdown, source.status, {
+ "Cache-Control": "public, s-maxage=300, stale-while-revalidate=86400",
+ "Content-Location": pathname,
+ });
+}
diff --git a/docs/src/lib/agent-readiness.test.ts b/docs/src/lib/agent-readiness.test.ts
new file mode 100644
index 000000000..b34d5c52f
--- /dev/null
+++ b/docs/src/lib/agent-readiness.test.ts
@@ -0,0 +1,188 @@
+import assert from "node:assert/strict";
+import { describe, it } from "node:test";
+
+import { createApiError, jsonError } from "./api-error";
+import {
+ getMarkdownRepresentation,
+ homepageMarkdown,
+ htmlToMarkdown,
+ isSafeMarkdownPath,
+ markdownSourceUrl,
+} from "./agent-markdown";
+import { appendVary, markdownProxyTarget, preferredType } from "./content-negotiation";
+import { buildOpenApiDocument } from "./openapi";
+
+describe("agent-readable HTTP behavior", () => {
+ it("honors q-values, specificity, and explicit rejection", () => {
+ assert.equal(preferredType(null), "text/html");
+ assert.equal(preferredType("*/*"), "text/html");
+ assert.equal(preferredType("text/markdown"), "text/markdown");
+ assert.equal(preferredType("text/html;q=0.8, text/markdown"), "text/markdown");
+ assert.equal(preferredType("text/html, text/markdown;q=0.5"), "text/html");
+ assert.equal(preferredType("text/*;q=0.8, text/html;q=0.8"), "text/html");
+ assert.equal(preferredType("text/html;q=0, */*;q=1"), "text/markdown");
+ assert.equal(preferredType("text/markdown;q=0, */*;q=1"), "text/html");
+ assert.equal(preferredType("text/markdown;q=1.5, text/html;q=0.5"), "text/html");
+ assert.equal(preferredType("text/html;q=0, text/markdown;q=0"), null);
+ assert.equal(preferredType("application/pdf"), null);
+ });
+
+ it("preserves framework Vary tokens and adds negotiated request headers once", () => {
+ const headers = new Headers({ Vary: "rsc, next-router-state-tree" });
+ appendVary(headers, "Accept", "Accept-Encoding");
+ appendVary(headers, "accept");
+
+ assert.equal(headers.get("Vary"), "rsc, next-router-state-tree, Accept, Accept-Encoding");
+ });
+
+ it("forwards the original path and query to the Markdown renderer", () => {
+ const { rewriteUrl, requestHeaders } = markdownProxyTarget(
+ "https://rybbit.com/docs/api/getting-started?source=audit",
+ { Accept: "text/markdown" }
+ );
+
+ assert.equal(
+ rewriteUrl.toString(),
+ "https://rybbit.com/api/agent/markdown?path=%2Fdocs%2Fapi%2Fgetting-started&query=%3Fsource%3Daudit"
+ );
+ assert.equal(requestHeaders.get("X-Rybbit-Markdown-Path"), "/docs/api/getting-started");
+ assert.equal(requestHeaders.get("X-Rybbit-Markdown-Query"), "?source=audit");
+ });
+
+ it("serves substantial homepage Markdown with a real heading hierarchy", () => {
+ assert.ok(homepageMarkdown.length >= 500);
+ assert.match(homepageMarkdown, /^# Rybbit/m);
+ assert.match(homepageMarkdown, /^## /m);
+ assert.match(homepageMarkdown, /^### /m);
+ assert.match(homepageMarkdown, /https:\/\/rybbit\.com\/docs/);
+ });
+
+ it("returns a recoverable Markdown 404 for an unknown page", async () => {
+ const response = await getMarkdownRepresentation(
+ "/definitely-not-a-real-page",
+ async () =>
+ new Response("<h1>Page not found</h1>", {
+ status: 404,
+ headers: { "Content-Type": "text/html; charset=utf-8" },
+ })
+ );
+
+ assert.equal(response.status, 404);
+ assert.equal(response.headers.get("Content-Type"), "text/markdown; charset=utf-8");
+ assert.match(response.headers.get("Vary") ?? "", /Accept/);
+
+ const body = await response.text();
+ assert.match(body, /^# Page not found/m);
+ assert.match(body, /\[Sitemap\]\(https:\/\/rybbit\.com\/sitemap\.xml\)/);
+ assert.match(body, /\[Agent index\]\(https:\/\/rybbit\.com\/llms\.txt\)/);
+ assert.match(body, /\[API specification\]\(https:\/\/rybbit\.com\/openapi\.json\)/);
+ });
+
+ it("preserves upstream redirects for Markdown clients", async () => {
+ const response = await getMarkdownRepresentation(
+ "/retired-page",
+ async () =>
+ new Response(null, {
+ status: 308,
+ headers: { Location: "/replacement" },
+ })
+ );
+
+ assert.equal(response.status, 308);
+ assert.equal(response.headers.get("Location"), "/replacement");
+ });
+
+ it("rejects oversized HTML sources before converting them to Markdown", async () => {
+ const response = await getMarkdownRepresentation(
+ "/large-page",
+ async () =>
+ new Response("<main><h1>Large page</h1></main>", {
+ headers: {
+ "Content-Length": "2000001",
+ "Content-Type": "text/html; charset=utf-8",
+ },
+ })
+ );
+
+ assert.equal(response.status, 502);
+ assert.match(await response.text(), /exceeded the safe conversion limit/i);
+ });
+
+ it("keeps Markdown source fetches on the configured origin", () => {
+ assert.equal(isSafeMarkdownPath("/docs/api/getting-started"), true);
+ assert.equal(isSafeMarkdownPath("//127.0.0.1/internal"), false);
+ assert.equal(isSafeMarkdownPath("/\\attacker.example/internal"), false);
+ assert.equal(isSafeMarkdownPath("/bad\npath"), false);
+ assert.equal(isSafeMarkdownPath("https://attacker.example/internal"), false);
+ assert.equal(isSafeMarkdownPath("/api/agent/markdown"), false);
+ assert.equal(isSafeMarkdownPath("/_next/image"), false);
+
+ const source = markdownSourceUrl("https://rybbit.com", "/docs/api/getting-started", "?source=agent");
+ assert.equal(source.origin, "https://rybbit.com");
+ assert.equal(source.pathname, "/docs/api/getting-started");
+ assert.equal(source.search, "?source=agent");
+ });
+
+ it("preserves indentation inside fenced code", () => {
+ const markdown = htmlToMarkdown("<main><pre><code>if (ready) {\n run();\n}</code></pre></main>");
+ assert.match(markdown, /if \(ready\) \{\n run\(\);\n\}/);
+ });
+
+ it("exposes stable JSON API error fields while preserving compatibility", async () => {
+ const body = createApiError({
+ code: "API_ROUTE_NOT_FOUND",
+ message: "No API route exists at this path.",
+ resolution: "Read the OpenAPI document and choose a listed operation.",
+ details: { path: "/api/missing" },
+ });
+
+ assert.deepEqual(body, {
+ error: "No API route exists at this path.",
+ code: "API_ROUTE_NOT_FOUND",
+ message: "No API route exists at this path.",
+ resolution: "Read the OpenAPI document and choose a listed operation.",
+ details: { path: "/api/missing" },
+ });
+
+ const response = jsonError(404, body);
+ assert.equal(response.status, 404);
+ assert.match(response.headers.get("Content-Type") ?? "", /^application\/json/);
+ assert.equal(response.headers.get("X-Content-Type-Options"), "nosniff");
+ assert.equal(((await response.json()) as { code: string }).code, "API_ROUTE_NOT_FOUND");
+ });
+
+ it("generates OpenAPI 3.1 for the documented API and structured errors", () => {
+ const document = buildOpenApiDocument();
+ const operations = Object.values(document.paths).flatMap(pathItem =>
+ Object.values(pathItem).filter(value => value && typeof value === "object" && "responses" in value)
+ );
+
+ assert.equal(document.openapi, "3.1.1");
+ assert.equal(document.servers[0].url, "https://app.rybbit.io");
+ assert.ok(Object.keys(document.paths).length >= 50);
+ assert.ok(operations.length >= 60);
+ assert.ok(document.paths["/api/sites/{site}/overview"]?.get);
+ assert.ok(document.paths["/api/track"]?.post);
+ assert.ok(document.components.schemas.ApiError.required.includes("resolution"));
+ assert.ok(document.tags.every(tag => tag.description.length > 0));
+ const license = document.info.license as { identifier?: string; url?: string };
+ assert.ok(!(license.identifier && license.url), "OpenAPI 3.1 license identifier and URL are mutually exclusive");
+ assert.deepEqual(document.paths["/api/track"]?.post?.security?.[0], {});
+ assert.deepEqual(document.paths["/api/auth/api-key/list"]?.get?.security, [{ CookieSession: [] }]);
+ assert.equal(
+ (document.components.securitySchemes.CookieSession as { name: string }).name,
+ "better-auth.session_token"
+ );
+ assert.deepEqual(
+ (document.paths["/api/sites/{site}/retention"]?.get?.parameters?.[0] as { schema: unknown }).schema,
+ {
+ oneOf: [
+ { type: "integer", minimum: 1 },
+ { type: "string", minLength: 1 },
+ ],
+ }
+ );
+ assert.equal(new Set(operations.map(operation => operation.operationId)).size, operations.length);
+ assert.doesNotThrow(() => JSON.stringify(document));
+ });
+});
diff --git a/docs/src/lib/api-error.ts b/docs/src/lib/api-error.ts
new file mode 100644
index 000000000..bf14b2153
--- /dev/null
+++ b/docs/src/lib/api-error.ts
@@ -0,0 +1,36 @@
+export interface ApiErrorBody {
+ code: string;
+ details?: unknown;
+ error: string;
+ message: string;
+ resolution: string;
+}
+
+interface ApiErrorInput {
+ code: string;
+ details?: unknown;
+ message: string;
+ resolution: string;
+}
+
+export function createApiError(input: ApiErrorInput): ApiErrorBody {
+ return {
+ error: input.message,
+ code: input.code,
+ message: input.message,
+ resolution: input.resolution,
+ ...(input.details === undefined ? {} : { details: input.details }),
+ };
+}
+
+export function jsonError(status: number, body: ApiErrorBody, headers?: HeadersInit): Response {
+ const responseHeaders = new Headers(headers);
+ responseHeaders.set("Content-Type", "application/json; charset=utf-8");
+ responseHeaders.set("Cache-Control", "no-store");
+ responseHeaders.set("X-Content-Type-Options", "nosniff");
+
+ return new Response(`${JSON.stringify(body)}\n`, {
+ status,
+ headers: responseHeaders,
+ });
+}
diff --git a/docs/src/lib/content-negotiation.ts b/docs/src/lib/content-negotiation.ts
new file mode 100644
index 000000000..193048f98
--- /dev/null
+++ b/docs/src/lib/content-negotiation.ts
@@ -0,0 +1,119 @@
+const PRODUCES = ["text/html", "text/markdown"] as const;
+
+type ProducedType = (typeof PRODUCES)[number];
+
+interface AcceptEntry {
+ position: number;
+ q: number;
+ specificity: number;
+ type: string;
+}
+
+function parseAccept(header: string): AcceptEntry[] {
+ return header
+ .split(",")
+ .map((raw, position) => {
+ const [rawType = "", ...rawParameters] = raw.split(";");
+ const type = rawType.trim().toLowerCase();
+ let q = 1;
+
+ for (const rawParameter of rawParameters) {
+ const [rawName = "", rawValue = ""] = rawParameter.split("=", 2);
+ if (rawName.trim().toLowerCase() !== "q") continue;
+
+ const value = rawValue.trim();
+ q = /^(?:0(?:\.\d{0,3})?|1(?:\.0{0,3})?)$/.test(value) ? Number(value) : 0;
+ }
+
+ return {
+ position,
+ q,
+ specificity: type === "*/*" ? 0 : type.endsWith("/*") ? 1 : 2,
+ type,
+ };
+ })
+ .filter(entry => entry.type.length > 0);
+}
+
+function matches(entry: AcceptEntry, candidate: ProducedType): boolean {
+ if (entry.type === "*/*") return true;
+ if (entry.type.endsWith("/*")) return candidate.startsWith(entry.type.slice(0, -1));
+ return entry.type === candidate;
+}
+
+/** Selects an HTTP representation according to RFC 9110 section 12.5.1. */
+export function preferredType(header: string | null): ProducedType | null {
+ if (!header) return PRODUCES[0];
+
+ const entries = parseAccept(header);
+ if (entries.length === 0) return PRODUCES[0];
+
+ let best: { position: number; q: number; specificity: number; type: ProducedType } | null = null;
+
+ for (const candidate of PRODUCES) {
+ let matched: AcceptEntry | null = null;
+
+ for (const entry of entries) {
+ if (!matches(entry, candidate)) continue;
+ if (
+ matched === null ||
+ entry.specificity > matched.specificity ||
+ (entry.specificity === matched.specificity && entry.position < matched.position)
+ ) {
+ matched = entry;
+ }
+ }
+
+ if (!matched || matched.q <= 0) continue;
+ if (
+ best === null ||
+ matched.q > best.q ||
+ (matched.q === best.q && matched.specificity > best.specificity) ||
+ (matched.q === best.q && matched.specificity === best.specificity && matched.position < best.position)
+ ) {
+ best = {
+ position: matched.position,
+ q: matched.q,
+ specificity: matched.specificity,
+ type: candidate,
+ };
+ }
+ }
+
+ return best?.type ?? null;
+}
+
+export function appendVary(headers: Headers, ...names: string[]): void {
+ const existing = (headers.get("Vary") ?? "")
+ .split(",")
+ .map(value => value.trim())
+ .filter(Boolean);
+ const known = new Set(existing.map(value => value.toLowerCase()));
+
+ for (const name of names) {
+ if (!known.has(name.toLowerCase())) {
+ existing.push(name);
+ known.add(name.toLowerCase());
+ }
+ }
+
+ headers.set("Vary", existing.join(", "));
+}
+
+export function markdownProxyTarget(requestUrl: string | URL, headers: HeadersInit) {
+ const originalUrl = new URL(requestUrl);
+ const rewriteUrl = new URL(originalUrl);
+ const originalPath = originalUrl.pathname;
+ const originalSearch = originalUrl.search;
+ const requestHeaders = new Headers(headers);
+
+ rewriteUrl.pathname = "/api/agent/markdown";
+ rewriteUrl.search = "";
+ rewriteUrl.searchParams.set("path", originalPath);
+ if (originalSearch) rewriteUrl.searchParams.set("query", originalSearch);
+
+ requestHeaders.set("X-Rybbit-Markdown-Path", originalPath);
+ requestHeaders.set("X-Rybbit-Markdown-Query", originalSearch);
+
+ return { rewriteUrl, requestHeaders };
+}
diff --git a/docs/src/lib/openapi.ts b/docs/src/lib/openapi.ts
new file mode 100644
index 000000000..4c92e305f
--- /dev/null
+++ b/docs/src/lib/openapi.ts
@@ -0,0 +1,292 @@
+import { existsSync, readdirSync, readFileSync } from "node:fs";
+import { join, relative, sep } from "node:path";
+
+const HTTP_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"] as const;
+type HttpMethod = (typeof HTTP_METHODS)[number];
+
+interface OpenApiOperation {
+ description: string;
+ externalDocs: { url: string };
+ operationId: string;
+ parameters?: Array<Record<string, unknown>>;
+ requestBody?: Record<string, unknown>;
+ responses: Record<string, unknown>;
+ security: Array<Record<string, string[]>>;
+ summary: string;
+ tags: string[];
+}
+
+type OpenApiPathItem = Partial<Record<Lowercase<HttpMethod>, OpenApiOperation>>;
+
+export interface OpenApiDocument {
+ components: {
+ parameters: Record<string, unknown>;
+ schemas: { ApiError: { required: string[]; [key: string]: unknown } };
+ securitySchemes: Record<string, unknown>;
+ };
+ externalDocs: { description: string; url: string };
+ info: Record<string, unknown>;
+ jsonSchemaDialect: string;
+ openapi: "3.1.1";
+ paths: Record<string, OpenApiPathItem>;
+ servers: Array<{ description: string; url: string }>;
+ tags: Array<{ description: string; name: string }>;
+}
+
+function apiDocsRoot(): string {
+ const candidates = [join(process.cwd(), "content/docs/api"), join(process.cwd(), "docs/content/docs/api")];
+ const root = candidates.find(existsSync);
+ if (!root) throw new Error("Could not locate content/docs/api for OpenAPI generation.");
+ return root;
+}
+
+function mdxFiles(directory: string): string[] {
+ return readdirSync(directory, { withFileTypes: true }).flatMap(entry => {
+ const path = join(directory, entry.name);
+ if (entry.isDirectory()) return mdxFiles(path);
+ return entry.isFile() && entry.name.endsWith(".mdx") ? [path] : [];
+ });
+}
+
+function frontmatterValue(source: string, key: string): string | undefined {
+ const match = source.match(new RegExp(`^${key}:\\s*(.+)$`, "m"));
+ return match?.[1]?.trim().replace(/^['"]|['"]$/g, "");
+}
+
+function canonicalParameterName(name: string): string {
+ return name === "siteId" ? "site" : name;
+}
+
+function openApiPath(path: string): string {
+ return path.replace(/:([A-Za-z][A-Za-z0-9_]*)/g, (_match, name: string) => `{${canonicalParameterName(name)}}`);
+}
+
+function operationId(method: HttpMethod, path: string): string {
+ const words = `${method.toLowerCase()} ${path}`.match(/[A-Za-z0-9]+/g) ?? [];
+ return words
+ .map((word, index) => (index === 0 ? word.toLowerCase() : `${word[0].toUpperCase()}${word.slice(1)}`))
+ .join("");
+}
+
+function tagFor(root: string, file: string): string {
+ const [first] = relative(root, file).split(sep);
+ if (first.endsWith(".mdx")) return "General";
+ return first
+ .split("-")
+ .map(word => `${word[0].toUpperCase()}${word.slice(1)}`)
+ .join(" ");
+}
+
+function docsUrl(root: string, file: string): string {
+ const slug = relative(root, file)
+ .split(sep)
+ .join("/")
+ .replace(/\.mdx$/, "");
+ return `https://rybbit.com/docs/api/${slug}`;
+}
+
+const commonParameterReferences = [
+ "StartDate",
+ "EndDate",
+ "TimeZone",
+ "StartDatetime",
+ "EndDatetime",
+ "PastMinutesStart",
+ "PastMinutesEnd",
+ "Filters",
+].map(name => ({ $ref: `#/components/parameters/${name}` }));
+
+function pathParameters(path: string): Array<Record<string, unknown>> {
+ return [...path.matchAll(/\{([A-Za-z][A-Za-z0-9_]*)\}/g)].map(match => ({
+ description: match[1] === "site" ? "Numeric Rybbit Site ID or string identifier." : `${match[1]} identifier.`,
+ in: "path",
+ name: match[1],
+ required: true,
+ schema:
+ match[1] === "site"
+ ? {
+ oneOf: [
+ { type: "integer", minimum: 1 },
+ { type: "string", minLength: 1 },
+ ],
+ }
+ : { type: "string", minLength: 1 },
+ }));
+}
+
+function operationSecurity(path: string): Array<Record<string, string[]>> {
+ if (path === "/api/track") return [{}, { BearerAuth: [] }, { QueryApiKey: [] }];
+ if (path.startsWith("/api/auth/")) return [{ CookieSession: [] }];
+ return [{ BearerAuth: [] }, { QueryApiKey: [] }, { CookieSession: [] }];
+}
+
+function successResponse(path: string): Record<string, unknown> {
+ if (path.endsWith("/export/pdf")) {
+ return {
+ description: "PDF report.",
+ content: { "application/pdf": { schema: { type: "string", contentEncoding: "base64" } } },
+ };
+ }
+ return {
+ description: "Successful response. Refer to the linked endpoint documentation for the response fields.",
+ content: { "application/json": { schema: {} } },
+ };
+}
+
+function errorResponses(): Record<string, unknown> {
+ return Object.fromEntries(
+ [
+ ["400", "Invalid request"],
+ ["401", "Authentication required"],
+ ["403", "Insufficient permission"],
+ ["404", "Resource not found"],
+ ["429", "Rate limit exceeded"],
+ ["500", "Unexpected server error"],
+ ].map(([status, description]) => [
+ status,
+ {
+ description,
+ content: { "application/json": { schema: { $ref: "#/components/schemas/ApiError" } } },
+ },
+ ])
+ );
+}
+
+export function buildOpenApiDocument(): OpenApiDocument {
+ const root = apiDocsRoot();
+ const paths: Record<string, OpenApiPathItem> = {};
+ const tags = new Set<string>();
+
+ for (const file of mdxFiles(root).sort()) {
+ const source = readFileSync(file, "utf8");
+ const route = source.match(/^(GET|POST|PUT|PATCH|DELETE)\s+(\/api\/\S+)\s*$/m);
+ if (!route || !HTTP_METHODS.includes(route[1] as HttpMethod)) continue;
+
+ const method = route[1] as HttpMethod;
+ const path = openApiPath(route[2]);
+ const methodKey = method.toLowerCase() as Lowercase<HttpMethod>;
+ const tag = tagFor(root, file);
+ const parameters = pathParameters(path);
+ if (/common parameters/i.test(source)) parameters.push(...commonParameterReferences);
+
+ const operation: OpenApiOperation = {
+ summary: frontmatterValue(source, "title") ?? `${method} ${path}`,
+ description: frontmatterValue(source, "description") ?? "See the endpoint documentation for details.",
+ operationId: operationId(method, path),
+ tags: [tag],
+ security: operationSecurity(path),
+ externalDocs: { url: docsUrl(root, file) },
+ responses: { "200": successResponse(path), ...errorResponses() },
+ ...(parameters.length === 0 ? {} : { parameters }),
+ ...(["POST", "PUT", "PATCH"].includes(method)
+ ? {
+ requestBody: {
+ required: true,
+ content: {
+ "application/json": {
+ schema: { type: "object", additionalProperties: true },
+ },
+ },
+ },
+ }
+ : {}),
+ };
+
+ if (paths[path]?.[methodKey]) {
+ throw new Error(`Duplicate OpenAPI operation ${method} ${path} while reading ${file}.`);
+ }
+ paths[path] = { ...paths[path], [methodKey]: operation };
+ tags.add(tag);
+ }
+
+ return {
+ openapi: "3.1.1",
+ jsonSchemaDialect: "https://json-schema.org/draft/2020-12/schema",
+ info: {
+ title: "Rybbit API",
+ version: "2.8.0-beta",
+ description:
+ "REST API for Rybbit web and product analytics. The API is in beta and may introduce breaking changes.",
+ termsOfService: "https://rybbit.com/terms-and-conditions",
+ contact: { name: "Rybbit", url: "https://rybbit.com/contact" },
+ license: {
+ name: "GNU Affero General Public License v3.0",
+ identifier: "AGPL-3.0-only",
+ },
+ },
+ servers: [{ url: "https://app.rybbit.io", description: "Rybbit Cloud API" }],
+ tags: [...tags].sort().map(name => ({ name, description: `${name} API operations.` })),
+ paths,
+ components: {
+ securitySchemes: {
+ BearerAuth: {
+ type: "http",
+ scheme: "bearer",
+ description: "Personal or organization API key sent as an Authorization Bearer token.",
+ },
+ QueryApiKey: {
+ type: "apiKey",
+ in: "query",
+ name: "api_key",
+ description: "Testing-only fallback. Bearer authentication is recommended.",
+ },
+ CookieSession: {
+ type: "apiKey",
+ in: "cookie",
+ name: "better-auth.session_token",
+ description:
+ "Authenticated dashboard session cookie. Secure deployments may prefix the cookie name with __Secure-.",
+ },
+ },
+ parameters: {
+ StartDate: { name: "start_date", in: "query", schema: { type: "string", format: "date" } },
+ EndDate: { name: "end_date", in: "query", schema: { type: "string", format: "date" } },
+ TimeZone: {
+ name: "time_zone",
+ in: "query",
+ schema: { type: "string", example: "America/Los_Angeles" },
+ },
+ StartDatetime: { name: "start_datetime", in: "query", schema: { type: "string" } },
+ EndDatetime: { name: "end_datetime", in: "query", schema: { type: "string" } },
+ PastMinutesStart: { name: "past_minutes_start", in: "query", schema: { type: "integer", minimum: 1 } },
+ PastMinutesEnd: { name: "past_minutes_end", in: "query", schema: { type: "integer", minimum: 0 } },
+ Filters: {
+ name: "filters",
+ in: "query",
+ description: "JSON-encoded array of analytics filters.",
+ schema: { type: "string" },
+ },
+ },
+ schemas: {
+ ApiError: {
+ type: "object",
+ additionalProperties: true,
+ required: ["error", "code", "message", "resolution"],
+ properties: {
+ error: { type: "string", description: "Backward-compatible human-readable error." },
+ code: { type: "string", description: "Stable machine-readable error code." },
+ message: { type: "string", description: "Human-readable explanation." },
+ resolution: { type: "string", description: "Action the caller can take to recover." },
+ details: { description: "Optional structured context for this error." },
+ },
+ },
+ },
+ },
+ externalDocs: {
+ description: "Rybbit API documentation",
+ url: "https://rybbit.com/docs/api/getting-started",
+ },
+ };
+}
+
+export function openApiResponse(includeBody = true): Response {
+ const serialized = `${JSON.stringify(buildOpenApiDocument(), null, 2)}\n`;
+ return new Response(includeBody ? serialized : null, {
+ headers: {
+ "Cache-Control": "public, max-age=0, s-maxage=3600, stale-while-revalidate=86400",
+ "Content-Length": String(Buffer.byteLength(serialized)),
+ "Content-Type": "application/json; charset=utf-8",
+ "X-Content-Type-Options": "nosniff",
+ },
+ });
+}
diff --git a/docs/src/proxy.ts b/docs/src/proxy.ts
index c245bdbf6..979947e02 100644
--- a/docs/src/proxy.ts
+++ b/docs/src/proxy.ts
@@ -1,10 +1,42 @@
-import createMiddleware from 'next-intl/middleware';
-import { routing } from './i18n/routing';
+import createMiddleware from "next-intl/middleware";
+import { type NextRequest, NextResponse } from "next/server";
-export default createMiddleware(routing);
+import { routing } from "./i18n/routing";
+import { appendVary, markdownProxyTarget, preferredType } from "./lib/content-negotiation";
+
+const internationalization = createMiddleware(routing);
+
+export default function proxy(request: NextRequest) {
+ if (request.method !== "GET" && request.method !== "HEAD") {
+ return internationalization(request);
+ }
+
+ const accept = request.headers.get("Accept");
+ const representation = preferredType(accept);
+
+ if (representation === "text/markdown") {
+ const { rewriteUrl, requestHeaders } = markdownProxyTarget(request.url, request.headers);
+
+ const response = NextResponse.rewrite(rewriteUrl, { request: { headers: requestHeaders } });
+ appendVary(response.headers, "Accept", "Accept-Encoding");
+ return response;
+ }
+
+ if (representation === null && accept) {
+ return new Response("Not Acceptable\n\nAvailable representations: text/html, text/markdown\n", {
+ status: 406,
+ headers: {
+ "Content-Type": "text/plain; charset=utf-8",
+ Vary: "Accept, Accept-Encoding",
+ },
+ });
+ }
+
+ const response = internationalization(request);
+ appendVary(response.headers, "Accept", "Accept-Encoding");
+ return response;
+}
export const config = {
- matcher: [
- '/((?!api|_next/static|_next/image|favicon.ico|.*\\..*).*)',
- ],
+ matcher: ["/((?!api|_next/static|_next/image|favicon.ico|.*\\..*).*)"],
};
diff --git a/docs/vercel.json b/docs/vercel.json
new file mode 100644
index 000000000..1d1792daa
--- /dev/null
+++ b/docs/vercel.json
@@ -0,0 +1,14 @@
+{
+ "$schema": "https://openapi.vercel.sh/vercel.json",
+ "headers": [
+ {
+ "source": "/(.*)",
+ "headers": [
+ {
+ "key": "Vary",
+ "value": "Accept, Accept-Encoding, RSC, Next-Router-State-Tree, Next-Router-Prefetch, Next-Router-Segment-Prefetch"
+ }
+ ]
+ }
+ ]
+}
diff --git a/server/src/index.ts b/server/src/index.ts
index 0753bc1a4..461d9091e 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -171,6 +171,7 @@ import {
resolveSiteId,
} from "./lib/auth-middleware.js";
import { mapHeaders } from "./lib/auth-utils.js";
+import { registerApiErrorResponses } from "./lib/api-errors.js";
import type { ScopeAction, ScopeResource } from "./lib/scopes.js";
import { auth } from "./lib/auth.js";
import { mcpRoutes } from "./mcp/index.js";
@@ -280,6 +281,7 @@ const server = Fastify({
});
registerRequestLogging(server);
+registerApiErrorResponses(server);
server.register(cors, {
delegator: createCorsOptionsDelegate(),
diff --git a/server/src/lib/api-errors.test.ts b/server/src/lib/api-errors.test.ts
new file mode 100644
index 000000000..dfbd1ec47
--- /dev/null
+++ b/server/src/lib/api-errors.test.ts
@@ -0,0 +1,113 @@
+import Fastify from "fastify";
+import { describe, expect, it } from "vitest";
+
+import { normalizeApiError, registerApiErrorResponses } from "./api-errors.js";
+
+describe("normalizeApiError", () => {
+ it("adds stable machine fields while preserving existing error details", () => {
+ expect(normalizeApiError(429, { error: "Rate limit exceeded", scope: "daily", retryAfter: 30 })).toEqual({
+ error: "Rate limit exceeded",
+ code: "RATE_LIMITED",
+ message: "Rate limit exceeded",
+ resolution: "Wait for the advertised retry period, then retry the request.",
+ scope: "daily",
+ retryAfter: 30,
+ });
+ });
+
+ it("preserves array error details instead of discarding them", () => {
+ expect(normalizeApiError(400, [{ issue: "Missing site ID" }])).toMatchObject({
+ code: "INVALID_REQUEST",
+ details: [{ issue: "Missing site ID" }],
+ });
+ });
+});
+
+describe("registerApiErrorResponses", () => {
+ it("returns structured JSON for unknown API paths and normalizes handler errors", async () => {
+ const app = Fastify();
+ registerApiErrorResponses(app);
+ app.get("/api/example", async (_request, reply) => reply.status(400).send({ error: "Bad input" }));
+ app.get("/api/success", async () => ({ ok: true }));
+
+ const missing = await app.inject({ method: "GET", url: "/api/missing" });
+ expect(missing.statusCode).toBe(404);
+ expect(missing.headers["content-type"]).toContain("application/json");
+ expect(missing.json()).toMatchObject({
+ code: "API_ROUTE_NOT_FOUND",
+ message: "No API route matches GET /api/missing.",
+ resolution: expect.stringContaining("openapi.json"),
+ });
+
+ const invalid = await app.inject({ method: "GET", url: "/api/example" });
+ expect(invalid.json()).toMatchObject({
+ error: "Bad input",
+ code: "INVALID_REQUEST",
+ message: "Bad input",
+ resolution: expect.any(String),
+ });
+
+ expect((await app.inject({ method: "GET", url: "/api/success" })).json()).toEqual({ ok: true });
+ await app.close();
+ });
+
+ it("does not rewrite protocol-specific MCP errors", async () => {
+ const app = Fastify();
+ registerApiErrorResponses(app);
+ app.post("/api/mcp", async (_request, reply) =>
+ reply.status(400).send({ jsonrpc: "2.0", error: { code: -32600, message: "Invalid Request" }, id: null })
+ );
+
+ const response = await app.inject({ method: "POST", url: "/api/mcp" });
+ expect(response.json()).toEqual({
+ jsonrpc: "2.0",
+ error: { code: -32600, message: "Invalid Request" },
+ id: null,
+ });
+ await app.close();
+ });
+
+ it("normalizes thrown, string, array, and response-schema-constrained API errors", async () => {
+ const app = Fastify();
+ registerApiErrorResponses(app);
+ app.get("/api/thrown", async () => {
+ throw new Error("Unexpected failure");
+ });
+ app.get("/api/string", async (_request, reply) => reply.status(400).send("Bad string input"));
+ app.get("/api/array", async (_request, reply) => reply.status(400).send([{ issue: "Missing site ID" }]));
+ app.get(
+ "/api/schema",
+ {
+ schema: {
+ response: {
+ 400: {
+ type: "object",
+ properties: { error: { type: "string" } },
+ },
+ },
+ },
+ },
+ async (_request, reply) => reply.status(400).send({ error: "Schema-constrained error" })
+ );
+
+ for (const path of ["/api/thrown", "/api/string", "/api/array", "/api/schema"]) {
+ const response = await app.inject({ method: "GET", url: path });
+ expect(response.headers["content-type"]).toContain("application/json");
+ expect(response.json()).toMatchObject({
+ code: expect.any(String),
+ error: expect.any(String),
+ message: expect.any(String),
+ resolution: expect.any(String),
+ });
+ }
+
+ expect((await app.inject({ method: "GET", url: "/api/array" })).json()).toMatchObject({
+ details: [{ issue: "Missing site ID" }],
+ });
+ expect((await app.inject({ method: "GET", url: "/api/schema" })).json()).toMatchObject({
+ code: "INVALID_REQUEST",
+ message: "Schema-constrained error",
+ });
+ await app.close();
+ });
+});
diff --git a/server/src/lib/api-errors.ts b/server/src/lib/api-errors.ts
new file mode 100644
index 000000000..bf0bb8c2a
--- /dev/null
+++ b/server/src/lib/api-errors.ts
@@ -0,0 +1,151 @@
+import type { FastifyInstance } from "fastify";
+
+interface StructuredApiError extends Record<string, unknown> {
+ code: string;
+ error: string;
+ message: string;
+ resolution: string;
+}
+
+const defaultsByStatus: Record<number, { code: string; message: string; resolution: string }> = {
+ 400: {
+ code: "INVALID_REQUEST",
+ message: "The request is invalid.",
+ resolution: "Check the request parameters and body against https://rybbit.com/openapi.json.",
+ },
+ 401: {
+ code: "AUTHENTICATION_REQUIRED",
+ message: "Authentication is required.",
+ resolution: "Send a valid API key in the Authorization header as a Bearer token.",
+ },
+ 403: {
+ code: "FORBIDDEN",
+ message: "The credential does not have permission for this operation.",
+ resolution: "Use a credential with the required scope and Site or Organization access.",
+ },
+ 404: {
+ code: "NOT_FOUND",
+ message: "The requested API resource was not found.",
+ resolution: "Check identifiers and paths against https://rybbit.com/openapi.json.",
+ },
+ 405: {
+ code: "METHOD_NOT_ALLOWED",
+ message: "The HTTP method is not supported for this path.",
+ resolution: "Choose a method listed for this path in https://rybbit.com/openapi.json.",
+ },
+ 409: {
+ code: "CONFLICT",
+ message: "The request conflicts with the current resource state.",
+ resolution: "Refresh the resource, resolve the conflicting state, and retry.",
+ },
+ 413: {
+ code: "PAYLOAD_TOO_LARGE",
+ message: "The request body is too large.",
+ resolution: "Reduce the payload size or split it into smaller requests.",
+ },
+ 415: {
+ code: "UNSUPPORTED_MEDIA_TYPE",
+ message: "The request media type is not supported.",
+ resolution: "Send JSON with Content-Type: application/json unless the operation documents another type.",
+ },
+ 429: {
+ code: "RATE_LIMITED",
+ message: "Rate limit exceeded.",
+ resolution: "Wait for the advertised retry period, then retry the request.",
+ },
+ 500: {
+ code: "INTERNAL_ERROR",
+ message: "The server could not complete the request.",
+ resolution: "Retry with exponential backoff. Contact support if the error persists.",
+ },
+};
+
+function defaultsFor(statusCode: number) {
+ return defaultsByStatus[statusCode] ?? (statusCode >= 500 ? defaultsByStatus[500] : defaultsByStatus[400]);
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+export function normalizeApiError(statusCode: number, payload: unknown): StructuredApiError {
+ const existing = isRecord(payload)
+ ? payload
+ : typeof payload === "string"
+ ? { error: payload }
+ : Array.isArray(payload)
+ ? { details: payload }
+ : {};
+ const defaults = defaultsFor(statusCode);
+ const message =
+ typeof existing.message === "string"
+ ? existing.message
+ : typeof existing.error === "string"
+ ? existing.error
+ : defaults.message;
+
+ return {
+ ...existing,
+ error: typeof existing.error === "string" ? existing.error : message,
+ code: typeof existing.code === "string" ? existing.code : defaults.code,
+ message,
+ resolution: typeof existing.resolution === "string" ? existing.resolution : defaults.resolution,
+ };
+}
+
+function pathname(url: string): string {
+ return url.split("?", 1)[0];
+}
+
+function isApiPath(path: string): boolean {
+ return path === "/api" || path.startsWith("/api/");
+}
+
+function isMcpPath(path: string): boolean {
+ return path === "/api/mcp" || path.startsWith("/api/mcp/");
+}
+
+function serializedPayloadValue(payload: unknown): unknown {
+ const text = Buffer.isBuffer(payload) ? payload.toString("utf8") : typeof payload === "string" ? payload : undefined;
+ if (text === undefined) return payload;
+
+ try {
+ return JSON.parse(text);
+ } catch {
+ return text;
+ }
+}
+
+export function registerApiErrorResponses(server: FastifyInstance): void {
+ server.addHook("onSend", async (request, reply, payload) => {
+ const path = pathname(request.url);
+ if (reply.statusCode < 400 || !isApiPath(path) || isMcpPath(path)) return payload;
+
+ const normalized = normalizeApiError(reply.statusCode, serializedPayloadValue(payload));
+ reply.type("application/json; charset=utf-8");
+ reply.header("Cache-Control", "no-store");
+ reply.header("X-Content-Type-Options", "nosniff");
+ reply.removeHeader("Content-Length");
+ return JSON.stringify(normalized);
+ });
+
+ server.setNotFoundHandler(async (request, reply) => {
+ const path = pathname(request.url);
+ if (isApiPath(path)) {
+ return reply.status(404).send({
+ error: `No API route matches ${request.method} ${path}.`,
+ code: "API_ROUTE_NOT_FOUND",
+ message: `No API route matches ${request.method} ${path}.`,
+ resolution: "Read https://rybbit.com/openapi.json and choose a documented operation.",
+ details: { method: request.method, path },
+ });
+ }
+
+ return reply.status(404).send({
+ error: "Resource not found.",
+ code: "NOT_FOUND",
+ message: "Resource not found.",
+ resolution: "Check the requested path and try again.",
+ });
+ });
+}