All files / src/test backendRoutes.ts

94.11% Statements 16/17
75% Branches 9/12
100% Functions 5/5
94.11% Lines 16/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82                                    1x           1x     5x         5x 5x 10940x 10940x 1955x             5x                     112114x       112114x                             714x 714x 277228x   714x 719x      
import fs from "node:fs";
import path from "node:path";
 
/**
 * The routes svc-core actually exposes, read from the generated API spec.
 *
 * `docs/spec/api/svc-core.md` is produced by `make spec` straight from the
 * FastAPI routers and CI fails when it is stale, so it is a faithful
 * description of the backend at the current commit — which makes it a usable
 * contract without standing a server up in the test run.
 */
export interface BackendRoute {
  method: string;
  /** Path template as FastAPI declares it, e.g. `/agents/{agent_id}`. */
  path: string;
  handler: string;
}
 
const SPEC = path.resolve(
  __dirname,
  "../../../../../docs/spec/api/svc-core.md",
);
 
/** `| `GET` | `/agents/{agent_id}` | `agent_id` | … |` */
const ROW = /^\|\s*`(GET|POST|PUT|PATCH|DELETE)`\s*\|\s*`([^`]+)`\s*\|\s*`?([^`|]*)`?\s*\|/;
 
export function loadBackendRoutes(): BackendRoute[] {
  Iif (!fs.existsSync(SPEC)) {
    throw new Error(
      `Backend API spec not found at ${SPEC}. Run \`make spec\` from the repo root.`,
    );
  }
  const routes: BackendRoute[] = [];
  for (const line of fs.readFileSync(SPEC, "utf8").split("\n")) {
    const m = ROW.exec(line.trim());
    if (m) {
      routes.push({
        method: m[1],
        path: m[2].trim(),
        handler: (m[3] ?? "").trim(),
      });
    }
  }
  return routes;
}
 
/**
 * Turn a FastAPI path template into a matcher.
 *
 * `{agent_id}` matches one path segment. Trailing slashes are treated as
 * insignificant, because FastAPI redirects between the two forms and the
 * frontend is inconsistent about which it sends.
 */
export function routeMatcher(template: string): RegExp {
  const escaped = template
    .replace(/\/+$/, "")
    .replace(/[.*+?^$()|[\]\\]/g, "\\$&")
    .replace(/\{[^}]+\}/g, "[^/]+");
  return new RegExp(`^${escaped}/?$`);
}
 
/**
 * Does any backend route serve this method + concrete path?
 *
 * A literal route wins over a parameterised one that could also match —
 * `/agents/new` is served by `new_agent`, not by `/agents/{agent_id}` — which
 * is the order FastAPI resolves them in.
 */
export function findBackendRoute(
  routes: BackendRoute[],
  method: string,
  urlPath: string,
): BackendRoute | undefined {
  const bare = urlPath.replace(/\/+$/, "") || "/";
  const candidates = routes.filter(
    (r) => r.method === method.toUpperCase() && routeMatcher(r.path).test(bare),
  );
  return (
    candidates.find((r) => !r.path.includes("{")) ?? candidates[0]
  );
}