// Every page route of a Next.js app, read off its `app/` directory (demo epic // D4, the privacy audit's route list) — derived, never typed: a page added to // either app is audited the next run without anyone listing it. // // A route is a directory holding a `page.{tsx,ts,jsx,js,mdx}`. Route groups // `(x)` add no segment; `api/`, private `_x` folders, parallel `@slot`s and // intercepting `(.)x` / `(..)x` routes are not pages of their own and are // left out. A dynamic segment (`[x]`, `[...x]`, `[[...x]]`) makes the route a // PATTERN, given concrete URLs by the audit's crawl (publish/privacyAudit.ts). // // SERVER ONLY (node:fs). import { readdirSync } from "node:fs"; import path from "node:path"; export type AppRoute = { // "/channels/[slug]/videos/[id]" — the app dir's own spelling. pattern: string; dynamic: boolean; // Matches a URL pathname of this route (dynamic routes only need it). match: RegExp; }; const PAGE_FILES = new Set(["page.tsx", "page.ts", "page.jsx", "page.js", "page.mdx"]); const escape = (s: string) => s.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&"); function segmentRegex(seg: string): { re: string; optional: boolean } { let m = /^\[\[\.\.\.[^\]]+\]\]$/.exec(seg); if (m) return { re: "(?:/.+)?", optional: true }; m = /^\[\.\.\.[^\]]+\]$/.exec(seg); if (m) return { re: "/.+", optional: false }; m = /^\[[^\]]+\]$/.exec(seg); if (m) return { re: "/[^/]+", optional: false }; return { re: `/${escape(seg)}`, optional: false }; } export function routeOf(segments: readonly string[]): AppRoute { const pattern = `/${segments.join("/")}`; const dynamic = segments.some((s) => s.startsWith("[")); const body = segments.map((s) => segmentRegex(s).re).join(""); return { pattern, dynamic, match: new RegExp(`^${body || "/"}/?$`) }; } /** Every page route under `appDir`, sorted by pattern. */ export function appRoutes(appDir: string): AppRoute[] { const out: AppRoute[] = []; const walk = (dir: string, segments: string[]) => { let entries; try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return; } if (entries.some((e) => e.isFile() && PAGE_FILES.has(e.name))) out.push(routeOf(segments)); for (const e of entries) { if (!e.isDirectory()) continue; const n = e.name; if (segments.length === 0 && n === "api") continue; if (n.startsWith("_") || n.startsWith("@") || n.startsWith(".") || n === "node_modules") continue; if (/^\(\.+\)/.test(n)) continue; if (/^\(.*\)$/.test(n)) walk(path.join(dir, n), segments); else walk(path.join(dir, n), [...segments, n]); } }; walk(appDir, []); const seen = new Set(); return out .filter((r) => (seen.has(r.pattern) ? false : (seen.add(r.pattern), true))) .sort((a, b) => a.pattern.localeCompare(b.pattern)); }