Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .claude/skills/add-endpoint/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ Follow the layers in order. Look at `src/modules/elements/` as the reference mod
7. **Tests**
- HTTP: `test/app.test.ts` with Supertest — success status and body, 400 for invalid input, 404/409 where they apply, and that `db.json` changed as expected.
- Pure logic (helpers): `*.test.ts` next to the code.
- `test/openapi.test.ts` fails until `openapi.json` is regenerated and catches documented routes that do not exist.
- `test/openapi.test.ts` fails until `openapi.json` is regenerated, catches documented routes that do not exist, and catches routes missing from `buildOpenApiDocument()`.
8. **Docs** — the endpoint table in `README.md`.
9. **Frontend** — if the shape or path changed, the frontend's `src/api/main.ts` and `main.types.ts` need a matching PR in `email-template-editor-reactjs`.

Expand Down
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ request → helmet → cors → request-id → pino-http → json → static

## API contract

- **Source of truth:** [`openapi.json`](openapi.json), generated from the zod schemas and served at `GET /openapi.json`. `test/openapi.test.ts` fails if the committed file is stale or documents a route the app does not have.
- **Source of truth:** [`openapi.json`](openapi.json), generated from the zod schemas and served at `GET /openapi.json`. `test/openapi.test.ts` fails if the committed file is stale, documents a route the app does not have, or misses a route the app has.
- The frontend's request types (`src/api/main.types.ts` in the frontend repo) must match it. A breaking change here needs a matching frontend PR.
- Errors are always `{ error: { code, message, details?, requestId } }` (see `src/common/middleware/error-handler.ts`).
- Keys in paths are URL-encoded by the client.
Expand Down
64 changes: 61 additions & 3 deletions test/openapi.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import type { Express } from "express";
import { Router, type Express } from "express";
import request from "supertest";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { afterAll, beforeAll, describe, expect, it, vi, type MockInstance } from "vitest";
import { createApp } from "../src/app.js";
import { createLogger } from "../src/common/logger.js";
import { loadConfig } from "../src/config/env.js";
Expand All @@ -15,6 +15,7 @@ const METHODS = ["get", "post", "put", "patch", "delete"] as const;

let dir: string;
let app: Express;
let buildApp: () => Express;

beforeAll(async () => {
dir = await mkdtemp(path.join(tmpdir(), "openapi-test-"));
Expand All @@ -26,9 +27,52 @@ beforeAll(async () => {
DB_FILE: dbFile,
PUBLIC_DIR: dir,
});
app = createApp({ config, store: new JsonFileStore(dbFile), logger: createLogger(config) });
buildApp = () =>
createApp({ config, store: new JsonFileStore(dbFile), logger: createLogger(config) });
app = buildApp();
});

interface RouteLayer {
route?: { path: string; methods: Record<string, boolean> };
handle: unknown;
}
interface RouterLike {
stack: RouteLayer[];
}
const isRouter = (handle: unknown): handle is RouterLike =>
typeof handle === "function" && Array.isArray((handle as Partial<RouterLike>).stack);

/**
* Lists every route as "METHOD /path" in OpenAPI form (`:key` → `{key}`).
* Express 5 does not keep a router's mount path, so `use` records which router was mounted where.
* Reads `router.stack` and `layer.route` (Express internals, unchanged since Express 4): if an
* Express upgrade changes them, the sanity check in the test below fails instead of passing empty.
*/
function listRoutes(root: RouterLike, use: MockInstance): string[] {
const mountPath = (parent: RouterLike, child: RouterLike): string => {
const i = use.mock.calls.findIndex(
(args, n) => use.mock.contexts[n] === parent && args.includes(child),
);
const path: unknown = use.mock.calls[i]?.[0];
return typeof path === "string" ? path : "/";
};
const join = (...parts: string[]) =>
`/${parts.join("/")}`.replace(/\/+/g, "/").replace(/(.)\/$/, "$1");

const walk = (router: RouterLike, prefix: string): string[] =>
router.stack.flatMap((layer) => {
if (layer.route) {
const path = join(prefix, layer.route.path).replace(/:(\w+)/g, "{$1}");
return Object.keys(layer.route.methods).map((method) => `${method.toUpperCase()} ${path}`);
}
return isRouter(layer.handle)
? walk(layer.handle, join(prefix, mountPath(router, layer.handle)))
: [];
});

return walk(root, "/");
}

afterAll(async () => {
await rm(dir, { recursive: true, force: true });
});
Expand Down Expand Up @@ -65,4 +109,18 @@ describe("OpenAPI contract", () => {
}
}
});

it("documents every route the app has (add new routes to buildOpenApiDocument())", () => {
const use = vi.spyOn(Router.prototype as { use: (...args: unknown[]) => unknown }, "use");
const routes = listRoutes((buildApp() as unknown as { router: RouterLike }).router, use);

const { paths } = buildOpenApiDocument();
const documented = Object.entries(paths).flatMap(([route, item]) =>
METHODS.filter((m) => m in item).map((m) => `${m.toUpperCase()} ${route}`),
);

// Sanity check: an empty or wrong list means Express internals changed, not that all is well.
expect(routes).toContain("PATCH /tree/nodes/{key}");
expect(routes.filter((route) => !documented.includes(route))).toEqual([]);
});
});