@rebasepro/cli 0.33.1 → 0.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/dist/{agent-setup-Cg_zBWoW.js → agent-setup-CGeAuP0Q.js} +2 -2
  2. package/dist/{agent-setup-Cg_zBWoW.js.map → agent-setup-CGeAuP0Q.js.map} +1 -1
  3. package/dist/{api-keys-fPQ55DCm.js → api-keys-DaWN8dyI.js} +3 -3
  4. package/dist/{api-keys-fPQ55DCm.js.map → api-keys-DaWN8dyI.js.map} +1 -1
  5. package/dist/{api-TbmW33D7.js → api-zx1wSK5a.js} +2 -2
  6. package/dist/{api-TbmW33D7.js.map → api-zx1wSK5a.js.map} +1 -1
  7. package/dist/{apps-DBTRoOeP.js → apps-D6vtDrkJ.js} +3 -3
  8. package/dist/{apps-DBTRoOeP.js.map → apps-D6vtDrkJ.js.map} +1 -1
  9. package/dist/{auth-BpyYLEFY.js → auth-DY7kU0z-.js} +8 -8
  10. package/dist/{auth-BpyYLEFY.js.map → auth-DY7kU0z-.js.map} +1 -1
  11. package/dist/{auth-session-B6aT0Dyj.js → auth-session-DCG96UGH.js} +4 -4
  12. package/dist/{auth-session-B6aT0Dyj.js.map → auth-session-DCG96UGH.js.map} +1 -1
  13. package/dist/{build-E5hfEWKj.js → build-D0egCUfU.js} +4 -4
  14. package/dist/{build-E5hfEWKj.js.map → build-D0egCUfU.js.map} +1 -1
  15. package/dist/{bundle-CIiKGrte.js → bundle-DhdhtD8K.js} +3 -3
  16. package/dist/{bundle-CIiKGrte.js.map → bundle-DhdhtD8K.js.map} +1 -1
  17. package/dist/{cloud-DNJyUU0T.js → cloud-DOR7bxDw.js} +218 -27
  18. package/dist/cloud-DOR7bxDw.js.map +1 -0
  19. package/dist/{command-Bks5xkrQ.js → command-BzSP5gBh.js} +2 -2
  20. package/dist/{command-Bks5xkrQ.js.map → command-BzSP5gBh.js.map} +1 -1
  21. package/dist/commands/cloud/db-connect.d.ts +31 -1
  22. package/dist/commands/cloud/db-query.d.ts +16 -0
  23. package/dist/commands/cloud/index.d.ts +1 -0
  24. package/dist/commands/cloud/resources.d.ts +19 -1
  25. package/dist/commands/dev.d.ts +15 -0
  26. package/dist/commands/users.d.ts +1 -0
  27. package/dist/{context-BOMEoKxn.js → context-xt20FMFA.js} +5 -1
  28. package/dist/{context-BOMEoKxn.js.map → context-xt20FMFA.js.map} +1 -1
  29. package/dist/{cron-CpUsQ739.js → cron-BGkXIB1N.js} +4 -4
  30. package/dist/{cron-CpUsQ739.js.map → cron-BGkXIB1N.js.map} +1 -1
  31. package/dist/{cron-ZRXsla0v.js → cron-CJ6Xk42E.js} +3 -3
  32. package/dist/{cron-ZRXsla0v.js.map → cron-CJ6Xk42E.js.map} +1 -1
  33. package/dist/{data-BJ9AZFUC.js → data-BpkvtCUe.js} +3 -3
  34. package/dist/{data-BJ9AZFUC.js.map → data-BpkvtCUe.js.map} +1 -1
  35. package/dist/{debug-nNbbxAeo.js → debug-C7Ss34XB.js} +2 -2
  36. package/dist/{debug-nNbbxAeo.js.map → debug-C7Ss34XB.js.map} +1 -1
  37. package/dist/{derive-Mky_u59_.js → derive-ChP6vgfi.js} +2 -2
  38. package/dist/{derive-Mky_u59_.js.map → derive-ChP6vgfi.js.map} +1 -1
  39. package/dist/{dev-bj6dEeSQ.js → dev-C7n36E6f.js} +23 -2
  40. package/dist/dev-C7n36E6f.js.map +1 -0
  41. package/dist/{doctor-FaBObSlb.js → doctor-D0o54XSQ.js} +2 -2
  42. package/dist/{doctor-FaBObSlb.js.map → doctor-D0o54XSQ.js.map} +1 -1
  43. package/dist/{fold-static-2t3UUX4z.js → fold-static-DTpaqbB0.js} +2 -2
  44. package/dist/{fold-static-2t3UUX4z.js.map → fold-static-DTpaqbB0.js.map} +1 -1
  45. package/dist/{function-portability-BIvlvR9q.js → function-portability-Dppl6uqg.js} +24 -5
  46. package/dist/{function-portability-BIvlvR9q.js.map → function-portability-Dppl6uqg.js.map} +1 -1
  47. package/dist/function-portability.d.ts +9 -0
  48. package/dist/{functions-B4JR6EZL.js → functions-DLuuldt2.js} +4 -4
  49. package/dist/{functions-B4JR6EZL.js.map → functions-DLuuldt2.js.map} +1 -1
  50. package/dist/{generate_sdk-ByD-gTsK.js → generate_sdk-UT1lwwRT.js} +2 -2
  51. package/dist/{generate_sdk-ByD-gTsK.js.map → generate_sdk-UT1lwwRT.js.map} +1 -1
  52. package/dist/index.es.js +39 -39
  53. package/dist/{init-DHCe5mJ5.js → init-u5Xmr1Ct.js} +4 -4
  54. package/dist/{init-DHCe5mJ5.js.map → init-u5Xmr1Ct.js.map} +1 -1
  55. package/dist/{logs-DpuMukJe.js → logs-DBYRSs6W.js} +4 -4
  56. package/dist/{logs-DpuMukJe.js.map → logs-DBYRSs6W.js.map} +1 -1
  57. package/dist/{migrate-CSY9ZDKy.js → migrate-Cw1FkvUK.js} +3 -3
  58. package/dist/{migrate-CSY9ZDKy.js.map → migrate-Cw1FkvUK.js.map} +1 -1
  59. package/dist/{normalize-imports-P86NVfpo.js → normalize-imports-E4yA1HfW.js} +2 -2
  60. package/dist/{normalize-imports-P86NVfpo.js.map → normalize-imports-E4yA1HfW.js.map} +1 -1
  61. package/dist/{project-command-Cl9EZzjr.js → project-command-7EGMemEy.js} +5 -5
  62. package/dist/{project-command-Cl9EZzjr.js.map → project-command-7EGMemEy.js.map} +1 -1
  63. package/dist/{resources-Db3USuPO.js → resources-CE6BeL94.js} +2 -2
  64. package/dist/{resources-Db3USuPO.js.map → resources-CE6BeL94.js.map} +1 -1
  65. package/dist/{rls-BxrQ0P50.js → rls-BxWLfEKl.js} +3 -3
  66. package/dist/{rls-BxrQ0P50.js.map → rls-BxWLfEKl.js.map} +1 -1
  67. package/dist/{schema-_FzZEoB8.js → schema-D8xFSBbN.js} +7 -6
  68. package/dist/{schema-_FzZEoB8.js.map → schema-D8xFSBbN.js.map} +1 -1
  69. package/dist/schema-reconcile-D_wvZY91.js +2 -0
  70. package/dist/{schema-show-h72UJ9zH.js → schema-show-C7bY7SgE.js} +3 -3
  71. package/dist/{schema-show-h72UJ9zH.js.map → schema-show-C7bY7SgE.js.map} +1 -1
  72. package/dist/{skills-DQ2bZGkj.js → skills-C8WdRTFg.js} +4 -4
  73. package/dist/{skills-DQ2bZGkj.js.map → skills-C8WdRTFg.js.map} +1 -1
  74. package/dist/{start-Cjx4W0bJ.js → start-CN_9C205.js} +2 -2
  75. package/dist/{start-Cjx4W0bJ.js.map → start-CN_9C205.js.map} +1 -1
  76. package/dist/{status-CDBk25VO.js → status-HWlZbY1E.js} +2 -2
  77. package/dist/{status-CDBk25VO.js.map → status-HWlZbY1E.js.map} +1 -1
  78. package/dist/{storage-Clc8dLG8.js → storage-DBE8lgH-.js} +9 -9
  79. package/dist/{storage-Clc8dLG8.js.map → storage-DBE8lgH-.js.map} +1 -1
  80. package/dist/{storage-objects-CfRKlTDe.js → storage-objects-ljDmtuH7.js} +3 -3
  81. package/dist/{storage-objects-CfRKlTDe.js.map → storage-objects-ljDmtuH7.js.map} +1 -1
  82. package/dist/{users-5PkqBY6R.js → users-DrJEtL9k.js} +9 -6
  83. package/dist/users-DrJEtL9k.js.map +1 -0
  84. package/package.json +10 -10
  85. package/templates/template/.cursorrules +2 -1
  86. package/templates/template/.github/copilot-instructions.md +2 -1
  87. package/templates/template/.windsurfrules +2 -1
  88. package/templates/template/AGENTS.md +2 -1
  89. package/templates/template/CLAUDE.md +2 -1
  90. package/templates/template/ai-instructions.md +5 -2
  91. package/templates/template/frontend/src/index.css +13 -0
  92. package/dist/cloud-DNJyUU0T.js.map +0 -1
  93. package/dist/dev-bj6dEeSQ.js.map +0 -1
  94. package/dist/schema-reconcile-DV14XY4o.js +0 -2
  95. package/dist/users-5PkqBY6R.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"debug-nNbbxAeo.js","names":[],"sources":["../src/commands/cloud/debug.ts"],"sourcesContent":["/**\n * `rebase cloud debug <subcommand>` — one entry point for \"why is my deployed\n * app not behaving\".\n *\n * ## Why this exists\n *\n * The useful signals for a deployed project live in four different places — the\n * control plane, the workload's pods, the tenant database, and the public URL —\n * and each is normally reached with a different tool and a different set of\n * flags. Getting to a log should not be a research task. This started life as a\n * hand-rolled `prod-debug.sh` for a single project, with the namespace and the\n * URL hardcoded at the top; it earned its place twice in one week, so it is\n * generalised here to any project the CLI can already resolve.\n *\n * ## Read-only by default\n *\n * Every subcommand here only reads. The two things the original script could do\n * that mutate are deliberately NOT reproduced as-is:\n *\n * - restarting the workload lives at `rebase cloud restart`, which already\n * gates downtime behind `--yes`; duplicating it here would give the same\n * destructive act a second, ungated spelling.\n * - `debug db` prints the port-forward recipe and the connection's *shape*.\n * It opens no session and prints no password — `rebase cloud db info\n * --reveal` is the explicit, auditable way to get one.\n *\n * ## The probes are the point\n *\n * `debug health` is the highest-value piece and the reason the script existed.\n * A bare status code is not a diagnosis: a 404 from a functions route means\n * something completely different from a 404 at the root, and a 200 on an\n * unauthenticated read is a finding rather than a success. So every probe ships\n * with the interpretation of what it got, not just the number — see\n * {@link PROBES}.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport { warnDeprecated } from \"@rebasepro/common\";\nimport { unknownCommandMessage } from \"../../utils/unknown-command\";\nimport {\n requireClient,\n requireProject,\n parseCloudArgs,\n displayProjectRef,\n fetchTenantBaseDomain,\n projectHost,\n colorStatus,\n keyValues,\n emit,\n printGroupHelp,\n fail,\n reportError,\n type CloudClient\n} from \"./context\";\n\n/* ═══════════════════════════════════════════════════════════════\n Health probes\n ═══════════════════════════════════════════════════════════════ */\n\n/** How a probe's outcome should be read. */\nexport type Verdict =\n /** Behaving as a healthy deployment should. */\n | \"ok\"\n /** Reachable and legal, but worth a human look (e.g. a public read). */\n | \"warn\"\n /** Broken, or wired up wrong. */\n | \"fail\"\n /** We could not classify the response. */\n | \"unknown\";\n\nexport interface ProbeReading {\n verdict: Verdict;\n /** What this status code *means for this endpoint*, in one sentence. */\n meaning: string;\n}\n\nexport interface ProbeSpec {\n id: string;\n /** Column label in human output. */\n label: string;\n method: \"GET\" | \"POST\";\n /** Path relative to the project origin. */\n path: (opts: ProbeTargets) => string;\n body?: unknown;\n /** One-line statement of what a healthy deployment answers here. */\n healthy: string;\n interpret: (status: number | null) => ProbeReading;\n /**\n * Read the response body as well. Set only where the body carries a fact the\n * status code cannot — today, the function listing.\n */\n needsBody?: boolean;\n /**\n * Sharpen the status-code reading using the parsed body. Returning null\n * keeps {@link interpret}'s verdict.\n */\n refine?: (body: unknown, targets: ProbeTargets) => ProbeReading | null;\n}\n\nexport interface ProbeTargets {\n /** Table used for the unauthenticated-read probe. */\n collection: string;\n /** Function to confirm exists, if the caller named one. */\n fn?: string;\n}\n\n/** A response never arrived: DNS, TLS, ingress, or the pod. */\nconst NO_RESPONSE: ProbeReading = {\n verdict: \"fail\",\n meaning:\n \"nothing answered — the hostname does not resolve, the ingress has no route, or no pod is running\"\n};\n\nfunction serverError(what: string): ProbeReading {\n return { verdict: \"fail\",\nmeaning: `the server is running but ${what}` };\n}\n\n/**\n * The probe set, in the order a failure cascades: if `health` is down, nothing\n * below it is meaningful, so it is checked first and reported first.\n */\nexport const PROBES: ProbeSpec[] = [\n {\n id: \"health\",\n label: \"health\",\n method: \"GET\",\n path: () => \"/health\",\n healthy: \"200 — the backend is up\",\n interpret: (status) => {\n if (status === null) return NO_RESPONSE;\n if (status === 200) return { verdict: \"ok\",\nmeaning: \"the backend is up and serving\" };\n if (status === 404) {\n return {\n verdict: \"fail\",\n meaning:\n \"something answered but it is not a Rebase backend — the ingress is routing this host elsewhere\"\n };\n }\n if (status >= 500) return serverError(\"its health endpoint is failing\");\n return { verdict: \"unknown\",\nmeaning: \"unexpected for a health endpoint\" };\n }\n },\n {\n id: \"spa\",\n label: \"spa\",\n method: \"GET\",\n path: () => \"/\",\n healthy: \"200 — the frontend is being served\",\n interpret: (status) => {\n if (status === null) return NO_RESPONSE;\n if (status === 200) return { verdict: \"ok\",\nmeaning: \"the frontend bundle is being served\" };\n if (status === 404) {\n return {\n verdict: \"warn\",\n meaning:\n \"no frontend at the root — expected for a backend-only project, otherwise the SPA assets were not bundled into the image\"\n };\n }\n if (status >= 500) return serverError(\"the root route throws\");\n return { verdict: \"unknown\",\nmeaning: \"unexpected at the site root\" };\n }\n },\n {\n id: \"auth\",\n label: \"auth\",\n method: \"POST\",\n path: () => \"/api/auth/login\",\n body: {},\n healthy: \"400 — auth is mounted and rejects an empty body\",\n interpret: (status) => {\n if (status === null) return NO_RESPONSE;\n // The probe deliberately posts an empty body: a healthy auth route\n // must reject it. Reachability is what is being tested, not a login.\n if (status === 400 || status === 422) {\n return { verdict: \"ok\",\nmeaning: \"auth is mounted and rejected the empty body, as it should\" };\n }\n if (status === 401 || status === 403) {\n return { verdict: \"ok\",\nmeaning: \"auth is mounted and refused the credentials\" };\n }\n if (status === 404) {\n return {\n verdict: \"fail\",\n meaning: \"the auth routes are NOT mounted — this project cannot sign anyone in\"\n };\n }\n if (status === 200) {\n return {\n verdict: \"fail\",\n meaning: \"an EMPTY login body was accepted — a login with no credentials must never succeed\"\n };\n }\n if (status >= 500) return serverError(\"the login route throws — often a missing or unmigrated auth table\");\n return { verdict: \"unknown\",\nmeaning: \"unexpected for a login route\" };\n }\n },\n {\n id: \"unauthRead\",\n label: \"unauth read\",\n method: \"GET\",\n path: (t) => `/api/data/${encodeURIComponent(t.collection)}`,\n healthy: \"401 — reads require authentication\",\n interpret: (status) => {\n if (status === null) return NO_RESPONSE;\n if (status === 401 || status === 403) {\n return { verdict: \"ok\",\nmeaning: \"unauthenticated reads are refused — row-level security is enforced\" };\n }\n if (status === 200) {\n // Legal, and sometimes intended. Never silently called healthy.\n return {\n verdict: \"warn\",\n meaning:\n \"this table is readable with NO authentication — correct only if it is deliberately public\"\n };\n }\n if (status === 404) {\n return {\n verdict: \"warn\",\n meaning: \"no such table on this deployment — check the name, or pass --table\"\n };\n }\n if (status >= 500) {\n return serverError(\n \"the read reached the database and failed — most often an RLS policy naming a column or table that is not there\"\n );\n }\n return { verdict: \"unknown\",\nmeaning: \"unexpected for a data read\" };\n }\n },\n {\n id: \"functions\",\n label: \"functions\",\n method: \"GET\",\n /**\n * The router's own listing endpoint, NOT a function's path.\n *\n * This matters, and it is the one place the original script got a wrong\n * answer. A function is a Hono sub-app mounted at `/<name>`, and it\n * usually defines only sub-routes (`/get`, `/list`) — so\n * `/api/functions/<name>` 404s **even when everything is mounted and\n * healthy**. Probing there cannot separate \"the router is missing\" from\n * \"that function defines no root route\", and reporting the first is how\n * you send someone to debug a deployment that was fine.\n *\n * `GET /api/functions` is unambiguous: the router registers a listing\n * route at its own root (see `createFunctionRoutes`), so a 200 proves\n * the mount *and* names every function that loaded.\n */\n path: () => \"/api/functions\",\n healthy: \"200 — the functions router is mounted and lists its functions\",\n interpret: (status) => {\n if (status === null) return NO_RESPONSE;\n if (status === 200) return { verdict: \"ok\",\nmeaning: \"the functions router is mounted\" };\n if (status === 401 || status === 403) {\n // The listing is behind auth on this deployment. That still\n // proves the router is there, which is what is being tested.\n return { verdict: \"ok\",\nmeaning: \"the functions router is mounted (its listing requires auth)\" };\n }\n if (status === 404) {\n return {\n verdict: \"fail\",\n meaning:\n \"the functions router did not mount — no functions directory was found at build time, or it held no functions, so every function on this project is unreachable\"\n };\n }\n if (status >= 500) return serverError(\"the functions router throws\");\n return { verdict: \"unknown\",\nmeaning: \"unexpected for the functions listing\" };\n },\n needsBody: true,\n refine: (body, t) => {\n const names = functionNames(body);\n if (!names) return null;\n if (t.fn && !names.includes(t.fn)) {\n // Definitive, because the listing is authoritative — no guessing\n // from a 404 that could equally mean the router is absent.\n return {\n verdict: \"fail\",\n meaning:\n `the router is mounted but no function is named \"${t.fn}\" — it loaded ${names.length}: ` +\n `${names.join(\", \")}`\n };\n }\n const found = t.fn ? `, including ${t.fn}` : \"\";\n return {\n verdict: \"ok\",\n meaning: `the functions router is mounted and loaded ${names.length} function${names.length === 1 ? \"\" : \"s\"}${found}`\n };\n }\n }\n];\n\n/** The function names out of a listing body, or null when it is not one. */\nexport function functionNames(body: unknown): string[] | null {\n const list = (body as { functions?: unknown } | null | undefined)?.functions;\n if (!Array.isArray(list)) return null;\n const names = list\n .map((f) => (f as { name?: unknown })?.name)\n .filter((n): n is string => typeof n === \"string\");\n return names.length === list.length ? names : null;\n}\n\nexport interface ProbeResult {\n id: string;\n label: string;\n method: string;\n url: string;\n status: number | null;\n ms: number;\n verdict: Verdict;\n meaning: string;\n healthy: string;\n /**\n * Whether the STATUS CODE alone looked healthy. False means the code itself\n * was wrong; true with a failing `verdict` means the code was fine and the\n * body carried the bad news (a named function that did not load). The\n * summary uses this so it never tells you to expect a 200 you already got.\n */\n statusOk: boolean;\n}\n\n/** Milliseconds before a probe is treated as unanswered. */\nconst PROBE_TIMEOUT_MS = 10_000;\n\n/**\n * Ceiling on a probe body we will parse. The only body read is the function\n * listing; anything larger is a page we have no use for, and a debug command\n * must not be the thing that runs a machine out of memory.\n */\nconst MAX_PROBE_BODY_BYTES = 256 * 1024;\n\n/**\n * Run one probe. A transport failure is a `null` status, never a thrown error:\n * \"nothing answered\" is a diagnosis in its own right and the other probes still\n * need to run.\n */\nexport async function runProbe(origin: string, spec: ProbeSpec, targets: ProbeTargets): Promise<ProbeResult> {\n const url = `${origin}${spec.path(targets)}`;\n const started = Date.now();\n let status: number | null = null;\n let body: unknown;\n try {\n const res = await fetch(url, {\n method: spec.method,\n headers: spec.body ? { \"Content-Type\": \"application/json\" } : undefined,\n body: spec.body ? JSON.stringify(spec.body) : undefined,\n redirect: \"manual\",\n signal: AbortSignal.timeout(PROBE_TIMEOUT_MS)\n });\n status = res.status;\n if (spec.needsBody && res.ok) {\n const text = await res.text();\n if (text.length <= MAX_PROBE_BODY_BYTES) {\n try {\n body = JSON.parse(text);\n } catch {\n // Not JSON — `refine` returns null and the status reading stands.\n }\n }\n }\n } catch {\n status = null;\n }\n const statusReading = spec.interpret(status);\n // The body can only sharpen a reading, never invent one where the request\n // failed outright.\n const reading = (status !== null && spec.refine?.(body, targets)) || statusReading;\n return {\n statusOk: statusReading.verdict === \"ok\",\n id: spec.id,\n label: spec.label,\n method: spec.method,\n url,\n status,\n ms: Date.now() - started,\n verdict: reading.verdict,\n meaning: reading.meaning,\n healthy: spec.healthy\n };\n}\n\n/** The worst verdict across probes — what the command's exit code keys off. */\nexport function overallVerdict(results: ProbeResult[]): Verdict {\n if (results.some((r) => r.verdict === \"fail\")) return \"fail\";\n if (results.some((r) => r.verdict === \"unknown\")) return \"unknown\";\n if (results.some((r) => r.verdict === \"warn\")) return \"warn\";\n return \"ok\";\n}\n\nfunction verdictMark(v: Verdict): string {\n switch (v) {\n case \"ok\":\n return chalk.green(\"✓\");\n case \"warn\":\n return chalk.yellow(\"!\");\n case \"fail\":\n return chalk.red(\"✗\");\n default:\n return chalk.gray(\"?\");\n }\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Log parsing\n ═══════════════════════════════════════════════════════════════\n\n `runtime-logs` renders each line as `<rfc3339> [<pod>] <text>`, where <text>\n is normally the application's structured JSON. These helpers unwrap that so\n the derived views (errors / requests / boot) work on the payload rather than\n on the transport's formatting.\n*/\n\nexport interface ParsedLogLine {\n ts: string | null;\n pod: string | null;\n text: string;\n}\n\nconst LOG_PREFIX_RE = /^(?:(\\d{4}-\\d{2}-\\d{2}T[\\d:.]+Z?)\\s+)?(?:\\[([^\\]]+)\\]\\s+)?([\\s\\S]*)$/;\n\nexport function parseLogLine(line: string): ParsedLogLine {\n const m = LOG_PREFIX_RE.exec(line);\n if (!m) return { ts: null,\npod: null,\ntext: line };\n return { ts: m[1] ?? null,\npod: m[2] ?? null,\ntext: m[3] ?? \"\" };\n}\n\n/**\n * Lines an operator scanning for a fault wants to see.\n *\n * Matches the structured `severity` field first, then the shapes that show up\n * in unstructured output. `refus`/`denied` are in the list because a permission\n * failure often logs at info level and is exactly what one is hunting for.\n */\nexport function isErrorLine(text: string): boolean {\n return /\"(?:severity|level)\":\\s*\"(?:ERROR|WARN(?:ING)?|error|warn)\"|\\bError:|\\bERR!|refus|denied|EACCES|ECONNREFUSED/i.test(\n text\n );\n}\n\nexport interface RequestLogEntry {\n status: number | null;\n method: string;\n path: string;\n latencyMs: number | null;\n}\n\n/**\n * Pull an HTTP request record out of a log line, or null when it is not one.\n *\n * Only structured request lines are recognised. Guessing at prose would produce\n * a table with invented columns, which is worse than a short one.\n */\nexport function parseRequestLine(text: string): RequestLogEntry | null {\n const start = text.indexOf(\"{\");\n if (start === -1) return null;\n let parsed: Record<string, unknown>;\n try {\n parsed = JSON.parse(text.slice(start)) as Record<string, unknown>;\n } catch {\n return null;\n }\n if (parsed.message !== \"request\" && parsed.msg !== \"request\") return null;\n\n const num = (v: unknown): number | null => {\n const n = typeof v === \"string\" ? Number(v) : typeof v === \"number\" ? v : NaN;\n return Number.isFinite(n) ? n : null;\n };\n return {\n status: num(parsed.status),\n method: typeof parsed.method === \"string\" ? parsed.method : \"\",\n path: typeof parsed.path === \"string\" ? parsed.path : \"\",\n latencyMs: num(parsed.latencyMs ?? parsed.durationMs)\n };\n}\n\n/**\n * Startup lines: what the server *decided* it was going to do. Which storage\n * backend it bound, which functions it loaded, whether auth tables were found.\n * This is the fastest way to tell a misconfiguration from a runtime fault.\n */\nexport function isBootLine(text: string): boolean {\n // \"Loaded custom functions\" and \"Loaded cron job…\" are 0.25's words for what\n // earlier runtimes logged as \"Mounted …\"; both are what a deployment runs.\n return /storage|Loaded (?:custom )?function|Loaded cron|Cron jobs scheduled|Cron scheduler|Mounted|Auth tables|Server running|listening|Refusing|migrat/i.test(text);\n}\n\n/** Render a number of seconds back as the compact duration a user would type. */\nexport function formatDuration(seconds: number): string {\n if (seconds % 86400 === 0 && seconds >= 86400) return `${seconds / 86400}d`;\n if (seconds % 3600 === 0 && seconds >= 3600) return `${seconds / 3600}h`;\n if (seconds % 60 === 0 && seconds >= 60) return `${seconds / 60}m`;\n return `${seconds}s`;\n}\n\n/**\n * Parse a duration like `15m`, `2h`, `90s`, `1d` (or a bare number of seconds)\n * into seconds. Returns null when it is not a duration.\n */\nexport function parseSince(input: string | undefined): number | null {\n if (!input) return null;\n const m = /^(\\d+(?:\\.\\d+)?)\\s*([smhd])?$/i.exec(input.trim());\n if (!m) return null;\n const value = parseFloat(m[1]);\n const unit = (m[2] || \"s\").toLowerCase();\n const mult = unit === \"s\" ? 1 : unit === \"m\" ? 60 : unit === \"h\" ? 3600 : 86400;\n return Math.round(value * mult);\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Shared fetches\n ═══════════════════════════════════════════════════════════════ */\n\n/** One pod's entry in a `runtime-logs` answer. */\nexport interface RuntimeLogsPod {\n pod: string;\n state: string;\n /** Lines this pod returned. */\n lines: number;\n message: string | null;\n hint: string | null;\n /** The server's per-pod BYTE budget cut this pod's output. Says nothing about the line limit. */\n truncated?: boolean;\n}\n\nexport interface RuntimeLogsResponse {\n logs?: string;\n pods?: RuntimeLogsPod[];\n ordering?: string;\n /** A byte budget or the pod-count ceiling cut the result. Says nothing about the line limit. */\n truncated?: boolean;\n state?: string;\n message?: string | null;\n}\n\n/**\n * The most lines `runtime-logs` returns per pod.\n *\n * The control plane enforces this (`MAX_TAIL_LINES` in\n * `saas/backend/functions/runtime-logs.ts`) by clamping a larger `tailLines`\n * without saying so: its answer names neither the limit nor the value it used.\n * `--tail 200000` therefore came back as 2000 lines reported as untruncated.\n * The CLI clamps first, with the same number, so the lowering is something it\n * can print rather than something that happened out of sight.\n */\nexport const SERVER_MAX_TAIL_LINES = 2000;\n\n/** How many lines per pod a read asks for, and why that may be less than requested. */\nexport interface TailLimit {\n /** What `--tail` asked for, or the view's default. */\n requested: number;\n /** What is sent: `requested`, lowered to {@link SERVER_MAX_TAIL_LINES}. */\n applied: number;\n /** Whether `--tail` was given, so a message can name the flag or the default. */\n explicit: boolean;\n /** Set when `applied < requested`: the sentence that says so. */\n note: string | null;\n}\n\nexport function resolveTail(requested: number, explicit: boolean): TailLimit {\n const applied = Math.min(requested, SERVER_MAX_TAIL_LINES);\n return {\n requested,\n applied,\n explicit,\n note:\n applied < requested\n ? `--tail ${requested} was lowered to ${applied}: the control plane returns at most ` +\n `${SERVER_MAX_TAIL_LINES} lines per pod.`\n : null\n };\n}\n\n/** Read `--tail`, refusing anything that is not a positive whole number. */\nfunction tailFromFlag(value: number | undefined, fallback: number): TailLimit {\n if (value === undefined) return resolveTail(fallback, false);\n if (!Number.isInteger(value) || value <= 0) {\n fail(`--tail must be a positive whole number of lines; received \"${value}\".`, undefined, \"usage\");\n }\n return resolveTail(value, true);\n}\n\n/** What one pod's lines actually cover. */\nexport interface PodCoverage extends RuntimeLogsPod {\n /** Earliest and latest timestamps among the lines this pod returned. */\n firstTimestamp: string | null;\n lastTimestamp: string | null;\n /** A limit cut what this pod would otherwise have returned for the window. */\n truncated: boolean;\n /** Which limit: the per-pod line limit, or the server's byte budget. */\n truncatedBy: \"tail\" | \"bytes\" | null;\n /** The plain explanation, when truncated. */\n truncatedReason: string | null;\n /**\n * Every line this pod holds in the window came back. With no window (read\n * from the start), its first line is the start of its log.\n */\n complete: boolean;\n}\n\n/** The window asked for against the window delivered. */\nexport interface LogCoverage {\n /** Start of the window asked for, ISO. Null when reading each pod from its start. */\n requestedFrom: string | null;\n /** Earliest and latest timestamps across every line returned. */\n firstTimestamp: string | null;\n lastTimestamp: string | null;\n pods: PodCoverage[];\n truncated: boolean;\n truncatedReasons: string[];\n}\n\n/** A span of milliseconds as `29d 23h`, `2h 5m`, `35m`, `40s`. */\nexport function formatSpan(ms: number): string {\n const s = Math.max(0, Math.round(ms / 1000));\n const d = Math.floor(s / 86400);\n const h = Math.floor((s % 86400) / 3600);\n const m = Math.floor((s % 3600) / 60);\n if (d > 0) return h > 0 ? `${d}d ${h}h` : `${d}d`;\n if (h > 0) return m > 0 ? `${h}h ${m}m` : `${h}h`;\n if (m > 0) return `${m}m`;\n return `${s}s`;\n}\n\nfunction timestampRange(lines: ParsedLogLine[]): { first: string | null; last: string | null } {\n let first: { text: string; ms: number } | null = null;\n let last: { text: string; ms: number } | null = null;\n for (const l of lines) {\n if (!l.ts) continue;\n const ms = Date.parse(l.ts);\n if (Number.isNaN(ms)) continue;\n if (!first || ms < first.ms) first = { text: l.ts,\nms };\n if (!last || ms > last.ms) last = { text: l.ts,\nms };\n }\n return { first: first?.text ?? null,\nlast: last?.text ?? null };\n}\n\n/**\n * Compare what a read covered with what it asked for.\n *\n * The server's `truncated` describes only its byte budgets and pod ceiling, so\n * a pod that filled the line limit came back marked complete however much of\n * the window it left unread. The line limit is the cut that matters most, and\n * it is detected here: a pod that returned as many lines as the limit, whose\n * earliest line is later than the start of the window, was cut by it.\n *\n * Filling the limit is the half that separates a cut from a young pod. A pod\n * that started an hour ago also has no line older than an hour; it returned\n * fewer lines than the limit, so what came back is its whole log, and nothing\n * was cut.\n */\nexport function assessCoverage(opts: {\n res: RuntimeLogsResponse;\n lines: ParsedLogLine[];\n /** The window asked for. Null reads each pod from its start. */\n sinceSeconds: number | null;\n tail: TailLimit;\n now: number;\n}): LogCoverage {\n const { res, lines, sinceSeconds, tail, now } = opts;\n const windowStartMs = sinceSeconds === null ? null : now - sinceSeconds * 1000;\n const requestedFrom = windowStartMs === null ? null : new Date(windowStartMs).toISOString();\n const limitName = tail.note\n ? `the control plane's ceiling of ${tail.applied} lines per pod`\n : tail.explicit\n ? `the --tail ${tail.applied} limit`\n : `the default of ${tail.applied} lines per pod`;\n // Only worth saying when raising it would read further back.\n const raise = tail.applied < SERVER_MAX_TAIL_LINES\n ? ` Raise --tail (at most ${SERVER_MAX_TAIL_LINES}) to read further back.`\n : ` The control plane returns only each pod's newest ${SERVER_MAX_TAIL_LINES}, so older lines cannot be read from here.`;\n\n const pods: PodCoverage[] = (res.pods ?? []).map((p) => {\n const range = timestampRange(lines.filter((l) => l.pod === p.pod));\n const base = { ...p,\nfirstTimestamp: range.first,\nlastTimestamp: range.last };\n if (p.state !== \"ok\") {\n return { ...base,\ntruncated: false,\ntruncatedBy: null,\ntruncatedReason: null,\ncomplete: false };\n }\n if (p.truncated) {\n return {\n ...base,\n truncated: true,\n truncatedBy: \"bytes\" as const,\n truncatedReason:\n `${p.pod}: the control plane's per-pod byte budget cut this pod's output short` +\n (range.first ? ` — what fit runs ${range.first} to ${range.last}.` : \".\"),\n complete: false\n };\n }\n const firstMs = range.first ? Date.parse(range.first) : null;\n const startsLate = windowStartMs === null || firstMs === null || firstMs > windowStartMs;\n if (p.lines >= tail.applied && startsLate) {\n let reason: string;\n if (firstMs === null) {\n reason = `${p.pod}: returned ${p.lines} lines, ${limitName}; they carry no timestamps, so how far back they reach is unknown.`;\n } else if (sinceSeconds !== null && windowStartMs !== null) {\n reason =\n `${p.pod}: returned ${p.lines} lines, ${limitName}, and the earliest is ${range.first} — ` +\n `${formatSpan(firstMs - windowStartMs)} after the ${formatDuration(sinceSeconds)} ` +\n `window begins (${requestedFrom}). Lines in between were not read.${raise}`;\n } else {\n reason =\n `${p.pod}: returned ${p.lines} lines, ${limitName}, so its log before ${range.first} ` +\n `was not read.${raise}`;\n }\n return { ...base,\ntruncated: true,\ntruncatedBy: \"tail\" as const,\ntruncatedReason: reason,\ncomplete: false };\n }\n return { ...base,\ntruncated: false,\ntruncatedBy: null,\ntruncatedReason: null,\ncomplete: true };\n });\n\n const truncatedReasons = pods.flatMap((p) => (p.truncatedReason ? [p.truncatedReason] : []));\n // The server's flag also covers cuts no single pod owns: its total byte\n // budget across pods, and the cap on how many pods it reads.\n if (res.truncated && !pods.some((p) => p.truncatedBy === \"bytes\")) {\n truncatedReasons.push(\n \"The control plane trimmed the combined result (its total byte budget, or the most pods it reads at once); the oldest lines were dropped.\"\n );\n }\n const overall = timestampRange(lines);\n return {\n requestedFrom,\n firstTimestamp: overall.first,\n lastTimestamp: overall.last,\n pods,\n truncated: Boolean(res.truncated) || pods.some((p) => p.truncated),\n truncatedReasons\n };\n}\n\nasync function fetchRuntimeLogs(\n client: CloudClient,\n projectId: string,\n opts: { sinceSeconds?: number; tailLines?: number; previous?: boolean }\n): Promise<RuntimeLogsResponse> {\n const params = new URLSearchParams();\n if (opts.sinceSeconds !== undefined) params.set(\"sinceSeconds\", String(opts.sinceSeconds));\n if (opts.tailLines !== undefined) params.set(\"tailLines\", String(opts.tailLines));\n if (opts.previous) params.set(\"previous\", \"true\");\n params.set(\"timestamps\", \"true\");\n const qs = params.toString();\n return client.functions.invoke<RuntimeLogsResponse>(\"runtime-logs\", undefined, {\n method: \"GET\",\n path: `${projectId}${qs ? `?${qs}` : \"\"}`\n });\n}\n\n/** Print the per-pod states runtime-logs reports, including its hints. */\nfunction printPodStates(res: RuntimeLogsResponse): void {\n if (res.state === \"no_pods\") {\n console.log(chalk.yellow(` ${res.message ?? \"No pods are running for this project.\"}`));\n console.log(\"\");\n return;\n }\n for (const p of res.pods ?? []) {\n if (p.state === \"ok\") continue;\n console.log(` ${chalk.yellow(p.pod)} ${chalk.gray(`(${p.state})`)}`);\n if (p.message) console.log(chalk.gray(` ${p.message}`));\n // The hint is the actionable half — a crash-looping container's reason\n // is in its PREVIOUS instance, and that is only discoverable if we say so.\n if (p.hint) console.log(chalk.cyan(` → ${p.hint}`));\n }\n}\n\n/**\n * The window asked for, the window delivered, and every cut between them.\n * Printed after the lines, where a reader's eye is when the output ends.\n */\nfunction printCoverage(coverage: LogCoverage, tail: TailLimit): void {\n const asked = coverage.requestedFrom ? `from ${coverage.requestedFrom}` : \"from each pod's start\";\n const got = coverage.firstTimestamp && coverage.lastTimestamp\n ? `${coverage.firstTimestamp} → ${coverage.lastTimestamp} ` +\n `(${formatSpan(Date.parse(coverage.lastTimestamp) - Date.parse(coverage.firstTimestamp))})`\n : \"no timestamped lines\";\n console.log(chalk.gray(` Asked for: ${asked}`));\n console.log(chalk.gray(` Returned: ${got}`));\n if (tail.note) console.log(chalk.yellow(` ! ${tail.note}`));\n if (coverage.truncated) {\n console.log(chalk.yellow(\" ! Truncated — the lines above do not cover the window asked for:\"));\n for (const reason of coverage.truncatedReasons) console.log(chalk.yellow(` ${reason}`));\n }\n console.log(\"\");\n}\n\n/**\n * Resolve the public origin a project is served at — or `--host`, when given.\n *\n * Shared with `rebase cloud cron`, which reads the runtime at the same address\n * `debug health` probes.\n */\nexport async function resolveOrigin(\n rawArgs: string[],\n client: CloudClient,\n url: string,\n projectId: string\n): Promise<string> {\n const parsed = arg({ \"--host\": String }, { argv: rawArgs.slice(3),\npermissive: true });\n if (parsed[\"--host\"]) {\n const h = parsed[\"--host\"].trim().replace(/\\/+$/, \"\");\n return /^https?:\\/\\//.test(h) ? h : `https://${h}`;\n }\n\n const [project, baseDomain] = await Promise.all([\n client.data.table(\"projects\").findById(projectId) as Promise<\n { subdomain?: string; host?: string; customDomain?: string } | undefined\n >,\n fetchTenantBaseDomain(client, url)\n ]);\n if (!project) fail(`Project ${displayProjectRef(rawArgs)} not found.`);\n\n const host = projectHost(project, baseDomain);\n if (!host) {\n fail(\n \"Could not determine the public URL for this project.\",\n \"It may never have been deployed. Pass --host <hostname> to probe an address directly.\"\n );\n }\n return `https://${host}`;\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Subcommand: health\n ═══════════════════════════════════════════════════════════════ */\n\nasync function healthCommand(rawArgs: string[]): Promise<void> {\n // Strict: `--tabel users` used to be dropped and the probe then ran\n // against the default table while reporting on the one asked for.\n const { flags: parsed } = parseCloudArgs({\n spec: HEALTH_FLAGS,\n rawArgs,\n commandWords: 3, // cloud debug health\n command: \"cloud debug\",\n maxPositionals: 0\n });\n const targets: ProbeTargets = {\n collection: resolveProbeTable(parsed) || \"users\",\n // Optional: the listing endpoint proves the mount on its own. A name\n // here additionally asserts that this particular function loaded.\n fn: parsed[\"--function\"]\n };\n\n const { client, url } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const origin = await resolveOrigin(rawArgs, client, url, projectId);\n\n // Sequential, not Promise.all: five simultaneous requests to a struggling\n // pod is a small load test, and the latency column would then measure our\n // own contention rather than the endpoint's.\n const results: ProbeResult[] = [];\n for (const spec of PROBES) results.push(await runProbe(origin, spec, targets));\n\n const overall = overallVerdict(results);\n\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` 🩺 Health — ${displayProjectRef(rawArgs)}`) + chalk.gray(` ${origin}`));\n console.log(\"\");\n const width = Math.max(...results.map((r) => r.label.length));\n for (const r of results) {\n const code = r.status === null ? chalk.red(\"---\") : String(r.status);\n console.log(\n ` ${verdictMark(r.verdict)} ${chalk.bold(r.label.padEnd(width))} ${code.padStart(3)} ${chalk.gray(`${r.ms}ms`)}`\n );\n console.log(` ${chalk.gray(r.meaning)}`);\n }\n console.log(\"\");\n if (overall === \"ok\") {\n console.log(chalk.green(\" Everything reachable and wired as expected.\"));\n } else {\n const bad = results.filter((r) => r.verdict === \"fail\" || r.verdict === \"warn\");\n console.log(chalk.gray(` ${bad.length} of ${results.length} check${bad.length === 1 ? \"\" : \"s\"} need attention.`));\n // Only where the status code itself was wrong — restating\n // \"expected 200\" under a probe that returned 200 reads as a bug.\n const wrongStatus = bad.filter((r) => !r.statusOk);\n if (wrongStatus.length > 0) {\n console.log(chalk.gray(\" A healthy deployment answers:\"));\n for (const r of wrongStatus) {\n console.log(chalk.gray(` ${r.label.padEnd(width)} ${r.healthy}`));\n }\n }\n }\n console.log(\"\");\n },\n { origin,\noverall,\nprobes: results }\n );\n\n // A failing probe is a failing command — this is meant to be usable in a\n // deploy script's `if`, not only read by a human.\n if (overall === \"fail\") process.exit(1);\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Subcommand: logs / errors / requests / boot\n ═══════════════════════════════════════════════════════════════ */\n\n/** What `debug logs`, `errors` and `boot` parse. Their help pairs against this. */\nexport const LOG_VIEW_FLAGS = {\n \"--since\": String,\n \"--tail\": Number,\n \"--previous\": Boolean\n} as const;\n\n/** What `debug requests` parses. */\nexport const REQUESTS_FLAGS = {\n \"--since\": String,\n \"--tail\": Number\n} as const;\n\n/** What `debug health` parses. */\nexport const HEALTH_FLAGS = {\n \"--table\": String,\n /** @deprecated Use `--table` instead. Accepted, with a warning, until a later release. */\n \"--collection\": String,\n \"--function\": String,\n // `--host` is read again inside `resolveOrigin`, which needs it before\n // the client exists; declared here because THIS is the parse that\n // decides whether the line is accepted at all.\n \"--host\": String\n} as const;\n\n/**\n * The table `debug health` probes, from `--table` or its deprecated spelling\n * `--collection`, which still works and warns once. Undefined when neither was\n * given.\n *\n * \"Table\" is the word for the app's data; \"collection\" is the CMS's. Both\n * spellings at once is refused unless they agree, since one of them would be\n * ignored.\n */\nexport function resolveProbeTable(flags: { \"--table\"?: string; \"--collection\"?: string }): string | undefined {\n const table = flags[\"--table\"];\n const collection = flags[\"--collection\"];\n if (collection === undefined) return table;\n warnDeprecated(\"cli.cloud-debug-health-collection\", \"`rebase cloud debug health --collection` is deprecated; use `--table` instead.\");\n if (table !== undefined && table !== collection) {\n fail(\"--table and --collection name the same thing; pass --table alone.\", undefined, \"usage\");\n }\n return table ?? collection;\n}\n\ninterface LogViewOptions {\n /** Keep only lines matching this. Omit to keep everything. */\n filter?: (text: string) => boolean;\n /** Default lookback when --since is not given. Null reads each pod from its start. */\n defaultSinceSeconds: number | null;\n /** Lines read per pod when --tail is not given. */\n defaultTail: number;\n /** Max lines rendered. */\n limit: number;\n title: string;\n /**\n * The lines wanted are the first a pod wrote, so a read that did not reach\n * a pod's start has not looked where they are — see {@link bootReach}.\n */\n needsStart?: boolean;\n}\n\nconst LOG_VIEWS = {\n logs: { defaultSinceSeconds: 900,\ndefaultTail: 500,\nlimit: 200,\ntitle: \"📄 Logs\" },\n errors: { filter: isErrorLine,\ndefaultSinceSeconds: 3600,\ndefaultTail: 500,\nlimit: 40,\ntitle: \"🔥 Errors\" },\n boot: {\n filter: isBootLine,\n // No window, and the most lines the control plane returns. Startup\n // happened when the pod started, which may have been days ago: a\n // 7-day window and the newest 500 lines missed it on any pod that had\n // served traffic since.\n defaultSinceSeconds: null,\n defaultTail: SERVER_MAX_TAIL_LINES,\n limit: 25,\n title: \"🚀 Boot\",\n needsStart: true\n }\n} satisfies Record<string, LogViewOptions>;\n\nconst REQUESTS_DEFAULTS = { sinceSeconds: 900,\ntail: 1000 };\n\n/** Read `--since`, refusing anything that is not a duration. Undefined when it was not given. */\nfunction sinceFromFlag(sinceArg: string | undefined): number | undefined {\n if (sinceArg === undefined) return undefined;\n const seconds = parseSince(sinceArg);\n if (seconds === null) fail(`--since must be a duration like 15m, 2h or 90s; received \"${sinceArg}\".`);\n return seconds;\n}\n\nfunction windowLabel(sinceSeconds: number | null): string {\n return sinceSeconds === null ? \"since each pod started\" : `last ${formatDuration(sinceSeconds)}`;\n}\n\n/**\n * Whether a boot read reached each pod's start, which is where its startup\n * lines are. A pod whose read was cut has not been looked at there, so finding\n * no startup lines in it means nothing — and a line from later in its life\n * that happens to mention `storage` is not its startup.\n *\n * Under `--since` a pod is never counted as reached: a complete read of the\n * window starts at the pod's first line only if the pod started inside it, and\n * nothing in the answer says whether it did.\n */\nexport function bootReach(pods: PodCoverage[], sinceSeconds: number | null): {\n reachedStart: boolean;\n unreached: string[];\n} {\n const unreached = pods\n .filter((p) => p.state === \"ok\" && (!p.complete || sinceSeconds !== null))\n .map((p) => p.pod);\n return { reachedStart: unreached.length === 0,\nunreached };\n}\n\nasync function logView(rawArgs: string[], view: LogViewOptions): Promise<void> {\n const { flags: parsed } = parseCloudArgs({\n spec: LOG_VIEW_FLAGS,\n rawArgs,\n commandWords: 3, // cloud debug logs|errors|boot\n command: \"cloud debug\",\n maxPositionals: 0\n });\n\n const sinceSeconds = sinceFromFlag(parsed[\"--since\"]) ?? view.defaultSinceSeconds;\n const tail = tailFromFlag(parsed[\"--tail\"], view.defaultTail);\n\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n\n let res: RuntimeLogsResponse;\n try {\n res = await fetchRuntimeLogs(client, projectId, {\n sinceSeconds: sinceSeconds ?? undefined,\n tailLines: tail.applied,\n previous: Boolean(parsed[\"--previous\"])\n });\n } catch (e) {\n reportError(e, \"Failed to fetch runtime logs\");\n }\n\n const all = (res.logs ?? \"\").split(\"\\n\").filter((l) => l !== \"\");\n const parsedLines = all.map(parseLogLine);\n const kept = view.filter ? parsedLines.filter((l) => view.filter!(l.text)) : parsedLines;\n const shown = kept.slice(-view.limit);\n const coverage = assessCoverage({ res,\nlines: parsedLines,\nsinceSeconds,\ntail,\nnow: Date.now() });\n const reach = view.needsStart ? bootReach(coverage.pods, sinceSeconds) : null;\n\n emit(\n () => {\n console.log(\"\");\n console.log(\n chalk.bold(` ${view.title} — ${displayProjectRef(rawArgs)}`) + chalk.gray(` ${windowLabel(sinceSeconds)}`)\n );\n console.log(\"\");\n printPodStates(res);\n if (shown.length === 0) {\n console.log(chalk.gray(\" (nothing matched in what was read)\"));\n console.log(\"\");\n } else {\n for (const l of shown) console.log(` ${l.pod ? chalk.gray(`[${l.pod}] `) : \"\"}${l.text}`);\n console.log(\"\");\n if (kept.length > shown.length) {\n console.log(chalk.gray(` (showing the last ${shown.length} of ${kept.length} matching lines)`));\n console.log(\"\");\n }\n }\n printCoverage(coverage, tail);\n if (reach && !reach.reachedStart) {\n const which = reach.unreached.join(\", \");\n console.log(\n chalk.yellow(\n sinceSeconds === null\n ? ` ! The start of ${which} was not read, so its startup lines are not among the lines above.`\n : ` ! The start of ${which} may not have been read: --since limits the read to a recent window. ` +\n \"Drop it to read each pod from its start.\"\n )\n );\n console.log(\"\");\n }\n },\n {\n sinceSeconds,\n tail: { requested: tail.requested,\napplied: tail.applied,\nserverMax: SERVER_MAX_TAIL_LINES,\nnote: tail.note },\n window: {\n requestedFrom: coverage.requestedFrom,\n firstTimestamp: coverage.firstTimestamp,\n lastTimestamp: coverage.lastTimestamp\n },\n state: res.state ?? null,\n pods: coverage.pods,\n truncated: coverage.truncated,\n truncatedReasons: coverage.truncatedReasons,\n ...(reach ? { reachedStart: reach.reachedStart,\nunreachedPods: reach.unreached } : {}),\n matched: kept.length,\n lines: shown\n }\n );\n}\n\nasync function requestsCommand(rawArgs: string[]): Promise<void> {\n const { flags: parsed } = parseCloudArgs({\n spec: REQUESTS_FLAGS,\n rawArgs,\n commandWords: 3, // cloud debug requests\n command: \"cloud debug\",\n maxPositionals: 0\n });\n const sinceSeconds = sinceFromFlag(parsed[\"--since\"]) ?? REQUESTS_DEFAULTS.sinceSeconds;\n const tail = tailFromFlag(parsed[\"--tail\"], REQUESTS_DEFAULTS.tail);\n\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n\n let res: RuntimeLogsResponse;\n try {\n res = await fetchRuntimeLogs(client, projectId, { sinceSeconds,\ntailLines: tail.applied });\n } catch (e) {\n reportError(e, \"Failed to fetch runtime logs\");\n }\n\n const parsedLines = (res.logs ?? \"\")\n .split(\"\\n\")\n .filter((l) => l !== \"\")\n .map(parseLogLine);\n const entries = parsedLines\n .map((l) => parseRequestLine(l.text))\n .filter((e): e is RequestLogEntry => e !== null);\n const shown = entries.slice(-40);\n const coverage = assessCoverage({ res,\nlines: parsedLines,\nsinceSeconds,\ntail,\nnow: Date.now() });\n\n emit(\n () => {\n console.log(\"\");\n console.log(\n chalk.bold(` 🌐 Requests — ${displayProjectRef(rawArgs)}`) +\n chalk.gray(` ${windowLabel(sinceSeconds)}`)\n );\n console.log(\"\");\n printPodStates(res);\n if (shown.length === 0) {\n console.log(chalk.gray(\" No structured request lines in what was read.\"));\n console.log(chalk.gray(\" (this view needs the server's request logging; try `debug logs`)\"));\n console.log(\"\");\n printCoverage(coverage, tail);\n return;\n }\n for (const e of shown) {\n const status = e.status ?? 0;\n const color = status >= 500 ? chalk.red : status >= 400 ? chalk.yellow : chalk.green;\n console.log(\n ` ${color(String(e.status ?? \"---\").padStart(3))} ${e.method.padEnd(6)} ${e.path.slice(0, 70).padEnd(70)} ${chalk.gray(\n e.latencyMs === null ? \"\" : `${e.latencyMs}ms`\n )}`\n );\n }\n console.log(\"\");\n printCoverage(coverage, tail);\n },\n {\n sinceSeconds,\n tail: { requested: tail.requested,\napplied: tail.applied,\nserverMax: SERVER_MAX_TAIL_LINES,\nnote: tail.note },\n window: {\n requestedFrom: coverage.requestedFrom,\n firstTimestamp: coverage.firstTimestamp,\n lastTimestamp: coverage.lastTimestamp\n },\n pods: coverage.pods,\n truncated: coverage.truncated,\n truncatedReasons: coverage.truncatedReasons,\n requests: shown\n }\n );\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Subcommand: pod\n ═══════════════════════════════════════════════════════════════ */\n\nasync function podCommand(rawArgs: string[]): Promise<void> {\n parseCloudArgs({ spec: {},\nrawArgs,\ncommandWords: 3,\ncommand: \"cloud debug\",\nmaxPositionals: 0 });\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n\n interface MetricsResponse {\n status?: string;\n cpu?: string | null;\n memory?: string | null;\n placement?: {\n cluster?: string | null;\n provider?: string | null;\n region?: string | null;\n namespace?: string | null;\n host?: string | null;\n image?: string | null;\n replicas?: { available?: number; desired?: number };\n };\n }\n\n let m: MetricsResponse;\n try {\n m = await client.functions.invoke<MetricsResponse>(\"metrics\", undefined, {\n method: \"GET\",\n path: projectId\n });\n } catch (e) {\n reportError(e, \"Failed to read workload placement\");\n }\n\n const p = m.placement ?? {};\n const replicas = p.replicas ?? {};\n\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` ☸ Workload — ${displayProjectRef(rawArgs)}`));\n console.log(\"\");\n keyValues([\n [\"Status\", m.status ? colorStatus(m.status === \"running\" ? \"active\" : m.status) : undefined],\n [\n \"Replicas\",\n replicas.desired === undefined\n ? undefined\n : `${replicas.available ?? 0} / ${replicas.desired} available`\n ],\n [\"Namespace\", p.namespace],\n [\"Cluster\", p.cluster],\n [\"Region\", [p.provider, p.region].filter(Boolean).join(\" · \") || undefined],\n [\"Host\", p.host],\n [\"Image\", p.image],\n // Reported as-is: the metrics function returns null for \"not\n // measurable\", which must not render as a number.\n [\"CPU\", m.cpu ?? undefined],\n [\"Memory\", m.memory ?? undefined]\n ]);\n console.log(\"\");\n if ((replicas.available ?? 0) === 0 && (replicas.desired ?? 0) > 0) {\n console.log(chalk.yellow(\" No replica is available — the pod is not passing its readiness check.\"));\n console.log(chalk.gray(\" See why with: \") + chalk.bold(\"rebase cloud debug logs --previous\"));\n console.log(\"\");\n }\n },\n { status: m.status ?? null,\nplacement: p }\n );\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Subcommand: db\n ═══════════════════════════════════════════════════════════════ */\n\nasync function dbDebugCommand(rawArgs: string[]): Promise<void> {\n parseCloudArgs({ spec: {},\nrawArgs,\ncommandWords: 3,\ncommand: \"cloud debug\",\nmaxPositionals: 0 });\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n\n interface DbInfo {\n type?: string;\n host?: string | null;\n port?: string | null;\n database?: string | null;\n username?: string | null;\n passwordAvailable?: boolean;\n unavailableReason?: string | null;\n directAccess?: {\n via: \"tunnel\";\n kubectl?: { namespace: string; service: string; localPort: number; remotePort: number };\n } | null;\n }\n\n let info: DbInfo;\n try {\n info = await client.functions.invoke<DbInfo>(\"db-info\", undefined, { method: \"GET\",\npath: projectId });\n } catch (e) {\n reportError(e, \"Failed to read database connection info\");\n }\n\n // The host above is a Service inside the platform's cluster, so `debug db`\n // has to say what to do about that. It used to print `kubectl port-forward\n // -n rebase-tenant-…`, which needs a kubeconfig for OUR cluster: a customer\n // has none, and nothing in the platform issues one. The tunnel is the\n // remedy a reader can actually run.\n const access = info.directAccess;\n const connectCmd = access ? \"rebase cloud db connect\" : null;\n const LOCAL_PORT = 5432;\n const psqlCmd =\n access && info.username && info.database\n ? `psql -h 127.0.0.1 -p ${LOCAL_PORT} -U ${info.username} -d ${info.database}`\n : null;\n // Only for a cluster the customer owns, where the credentials are theirs.\n const kubectlCmd = access?.kubectl\n ? `kubectl port-forward -n ${access.kubectl.namespace} svc/${access.kubectl.service} `\n + `${access.kubectl.localPort}:${access.kubectl.remotePort}`\n : null;\n\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` 🐘 Database — ${displayProjectRef(rawArgs)}`));\n console.log(\"\");\n if (info.unavailableReason) {\n console.log(chalk.yellow(` ${info.unavailableReason}`));\n console.log(\"\");\n return;\n }\n keyValues([\n [\"Type\", info.type],\n [\"Host\", info.host],\n [\"Port\", info.port],\n [\"Database\", info.database],\n [\"Username\", info.username],\n [\"Password\", info.passwordAvailable ? chalk.gray(\"stored — not shown here\") : chalk.yellow(\"none stored\")]\n ]);\n console.log(\"\");\n if (connectCmd) {\n // Printed rather than run. Opening a tunnel and a database shell\n // is not something a command called `debug` should do implicitly.\n console.log(chalk.gray(\" That host is inside the platform's cluster and does not resolve here.\"));\n console.log(chalk.gray(\" To reach the database from this machine:\"));\n console.log(\"\");\n console.log(` ${connectCmd}`);\n if (psqlCmd) console.log(` ${psqlCmd}`);\n console.log(\"\");\n if (kubectlCmd) {\n console.log(chalk.gray(\" Or, on your own cluster:\"));\n console.log(` ${kubectlCmd}`);\n console.log(\"\");\n }\n if (info.passwordAvailable) {\n console.log(\n chalk.gray(\" Get the password with: \") + chalk.bold(\"rebase cloud db info --reveal\")\n );\n console.log(\"\");\n }\n }\n },\n {\n type: info.type ?? null,\n host: info.host ?? null,\n port: info.port ?? null,\n database: info.database ?? null,\n username: info.username ?? null,\n passwordAvailable: Boolean(info.passwordAvailable),\n connectCommand: connectCmd,\n kubectlCommand: kubectlCmd,\n psqlCommand: psqlCmd\n }\n );\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Dispatch\n ═══════════════════════════════════════════════════════════════ */\n\n/**\n * Everything the switch below dispatches, for the did-you-mean. `workload` is\n * the older spelling of `pod` and stays out of it: suggesting the name we no\n * longer print in the help would teach the wrong one.\n */\nconst DEBUG_SUBCOMMANDS = [\"health\", \"logs\", \"errors\", \"boot\", \"requests\", \"pod\", \"db\"] as const;\n\nexport async function debugCommand(action: string | undefined, rawArgs: string[]): Promise<void> {\n switch (action) {\n case undefined:\n case \"health\":\n // Bare `rebase cloud debug` runs the probes: it is the answer to\n // \"something is wrong\" more often than any other view here.\n await healthCommand(rawArgs);\n break;\n case \"logs\":\n case \"errors\":\n case \"boot\":\n await logView(rawArgs, LOG_VIEWS[action]);\n break;\n case \"requests\":\n await requestsCommand(rawArgs);\n break;\n case \"pod\":\n case \"workload\":\n await podCommand(rawArgs);\n break;\n case \"db\":\n await dbDebugCommand(rawArgs);\n break;\n case \"help\":\n case \"--help\":\n printDebugHelp();\n break;\n default:\n // One refusal path in both modes. The terminal branch used to print\n // the whole help page to STDOUT — the results stream — after a\n // command that produced no result, which is the same shape the\n // index dispatcher was fixed out of. `fail` writes the machine\n // envelope under `--json` and one red line to stderr otherwise, and\n // the words come from the shared builder so the human line and the\n // machine one cannot drift apart: it carries the near-miss when\n // there is one, and names the page for the rest.\n fail(unknownCommandMessage(action, DEBUG_SUBCOMMANDS, \"cloud debug\"), undefined, \"unknown_command\");\n }\n}\n\n/**\n * The log flags as one action's help lists them, with THAT action's defaults.\n * They were one group-wide list saying \"Default: 500\", which was true of two of\n * the four actions, and offered `--previous` to `requests`, which rejects it.\n */\nfunction logFlagHelp(defaults: { sinceSeconds: number | null; tail: number }, previous: boolean): Array<[string, string]> {\n const flags: Array<[string, string]> = [\n [\n \"--since <dur>\",\n defaults.sinceSeconds === null\n ? \"Only lines this recent: 90s, 15m, 2h, 1d. Default: from each pod's start\"\n : `Lookback window: 90s, 15m, 2h, 1d. Default: ${formatDuration(defaults.sinceSeconds)}`\n ],\n [\"--tail <n>\", `Newest lines to read per pod, at most ${SERVER_MAX_TAIL_LINES}. Default: ${defaults.tail}`]\n ];\n if (previous) flags.push([\"--previous\", \"Read the CRASHED container instance, where the reason lives\"]);\n return flags;\n}\n\nfunction logViewFlagHelp(view: LogViewOptions): Array<[string, string]> {\n return logFlagHelp({ sinceSeconds: view.defaultSinceSeconds,\ntail: view.defaultTail }, true);\n}\n\nexport function printDebugHelp(): void {\n printGroupHelp({\n command: \"cloud debug\",\n title: \"Find out why a deployed project is misbehaving\",\n actions: [\n {\n action: \"health\",\n section: \"End-to-end\",\n description: \"Probe the live URL and explain every status code (the default)\",\n flags: [\n [\"--host <hostname>\", \"Probe this address instead of the project's own\"],\n [\"--table <name>\", \"Table for the unauth-read probe. Default: users\"],\n [\"--collection <name>\", \"Deprecated spelling of --table. Still works, and warns\"],\n [\"--function <name>\", \"Also assert this function loaded, against the listing\"]\n ]\n },\n { action: \"logs\",\nsection: \"Runtime\",\ndescription: \"Recent application logs\",\nflags: logViewFlagHelp(LOG_VIEWS.logs) },\n { action: \"errors\",\nsection: \"Runtime\",\ndescription: \"Error and warning lines only\",\nflags: logViewFlagHelp(LOG_VIEWS.errors) },\n { action: \"requests\",\nsection: \"Runtime\",\ndescription: \"HTTP requests the server logged: status, path, latency\",\nflags: logFlagHelp(REQUESTS_DEFAULTS, false) },\n { action: \"boot\",\nsection: \"Runtime\",\ndescription: \"What the server decided at startup: storage, functions, auth\",\nflags: logViewFlagHelp(LOG_VIEWS.boot) },\n { action: \"pod\",\nsection: \"Runtime\",\ndescription: \"Replicas, image, namespace, cluster placement\" },\n { action: \"db\",\nsection: \"Data\",\ndescription: \"Connection shape and the port-forward recipe. Never the password\" }\n ],\n notes: [\n \"Everything here is read-only. `health` exits non-zero when a check fails, so it works in a\",\n \"deploy script. To restart a workload, use `rebase cloud restart`.\",\n \"The log views end with the window asked for, the window returned, and anything that cut\",\n `between them. The control plane returns at most ${SERVER_MAX_TAIL_LINES} lines per pod.`\n ]\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2GA,IAAM,cAA4B;CAC9B,SAAS;CACT,SACI;AACR;AAEA,SAAS,YAAY,MAA4B;CAC7C,OAAO;EAAE,SAAS;EACtB,SAAS,6BAA6B;CAAO;AAC7C;;;;;AAMA,IAAa,SAAsB;CAC/B;EACI,IAAI;EACJ,OAAO;EACP,QAAQ;EACR,YAAY;EACZ,SAAS;EACT,YAAY,WAAW;GACnB,IAAI,WAAW,MAAM,OAAO;GAC5B,IAAI,WAAW,KAAK,OAAO;IAA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E,OAAO,YAAY;EAAE,cAAc,KAAK;EAC5C,MAAM,KAAK;CAAY,GAAG,IAAI;AAC9B;AAEA,SAAgB,iBAAuB;CACnC,eAAe;EACX,SAAS;EACT,OAAO;EACP,SAAS;GACL;IACI,QAAQ;IACR,SAAS;IACT,aAAa;IACb,OAAO;KACH,CAAC,qBAAqB,iDAAiD;KACvE,CAAC,kBAAkB,iDAAiD;KACpE,CAAC,uBAAuB,wDAAwD;KAChF,CAAC,qBAAqB,uDAAuD;IACjF;GACJ;GACA;IAAE,QAAQ;IACtB,SAAS;IACT,aAAa;IACb,OAAO,gBAAgB,UAAU,IAAI;GAAE;GAC3B;IAAE,QAAQ;IACtB,SAAS;IACT,aAAa;IACb,OAAO,gBAAgB,UAAU,MAAM;GAAE;GAC7B;IAAE,QAAQ;IACtB,SAAS;IACT,aAAa;IACb,OAAO,YAAY,mBAAmB,KAAK;GAAE;GACjC;IAAE,QAAQ;IACtB,SAAS;IACT,aAAa;IACb,OAAO,gBAAgB,UAAU,IAAI;GAAE;GAC3B;IAAE,QAAQ;IACtB,SAAS;IACT,aAAa;GAAgD;GACjD;IAAE,QAAQ;IACtB,SAAS;IACT,aAAa;GAAmE;EACxE;EACA,OAAO;GACH;GACA;GACA;GACA,mDAAmD,sBAAsB;EAC7E;CACJ,CAAC;AACL"}
1
+ {"version":3,"file":"debug-C7Ss34XB.js","names":[],"sources":["../src/commands/cloud/debug.ts"],"sourcesContent":["/**\n * `rebase cloud debug <subcommand>` — one entry point for \"why is my deployed\n * app not behaving\".\n *\n * ## Why this exists\n *\n * The useful signals for a deployed project live in four different places — the\n * control plane, the workload's pods, the tenant database, and the public URL —\n * and each is normally reached with a different tool and a different set of\n * flags. Getting to a log should not be a research task. This started life as a\n * hand-rolled `prod-debug.sh` for a single project, with the namespace and the\n * URL hardcoded at the top; it earned its place twice in one week, so it is\n * generalised here to any project the CLI can already resolve.\n *\n * ## Read-only by default\n *\n * Every subcommand here only reads. The two things the original script could do\n * that mutate are deliberately NOT reproduced as-is:\n *\n * - restarting the workload lives at `rebase cloud restart`, which already\n * gates downtime behind `--yes`; duplicating it here would give the same\n * destructive act a second, ungated spelling.\n * - `debug db` prints the port-forward recipe and the connection's *shape*.\n * It opens no session and prints no password — `rebase cloud db info\n * --reveal` is the explicit, auditable way to get one.\n *\n * ## The probes are the point\n *\n * `debug health` is the highest-value piece and the reason the script existed.\n * A bare status code is not a diagnosis: a 404 from a functions route means\n * something completely different from a 404 at the root, and a 200 on an\n * unauthenticated read is a finding rather than a success. So every probe ships\n * with the interpretation of what it got, not just the number — see\n * {@link PROBES}.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport { warnDeprecated } from \"@rebasepro/common\";\nimport { unknownCommandMessage } from \"../../utils/unknown-command\";\nimport {\n requireClient,\n requireProject,\n parseCloudArgs,\n displayProjectRef,\n fetchTenantBaseDomain,\n projectHost,\n colorStatus,\n keyValues,\n emit,\n printGroupHelp,\n fail,\n reportError,\n type CloudClient\n} from \"./context\";\n\n/* ═══════════════════════════════════════════════════════════════\n Health probes\n ═══════════════════════════════════════════════════════════════ */\n\n/** How a probe's outcome should be read. */\nexport type Verdict =\n /** Behaving as a healthy deployment should. */\n | \"ok\"\n /** Reachable and legal, but worth a human look (e.g. a public read). */\n | \"warn\"\n /** Broken, or wired up wrong. */\n | \"fail\"\n /** We could not classify the response. */\n | \"unknown\";\n\nexport interface ProbeReading {\n verdict: Verdict;\n /** What this status code *means for this endpoint*, in one sentence. */\n meaning: string;\n}\n\nexport interface ProbeSpec {\n id: string;\n /** Column label in human output. */\n label: string;\n method: \"GET\" | \"POST\";\n /** Path relative to the project origin. */\n path: (opts: ProbeTargets) => string;\n body?: unknown;\n /** One-line statement of what a healthy deployment answers here. */\n healthy: string;\n interpret: (status: number | null) => ProbeReading;\n /**\n * Read the response body as well. Set only where the body carries a fact the\n * status code cannot — today, the function listing.\n */\n needsBody?: boolean;\n /**\n * Sharpen the status-code reading using the parsed body. Returning null\n * keeps {@link interpret}'s verdict.\n */\n refine?: (body: unknown, targets: ProbeTargets) => ProbeReading | null;\n}\n\nexport interface ProbeTargets {\n /** Table used for the unauthenticated-read probe. */\n collection: string;\n /** Function to confirm exists, if the caller named one. */\n fn?: string;\n}\n\n/** A response never arrived: DNS, TLS, ingress, or the pod. */\nconst NO_RESPONSE: ProbeReading = {\n verdict: \"fail\",\n meaning:\n \"nothing answered — the hostname does not resolve, the ingress has no route, or no pod is running\"\n};\n\nfunction serverError(what: string): ProbeReading {\n return { verdict: \"fail\",\nmeaning: `the server is running but ${what}` };\n}\n\n/**\n * The probe set, in the order a failure cascades: if `health` is down, nothing\n * below it is meaningful, so it is checked first and reported first.\n */\nexport const PROBES: ProbeSpec[] = [\n {\n id: \"health\",\n label: \"health\",\n method: \"GET\",\n path: () => \"/health\",\n healthy: \"200 — the backend is up\",\n interpret: (status) => {\n if (status === null) return NO_RESPONSE;\n if (status === 200) return { verdict: \"ok\",\nmeaning: \"the backend is up and serving\" };\n if (status === 404) {\n return {\n verdict: \"fail\",\n meaning:\n \"something answered but it is not a Rebase backend — the ingress is routing this host elsewhere\"\n };\n }\n if (status >= 500) return serverError(\"its health endpoint is failing\");\n return { verdict: \"unknown\",\nmeaning: \"unexpected for a health endpoint\" };\n }\n },\n {\n id: \"spa\",\n label: \"spa\",\n method: \"GET\",\n path: () => \"/\",\n healthy: \"200 — the frontend is being served\",\n interpret: (status) => {\n if (status === null) return NO_RESPONSE;\n if (status === 200) return { verdict: \"ok\",\nmeaning: \"the frontend bundle is being served\" };\n if (status === 404) {\n return {\n verdict: \"warn\",\n meaning:\n \"no frontend at the root — expected for a backend-only project, otherwise the SPA assets were not bundled into the image\"\n };\n }\n if (status >= 500) return serverError(\"the root route throws\");\n return { verdict: \"unknown\",\nmeaning: \"unexpected at the site root\" };\n }\n },\n {\n id: \"auth\",\n label: \"auth\",\n method: \"POST\",\n path: () => \"/api/auth/login\",\n body: {},\n healthy: \"400 — auth is mounted and rejects an empty body\",\n interpret: (status) => {\n if (status === null) return NO_RESPONSE;\n // The probe deliberately posts an empty body: a healthy auth route\n // must reject it. Reachability is what is being tested, not a login.\n if (status === 400 || status === 422) {\n return { verdict: \"ok\",\nmeaning: \"auth is mounted and rejected the empty body, as it should\" };\n }\n if (status === 401 || status === 403) {\n return { verdict: \"ok\",\nmeaning: \"auth is mounted and refused the credentials\" };\n }\n if (status === 404) {\n return {\n verdict: \"fail\",\n meaning: \"the auth routes are NOT mounted — this project cannot sign anyone in\"\n };\n }\n if (status === 200) {\n return {\n verdict: \"fail\",\n meaning: \"an EMPTY login body was accepted — a login with no credentials must never succeed\"\n };\n }\n if (status >= 500) return serverError(\"the login route throws — often a missing or unmigrated auth table\");\n return { verdict: \"unknown\",\nmeaning: \"unexpected for a login route\" };\n }\n },\n {\n id: \"unauthRead\",\n label: \"unauth read\",\n method: \"GET\",\n path: (t) => `/api/data/${encodeURIComponent(t.collection)}`,\n healthy: \"401 — reads require authentication\",\n interpret: (status) => {\n if (status === null) return NO_RESPONSE;\n if (status === 401 || status === 403) {\n return { verdict: \"ok\",\nmeaning: \"unauthenticated reads are refused — row-level security is enforced\" };\n }\n if (status === 200) {\n // Legal, and sometimes intended. Never silently called healthy.\n return {\n verdict: \"warn\",\n meaning:\n \"this table is readable with NO authentication — correct only if it is deliberately public\"\n };\n }\n if (status === 404) {\n return {\n verdict: \"warn\",\n meaning: \"no such table on this deployment — check the name, or pass --table\"\n };\n }\n if (status >= 500) {\n return serverError(\n \"the read reached the database and failed — most often an RLS policy naming a column or table that is not there\"\n );\n }\n return { verdict: \"unknown\",\nmeaning: \"unexpected for a data read\" };\n }\n },\n {\n id: \"functions\",\n label: \"functions\",\n method: \"GET\",\n /**\n * The router's own listing endpoint, NOT a function's path.\n *\n * This matters, and it is the one place the original script got a wrong\n * answer. A function is a Hono sub-app mounted at `/<name>`, and it\n * usually defines only sub-routes (`/get`, `/list`) — so\n * `/api/functions/<name>` 404s **even when everything is mounted and\n * healthy**. Probing there cannot separate \"the router is missing\" from\n * \"that function defines no root route\", and reporting the first is how\n * you send someone to debug a deployment that was fine.\n *\n * `GET /api/functions` is unambiguous: the router registers a listing\n * route at its own root (see `createFunctionRoutes`), so a 200 proves\n * the mount *and* names every function that loaded.\n */\n path: () => \"/api/functions\",\n healthy: \"200 — the functions router is mounted and lists its functions\",\n interpret: (status) => {\n if (status === null) return NO_RESPONSE;\n if (status === 200) return { verdict: \"ok\",\nmeaning: \"the functions router is mounted\" };\n if (status === 401 || status === 403) {\n // The listing is behind auth on this deployment. That still\n // proves the router is there, which is what is being tested.\n return { verdict: \"ok\",\nmeaning: \"the functions router is mounted (its listing requires auth)\" };\n }\n if (status === 404) {\n return {\n verdict: \"fail\",\n meaning:\n \"the functions router did not mount — no functions directory was found at build time, or it held no functions, so every function on this project is unreachable\"\n };\n }\n if (status >= 500) return serverError(\"the functions router throws\");\n return { verdict: \"unknown\",\nmeaning: \"unexpected for the functions listing\" };\n },\n needsBody: true,\n refine: (body, t) => {\n const names = functionNames(body);\n if (!names) return null;\n if (t.fn && !names.includes(t.fn)) {\n // Definitive, because the listing is authoritative — no guessing\n // from a 404 that could equally mean the router is absent.\n return {\n verdict: \"fail\",\n meaning:\n `the router is mounted but no function is named \"${t.fn}\" — it loaded ${names.length}: ` +\n `${names.join(\", \")}`\n };\n }\n const found = t.fn ? `, including ${t.fn}` : \"\";\n return {\n verdict: \"ok\",\n meaning: `the functions router is mounted and loaded ${names.length} function${names.length === 1 ? \"\" : \"s\"}${found}`\n };\n }\n }\n];\n\n/** The function names out of a listing body, or null when it is not one. */\nexport function functionNames(body: unknown): string[] | null {\n const list = (body as { functions?: unknown } | null | undefined)?.functions;\n if (!Array.isArray(list)) return null;\n const names = list\n .map((f) => (f as { name?: unknown })?.name)\n .filter((n): n is string => typeof n === \"string\");\n return names.length === list.length ? names : null;\n}\n\nexport interface ProbeResult {\n id: string;\n label: string;\n method: string;\n url: string;\n status: number | null;\n ms: number;\n verdict: Verdict;\n meaning: string;\n healthy: string;\n /**\n * Whether the STATUS CODE alone looked healthy. False means the code itself\n * was wrong; true with a failing `verdict` means the code was fine and the\n * body carried the bad news (a named function that did not load). The\n * summary uses this so it never tells you to expect a 200 you already got.\n */\n statusOk: boolean;\n}\n\n/** Milliseconds before a probe is treated as unanswered. */\nconst PROBE_TIMEOUT_MS = 10_000;\n\n/**\n * Ceiling on a probe body we will parse. The only body read is the function\n * listing; anything larger is a page we have no use for, and a debug command\n * must not be the thing that runs a machine out of memory.\n */\nconst MAX_PROBE_BODY_BYTES = 256 * 1024;\n\n/**\n * Run one probe. A transport failure is a `null` status, never a thrown error:\n * \"nothing answered\" is a diagnosis in its own right and the other probes still\n * need to run.\n */\nexport async function runProbe(origin: string, spec: ProbeSpec, targets: ProbeTargets): Promise<ProbeResult> {\n const url = `${origin}${spec.path(targets)}`;\n const started = Date.now();\n let status: number | null = null;\n let body: unknown;\n try {\n const res = await fetch(url, {\n method: spec.method,\n headers: spec.body ? { \"Content-Type\": \"application/json\" } : undefined,\n body: spec.body ? JSON.stringify(spec.body) : undefined,\n redirect: \"manual\",\n signal: AbortSignal.timeout(PROBE_TIMEOUT_MS)\n });\n status = res.status;\n if (spec.needsBody && res.ok) {\n const text = await res.text();\n if (text.length <= MAX_PROBE_BODY_BYTES) {\n try {\n body = JSON.parse(text);\n } catch {\n // Not JSON — `refine` returns null and the status reading stands.\n }\n }\n }\n } catch {\n status = null;\n }\n const statusReading = spec.interpret(status);\n // The body can only sharpen a reading, never invent one where the request\n // failed outright.\n const reading = (status !== null && spec.refine?.(body, targets)) || statusReading;\n return {\n statusOk: statusReading.verdict === \"ok\",\n id: spec.id,\n label: spec.label,\n method: spec.method,\n url,\n status,\n ms: Date.now() - started,\n verdict: reading.verdict,\n meaning: reading.meaning,\n healthy: spec.healthy\n };\n}\n\n/** The worst verdict across probes — what the command's exit code keys off. */\nexport function overallVerdict(results: ProbeResult[]): Verdict {\n if (results.some((r) => r.verdict === \"fail\")) return \"fail\";\n if (results.some((r) => r.verdict === \"unknown\")) return \"unknown\";\n if (results.some((r) => r.verdict === \"warn\")) return \"warn\";\n return \"ok\";\n}\n\nfunction verdictMark(v: Verdict): string {\n switch (v) {\n case \"ok\":\n return chalk.green(\"✓\");\n case \"warn\":\n return chalk.yellow(\"!\");\n case \"fail\":\n return chalk.red(\"✗\");\n default:\n return chalk.gray(\"?\");\n }\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Log parsing\n ═══════════════════════════════════════════════════════════════\n\n `runtime-logs` renders each line as `<rfc3339> [<pod>] <text>`, where <text>\n is normally the application's structured JSON. These helpers unwrap that so\n the derived views (errors / requests / boot) work on the payload rather than\n on the transport's formatting.\n*/\n\nexport interface ParsedLogLine {\n ts: string | null;\n pod: string | null;\n text: string;\n}\n\nconst LOG_PREFIX_RE = /^(?:(\\d{4}-\\d{2}-\\d{2}T[\\d:.]+Z?)\\s+)?(?:\\[([^\\]]+)\\]\\s+)?([\\s\\S]*)$/;\n\nexport function parseLogLine(line: string): ParsedLogLine {\n const m = LOG_PREFIX_RE.exec(line);\n if (!m) return { ts: null,\npod: null,\ntext: line };\n return { ts: m[1] ?? null,\npod: m[2] ?? null,\ntext: m[3] ?? \"\" };\n}\n\n/**\n * Lines an operator scanning for a fault wants to see.\n *\n * Matches the structured `severity` field first, then the shapes that show up\n * in unstructured output. `refus`/`denied` are in the list because a permission\n * failure often logs at info level and is exactly what one is hunting for.\n */\nexport function isErrorLine(text: string): boolean {\n return /\"(?:severity|level)\":\\s*\"(?:ERROR|WARN(?:ING)?|error|warn)\"|\\bError:|\\bERR!|refus|denied|EACCES|ECONNREFUSED/i.test(\n text\n );\n}\n\nexport interface RequestLogEntry {\n status: number | null;\n method: string;\n path: string;\n latencyMs: number | null;\n}\n\n/**\n * Pull an HTTP request record out of a log line, or null when it is not one.\n *\n * Only structured request lines are recognised. Guessing at prose would produce\n * a table with invented columns, which is worse than a short one.\n */\nexport function parseRequestLine(text: string): RequestLogEntry | null {\n const start = text.indexOf(\"{\");\n if (start === -1) return null;\n let parsed: Record<string, unknown>;\n try {\n parsed = JSON.parse(text.slice(start)) as Record<string, unknown>;\n } catch {\n return null;\n }\n if (parsed.message !== \"request\" && parsed.msg !== \"request\") return null;\n\n const num = (v: unknown): number | null => {\n const n = typeof v === \"string\" ? Number(v) : typeof v === \"number\" ? v : NaN;\n return Number.isFinite(n) ? n : null;\n };\n return {\n status: num(parsed.status),\n method: typeof parsed.method === \"string\" ? parsed.method : \"\",\n path: typeof parsed.path === \"string\" ? parsed.path : \"\",\n latencyMs: num(parsed.latencyMs ?? parsed.durationMs)\n };\n}\n\n/**\n * Startup lines: what the server *decided* it was going to do. Which storage\n * backend it bound, which functions it loaded, whether auth tables were found.\n * This is the fastest way to tell a misconfiguration from a runtime fault.\n */\nexport function isBootLine(text: string): boolean {\n // \"Loaded custom functions\" and \"Loaded cron job…\" are 0.25's words for what\n // earlier runtimes logged as \"Mounted …\"; both are what a deployment runs.\n return /storage|Loaded (?:custom )?function|Loaded cron|Cron jobs scheduled|Cron scheduler|Mounted|Auth tables|Server running|listening|Refusing|migrat/i.test(text);\n}\n\n/** Render a number of seconds back as the compact duration a user would type. */\nexport function formatDuration(seconds: number): string {\n if (seconds % 86400 === 0 && seconds >= 86400) return `${seconds / 86400}d`;\n if (seconds % 3600 === 0 && seconds >= 3600) return `${seconds / 3600}h`;\n if (seconds % 60 === 0 && seconds >= 60) return `${seconds / 60}m`;\n return `${seconds}s`;\n}\n\n/**\n * Parse a duration like `15m`, `2h`, `90s`, `1d` (or a bare number of seconds)\n * into seconds. Returns null when it is not a duration.\n */\nexport function parseSince(input: string | undefined): number | null {\n if (!input) return null;\n const m = /^(\\d+(?:\\.\\d+)?)\\s*([smhd])?$/i.exec(input.trim());\n if (!m) return null;\n const value = parseFloat(m[1]);\n const unit = (m[2] || \"s\").toLowerCase();\n const mult = unit === \"s\" ? 1 : unit === \"m\" ? 60 : unit === \"h\" ? 3600 : 86400;\n return Math.round(value * mult);\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Shared fetches\n ═══════════════════════════════════════════════════════════════ */\n\n/** One pod's entry in a `runtime-logs` answer. */\nexport interface RuntimeLogsPod {\n pod: string;\n state: string;\n /** Lines this pod returned. */\n lines: number;\n message: string | null;\n hint: string | null;\n /** The server's per-pod BYTE budget cut this pod's output. Says nothing about the line limit. */\n truncated?: boolean;\n}\n\nexport interface RuntimeLogsResponse {\n logs?: string;\n pods?: RuntimeLogsPod[];\n ordering?: string;\n /** A byte budget or the pod-count ceiling cut the result. Says nothing about the line limit. */\n truncated?: boolean;\n state?: string;\n message?: string | null;\n}\n\n/**\n * The most lines `runtime-logs` returns per pod.\n *\n * The control plane enforces this (`MAX_TAIL_LINES` in\n * `saas/backend/functions/runtime-logs.ts`) by clamping a larger `tailLines`\n * without saying so: its answer names neither the limit nor the value it used.\n * `--tail 200000` therefore came back as 2000 lines reported as untruncated.\n * The CLI clamps first, with the same number, so the lowering is something it\n * can print rather than something that happened out of sight.\n */\nexport const SERVER_MAX_TAIL_LINES = 2000;\n\n/** How many lines per pod a read asks for, and why that may be less than requested. */\nexport interface TailLimit {\n /** What `--tail` asked for, or the view's default. */\n requested: number;\n /** What is sent: `requested`, lowered to {@link SERVER_MAX_TAIL_LINES}. */\n applied: number;\n /** Whether `--tail` was given, so a message can name the flag or the default. */\n explicit: boolean;\n /** Set when `applied < requested`: the sentence that says so. */\n note: string | null;\n}\n\nexport function resolveTail(requested: number, explicit: boolean): TailLimit {\n const applied = Math.min(requested, SERVER_MAX_TAIL_LINES);\n return {\n requested,\n applied,\n explicit,\n note:\n applied < requested\n ? `--tail ${requested} was lowered to ${applied}: the control plane returns at most ` +\n `${SERVER_MAX_TAIL_LINES} lines per pod.`\n : null\n };\n}\n\n/** Read `--tail`, refusing anything that is not a positive whole number. */\nfunction tailFromFlag(value: number | undefined, fallback: number): TailLimit {\n if (value === undefined) return resolveTail(fallback, false);\n if (!Number.isInteger(value) || value <= 0) {\n fail(`--tail must be a positive whole number of lines; received \"${value}\".`, undefined, \"usage\");\n }\n return resolveTail(value, true);\n}\n\n/** What one pod's lines actually cover. */\nexport interface PodCoverage extends RuntimeLogsPod {\n /** Earliest and latest timestamps among the lines this pod returned. */\n firstTimestamp: string | null;\n lastTimestamp: string | null;\n /** A limit cut what this pod would otherwise have returned for the window. */\n truncated: boolean;\n /** Which limit: the per-pod line limit, or the server's byte budget. */\n truncatedBy: \"tail\" | \"bytes\" | null;\n /** The plain explanation, when truncated. */\n truncatedReason: string | null;\n /**\n * Every line this pod holds in the window came back. With no window (read\n * from the start), its first line is the start of its log.\n */\n complete: boolean;\n}\n\n/** The window asked for against the window delivered. */\nexport interface LogCoverage {\n /** Start of the window asked for, ISO. Null when reading each pod from its start. */\n requestedFrom: string | null;\n /** Earliest and latest timestamps across every line returned. */\n firstTimestamp: string | null;\n lastTimestamp: string | null;\n pods: PodCoverage[];\n truncated: boolean;\n truncatedReasons: string[];\n}\n\n/** A span of milliseconds as `29d 23h`, `2h 5m`, `35m`, `40s`. */\nexport function formatSpan(ms: number): string {\n const s = Math.max(0, Math.round(ms / 1000));\n const d = Math.floor(s / 86400);\n const h = Math.floor((s % 86400) / 3600);\n const m = Math.floor((s % 3600) / 60);\n if (d > 0) return h > 0 ? `${d}d ${h}h` : `${d}d`;\n if (h > 0) return m > 0 ? `${h}h ${m}m` : `${h}h`;\n if (m > 0) return `${m}m`;\n return `${s}s`;\n}\n\nfunction timestampRange(lines: ParsedLogLine[]): { first: string | null; last: string | null } {\n let first: { text: string; ms: number } | null = null;\n let last: { text: string; ms: number } | null = null;\n for (const l of lines) {\n if (!l.ts) continue;\n const ms = Date.parse(l.ts);\n if (Number.isNaN(ms)) continue;\n if (!first || ms < first.ms) first = { text: l.ts,\nms };\n if (!last || ms > last.ms) last = { text: l.ts,\nms };\n }\n return { first: first?.text ?? null,\nlast: last?.text ?? null };\n}\n\n/**\n * Compare what a read covered with what it asked for.\n *\n * The server's `truncated` describes only its byte budgets and pod ceiling, so\n * a pod that filled the line limit came back marked complete however much of\n * the window it left unread. The line limit is the cut that matters most, and\n * it is detected here: a pod that returned as many lines as the limit, whose\n * earliest line is later than the start of the window, was cut by it.\n *\n * Filling the limit is the half that separates a cut from a young pod. A pod\n * that started an hour ago also has no line older than an hour; it returned\n * fewer lines than the limit, so what came back is its whole log, and nothing\n * was cut.\n */\nexport function assessCoverage(opts: {\n res: RuntimeLogsResponse;\n lines: ParsedLogLine[];\n /** The window asked for. Null reads each pod from its start. */\n sinceSeconds: number | null;\n tail: TailLimit;\n now: number;\n}): LogCoverage {\n const { res, lines, sinceSeconds, tail, now } = opts;\n const windowStartMs = sinceSeconds === null ? null : now - sinceSeconds * 1000;\n const requestedFrom = windowStartMs === null ? null : new Date(windowStartMs).toISOString();\n const limitName = tail.note\n ? `the control plane's ceiling of ${tail.applied} lines per pod`\n : tail.explicit\n ? `the --tail ${tail.applied} limit`\n : `the default of ${tail.applied} lines per pod`;\n // Only worth saying when raising it would read further back.\n const raise = tail.applied < SERVER_MAX_TAIL_LINES\n ? ` Raise --tail (at most ${SERVER_MAX_TAIL_LINES}) to read further back.`\n : ` The control plane returns only each pod's newest ${SERVER_MAX_TAIL_LINES}, so older lines cannot be read from here.`;\n\n const pods: PodCoverage[] = (res.pods ?? []).map((p) => {\n const range = timestampRange(lines.filter((l) => l.pod === p.pod));\n const base = { ...p,\nfirstTimestamp: range.first,\nlastTimestamp: range.last };\n if (p.state !== \"ok\") {\n return { ...base,\ntruncated: false,\ntruncatedBy: null,\ntruncatedReason: null,\ncomplete: false };\n }\n if (p.truncated) {\n return {\n ...base,\n truncated: true,\n truncatedBy: \"bytes\" as const,\n truncatedReason:\n `${p.pod}: the control plane's per-pod byte budget cut this pod's output short` +\n (range.first ? ` — what fit runs ${range.first} to ${range.last}.` : \".\"),\n complete: false\n };\n }\n const firstMs = range.first ? Date.parse(range.first) : null;\n const startsLate = windowStartMs === null || firstMs === null || firstMs > windowStartMs;\n if (p.lines >= tail.applied && startsLate) {\n let reason: string;\n if (firstMs === null) {\n reason = `${p.pod}: returned ${p.lines} lines, ${limitName}; they carry no timestamps, so how far back they reach is unknown.`;\n } else if (sinceSeconds !== null && windowStartMs !== null) {\n reason =\n `${p.pod}: returned ${p.lines} lines, ${limitName}, and the earliest is ${range.first} — ` +\n `${formatSpan(firstMs - windowStartMs)} after the ${formatDuration(sinceSeconds)} ` +\n `window begins (${requestedFrom}). Lines in between were not read.${raise}`;\n } else {\n reason =\n `${p.pod}: returned ${p.lines} lines, ${limitName}, so its log before ${range.first} ` +\n `was not read.${raise}`;\n }\n return { ...base,\ntruncated: true,\ntruncatedBy: \"tail\" as const,\ntruncatedReason: reason,\ncomplete: false };\n }\n return { ...base,\ntruncated: false,\ntruncatedBy: null,\ntruncatedReason: null,\ncomplete: true };\n });\n\n const truncatedReasons = pods.flatMap((p) => (p.truncatedReason ? [p.truncatedReason] : []));\n // The server's flag also covers cuts no single pod owns: its total byte\n // budget across pods, and the cap on how many pods it reads.\n if (res.truncated && !pods.some((p) => p.truncatedBy === \"bytes\")) {\n truncatedReasons.push(\n \"The control plane trimmed the combined result (its total byte budget, or the most pods it reads at once); the oldest lines were dropped.\"\n );\n }\n const overall = timestampRange(lines);\n return {\n requestedFrom,\n firstTimestamp: overall.first,\n lastTimestamp: overall.last,\n pods,\n truncated: Boolean(res.truncated) || pods.some((p) => p.truncated),\n truncatedReasons\n };\n}\n\nasync function fetchRuntimeLogs(\n client: CloudClient,\n projectId: string,\n opts: { sinceSeconds?: number; tailLines?: number; previous?: boolean }\n): Promise<RuntimeLogsResponse> {\n const params = new URLSearchParams();\n if (opts.sinceSeconds !== undefined) params.set(\"sinceSeconds\", String(opts.sinceSeconds));\n if (opts.tailLines !== undefined) params.set(\"tailLines\", String(opts.tailLines));\n if (opts.previous) params.set(\"previous\", \"true\");\n params.set(\"timestamps\", \"true\");\n const qs = params.toString();\n return client.functions.invoke<RuntimeLogsResponse>(\"runtime-logs\", undefined, {\n method: \"GET\",\n path: `${projectId}${qs ? `?${qs}` : \"\"}`\n });\n}\n\n/** Print the per-pod states runtime-logs reports, including its hints. */\nfunction printPodStates(res: RuntimeLogsResponse): void {\n if (res.state === \"no_pods\") {\n console.log(chalk.yellow(` ${res.message ?? \"No pods are running for this project.\"}`));\n console.log(\"\");\n return;\n }\n for (const p of res.pods ?? []) {\n if (p.state === \"ok\") continue;\n console.log(` ${chalk.yellow(p.pod)} ${chalk.gray(`(${p.state})`)}`);\n if (p.message) console.log(chalk.gray(` ${p.message}`));\n // The hint is the actionable half — a crash-looping container's reason\n // is in its PREVIOUS instance, and that is only discoverable if we say so.\n if (p.hint) console.log(chalk.cyan(` → ${p.hint}`));\n }\n}\n\n/**\n * The window asked for, the window delivered, and every cut between them.\n * Printed after the lines, where a reader's eye is when the output ends.\n */\nfunction printCoverage(coverage: LogCoverage, tail: TailLimit): void {\n const asked = coverage.requestedFrom ? `from ${coverage.requestedFrom}` : \"from each pod's start\";\n const got = coverage.firstTimestamp && coverage.lastTimestamp\n ? `${coverage.firstTimestamp} → ${coverage.lastTimestamp} ` +\n `(${formatSpan(Date.parse(coverage.lastTimestamp) - Date.parse(coverage.firstTimestamp))})`\n : \"no timestamped lines\";\n console.log(chalk.gray(` Asked for: ${asked}`));\n console.log(chalk.gray(` Returned: ${got}`));\n if (tail.note) console.log(chalk.yellow(` ! ${tail.note}`));\n if (coverage.truncated) {\n console.log(chalk.yellow(\" ! Truncated — the lines above do not cover the window asked for:\"));\n for (const reason of coverage.truncatedReasons) console.log(chalk.yellow(` ${reason}`));\n }\n console.log(\"\");\n}\n\n/**\n * Resolve the public origin a project is served at — or `--host`, when given.\n *\n * Shared with `rebase cloud cron`, which reads the runtime at the same address\n * `debug health` probes.\n */\nexport async function resolveOrigin(\n rawArgs: string[],\n client: CloudClient,\n url: string,\n projectId: string\n): Promise<string> {\n const parsed = arg({ \"--host\": String }, { argv: rawArgs.slice(3),\npermissive: true });\n if (parsed[\"--host\"]) {\n const h = parsed[\"--host\"].trim().replace(/\\/+$/, \"\");\n return /^https?:\\/\\//.test(h) ? h : `https://${h}`;\n }\n\n const [project, baseDomain] = await Promise.all([\n client.data.table(\"projects\").findById(projectId) as Promise<\n { subdomain?: string; host?: string; customDomain?: string } | undefined\n >,\n fetchTenantBaseDomain(client, url)\n ]);\n if (!project) fail(`Project ${displayProjectRef(rawArgs)} not found.`);\n\n const host = projectHost(project, baseDomain);\n if (!host) {\n fail(\n \"Could not determine the public URL for this project.\",\n \"It may never have been deployed. Pass --host <hostname> to probe an address directly.\"\n );\n }\n return `https://${host}`;\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Subcommand: health\n ═══════════════════════════════════════════════════════════════ */\n\nasync function healthCommand(rawArgs: string[]): Promise<void> {\n // Strict: `--tabel users` used to be dropped and the probe then ran\n // against the default table while reporting on the one asked for.\n const { flags: parsed } = parseCloudArgs({\n spec: HEALTH_FLAGS,\n rawArgs,\n commandWords: 3, // cloud debug health\n command: \"cloud debug\",\n maxPositionals: 0\n });\n const targets: ProbeTargets = {\n collection: resolveProbeTable(parsed) || \"users\",\n // Optional: the listing endpoint proves the mount on its own. A name\n // here additionally asserts that this particular function loaded.\n fn: parsed[\"--function\"]\n };\n\n const { client, url } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const origin = await resolveOrigin(rawArgs, client, url, projectId);\n\n // Sequential, not Promise.all: five simultaneous requests to a struggling\n // pod is a small load test, and the latency column would then measure our\n // own contention rather than the endpoint's.\n const results: ProbeResult[] = [];\n for (const spec of PROBES) results.push(await runProbe(origin, spec, targets));\n\n const overall = overallVerdict(results);\n\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` 🩺 Health — ${displayProjectRef(rawArgs)}`) + chalk.gray(` ${origin}`));\n console.log(\"\");\n const width = Math.max(...results.map((r) => r.label.length));\n for (const r of results) {\n const code = r.status === null ? chalk.red(\"---\") : String(r.status);\n console.log(\n ` ${verdictMark(r.verdict)} ${chalk.bold(r.label.padEnd(width))} ${code.padStart(3)} ${chalk.gray(`${r.ms}ms`)}`\n );\n console.log(` ${chalk.gray(r.meaning)}`);\n }\n console.log(\"\");\n if (overall === \"ok\") {\n console.log(chalk.green(\" Everything reachable and wired as expected.\"));\n } else {\n const bad = results.filter((r) => r.verdict === \"fail\" || r.verdict === \"warn\");\n console.log(chalk.gray(` ${bad.length} of ${results.length} check${bad.length === 1 ? \"\" : \"s\"} need attention.`));\n // Only where the status code itself was wrong — restating\n // \"expected 200\" under a probe that returned 200 reads as a bug.\n const wrongStatus = bad.filter((r) => !r.statusOk);\n if (wrongStatus.length > 0) {\n console.log(chalk.gray(\" A healthy deployment answers:\"));\n for (const r of wrongStatus) {\n console.log(chalk.gray(` ${r.label.padEnd(width)} ${r.healthy}`));\n }\n }\n }\n console.log(\"\");\n },\n { origin,\noverall,\nprobes: results }\n );\n\n // A failing probe is a failing command — this is meant to be usable in a\n // deploy script's `if`, not only read by a human.\n if (overall === \"fail\") process.exit(1);\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Subcommand: logs / errors / requests / boot\n ═══════════════════════════════════════════════════════════════ */\n\n/** What `debug logs`, `errors` and `boot` parse. Their help pairs against this. */\nexport const LOG_VIEW_FLAGS = {\n \"--since\": String,\n \"--tail\": Number,\n \"--previous\": Boolean\n} as const;\n\n/** What `debug requests` parses. */\nexport const REQUESTS_FLAGS = {\n \"--since\": String,\n \"--tail\": Number\n} as const;\n\n/** What `debug health` parses. */\nexport const HEALTH_FLAGS = {\n \"--table\": String,\n /** @deprecated Use `--table` instead. Accepted, with a warning, until a later release. */\n \"--collection\": String,\n \"--function\": String,\n // `--host` is read again inside `resolveOrigin`, which needs it before\n // the client exists; declared here because THIS is the parse that\n // decides whether the line is accepted at all.\n \"--host\": String\n} as const;\n\n/**\n * The table `debug health` probes, from `--table` or its deprecated spelling\n * `--collection`, which still works and warns once. Undefined when neither was\n * given.\n *\n * \"Table\" is the word for the app's data; \"collection\" is the CMS's. Both\n * spellings at once is refused unless they agree, since one of them would be\n * ignored.\n */\nexport function resolveProbeTable(flags: { \"--table\"?: string; \"--collection\"?: string }): string | undefined {\n const table = flags[\"--table\"];\n const collection = flags[\"--collection\"];\n if (collection === undefined) return table;\n warnDeprecated(\"cli.cloud-debug-health-collection\", \"`rebase cloud debug health --collection` is deprecated; use `--table` instead.\");\n if (table !== undefined && table !== collection) {\n fail(\"--table and --collection name the same thing; pass --table alone.\", undefined, \"usage\");\n }\n return table ?? collection;\n}\n\ninterface LogViewOptions {\n /** Keep only lines matching this. Omit to keep everything. */\n filter?: (text: string) => boolean;\n /** Default lookback when --since is not given. Null reads each pod from its start. */\n defaultSinceSeconds: number | null;\n /** Lines read per pod when --tail is not given. */\n defaultTail: number;\n /** Max lines rendered. */\n limit: number;\n title: string;\n /**\n * The lines wanted are the first a pod wrote, so a read that did not reach\n * a pod's start has not looked where they are — see {@link bootReach}.\n */\n needsStart?: boolean;\n}\n\nconst LOG_VIEWS = {\n logs: { defaultSinceSeconds: 900,\ndefaultTail: 500,\nlimit: 200,\ntitle: \"📄 Logs\" },\n errors: { filter: isErrorLine,\ndefaultSinceSeconds: 3600,\ndefaultTail: 500,\nlimit: 40,\ntitle: \"🔥 Errors\" },\n boot: {\n filter: isBootLine,\n // No window, and the most lines the control plane returns. Startup\n // happened when the pod started, which may have been days ago: a\n // 7-day window and the newest 500 lines missed it on any pod that had\n // served traffic since.\n defaultSinceSeconds: null,\n defaultTail: SERVER_MAX_TAIL_LINES,\n limit: 25,\n title: \"🚀 Boot\",\n needsStart: true\n }\n} satisfies Record<string, LogViewOptions>;\n\nconst REQUESTS_DEFAULTS = { sinceSeconds: 900,\ntail: 1000 };\n\n/** Read `--since`, refusing anything that is not a duration. Undefined when it was not given. */\nfunction sinceFromFlag(sinceArg: string | undefined): number | undefined {\n if (sinceArg === undefined) return undefined;\n const seconds = parseSince(sinceArg);\n if (seconds === null) fail(`--since must be a duration like 15m, 2h or 90s; received \"${sinceArg}\".`);\n return seconds;\n}\n\nfunction windowLabel(sinceSeconds: number | null): string {\n return sinceSeconds === null ? \"since each pod started\" : `last ${formatDuration(sinceSeconds)}`;\n}\n\n/**\n * Whether a boot read reached each pod's start, which is where its startup\n * lines are. A pod whose read was cut has not been looked at there, so finding\n * no startup lines in it means nothing — and a line from later in its life\n * that happens to mention `storage` is not its startup.\n *\n * Under `--since` a pod is never counted as reached: a complete read of the\n * window starts at the pod's first line only if the pod started inside it, and\n * nothing in the answer says whether it did.\n */\nexport function bootReach(pods: PodCoverage[], sinceSeconds: number | null): {\n reachedStart: boolean;\n unreached: string[];\n} {\n const unreached = pods\n .filter((p) => p.state === \"ok\" && (!p.complete || sinceSeconds !== null))\n .map((p) => p.pod);\n return { reachedStart: unreached.length === 0,\nunreached };\n}\n\nasync function logView(rawArgs: string[], view: LogViewOptions): Promise<void> {\n const { flags: parsed } = parseCloudArgs({\n spec: LOG_VIEW_FLAGS,\n rawArgs,\n commandWords: 3, // cloud debug logs|errors|boot\n command: \"cloud debug\",\n maxPositionals: 0\n });\n\n const sinceSeconds = sinceFromFlag(parsed[\"--since\"]) ?? view.defaultSinceSeconds;\n const tail = tailFromFlag(parsed[\"--tail\"], view.defaultTail);\n\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n\n let res: RuntimeLogsResponse;\n try {\n res = await fetchRuntimeLogs(client, projectId, {\n sinceSeconds: sinceSeconds ?? undefined,\n tailLines: tail.applied,\n previous: Boolean(parsed[\"--previous\"])\n });\n } catch (e) {\n reportError(e, \"Failed to fetch runtime logs\");\n }\n\n const all = (res.logs ?? \"\").split(\"\\n\").filter((l) => l !== \"\");\n const parsedLines = all.map(parseLogLine);\n const kept = view.filter ? parsedLines.filter((l) => view.filter!(l.text)) : parsedLines;\n const shown = kept.slice(-view.limit);\n const coverage = assessCoverage({ res,\nlines: parsedLines,\nsinceSeconds,\ntail,\nnow: Date.now() });\n const reach = view.needsStart ? bootReach(coverage.pods, sinceSeconds) : null;\n\n emit(\n () => {\n console.log(\"\");\n console.log(\n chalk.bold(` ${view.title} — ${displayProjectRef(rawArgs)}`) + chalk.gray(` ${windowLabel(sinceSeconds)}`)\n );\n console.log(\"\");\n printPodStates(res);\n if (shown.length === 0) {\n console.log(chalk.gray(\" (nothing matched in what was read)\"));\n console.log(\"\");\n } else {\n for (const l of shown) console.log(` ${l.pod ? chalk.gray(`[${l.pod}] `) : \"\"}${l.text}`);\n console.log(\"\");\n if (kept.length > shown.length) {\n console.log(chalk.gray(` (showing the last ${shown.length} of ${kept.length} matching lines)`));\n console.log(\"\");\n }\n }\n printCoverage(coverage, tail);\n if (reach && !reach.reachedStart) {\n const which = reach.unreached.join(\", \");\n console.log(\n chalk.yellow(\n sinceSeconds === null\n ? ` ! The start of ${which} was not read, so its startup lines are not among the lines above.`\n : ` ! The start of ${which} may not have been read: --since limits the read to a recent window. ` +\n \"Drop it to read each pod from its start.\"\n )\n );\n console.log(\"\");\n }\n },\n {\n sinceSeconds,\n tail: { requested: tail.requested,\napplied: tail.applied,\nserverMax: SERVER_MAX_TAIL_LINES,\nnote: tail.note },\n window: {\n requestedFrom: coverage.requestedFrom,\n firstTimestamp: coverage.firstTimestamp,\n lastTimestamp: coverage.lastTimestamp\n },\n state: res.state ?? null,\n pods: coverage.pods,\n truncated: coverage.truncated,\n truncatedReasons: coverage.truncatedReasons,\n ...(reach ? { reachedStart: reach.reachedStart,\nunreachedPods: reach.unreached } : {}),\n matched: kept.length,\n lines: shown\n }\n );\n}\n\nasync function requestsCommand(rawArgs: string[]): Promise<void> {\n const { flags: parsed } = parseCloudArgs({\n spec: REQUESTS_FLAGS,\n rawArgs,\n commandWords: 3, // cloud debug requests\n command: \"cloud debug\",\n maxPositionals: 0\n });\n const sinceSeconds = sinceFromFlag(parsed[\"--since\"]) ?? REQUESTS_DEFAULTS.sinceSeconds;\n const tail = tailFromFlag(parsed[\"--tail\"], REQUESTS_DEFAULTS.tail);\n\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n\n let res: RuntimeLogsResponse;\n try {\n res = await fetchRuntimeLogs(client, projectId, { sinceSeconds,\ntailLines: tail.applied });\n } catch (e) {\n reportError(e, \"Failed to fetch runtime logs\");\n }\n\n const parsedLines = (res.logs ?? \"\")\n .split(\"\\n\")\n .filter((l) => l !== \"\")\n .map(parseLogLine);\n const entries = parsedLines\n .map((l) => parseRequestLine(l.text))\n .filter((e): e is RequestLogEntry => e !== null);\n const shown = entries.slice(-40);\n const coverage = assessCoverage({ res,\nlines: parsedLines,\nsinceSeconds,\ntail,\nnow: Date.now() });\n\n emit(\n () => {\n console.log(\"\");\n console.log(\n chalk.bold(` 🌐 Requests — ${displayProjectRef(rawArgs)}`) +\n chalk.gray(` ${windowLabel(sinceSeconds)}`)\n );\n console.log(\"\");\n printPodStates(res);\n if (shown.length === 0) {\n console.log(chalk.gray(\" No structured request lines in what was read.\"));\n console.log(chalk.gray(\" (this view needs the server's request logging; try `debug logs`)\"));\n console.log(\"\");\n printCoverage(coverage, tail);\n return;\n }\n for (const e of shown) {\n const status = e.status ?? 0;\n const color = status >= 500 ? chalk.red : status >= 400 ? chalk.yellow : chalk.green;\n console.log(\n ` ${color(String(e.status ?? \"---\").padStart(3))} ${e.method.padEnd(6)} ${e.path.slice(0, 70).padEnd(70)} ${chalk.gray(\n e.latencyMs === null ? \"\" : `${e.latencyMs}ms`\n )}`\n );\n }\n console.log(\"\");\n printCoverage(coverage, tail);\n },\n {\n sinceSeconds,\n tail: { requested: tail.requested,\napplied: tail.applied,\nserverMax: SERVER_MAX_TAIL_LINES,\nnote: tail.note },\n window: {\n requestedFrom: coverage.requestedFrom,\n firstTimestamp: coverage.firstTimestamp,\n lastTimestamp: coverage.lastTimestamp\n },\n pods: coverage.pods,\n truncated: coverage.truncated,\n truncatedReasons: coverage.truncatedReasons,\n requests: shown\n }\n );\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Subcommand: pod\n ═══════════════════════════════════════════════════════════════ */\n\nasync function podCommand(rawArgs: string[]): Promise<void> {\n parseCloudArgs({ spec: {},\nrawArgs,\ncommandWords: 3,\ncommand: \"cloud debug\",\nmaxPositionals: 0 });\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n\n interface MetricsResponse {\n status?: string;\n cpu?: string | null;\n memory?: string | null;\n placement?: {\n cluster?: string | null;\n provider?: string | null;\n region?: string | null;\n namespace?: string | null;\n host?: string | null;\n image?: string | null;\n replicas?: { available?: number; desired?: number };\n };\n }\n\n let m: MetricsResponse;\n try {\n m = await client.functions.invoke<MetricsResponse>(\"metrics\", undefined, {\n method: \"GET\",\n path: projectId\n });\n } catch (e) {\n reportError(e, \"Failed to read workload placement\");\n }\n\n const p = m.placement ?? {};\n const replicas = p.replicas ?? {};\n\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` ☸ Workload — ${displayProjectRef(rawArgs)}`));\n console.log(\"\");\n keyValues([\n [\"Status\", m.status ? colorStatus(m.status === \"running\" ? \"active\" : m.status) : undefined],\n [\n \"Replicas\",\n replicas.desired === undefined\n ? undefined\n : `${replicas.available ?? 0} / ${replicas.desired} available`\n ],\n [\"Namespace\", p.namespace],\n [\"Cluster\", p.cluster],\n [\"Region\", [p.provider, p.region].filter(Boolean).join(\" · \") || undefined],\n [\"Host\", p.host],\n [\"Image\", p.image],\n // Reported as-is: the metrics function returns null for \"not\n // measurable\", which must not render as a number.\n [\"CPU\", m.cpu ?? undefined],\n [\"Memory\", m.memory ?? undefined]\n ]);\n console.log(\"\");\n if ((replicas.available ?? 0) === 0 && (replicas.desired ?? 0) > 0) {\n console.log(chalk.yellow(\" No replica is available — the pod is not passing its readiness check.\"));\n console.log(chalk.gray(\" See why with: \") + chalk.bold(\"rebase cloud debug logs --previous\"));\n console.log(\"\");\n }\n },\n { status: m.status ?? null,\nplacement: p }\n );\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Subcommand: db\n ═══════════════════════════════════════════════════════════════ */\n\nasync function dbDebugCommand(rawArgs: string[]): Promise<void> {\n parseCloudArgs({ spec: {},\nrawArgs,\ncommandWords: 3,\ncommand: \"cloud debug\",\nmaxPositionals: 0 });\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n\n interface DbInfo {\n type?: string;\n host?: string | null;\n port?: string | null;\n database?: string | null;\n username?: string | null;\n passwordAvailable?: boolean;\n unavailableReason?: string | null;\n directAccess?: {\n via: \"tunnel\";\n kubectl?: { namespace: string; service: string; localPort: number; remotePort: number };\n } | null;\n }\n\n let info: DbInfo;\n try {\n info = await client.functions.invoke<DbInfo>(\"db-info\", undefined, { method: \"GET\",\npath: projectId });\n } catch (e) {\n reportError(e, \"Failed to read database connection info\");\n }\n\n // The host above is a Service inside the platform's cluster, so `debug db`\n // has to say what to do about that. It used to print `kubectl port-forward\n // -n rebase-tenant-…`, which needs a kubeconfig for OUR cluster: a customer\n // has none, and nothing in the platform issues one. The tunnel is the\n // remedy a reader can actually run.\n const access = info.directAccess;\n const connectCmd = access ? \"rebase cloud db connect\" : null;\n const LOCAL_PORT = 5432;\n const psqlCmd =\n access && info.username && info.database\n ? `psql -h 127.0.0.1 -p ${LOCAL_PORT} -U ${info.username} -d ${info.database}`\n : null;\n // Only for a cluster the customer owns, where the credentials are theirs.\n const kubectlCmd = access?.kubectl\n ? `kubectl port-forward -n ${access.kubectl.namespace} svc/${access.kubectl.service} `\n + `${access.kubectl.localPort}:${access.kubectl.remotePort}`\n : null;\n\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` 🐘 Database — ${displayProjectRef(rawArgs)}`));\n console.log(\"\");\n if (info.unavailableReason) {\n console.log(chalk.yellow(` ${info.unavailableReason}`));\n console.log(\"\");\n return;\n }\n keyValues([\n [\"Type\", info.type],\n [\"Host\", info.host],\n [\"Port\", info.port],\n [\"Database\", info.database],\n [\"Username\", info.username],\n [\"Password\", info.passwordAvailable ? chalk.gray(\"stored — not shown here\") : chalk.yellow(\"none stored\")]\n ]);\n console.log(\"\");\n if (connectCmd) {\n // Printed rather than run. Opening a tunnel and a database shell\n // is not something a command called `debug` should do implicitly.\n console.log(chalk.gray(\" That host is inside the platform's cluster and does not resolve here.\"));\n console.log(chalk.gray(\" To reach the database from this machine:\"));\n console.log(\"\");\n console.log(` ${connectCmd}`);\n if (psqlCmd) console.log(` ${psqlCmd}`);\n console.log(\"\");\n if (kubectlCmd) {\n console.log(chalk.gray(\" Or, on your own cluster:\"));\n console.log(` ${kubectlCmd}`);\n console.log(\"\");\n }\n if (info.passwordAvailable) {\n console.log(\n chalk.gray(\" Get the password with: \") + chalk.bold(\"rebase cloud db info --reveal\")\n );\n console.log(\"\");\n }\n }\n },\n {\n type: info.type ?? null,\n host: info.host ?? null,\n port: info.port ?? null,\n database: info.database ?? null,\n username: info.username ?? null,\n passwordAvailable: Boolean(info.passwordAvailable),\n connectCommand: connectCmd,\n kubectlCommand: kubectlCmd,\n psqlCommand: psqlCmd\n }\n );\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Dispatch\n ═══════════════════════════════════════════════════════════════ */\n\n/**\n * Everything the switch below dispatches, for the did-you-mean. `workload` is\n * the older spelling of `pod` and stays out of it: suggesting the name we no\n * longer print in the help would teach the wrong one.\n */\nconst DEBUG_SUBCOMMANDS = [\"health\", \"logs\", \"errors\", \"boot\", \"requests\", \"pod\", \"db\"] as const;\n\nexport async function debugCommand(action: string | undefined, rawArgs: string[]): Promise<void> {\n switch (action) {\n case undefined:\n case \"health\":\n // Bare `rebase cloud debug` runs the probes: it is the answer to\n // \"something is wrong\" more often than any other view here.\n await healthCommand(rawArgs);\n break;\n case \"logs\":\n case \"errors\":\n case \"boot\":\n await logView(rawArgs, LOG_VIEWS[action]);\n break;\n case \"requests\":\n await requestsCommand(rawArgs);\n break;\n case \"pod\":\n case \"workload\":\n await podCommand(rawArgs);\n break;\n case \"db\":\n await dbDebugCommand(rawArgs);\n break;\n case \"help\":\n case \"--help\":\n printDebugHelp();\n break;\n default:\n // One refusal path in both modes. The terminal branch used to print\n // the whole help page to STDOUT — the results stream — after a\n // command that produced no result, which is the same shape the\n // index dispatcher was fixed out of. `fail` writes the machine\n // envelope under `--json` and one red line to stderr otherwise, and\n // the words come from the shared builder so the human line and the\n // machine one cannot drift apart: it carries the near-miss when\n // there is one, and names the page for the rest.\n fail(unknownCommandMessage(action, DEBUG_SUBCOMMANDS, \"cloud debug\"), undefined, \"unknown_command\");\n }\n}\n\n/**\n * The log flags as one action's help lists them, with THAT action's defaults.\n * They were one group-wide list saying \"Default: 500\", which was true of two of\n * the four actions, and offered `--previous` to `requests`, which rejects it.\n */\nfunction logFlagHelp(defaults: { sinceSeconds: number | null; tail: number }, previous: boolean): Array<[string, string]> {\n const flags: Array<[string, string]> = [\n [\n \"--since <dur>\",\n defaults.sinceSeconds === null\n ? \"Only lines this recent: 90s, 15m, 2h, 1d. Default: from each pod's start\"\n : `Lookback window: 90s, 15m, 2h, 1d. Default: ${formatDuration(defaults.sinceSeconds)}`\n ],\n [\"--tail <n>\", `Newest lines to read per pod, at most ${SERVER_MAX_TAIL_LINES}. Default: ${defaults.tail}`]\n ];\n if (previous) flags.push([\"--previous\", \"Read the CRASHED container instance, where the reason lives\"]);\n return flags;\n}\n\nfunction logViewFlagHelp(view: LogViewOptions): Array<[string, string]> {\n return logFlagHelp({ sinceSeconds: view.defaultSinceSeconds,\ntail: view.defaultTail }, true);\n}\n\nexport function printDebugHelp(): void {\n printGroupHelp({\n command: \"cloud debug\",\n title: \"Find out why a deployed project is misbehaving\",\n actions: [\n {\n action: \"health\",\n section: \"End-to-end\",\n description: \"Probe the live URL and explain every status code (the default)\",\n flags: [\n [\"--host <hostname>\", \"Probe this address instead of the project's own\"],\n [\"--table <name>\", \"Table for the unauth-read probe. Default: users\"],\n [\"--collection <name>\", \"Deprecated spelling of --table. Still works, and warns\"],\n [\"--function <name>\", \"Also assert this function loaded, against the listing\"]\n ]\n },\n { action: \"logs\",\nsection: \"Runtime\",\ndescription: \"Recent application logs\",\nflags: logViewFlagHelp(LOG_VIEWS.logs) },\n { action: \"errors\",\nsection: \"Runtime\",\ndescription: \"Error and warning lines only\",\nflags: logViewFlagHelp(LOG_VIEWS.errors) },\n { action: \"requests\",\nsection: \"Runtime\",\ndescription: \"HTTP requests the server logged: status, path, latency\",\nflags: logFlagHelp(REQUESTS_DEFAULTS, false) },\n { action: \"boot\",\nsection: \"Runtime\",\ndescription: \"What the server decided at startup: storage, functions, auth\",\nflags: logViewFlagHelp(LOG_VIEWS.boot) },\n { action: \"pod\",\nsection: \"Runtime\",\ndescription: \"Replicas, image, namespace, cluster placement\" },\n { action: \"db\",\nsection: \"Data\",\ndescription: \"Connection shape and the port-forward recipe. Never the password\" }\n ],\n notes: [\n \"Everything here is read-only. `health` exits non-zero when a check fails, so it works in a\",\n \"deploy script. To restart a workload, use `rebase cloud restart`.\",\n \"The log views end with the window asked for, the window returned, and anything that cut\",\n `between them. The control plane returns at most ${SERVER_MAX_TAIL_LINES} lines per pod.`\n ]\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2GA,IAAM,cAA4B;CAC9B,SAAS;CACT,SACI;AACR;AAEA,SAAS,YAAY,MAA4B;CAC7C,OAAO;EAAE,SAAS;EACtB,SAAS,6BAA6B;CAAO;AAC7C;;;;;AAMA,IAAa,SAAsB;CAC/B;EACI,IAAI;EACJ,OAAO;EACP,QAAQ;EACR,YAAY;EACZ,SAAS;EACT,YAAY,WAAW;GACnB,IAAI,WAAW,MAAM,OAAO;GAC5B,IAAI,WAAW,KAAK,OAAO;IAAE,SAAS;IAClD,SAAS;GAAgC;GAC7B,IAAI,WAAW,KACX,OAAO;IACH,SAAS;IACT,SACI;GACR;GAEJ,IAAI,UAAU,KAAK,OAAO,YAAY,gCAAgC;GACtE,OAAO;IAAE,SAAS;IAC9B,SAAS;GAAmC;EACpC;CACJ;CACA;EACI,IAAI;EACJ,OAAO;EACP,QAAQ;EACR,YAAY;EACZ,SAAS;EACT,YAAY,WAAW;GACnB,IAAI,WAAW,MAAM,OAAO;GAC5B,IA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D;IACjF;GACJ;GACA;IAAE,QAAQ;IACtB,SAAS;IACT,aAAa;IACb,OAAO,gBAAgB,UAAU,IAAI;GAAE;GAC3B;IAAE,QAAQ;IACtB,SAAS;IACT,aAAa;IACb,OAAO,gBAAgB,UAAU,MAAM;GAAE;GAC7B;IAAE,QAAQ;IACtB,SAAS;IACT,aAAa;IACb,OAAO,YAAY,mBAAmB,KAAK;GAAE;GACjC;IAAE,QAAQ;IACtB,SAAS;IACT,aAAa;IACb,OAAO,gBAAgB,UAAU,IAAI;GAAE;GAC3B;IAAE,QAAQ;IACtB,SAAS;IACT,aAAa;GAAgD;GACjD;IAAE,QAAQ;IACtB,SAAS;IACT,aAAa;GAAmE;EACxE;EACA,OAAO;GACH;GACA;GACA;GACA,mDAAmD,sBAAsB;EAC7E;CACJ,CAAC;AACL"}
@@ -2,7 +2,7 @@ import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
2
2
  import { C as resolveBackendPaths } from "./manifest-RjqxfCpb.js";
3
3
  import { n as cliVersion } from "./version-ONIeo7jl.js";
4
4
  import { t as createSchemaModuleImporter } from "./import-schema-module-Df67TIWj.js";
5
- import { t as analyseFunctionsDirectory } from "./function-portability-BIvlvR9q.js";
5
+ import { t as analyseFunctionsDirectory } from "./function-portability-Dppl6uqg.js";
6
6
  import fs from "fs";
7
7
  import path from "path";
8
8
  import { fileURLToPath } from "url";
@@ -468,4 +468,4 @@ function projectResourceGraph(graph) {
468
468
  //#endregion
469
469
  export { projectResourceGraph as a, withImplicitDefaults as c, derive_exports as i, writeResourceGraphFile as l, deriveOptionsFor as n, readResourceGraphFile as o, deriveResourceGraph as r, serializeResourceGraph as s, RESOURCE_GRAPH_FILENAME as t };
470
470
 
471
- //# sourceMappingURL=derive-Mky_u59_.js.map
471
+ //# sourceMappingURL=derive-ChP6vgfi.js.map