Skip to content

See how your app actually fits together. An interactive, plain-English map of your codebase, drawn by Claude or Codex.

Scan: Firebase Cloud Functions as endpoints (#8)

Hayden Smithb7d109dcf2db
diff --git a/README.md b/README.md
index 291c21f..13fa5a4 100644
--- a/README.md
+++ b/README.md
@@ -210,7 +210,7 @@ flowchart LR
Scripts do the mechanical work: finding repos, parsing code in a dozen languages, matching web requests to endpoints, laying out the map. They're plain Node with no dependencies. Claude or Codex does the part only a reader can: deciding what the parts of your app *are*, and saying so plainly. Details in [How it works](docs/how-it-works.md).
**Languages:** TypeScript, JavaScript, Python, Go, Rust, Java, Kotlin, Scala, plus Vue, Svelte and Astro files, with lighter support for others.<br>
-**Endpoints:** Express, Koa, Hono, Next.js, Flask, FastAPI, Django, Go's net/http, Gin, Echo and chi, Actix, Axum, Spring.<br>
+**Endpoints:** Express, Koa, Hono, Next.js, Firebase Cloud Functions, Flask, FastAPI, Django, Go's net/http, Gin, Echo and chi, Actix, Axum, Spring.<br>
**Screens:** Next.js, React Router, Vue, SvelteKit, Remix, Nuxt, Astro, Expo, Angular, TanStack.
## What it adds to your project
diff --git a/docs/development.md b/docs/development.md
index ffea50a..6b16c62 100644
--- a/docs/development.md
+++ b/docs/development.md
@@ -77,6 +77,7 @@ The tests use Node's built-in test runner, so there's nothing to install (`npm t
| `helpers-lib.test.mjs` | globs, file types, command-line flags, fallback names |
| `secrets.test.mjs` | Health finds secrets, masks them, and ignores placeholders |
| `health.test.mjs` | which endpoints Health calls open to anyone (FastAPI sample in `fixtures/`) |
+| `firebase.test.mjs` | Firebase Cloud Functions: callables and onRequest functions as endpoints, the website's calls to them, Screens, Health, background functions (React + Firebase sample in `fixtures/`) |
| `sample-app.test.mjs` | a whole map of a two-repo shop: endpoints, cross-repo requests, Health, offline map, no secret values written, updates |
| `serve.test.mjs` | the map's server: 127.0.0.1 only, token and same-origin checks, nothing served from outside its folder |
| `ask.test.mjs` | asking through Claude Code or Codex: which one is used, read-only, follow-ups, sign-in errors (stand-in CLIs in `fixtures/fake-cli/`) |
diff --git a/docs/how-it-works.md b/docs/how-it-works.md
index 210de6e..d7ce21f 100644
--- a/docs/how-it-works.md
+++ b/docs/how-it-works.md
@@ -30,12 +30,13 @@ Supported languages: TypeScript and JavaScript (including Vue, Svelte and Astro
The most useful lines on the map connect a screen's web requests to the server code that answers them, often across repos. Floorplan:
-- **Finds endpoints** in Express, Koa, Hono, Next.js (route files and API routes), Flask, FastAPI, Django, Go (net/http, Gin, Echo, chi, Fiber), Actix, Axum and Spring.
+- **Finds endpoints** in Express, Koa, Hono, Next.js (route files and API routes), Firebase Cloud Functions, Flask, FastAPI, Django, Go (net/http, Gin, Echo, chi, Fiber), Actix, Axum and Spring.
- **Resolves prefixes**: Flask blueprints registered with a `url_prefix`, and Express routers mounted with `app.use('/api/users', usersRouter)`, including routers mounted inside other routers and mounts with middleware in front.
- **Finds requests** made with `fetch`, axios, ky, `requests` and similar, including:
- addresses built in a variable first: `const url = …; api.get(url)`;
- template strings with nested parts;
- small helpers in the same file that add a prefix, like `call('/definitions')`.
+- **Firebase Cloud Functions** are called by name rather than by address. A callable function (`onCall`) shows up as `CALL /approveItem` under the name your functions entry file exports it as, and the website's `httpsCallable(functions, 'approveItem')` calls reach it, including through a helper of your own that wraps `httpsCallable`. An `onRequest` function is an ordinary endpoint at `/<name>`, and an Express app passed to it keeps its own routes under that name. Scheduled and other background functions (Firestore, Storage, Pub/Sub) are listed for the AI to place on the map.
- **Matches** the two. When a request only spells out part of the address, because the base URL lives in settings, Floorplan learns each client's base path and prefers matches that fit it.
It's pattern matching, not a compiler, so it catches most connections but not all. If an important link is missing, ask for it to be added to the floorplan, and it will record it as an explicit connection.
diff --git a/skills/floorplan/SKILL.md b/skills/floorplan/SKILL.md
index 77ea2d6..0e3a7fa 100644
--- a/skills/floorplan/SKILL.md
+++ b/skills/floorplan/SKILL.md
@@ -141,5 +141,5 @@ People can also use **Flows → Request a new flow** to have the agent trace som
- Paths are relative to the codebase root and use forward slashes. In a multi-repo root they start with the repo folder, e.g. `api-service/src/**`.
- Route keys in descriptions are `"METHOD /full/path"` exactly as the worksheet prints them.
- The map makes no outside requests: the build inlines the layout engine (ELK) and fonts from `${CLAUDE_SKILL_DIR}/assets/vendor/`, so it works offline.
-- HTTP edges come from matching URL strings at call sites (including URLs kept in a variable first, nested template strings, and small same-file helpers that add a path prefix) to route definitions (Flask, FastAPI, Express, Next.js, Spring, Go and others), with blueprint/router prefixes resolved, nested mounts included. Treat them as strong hints. If an important service-to-service link is missing, add it as an explicit edge.
+- HTTP edges come from matching URL strings at call sites (including URLs kept in a variable first, nested template strings, and small same-file helpers that add a path prefix) to route definitions (Flask, FastAPI, Express, Next.js, Spring, Go and others), with blueprint/router prefixes resolved, nested mounts included. Firebase callables are matched by name (`CALL /<name>`, from `httpsCallable`) and `onRequest` functions by URL; the summary's FIREBASE FUNCTIONS section lists scheduled and trigger functions, which belong in a `worker` node. Treat them as strong hints. If an important service-to-service link is missing, add it as an explicit edge.
- Don't hand-edit graph.json or index.html; they're regenerated on every build.
diff --git a/skills/floorplan/assets/viewer.html b/skills/floorplan/assets/viewer.html
index 18105e0..97ddd3d 100644
--- a/skills/floorplan/assets/viewer.html
+++ b/skills/floorplan/assets/viewer.html
@@ -24,7 +24,7 @@
--n-ui: #7cc4ff; --n-service: #b49cff; --n-worker: #f0c36b; --n-library: #6fd7a8; --n-feature: #8fb4ff; --n-data: #63d2b8; --n-config: #a3a3a3;
--n-test: #f19ac7; --n-script: #f5a66b; --n-infra: #f28b8b; --n-external: #e3a6f0; --n-misc: #8b8b8b; --n-dir: #a3a3a3; --n-file: #a3a3a3;
--n-module: #a3a3a3; --n-symbol: #c7b8ff; --n-route: #7aa7ff; --n-connector: #8b8b8b;
- --m-GET: #6fd7a8; --m-POST: #7aa7ff; --m-PUT: #f0c36b; --m-PATCH: #c7a3ff; --m-DELETE: #f28b8b; --m-ANY: #a3a3a3;
+ --m-GET: #6fd7a8; --m-POST: #7aa7ff; --m-PUT: #f0c36b; --m-PATCH: #c7a3ff; --m-DELETE: #f28b8b; --m-CALL: #6fcfd9; --m-ANY: #a3a3a3;
--panel-w: 360px; --pw: calc(var(--panel-w) + 32px); --gutter: 28px;
color-scheme: dark;
}
@@ -476,7 +476,7 @@ const KIND_PLAIN = { contains: 'Contains', import: 'Uses', http: 'Web requests',
const KIND_LABEL = new Proxy({}, { get: (_, k) => (technical() ? KIND_TECH : KIND_PLAIN)[k] || k });
let technicalFlag = false;
const technical = () => technicalFlag;
-const METHODS = { GET: 1, POST: 1, PUT: 1, PATCH: 1, DELETE: 1 };
+const METHODS = { GET: 1, POST: 1, PUT: 1, PATCH: 1, DELETE: 1, CALL: 1 };
const store = { get(k, d) { try { return JSON.parse(localStorage.getItem('floorplan:' + k) ?? localStorage.getItem('show-code:' + k)) ?? d; } catch { return d; } }, set(k, v) { try { localStorage.setItem('floorplan:' + k, JSON.stringify(v)); } catch {} } };
const h = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
const fmt = (n) => n >= 10000 ? Math.round(n / 1000) + 'k' : n >= 1000 ? (n / 1000).toFixed(1) + 'k' : String(n);
diff --git a/skills/floorplan/references/schema.md b/skills/floorplan/references/schema.md
index 4897ef2..9fdafb7 100644
--- a/skills/floorplan/references/schema.md
+++ b/skills/floorplan/references/schema.md
@@ -80,6 +80,7 @@ Good candidates:
- publisher → queue → consumer (`queue` / `event`)
- webhooks coming in from third parties (`http`, from the external node to the handler)
- cron/scheduler → job (`call`)
+- Firebase background functions (schedules, Firestore/Storage/Pub/Sub triggers, from the scan's FIREBASE FUNCTIONS list) → a `worker` node; link the collection or topic that triggers them (`event`)
- calls through env-configured base URLs that the matcher missed (`http`)
## annotations
diff --git a/skills/floorplan/scripts/lib/extract.mjs b/skills/floorplan/scripts/lib/extract.mjs
index 5da7e61..a29143a 100644
--- a/skills/floorplan/scripts/lib/extract.mjs
+++ b/skills/floorplan/scripts/lib/extract.mjs
@@ -31,6 +31,10 @@ const FILE_EXT_TAIL = /\.(png|jpe?g|gif|svg|ico|webp|css|js|mjs|ts|tsx|json|html
function normalizeCallLiteral(raw) {
let s = raw.trim();
let host = null;
+ // a Firebase function's own address (https://us-central1-<project>.cloudfunctions.net/signDocument) is
+ // this app's backend, not an outside service
+ const fn = /^https?:\/\/[^/\s]*\.cloudfunctions\.net(\/.*)$/i.exec(s);
+ if (fn) s = fn[1];
const abs = /^https?:\/\/([^/${}\s]+)(.*)$/i.exec(s);
if (abs) { host = abs[1].toLowerCase(); s = abs[2] || '/'; }
// leading interpolations: ${API_BASE}/x, {BASE_URL}/x
@@ -135,7 +139,11 @@ function extractJs(src, filePath) {
const imports = [];
for (const m of all(/(?:^|[;\n}])\s*import\s+(?!\()((?:type\s+)?[^'";]*?)\s+from\s+["']([^"'\n]+)["']/g, code)) imports.push({ spec: m[2], ...parseImportClause(m[1]), line: at(m.index) });
for (const m of all(/(?:^|[;\n])\s*import\s+["']([^"'\n]+)["']/g, code)) imports.push({ spec: m[1], names: [], line: at(m.index) });
- for (const m of all(/\bexport\s+(?:type\s+)?(\*(?:\s+as\s+\w+)?|\{[^}]*\})\s+from\s+["']([^"'\n]+)["']/g, code)) imports.push({ spec: m[2], names: m[1].startsWith('{') ? parseImportClause(m[1]).names : [], line: at(m.index), reexport: true });
+ for (const m of all(/\bexport\s+(?:type\s+)?(\*(?:\s+as\s+\w+)?|\{[^}]*\})\s+from\s+["']([^"'\n]+)["']/g, code)) {
+ // `export { a as b } from` → exported { b: 'a' }, the names this file passes on
+ const clause = m[1].startsWith('{') ? parseImportClause(m[1]) : null;
+ imports.push({ spec: m[2], names: clause ? clause.names : [], ...(clause ? { exported: clause.locals } : {}), line: at(m.index), reexport: true });
+ }
for (const m of all(/\brequire\(\s*["']([^"'\n]+)["']\s*\)/g, code)) {
// `const usersRouter = require('./users')` / `const { a, b: c } = require(…)` bind local names
const before = code.slice(code.lastIndexOf('\n', m.index) + 1, m.index);
@@ -194,12 +202,93 @@ function extractJs(src, filePath) {
for (const method of methods.length ? methods : ['ANY']) routes.push({ method, path: p, var: null, line: 1, framework: 'next' });
}
+ const triggers = /firebase-functions/.test(code) ? firebaseFunctions(code, at, routes, mounts) : [];
+
const serverLine = /\b\w+\.(use|route)\(\s*["'`]\/|\b(?:app|server|fastify|hono|routes?|router|[a-z]+Router)\.(?:get|post|put|patch|delete|all|options|head)\(\s*["'`]\//;
const { calls, hosts } = extractCalls(code, at, { skip: serverLine });
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);
- return { imports, symbols, routes, mounts, calls, hosts };
+ const callables = /\bhttpsCallable\b/.test(code) ? callableCalls(code, at) : { calls: [], wrappers: [] };
+ calls.push(...callables.calls);
+ return { imports, symbols, routes, mounts, calls, hosts, ...(triggers.length ? { triggers } : {}), ...(callables.wrappers.length ? { callableWrappers: callables.wrappers } : {}) };
+}
+
+// ---------- Firebase Cloud Functions ----------
+
+// `export const approveItem = onCall(…)`, `exports.sign = functions.region('eu').https.onRequest(…)`,
+// `export const nightly = onSchedule('every day 03:00', …)`: the exported name, the chain before the
+// trigger (v1 style `functions.firestore.document('x')`), and the trigger itself
+const FIREBASE_FN = /(?:\bexport\s+(?:const|let|var)\s+|(?:^|[;\n])[ \t]*(?:const|let|var)\s+|\b(?:module\.)?exports\.)([A-Za-z_$][\w$]*)\s*(?::[^=\n]*)?=\s*((?:[A-Za-z_$][\w$]*(?:\([^()]*\))?\s*\.\s*)*)((?:on|before)[A-Z]\w*)\s*(?:<[^;]{0,300}?>)?\s*\(/g;
+const FIRST_STRING = /["'`]([^"'`\n]{1,120})["'`]/;
+
+/**
+ * Callable and onRequest functions become endpoints named after their export (CALL /approveItem,
+ * ANY /signDocument); Firebase serves an Express app passed to onRequest under the function's name,
+ * so that becomes a mount. Every other trigger (schedules, Firestore, Storage, Pub/Sub, Auth) is a
+ * background job, returned for the scan summary.
+ */
+function firebaseFunctions(code, at, routes, mounts) {
+ const triggers = [];
+ for (const m of code.matchAll(FIREBASE_FN)) {
+ const [, name, chain, on] = m;
+ const line = at(m.index + m[0].indexOf(name));
+ const args = code.slice(m.index + m[0].length, m.index + m[0].length + 300);
+ if (on === 'onCall' || on === 'onCallGenkit' || on === 'onRequest') {
+ routes.push({ method: on === 'onRequest' ? 'ANY' : 'CALL', path: '/' + name, var: null, line, framework: 'firebase', handler: name });
+ const app = on === 'onRequest' && /^\s*(?:\{[^{}]*\}\s*,\s*)?([A-Za-z_$][\w$]*)\s*\)/.exec(args)?.[1];
+ if (app) mounts.push({ prefix: '/' + name, var: app, line });
+ continue;
+ }
+ // v1 triggers name the provider in the chain (functions.pubsub.schedule(…).onRun); v2 ones are named for it
+ const provider = /\b(pubsub|firestore|storage|auth|database|tasks|analytics|remoteConfig|testLab)\b/.exec(chain)?.[1];
+ if (chain ? !provider : !/^(onSchedule|onDocument|onObject|onMessagePublished|onValue|onTaskDispatched|onCustomEventPublished|on\w*Alert|onTestMatrix|onConfigUpdated|before[A-Z])/.test(on)) continue;
+ // what it runs on: the last string in the chain (after any region), else the first argument
+ const what = [...chain.matchAll(new RegExp(FIRST_STRING, 'g'))].pop()?.[1] || FIRST_STRING.exec(/^[^)]*/.exec(args)[0])?.[1] || null;
+ triggers.push({ name, on: provider ? `${provider}.${on}` : on, ...(what ? { what } : {}), line });
+ }
+ return triggers;
+}
+
+// httpsCallable(functions, 'approveItem'), httpsCallable<Req, Res>(getFunctions(app), 'x') and the
+// older functions.httpsCallable('x'); the generic arguments may span lines
+const CALLABLE = /\bhttpsCallable\s*(?:<[^;]{0,300}?>)?\s*\(\s*(?:[^,()'"`]*(?:\([^()]*\))?\s*,\s*)?(["'`])([\w-]+)\1/g;
+const DEFS = /(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*(?:<[^>]*>)?\s*\(([^)]*)\)|\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s*)?(?:<[^>]*>\s*)?\(([^)]*)\)\s*(?::\s*[^=]+?)?=>/g;
+/** A callable's name as a path: grouped functions deploy as `group-name`, so 'items-approve' → /items/approve. */
+const callablePath = (name) => '/' + name.split('-').filter(Boolean).join('/');
+
+/**
+ * Calls to Firebase callable functions, by name, plus helpers that wrap httpsCallable
+ * (`const call = (name, data) => httpsCallable(functions, name)(data)`) and their same-file uses.
+ * The helpers' names are returned too, so scan.mjs can follow uses in the files that import them.
+ */
+function callableCalls(code, at) {
+ const calls = [...code.matchAll(CALLABLE)].map((m) => ({ path: callablePath(m[2]), method: 'CALL', line: at(m.index) }));
+ const wrappers = [];
+ for (const m of code.matchAll(DEFS)) {
+ const name = m[1] || m[3];
+ const p0 = /^[A-Za-z_$][\w$]*/.exec((m[2] ?? m[4]).trim())?.[0];
+ if (!p0) continue;
+ const body = code.slice(m.index + m[0].length, m.index + m[0].length + 400);
+ if (!new RegExp(`\\bhttpsCallable\\s*(?:<[^;]{0,300}?>)?\\s*\\(\\s*(?:[^,()'"\`]*(?:\\([^()]*\\))?\\s*,\\s*)?${p0}\\s*[,)]`).test(body)) continue;
+ wrappers.push(name);
+ calls.push(...callsVia(code, name, at(m.index)));
+ }
+ return { calls, wrappers };
+}
+
+/** Uses of a callable helper: `callFunction('approveItem', data)` → CALL /approveItem. */
+function callsVia(code, name, skipLine = 0) {
+ const out = [];
+ const re = new RegExp(`(?<![\\w$.])${name.replace(/\$/g, '\\$')}\\s*(?:<[^;]{0,300}?>)?\\s*\\(\\s*(["'\`])([\\w-]+)\\1`, 'g');
+ const at = lineIndex(code);
+ for (const m of code.matchAll(re)) {
+ const line = at(m.index);
+ if (line !== skipLine) out.push({ path: callablePath(m[2]), method: 'CALL', line });
+ }
+ return out;
}
+/** The same, in another file that imports the helper (under its local name there). */
+export const callableCallsVia = (src, localName) => callsVia(stripCStyle(src), localName);
/**
* Calls through a helper defined in the same file that adds a prefix and fetches, e.g.
@@ -210,8 +299,7 @@ function extractJs(src, filePath) {
*/
function wrapperCalls(code, at) {
const out = [];
- const defs = /(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*(?:<[^>]*>)?\s*\(([^)]*)\)|\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s*)?(?:<[^>]*>\s*)?\(([^)]*)\)\s*(?::\s*[^=]+?)?=>/g;
- for (const m of code.matchAll(defs)) {
+ for (const m of code.matchAll(DEFS)) {
const name = m[1] || m[3];
const params = (m[2] ?? m[4]).split(',').map((p) => p.trim()).filter(Boolean);
const pnames = params.map((p) => /^[A-Za-z_$][\w$]*/.exec(p)?.[0]);
@@ -482,9 +570,12 @@ function addDocs(src, lang, r) {
if (d) s.doc = d;
}
// A route's handler is the first declaration after it (decorator-style frameworks).
- const syms = (r.symbols || []).slice().sort((a, b) => a.line - b.line);
+ // (a Firebase function's export isn't the handler of the Express routes above it)
+ const fbNames = new Set((r.routes || []).filter((rt) => rt.framework === 'firebase').map((rt) => rt.handler));
+ const syms = (r.symbols || []).filter((s) => !fbNames.has(s.name)).sort((a, b) => a.line - b.line);
for (const rt of r.routes || []) {
if (rt.framework === 'next') { rt.handler = rt.method; continue; }
+ if (rt.framework === 'firebase') { const d = r.symbols.find((s) => s.name === rt.handler)?.doc || commentBefore(lines, rt.line - 1); if (d) rt.doc = d; continue; }
const h = syms.find((s) => s.line >= rt.line && s.line - rt.line <= 12);
if (h) { rt.handler = h.name; if (h.doc) rt.doc = h.doc; }
else if (lang === 'python') {
diff --git a/skills/floorplan/scripts/lib/health.mjs b/skills/floorplan/scripts/lib/health.mjs
index 17526d4..446fc50 100644
--- a/skills/floorplan/scripts/lib/health.mjs
+++ b/skills/floorplan/scripts/lib/health.mjs
@@ -178,7 +178,8 @@ const isDbDep = (name) => DB_DEPENDENCY.test(snake(name));
const isGuardDep = (name) => isGuardName(name) && !isDbDep(name);
// A handler body that inspects the caller itself.
const INLINE_CHECK = /request\.headers(?:\.get)?\(?\s*\[?\s*['"](authorization|x-api-key|x-[\w-]*(token|key|secret|signature)[\w-]*)['"]|req\.headers(?:\.|\[\s*['"])(authorization|x-api-key)|\b(verify|check|require|validate|authenticate|authorize)_?\w*(auth|token|session|user|key|signature|webhook|hmac|jwt|device|staff|admin|permission|role|request|caller)\w*\s*\(|\bcurrent_user\b|get_jwt_identity|verify_jwt_in_request|compare_digest|abort\(\s*40[13]\b|,\s*40[13]\s*\)?\s*$|status(?:Code)?\s*[:=(]\s*40[13]\b|\.status\(\s*40[13]\s*\)|req\.user\b|req\.session\.user|req\.auth\b|jwt\.verify|jwtVerify|getServerSession|auth\(\)|currentUser\(|getAuth\(|auth\.getUser|getSession\(|verifyIdToken|getToken\(/m;
-const SIGNATURE_CHECK = /hmac|signature|verify_?webhook|construct_?event|x-hub-signature|compare_digest|svix|webhooks?\.verify|jwt\.decode|oidc|id_token|authenticated|verify_\w*(token|request|push)/i;
+const FIREBASE_CHECK = /\b\w+\.auth\b(?!\s*\()|HttpsError\(\s*["'](unauthenticated|permission-denied)["']|enforceAppCheck\s*:\s*true|\b\w+\.app\b\s*(==|!=|===|!==)\s*(undefined|null)|!\s*\w+\.app\b/;
+const SIGNATURE_CHECK =/hmac|signature|verify_?webhook|construct_?event|x-hub-signature|compare_digest|svix|webhooks?\.verify|jwt\.decode|oidc|id_token|authenticated|verify_\w*(token|request|push)/i;
const NEXT_GUARD = /getServerSession|\bauth\(\)|currentUser\(|getAuth\(|auth\.getUser|supabase\.auth\.get(User|Session)|getSession\(|verifyIdToken|jwt\.verify|jwtVerify|getToken\(|clerkClient|requireAuth|requireUser|withAuth|validateRequest|headers\(\)\.get\(\s*['"]authorization|status:\s*40[13]\b/;
const NEXT_MIDDLEWARE_GUARD = /getToken|withAuth|clerkMiddleware|authMiddleware|auth\(|supabase|getSession|jwtVerify|jwt\.verify|cookies\.get\([^)]*(session|token|auth)|redirect\([^)]*login/i;
@@ -299,6 +300,17 @@ function jsRoutes(src, f, out) {
routes.forEach((r, idx) => {
const rec = { k: 'route', line: r.line, method: r.method };
+ if (r.framework === 'firebase') {
+ // a callable checks request.auth (v1: context.auth) or turns on App Check; an onRequest function
+ // checks a token or signature itself, like any other handler
+ const next = routes.slice(idx + 1).find((x) => x.line > r.line)?.line || r.line + 80;
+ const body = lines.slice(r.line - 1, Math.min(next - 1, r.line + 80)).join('\n');
+ if (FIREBASE_CHECK.test(body) || INLINE_CHECK.test(body)) rec.via = 'inline';
+ if (SIGNATURE_CHECK.test(body)) rec.signed = true;
+ rec.fn = r.handler;
+ out.push(rec);
+ return;
+ }
if (r.framework === 'next') {
if (NEXT_GUARD.test(src)) rec.via = 'inline';
if (SIGNATURE_CHECK.test(src)) rec.signed = true;
diff --git a/skills/floorplan/scripts/lib/routes.mjs b/skills/floorplan/scripts/lib/routes.mjs
index 711962f..614aeb6 100644
--- a/skills/floorplan/scripts/lib/routes.mjs
+++ b/skills/floorplan/scripts/lib/routes.mjs
@@ -65,11 +65,33 @@ export function resolveRoutes(files) {
return each.reduce((a, b) => a.filter((x) => b.includes(x)));
};
+ // Firebase deploys a function under the name the functions entry file exports it as, so
+ // `export { approveItem as approve } from './items'` renames it: `${file}|approveItem` -> ['approve']
+ const exportedAs = new Map();
+ for (const f of files) for (const imp of f.imports || []) {
+ if (!imp.exported || !imp.files?.length) continue;
+ for (const [as, orig] of Object.entries(imp.exported)) {
+ if (as === orig) continue;
+ const k = `${imp.files[0]}|${orig}`;
+ exportedAs.set(k, [...(exportedAs.get(k) || []), as]);
+ }
+ }
+
+ // onRequest(app) serves an Express app under the function's name; its own routes are the endpoints
+ const byPath = new Map(files.map((f) => [f.path, f]));
+ const wrapsApp = (file, prefix) => [...mountsTo].some(([to, ms]) => ms.some((m) => m.from === file && m.prefix === prefix) && byPath.get(to)?.routes?.some((r) => r.framework !== 'firebase'));
+
const routes = [];
for (const f of files) {
// Test files define throwaway apps and stub servers; their routes aren't part of the system.
if (!f.routes?.length || TEST_FILE.test(f.path)) continue;
for (const r of f.routes) {
+ if (r.framework === 'firebase') {
+ if (r.method === 'ANY' && wrapsApp(f.path, r.path)) continue;
+ // served at its own name, whatever the file's routers are mounted under
+ for (const name of exportedAs.get(`${f.path}|${r.handler}`) || [r.handler]) routes.push({ file: f.path, method: r.method, path: '/' + name, line: r.line, handler: name, framework: 'firebase', ...(r.doc ? { doc: r.doc } : {}) });
+ continue;
+ }
const defPrefix = (r.var && f.routers?.[r.var]) || '';
const mw = mountMw(f.path, r.var);
for (const mp of outerPrefixes(f.path, r.var)) routes.push({ file: f.path, method: r.method, path: joinPath(mp, defPrefix, r.path), line: r.line, ...(r.handler ? { handler: r.handler } : {}), ...(r.doc ? { doc: r.doc } : {}), ...(mw.length ? { mountMw: mw } : {}) });
@@ -123,6 +145,8 @@ export function matchCalls(files, routes) {
let best = -Infinity, hits = [];
for (const r of rs) {
if (r.file === f.path) continue;
+ // a Firebase callable (CALL) is only ever reached through httpsCallable, and only reaches callables
+ if ((call.method === 'CALL') !== (r.method === 'CALL')) continue;
if (call.method && r.method !== 'ANY' && r.method !== call.method) continue;
const sc = score(cs, r.segs);
if (!sc) continue;
diff --git a/skills/floorplan/scripts/scan.mjs b/skills/floorplan/scripts/scan.mjs
index 2c48f0a..6da05d7 100644
--- a/skills/floorplan/scripts/scan.mjs
+++ b/skills/floorplan/scripts/scan.mjs
@@ -9,7 +9,7 @@ import fs from 'node:fs';
import { createHash } from 'node:crypto';
import path from 'node:path';
import { discover, gitFiles, gitInfo, classify, toPosix, parseArgs, fmtNum, HARD_IGNORE_DIRS, MAP_DIR, LEGACY_MAP_DIR, isMapDir, mapDir, keepOutOfGit } from './lib/common.mjs';
-import { extract } from './lib/extract.mjs';
+import { extract, callableCallsVia } from './lib/extract.mjs';
import { findIssues } from './lib/health.mjs';
import { findScreens } from './lib/screens.mjs';
import { createResolver } from './lib/resolve.mjs';
@@ -126,6 +126,17 @@ for (const e of edges) {
else edgeMap.set(k, { ...e, count: 1 });
}
+// Firebase callable helpers used from other files: `import { callFunction } from '../lib/firebase'`,
+// then callFunction('approveItem', data) calls the approveItem function
+const wrappers = new Map(files.filter((f) => f.callableWrappers).map((f) => [f.path, new Set(f.callableWrappers)]));
+if (wrappers.size) for (const f of files) {
+ const via = (f.imports || []).flatMap((imp) => Object.entries(imp.locals || {}).filter(([, orig]) => imp.files?.some((t) => wrappers.get(t)?.has(orig))).map(([local]) => local));
+ if (!via.length) continue;
+ let src;
+ try { src = fs.readFileSync(path.join(root, f.path), 'utf8'); } catch { continue; }
+ for (const local of via) f.calls = [...(f.calls || []), ...callableCallsVia(src, local)];
+}
+
// ---------- 4. routes and HTTP calls ----------
const routes = resolveRoutes(files);
const http = matchCalls(files, routes);
@@ -148,6 +159,7 @@ const scan = {
...(f.tooLarge ? { tooLarge: true } : {}),
...(f.issues ? { issues: f.issues } : {}),
...(f.screens ? { screens: f.screens } : {}),
+ ...(f.triggers ? { triggers: f.triggers } : {}),
})),
edges: [...edgeMap.values()].map(({ from, to, names, count, dynamic }) => ({ from, to, ...(names.length ? { names } : {}), ...(count > 1 ? { count } : {}), ...(dynamic ? { dynamic } : {}) })),
externals: [...externals.values()].map((e) => ({ id: `${e.eco}:${e.name}`, eco: e.eco, name: e.name, imports: e.count, files: e.files.size })),
@@ -251,6 +263,20 @@ for (const h of http) {
for (const [k, v] of [...httpDir.entries()].sort((a, b) => b[1] - a[1]).slice(0, 12)) line(` ${String(v).padStart(5)} ${k}`);
line();
+// Firebase Cloud Functions: endpoints are already in the HTTP line; background ones need a place on the map
+const fbRoutes = files.flatMap((f) => (f.routes || []).filter((r) => r.framework === 'firebase'));
+const triggers = files.flatMap((f) => (f.triggers || []).map((t) => ({ ...t, file: f.path })));
+if (fbRoutes.length || triggers.length) {
+ const callable = fbRoutes.filter((r) => r.method === 'CALL').length;
+ line(`FIREBASE FUNCTIONS ${callable} callable, ${fbRoutes.length - callable} onRequest, ${triggers.length} background`);
+ if (triggers.length) {
+ line(' background (schedules and triggers; place them in a worker node):');
+ for (const t of triggers.slice(0, 20)) line(` ${t.name} ${t.on}${t.what ? ` "${t.what}"` : ''} ${t.file}:${t.line}`);
+ if (triggers.length > 20) line(` … ${triggers.length - 20} more`);
+ }
+ line();
+}
+
const topExt = scan.externals.sort((a, b) => b.files - a.files).slice(0, 25);
line(`EXTERNAL PACKAGES (top ${topExt.length} by importing files)`);
line(' ' + topExt.map((e) => `${e.id}(${e.files})`).join(' '));
diff --git a/tests/firebase.test.mjs b/tests/firebase.test.mjs
new file mode 100644
index 0000000..cb52119
--- /dev/null
+++ b/tests/firebase.test.mjs
@@ -0,0 +1,96 @@
+// Firebase Cloud Functions (#8): callables and onRequest functions are endpoints named after their
+// export, the website's httpsCallable and fetch calls reach them, and Screens and Health follow.
+import { test, before, after } from 'node:test';
+import assert from 'node:assert/strict';
+import fs from 'node:fs';
+import path from 'node:path';
+import { REPO, lib, makeProject, run, readGraph, routeKeys, openEndpoints, cleanup } from './helpers.mjs';
+
+const { extract } = await lib('extract.mjs');
+const { matchCalls } = await lib('routes.mjs');
+
+let root, graph, summary;
+before(() => {
+ root = makeProject({}, { arch: {
+ project: { name: 'firebase-app', summary: 'Test fixture.' },
+ nodes: [
+ { id: 'web', label: 'Website', kind: 'ui', summary: 'The website.', paths: ['web/**'] },
+ { id: 'fn', label: 'Functions', kind: 'service', summary: 'Cloud Functions.', paths: ['functions/**'] },
+ ],
+ } });
+ fs.cpSync(path.join(REPO, 'tests', 'fixtures', 'firebase-app'), root, { recursive: true });
+ summary = run('scan.mjs', root);
+ run('build.mjs', root, '--no-claude-md');
+ graph = readGraph(root);
+});
+after(() => cleanup(root));
+
+test('callables and onRequest functions are endpoints, under the name the entry file exports', () => {
+ // archiveItem is exported as retireItem; api is an Express app, so its own routes are the endpoints
+ assert.deepEqual(routeKeys(graph), [
+ 'ANY /legacyPing', 'ANY /signDocument', 'CALL /approveItem', 'CALL /legacyStats', 'CALL /retireItem',
+ 'GET /api/reports', 'POST /api/reports',
+ ]);
+ assert.equal(graph.routes.find((r) => r.p === '/approveItem').d, 'Approves an item once an admin has reviewed it.');
+ assert.equal(graph.routes.find((r) => r.p === '/api/reports' && r.m === 'GET').name, 'Get api reports');
+});
+
+test("the website's calls reach the functions: httpsCallable, a helper around it, and fetch", () => {
+ const http = graph.links.filter((l) => l.k === 'http').map((l) => `${l.a.slice(2)} -> ${l.b.slice(2)} ${l.labels.join(', ')}`).sort();
+ assert.deepEqual(http, [
+ 'web/src/lib/firebase.ts -> functions/src/docs/api.ts GET /api/reports',
+ 'web/src/lib/firebase.ts -> functions/src/docs/signDocument.ts ANY /signDocument',
+ 'web/src/pages/Items.tsx -> functions/src/items/itemCallables.ts CALL /approveItem, CALL /retireItem',
+ 'web/src/pages/Items.tsx -> functions/src/legacy/v1.js CALL /legacyStats',
+ ]);
+});
+
+test('Screens shows the server code behind a page that calls functions', () => {
+ const items = graph.screens.find((s) => s.url === '/items');
+ assert.ok(items, 'the /items screen');
+ const server = items.behind.filter((b) => b.kind === 'server').map((b) => b.id);
+ assert.deepEqual(server, ['f:functions/src/items/itemCallables.ts', 'f:functions/src/legacy/v1.js']);
+});
+
+test('Health: a callable that checks request.auth or context.auth is protected; one that does not is open', () => {
+ assert.deepEqual(openEndpoints(graph), ['ANY /legacyPing', 'CALL /retireItem', 'GET /api/reports', 'POST /api/reports']);
+});
+
+test('background functions are listed in the scan summary', () => {
+ assert.match(summary, /FIREBASE FUNCTIONS {2}3 callable, 3 onRequest, 3 background/);
+ assert.match(summary, /nightlyCleanup {2}onSchedule "every day 03:00"/);
+ assert.match(summary, /onOrderCreated {2}onDocumentCreated "orders\/\{orderId\}"/);
+ assert.match(summary, /weeklyDigest {2}pubsub\.onRun "every monday 09:00"/);
+});
+
+test('v1 chains, multi-line generics, grouped names and cloudfunctions.net addresses', () => {
+ const fn = extract([
+ `const functions = require('firebase-functions');`,
+ `exports.report = functions.region('europe-west1').runWith({ memory: '1GB' }).https.onRequest((req, res) => res.end());`,
+ `exports.onSignup = functions.auth.user().onCreate(async (user) => {});`,
+ `const unsubscribe = db.collection('x').onSnapshot(() => {});`,
+ ].join('\n'), 'javascript', 'functions/index.js');
+ assert.deepEqual(fn.routes.map((r) => `${r.method} ${r.path}`), ['ANY /report']);
+ assert.deepEqual(fn.triggers.map((t) => `${t.name} ${t.on}`), ['onSignup auth.onCreate']);
+
+ const web = extract([
+ `import { httpsCallable } from 'firebase/functions';`,
+ `const a = httpsCallable<`,
+ ` Req,`,
+ ` Promise<Res>`,
+ `>(getFunctions(app), 'items-approve');`,
+ `const b = functions.httpsCallable('legacyName');`,
+ 'fetch(`https://${REGION}-${PROJECT}.cloudfunctions.net/report`);',
+ ].join('\n'), 'typescript', 'web/api.ts');
+ assert.deepEqual(web.calls.map((c) => `${c.method} ${c.path}`).sort(), ['CALL /items/approve', 'CALL /legacyName', 'null /report']);
+ assert.deepEqual(web.hosts, []);
+});
+
+test('a callable only matches callables, and a URL never matches a callable', () => {
+ const routes = [
+ { file: 'fn/a.ts', method: 'CALL', path: '/approve' },
+ { file: 'api/b.ts', method: 'ANY', path: '/approve' },
+ ];
+ const files = [{ path: 'web/x.ts', calls: [{ path: '/approve', method: 'CALL', line: 1 }, { path: '/approve', method: 'POST', line: 2 }] }];
+ assert.deepEqual(matchCalls(files, routes).map((h) => `${h.line} ${h.to}`), ['1 fn/a.ts', '2 api/b.ts']);
+});
diff --git a/tests/fixtures/firebase-app/functions/src/docs/api.ts b/tests/fixtures/firebase-app/functions/src/docs/api.ts
new file mode 100644
index 0000000..0425227
--- /dev/null
+++ b/tests/fixtures/firebase-app/functions/src/docs/api.ts
@@ -0,0 +1,8 @@
+import express from 'express';
+import { onRequest } from 'firebase-functions/v2/https';
+
+const app = express();
+app.get('/reports', (req, res) => res.json([]));
+app.post('/reports', (req, res) => res.json({}));
+
+export const api = onRequest(app);
diff --git a/tests/fixtures/firebase-app/functions/src/docs/signDocument.ts b/tests/fixtures/firebase-app/functions/src/docs/signDocument.ts
new file mode 100644
index 0000000..aaf15ac
--- /dev/null
+++ b/tests/fixtures/firebase-app/functions/src/docs/signDocument.ts
@@ -0,0 +1,8 @@
+import { onRequest } from 'firebase-functions/v2/https';
+import { getAuth } from 'firebase-admin/auth';
+
+export const signDocument = onRequest({ cors: true }, async (req, res) => {
+ const token = (req.headers.authorization || '').replace('Bearer ', '');
+ await getAuth().verifyIdToken(token);
+ res.json({ signed: true });
+});
diff --git a/tests/fixtures/firebase-app/functions/src/index.ts b/tests/fixtures/firebase-app/functions/src/index.ts
new file mode 100644
index 0000000..8fef19b
--- /dev/null
+++ b/tests/fixtures/firebase-app/functions/src/index.ts
@@ -0,0 +1,6 @@
+// The functions Firebase deploys: everything exported from here.
+export { approveItem, archiveItem as retireItem } from './items/itemCallables';
+export { signDocument } from './docs/signDocument';
+export { api } from './docs/api';
+export { nightlyCleanup, onOrderCreated } from './jobs/background';
+export { legacyStats, legacyPing } from './legacy/v1';
diff --git a/tests/fixtures/firebase-app/functions/src/items/itemCallables.ts b/tests/fixtures/firebase-app/functions/src/items/itemCallables.ts
new file mode 100644
index 0000000..ccb072e
--- /dev/null
+++ b/tests/fixtures/firebase-app/functions/src/items/itemCallables.ts
@@ -0,0 +1,15 @@
+import { onCall, HttpsError } from 'firebase-functions/v2/https';
+
+/** Approves an item once an admin has reviewed it. */
+export const approveItem = onCall<{ id: string }, Promise<{ ok: boolean }>>(
+ { region: 'europe-west1' },
+ async (request) => {
+ if (!request.auth) throw new HttpsError('unauthenticated', 'Sign in first');
+ return { ok: true };
+ },
+);
+
+/** Archives an item. Anyone can call it. */
+export const archiveItem = onCall(async (request) => {
+ return { ok: !!request.data.id };
+});
diff --git a/tests/fixtures/firebase-app/functions/src/jobs/background.ts b/tests/fixtures/firebase-app/functions/src/jobs/background.ts
new file mode 100644
index 0000000..b15687b
--- /dev/null
+++ b/tests/fixtures/firebase-app/functions/src/jobs/background.ts
@@ -0,0 +1,5 @@
+import { onSchedule } from 'firebase-functions/v2/scheduler';
+import { onDocumentCreated } from 'firebase-functions/v2/firestore';
+
+export const nightlyCleanup = onSchedule('every day 03:00', async () => {});
+export const onOrderCreated = onDocumentCreated('orders/{orderId}', async (event) => {});
diff --git a/tests/fixtures/firebase-app/functions/src/legacy/v1.js b/tests/fixtures/firebase-app/functions/src/legacy/v1.js
new file mode 100644
index 0000000..425ff9d
--- /dev/null
+++ b/tests/fixtures/firebase-app/functions/src/legacy/v1.js
@@ -0,0 +1,8 @@
+const functions = require('firebase-functions');
+
+exports.legacyStats = functions.region('us-east1').https.onCall((data, context) => {
+ if (!context.auth) throw new functions.https.HttpsError('unauthenticated', 'no');
+ return { n: 1 };
+});
+exports.legacyPing = functions.https.onRequest((req, res) => res.send('ok'));
+exports.weeklyDigest = functions.pubsub.schedule('every monday 09:00').onRun(async () => null);
diff --git a/tests/fixtures/firebase-app/web/src/App.tsx b/tests/fixtures/firebase-app/web/src/App.tsx
new file mode 100644
index 0000000..b07b365
--- /dev/null
+++ b/tests/fixtures/firebase-app/web/src/App.tsx
@@ -0,0 +1,12 @@
+import { BrowserRouter, Routes, Route } from 'react-router-dom';
+import Items from './pages/Items';
+
+export default function App() {
+ return (
+ <BrowserRouter>
+ <Routes>
+ <Route path="/items" element={<Items />} />
+ </Routes>
+ </BrowserRouter>
+ );
+}
diff --git a/tests/fixtures/firebase-app/web/src/lib/app.ts b/tests/fixtures/firebase-app/web/src/lib/app.ts
new file mode 100644
index 0000000..3caca98
--- /dev/null
+++ b/tests/fixtures/firebase-app/web/src/lib/app.ts
@@ -0,0 +1,2 @@
+import { initializeApp } from 'firebase/app';
+export const app = initializeApp({ projectId: 'demo' });
diff --git a/tests/fixtures/firebase-app/web/src/lib/firebase.ts b/tests/fixtures/firebase-app/web/src/lib/firebase.ts
new file mode 100644
index 0000000..1a740cb
--- /dev/null
+++ b/tests/fixtures/firebase-app/web/src/lib/firebase.ts
@@ -0,0 +1,14 @@
+import { getFunctions, httpsCallable } from 'firebase/functions';
+import { app } from './app';
+
+export const functions = getFunctions(app);
+const API_BASE = import.meta.env.VITE_FUNCTIONS_URL;
+
+/** Calls a callable function by name. */
+export const callFunction = <T>(name: string, data?: unknown) => httpsCallable(functions, name)(data) as Promise<T>;
+
+export async function signDocument(id: string) {
+ return fetch(`${API_BASE}/signDocument`, { method: 'POST', body: JSON.stringify({ id }) });
+}
+
+export const reports = () => fetch(`${API_BASE}/api/reports`);
diff --git a/tests/fixtures/firebase-app/web/src/pages/Items.tsx b/tests/fixtures/firebase-app/web/src/pages/Items.tsx
new file mode 100644
index 0000000..e40e587
--- /dev/null
+++ b/tests/fixtures/firebase-app/web/src/pages/Items.tsx
@@ -0,0 +1,13 @@
+import { httpsCallable } from 'firebase/functions';
+import { functions, callFunction } from '../lib/firebase';
+
+const approveItem = httpsCallable<
+ { id: string },
+ { ok: boolean }
+>(functions, 'approveItem');
+
+export default function Items() {
+ const retire = (id: string) => callFunction('retireItem', { id });
+ const stats = () => callFunction('legacyStats');
+ return <button onClick={() => approveItem({ id: '1' })}>Approve</button>;
+}