Skip to content
Open
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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Changelog

## Unreleased

- **Bun route tables split across files are on the map:** a Bun server whose `routes` are spread in from other files (`routes: secureRoutes({ ...appRoutes, ...apiRoutes })`) showed no endpoints, so the website's requests weren't connected and Health's sign-in check had nothing to look at. Now each name spread into `Bun.serve`'s routes is followed to the object that defines it, in the same file, an imported one, or through a file that re-exports it, and its paths become endpoints in that file. A route whose value is a helper handed the methods (`createRouteHandler({ GET: list, POST: create })`) gets one endpoint per method, and `routes:` may sit inside one wrapping call. An object of paths that no `Bun.serve` spreads in stays data. Reported in #133.

## 0.11.0 (2026-11-16)

- **Serverless Framework endpoints are on the map:** a backend whose endpoints are declared in `serverless.yml` rather than in code showed none, so the website's requests to it weren't connected and Health skipped its sign-in check. Endpoints now come from each function's `http` and `httpApi` events (`path` and `method`, `any` and `*`, and the short `http: GET /orders` form) in `serverless.yml`, `serverless-*.yml` and `serverless_*.yml`, including function lists split across files included with `${file(./functions.yml)}`. Each endpoint sits in the file its `handler:` names (`src/orders.create` is `create` in `src/orders.ts`), followed through a file that re-exports it, or into another file's function when the handler only passes the request on to it (`(event) => withEvent(event, options, orders.create)`). Health counts an `authorizer`, `private: true` (an API key) or a sign-in check handed to the wrapper as protecting an endpoint, and still reads the handler for a check of its own. CloudFormation tags (`!Ref`, `!GetAtt`, `!Sub`), `${opt:…}` and `${self:…}` variables and anchors are read without trouble, and the scan summary lists schedules, queues, streams and other background functions for a worker node. Sample configs in test folders add no endpoints. Reported and fixed by @ShehanEk in #131 and #132.
Expand Down
2 changes: 1 addition & 1 deletion docs/development.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ The tests use Node's built-in test runner, so there's nothing to install (`npm t
| `fastify.test.mjs` | Fastify: plugins registered with a prefix, nested registers, and the website's requests reaching the right plugin (sample in `fixtures/`) |
| `fastify-route-options.test.mjs` | Fastify routes declared as objects (`app.route({ method, url, handler })`): method lists, keys inside `schema` left alone, a method or url that isn't written out skipped, routers with any name the file made, a non-router's `route()` left alone, and the website's requests reaching them |
| `nestjs.test.mjs` | NestJS: endpoints from `@Controller` and `@Get`/`@Post`… decorators with their full path and method name, several controllers and other classes in one file, decorators outside a NestJS file left alone, the website's requests reaching the right controller, and Health reading `@UseGuards`, `@Public()` and an app-wide guard (`APP_GUARD`, `useGlobalGuards`) for Nest routes only, with look-alikes that must not count (rate limits, a guard on the next class) (sample in `fixtures/`) |
| `route-tables.test.mjs` | endpoints listed as data: `{ method, path, handle }` objects with a plain path or a regular expression (captures as parameters, groups of words expanded, odd patterns dropped rather than widened), `Bun.serve({ routes })`, a website's list of its own requests left alone (`action`, `resolve` or `fetch` count only in a file that serves), Fastify route objects counted once, and Health still reading the Express routes beside a table (sample in `fixtures/`) |
| `route-tables.test.mjs` | endpoints listed as data: `{ method, path, handle }` objects with a plain path or a regular expression (captures as parameters, groups of words expanded, odd patterns dropped rather than widened), `Bun.serve({ routes })` (also inside a wrapping call, with method maps a helper is handed, and route maps spread in from other files, which stay data until a `Bun.serve` spreads them), a website's list of its own requests left alone (`action`, `resolve` or `fetch` count only in a file that serves), Fastify route objects counted once, and Health still reading the Express routes beside a table (sample in `fixtures/`) |
| `api-helpers.test.mjs` | requests made through an app's own helpers (`apiGet('/tasks')`, `apiSend('PATCH', …)`), a client's base address winning over a closer-looking address on the same server, and that base reaching the client's other files but not another app in the same folder |
| `request-matching.test.mjs` | a request whose address has a part filled in at run time (`/api/users/${id}`) reaching the endpoint with a parameter there rather than a fixed sibling (`/api/users/stripe`), also once the caller's base address is known, and the method read from the call's options on the lines below its address (sample Next.js app written by the test) |
| `url-builders.test.mjs` | web requests whose address a method of the same class builds (Angular services), directly or through another such method, and calls whose address wraps onto the next line; a builder's own template and a link that is never requested are left out, and a request on the line right after a builder is kept |
Expand Down
13 changes: 11 additions & 2 deletions skills/floorplan/scripts/lib/extract.mjs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Per-language, regex-based extraction of imports, exported symbols, HTTP routes and HTTP calls.
// Deliberately approximate: good enough to draw the map, cheap enough to run on any repo.
import { forwardIndexOf, importStatements, callArgs } from './common.mjs';
import { dataRoutes } from './route-tables.mjs';
import { dataRoutes, bunRouteSpreads, routeMaps } from './route-tables.mjs';

import path from 'node:path';

Expand Down Expand Up @@ -460,6 +460,12 @@ function extractJs(src, filePath) {
routes.push(...dataRoutes(code, at, { handlerOf: tableHandler, serves: dataAt > 0 || routerVars.size > 0 || SERVES.test(code), skip: objectRoutes.map((o) => o[3]) }));
for (const r of routes.slice(dataAt)) objectRoutes.push([r.line, r.line, r.path]);

// route maps a Bun.serve spreads into its routes, read where they're defined and placed by resolveRoutes
const bunSpreads = bunRouteSpreads(code);
const maps = /["'`]\/[^"'`\n]*["'`]\s*:/.test(code) ? routeMaps(code, at, tableHandler) : {};
// a map's own keys are its routes, not requests the file makes
const mapKeys = Object.values(maps).flat().map((r) => [r.line, r.path]);

routes.push(...keyedRouteTable(code, at));
if (/@nestjs\/common/.test(code) && /@Controller\s*\(/.test(code)) routes.push(...nestRoutes(code, at));

Expand All @@ -477,6 +483,9 @@ function extractJs(src, filePath) {
if (objectRoutes.length) for (let i = calls.length - 1; i >= 0; i--) {
if (objectRoutes.some(([a, b, url]) => calls[i].line >= a && calls[i].line <= b && calls[i].path === url)) calls.splice(i, 1);
}
if (mapKeys.length) for (let i = calls.length - 1; i >= 0; i--) {
if (mapKeys.some(([line, key]) => calls[i].line === line && key.endsWith(calls[i].path))) calls.splice(i, 1);
}
const seenCall = new Set(calls.map((c) => `${c.line}|${c.path}`));
for (const c of wrapperCalls(code, at)) if (!seenCall.has(`${c.line}|${c.path}`)) calls.push(c);
const built = urlBuilderCalls(code, at);
Expand All @@ -491,7 +500,7 @@ function extractJs(src, filePath) {
const callables = /\bhttpsCallable\b/.test(code) ? callableCalls(code, at) : { calls: [], wrappers: [] };
calls.push(...callables.calls);
if (/\.functions\s*\.\s*invoke\b/.test(code)) calls.push(...edgeInvokeCalls(code, at));
return { imports, symbols, routes, mounts, calls, hosts, ...(routerVars.size ? { routerVars: [...routerVars] } : {}), ...(triggers.length ? { triggers } : {}), ...(callables.wrappers.length ? { callableWrappers: callables.wrappers } : {}) };
return { imports, symbols, routes, mounts, calls, hosts, ...(routerVars.size ? { routerVars: [...routerVars] } : {}), ...(triggers.length ? { triggers } : {}), ...(callables.wrappers.length ? { callableWrappers: callables.wrappers } : {}), ...(bunSpreads.length ? { bunSpreads } : {}), ...(Object.keys(maps).length ? { routeMaps: maps } : {}) };
}

// ---------- Supabase Edge Functions ----------
Expand Down
92 changes: 77 additions & 15 deletions skills/floorplan/scripts/lib/route-tables.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -282,27 +282,89 @@ function routeTableRoutes(code, at, { handlerOf, serves, skip }) {
return found.filter((t) => t.serving || table).flatMap((t) => t.routes);
}

/** `routes: { "/api/x": { GET: a, POST: b }, "/y": handler }` in a file that starts Bun.serve. */
function bunRoutes(code, at, handlerOf) {
if (!/\bBun\.serve\s*(?:<[^>]*>)?\s*\(/.test(code)) return [];
const BUN_SERVE = /\bBun\.serve\s*(?:<[^>]*>)?\s*\(/;
// a call wrapping an object, `secureRoutes({` or `createRouteHandler({`: the object is what it's handed
const WRAPPED = /^[A-Za-z_$][\w$.]*\s*\(\s*\{/;

/**
* The methods of one route's value: a `{ GET: a, POST: b }` object, also when a helper is handed it
* (`createRouteHandler({ GET: a })`, whose keys must all be methods), or [] when the value serves every method.
*/
function methodsOf(code, e) {
if (e.value.startsWith('{')) return entries(code, e.start).filter((x) => VERBS.has(x.key));
if (!WRAPPED.test(e.value)) return [];
const inner = entries(code, code.indexOf('{', e.start));
return inner.length && inner.every((x) => VERBS.has(x.key)) ? inner : [];
}

/** The routes in the object literal whose `{` is at `open`: each `"/path"` key, per method. */
function objectRoutes(code, open, at, handlerOf) {
const routes = [];
for (const m of code.matchAll(/\broutes\s*:\s*\{/g)) {
for (const e of entries(code, m.index + m[0].length - 1)) {
if (!e.key.startsWith('/')) continue;
const line = at(e.at);
const methods = e.value.startsWith('{') ? entries(code, e.start).filter((x) => VERBS.has(x.key)) : [];
const targets = methods.length ? methods : [{ key: 'ANY', value: e.value }];
for (const t of targets) {
if (/^(?:false|null|undefined)$/.test(t.value)) continue; // left to the server's fetch()
// a static response (`new Response("ok")`, `Bun.file(…)`) serves the route too, with no handler to name
const handler = handlerOf(t.value)?.handler;
routes.push({ method: t.key, path: e.key, var: null, line, framework: 'table', ...(handler ? { handler } : {}) });
}
for (const e of entries(code, open)) {
if (!e.key.startsWith('/')) continue;
const line = at(e.at);
const methods = methodsOf(code, e);
const targets = methods.length ? methods : [{ key: 'ANY', value: e.value }];
for (const t of targets) {
if (/^(?:false|null|undefined)$/.test(t.value)) continue; // left to the server's fetch()
// a static response (`new Response("ok")`, `Bun.file(…)`) serves the route too, with no handler to name
const handler = handlerOf(t.value)?.handler;
routes.push({ method: t.key, path: e.key, var: null, line, framework: 'table', ...(handler ? { handler } : {}) });
}
}
return routes;
}

/** The names spread into the object literal whose `{` is at `open`: `{ ...appRoutes, ...api }` → [appRoutes, api]. */
function spreadsOf(code, open) {
const out = [];
const close = balancedEnd(code, open) - 1;
for (let i = open + 1; i < close;) {
const end = valueEnd(code, i, close);
const s = /^\s*\.\.\.\s*([A-Za-z_$][\w$]*)\s*$/.exec(code.slice(i, end));
if (s) out.push(s[1]);
i = end + 1;
}
return out;
}

/** Where each `routes:` object of Bun.serve opens, also inside one wrapping call (`routes: secureRoutes({ … })`). */
function bunRouteObjects(code) {
if (!BUN_SERVE.test(code)) return [];
return [...code.matchAll(/\broutes\s*:\s*(?:[A-Za-z_$][\w$.]*\s*\(\s*)?\{/g)].map((m) => m.index + m[0].length - 1);
}

/** `routes: { "/api/x": { GET: a, POST: b }, "/y": handler }` in a file that starts Bun.serve. */
function bunRoutes(code, at, handlerOf) {
return bunRouteObjects(code).flatMap((open) => objectRoutes(code, open, at, handlerOf));
}

/**
* The names a file's Bun.serve spreads into its routes (`routes: { ...appRoutes, ...apiRoutes }`). They name
* route maps kept elsewhere, in this file or another; resolveRoutes reads them where they are defined.
*/
export function bunRouteSpreads(code) {
return [...new Set(bunRouteObjects(code).flatMap((open) => spreadsOf(code, open)))];
}

/**
* Objects every key of which is a path, `const appRoutes = { "/": home, "/todos": createRouteHandler({ … }) }`,
* by name: { appRoutes: [route records] }. Just data on their own: they are endpoints only once a Bun.serve
* spreads them into its routes (bunRouteSpreads), which is what keeps a website's map of its own links out.
*/
export function routeMaps(code, at, handlerOf) {
const maps = {};
const def = /(?:^|[\s;])(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;{]{0,200})?=\s*\{/g;
for (const m of code.matchAll(def)) {
const open = m.index + m[0].length - 1;
const keys = entries(code, open);
if (!keys.length || !keys.every((e) => e.key.startsWith('/'))) continue;
const routes = objectRoutes(code, open, at, handlerOf);
if (routes.length) maps[m[1]] = routes;
}
return maps;
}

/**
* Route records ({ method, path, var, line, framework: 'table', handler? }) declared as data in
* comment-stripped JS/TS. `handlerOf(text)` names a value's handler ({ handler } or null when it isn't a
Expand Down
27 changes: 27 additions & 0 deletions skills/floorplan/scripts/lib/routes.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -112,8 +112,35 @@ function mountTarget(f, mount, byPath) {
return { file: f.path, v: head }; // defined in the same file
}

/**
* Route maps a Bun.serve spreads into its routes (`routes: secureRoutes({ ...appRoutes, ...apiRoutes })`)
* become endpoints of the file that defines them: the serving file itself, or the one it imports each name
* from, through barrels as exportOf follows them. A map nothing serves stays data.
*/
function placeBunRouteMaps(files, byPath) {
const placed = new Set();
const take = (t, name) => {
const key = `${t.path}|${name}`;
if (!placed.has(key)) { placed.add(key); t.routes = [...(t.routes || []), ...t.routeMaps[name]]; }
};
const fromExport = (file, name, depth) => {
const t = byPath.get(file);
if (!t || depth > 8) return;
if (t.routeMaps && Object.hasOwn(t.routeMaps, name)) return take(t, name);
const passed = (t.imports || []).filter((i) => i.reexport && i.files?.length);
for (const imp of passed) if (imp.exported && Object.hasOwn(imp.exported, name)) return fromExport(imp.files[0], imp.exported[name], depth + 1);
for (const imp of passed) if (!imp.exported) fromExport(imp.files[0], name, depth + 1);
};
for (const f of files) for (const name of isTestFile(f.path) ? [] : f.bunSpreads || []) {
if (f.routeMaps && Object.hasOwn(f.routeMaps, name)) { take(f, name); continue; }
const imp = (f.imports || []).find((i) => i.files?.length && i.locals && Object.hasOwn(i.locals, name));
if (imp && imp.locals[name] !== '*') fromExport(imp.files[0], imp.locals[name], 0);
}
}

export function resolveRoutes(files) {
const byPath = new Map(files.map((f) => [f.path, f]));
placeBunRouteMaps(files, byPath);
const servesOrMounts = (p) => { const t = byPath.get(p); return !!(t?.routes?.length || t?.mounts?.some((m) => m.var || m.spec)); };
// mountsTo[file] = [{ from, on, v, prefix, line }] (v === '*' applies to every route in the file)
const mountsTo = new Map();
Expand Down
56 changes: 56 additions & 0 deletions tests/route-tables.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,62 @@ test('Bun.serve routes: method objects give one endpoint per method, anything el
assert.deepEqual(routesOf(src.replace('Bun.serve(', 'configure('), 'server/index.ts'), []);
});

test('Bun.serve routes inside a wrapping call, and method maps a helper is handed', () => {
const src = [
`const server = Bun.serve({`,
` routes: secureRoutes({`,
` "/api/carts": createRouteHandler({ GET: carts.index, POST: carts.create }),`,
` "/api/health": cached({ ttl: 5, handler: health }),`,
` }),`,
`});`,
].join('\n');
assert.deepEqual(routesOf(src, 'server/index.ts'), [
'GET /api/carts table L3 index',
'POST /api/carts table L3 create',
// a helper handed anything but methods serves the route as a whole
'ANY /api/health table L4 -',
]);
});

test('route maps a Bun.serve spreads in are endpoints where they are defined, and only then', () => {
const project = makeProject({
'server/package.json': JSON.stringify({ name: 'server' }),
'server/src/main.ts': [
`import { cartRoutes } from "./routes/carts";`,
`import { adminRoutes } from "./routes";`,
`const healthRoutes = { "/api/health": () => new Response("ok") };`,
`Bun.serve({ port: 3000, routes: secureRoutes({ ...cartRoutes, ...adminRoutes, ...healthRoutes }) });`,
].join('\n'),
'server/src/routes/carts.ts': [
`export const cartRoutes = {`,
` "/api/carts": createRouteHandler({ GET: carts.index, POST: carts.create }),`,
` "/api/carts/:id": createRouteHandler({ DELETE: carts.destroy }),`,
`};`,
].join('\n'),
'server/src/routes/index.ts': `export { adminRoutes } from "./admin";\n`,
'server/src/routes/admin.ts': `export const adminRoutes = { "/admin": admin.index };\n`,
// every key a path, but nothing serves it: the website's own list of links
'server/src/links.ts': `export const footerLinks = { "/about": aboutPage, "/terms": termsPage };\n`,
'web/src/api.ts': `export const addToCart = () => fetch("/api/carts", { method: "POST" });\n`,
}, { arch: {
project: { name: 'bun-route-maps', summary: 'Test fixture.' },
nodes: [
{ id: 'web', label: 'Website', kind: 'ui', summary: 'The website.', paths: ['web/**'] },
{ id: 'api', label: 'Server', kind: 'service', summary: 'The Bun server.', paths: ['server/**'] },
],
} });
try {
run('scan.mjs', project);
run('build.mjs', project, '--no-claude-md');
const g = readGraph(project);
assert.deepEqual(routeKeys(g), ['ANY /admin', 'ANY /api/health', 'DELETE /api/carts/:id', 'GET /api/carts', 'POST /api/carts']);
const http = g.links.filter((l) => l.k === 'http').map((l) => `${l.a.slice(2)} -> ${l.b.slice(2)}`);
assert.deepEqual(http, ['web/src/api.ts -> server/src/routes/carts.ts']);
} finally {
cleanup(project);
}
});

test("a website's list of the requests it makes is not a route table", () => {
// `action`, `resolve` and `fetch` are as common in an API client's call list as in a server's routes
const client = [
Expand Down