@reddoorla/maintenance 0.72.0 → 0.75.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.
- package/dist/airtable-6L3JD7FY.js +9 -0
- package/dist/{announce-HJCGEVJA.js → announce-V6EYPPUR.js} +4 -4
- package/dist/{blux-FKZYMKLF.js → blux-C24OVDDW.js} +1044 -69
- package/dist/blux-C24OVDDW.js.map +1 -0
- package/dist/{bump-deps-GZEJAUKI.js → bump-deps-OQR3IXLN.js} +2 -2
- package/dist/chunk-2OP4JKIQ.js +19 -0
- package/dist/chunk-2OP4JKIQ.js.map +1 -0
- package/dist/{chunk-BJCA7O4A.js → chunk-3PU2QWOJ.js} +2 -2
- package/dist/{chunk-GI4M2AMO.js → chunk-4BHNP6Y2.js} +2 -2
- package/dist/{chunk-KRHPS3R4.js → chunk-6OYICQSJ.js} +47 -3
- package/dist/chunk-6OYICQSJ.js.map +1 -0
- package/dist/{chunk-BWKK2ZXS.js → chunk-GXVX4HUH.js} +32 -2
- package/dist/chunk-GXVX4HUH.js.map +1 -0
- package/dist/{chunk-KLB2OLPW.js → chunk-HBFMTM2E.js} +3 -3
- package/dist/{chunk-SQJ53Z7R.js → chunk-I55YWV6T.js} +3 -3
- package/dist/{chunk-7P7YETHG.js → chunk-IDBMYDVH.js} +2 -2
- package/dist/{chunk-JGLAWXUC.js → chunk-JR67FZVC.js} +7 -3
- package/dist/chunk-JR67FZVC.js.map +1 -0
- package/dist/{chunk-APTAITXZ.js → chunk-KKL3RYFQ.js} +2 -2
- package/dist/{chunk-NRISG4XD.js → chunk-NUIBQPB3.js} +42 -11
- package/dist/chunk-NUIBQPB3.js.map +1 -0
- package/dist/{chunk-BHE5CUWI.js → chunk-PERP7LSS.js} +269 -18
- package/dist/chunk-PERP7LSS.js.map +1 -0
- package/dist/chunk-RHPDQW6D.js +29 -0
- package/dist/chunk-RHPDQW6D.js.map +1 -0
- package/dist/{chunk-HR5SONJC.js → chunk-SK44IFZN.js} +2 -2
- package/dist/cli/bin.js +31 -19
- package/dist/cli/bin.js.map +1 -1
- package/dist/cli/commands/audit.js +6 -6
- package/dist/{convert-to-pnpm-SVFDLXZS.js → convert-to-pnpm-OVMASATZ.js} +2 -2
- package/dist/{digest-VX7Q4MNF.js → digest-LEMZS5ZK.js} +99 -7
- package/dist/digest-LEMZS5ZK.js.map +1 -0
- package/dist/{ensure-site-O7G5ZJS7.js → ensure-site-3SOAWTZF.js} +2 -2
- package/dist/forms/index.js +1 -1
- package/dist/{github-signals-QVW2LB7N.js → github-signals-TF3VSNIN.js} +4 -4
- package/dist/{health-endpoint-IYR5VBUT.js → health-endpoint-JZGYCMTV.js} +2 -2
- package/dist/index.d.ts +104 -19
- package/dist/index.js +122 -30
- package/dist/index.js.map +1 -1
- package/dist/{init-CU6PVZRG.js → init-7PTP4O2K.js} +4 -4
- package/dist/{launch-JWXCTJRG.js → launch-W33FWWOZ.js} +6 -6
- package/dist/{lighthouse-airtable-J5TLASJC.js → lighthouse-airtable-ZXNMDEPE.js} +3 -3
- package/dist/{onboard-6UQE5QIO.js → onboard-PX36YDZA.js} +2 -2
- package/dist/{orchestrate-ZDH24Z6Y.js → orchestrate-NYRYEKQM.js} +3 -3
- package/dist/{preflight-BNTMWTPG.js → preflight-JCQFKB6M.js} +4 -4
- package/dist/{renovate-dispatch-C3ALLACX.js → renovate-dispatch-6II2JVOX.js} +29 -27
- package/dist/renovate-dispatch-6II2JVOX.js.map +1 -0
- package/dist/{report-YLFSGNWR.js → report-POHQEV6F.js} +21 -5
- package/dist/report-POHQEV6F.js.map +1 -0
- package/dist/screenouts-7P5GOZMV.js +57 -0
- package/dist/screenouts-7P5GOZMV.js.map +1 -0
- package/dist/{self-updating-64FNRQB5.js → self-updating-2YSVNMPP.js} +2 -2
- package/dist/{selftest-7DPNGL6R.js → selftest-OO2WDSDM.js} +5 -5
- package/dist/{smoke-suite-TWILWDSF.js → smoke-suite-CSP23NZM.js} +2 -2
- package/dist/spam-classifier-VG4ICIWS.js +217 -0
- package/dist/spam-classifier-VG4ICIWS.js.map +1 -0
- package/dist/submissions-BNRGY3JQ.js +122 -0
- package/dist/submissions-BNRGY3JQ.js.map +1 -0
- package/dist/submissions-MDKWJYMM.js +281 -0
- package/dist/submissions-MDKWJYMM.js.map +1 -0
- package/dist/{svelte-codemods-RVDTTXFD.js → svelte-codemods-V54KOBWU.js} +2 -2
- package/dist/{sync-configs-BUUD6L5Q.js → sync-configs-UBCJRASZ.js} +2 -2
- package/dist/{upgrade-HHKWYJRN.js → upgrade-WR6ICPAG.js} +2 -2
- package/dist/{websites-EH2ULELZ.js → websites-U6642XSE.js} +10 -2
- package/dist/{write-audits-to-airtable-LZDYTNX5.js → write-audits-to-airtable-22T6D733.js} +4 -4
- package/package.json +1 -1
- package/dist/airtable-U2GTDTK5.js +0 -9
- package/dist/blux-FKZYMKLF.js.map +0 -1
- package/dist/chunk-BHE5CUWI.js.map +0 -1
- package/dist/chunk-BWKK2ZXS.js.map +0 -1
- package/dist/chunk-JGLAWXUC.js.map +0 -1
- package/dist/chunk-KRHPS3R4.js.map +0 -1
- package/dist/chunk-NRISG4XD.js.map +0 -1
- package/dist/chunk-QTHKOIFJ.js +0 -13
- package/dist/chunk-QTHKOIFJ.js.map +0 -1
- package/dist/digest-VX7Q4MNF.js.map +0 -1
- package/dist/renovate-dispatch-C3ALLACX.js.map +0 -1
- package/dist/report-YLFSGNWR.js.map +0 -1
- /package/dist/{airtable-U2GTDTK5.js.map → airtable-6L3JD7FY.js.map} +0 -0
- /package/dist/{announce-HJCGEVJA.js.map → announce-V6EYPPUR.js.map} +0 -0
- /package/dist/{bump-deps-GZEJAUKI.js.map → bump-deps-OQR3IXLN.js.map} +0 -0
- /package/dist/{chunk-BJCA7O4A.js.map → chunk-3PU2QWOJ.js.map} +0 -0
- /package/dist/{chunk-GI4M2AMO.js.map → chunk-4BHNP6Y2.js.map} +0 -0
- /package/dist/{chunk-KLB2OLPW.js.map → chunk-HBFMTM2E.js.map} +0 -0
- /package/dist/{chunk-SQJ53Z7R.js.map → chunk-I55YWV6T.js.map} +0 -0
- /package/dist/{chunk-7P7YETHG.js.map → chunk-IDBMYDVH.js.map} +0 -0
- /package/dist/{chunk-APTAITXZ.js.map → chunk-KKL3RYFQ.js.map} +0 -0
- /package/dist/{chunk-HR5SONJC.js.map → chunk-SK44IFZN.js.map} +0 -0
- /package/dist/{convert-to-pnpm-SVFDLXZS.js.map → convert-to-pnpm-OVMASATZ.js.map} +0 -0
- /package/dist/{ensure-site-O7G5ZJS7.js.map → ensure-site-3SOAWTZF.js.map} +0 -0
- /package/dist/{github-signals-QVW2LB7N.js.map → github-signals-TF3VSNIN.js.map} +0 -0
- /package/dist/{health-endpoint-IYR5VBUT.js.map → health-endpoint-JZGYCMTV.js.map} +0 -0
- /package/dist/{init-CU6PVZRG.js.map → init-7PTP4O2K.js.map} +0 -0
- /package/dist/{launch-JWXCTJRG.js.map → launch-W33FWWOZ.js.map} +0 -0
- /package/dist/{lighthouse-airtable-J5TLASJC.js.map → lighthouse-airtable-ZXNMDEPE.js.map} +0 -0
- /package/dist/{onboard-6UQE5QIO.js.map → onboard-PX36YDZA.js.map} +0 -0
- /package/dist/{orchestrate-ZDH24Z6Y.js.map → orchestrate-NYRYEKQM.js.map} +0 -0
- /package/dist/{preflight-BNTMWTPG.js.map → preflight-JCQFKB6M.js.map} +0 -0
- /package/dist/{self-updating-64FNRQB5.js.map → self-updating-2YSVNMPP.js.map} +0 -0
- /package/dist/{selftest-7DPNGL6R.js.map → selftest-OO2WDSDM.js.map} +0 -0
- /package/dist/{smoke-suite-TWILWDSF.js.map → smoke-suite-CSP23NZM.js.map} +0 -0
- /package/dist/{svelte-codemods-RVDTTXFD.js.map → svelte-codemods-V54KOBWU.js.map} +0 -0
- /package/dist/{sync-configs-BUUD6L5Q.js.map → sync-configs-UBCJRASZ.js.map} +0 -0
- /package/dist/{upgrade-HHKWYJRN.js.map → upgrade-WR6ICPAG.js.map} +0 -0
- /package/dist/{websites-EH2ULELZ.js.map → websites-U6642XSE.js.map} +0 -0
- /package/dist/{write-audits-to-airtable-LZDYTNX5.js.map → write-audits-to-airtable-22T6D733.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/audits/deps.ts","../src/audits/deps-outdated.ts","../src/audits/lint.ts","../src/github/gh-rest.ts","../src/audits/security.ts","../src/audits/lighthouse.ts","../src/audits/util/site-config.ts","../src/util/free-port.ts","../src/audits/a11y.ts","../src/audits/domain.ts","../src/audits/route-discovery.ts","../src/audits/browser.ts","../src/audits/netlify-deploy.ts","../src/audits/function-health.ts","../src/audits/smoke.ts","../src/audits/form-e2e.ts","../src/audits/index.ts"],"sourcesContent":["import { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport type { AuditResult } from \"../types.js\";\nimport { siteLabel } from \"../util/site.js\";\nimport { baselineVersions } from \"../configs/baseline-versions.js\";\nimport type { AuditContext } from \"./util/inject.js\";\nimport { defaultSpawn } from \"./util/spawn.js\";\nimport { scanOutdated, type OutdatedCounts } from \"./deps-outdated.js\";\n\nexport type Drift = \"same\" | \"patch\" | \"minor\" | \"major\" | \"newer\";\n\nexport type DepsDriftEntry = {\n pkg: string;\n baseline: string;\n actual: string;\n drift: Drift;\n};\n\n/** The deps audit reports TWO signals:\n * - `entries`: declared-range drift vs the canonical baseline (what the\n * package.json *asks for*, caret-stripped) — the long-standing signal.\n * - `outdated`: real installed-version drift vs the registry's latest, from\n * the committed lockfile (null when it can't be determined). Added so the\n * \"Deps Drifted\" dashboard number stops being the only — and misleading —\n * deps signal. */\nexport type DepsDetails = {\n entries: DepsDriftEntry[];\n outdated: OutdatedCounts | null;\n};\n\nfunction stripCaret(range: string): string {\n return range.replace(/^[\\^~]/, \"\");\n}\n\n/** A spec we can drift-compare against a semver baseline: a plain version or\n * caret/tilde range like \"5.55.10\", \"^5.55.10\", \"~5.0.0\". Excludes \"*\",\n * \"latest\", \"workspace:*\", \"npm:\"-aliases, and git/URL/file specs — those used\n * to parse to NaN and produce bogus drift, so they're skipped instead. */\nfunction isComparableRange(spec: string): boolean {\n return /^[\\^~]?\\d/.test(spec.trim());\n}\n\nfunction parseSemver(v: string): [number, number, number] {\n const cleaned = stripCaret(v).split(\"-\")[0] ?? \"0.0.0\";\n const parts = cleaned.split(\".\").map((n) => Number.parseInt(n, 10));\n return [parts[0] ?? 0, parts[1] ?? 0, parts[2] ?? 0];\n}\n\nfunction compareSemver(actual: string, baseline: string): Drift {\n const [aMajor, aMinor, aPatch] = parseSemver(actual);\n const [bMajor, bMinor, bPatch] = parseSemver(baseline);\n if (aMajor > bMajor) return \"newer\";\n if (aMajor < bMajor) return \"major\";\n if (aMinor > bMinor) return \"newer\";\n if (aMinor < bMinor) return \"minor\";\n if (aPatch > bPatch) return \"newer\";\n if (aPatch < bPatch) return \"patch\";\n return \"same\";\n}\n\nexport async function depsAudit(ctx: AuditContext): Promise<AuditResult> {\n const pkgPath = join(ctx.site.path, \"package.json\");\n let pkgRaw: string;\n try {\n pkgRaw = await readFile(pkgPath, \"utf-8\");\n } catch (err) {\n return {\n audit: \"deps\",\n site: siteLabel(ctx.site),\n status: \"skip\",\n summary: `no package.json at ${pkgPath}`,\n details: { error: String(err) },\n };\n }\n\n let pkg: { dependencies?: Record<string, string>; devDependencies?: Record<string, string> };\n try {\n pkg = JSON.parse(pkgRaw) as {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n };\n } catch (err) {\n return {\n audit: \"deps\",\n site: siteLabel(ctx.site),\n status: \"fail\",\n summary: `package.json is not valid JSON: ${(err as Error).message}`,\n details: { error: String(err) },\n };\n }\n const installed: Record<string, string> = {\n ...(pkg.dependencies ?? {}),\n ...(pkg.devDependencies ?? {}),\n };\n\n const entries: DepsDriftEntry[] = [];\n for (const [name, baseline] of Object.entries(baselineVersions)) {\n const actual = installed[name];\n if (!actual) continue;\n // Skip non-semver specs (\"*\", \"workspace:*\", \"npm:\"-aliases, git/URL): they\n // can't be drift-compared and used to yield NaN-driven bogus drift (LOW-3).\n if (!isComparableRange(actual)) continue;\n entries.push({\n pkg: name,\n baseline,\n actual,\n drift: compareSemver(actual, baseline),\n });\n }\n\n const anyMajor = entries.some((d) => d.drift === \"major\");\n const anyMinor = entries.some((d) => d.drift === \"minor\");\n const anyNewer = entries.some((d) => d.drift === \"newer\");\n\n // Status stays driven by the declared-range baseline drift (unchanged\n // behavior). The outdated count is an independent, informational signal.\n const status: AuditResult[\"status\"] = anyMajor ? \"fail\" : anyMinor || anyNewer ? \"warn\" : \"pass\";\n\n const driftSummary =\n status === \"pass\"\n ? `all ${entries.length} tracked deps in line with baseline`\n : status === \"warn\"\n ? `${entries.filter((d) => d.drift !== \"same\").length} of ${entries.length} tracked deps drifted`\n : `${entries.filter((d) => d.drift === \"major\").length} deps lagging by a major version`;\n\n const outdated = await scanOutdated(ctx.site.path, ctx.spawn ?? defaultSpawn);\n const summary = outdated\n ? `${driftSummary}; ${outdated.outdated} outdated install(s) (${outdated.major} major)`\n : driftSummary;\n\n return {\n audit: \"deps\",\n site: siteLabel(ctx.site),\n status,\n summary,\n details: { entries, outdated } satisfies DepsDetails,\n };\n}\n","import { stat } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport type { SpawnFn } from \"./util/spawn.js\";\n\n/** Real installed-version drift, distinct from the declared-range \"drift\" the\n * deps audit computes against the baseline: how many dependencies are behind\n * the registry's latest, per the committed lockfile. */\nexport type OutdatedCounts = { outdated: number; major: number };\n\nasync function exists(path: string): Promise<boolean> {\n try {\n await stat(path);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction majorOf(version: string): number {\n const head = version.replace(/^[\\^~]/, \"\").split(\".\")[0] ?? \"0\";\n const n = Number.parseInt(head, 10);\n return Number.isNaN(n) ? 0 : n;\n}\n\n/**\n * Count outdated dependencies for a site, using its committed lockfile as the\n * source of truth for \"what's installed/deployed\". Returns `null` (skip — the\n * caller degrades gracefully) when it can't determine this:\n * - no `pnpm-lock.yaml` (not a pnpm site, or never installed)\n * - the lockfile is stale vs package.json (`--frozen-lockfile` install fails)\n * - `pnpm outdated` output isn't parseable\n *\n * `pnpm outdated` exits non-zero precisely WHEN there are outdated packages, so\n * its exit code is ignored and only its JSON is parsed. `--frozen-lockfile`\n * never mutates the lockfile, so this stays read-only with respect to the repo.\n */\nexport async function scanOutdated(\n sitePath: string,\n spawn: SpawnFn,\n): Promise<OutdatedCounts | null> {\n if (!(await exists(join(sitePath, \"pnpm-lock.yaml\")))) return null;\n\n // Everything below is best-effort: a thrown spawn (timeout, `pnpm` not on\n // PATH, spawn error) must degrade to a skip (null), NOT bubble up and flip the\n // whole deps audit to a hard fail — the declared-range drift is independent of\n // pnpm and must still report. (Mirrors securityAudit's try/catch.)\n try {\n // Materialize node_modules from the lockfile, but only when it's missing —\n // an already-installed checkout skips the cold install. `--frozen-lockfile`\n // never rewrites the lockfile (read-only wrt the repo) and fails fast on a\n // lockfile out of sync with package.json → skip.\n if (!(await exists(join(sitePath, \"node_modules\")))) {\n const install = await spawn(\"pnpm\", [\"install\", \"--frozen-lockfile\"], {\n cwd: sitePath,\n timeoutMs: 180_000,\n });\n if (install.code !== 0) return null;\n }\n\n // `pnpm outdated` exits non-zero precisely WHEN there are outdated packages,\n // so its exit code is ignored and only its JSON is parsed.\n const res = await spawn(\"pnpm\", [\"outdated\", \"--json\"], {\n cwd: sitePath,\n timeoutMs: 60_000,\n });\n const parsed = JSON.parse(res.stdout || \"{}\") as Record<\n string,\n { current?: string; latest?: string }\n >;\n const entries = Object.values(parsed);\n return {\n outdated: entries.length,\n major: entries.filter((e) => e.current && e.latest && majorOf(e.latest) > majorOf(e.current))\n .length,\n };\n } catch {\n return null;\n }\n}\n","import { existsSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { ESLint } from \"eslint\";\nimport { check as prettierCheck, resolveConfig as prettierResolveConfig } from \"prettier\";\nimport { glob } from \"tinyglobby\";\nimport type { AuditResult } from \"../types.js\";\nimport { siteLabel } from \"../util/site.js\";\nimport type { AuditContext } from \"./util/inject.js\";\n\nconst TARGET_GLOBS = [\"**/*.{ts,js,svelte}\"];\nconst IGNORE = [\"node_modules/**\", \"dist/**\", \".svelte-kit/**\", \"build/**\", \".netlify/**\"];\n\nasync function listFiles(cwd: string): Promise<string[]> {\n return glob(TARGET_GLOBS, { cwd, ignore: IGNORE, absolute: false });\n}\n\nexport async function lintAudit(ctx: AuditContext): Promise<AuditResult> {\n const { site } = ctx;\n const configPath = join(site.path, \"eslint.config.js\");\n\n if (!existsSync(configPath)) {\n return {\n audit: \"lint\",\n site: siteLabel(site),\n status: \"skip\",\n summary: \"no eslint config at site root\",\n };\n }\n\n const eslint = new ESLint({\n cwd: site.path,\n overrideConfigFile: configPath,\n errorOnUnmatchedPattern: false,\n });\n\n const relFiles = await listFiles(site.path);\n\n // Pass relative paths to ESLint; its cwd is already site.path. Avoids\n // dereferencing symlinks on pnpm workspaces.\n const eslintResults = await eslint.lintFiles(relFiles);\n const eslintErrors = eslintResults.reduce((n, r) => n + r.errorCount, 0);\n const eslintWarnings = eslintResults.reduce((n, r) => n + r.warningCount, 0);\n\n const prettierUnformatted: string[] = [];\n for (const rel of relFiles) {\n const absForResolve = join(site.path, rel);\n const source = await readFile(absForResolve, \"utf-8\");\n const options = (await prettierResolveConfig(absForResolve)) ?? {};\n const ok = await prettierCheck(source, { ...options, filepath: absForResolve });\n if (!ok) prettierUnformatted.push(rel);\n }\n\n const status: AuditResult[\"status\"] =\n eslintErrors > 0 || prettierUnformatted.length > 0\n ? \"fail\"\n : eslintWarnings > 0\n ? \"warn\"\n : \"pass\";\n\n const summary =\n status === \"pass\"\n ? `lint clean across ${relFiles.length} files`\n : `${eslintErrors} eslint errors, ${eslintWarnings} warnings, ${prettierUnformatted.length} unformatted`;\n\n return {\n audit: \"lint\",\n site: siteLabel(site),\n status,\n summary,\n details: {\n eslintErrors,\n eslintWarnings,\n prettierUnformatted,\n files: relFiles.length,\n },\n };\n}\n","import { assertUrlSegment } from \"./gh.js\";\n\n/**\n * A `fetch`-based GitHub client covering the two operations the dashboard's\n * request-path Renovate trigger needs: resolve a repo's default branch and fire\n * a `workflow_dispatch`.\n *\n * Why not reuse `makeGitHub` (in gh.ts)? That client shells out to the `gh` CLI\n * (`spawn(\"gh\", …)`), which is the right tool inside GitHub Actions / a dev box\n * but is ABSENT in the Netlify Functions (AWS Lambda) runtime where this code\n * runs — so every `gh` call there throws `ENOENT`. The button's first live\n * dispatch surfaced exactly that as a 502. The Lambda runtime has a global\n * `fetch`, so we talk to the REST API directly.\n *\n * Mirrors the relevant subset of the `GitHub` interface so the `.mts` handler's\n * dispatch adapter is a drop-in swap. `fetch` is injectable for tests.\n */\n/** A subset of a GitHub Actions workflow run, mapped to camelCase. */\nexport type WorkflowRun = {\n id: number;\n status: string; // \"queued\" | \"in_progress\" | \"completed\" | \"requested\" | \"waiting\" | ...\n conclusion: string | null; // \"success\" | \"failure\" | \"cancelled\" | \"timed_out\" | ... | null\n createdAt: string; // ISO\n htmlUrl: string;\n};\n\n/** One GitHub Dependabot alert, mapped to the fields the security audit needs. */\nexport type DependabotAlert = {\n /** The vulnerable package name (`dependency.package.name`). */\n package: string;\n /** GitHub's raw severity vocabulary: \"low\" | \"medium\" | \"high\" | \"critical\". The audit layer\n * maps \"medium\" → the app's \"moderate\"; the rest pass through. */\n severity: string;\n /** Human advisory summary (`security_advisory.summary`). */\n summary: string;\n /** CVE id from the advisory's `cve_id`, as a 0- or 1-element array. Empty for GHSA-only\n * advisories (no CVE assigned) — those have no inline identifier here, but `url` still links\n * to the GHSA advisory page. (The GitHub `identifiers[]` array is intentionally not surfaced.) */\n cves: string[];\n /** Link to the alert (`html_url`), or null. */\n url: string | null;\n /** Dependency graph scope, or null when GitHub doesn't classify it. \"development\" marks a\n * build-time-only dependency (lower live-exploit surface for a static site). */\n scope: \"runtime\" | \"development\" | null;\n};\n\nexport type GitHubRest = {\n defaultBranch: (repo: string) => Promise<string>;\n /** Fire a `workflow_dispatch` for `<workflow>` (a filename like `renovate.yml`)\n * on `ref`. Needs the token's `actions:write` scope; a non-2xx (404 no such\n * workflow / 403 missing scope) surfaces as a thrown error carrying the status. */\n dispatchWorkflow: (repo: string, workflow: string, ref: string) => Promise<void>;\n /** List a workflow's runs, newest first, created on/after `opts.since` (ISO).\n * Used to re-find the run a prior `workflow_dispatch` started (dispatch returns\n * 204 with no id). Non-2xx surfaces as a thrown error carrying the status. */\n listWorkflowRuns: (\n repo: string,\n workflow: string,\n opts: { since: string; event?: string; perPage?: number },\n ) => Promise<WorkflowRun[]>;\n /** The name of the in-progress step of a run's in-progress job, or null if none\n * is currently running (between steps / completed). Used to show a coarse \"phase\"\n * in the refresh spinner. Non-2xx throws (callers treat it best-effort). */\n currentRunStep: (repo: string, runId: number) => Promise<string | null>;\n /** List a repo's Dependabot alerts, following pagination. `opts.state` defaults to \"open\".\n * Needs the token's Dependabot-alerts read permission (fine-grained PAT) or `repo`/\n * `security_events` (classic PAT); a non-2xx (403 missing scope / 404 alerts disabled)\n * throws carrying the status so the caller can fall back. */\n listDependabotAlerts: (\n repo: string,\n opts?: { state?: \"open\" | \"dismissed\" | \"fixed\" | \"auto_dismissed\" },\n ) => Promise<DependabotAlert[]>;\n};\n\nconst GITHUB_API = \"https://api.github.com\";\n\n/** Per-request timeout for the Dependabot fetch. It runs inside the nightly fleet sweep at\n * `--concurrency 1`, so a hung connection (half-open TCP / accept-but-no-response) would otherwise\n * stall the whole sweep — `fetch` has no default overall timeout. With this signal a hang rejects\n * with an AbortError, which the audit's try/catch converts to the pnpm-audit fallback. */\nconst DEPENDABOT_FETCH_TIMEOUT_MS = 15_000;\n\n/** Extract the `rel=\"next\"` URL from a GitHub `Link` header, or null when absent. GitHub's\n * Dependabot-alerts endpoint paginates ONLY by opaque `after` cursor exposed via this header —\n * there is no numeric `page` param (it is silently ignored) — so following rel=\"next\" is the only\n * correct way to advance pages. */\nfunction nextLink(link: string | null): string | null {\n if (!link) return null;\n for (const part of link.split(\",\")) {\n const m = part.match(/<([^>]+)>\\s*;\\s*rel=\"next\"/);\n if (m) return m[1] ?? null;\n }\n return null;\n}\n\n/** Split + validate an `owner/repo`, mirroring the shape check in gh.ts's methods. */\nfunction splitRepo(repo: string): { owner: string; name: string } {\n const [owner, name, ...rest] = repo.split(\"/\");\n if (!owner || !name || rest.length > 0) {\n throw new Error(`expected \"owner/repo\", got ${JSON.stringify(repo)}`);\n }\n return { owner, name };\n}\n\n/** Best-effort response body for an error message; capped so a huge body can't bloat logs. */\nasync function bodyText(res: Response): Promise<string> {\n try {\n return (await res.text()).slice(0, 300);\n } catch {\n return \"<no body>\";\n }\n}\n\n/** Map one raw Dependabot-alert object to {@link DependabotAlert}, or null if it carries no\n * usable package name (fail-soft — a malformed alert is dropped rather than propagated). */\nfunction mapDependabotAlert(raw: Record<string, unknown>): DependabotAlert | null {\n const dependency = (raw[\"dependency\"] ?? {}) as Record<string, unknown>;\n const pkg = (dependency[\"package\"] ?? {}) as Record<string, unknown>;\n const packageName = typeof pkg[\"name\"] === \"string\" ? (pkg[\"name\"] as string) : null;\n if (!packageName) return null;\n\n const adv = (raw[\"security_advisory\"] ?? {}) as Record<string, unknown>;\n const cveId = typeof adv[\"cve_id\"] === \"string\" ? (adv[\"cve_id\"] as string) : null;\n const rawScope = dependency[\"scope\"];\n return {\n package: packageName,\n severity: typeof adv[\"severity\"] === \"string\" ? (adv[\"severity\"] as string) : \"\",\n summary: typeof adv[\"summary\"] === \"string\" ? (adv[\"summary\"] as string) : \"\",\n cves: cveId ? [cveId] : [],\n url: typeof raw[\"html_url\"] === \"string\" ? (raw[\"html_url\"] as string) : null,\n scope: rawScope === \"runtime\" || rawScope === \"development\" ? rawScope : null,\n };\n}\n\nexport function makeGitHubRest(deps: { token: string; fetch?: typeof fetch }): GitHubRest {\n const doFetch = deps.fetch ?? fetch;\n // GitHub requires a User-Agent; the rest are the documented JSON-API headers.\n const baseHeaders: Record<string, string> = {\n authorization: `Bearer ${deps.token}`,\n accept: \"application/vnd.github+json\",\n \"x-github-api-version\": \"2022-11-28\",\n \"user-agent\": \"reddoor-maintenance-dashboard\",\n };\n\n return {\n async defaultBranch(repo) {\n const { owner, name } = splitRepo(repo);\n assertUrlSegment(\"path\", owner);\n assertUrlSegment(\"path\", name);\n const res = await doFetch(`${GITHUB_API}/repos/${owner}/${name}`, { headers: baseHeaders });\n if (!res.ok) {\n throw new Error(\n `GitHub GET repos/${owner}/${name} failed (${res.status}): ${await bodyText(res)}`,\n );\n }\n let body: { default_branch?: string };\n try {\n body = (await res.json()) as { default_branch?: string };\n } catch {\n throw new Error(`GitHub repos/${owner}/${name}: 200 with a non-JSON body`);\n }\n if (!body.default_branch) {\n throw new Error(`GitHub repos/${owner}/${name}: response had no default_branch`);\n }\n return body.default_branch;\n },\n\n async dispatchWorkflow(repo, workflow, ref) {\n const { owner, name } = splitRepo(repo);\n // Every segment interpolates into the API path — guard them all (defense in\n // depth), matching gh.ts's dispatchWorkflow. `ref` is repo-sourced.\n assertUrlSegment(\"path\", owner);\n assertUrlSegment(\"path\", name);\n assertUrlSegment(\"path\", workflow);\n assertUrlSegment(\"branch\", ref);\n const res = await doFetch(\n `${GITHUB_API}/repos/${owner}/${name}/actions/workflows/${workflow}/dispatches`,\n {\n method: \"POST\",\n headers: { ...baseHeaders, \"content-type\": \"application/json\" },\n body: JSON.stringify({ ref }),\n },\n );\n // 204 No Content on success.\n if (!res.ok) {\n throw new Error(\n `GitHub workflow_dispatch ${owner}/${name}/${workflow} failed (${res.status}): ${await bodyText(res)}`,\n );\n }\n },\n\n async listWorkflowRuns(repo, workflow, opts) {\n const { owner, name } = splitRepo(repo);\n assertUrlSegment(\"path\", owner);\n assertUrlSegment(\"path\", name);\n assertUrlSegment(\"path\", workflow);\n const qs = new URLSearchParams({\n created: `>=${opts.since}`,\n per_page: String(opts.perPage ?? 1),\n });\n if (opts.event) qs.set(\"event\", opts.event);\n const res = await doFetch(\n `${GITHUB_API}/repos/${owner}/${name}/actions/workflows/${workflow}/runs?${qs.toString()}`,\n { headers: baseHeaders },\n );\n if (!res.ok) {\n throw new Error(\n `GitHub GET runs ${owner}/${name}/${workflow} failed (${res.status}): ${await bodyText(res)}`,\n );\n }\n let body: { workflow_runs?: Array<Record<string, unknown>> };\n try {\n body = (await res.json()) as { workflow_runs?: Array<Record<string, unknown>> };\n } catch {\n throw new Error(`GitHub runs ${owner}/${name}/${workflow}: 200 with a non-JSON body`);\n }\n return (\n (body.workflow_runs ?? [])\n .map((r) => ({\n id: Number(r.id),\n status: String(r.status ?? \"\"),\n conclusion: (r.conclusion as string | null) ?? null,\n createdAt: String(r.created_at ?? \"\"),\n htmlUrl: String(r.html_url ?? \"\"),\n }))\n // Fail-soft like the other fields: a record with a missing/garbage id\n // (Number(...) → NaN) is dropped rather than propagated.\n .filter((r) => Number.isFinite(r.id))\n );\n },\n\n async currentRunStep(repo, runId) {\n const { owner, name } = splitRepo(repo);\n assertUrlSegment(\"path\", owner);\n assertUrlSegment(\"path\", name);\n if (!Number.isInteger(runId) || runId < 0) {\n throw new Error(`currentRunStep: expected a non-negative integer runId, got ${runId}`);\n }\n const res = await doFetch(`${GITHUB_API}/repos/${owner}/${name}/actions/runs/${runId}/jobs`, {\n headers: baseHeaders,\n });\n if (!res.ok) {\n throw new Error(\n `GitHub GET run ${owner}/${name}/${runId} jobs failed (${res.status}): ${await bodyText(res)}`,\n );\n }\n let body: {\n jobs?: Array<{ status?: string; steps?: Array<{ name?: string; status?: string }> }>;\n };\n try {\n body = (await res.json()) as typeof body;\n } catch {\n throw new Error(`GitHub run ${owner}/${name}/${runId} jobs: 200 with a non-JSON body`);\n }\n const jobs = body.jobs ?? [];\n // Prefer the in-progress job; fall back to the first job (single-job workflows).\n const job = jobs.find((j) => j.status === \"in_progress\") ?? jobs[0];\n const step = (job?.steps ?? []).find((s) => s.status === \"in_progress\");\n return step?.name ?? null;\n },\n\n async listDependabotAlerts(repo, opts) {\n const { owner, name } = splitRepo(repo);\n assertUrlSegment(\"path\", owner);\n assertUrlSegment(\"path\", name);\n const state = opts?.state ?? \"open\";\n const out: DependabotAlert[] = [];\n // Follow the Link rel=\"next\" cursor (NOT a numeric `page` param — that is silently ignored\n // and would re-fetch page 1 forever, duplicating counts). The iteration cap is a runaway\n // backstop. Each request carries an abort timeout so a hung connection rejects (→ the\n // caller's try/catch → pnpm fallback) instead of stalling the whole sequential fleet sweep.\n let url: string | null =\n `${GITHUB_API}/repos/${owner}/${name}/dependabot/alerts?` +\n new URLSearchParams({ state, per_page: \"100\" }).toString();\n for (let i = 0; i < 100 && url; i++) {\n const res = await doFetch(url, {\n headers: baseHeaders,\n signal: AbortSignal.timeout(DEPENDABOT_FETCH_TIMEOUT_MS),\n });\n if (!res.ok) {\n throw new Error(\n `GitHub GET dependabot/alerts ${owner}/${name} failed (${res.status}): ${await bodyText(res)}`,\n );\n }\n let body: unknown;\n try {\n body = await res.json();\n } catch {\n throw new Error(`GitHub dependabot/alerts ${owner}/${name}: 200 with a non-JSON body`);\n }\n // The alerts endpoint returns a bare array; anything else means we're done.\n if (!Array.isArray(body)) break;\n for (const raw of body as Array<Record<string, unknown>>) {\n const mapped = mapDependabotAlert(raw);\n if (mapped) out.push(mapped);\n }\n url = nextLink(res.headers.get(\"link\"));\n }\n return out;\n },\n };\n}\n","import type { AuditResult } from \"../types.js\";\nimport { siteLabel } from \"../util/site.js\";\nimport { defaultSpawn, type SpawnResult } from \"./util/spawn.js\";\nimport type { AuditContext } from \"./util/inject.js\";\nimport { makeGitHubRest, type DependabotAlert } from \"../github/gh-rest.js\";\nimport { readGitHubConfig } from \"../github/config.js\";\n\ntype Severity = \"low\" | \"moderate\" | \"high\" | \"critical\";\n\ntype Counts = { low: number; moderate: number; high: number; critical: number };\n\ntype AdvisoryEntry = {\n module: string;\n severity: Severity;\n title: string;\n cves?: string[];\n url?: string;\n /** Dependency graph scope from Dependabot (\"runtime\" | \"development\"); absent for the\n * lockfile `pnpm audit` fallback, which carries no per-package scope. Display-only. */\n scope?: \"runtime\" | \"development\";\n};\n\n// pnpm audit output (npm-compat with extra advisories map keyed by ID).\ntype PnpmAuditJson = {\n metadata?: { vulnerabilities?: Partial<Counts> };\n advisories?: Record<\n string,\n {\n id?: number;\n title?: string;\n module_name?: string;\n severity?: string;\n cves?: string[];\n url?: string;\n }\n >;\n};\n\n// npm v7+ shape (vulnerabilities keyed by package name).\ntype NpmAuditJson = {\n metadata?: { vulnerabilities?: Partial<Counts> };\n vulnerabilities?: Record<\n string,\n {\n name?: string;\n severity?: string;\n via?: unknown;\n url?: string;\n }\n >;\n};\n\nfunction classify(v: Counts) {\n if (v.critical > 0 || v.high > 0) return \"fail\" as const;\n if (v.moderate > 0 || v.low > 0) return \"warn\" as const;\n return \"pass\" as const;\n}\n\nfunction normalizeSeverity(s: unknown): Severity {\n if (s === \"low\" || s === \"moderate\" || s === \"high\" || s === \"critical\") return s;\n // npm/pnpm sometimes emit \"info\" for informational advisories. Map down\n // rather than defaulting to \"moderate\" (which would inflate severity).\n return \"low\";\n}\n\nfunction extractAdvisoriesFromPnpm(parsed: PnpmAuditJson): AdvisoryEntry[] {\n const out: AdvisoryEntry[] = [];\n for (const a of Object.values(parsed.advisories ?? {})) {\n if (!a) continue;\n out.push({\n module: a.module_name ?? \"unknown\",\n severity: normalizeSeverity(a.severity),\n title: a.title ?? \"(no title)\",\n ...(a.cves ? { cves: a.cves } : {}),\n ...(a.url ? { url: a.url } : {}),\n });\n }\n return out;\n}\n\n/** Walk an npm v7+ `via` chain to find the root entry whose `via` array\n * contains a real advisory object (rather than another package name string).\n * Returns the package name at the root and the advisory detail. */\nfunction resolveNpmAdvisoryRoot(\n startName: string,\n vulnerabilities: NonNullable<NpmAuditJson[\"vulnerabilities\"]>,\n): { rootName: string; detail?: { title?: string; url?: string } } {\n const seen = new Set<string>();\n let current = startName;\n while (!seen.has(current)) {\n seen.add(current);\n const entry = vulnerabilities[current];\n if (!entry || !Array.isArray(entry.via)) return { rootName: current };\n\n const detailed = entry.via.find(\n (e): e is { title?: string; url?: string } => typeof e === \"object\" && e !== null,\n );\n if (detailed) return { rootName: current, detail: detailed };\n\n const next = entry.via.find((e): e is string => typeof e === \"string\");\n if (!next || next === current) return { rootName: current };\n current = next;\n }\n return { rootName: current };\n}\n\nfunction extractAdvisoriesFromNpm(parsed: NpmAuditJson): AdvisoryEntry[] {\n const vulnerabilities = parsed.vulnerabilities ?? {};\n const roots = new Map<string, AdvisoryEntry>();\n\n for (const [name, v] of Object.entries(vulnerabilities)) {\n if (!v) continue;\n const { rootName, detail } = resolveNpmAdvisoryRoot(name, vulnerabilities);\n if (roots.has(rootName)) continue; // already surfaced via another transitive entry\n\n const rootEntry = vulnerabilities[rootName];\n const severity = normalizeSeverity(rootEntry?.severity ?? v.severity);\n const title = detail?.title ?? rootName;\n const url = detail?.url;\n\n roots.set(rootName, {\n module: rootEntry?.name ?? rootName,\n severity,\n title,\n ...(url ? { url } : {}),\n });\n }\n\n return [...roots.values()];\n}\n\ntype ToolResult =\n | { kind: \"missing\" }\n | { kind: \"error\"; reason: string }\n | { kind: \"ok\"; parsed: PnpmAuditJson & NpmAuditJson };\n\nasync function runAuditTool(\n spawn: (cmd: string, args: readonly string[], opts?: { cwd?: string }) => Promise<SpawnResult>,\n cmd: string,\n args: readonly string[],\n cwd: string,\n): Promise<ToolResult> {\n let raw: SpawnResult;\n try {\n raw = await spawn(cmd, args, { cwd });\n } catch (err) {\n const e = err as NodeJS.ErrnoException;\n if (e.code === \"ENOENT\" || /ENOENT/.test(String(err))) return { kind: \"missing\" };\n return { kind: \"error\", reason: `spawn failed: ${String(err).slice(0, 200)}` };\n }\n\n // 0 = clean, 1 = vulns found. Anything else is a real error.\n if (raw.code !== 0 && raw.code !== 1) {\n return {\n kind: \"error\",\n reason: `exit ${raw.code}${raw.stderr ? `: ${raw.stderr.slice(0, 150)}` : \"\"}`,\n };\n }\n\n let parsed: PnpmAuditJson & NpmAuditJson;\n try {\n parsed = JSON.parse(raw.stdout || \"{}\") as PnpmAuditJson & NpmAuditJson;\n } catch (err) {\n return { kind: \"error\", reason: `unparseable JSON: ${String(err).slice(0, 100)}` };\n }\n\n // pnpm error envelope: { error: { code, message } }. npm sometimes emits\n // a top-level error too. Either means the audit didn't actually run.\n const errEnvelope = (parsed as unknown as { error?: { code?: string } }).error;\n if (errEnvelope && typeof errEnvelope === \"object\") {\n return { kind: \"error\", reason: errEnvelope.code ?? \"error envelope returned\" };\n }\n\n // Without metadata.vulnerabilities there are no counts to report and we\n // can't trust the result. An empty `{}` is just as suspect as a missing\n // key — counts default to 0 and we'd silently report \"pass\". Treat both\n // as a tool failure so the caller can fall through to the other audit.\n const vulnsMeta = parsed.metadata?.vulnerabilities;\n if (!vulnsMeta || Object.keys(vulnsMeta).length === 0) {\n return { kind: \"error\", reason: \"no metadata.vulnerabilities in output\" };\n }\n\n return { kind: \"ok\", parsed };\n}\n\n/** The Dependabot fetch the security audit needs, injectable for tests. The real default is\n * built from GITHUB_TOKEN; absent token (or a site with no gitRepo) → pnpm/npm audit fallback. */\nexport type DependabotDeps = {\n listAlerts: (repo: string) => Promise<DependabotAlert[]>;\n};\n\nfunction defaultDependabotDeps(): DependabotDeps | null {\n const cfg = readGitHubConfig();\n if (!cfg) return null;\n const gh = makeGitHubRest({ token: cfg.token });\n return { listAlerts: (repo) => gh.listDependabotAlerts(repo, { state: \"open\" }) };\n}\n\n/** Map GitHub's severity vocabulary onto the app's. \"medium\" → \"moderate\"; an unrecognized\n * value maps DOWN to \"low\" rather than inflating (mirrors `normalizeSeverity`). */\nfunction ghSeverityToApp(s: string): Severity {\n if (s === \"critical\" || s === \"high\" || s === \"low\") return s;\n if (s === \"medium\" || s === \"moderate\") return \"moderate\";\n return \"low\";\n}\n\n/** Build a security AuditResult from GitHub Dependabot alerts, or null if the fetch failed so\n * the caller falls back to `pnpm audit`. ALL open alerts count toward the severity tallies —\n * the cockpit's auto-patching (amber) vs Renovate-exhausted (red) bands decide urgency, so the\n * prod/dev scope is carried on each advisory for display only, not used to weight the counts. */\nasync function dependabotAudit(\n deps: DependabotDeps,\n repo: string,\n label: string,\n): Promise<AuditResult | null> {\n let alerts: DependabotAlert[];\n try {\n alerts = await deps.listAlerts(repo);\n } catch (e) {\n // Loud, greppable degradation marker: the caller silently falls back to the\n // weaker lockfile `pnpm audit`, so a systematic token/permission regression\n // would otherwise be invisible across the whole fleet.\n console.error(\n `[security] ${label}: dependabot API failed — degraded to pnpm audit: ` +\n `${e instanceof Error ? e.message : String(e)}`,\n );\n return null;\n }\n\n const counts: Counts = { low: 0, moderate: 0, high: 0, critical: 0 };\n const advisories: AdvisoryEntry[] = [];\n for (const a of alerts) {\n const severity = ghSeverityToApp(a.severity);\n counts[severity] += 1;\n advisories.push({\n module: a.package,\n severity,\n title: a.summary || \"(no title)\",\n ...(a.cves.length > 0 ? { cves: a.cves } : {}),\n ...(a.url ? { url: a.url } : {}),\n ...(a.scope ? { scope: a.scope } : {}),\n });\n }\n\n const status = classify(counts);\n const total = counts.low + counts.moderate + counts.high + counts.critical;\n const summary =\n status === \"pass\"\n ? \"Dependabot: 0 alerts\"\n : `Dependabot: ${total} alert(s) (${counts.critical}C/${counts.high}H/${counts.moderate}M/${counts.low}L)`;\n\n return { audit: \"security\", site: label, status, summary, details: { counts, advisories } };\n}\n\nexport async function securityAudit(ctx: AuditContext): Promise<AuditResult> {\n const spawn = ctx.spawn ?? defaultSpawn;\n const site = ctx.site;\n const label = siteLabel(site);\n\n // Prefer GitHub Dependabot alerts (ground truth: prod+dev, GitHub Advisory DB) for repo-backed\n // sites. The lockfile `pnpm audit` below stays the fallback for sites with no GitHub repo, no\n // token, or a transient API failure — a Dependabot hiccup must never fail an otherwise-fine site.\n if (site.gitRepo) {\n const dependabot = ctx.dependabotDeps ?? defaultDependabotDeps();\n if (dependabot) {\n const viaDependabot = await dependabotAudit(dependabot, site.gitRepo, label);\n if (viaDependabot) return viaDependabot;\n }\n }\n\n let used: \"pnpm audit\" | \"npm audit\" = \"pnpm audit\";\n let result = await runAuditTool(spawn, \"pnpm\", [\"audit\", \"--json\", \"--prod\"], site.path);\n\n // Fall through to npm if pnpm is missing OR pnpm couldn't actually\n // audit the project (e.g., no pnpm-lock.yaml). Previously we only fell\n // through on ENOENT, which meant npm-using sites silently reported \"pass\"\n // because pnpm returned an error envelope with no metadata.\n if (result.kind !== \"ok\") {\n const pnpmReason = result.kind === \"missing\" ? \"not installed\" : result.reason;\n const npmResult = await runAuditTool(\n spawn,\n \"npm\",\n [\"audit\", \"--json\", \"--omit=dev\"],\n site.path,\n );\n if (npmResult.kind === \"ok\") {\n result = npmResult;\n used = \"npm audit\";\n } else {\n const npmReason = npmResult.kind === \"missing\" ? \"not installed\" : npmResult.reason;\n return {\n audit: \"security\",\n site: label,\n status: \"skip\",\n summary: `cannot run audit — pnpm: ${pnpmReason}; npm: ${npmReason}`,\n };\n }\n }\n\n const parsed = result.parsed;\n\n const counts: Counts = {\n low: parsed.metadata?.vulnerabilities?.low ?? 0,\n moderate: parsed.metadata?.vulnerabilities?.moderate ?? 0,\n high: parsed.metadata?.vulnerabilities?.high ?? 0,\n critical: parsed.metadata?.vulnerabilities?.critical ?? 0,\n };\n\n const advisories =\n used === \"pnpm audit\" ? extractAdvisoriesFromPnpm(parsed) : extractAdvisoriesFromNpm(parsed);\n\n const status = classify(counts);\n const total = counts.low + counts.moderate + counts.high + counts.critical;\n const summary =\n status === \"pass\"\n ? `${used}: 0 vulnerabilities`\n : `${used}: ${total} vulnerabilities (${counts.critical}C/${counts.high}H/${counts.moderate}M/${counts.low}L)`;\n\n return {\n audit: \"security\",\n site: label,\n status,\n summary,\n details: { counts, advisories },\n };\n}\n","import { readFile, writeFile, mkdtemp, rm, readdir } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport type { AuditResult, Site } from \"../types.js\";\nimport { siteLabel } from \"../util/site.js\";\nimport { lighthouseConfig } from \"../configs/lighthouse.js\";\nimport { defaultSpawn } from \"./util/spawn.js\";\nimport type { SpawnFn, SpawnResult } from \"./util/spawn.js\";\nimport type { AuditContext } from \"./util/inject.js\";\nimport { readSiteConfig } from \"./util/site-config.js\";\nimport { findFreePort, withFreePort } from \"../util/free-port.js\";\n\ntype ManifestEntry = {\n url: string;\n summary: Record<string, number>;\n htmlPath?: string;\n jsonPath?: string;\n};\n\ntype AssertionResult = {\n name: string;\n actual: number;\n expected: number;\n operator: string;\n passed: boolean;\n level: \"warn\" | \"error\";\n auditProperty?: string;\n auditId?: string;\n};\n\ntype NormalizedLhciResult = {\n summary: Record<string, number>;\n assertionsFailed: number;\n assertions: Array<{ category: string; level: \"warn\" | \"error\"; message: string }>;\n};\n\nasync function readJsonMaybe<T>(path: string): Promise<T | null> {\n try {\n const raw = await readFile(path, \"utf-8\");\n return JSON.parse(raw) as T;\n } catch {\n return null;\n }\n}\n\ntype LhrFile = {\n requestedUrl: string;\n finalUrl?: string;\n categories: Record<string, { score: number | null }>;\n};\n\n/**\n * Build manifest-equivalent entries by scanning the `.lighthouseci/` dir\n * for `lhr-*.json` files written by `lhci collect`. We used to read\n * `manifest.json` directly, but lhci 0.15+ no longer writes it — the\n * audit would silently return \"no manifest written\" against a perfectly\n * healthy run. Reproduced on caltex 2026-05-28 (0.10.5 dogfood).\n */\nasync function readLhrEntries(resultsDir: string): Promise<ManifestEntry[]> {\n const files = await readdir(resultsDir).catch(() => [] as string[]);\n const entries: ManifestEntry[] = [];\n for (const f of files) {\n if (!f.startsWith(\"lhr-\") || !f.endsWith(\".json\")) continue;\n const lhr = await readJsonMaybe<LhrFile>(join(resultsDir, f));\n if (!lhr || !lhr.categories) continue;\n const summary: Record<string, number> = {};\n for (const [k, v] of Object.entries(lhr.categories)) {\n if (typeof v?.score === \"number\") summary[k] = v.score;\n }\n entries.push({ url: lhr.requestedUrl, summary });\n }\n return entries;\n}\n\nfunction averageSummaries(entries: ManifestEntry[]): Record<string, number> {\n if (entries.length === 0) return {};\n const sums: Record<string, number> = {};\n const counts: Record<string, number> = {};\n for (const e of entries) {\n for (const [k, v] of Object.entries(e.summary ?? {})) {\n if (typeof v !== \"number\") continue;\n sums[k] = (sums[k] ?? 0) + v;\n counts[k] = (counts[k] ?? 0) + 1;\n }\n }\n const out: Record<string, number> = {};\n for (const k of Object.keys(sums)) {\n const total = sums[k] ?? 0;\n const count = counts[k] ?? 1;\n out[k] = total / count;\n }\n return out;\n}\n\nfunction categoryFromAssertion(a: AssertionResult): string {\n // `name` looks like \"categories:accessibility\" or \"audits:uses-http2\".\n const colonIdx = a.name.indexOf(\":\");\n return colonIdx >= 0 ? a.name.slice(colonIdx + 1) : a.name;\n}\n\nfunction messageForAssertion(a: AssertionResult): string {\n // `a.actual` is parsed from external lhci/Lighthouse JSON; a malformed or\n // missing value (not a number) would make `.toFixed` throw and crash the whole\n // audit. Guard it and fall back to a readable string instead.\n const actual = typeof a.actual === \"number\" ? a.actual.toFixed(2) : \"n/a\";\n return `${a.name} ${a.operator} ${a.expected} (actual: ${actual})`;\n}\n\n/** Shared tail: scan `.lighthouseci/` for lhr-*.json + assertion-results.json and\n * build the AuditResult. Identical for the checkout and deployed paths. */\nasync function parseLhciResults(\n resultsDir: string,\n label: string,\n raw: SpawnResult,\n): Promise<AuditResult> {\n const manifest = await readLhrEntries(resultsDir);\n\n if (manifest.length === 0) {\n return {\n audit: \"lighthouse\",\n site: label,\n status: \"fail\",\n summary: `lighthouse: no lhr-*.json written (exit ${raw.code})${\n raw.stderr ? ` — ${raw.stderr.slice(0, 200)}` : \"\"\n }`,\n };\n }\n\n const assertionResults =\n (await readJsonMaybe<AssertionResult[]>(join(resultsDir, \"assertion-results.json\"))) ?? [];\n\n const failed = assertionResults.filter((a) => !a.passed);\n const assertions = failed.map((a) => ({\n category: categoryFromAssertion(a),\n level: a.level,\n message: messageForAssertion(a),\n }));\n\n const anyError = assertions.some((a) => a.level === \"error\");\n const anyWarn = assertions.some((a) => a.level === \"warn\");\n const status: AuditResult[\"status\"] = anyError ? \"fail\" : anyWarn ? \"warn\" : \"pass\";\n\n const normalized: NormalizedLhciResult = {\n summary: averageSummaries(manifest),\n assertionsFailed: failed.length,\n assertions,\n };\n\n const summary =\n status === \"pass\"\n ? \"lighthouse: all categories passing\"\n : `lighthouse: ${failed.length} assertion(s) failed`;\n\n return { audit: \"lighthouse\", site: label, status, summary, details: normalized };\n}\n\n/** Checkout mode (unchanged behavior): boot the site's vite dev server on a\n * pinned free port and audit the local fixtures/override URL. */\nasync function checkoutLighthouse(spawn: SpawnFn, site: Site, label: string): Promise<AuditResult> {\n const siteCfg = await readSiteConfig(site.path);\n // Allocate a free port + force vite to `--strictPort` so the spawned dev\n // server either binds the port we picked or fails loudly (caltex 2026-05-28\n // zombie-vite incident).\n const port = await findFreePort();\n const baseUrl = siteCfg.lighthouseUrl ?? lighthouseConfig.ci.collect.url[0];\n const resolvedConfig = {\n ...lighthouseConfig,\n ci: {\n ...lighthouseConfig.ci,\n collect: {\n ...lighthouseConfig.ci.collect,\n url: [withFreePort(baseUrl, port)],\n startServerCommand: `npm run vite:dev -- --port ${port} --strictPort`,\n },\n },\n };\n\n const configDir = await mkdtemp(join(tmpdir(), \"reddoor-lhci-\"));\n const configPath = join(configDir, \"lighthouserc.json\");\n await writeFile(configPath, JSON.stringify(resolvedConfig), \"utf-8\");\n\n const resultsDir = join(site.path, \".lighthouseci\");\n await rm(resultsDir, { recursive: true, force: true });\n\n let raw: SpawnResult;\n try {\n raw = await spawn(\"npx\", [\"--yes\", \"@lhci/cli\", \"autorun\", `--config=${configPath}`], {\n cwd: site.path,\n timeoutMs: 5 * 60_000,\n });\n } catch (err) {\n await rm(configDir, { recursive: true, force: true });\n const e = err as NodeJS.ErrnoException;\n if (e.code === \"ENOENT\" || /ENOENT/.test(String(err))) {\n return {\n audit: \"lighthouse\",\n site: label,\n status: \"skip\",\n summary: \"npx/@lhci/cli not available\",\n };\n }\n throw err;\n }\n await rm(configDir, { recursive: true, force: true });\n\n return parseLhciResults(resultsDir, label, raw);\n}\n\n/** Deployed mode: audit a production URL directly — no checkout, no dev server.\n * Runs in a throwaway tmp cwd; uploads to the filesystem so fleet runs never\n * push 200 public reports to temporary-public-storage. */\nasync function deployedLighthouse(\n spawn: SpawnFn,\n deployedUrl: string,\n label: string,\n): Promise<AuditResult> {\n const workDir = await mkdtemp(join(tmpdir(), \"reddoor-lh-deployed-\"));\n const resolvedConfig = {\n ci: {\n // Deliberately NOT spread from lighthouseConfig.ci.collect: deployed mode\n // must omit startServerCommand and the dev-server settings entirely.\n collect: {\n url: [deployedUrl],\n // 3 runs to damp Lighthouse's run-to-run variance; parseLhciResults\n // averages the lhr files. (Median is a tracked future refinement.)\n numberOfRuns: 3,\n // Use devtools (applied) throttling instead of the desktop preset's\n // default `simulate` (Lantern). Lantern estimates LCP from the\n // dependency graph and can't model an LCP element revealed by a\n // JS-load opacity fade (e.g. gallerysonder's GridImage): on a fast\n // observed load it finds no LCP node and throws NO_LCP, nulling the\n // perf score, which the cockpit then coerces to a misleading 0.\n // devtools reads the real LCP paint event from the throttled trace\n // instead. Trade-off: slightly noisier run-to-run, damped by the\n // numberOfRuns:3 average above.\n settings: { preset: \"desktop\", throttlingMethod: \"devtools\", skipAudits: [\"uses-http2\"] },\n },\n assert: lighthouseConfig.ci.assert,\n upload: { target: \"filesystem\", outputDir: join(workDir, \"lhci-report\") },\n },\n };\n\n const configPath = join(workDir, \"lighthouserc.json\");\n await writeFile(configPath, JSON.stringify(resolvedConfig), \"utf-8\");\n\n const resultsDir = join(workDir, \".lighthouseci\");\n\n let raw: SpawnResult;\n try {\n raw = await spawn(\"npx\", [\"--yes\", \"@lhci/cli\", \"autorun\", `--config=${configPath}`], {\n cwd: workDir,\n // 3 serial cold runs of a slow deployed site (lhci's own maxWaitForLoad\n // ~45-60s each) + first-use Chrome download can plausibly exceed 3 min →\n // SIGTERM → no lhr-*.json → spurious \"no scores\". Match the 5-min budget\n // the checkout path already gives (erp-industrials nightly flake,\n // morning-brief 2026-06-10 MEDIUM-F).\n timeoutMs: 5 * 60_000,\n });\n } catch (err) {\n await rm(workDir, { recursive: true, force: true });\n const e = err as NodeJS.ErrnoException;\n if (e.code === \"ENOENT\" || /ENOENT/.test(String(err))) {\n return {\n audit: \"lighthouse\",\n site: label,\n status: \"skip\",\n summary: \"npx/@lhci/cli not available\",\n };\n }\n throw err;\n }\n\n try {\n return await parseLhciResults(resultsDir, label, raw);\n } finally {\n await rm(workDir, { recursive: true, force: true });\n }\n}\n\nexport async function lighthouseAudit(ctx: AuditContext): Promise<AuditResult> {\n const spawn = ctx.spawn ?? defaultSpawn;\n const site = ctx.site;\n const label = siteLabel(site);\n\n return site.deployedUrl\n ? deployedLighthouse(spawn, site.deployedUrl, label)\n : checkoutLighthouse(spawn, site, label);\n}\n","import { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nexport type SiteConfig = {\n /** Override URL the lighthouse audit hits. Sites without the default\n * `/dev/a11y-fixtures` dev route set this to their homepage. */\n lighthouseUrl?: string;\n};\n\n/**\n * Read per-site overrides from `package.json#reddoor`. Returns `{}` on any\n * failure (missing file, malformed JSON, missing key, wrong type) so every\n * caller can safely fall back to its built-in default. Never throws.\n */\nexport async function readSiteConfig(sitePath: string): Promise<SiteConfig> {\n let raw: string;\n try {\n raw = await readFile(join(sitePath, \"package.json\"), \"utf-8\");\n } catch {\n return {};\n }\n let pkg: unknown;\n try {\n pkg = JSON.parse(raw);\n } catch {\n return {};\n }\n if (!pkg || typeof pkg !== \"object\") return {};\n const cfg = (pkg as { reddoor?: unknown }).reddoor;\n if (!cfg || typeof cfg !== \"object\") return {};\n\n const out: SiteConfig = {};\n const url = (cfg as { lighthouseUrl?: unknown }).lighthouseUrl;\n if (typeof url === \"string\" && url.length > 0) {\n out.lighthouseUrl = url;\n }\n return out;\n}\n","import { createServer } from \"node:net\";\n\n/**\n * Bind an ephemeral TCP port, capture it, release it, and return it. Used\n * by the lighthouse and a11y audits to pick a port the audit's own dev\n * server will then bind via `--strictPort`.\n *\n * Why: vite's default behavior on a busy port is to bump to the next free\n * one (5173 → 5174 → …). When zombie vite processes (or any squatter) are\n * already on 5173, the audit's spawned vite lands on a higher port, but\n * the audit tooling (lhci, playwright) still probes 5173 — hits the\n * zombie — gets stale 404s — fails with \"no manifest written\" / \"no\n * results written (exit 1)\". Reproduced on caltex 2026-05-28 with 10\n * orphaned vite processes accumulated across this repo, the reports repo,\n * and caltex itself. Allocating a free port up front + `--strictPort`\n * makes the audit immune to port collisions.\n *\n * TOCTOU note: the small window between close() and the spawned vite\n * binding is theoretically racy, but in practice we run one audit at a\n * time and the OS keeps the port free for re-use. If vite still fails to\n * bind under `--strictPort`, the audit fails loudly — that's the correct\n * outcome (vs. silently auditing the wrong server).\n */\nexport async function findFreePort(): Promise<number> {\n return new Promise((resolve, reject) => {\n const server = createServer();\n server.unref();\n server.on(\"error\", reject);\n server.listen(0, \"127.0.0.1\", () => {\n const addr = server.address();\n if (typeof addr === \"object\" && addr) {\n const port = addr.port;\n server.close(() => resolve(port));\n } else {\n server.close();\n reject(new Error(\"findFreePort: could not determine assigned port from socket\"));\n }\n });\n });\n}\n\n/**\n * Swap the port (and force `localhost` host) on a URL so it points at the\n * audit's freshly-allocated dev server. Preserves the path + any query.\n * Used to rewrite the lighthouse `url` so lhci probes the correct port.\n */\nexport function withFreePort(url: string, port: number): string {\n const u = new URL(url);\n u.hostname = \"localhost\";\n u.port = String(port);\n return u.toString();\n}\n","import { readFile, writeFile, mkdtemp, rm } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport type { AuditResult } from \"../types.js\";\nimport { siteLabel } from \"../util/site.js\";\nimport { a11yRoutes, smokeRoutes } from \"../configs/playwright-a11y.js\";\nimport { defaultSpawn } from \"./util/spawn.js\";\nimport type { AuditContext } from \"./util/inject.js\";\nimport { findFreePort } from \"../util/free-port.js\";\n\ntype Impact = \"minor\" | \"moderate\" | \"serious\" | \"critical\";\n\ntype AxeViolation = {\n id: string;\n impact: Impact;\n route: string;\n help?: string;\n helpUrl?: string;\n nodes?: Array<{ html?: string; target?: string[] }>;\n};\n\ntype NormalizedA11y = {\n totalViolations: number;\n byImpact: Partial<Record<Impact, number>>;\n violations: AxeViolation[];\n};\n\nconst RESULTS_REL = \".reddoor-a11y/results.json\";\n\nasync function readJsonMaybe<T>(path: string): Promise<T | null> {\n try {\n const raw = await readFile(path, \"utf-8\");\n return JSON.parse(raw) as T;\n } catch {\n return null;\n }\n}\n\n// The audit-controlled playwright config. We synthesize it (rather than\n// rely on the site's playwright.config.ts) so we can pin the dev server\n// port + force `--strictPort` — same fix as the lighthouse audit, same\n// reason (zombie vite processes squatting on 5173 would otherwise eat\n// the audit's request and return stale 404s).\nfunction buildPlaywrightConfig(port: number, sitePath: string): string {\n return `import { defineConfig } from \"@playwright/test\";\n\nexport default defineConfig({\n testDir: \".\",\n testMatch: /.*\\\\.spec\\\\.ts$/,\n fullyParallel: true,\n forbidOnly: !!process.env.CI,\n retries: process.env.CI ? 2 : 0,\n reporter: process.env.CI ? \"github\" : \"list\",\n use: {\n baseURL: \"http://localhost:${port}\",\n trace: \"on-first-retry\",\n },\n webServer: {\n // --strictPort: refuse to bump to a different port if ours is taken,\n // so the audit fails loudly instead of probing a zombie.\n // reuseExistingServer:false: never reuse — we control the lifecycle.\n // cwd: playwright's default webServer.cwd is the config file's\n // directory. Our config lives in /tmp so without this override,\n // \"npm run vite:dev\" tries to read /tmp/.../package.json and\n // ENOENTs before vite ever starts. Caltex 2026-05-28 (0.10.5).\n command: \"npm run vite:dev -- --port ${port} --strictPort\",\n url: \"http://localhost:${port}/dev/a11y-fixtures\",\n cwd: ${JSON.stringify(sitePath)},\n reuseExistingServer: false,\n timeout: 120_000,\n },\n});\n`;\n}\n\n// The spec the audit writes runs all configured routes through axe in a single\n// test (so worker isolation doesn't fragment the collected violations) and\n// writes the structured result to <cwd>/.reddoor-a11y/results.json before\n// asserting. That way, the audit can read real axe details even when the\n// expect(...).toEqual([]) assertion fails.\nfunction buildSpec(): string {\n return `import { test, expect } from \"@playwright/test\";\nimport AxeBuilder from \"@axe-core/playwright\";\nimport { mkdir, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\n\nconst pages = ${JSON.stringify(a11yRoutes)};\nconst smokePages = ${JSON.stringify(smokeRoutes)};\nconst OUTPUT = process.env.REDDOOR_A11Y_OUTPUT;\n\n// Playwright's default per-test timeout is 30s. We loop through every\n// configured route in a single test, so the budget needs to scale.\ntest.setTimeout(5 * 60_000);\n\ntest(\"a11y + hydration across configured routes\", async ({ page }) => {\n const violations = [];\n\n // Capture uncaught client-side exceptions across every route we visit. A page\n // that builds + SSRs cleanly can still throw on hydrate and blank itself\n // (data-dynamiq: a Svelte 4->5 run() referenced a $state declared after it) --\n // axe never sees that, so we listen for it directly and tag the route in scope.\n let currentRoute = \"\";\n page.on(\"pageerror\", (err) => {\n violations.push({\n id: \"client-error\",\n impact: \"critical\",\n route: currentRoute,\n help: String(err && err.message ? err.message : err),\n });\n });\n\n for (const { path, name } of pages) {\n currentRoute = name;\n await page.goto(path);\n // Snap CSS transitions/animations to their resting state before axe runs.\n // AnimateIn-style fixtures transition opacity 0->1; sampling mid-transition\n // makes axe compute color-contrast against semi-transparent text, yielding a\n // flaky \"serious\" color-contrast violation (~1/3 of runs on /dev/animate-in).\n // Disabling transitions/animations forces the final, rendered state\n // deterministically -- which is also what users (and prefers-reduced-motion\n // users) actually see, so it's the correct thing to assert.\n await page.addStyleTag({\n content: \"*,*::before,*::after{transition:none!important;animation:none!important;}\",\n });\n const results = await new AxeBuilder({ page })\n .withTags([\"wcag2a\",\"wcag2aa\",\"wcag21a\",\"wcag21aa\",\"wcag22aa\"])\n .analyze();\n for (const v of results.violations) {\n violations.push({\n id: v.id,\n impact: v.impact ?? \"moderate\",\n route: name,\n help: v.help,\n helpUrl: v.helpUrl,\n nodes: v.nodes.map((n) => ({ html: n.html, target: n.target })),\n });\n }\n }\n\n // Hydration smoke check: load real routes (the homepage) and fail on any\n // uncaught client-side error. No axe here -- real routes carry pre-existing\n // a11y debt we don't gate on; we only assert they don't crash on hydrate.\n // HTTP/SSR errors don't fire 'pageerror', so a data-less CI homepage that\n // renders empty-but-valid won't false-fail -- only a real client crash does.\n for (const { path, name } of smokePages) {\n currentRoute = name;\n await page.goto(path);\n // Let hydration + first effects run so a TDZ/ReferenceError surfaces.\n await page.waitForTimeout(2000);\n }\n\n const byImpact = {};\n for (const v of violations) {\n byImpact[v.impact] = (byImpact[v.impact] ?? 0) + 1;\n }\n if (OUTPUT) {\n await mkdir(dirname(OUTPUT), { recursive: true });\n await writeFile(\n OUTPUT,\n JSON.stringify({ totalViolations: violations.length, byImpact, violations }, null, 2),\n );\n }\n expect(violations).toEqual([]);\n});\n`;\n}\n\nexport async function a11yAudit(ctx: AuditContext): Promise<AuditResult> {\n const spawn = ctx.spawn ?? defaultSpawn;\n const site = ctx.site;\n const label = siteLabel(site);\n\n // specDir lives INSIDE site.path (not /tmp) so the spec's\n // `import AxeBuilder from \"@axe-core/playwright\"` resolves via Node's\n // walk-up — the site's node_modules is the nearest one. A spec written\n // to /tmp ENOENTs at module resolution before any test runs. Caltex\n // 2026-05-28 (0.10.6 dogfood), third layer of the same class as the\n // webServer.cwd bug.\n const specDir = await mkdtemp(join(site.path, \".reddoor-a11y-spec-\"));\n // Everything past mkdtemp is wrapped so the transient specDir is removed on\n // EVERY catchable exit — success, skip-return, or any throw (a failed\n // writeFile/findFreePort used to orphan it). A timeout-SIGKILL of the parent\n // can't be caught here; `.reddoor-a11y-spec-*/` is fleet-gitignored as the\n // backstop for that. (2026-06-10 MEDIUM-D; recurred from 06-05 M3.)\n try {\n const specPath = join(specDir, \"a11y.spec.ts\");\n await writeFile(specPath, buildSpec(), \"utf-8\");\n\n const port = await findFreePort();\n const configPath = join(specDir, \"playwright.config.ts\");\n await writeFile(configPath, buildPlaywrightConfig(port, site.path), \"utf-8\");\n\n const resultsPath = join(site.path, RESULTS_REL);\n // Clear stale artifacts so a failed spawn never reports old data.\n await rm(join(site.path, \".reddoor-a11y\"), { recursive: true, force: true });\n\n let raw;\n try {\n raw = await spawn(\n \"npx\",\n [\"--yes\", \"playwright\", \"test\", `--config=${configPath}`, \"--reporter=line\", specPath],\n {\n cwd: site.path,\n env: { ...process.env, REDDOOR_A11Y_OUTPUT: resultsPath },\n // playwright on a cold tree downloads Chrome, boots the site's dev\n // server, and runs axe over every configured route. The shared 30 s\n // default in runAudits is fine for deps/lint/security but starves\n // playwright (mirrors the lighthouse fix shipped earlier).\n timeoutMs: 5 * 60_000,\n },\n );\n } catch (err) {\n const e = err as NodeJS.ErrnoException;\n if (e.code === \"ENOENT\" || /ENOENT/.test(String(err))) {\n return {\n audit: \"a11y\",\n site: label,\n status: \"skip\",\n summary: \"npx/playwright not available\",\n };\n }\n throw err;\n }\n\n const artifact = await readJsonMaybe<NormalizedA11y>(resultsPath);\n\n if (!artifact) {\n return {\n audit: \"a11y\",\n site: label,\n status: \"fail\",\n summary: `a11y: no results written (exit ${raw.code})${\n raw.stderr ? ` — ${raw.stderr.slice(0, 200)}` : \"\"\n }`,\n };\n }\n\n const hasSerious =\n (artifact.byImpact.serious ?? 0) > 0 || (artifact.byImpact.critical ?? 0) > 0;\n const hasAny = artifact.totalViolations > 0;\n\n const status: AuditResult[\"status\"] = hasSerious ? \"fail\" : hasAny ? \"warn\" : \"pass\";\n const summary =\n status === \"pass\"\n ? `a11y: 0 violations across ${a11yRoutes.length} routes (+${smokeRoutes.length} hydration smoke)`\n : `a11y: ${artifact.totalViolations} violations`;\n\n return {\n audit: \"a11y\",\n site: label,\n status,\n summary,\n details: artifact,\n };\n } finally {\n await rm(specDir, { recursive: true, force: true });\n }\n}\n","import { promises as dnsPromises } from \"node:dns\";\nimport tls from \"node:tls\";\nimport type { AuditResult } from \"../types.js\";\nimport type { AuditContext } from \"./util/inject.js\";\nimport { siteLabel } from \"../util/site.js\";\n\n/** Result of probing a site's domain: did DNS resolve, and how many days until the TLS cert\n * expires (null when unresolved or no usable cert). The auto-tick verdict is recomputed from\n * the persisted fields — this is just the raw signal. */\nexport type DomainCheck = {\n resolved: boolean;\n certDaysRemaining: number | null;\n};\n\n/** Injected IO so the check is unit-testable without real DNS/TLS. `lookup` throws when the host\n * doesn't resolve; `certValidTo` returns the cert's notAfter date, or null when there's none. */\nexport type DomainDeps = {\n lookup: (host: string) => Promise<void>;\n certValidTo: (host: string) => Promise<Date | null>;\n now: Date;\n};\n\nconst MS_PER_DAY = 24 * 60 * 60 * 1000;\n\n/**\n * Probe one URL's domain: resolve DNS, then read the TLS certificate expiry. PURE given its deps.\n * Any failure degrades safely — an unresolvable host or a missing/unreadable cert yields\n * `certDaysRemaining: null` (which the auto-tick rule treats as \"not provable\", never a pass).\n */\nexport async function checkDomain(url: string, deps: DomainDeps): Promise<DomainCheck> {\n let host: string;\n try {\n host = new URL(url).hostname;\n } catch {\n return { resolved: false, certDaysRemaining: null };\n }\n try {\n await deps.lookup(host);\n } catch {\n return { resolved: false, certDaysRemaining: null };\n }\n let validTo: Date | null;\n try {\n validTo = await deps.certValidTo(host);\n } catch {\n validTo = null;\n }\n if (!validTo || Number.isNaN(validTo.getTime()))\n return { resolved: true, certDaysRemaining: null };\n return {\n resolved: true,\n certDaysRemaining: Math.floor((validTo.getTime() - deps.now.getTime()) / MS_PER_DAY),\n };\n}\n\n/** Real DNS + TLS. `certValidTo` opens a TLS socket (SNI = host), reads the peer cert's\n * `valid_to`, and closes immediately — no HTTP request. */\nexport function defaultDomainDeps(now: Date): DomainDeps {\n return {\n lookup: async (host) => {\n await dnsPromises.lookup(host);\n },\n certValidTo: (host) =>\n new Promise<Date | null>((resolvePromise) => {\n // `rejectUnauthorized: true` is what makes this check HONEST and the green box truthful:\n // the secureConnect callback only fires on a trusted, host-matching (SNI), unexpired\n // chain — an expired / self-signed / untrusted-CA / SAN-mismatched cert fires \"error\"\n // → null → fail. The whole \"valid cert\" claim depends on this. NEVER set it false.\n // `socket.authorized` is asserted belt-and-suspenders before trusting `valid_to`.\n const socket = tls.connect(\n { host, port: 443, servername: host, timeout: 10_000, rejectUnauthorized: true },\n () => {\n const cert = socket.authorized ? socket.getPeerCertificate() : null;\n socket.end();\n const validTo = cert && cert.valid_to ? new Date(cert.valid_to) : null;\n resolvePromise(validTo);\n },\n );\n socket.on(\"error\", () => resolvePromise(null));\n socket.on(\"timeout\", () => {\n socket.destroy();\n resolvePromise(null);\n });\n }),\n now,\n };\n}\n\n/**\n * Audit a site's domain (DNS + TLS) against its deployed URL. Checkout-free — needs only\n * `site.deployedUrl`. Skips a site with no deployed URL. Writes `certDaysRemaining` + a checked-at\n * timestamp via the Airtable layer; the auto-tick rule decides pass/fail from those.\n */\nexport async function domainAudit(ctx: AuditContext): Promise<AuditResult> {\n const { site } = ctx;\n const label = siteLabel(site);\n if (!site.deployedUrl) {\n return { audit: \"domain\", site: label, status: \"skip\", summary: \"no deployed URL\" };\n }\n const now = ctx.now ?? new Date();\n const deps = ctx.domainDeps ?? defaultDomainDeps(now);\n const check = await checkDomain(site.deployedUrl, deps);\n const checkedAt = now.toISOString();\n const status: AuditResult[\"status\"] =\n check.resolved && check.certDaysRemaining !== null && check.certDaysRemaining > 14\n ? \"pass\"\n : \"warn\";\n const summary = !check.resolved\n ? \"did not resolve\"\n : check.certDaysRemaining === null\n ? \"resolved, no usable TLS cert\"\n : `resolved, cert ${check.certDaysRemaining}d remaining`;\n return {\n audit: \"domain\",\n site: label,\n status,\n summary,\n details: { resolved: check.resolved, certDaysRemaining: check.certDaysRemaining, checkedAt },\n };\n}\n","/**\n * Route discovery for the deployed-URL browser audit. Pulls the site's sitemap, then samples a\n * REPRESENTATIVE set of paths — bucketed by path family (first segment) and sampled round-robin —\n * so every page *type* is covered, including the dynamic CMS-generated templates (Prismic\n * `[uid]`/`[slug]` detail pages: blog posts, projects, portfolio items) where broken\n * images / overflowing galleries / dead links hide. Taking the first N sitemap entries would skew\n * to top-level static pages and miss them. Pure functions + one fetch-injected entry point.\n */\n\nexport type DiscoverDeps = {\n /** Fetch a URL, returning its text body, or null on any non-2xx / network error. */\n fetchText: (url: string) => Promise<string | null>;\n};\n\nexport type DiscoveredRoutes = {\n /** Absolute URLs (rebuilt on the deployed origin), always including the homepage. */\n routes: string[];\n source: \"sitemap\" | \"homepage-links\" | \"root-only\";\n /** Path-family → count, for the evidence note (\"/, /work ×4, /blog ×4\"). */\n familyCounts: Record<string, number>;\n};\n\nconst DEFAULT_CAP = 15;\n\n/** Extract `<loc>` URLs from sitemap XML. Tolerant of namespaces/whitespace; ignores junk. */\nexport function parseSitemapUrls(xml: string): string[] {\n const out: string[] = [];\n const re = /<loc>\\s*([^<\\s]+)\\s*<\\/loc>/gi;\n let m: RegExpExecArray | null;\n while ((m = re.exec(xml)) !== null) {\n const url = m[1];\n if (url) out.push(url.trim());\n }\n return out;\n}\n\n/** Same-origin `<a href>` paths from an HTML body (homepage fallback). Returns root-relative\n * pathnames; off-origin / anchor / mailto / tel links are dropped. */\nexport function parseHtmlLinks(html: string, baseUrl: string): string[] {\n const out = new Set<string>();\n const re = /<a\\b[^>]*\\bhref\\s*=\\s*[\"']([^\"']+)[\"']/gi;\n let m: RegExpExecArray | null;\n while ((m = re.exec(html)) !== null) {\n const href = m[1];\n if (!href || href.startsWith(\"#\") || /^(mailto:|tel:|javascript:)/i.test(href)) continue;\n try {\n const u = new URL(href, baseUrl);\n if (u.origin !== new URL(baseUrl).origin) continue;\n out.add(u.pathname);\n } catch {\n /* skip unparseable */\n }\n }\n return [...out];\n}\n\n/** First non-empty path segment (\"/\" → \"\", \"/work/x\" → \"work\"). The \"family\" we bucket by. */\nfunction family(pathname: string): string {\n return pathname.split(\"/\").filter(Boolean)[0] ?? \"\";\n}\n\n/**\n * Sample a representative set of PATHNAMES from a list of URLs/paths. Always includes \"/\". Buckets\n * the rest by path family and takes them round-robin (one per family per pass), so every family\n * is represented before any family gets a second page — guaranteeing CMS templates aren't skipped.\n * Caps the total. PURE.\n */\nexport function sampleRoutePaths(urlsOrPaths: string[], cap: number = DEFAULT_CAP): string[] {\n const seen = new Set<string>([\"/\"]);\n const buckets = new Map<string, string[]>();\n for (const raw of urlsOrPaths) {\n let pathname: string;\n try {\n pathname = raw.startsWith(\"/\")\n ? new URL(raw, \"https://x.invalid\").pathname\n : new URL(raw).pathname;\n } catch {\n continue;\n }\n if (pathname === \"/\") continue; // root already guaranteed\n if (seen.has(pathname)) continue;\n seen.add(pathname);\n const fam = family(pathname);\n const arr = buckets.get(fam) ?? [];\n arr.push(pathname);\n buckets.set(fam, arr);\n }\n const result = [\"/\"];\n const families = [...buckets.values()];\n let guard = 0;\n while (result.length < cap && families.some((f) => f.length > 0) && guard++ < 10_000) {\n for (const fam of families) {\n if (result.length >= cap) break;\n const next = fam.shift();\n if (next) result.push(next);\n }\n }\n return result;\n}\n\n/** Per-family counts of a sampled path list, for the evidence note. */\nexport function familyCountsOf(paths: string[]): Record<string, number> {\n const counts: Record<string, number> = {};\n for (const p of paths) {\n const key = p === \"/\" ? \"/\" : `/${family(p)}`;\n counts[key] = (counts[key] ?? 0) + 1;\n }\n return counts;\n}\n\n/**\n * Discover a representative route set for `deployedUrl`. Tries `<origin>/sitemap.xml` first\n * (family-sampled); falls back to the homepage's same-origin links; worst case the homepage only.\n * Returns absolute URLs rebuilt on the deployed origin.\n */\nexport async function discoverRoutes(\n deployedUrl: string,\n deps: DiscoverDeps,\n cap: number = DEFAULT_CAP,\n): Promise<DiscoveredRoutes> {\n const origin = new URL(deployedUrl).origin;\n const abs = (paths: string[]) => paths.map((p) => new URL(p, origin).href);\n\n const sitemapXml = await deps.fetchText(new URL(\"/sitemap.xml\", origin).href);\n if (sitemapXml) {\n const urls = parseSitemapUrls(sitemapXml);\n if (urls.length > 0) {\n const paths = sampleRoutePaths(urls, cap);\n return { routes: abs(paths), source: \"sitemap\", familyCounts: familyCountsOf(paths) };\n }\n }\n\n const homeHtml = await deps.fetchText(origin);\n if (homeHtml) {\n const links = parseHtmlLinks(homeHtml, origin);\n if (links.length > 0) {\n const paths = sampleRoutePaths(links, cap);\n return { routes: abs(paths), source: \"homepage-links\", familyCounts: familyCountsOf(paths) };\n }\n }\n\n return { routes: [new URL(\"/\", origin).href], source: \"root-only\", familyCounts: { \"/\": 1 } };\n}\n","import type { AuditResult } from \"../types.js\";\nimport type { AuditContext } from \"./util/inject.js\";\nimport { siteLabel } from \"../util/site.js\";\nimport {\n discoverRoutes,\n familyCountsOf,\n type DiscoverDeps,\n type DiscoveredRoutes,\n} from \"./route-discovery.js\";\n\n/** One route probed across desktop engines + mobile devices, plus the internal links found on it,\n * plus the chromium-derived reachability + SEO signals (captured on the page chromium already\n * opened — no extra navigation). */\nexport type RouteResult = {\n url: string;\n /** Per desktop engine (chromium/firefox/webkit): loaded with no JS error + a visible main landmark. */\n desktop: Array<{ engine: string; ok: boolean }>;\n /** Per mobile device: loaded with no JS error and no horizontal overflow. */\n mobile: Array<{ device: string; ok: boolean }>;\n /** Same-origin links discovered on the page (absolute URLs), for the Links check. */\n links: string[];\n /** HTTP status of the chromium navigation (2xx/3xx = reachable). null = the nav failed/threw. */\n status: number | null;\n /** The chromium `<title>` (trimmed by the reducer), or null when not captured. */\n title: string | null;\n /** The chromium `meta[name=\"description\"]` content, or null when absent/not captured. */\n metaDescription: string | null;\n};\n\nexport type LinkResult = { url: string; status: number | null };\n\n/** Injected browser IO. The real impl drives Playwright; tests pass a fake. */\nexport type BrowserRunner = {\n probe: (urls: string[]) => Promise<RouteResult[]>;\n checkLinks: (urls: string[]) => Promise<LinkResult[]>;\n close?: () => Promise<void>;\n};\n\nexport type BrowserSummary = {\n desktopOk: boolean;\n mobileOk: boolean;\n linksOk: boolean;\n /** Every sampled route returned a 2xx/3xx status (point-in-time uptime). */\n reachableOk: boolean;\n /** Every sampled route has a non-empty `<title>` ≤ 70 chars + a non-empty meta description, and\n * no two routes share a title. */\n titleMetaOk: boolean;\n brokenLinks: number;\n routesChecked: number;\n note: string;\n};\n\n/** A link status counts as broken when it didn't return a 2xx/3xx (null = unreachable). */\nfunction isBroken(status: number | null): boolean {\n return status === null || status >= 400;\n}\n\n/**\n * Reduce raw per-route observations to the three checklist verdicts. PURE.\n * - desktopOk: EVERY route loaded cleanly in EVERY desktop engine.\n * - mobileOk: EVERY route loaded cleanly (no overflow / error) on EVERY mobile device.\n * - linksOk: NO internal link is broken.\n * Empty observations (a probe that produced nothing) → not ok (fail-safe: prove, don't assume).\n */\nexport function summarizeBrowser(\n routes: RouteResult[],\n links: LinkResult[],\n familyCounts: Record<string, number>,\n): BrowserSummary {\n const desktopChecks = routes.flatMap((r) => r.desktop);\n const mobileChecks = routes.flatMap((r) => r.mobile);\n // Per-route completeness: EVERY route must carry observations AND every observation must be ok.\n // (Guarding only the flattened array would excuse a route that produced no observations at all —\n // a false green.) A route with an empty desktop[]/mobile[] (never rendered) → not ok.\n const desktopOk =\n routes.length > 0 && routes.every((r) => r.desktop.length > 0 && r.desktop.every((d) => d.ok));\n const mobileOk =\n routes.length > 0 && routes.every((r) => r.mobile.length > 0 && r.mobile.every((m) => m.ok));\n const brokenLinks = links.filter((l) => isBroken(l.status)).length;\n // linksOk requires links to have ACTUALLY been checked — zero links checked is \"not proven\",\n // never a pass (e.g. a JS-rendered page whose hrefs weren't in the DOM, or a chromium evaluate\n // that threw → []). Otherwise the box would assert \"all links resolve\" having checked nothing.\n const linksOk = links.length > 0 && brokenLinks === 0;\n\n // reachableOk: every sampled route returned 2xx/3xx. Empty observations → false (fail-safe).\n const reachableOk =\n routes.length > 0 &&\n routes.every((r) => r.status !== null && r.status >= 200 && r.status < 400);\n\n // titleMetaOk (chromium-only signals): every route has a non-empty title ≤ 70 chars + a non-empty\n // meta description, AND no two routes share a title. Empty observations → false (fail-safe).\n const trimmedTitles = routes.map((r) => (r.title ?? \"\").trim());\n const eachTitleMetaValid =\n routes.length > 0 &&\n routes.every((r, i) => {\n const t = trimmedTitles[i]!;\n const desc = (r.metaDescription ?? \"\").trim();\n return t.length > 0 && t.length <= 70 && desc.length > 0;\n });\n const noDuplicateTitles = new Set(trimmedTitles).size === trimmedTitles.length;\n const titleMetaOk = eachTitleMetaValid && noDuplicateTitles;\n\n const engines = [...new Set(desktopChecks.map((d) => d.engine))];\n const devices = [...new Set(mobileChecks.map((m) => m.device))];\n const families = Object.entries(familyCounts)\n .map(([f, n]) => (f === \"/\" ? \"/\" : `${f} ×${n}`))\n .join(\", \");\n const note =\n `${routes.length} routes (${families}); ` +\n `desktop ${engines.join(\"/\") || \"—\"}; mobile ${devices.join(\"/\") || \"—\"}; ` +\n `${links.length} links, ${brokenLinks} broken`;\n\n return {\n desktopOk,\n mobileOk,\n linksOk,\n reachableOk,\n titleMetaOk,\n brokenLinks,\n routesChecked: routes.length,\n note,\n };\n}\n\n/**\n * Deployed-URL browser audit: discovers a representative route set (incl. CMS templates), probes\n * each across desktop engines + mobile devices, and checks internal links — all against the LIVE\n * url (checkout-free). Skips a site with no deployed URL. Produces ONE AuditResult whose details\n * carry the three verdicts (Crossbrowser / Mobile / Links); the Airtable layer fans them out and\n * the auto-tick rule gates each on freshness.\n */\nexport async function browserAudit(ctx: AuditContext): Promise<AuditResult> {\n const { site } = ctx;\n const label = siteLabel(site);\n if (!site.deployedUrl) {\n return { audit: \"browser\", site: label, status: \"skip\", summary: \"no deployed URL\" };\n }\n const now = ctx.now ?? new Date();\n const discoverDeps = ctx.discoverDeps ?? defaultDiscoverDeps();\n const runner = ctx.browserRunner ?? (await defaultBrowserRunner());\n try {\n const discovered: DiscoveredRoutes = await discoverRoutes(site.deployedUrl, discoverDeps);\n const routeResults = await runner.probe(discovered.routes);\n const internalLinks = [...new Set(routeResults.flatMap((r) => r.links))];\n const linkResults = await runner.checkLinks(internalLinks);\n const summary = summarizeBrowser(\n routeResults,\n linkResults,\n discovered.familyCounts ?? familyCountsOf(discovered.routes),\n );\n const status: AuditResult[\"status\"] =\n summary.desktopOk && summary.mobileOk && summary.linksOk ? \"pass\" : \"warn\";\n return {\n audit: \"browser\",\n site: label,\n status,\n summary: summary.note,\n details: { ...summary, checkedAt: now.toISOString() },\n };\n } finally {\n await runner.close?.();\n }\n}\n\n/** Bound the plain fetch()es (route-discovery GET + link HEAD/GET) so a host that hangs\n * WITHOUT erroring can't stall the sequential fleet audit indefinitely. Playwright's\n * page.goto already has PAGE_TIMEOUT_MS; these fetches had no ceiling. On abort the existing\n * catch path treats it exactly like a network error (→ null), so a slow host degrades, never throws. */\nconst FETCH_TIMEOUT_MS = 10_000;\n\n/** Real route-discovery fetch: GET text, null on any non-2xx / error / timeout. */\nexport function defaultDiscoverDeps(): DiscoverDeps {\n return {\n fetchText: async (url) => {\n try {\n const res = await fetch(url, {\n redirect: \"follow\",\n signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),\n });\n if (!res.ok) return null;\n return await res.text();\n } catch {\n return null;\n }\n },\n };\n}\n\nconst DESKTOP_VIEWPORT = { width: 1366, height: 900 };\nconst PAGE_TIMEOUT_MS = 30_000;\n\n/**\n * Real Playwright runner. Launches chromium/firefox/webkit (desktop) + mobile-emulated chromium &\n * webkit, probes each route, and HEAD/GET-checks internal links. Every failure degrades to a\n * `false`/`null` (never throws past the audit), so a flaky run yields a non-pass (→ the box stays\n * manual) rather than a false green. Imported lazily so unit tests (which inject a fake runner)\n * never load Playwright.\n */\nexport async function defaultBrowserRunner(): Promise<BrowserRunner> {\n const { chromium, firefox, webkit, devices } = await import(\"@playwright/test\");\n const desktopEngines = [\n { engine: \"chromium\", type: chromium },\n { engine: \"firefox\", type: firefox },\n { engine: \"webkit\", type: webkit },\n ];\n const mobileTargets = [\n { device: \"Pixel 7\", descriptor: devices[\"Pixel 7\"] },\n { device: \"iPhone 14\", descriptor: devices[\"iPhone 14\"] },\n ];\n\n return {\n async probe(urls) {\n const results: RouteResult[] = [];\n const browsers = await Promise.all(desktopEngines.map((e) => e.type.launch()));\n const mobileBrowsers = await Promise.all(mobileTargets.map(() => chromium.launch()));\n try {\n for (const url of urls) {\n const desktop: RouteResult[\"desktop\"] = [];\n const linkSet = new Set<string>();\n let status: number | null = null;\n let title: string | null = null;\n let metaDescription: string | null = null;\n for (let i = 0; i < desktopEngines.length; i++) {\n const engine = desktopEngines[i]!.engine;\n const browser = browsers[i]!;\n const ctx = await browser.newContext({ viewport: DESKTOP_VIEWPORT });\n const page = await ctx.newPage();\n const errors: string[] = [];\n page.on(\"pageerror\", (e) => errors.push(String(e)));\n let ok = false;\n try {\n const resp = await page.goto(url, {\n waitUntil: \"domcontentloaded\",\n timeout: PAGE_TIMEOUT_MS,\n });\n const hasMain = await page\n .locator(\"main, [role=main]\")\n .first()\n .isVisible()\n .catch(() => false);\n ok = !!resp && resp.ok() && errors.length === 0 && hasMain;\n if (engine === \"chromium\") {\n status = resp ? resp.status() : null;\n title = ((await page.title().catch(() => \"\")) as string).trim() || null;\n metaDescription =\n (\n ((await page\n .evaluate(\n \"document.querySelector('meta[name=\\\"description\\\"]')?.getAttribute('content') || ''\",\n )\n .catch(() => \"\")) as string) || \"\"\n ).trim() || null;\n // Link discovery runs on chromium only (cost). Links coverage therefore depends on\n // chromium loading this route + the evaluate succeeding; if it yields nothing, the\n // Links verdict is \"not proven\" (links.length===0 ⇒ linksOk false), never a pass.\n // String-form evaluate so the browser-context code isn't type-checked against the\n // Node lib (no DOM globals in this project's tsconfig). Returns absolute hrefs.\n const hrefs = (await page\n .evaluate(\"Array.from(document.querySelectorAll('a[href]')).map((a) => a.href)\")\n .catch(() => [])) as string[];\n const origin = new URL(url).origin;\n for (const h of hrefs) {\n try {\n if (new URL(h).origin === origin) linkSet.add(new URL(h).href);\n } catch {\n /* skip */\n }\n }\n }\n } catch {\n ok = false;\n } finally {\n await ctx.close().catch(() => {});\n }\n desktop.push({ engine, ok });\n }\n\n const mobile: RouteResult[\"mobile\"] = [];\n for (let i = 0; i < mobileTargets.length; i++) {\n const { device, descriptor } = mobileTargets[i]!;\n const browser = mobileBrowsers[i]!;\n const ctx = await browser.newContext({ ...descriptor });\n const page = await ctx.newPage();\n const errors: string[] = [];\n page.on(\"pageerror\", (e) => errors.push(String(e)));\n let ok = false;\n try {\n const resp = await page.goto(url, {\n waitUntil: \"domcontentloaded\",\n timeout: PAGE_TIMEOUT_MS,\n });\n const overflow = (await page\n .evaluate(\"document.documentElement.scrollWidth > window.innerWidth + 2\")\n .catch(() => true)) as boolean;\n ok = !!resp && resp.ok() && errors.length === 0 && !overflow;\n } catch {\n ok = false;\n } finally {\n await ctx.close().catch(() => {});\n }\n mobile.push({ device, ok });\n }\n\n results.push({\n url,\n desktop,\n mobile,\n links: [...linkSet],\n status,\n title,\n metaDescription,\n });\n }\n } finally {\n await Promise.all([...browsers, ...mobileBrowsers].map((b) => b.close().catch(() => {})));\n }\n return results;\n },\n\n async checkLinks(urls) {\n const out: LinkResult[] = [];\n for (const url of urls) {\n let status: number | null;\n try {\n let res = await fetch(url, {\n method: \"HEAD\",\n redirect: \"follow\",\n signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),\n });\n // Some servers reject HEAD (405/501) — retry GET before declaring it broken.\n if (res.status === 405 || res.status === 501) {\n res = await fetch(url, {\n method: \"GET\",\n redirect: \"follow\",\n signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),\n });\n }\n status = res.status;\n } catch {\n status = null;\n }\n out.push({ url, status });\n }\n return out;\n },\n };\n}\n","import type { AuditResult } from \"../types.js\";\nimport type { AuditContext } from \"./util/inject.js\";\nimport { siteLabel } from \"../util/site.js\";\n\n/** Bound the deploy read so a half-open TCP can't stall the sequential fleet sweep\n * (parity with the Dependabot fetch). A timeout aborts into the same catch that\n * maps every read failure to `{ ok: false }` — i.e. \"couldn't read, keep prior status\". */\nconst NETLIFY_FETCH_TIMEOUT_MS = 15_000;\n\n/** Result of probing a site's latest PRODUCTION Netlify deploy. Every field is\n * nullable: a site with no production deploy yet degrades to all-nulls (a real\n * \"none\" verdict). A read FAILURE is NOT represented here — it surfaces as\n * `{ ok: false }` on the enclosing `NetlifyDeployFetch` so it can't be mistaken\n * for a verdict. See `NetlifyDeployFetch`.\n * - `state` is Netlify's raw deploy state (`ready`/`error`/`building`/…), lower-cased,\n * or null when the site has no production deploy.\n * - `deployedAt` is the deploy's publish/create time (ISO), or null.\n * - `logUrl` links to the deploy (its live URL or the Netlify admin/build-log page).\n * - `errorMessage` is Netlify's `error_message` for a failed build, or null. */\nexport type NetlifyDeployCheck = {\n state: string | null;\n deployedAt: string | null;\n logUrl: string | null;\n errorMessage: string | null;\n};\n\n/** Outcome of probing Netlify, distinguishing \"couldn't read\" from \"read OK\".\n * This distinction is load-bearing: `Deploy status` drives the cockpit's Broken\n * band (an ALARM), so a transient read failure must NOT be allowed to clear a\n * real `error` — unlike a degraded \"no deploy yet\", which is a real verdict.\n * - `{ ok: false }` — the API was unreachable/unreadable (network error, non-2xx,\n * malformed body). The caller persists nothing, leaving the prior status intact.\n * - `{ ok: true, deploy }` — the API answered. `deploy` is the latest production\n * deploy, or all-nulls when the site genuinely has no production deploy yet\n * (a real verdict, safe to persist). */\nexport type NetlifyDeployFetch = { ok: false } | { ok: true; deploy: NetlifyDeployCheck };\n\n/** Injected IO so the check is unit-testable without hitting the Netlify API.\n * `fetchLatestProductionDeploy` returns a `NetlifyDeployFetch` — `{ ok: false }`\n * when the call couldn't be read, else `{ ok: true, deploy }` with the latest\n * production deploy (or all-nulls for a site with none). `now` is the clock for\n * the checked-at stamp. */\nexport type NetlifyDeployDeps = {\n fetchLatestProductionDeploy: (siteId: string) => Promise<NetlifyDeployFetch>;\n now: Date;\n};\n\n/** The Netlify deploy states we treat as a successful production build. */\nconst READY_STATES: ReadonlySet<string> = new Set([\"ready\"]);\n/** States that mean the build actually failed — the \"needs attention\" case. */\nconst FAILED_STATES: ReadonlySet<string> = new Set([\"error\", \"failed\", \"rejected\"]);\n/** States that mean a build is still in flight — neutral, not yet a verdict. */\nconst IN_PROGRESS_STATES: ReadonlySet<string> = new Set([\n \"building\",\n \"enqueued\",\n \"new\",\n \"processing\",\n \"uploading\",\n \"preparing\",\n]);\n\nexport function isReadyState(state: string | null): boolean {\n return state !== null && READY_STATES.has(state);\n}\nexport function isFailedState(state: string | null): boolean {\n return state !== null && FAILED_STATES.has(state);\n}\nexport function isInProgressState(state: string | null): boolean {\n return state !== null && IN_PROGRESS_STATES.has(state);\n}\n\n/**\n * Probe one Netlify site's latest production deploy. PURE given its deps — the\n * real network/parse work lives in `defaultNetlifyDeployDeps`. Propagates the\n * read/no-read distinction: a deps throw is treated as `{ ok: false }` (couldn't\n * read), so the caller preserves the prior status rather than clearing it.\n */\nexport async function checkNetlifyDeploy(\n siteId: string,\n deps: NetlifyDeployDeps,\n): Promise<NetlifyDeployFetch> {\n return deps\n .fetchLatestProductionDeploy(siteId)\n .catch(() => ({ ok: false }) as NetlifyDeployFetch);\n}\n\n/** Coerce an untrusted value to a trimmed non-empty string, or null. */\nfunction str(raw: unknown): string | null {\n if (typeof raw !== \"string\") return null;\n const trimmed = raw.trim();\n return trimmed.length > 0 ? trimmed : null;\n}\n\n/**\n * Real Netlify API deps. Fetches the latest production deploy for `siteId` and\n * maps the raw JSON into a `NetlifyDeployFetch`. A read failure — network error,\n * non-2xx, malformed/unexpected body — resolves to `{ ok: false }` (the caller\n * preserves the prior status); an empty deploy list resolves to a real all-null\n * `{ ok: true }` verdict. NEVER throws: a fleet sweep must not red an unrelated\n * site because one site's Netlify call hiccuped.\n *\n * `fetchImpl` is injected (defaults to the global `fetch`) only so the default\n * deps themselves stay testable; production callers pass nothing.\n */\nexport function defaultNetlifyDeployDeps(\n token: string,\n now: Date,\n fetchImpl: typeof fetch = fetch,\n): NetlifyDeployDeps {\n return {\n now,\n fetchLatestProductionDeploy: async (siteId): Promise<NetlifyDeployFetch> => {\n // `production=true` + `per_page=1` asks Netlify for ONLY the newest\n // production deploy, so we read `[0]` without paging. siteId is the\n // Airtable-supplied site identity; encode it so it can't break the path.\n const url =\n `https://api.netlify.com/api/v1/sites/${encodeURIComponent(siteId)}/deploys` +\n `?per_page=1&production=true`;\n let res: Response;\n try {\n res = await fetchImpl(url, {\n headers: { Authorization: `Bearer ${token}` },\n signal: AbortSignal.timeout(NETLIFY_FETCH_TIMEOUT_MS),\n });\n } catch {\n return { ok: false }; // network error — couldn't read; preserve prior status\n }\n if (!res.ok) return { ok: false }; // non-2xx — couldn't read\n let body: unknown;\n try {\n body = await res.json();\n } catch {\n return { ok: false }; // malformed JSON — couldn't read\n }\n if (!Array.isArray(body)) return { ok: false }; // unexpected shape — couldn't read\n if (body.length === 0) {\n // Read OK; the site genuinely has no production deploy yet. An all-null\n // verdict is real (not a read failure), so it's safe to persist.\n return {\n ok: true,\n deploy: { state: null, deployedAt: null, logUrl: null, errorMessage: null },\n };\n }\n const d = body[0] as Record<string, unknown>;\n const state = str(d[\"state\"]);\n // Prefer the publish time; fall back to create time for an in-progress deploy.\n const deployedAt = str(d[\"published_at\"]) ?? str(d[\"created_at\"]);\n // Prefer the live deploy URL, then the Netlify admin page, then a raw log link.\n const logUrl = str(d[\"deploy_ssl_url\"]) ?? str(d[\"admin_url\"]) ?? str(d[\"deploy_url\"]);\n const errorMessage = str(d[\"error_message\"]);\n return {\n ok: true,\n deploy: {\n state: state ? state.toLowerCase() : null,\n deployedAt,\n logUrl,\n errorMessage,\n },\n };\n },\n };\n}\n\n/**\n * Audit a site's latest PRODUCTION Netlify deploy health. Checkout-free — needs\n * only the site's Netlify id. Degrades gracefully fleet-wide:\n * - no `site.netlifyId` → skip (\"no netlify id\"); the site simply isn't on Netlify\n * (or hasn't been wired up) so there's nothing to check.\n * - no `NETLIFY_PAT` in the env → skip (\"no NETLIFY_PAT\"); the whole audit is\n * unconfigured, which must not red every site.\n *\n * Status mapping: `ready` → pass; a failed build (`error`/`failed`/`rejected`) →\n * fail (the \"needs attention\" status — it lands the site in the cockpit's attention\n * tier, mirroring a sub-floor Lighthouse score); an in-flight build or any\n * unknown/unreadable state → warn (neutral, no verdict yet). `details` carries\n * `{ state, deployedAt, logUrl, checkedAt }` for the Airtable writer + dashboard.\n */\nexport async function netlifyDeployAudit(ctx: AuditContext): Promise<AuditResult> {\n const { site } = ctx;\n const label = siteLabel(site);\n if (!site.netlifyId) {\n return { audit: \"netlify-deploy\", site: label, status: \"skip\", summary: \"no netlify id\" };\n }\n const token = process.env.NETLIFY_PAT;\n if (!token) {\n return { audit: \"netlify-deploy\", site: label, status: \"skip\", summary: \"no NETLIFY_PAT\" };\n }\n\n const now = ctx.now ?? new Date();\n const deps = ctx.netlifyDeployDeps ?? defaultNetlifyDeployDeps(token, now);\n const fetched = await checkNetlifyDeploy(site.netlifyId, deps);\n\n // Couldn't read Netlify (network error / non-2xx / malformed). Return WITHOUT\n // details so `hasNetlifyDeployResult` is false and the Airtable writer skips the\n // write — leaving the prior `Deploy status` intact. A `Deploy status` of `error`\n // drives the cockpit's Broken band, and a transient API hiccup during the nightly\n // sweep must NEVER silently clear that alarm to \"all clear\" while prod is down.\n if (!fetched.ok) {\n return {\n audit: \"netlify-deploy\",\n site: label,\n status: \"warn\",\n summary: \"deploy status unavailable (Netlify API unreachable)\",\n };\n }\n const check = fetched.deploy;\n const checkedAt = now.toISOString();\n\n const status: AuditResult[\"status\"] = isReadyState(check.state)\n ? \"pass\"\n : isFailedState(check.state)\n ? \"fail\"\n : \"warn\";\n\n const summary =\n check.state === null\n ? \"no deploy found\"\n : isFailedState(check.state)\n ? `deploy ${check.state}${check.errorMessage ? ` — ${check.errorMessage}` : \"\"}`\n : `deploy ${check.state}`;\n\n return {\n audit: \"netlify-deploy\",\n site: label,\n status,\n summary,\n details: {\n state: check.state,\n deployedAt: check.deployedAt,\n logUrl: check.logUrl,\n checkedAt,\n },\n };\n}\n","import type { AuditResult } from \"../types.js\";\nimport type { AuditContext } from \"./util/inject.js\";\nimport { siteLabel } from \"../util/site.js\";\n\n/** The parts of the deployed `/health` body this audit reads. `ok` is the endpoint's self-rollup\n * (`functionRan && prismic !== \"error\"`); `prismic` is the server-side CMS probe status; `forms`\n * are booleans recorded for the dashboard only. A public endpoint can return anything, so every\n * field is validated/coerced by `parseHealthBody`. */\nexport type HealthBody = {\n ok: boolean;\n prismic: \"ok\" | \"error\" | \"skipped\" | null;\n forms: { ingestUrl: boolean; ingestToken: boolean; turnstile: boolean } | null;\n};\n\n/** Outcome of fetching `{deployedUrl}/health`, distinguishing \"no usable report\" (`present:false`\n * → self-skip, the writer preserves the prior verdict) from \"read a body\" (`present:true`\n * → a real pass/fail). `present:true` with a real `HealthBody` is a 200 JSON response (`ok`\n * drives pass/fail); the fetch layer also synthesizes an all-`ok:false` body for \"deployed but\n * erroring\" responses (a non-404 non-2xx, or a 200 that isn't valid JSON) so those fail loudly\n * instead of silently skipping. Mirrors `netlify-deploy`'s `NetlifyDeployFetch` read/no-read split. */\nexport type HealthFetch = { present: false } | { present: true; body: HealthBody };\n\n/** Injected IO so the audit is unit-testable without a network. `fetchHealth` returns a\n * `HealthFetch`; `now` is the clock for the checked-at stamp. */\nexport type FunctionHealthDeps = {\n fetchHealth: (deployedUrl: string) => Promise<HealthFetch>;\n now: Date;\n};\n\nconst HEALTH_TIMEOUT_MS = 10_000;\n\n/** A synthetic \"deployed but erroring\" body for responses that carry no real health data — a\n * non-404 non-2xx status, or a 200 whose body isn't valid JSON. `ok:false` drives a `fail`\n * verdict; the null fields just mean \"nothing more to report\" (not a real CMS/forms read). */\nconst ERRORING_BODY: HealthBody = { ok: false, prismic: null, forms: null };\n\n/** Coerce an untrusted `/health` JSON payload into a `HealthFetch`. PURE. A non-object, or a body\n * without a boolean `ok`, is `{present:false}` (not a usable report — the endpoint hasn't\n * adopted the health-check contract, distinct from a deployed-but-erroring response). An\n * unrecognized `prismic` or a missing/!object `forms` degrades that field to null but keeps the\n * body present. */\nexport function parseHealthBody(raw: unknown): HealthFetch {\n if (!raw || typeof raw !== \"object\") return { present: false };\n const o = raw as Record<string, unknown>;\n if (typeof o[\"ok\"] !== \"boolean\") return { present: false };\n const prismic =\n o[\"prismic\"] === \"ok\" || o[\"prismic\"] === \"error\" || o[\"prismic\"] === \"skipped\"\n ? (o[\"prismic\"] as \"ok\" | \"error\" | \"skipped\")\n : null;\n const f = o[\"forms\"];\n const forms =\n f && typeof f === \"object\"\n ? {\n ingestUrl: (f as Record<string, unknown>)[\"ingestUrl\"] === true,\n ingestToken: (f as Record<string, unknown>)[\"ingestToken\"] === true,\n turnstile: (f as Record<string, unknown>)[\"turnstile\"] === true,\n }\n : null;\n return { present: true, body: { ok: o[\"ok\"], prismic, forms } };\n}\n\n/** Real fetch deps. GETs `{deployedUrl}/health` with a 10s abort timeout. Maps the response\n * precisely so a _deployed-but-erroring_ function fails loudly while a _not-yet-adopted_\n * `/health` stays a self-skip (spec R2.1):\n * - unparseable deployed URL, network error/timeout, or HTTP 404 → `{present:false}` (not\n * adopted / unreachable — self-skip, writer preserves the prior verdict).\n * - any OTHER non-2xx (5xx, 403, …), or a 200 whose body isn't valid JSON → `{present:true,\n * body:ERRORING_BODY}` (deployed but erroring — a real `fail`).\n * - a 200 JSON body → `parseHealthBody` (usually a real pass/fail; an unrecognized shape still\n * degrades to `{present:false}`, i.e. not-yet-adopted).\n * NEVER throws, so one site's dead endpoint can't red an unrelated site in the fleet sweep.\n * `fetchImpl` is injected only so the default deps stay testable; production callers pass\n * nothing. */\nexport function defaultFunctionHealthDeps(\n now: Date,\n fetchImpl: typeof fetch = fetch,\n): FunctionHealthDeps {\n return {\n now,\n fetchHealth: async (deployedUrl): Promise<HealthFetch> => {\n let url: string;\n try {\n // Root `/health` — an absolute path replaces any path on the deployed URL.\n url = new URL(\"/health\", deployedUrl).toString();\n } catch {\n return { present: false }; // unparseable deployed URL — nothing to probe\n }\n let res: Response;\n try {\n res = await fetchImpl(url, { signal: AbortSignal.timeout(HEALTH_TIMEOUT_MS) });\n } catch {\n return { present: false }; // network error / timeout — unreachable, self-skip\n }\n if (res.status === 404) return { present: false }; // not adopted yet — self-skip\n if (!res.ok) return { present: true, body: ERRORING_BODY }; // deployed but erroring — fail\n let body: unknown;\n try {\n body = await res.json();\n } catch {\n return { present: true, body: ERRORING_BODY }; // 200 non-JSON — deployed but erroring, fail\n }\n return parseHealthBody(body);\n },\n };\n}\n\n/**\n * Audit a site's deployed `/health` function. Checkout-free — needs only `site.deployedUrl`. Skips\n * a site with no deployed URL. Status mapping (spec Phase 2, R2.1):\n * - no usable report (unreachable, timeout, or `/health` 404 — not yet adopted) → `skip` WITHOUT\n * details → the Airtable writer preserves the prior verdict (a site that hasn't adopted\n * `/health`, or a transient outage, stays \"never ran\"; Plan 4 maps that to unknown/amber, which\n * blocks).\n * - deployed but erroring — any other non-2xx, a 200 non-JSON body, or a 200 JSON body with\n * `ok:false` → `fail` (records details so the fail persists).\n * - a 200 JSON body with `ok:true` → `pass` (records details).\n * `details` carries `{ ok, prismic, forms, checkedAt }`; the Airtable layer derives the\n * `Function health` + `CMS Reachable` verdicts (CMS from `prismic === \"ok\"`) + the checked-at stamp.\n * It must NEVER write `Deploy status` — that stays the Netlify build state.\n */\nexport async function functionHealthAudit(ctx: AuditContext): Promise<AuditResult> {\n const { site } = ctx;\n const label = siteLabel(site);\n if (!site.deployedUrl) {\n return { audit: \"function-health\", site: label, status: \"skip\", summary: \"no deployed URL\" };\n }\n const now = ctx.now ?? new Date();\n const deps = ctx.functionHealthDeps ?? defaultFunctionHealthDeps(now);\n const fetched: HealthFetch = await deps\n .fetchHealth(site.deployedUrl)\n .catch(() => ({ present: false }) as HealthFetch);\n\n if (!fetched.present) {\n return {\n audit: \"function-health\",\n site: label,\n status: \"skip\",\n summary: \"health endpoint unreachable / not adopted\",\n };\n }\n const checkedAt = now.toISOString();\n const status: AuditResult[\"status\"] = fetched.body.ok ? \"pass\" : \"fail\";\n const summary = `health ${fetched.body.ok ? \"ok\" : \"not ok\"} (prismic ${fetched.body.prismic ?? \"?\"})`;\n return {\n audit: \"function-health\",\n site: label,\n status,\n summary,\n details: {\n ok: fetched.body.ok,\n prismic: fetched.body.prismic,\n forms: fetched.body.forms,\n checkedAt,\n },\n };\n}\n","import { access, readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport type { AuditResult } from \"../types.js\";\nimport type { AuditContext } from \"./util/inject.js\";\nimport { defaultSpawn } from \"./util/spawn.js\";\nimport { siteLabel } from \"../util/site.js\";\nimport { findFreePort } from \"../util/free-port.js\";\n\n/** Persisted smoke verdict: the site's own `test:smoke` suite passed or failed. */\nexport type SmokeDetails = { ok: \"pass\" | \"fail\"; checkedAt: string };\n\n// ESC built from a char code so the regex source carries no literal control\n// char (keeps `no-control-regex` quiet). Matches the SGR color codes Playwright emits.\nconst ANSI = new RegExp(`${String.fromCharCode(27)}\\\\[[0-9;]*m`, \"g\");\n\n/**\n * Distill the actionable failure out of a Playwright run. The list reporter writes\n * its failing-test list — \"N) [chromium] › file:line › title\" followed by the\n * Error/Expected/Received head — plus an \"N failed\" tally to STDOUT; STDERR only\n * carries dev-server/npm noise (e.g. `[WebServer] npm warn …`). So summarize stdout\n * first (which test, and why) and fall back to stderr only when stdout yielded\n * nothing useful (a crash before the reporter ran). Capped so a runaway report\n * can't bloat the CLI/Airtable summary.\n */\nexport function summarizeSmokeFailure(stdout: string, stderr: string): string {\n const lines = stdout\n .replace(ANSI, \"\")\n .split(\"\\n\")\n .map((l) => l.trim());\n const failing: string[] = [];\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n if (line === undefined) continue;\n // The list reporter numbers each failing test: \"1) [chromium] › file › title\".\n if (/^\\d+\\)\\s/.test(line)) {\n failing.push(line);\n // Grab the next 3 NON-BLANK lines — the Error:/Expected:/Received: head.\n // Skip blanks without spending the budget, and stop at the next failing block.\n let taken = 0;\n for (let j = i + 1; j < lines.length && taken < 3; j++) {\n const next = lines[j];\n if (!next) continue;\n if (/^\\d+\\)\\s/.test(next)) break;\n failing.push(next);\n taken++;\n }\n break;\n }\n }\n const tally = lines.find((l) => l !== undefined && /\\b\\d+\\s+failed\\b/.test(l));\n const distilled = [tally, ...failing].filter(Boolean).join(\" | \");\n if (distilled) return distilled.slice(0, 300);\n const err = stderr.replace(ANSI, \"\").trim();\n return err ? err.slice(0, 200) : \"no reporter output\";\n}\n\n/**\n * R3.2: a site whose `package.json` has no `test:smoke` script (or no\n * `package.json` at all) has simply not adopted the suite yet — treat both\n * the same as \"can't tell\", NOT as a failure. Read BEFORE spawning so a\n * not-yet-adopted site never pays a real `pnpm` invocation.\n */\nasync function hasTestSmokeScript(sitePath: string): Promise<boolean> {\n try {\n const raw = await readFile(join(sitePath, \"package.json\"), \"utf-8\");\n const pkg = JSON.parse(raw) as { scripts?: Record<string, string> };\n return typeof pkg.scripts?.[\"test:smoke\"] === \"string\";\n } catch {\n return false;\n }\n}\n\nasync function hasNodeModules(sitePath: string): Promise<boolean> {\n try {\n await access(join(sitePath, \"node_modules\"));\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Run a site's own `pnpm test:smoke` suite in its checkout and reduce the exit\n * code to a verdict. Clone-based: the CLI (`prepareFleetSites`) has already put a\n * real checkout at `site.path` (smoke is NOT in CHECKOUT_FREE_AUDITS). Reuses the\n * a11y harness treatment: a 5-min timeout (Playwright cold-boots the dev server +\n * installs chromium) and a freshly-allocated free port passed as REDDOOR_SMOKE_PORT\n * so the site's smoke playwright config can bind `--port <n> --strictPort` and stay\n * immune to a zombie-vite squatting 5173 (see free-port.ts).\n *\n * A site that hasn't adopted `test:smoke` yet (no script, or no package.json) →\n * skip (R3.2), same bucket as `pnpm` itself being unavailable. exit 0 → pass;\n * non-zero → fail (only reached once the suite is known to exist). A skip never\n * carries details, so the Airtable writer preserves the prior verdict.\n */\nexport async function smokeAudit(ctx: AuditContext): Promise<AuditResult> {\n const spawn = ctx.spawn ?? defaultSpawn;\n const site = ctx.site;\n const label = siteLabel(site);\n const now = ctx.now ?? new Date();\n const checkedAt = now.toISOString();\n\n if (!(await hasTestSmokeScript(site.path))) {\n return {\n audit: \"smoke\",\n site: label,\n status: \"skip\",\n summary: \"no test:smoke script\",\n };\n }\n\n // The nightly fleet producer runs against FRESH clones (cloneIfNeeded does a\n // bare `git clone`, no install), so the site's own playwright/vite aren't on\n // PATH yet — without this, `pnpm test:smoke` exits non-zero and we'd persist a\n // FALSE Smoke OK=fail. Install only when node_modules is absent (a local\n // already-installed checkout is untouched). Any install failure → skip (NO\n // details), so the Airtable writer preserves the prior verdict rather than\n // recording a false fail. Mirrors deps-outdated.ts.\n if (!(await hasNodeModules(site.path))) {\n let install;\n try {\n install = await spawn(\"pnpm\", [\"install\", \"--frozen-lockfile\"], {\n cwd: site.path,\n timeoutMs: 5 * 60_000,\n });\n } catch (err) {\n const e = err as NodeJS.ErrnoException;\n if (e.code === \"ENOENT\" || /ENOENT/.test(String(err))) {\n return { audit: \"smoke\", site: label, status: \"skip\", summary: \"pnpm not available\" };\n }\n throw err;\n }\n if (install.code !== 0) {\n // Lockfile drift shouldn't red a site — retry unfrozen once (the clone is\n // ephemeral, so a rewritten lockfile is harmless). Still failing → skip.\n const retry = await spawn(\"pnpm\", [\"install\"], { cwd: site.path, timeoutMs: 5 * 60_000 });\n if (retry.code !== 0) {\n return {\n audit: \"smoke\",\n site: label,\n status: \"skip\",\n summary: `smoke: pnpm install failed (exit ${retry.code}) — deps unavailable`,\n };\n }\n }\n }\n\n const port = await findFreePort();\n\n let raw;\n try {\n raw = await spawn(\"pnpm\", [\"test:smoke\"], {\n cwd: site.path,\n env: { ...process.env, REDDOOR_SMOKE_PORT: String(port) },\n // Playwright on a cold tree installs chromium, boots the site's dev server,\n // and runs the smoke specs — the shared 30s default starves it (mirrors a11y).\n timeoutMs: 5 * 60_000,\n });\n } catch (err) {\n const e = err as NodeJS.ErrnoException;\n if (e.code === \"ENOENT\" || /ENOENT/.test(String(err))) {\n return { audit: \"smoke\", site: label, status: \"skip\", summary: \"pnpm not available\" };\n }\n throw err;\n }\n\n if (raw.code === 0) {\n return {\n audit: \"smoke\",\n site: label,\n status: \"pass\",\n summary: \"smoke: suite green\",\n details: { ok: \"pass\", checkedAt } satisfies SmokeDetails,\n };\n }\n return {\n audit: \"smoke\",\n site: label,\n status: \"fail\",\n summary: `smoke: suite failed (exit ${raw.code}) — ${summarizeSmokeFailure(raw.stdout, raw.stderr)}`,\n details: { ok: \"fail\", checkedAt } satisfies SmokeDetails,\n };\n}\n","import type { AuditResult } from \"../types.js\";\nimport type { AuditContext } from \"./util/inject.js\";\nimport { siteLabel } from \"../util/site.js\";\n\n/** Cloudflare's PUBLIC test sitekey — always issues a passing client token with no\n * real challenge, so the probe can satisfy a site's Turnstile widget without any\n * secret. The central `testMode` ingest branch (src/forms/ingest.ts, health-gate\n * plan3 Task 5) skips Turnstile enforcement for testMode submissions, making the\n * token's validity moot — it exists to get past the CLIENT widget only. */\nexport const CF_TEST_SITEKEY = \"1x00000000000000000000AA\";\n\n/** The canonical starter contact route. Sites built from reddoor-starter serve the\n * form here; route discovery for bespoke paths is a follow-up (see Open items). */\nconst CONTACT_PATH = \"/contact\";\n\n/** Persisted form-e2e verdict. `ok` is the single-select value: \"pass\"/\"fail\" when a\n * form was found + submitted; null when NO contact form exists (n/a — paired with a\n * fresh checkedAt so the writer stores \"checked, no form\" distinctly from \"never ran\"). */\nexport type FormE2eDetails = {\n ok: \"pass\" | \"fail\" | null;\n formPresent: boolean;\n checkedAt: string;\n};\n\n/** Outcome of driving one site's contact form. `formPresent:false` ⇒ n/a\n * (persisted). `testModeUndeclared` ⇒ the site's /health does not declare\n * `forms.testMode`, so the probe refused to submit — a plain skip, prior\n * verdict preserved. */\nexport type FormSubmitOutcome =\n | { formPresent: false }\n | { formPresent: true; success: boolean; detail?: string }\n | { testModeUndeclared: true };\n\n/** Injected browser IO. The real impl drives Playwright; tests pass a fake. */\nexport type FormRunner = {\n submit: (opts: {\n baseUrl: string;\n testMode: boolean;\n testSitekey: string;\n }) => Promise<FormSubmitOutcome>;\n close?: () => Promise<void>;\n};\n\n/** Opt-in gate for the live Playwright fallback. `defaultFormRunner` drives a REAL\n * browser against `site.deployedUrl` and submits the REAL production contact form.\n * Both central prerequisites HAVE landed: ingest's `testMode` short-circuit\n * (health-gate plan3 Task 5, `src/forms/ingest.ts`) and the starter's\n * `buildPayload` forwarding (Task 6, `reddoor-starter/src/routes/contact/\n * +page.server.ts`). But forwarding is PER-SITE — a site built before Task 6\n * ignores the injected marker and would deliver the probe as a REAL lead. Two\n * layers keep that impossible: (1) this env gate keeps the runner inert in any\n * unfiltered `runAudits` call (e.g. the `init` recipe's final step) unless the\n * operator/producer explicitly arms it (`REDDOOR_FORM_E2E_LIVE=1` — the nightly\n * fleet-form-e2e workflow does); (2) even armed, the runner preflights the\n * site's /health and refuses to submit unless it DECLARES `forms.testMode`\n * (see `declaresTestModeForwarding`) — the declaration ships in the same deploy\n * as the forwarding, so it is always truthful. */\nconst LIVE_ENV_VAR = \"REDDOOR_FORM_E2E_LIVE\";\n\nfunction liveRunnerEnabled(env: NodeJS.ProcessEnv = process.env): boolean {\n return env[LIVE_ENV_VAR] === \"1\" || env[LIVE_ENV_VAR] === \"true\";\n}\n\n/**\n * Submit the REAL production contact form against `site.deployedUrl` in test-mode\n * and reduce the outcome to a verdict. Checkout-free (drives the deployed URL, like\n * browser.ts). The submission carries a `testMode` marker that central ingest is\n * INTENDED to recognize and route away from every real sink (no inbox/DB/webhook,\n * Turnstile enforcement bypassed) once that branch exists — see `liveRunnerEnabled`\n * above for why the live Playwright fallback stays gated off until then. Tests that\n * inject `ctx.formRunner` bypass the gate entirely (it only guards the real,\n * dynamically-imported Playwright runner).\n *\n * - no deployedUrl → skip, NO details → writer preserves the prior verdict.\n * - no injected runner + live gate off → skip, NO details (not yet safe to run live).\n * - no contact form → skip WITH details (ok:null + fresh checkedAt) → persisted as n/a.\n * - form submitted, success → pass (ok:\"pass\"); not success → warn (ok:\"fail\").\n */\nexport async function formE2eAudit(ctx: AuditContext): Promise<AuditResult> {\n const { site } = ctx;\n const label = siteLabel(site);\n if (!site.deployedUrl) {\n return { audit: \"form-e2e\", site: label, status: \"skip\", summary: \"no deployed URL\" };\n }\n if (!ctx.formRunner && !liveRunnerEnabled()) {\n return {\n audit: \"form-e2e\",\n site: label,\n status: \"skip\",\n summary:\n \"live form-e2e disabled (central testMode ingest suppression not yet wired — \" +\n `set ${LIVE_ENV_VAR}=1 once it is)`,\n };\n }\n const now = ctx.now ?? new Date();\n const checkedAt = now.toISOString();\n const runner = ctx.formRunner ?? (await defaultFormRunner());\n try {\n const outcome = await runner.submit({\n baseUrl: site.deployedUrl,\n testMode: true,\n testSitekey: CF_TEST_SITEKEY,\n });\n if (\"testModeUndeclared\" in outcome) {\n // Not n/a — the site may well have a form; it just hasn't rolled out\n // testMode forwarding, so probing it would submit a real lead. Plain\n // skip with NO details preserves the prior verdict.\n return {\n audit: \"form-e2e\",\n site: label,\n status: \"skip\",\n summary:\n \"site /health does not declare forms.testMode — probe refused \" +\n \"(testMode forwarding not yet rolled out here)\",\n };\n }\n if (!outcome.formPresent) {\n return {\n audit: \"form-e2e\",\n site: label,\n status: \"skip\",\n summary: \"no contact form (n/a)\",\n details: { ok: null, formPresent: false, checkedAt } satisfies FormE2eDetails,\n };\n }\n const ok: \"pass\" | \"fail\" = outcome.success ? \"pass\" : \"fail\";\n return {\n audit: \"form-e2e\",\n site: label,\n status: outcome.success ? \"pass\" : \"warn\",\n summary: outcome.success\n ? \"form-e2e: synthetic submission succeeded\"\n : `form-e2e: synthetic submission failed${outcome.detail ? ` — ${outcome.detail}` : \"\"}`,\n details: { ok, formPresent: true, checkedAt } satisfies FormE2eDetails,\n };\n } finally {\n await runner.close?.();\n }\n}\n\n/** Minimum plausible fill time the site's bot-timing screen enforces (client.ts\n * MIN_FILL_MS = 800). A too-fast submit is silently dropped (success shown, ingest\n * never reached), so the probe waits past this before submitting. */\nconst FILL_SETTLE_MS = 1200;\nconst PAGE_TIMEOUT_MS = 30_000;\nconst HEALTH_TIMEOUT_MS = 10_000;\n\n/**\n * GET `{baseUrl}/health` and report whether the site DECLARES that its contact\n * form forwards the `testMode` marker (`forms.testMode === true`, strict\n * boolean). The starter sets the flag in the same deploy whose `buildPayload`\n * forwards the marker, so a declaration is proof the injected field round-trips\n * to central ingest's short-circuit instead of landing as a real lead.\n * Fail-closed: unreachable /health, non-2xx, unparseable body, or a missing/\n * non-boolean flag all return false — the probe then refuses to submit.\n */\nexport async function declaresTestModeForwarding(baseUrl: string): Promise<boolean> {\n try {\n const res = await fetch(new URL(\"/health\", baseUrl), {\n signal: AbortSignal.timeout(HEALTH_TIMEOUT_MS),\n });\n if (!res.ok) return false;\n const body: unknown = await res.json();\n if (typeof body !== \"object\" || body === null) return false;\n const forms = (body as Record<string, unknown>).forms;\n if (typeof forms !== \"object\" || forms === null) return false;\n return (forms as Record<string, unknown>).testMode === true;\n } catch {\n return false;\n }\n}\n\n/**\n * Real Playwright form runner. Lazily imports @playwright/test so unit tests (which\n * inject a fake runner) never load it — and so the audit's static import graph stays\n * central-dep-free for `test:dist`. Every failure degrades to `success:false` (never\n * throws past the audit), so a flaky run yields a non-pass (box stays manual), not a\n * false green.\n */\nexport async function defaultFormRunner(): Promise<FormRunner> {\n const { chromium } = await import(\"@playwright/test\");\n return {\n async submit({ baseUrl, testSitekey }) {\n // Per-site safety preflight — refuse before a browser even launches.\n if (!(await declaresTestModeForwarding(baseUrl))) {\n return { testModeUndeclared: true };\n }\n const browser = await chromium.launch();\n try {\n const ctx = await browser.newContext();\n const page = await ctx.newPage();\n const url = new URL(CONTACT_PATH, baseUrl).toString();\n const resp = await page\n .goto(url, { waitUntil: \"domcontentloaded\", timeout: PAGE_TIMEOUT_MS })\n .catch(() => null);\n // No page, non-2xx, or no <form> with the expected fields ⇒ no contact form (n/a).\n const form = page.locator(\"form\").first();\n const hasForm =\n !!resp &&\n resp.ok() &&\n (await form.count().catch(() => 0)) > 0 &&\n (await page\n .locator('input[name=\"email\"], input[type=\"email\"]')\n .count()\n .catch(() => 0)) > 0;\n if (!hasForm) return { formPresent: false };\n\n await page.fill('[name=\"name\"]', \"Reddoor Monitor\").catch(() => {});\n await page.fill('[name=\"email\"]', \"monitor+e2e@reddoorla.com\").catch(() => {});\n await page.fill('[name=\"phone\"]', \"5555550123\").catch(() => {});\n await page\n .fill('[name=\"message\"]', \"Synthetic end-to-end health check — please ignore.\")\n .catch(() => {});\n\n // Inject the testMode marker + a Turnstile token into the submitted form.\n // The site declared forwarding (preflight above), so the marker routes the\n // submission away from every real sink via central ingest's testMode\n // short-circuit; that branch also skips Turnstile enforcement, making the\n // token's value inconsequential — the CF public test sitekey documents the\n // zero-secret path past the client widget. String-form evaluate\n // (mirrors browser.ts) so the browser-context code isn't type-checked\n // against the Node lib (no DOM globals in this project's tsconfig). The\n // token value is a hardcoded constant (never user input), so inlining it\n // via JSON.stringify into the expression string is safe.\n await page.evaluate(`\n (function () {\n const f = document.querySelector(\"form\");\n if (!f) return;\n const add = (name, value) => {\n let el = f.querySelector('input[name=\"' + name + '\"]');\n if (!el) {\n el = document.createElement(\"input\");\n el.type = \"hidden\";\n el.name = name;\n f.appendChild(el);\n }\n el.value = value;\n };\n add(\"testMode\", \"true\");\n add(\"cf-turnstile-response\", ${JSON.stringify(`testmode-${testSitekey}`)});\n })();\n `);\n\n // Beat the bot-timing screen, then submit and wait for the success banner\n // (role=\"status\") the starter renders on a successful action.\n await page.waitForTimeout(FILL_SETTLE_MS);\n // Capture the action POST so a failure names the real server response\n // (espada 2026-07-10: three \"no success banner\" warns were undiagnosable\n // without it — the POST status/alert text is the evidence).\n const postResponse = page\n .waitForResponse((r) => r.request().method() === \"POST\", {\n timeout: PAGE_TIMEOUT_MS,\n })\n .catch(() => null);\n // Both standard submit controls: reddoor-website uses `<input type=\"submit\">`\n // (its first enrolled run timed out matching button-only and false-failed).\n await page\n .locator('button[type=\"submit\"], input[type=\"submit\"]')\n .first()\n .click({ timeout: PAGE_TIMEOUT_MS });\n const ok = await page\n .locator('[role=\"status\"]')\n .first()\n .waitFor({ state: \"visible\", timeout: PAGE_TIMEOUT_MS })\n .then(() => true)\n .catch(() => false);\n if (ok) return { formPresent: true, success: true };\n const actionResp = await postResponse;\n const alertText = await page\n .locator('[role=\"alert\"]')\n .first()\n .textContent({ timeout: 1000 })\n .catch(() => null);\n const respBit = actionResp\n ? `POST ${actionResp.status()}${actionResp.status() >= 400 ? ` ${(await actionResp.text().catch(() => \"\")).slice(0, 80)}` : \"\"}`\n : \"no POST observed\";\n return {\n formPresent: true,\n success: false,\n detail: `no success banner after submit — ${respBit}${alertText ? `; alert: ${alertText.trim().slice(0, 80)}` : \"\"}`,\n };\n } catch (err) {\n return { formPresent: true, success: false, detail: String(err).slice(0, 120) };\n } finally {\n await browser.close().catch(() => {});\n }\n },\n };\n}\n","import type { AuditName, AuditResult, Site } from \"../types.js\";\nimport type { AuditContext } from \"./util/inject.js\";\nimport { defaultSpawn } from \"./util/spawn.js\";\nimport type { SpawnFn } from \"./util/spawn.js\";\nimport { depsAudit } from \"./deps.js\";\nimport { lintAudit } from \"./lint.js\";\nimport { securityAudit } from \"./security.js\";\nimport { lighthouseAudit } from \"./lighthouse.js\";\nimport { a11yAudit } from \"./a11y.js\";\nimport { domainAudit } from \"./domain.js\";\nimport { browserAudit } from \"./browser.js\";\nimport { netlifyDeployAudit } from \"./netlify-deploy.js\";\nimport { functionHealthAudit } from \"./function-health.js\";\nimport { smokeAudit } from \"./smoke.js\";\nimport { formE2eAudit } from \"./form-e2e.js\";\n\nconst REGISTRY: Record<AuditName, (ctx: AuditContext) => Promise<AuditResult>> = {\n deps: depsAudit,\n lint: lintAudit,\n security: securityAudit,\n lighthouse: lighthouseAudit,\n a11y: a11yAudit,\n domain: domainAudit,\n browser: browserAudit,\n \"netlify-deploy\": netlifyDeployAudit,\n \"function-health\": functionHealthAudit,\n smoke: smokeAudit,\n \"form-e2e\": formE2eAudit,\n};\n\nexport const ALL_AUDIT_NAMES = Object.keys(REGISTRY) as AuditName[];\n\n/** Default per-audit spawn timeout when running via runAudits (30 s). */\nconst DEFAULT_AUDIT_TIMEOUT_MS = 30_000;\n\nfunction timedSpawn(timeoutMs: number): SpawnFn {\n return (cmd, args, opts = {}) =>\n defaultSpawn(cmd, args, { ...opts, timeoutMs: opts.timeoutMs ?? timeoutMs });\n}\n\n/** Single-audit runner with the same error-to-result conversion that\n * `runAudits` applies. Exposed so the CLI can wrap each audit in its\n * own progress task (listr2) and surface per-audit completion timing,\n * while keeping audit implementations UI-free. */\nexport async function runOneAudit(site: Site, name: AuditName): Promise<AuditResult> {\n if (!(name in REGISTRY)) throw new Error(`unknown audit: ${name}`);\n const spawn = timedSpawn(DEFAULT_AUDIT_TIMEOUT_MS);\n // `||` not `??`: an empty-string slug (Airtable Name with no slug-able chars)\n // must fall back to the path, not render a blank `AuditResult.site` that would\n // then collapse fleet write-back grouping under the \"\" key.\n const label = site.name || site.path;\n try {\n return await REGISTRY[name]({ site, spawn });\n } catch (err) {\n return {\n audit: name,\n site: label,\n status: \"fail\",\n summary: `${name}: unexpected error — ${String(err)}`,\n };\n }\n}\n\nexport async function runAudits(site: Site, which?: AuditName[]): Promise<AuditResult[]> {\n const names = which ?? ALL_AUDIT_NAMES;\n for (const n of names) {\n if (!(n in REGISTRY)) throw new Error(`unknown audit: ${n}`);\n }\n return Promise.all(names.map((n) => runOneAudit(site, n)));\n}\n\nexport async function runAuditsAcross(sites: Site[], which?: AuditName[]): Promise<AuditResult[]> {\n const all = await Promise.all(sites.map((s) => runAudits(s, which)));\n return all.flat();\n}\n\nexport { depsAudit, lintAudit, securityAudit, lighthouseAudit, a11yAudit };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,QAAAA,aAAY;;;ACDrB,SAAS,YAAY;AACrB,SAAS,YAAY;AAQrB,eAAe,OAAO,MAAgC;AACpD,MAAI;AACF,UAAM,KAAK,IAAI;AACf,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,SAAS,QAAQ,SAAyB;AACxC,QAAM,OAAO,QAAQ,QAAQ,UAAU,EAAE,EAAE,MAAM,GAAG,EAAE,CAAC,KAAK;AAC5D,QAAM,IAAI,OAAO,SAAS,MAAM,EAAE;AAClC,SAAO,OAAO,MAAM,CAAC,IAAI,IAAI;AAC/B;AAcA,eAAsB,aACpB,UACA,OACgC;AAChC,MA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,MAAM;AAAA,MACN,QAAQ;AAAA,MACR,SAAS,GAAG,IAAI,6BAAwB,OAAO,GAAG,CAAC;AAAA,IACrD;AAAA,EACF;AACF;AAEA,eAAsB,UAAU,MAAY,OAA6C;AACvF,QAAM,QAAQ,SAAS;AACvB,aAAW,KAAK,OAAO;AACrB,QAAI,EAAE,KAAK,UAAW,OAAM,IAAI,MAAM,kBAAkB,CAAC,EAAE;AAAA,EAC7D;AACA,SAAO,QAAQ,IAAI,MAAM,IAAI,CAAC,MAAM,YAAY,MAAM,CAAC,CAAC,CAAC;AAC3D;AAEA,eAAsB,gBAAgB,OAAe,OAA6C;AAChG,QAAM,MAAM,MAAM,QAAQ,IAAI,MAAM,IAAI,CAAC,MAAM,UAAU,GAAG,KAAK,CAAC,CAAC;AACnE,SAAO,IAAI,KAAK;AAClB;","names":["join","join","readFile","join","join","readFile","readFile","join","readFile","join","readFile","join","readFile","writeFile","mkdtemp","rm","join","readJsonMaybe","readFile","mkdtemp","join","writeFile","rm","readFile","join","readFile","join","PAGE_TIMEOUT_MS","HEALTH_TIMEOUT_MS"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/reports/airtable/websites.ts"],"sourcesContent":["import type { FieldSet } from \"airtable\";\nimport type { AirtableBase } from \"./client.js\";\nimport type { LighthouseScores, LighthouseScoreWriteback } from \"../types.js\";\n\nexport const WEBSITES_TABLE = \"Websites\";\n\nexport type Frequency = \"None\" | \"Monthly\" | \"Quarterly\" | \"Yearly\";\n\nexport type Status =\n | \"in development\"\n | \"launch period\"\n | \"maintenance\"\n | \"hosting\"\n | \"probably not our problem\"\n | \"deprecated\";\n\n/**\n * Per-site notification routing. When present on a `maintenance` site, the form\n * notification is addressed by the value of a submission field (`field`, read from\n * `extraFields`) — e.g. route a contact form's `interest` to a different recipient\n * per option, always CC-ing a shared address. Absent (`null`) → the site keeps the\n * default single-POC behavior. Recipients live HERE (server-side Airtable config),\n * never supplied by the submitting site, so the ingest can't be turned into an open\n * relay.\n */\nexport type NotifyRouting = {\n /** The `extraFields` key whose value selects a route, e.g. \"interest\". */\n field: string;\n /** Field-value → recipient address(es). */\n routes: Record<string, string | string[]>;\n /** Recipient(s) when the value matches no route. */\n default?: string | string[];\n /** Address(es) CC'd on every routed (maintenance) send. */\n cc?: string[];\n};\n\nexport type WebsiteRow = {\n id: string;\n name: string;\n url: string;\n status: Status | null;\n pointOfContact: string | null;\n maintenanceFreq: Frequency;\n testingFreq: Frequency;\n /** The literal Airtable cell values behind the coerced frequencies. `toFrequency`\n * trims whitespace (\"Monthly \" reads as Monthly), then maps any still-unrecognized\n * value (\"Quaterly\") to \"None\" with a LOUD console.warn so nothing bogus reaches a\n * client email and the drop is never invisible. Preflight validates THESE to surface\n * the same failure as a structured finding. Null = blank cell. */\n maintenanceFreqRaw: string | null;\n testingFreqRaw: string | null;\n /** Last manually-recorded maintenance day (used as fallback when no Reports row exists). */\n maintenanceDay: string | null;\n testingDay: string | null;\n ga4PropertyId: string | null;\n /** Operator-supplied query for the Google search-presence check (e.g. the business name).\n * Null = no query set → the check is skipped for this site. */\n searchQuery: string | null;\n /** Explicit Search Console property for this site (`sc-domain:...` or `https://.../`).\n * Null = auto-resolve from the SA's visible properties by host. */\n searchConsoleProperty: string | null;\n /** ISO timestamp of the last draft run where THIS site's GA/Search enrichment\n * ERRORED (vs a legitimate \"not configured\" skip). Set by drafting on a soft-fail,\n * cleared (null) on a clean enrichment, so the per-site analytics-failure signal\n * self-heals. Null when the operator-added `Analytics soft-fail at` column is absent. */\n analyticsSoftFailAt: string | null;\n /** GitHub repo identity as `owner/repo`. Null = no git wiring → self-update ops skip\n * (or, for local runs, fall back to the checkout's origin remote). */\n gitRepo: string | null;\n reportRecipientsTo: string | null;\n reportRecipientsCc: string | null;\n acceptedWatchConditions: string[];\n /** First attachment in the Header image field (Airtable's signed URL — fetch before expiry). */\n headerImage: { url: string; filename: string; type: string } | null;\n /** Lighthouse \"current state\" snapshot, kept fresh by `audit lighthouse --write-airtable`. */\n pScore: number | null;\n rScore: number | null;\n bpScore: number | null;\n seoScore: number | null;\n /** ISO timestamp set by `audit lighthouse --write-airtable` when scores were last refreshed. */\n lastLighthouseAuditAt: string | null;\n /** Last-known counts from non-lighthouse audits, written by\n * `audit --write-airtable`. `null` = never audited (or this audit\n * type was skipped on the last run). 0 = audited, clean. */\n a11yViolations: number | null;\n /** Declared-range drift vs the Reddoor baseline (what package.json asks for). */\n depsDrifted: number | null;\n depsMajorBehind: number | null;\n /** Real installed-version drift: deps behind the registry's latest, from the\n * committed lockfile (`pnpm outdated`). Null = not determined this run. */\n depsOutdated: number | null;\n /** Of {@link depsOutdated}, how many are a *major* version behind the\n * registry's latest — the \"majors available on npm\" signal, distinct from the\n * baseline-drift {@link depsMajorBehind}. Null = not determined this run. */\n depsMajorOutdated: number | null;\n securityVulnsCritical: number | null;\n securityVulnsHigh: number | null;\n securityVulnsModerate: number | null;\n securityVulnsLow: number | null;\n /** Count of consecutive nightly Renovate auto-fix dispatches for the CURRENT\n * critical/high vuln episode that have NOT yet cleared it. Owned by\n * `renovate-dispatch`: +1 per real dispatch, reset to 0 when vulns clear.\n * Null = field absent / never dispatched → reads as 0. At/above\n * AUTO_FIX_EXHAUSTED_CYCLES the vuln renders as \"auto-fix failed\". */\n securityAutoFixAttempts: number | null;\n /** ISO timestamp the security audit last ran — gates freshness of the Security Updates auto-tick\n * (clean counts only auto-tick when recent). */\n lastSecurityAuditAt: string | null;\n /** The known advisories behind the counts (severity-sorted, capped), so the dashboard can show\n * WHICH packages are vulnerable, not just the totals. null = never audited / unparseable;\n * empty array = audited clean. Written alongside the counts by the security audit. */\n securityAdvisories: SecurityAdvisory[] | null;\n /** Domain/DNS/SSL probe (the `domain` audit). `certDaysRemaining` is days until the TLS cert\n * expires (null = unresolved or no usable cert); `domainCheckedAt` is when it last ran. */\n certDaysRemaining: number | null;\n domainCheckedAt: string | null;\n /** Netlify site id — the IDENTITY the `netlify-deploy` audit needs to query the\n * Netlify API. Read-only input (operator-set in Airtable); null = not on Netlify\n * (or not wired) → that audit skips. Never derived from the URL. */\n netlifyId: string | null;\n /** Latest PRODUCTION deploy health (the `netlify-deploy` audit). `deployStatus` is\n * Netlify's deploy state lower-cased (`ready`/`error`/`building`/…), null = none / not\n * checked; `lastDeployAt` is when it deployed; `deployLogUrl` links to the deploy/log. */\n deployStatus: string | null;\n lastDeployAt: string | null;\n deployLogUrl: string | null;\n /** When the `netlify-deploy` audit last RAN (freshness stamp for `deployStatus`). The audit\n * already writes \"Deploy checked at\"; this read-back is the Plan-2 fix so `deployEvidence`\n * (Plan 4) can gate on check time — NOT on `lastDeployAt`, which is deploy time, not check time. */\n deployCheckedAt: string | null;\n /** Function-health verdict (the `function-health` audit): the deployed `/health` function\n * answered `ok:true` (pass) or `ok:false` (fail). Single-select `pass`/`fail`; null = never ran\n * / unreachable (→ Plan 4 maps to unknown/amber). Kept SEPARATE from `deployStatus` so\n * `isFailedDeployStatus` keeps meaning \"the build failed\". */\n functionHealth: \"pass\" | \"fail\" | null;\n /** CMS reachability (server-side), derived from the same `/health` body's `details.prismic ===\n * \"ok\"`. Single-select `pass`/`fail`; null = never ran. No per-site Prismic token or identity\n * column is ever built — this rides `/health`. */\n cmsReachable: \"pass\" | \"fail\" | null;\n /** When the `function-health` audit last ran — the freshness gate for BOTH `functionHealth` and\n * `cmsReachable`. Null = never ran. */\n functionHealthCheckedAt: string | null;\n /** Deployed-URL browser probe (the `browser` audit): cross-engine render OK, mobile render OK,\n * internal-links OK + broken count, and when it last ran (one timestamp gates all three). */\n crossbrowserOk: boolean | null;\n mobileOk: boolean | null;\n linksOk: boolean | null;\n brokenLinks: number | null;\n browserCheckedAt: string | null;\n /** Uptime-reachable verdict (browser audit): every sampled route returned 2xx/3xx. Single-select\n * `pass`/`fail`; null = never ran. Point-in-time. Freshness-gated by `browserCheckedAt`. */\n reachableOk: \"pass\" | \"fail\" | null;\n /** Titles & meta verdict (browser audit, chromium): every sampled route has a non-empty `<title>`\n * ≤ 70 chars + a non-empty meta description, and no duplicate titles across the sample.\n * Single-select `pass`/`fail`; null = never ran. Freshness-gated by `browserCheckedAt`. */\n titleMetaOk: \"pass\" | \"fail\" | null;\n /** Per-site copy overrides (M6a). Blank → null → the DEFAULT_COPY value. */\n copyIntro: string | null;\n copyContact: string | null;\n copyFooter: string | null;\n /** Go-live timestamp, stamped when a Launch report sends (M6b). Null = not yet launched. */\n launchedAt: string | null;\n /** Optional per-site webhook (e.g. Zapier Catch Hook). When set, the ingest\n * POSTs newsletter-formType submissions here (best-effort). Blank → null. */\n newsletterWebhook: string | null;\n /** Per-site Mailchimp (newsletter). Both must be set for the direct add;\n * blank → skipped. The API key is `key-dc` format; dc is derived from it. */\n mailchimpApiKey: string | null;\n mailchimpAudienceId: string | null;\n /** Per-site Cloudflare Turnstile gate. When true, a submission whose Turnstile\n * token verifies as \"fail\" is escalated to auto-spam regardless of content score\n * (an absent/unverifiable token stays neutral — fail-open). Airtable checkbox. */\n requireTurnstile: boolean;\n /** GitHub-signals sweep (slice 2a), written nightly by `github-signals --fleet`. */\n renovateFailingCis: number | null;\n defaultBranchCi: string | null; // \"passing\" | \"failing\" | \"pending\" | \"none\"\n lastCommitAt: string | null;\n githubSignalsAt: string | null;\n /** Per-site smoke-suite verdict (the `smoke` audit runs `pnpm test:smoke`).\n * Single-select pass/fail; null = never ran. `lastSmokeAt` gates freshness. */\n smokeOk: \"pass\" | \"fail\" | null;\n lastSmokeAt: string | null;\n /** Synthetic form end-to-end verdict (the `form-e2e` audit submits the real prod\n * contact form in test-mode). Single-select pass/fail; null = never ran OR (with\n * a fresh `formE2eCheckedAt`) no contact form → n/a. `formE2eCheckedAt` gates\n * freshness AND encodes the n/a-vs-never-ran distinction. */\n formE2eOk: \"pass\" | \"fail\" | null;\n formE2eCheckedAt: string | null;\n notifyRouting: NotifyRouting | null;\n};\n\nexport function siteSlug(name: string): string {\n return name\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-|-$/g, \"\");\n}\n\n/** Blank-trim-to-null: a non-string or whitespace-only value becomes null,\n * otherwise the trimmed string. */\nfunction trimToNull(raw: unknown): string | null {\n if (typeof raw !== \"string\") return null;\n const trimmed = raw.trim();\n return trimmed.length > 0 ? trimmed : null;\n}\n\n/**\n * Parse the Websites `Notify Routing` JSON into a NotifyRouting, defensively: a\n * non-string, blank, malformed-JSON, or wrong-shape value yields null (the site\n * then keeps default single-POC routing) — never throws. Mirrors the pipeline's\n * \"a bad Airtable string degrades quietly\" rule.\n */\nexport function parseNotifyRouting(raw: unknown): NotifyRouting | null {\n if (typeof raw !== \"string\") return null;\n const trimmed = raw.trim();\n if (!trimmed) return null;\n let parsed: unknown;\n try {\n parsed = JSON.parse(trimmed);\n } catch {\n return null;\n }\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) return null;\n const o = parsed as Record<string, unknown>;\n if (typeof o.field !== \"string\" || !o.field.trim()) return null;\n if (!o.routes || typeof o.routes !== \"object\" || Array.isArray(o.routes)) return null;\n const routing: NotifyRouting = {\n field: o.field,\n routes: o.routes as Record<string, string | string[]>,\n };\n if (o.default !== undefined) routing.default = o.default as string | string[];\n if (Array.isArray(o.cc)) routing.cc = o.cc.filter((x): x is string => typeof x === \"string\");\n return routing;\n}\n\n/**\n * Active sites: actively-maintained or pre-launch. Single source of truth for\n * \"is this a live site\" — the operator cockpit shows these, and the fleet\n * audit/report path runs against these. A `null` status (not-yet-active) is\n * deliberately excluded.\n */\nexport const ACTIVE_STATUSES: ReadonlySet<Status> = new Set<Status>([\n \"maintenance\",\n \"launch period\",\n]);\n\nexport function isDashboardVisible(site: WebsiteRow): boolean {\n return site.status !== null && ACTIVE_STATUSES.has(site.status);\n}\n\n/**\n * Pre-launch lifecycle stages: the site is being built/prepared, NOT yet live. A\n * Launch report (recipes/launch.ts) flips Status → \"maintenance\" at go-live\n * (updateLaunched), so \"maintenance\" is the true live state. Pre-launch sites must\n * not be audited as production (their deploy/domain/uptime/CMS audits fail because\n * nothing is live yet) nor scheduled recurring Maintenance/Testing reports.\n */\nexport const PRE_LAUNCH_STATUSES: ReadonlySet<Status> = new Set<Status>([\n \"in development\",\n \"launch period\",\n]);\n\nexport function isPreLaunch(status: Status | null): boolean {\n return status !== null && PRE_LAUNCH_STATUSES.has(status);\n}\n\nconst FREQUENCIES: readonly Frequency[] = [\"None\", \"Monthly\", \"Quarterly\", \"Yearly\"];\n\n/** Coerce an Airtable single-select value to a known Frequency at the read boundary.\n * Whitespace is trimmed first, so an operator's trailing-space option (\"Quarterly \")\n * still schedules instead of silently unscheduling the site. Any other non-empty,\n * unrecognized value — a renamed / typo'd option — warns LOUDLY and falls back to\n * \"None\" (its section is simply omitted) rather than flowing a bogus string downstream,\n * which the announcement would otherwise render as \"We do this undefined.\" into a\n * client email. Blank/undefined is a silent \"None\": no schedule is intentional. */\nfunction toFrequency(raw: unknown, context: string): Frequency {\n if (typeof raw !== \"string\") return \"None\";\n const trimmed = raw.trim();\n if ((FREQUENCIES as readonly string[]).includes(trimmed)) return trimmed as Frequency;\n if (trimmed !== \"\") {\n console.warn(\n `⚠ ${context}: unrecognized frequency '${raw}' — treating as None (not scheduling); fix the Airtable value`,\n );\n }\n return \"None\";\n}\n\n/** Coerce an Airtable tri-state single-select verdict cell (`pass`/`fail`/blank) to\n * `\"pass\" | \"fail\" | null`. Any value other than the literal strings \"pass\"/\"fail\" — blank,\n * an unrecognized option, a typo, wrong type — reads as null (\"never ran\"), never guessed. The\n * ONE shared reader for every verdict column of this shape: `Function health`, `CMS Reachable`,\n * `Uptime Reachable`, `Titles & Meta OK` (Plan 2), and reused (not redeclared) by Plan 3's\n * `Smoke OK` / `Form E2E OK` read-backs. */\nexport function toVerdict(raw: unknown): \"pass\" | \"fail\" | null {\n return raw === \"pass\" || raw === \"fail\" ? raw : null;\n}\n\n// NOTE: every `f[\"...\"]` key below is a load-bearing magic string that must match\n// the live Airtable \"Websites\" column name EXACTLY — including the legacy\n// misspelling `\"maintenence freq\"`, the mixed-case `\"GA4 property ID\"`, and the\n// lowercase `\"url\"` / `\"point of contact\"`. A column rename in Airtable silently\n// returns undefined here (→ null), which degrades quietly (GA skipped, recipients\n// empty) with no error. If you rename a column, change it here too.\nexport function mapRow(rec: { id: string; fields: Record<string, unknown> }): WebsiteRow {\n const f = rec.fields;\n const name = String(f[\"Name\"] ?? \"\");\n const attachments =\n (f[\"Header image\"] as Array<{ url: string; filename: string; type: string }> | undefined) ?? [];\n const header = attachments[0] ?? null;\n return {\n id: rec.id,\n name,\n url: String(f[\"url\"] ?? \"\"),\n status: (f[\"Status\"] as Status | undefined) ?? null,\n pointOfContact: (f[\"point of contact\"] as string | undefined) ?? null,\n maintenanceFreq: toFrequency(f[\"maintenence freq\"], `${name} maintenance`),\n testingFreq: toFrequency(f[\"testing freq\"], `${name} testing`),\n maintenanceFreqRaw: (f[\"maintenence freq\"] as string | undefined) ?? null,\n testingFreqRaw: (f[\"testing freq\"] as string | undefined) ?? null,\n maintenanceDay: (f[\"maintenance day\"] as string | undefined) ?? null,\n testingDay: (f[\"testing day\"] as string | undefined) ?? null,\n ga4PropertyId: (f[\"GA4 property ID\"] as string | undefined) ?? null,\n searchQuery: (f[\"Search query\"] as string | undefined) ?? null,\n searchConsoleProperty: (f[\"Search Console property\"] as string | undefined) ?? null,\n analyticsSoftFailAt: (f[\"Analytics soft-fail at\"] as string | undefined) ?? null,\n gitRepo: (f[\"Git repo\"] as string | undefined) ?? null,\n reportRecipientsTo: (f[\"Report recipients (To)\"] as string | undefined) ?? null,\n reportRecipientsCc: (f[\"Report recipients (CC)\"] as string | undefined) ?? null,\n acceptedWatchConditions: Array.isArray(f[\"Accepted Watch Conditions\"])\n ? (f[\"Accepted Watch Conditions\"] as string[])\n : [],\n headerImage: header,\n pScore: (f[\"pScore\"] as number | undefined) ?? null,\n rScore: (f[\"rScore\"] as number | undefined) ?? null,\n bpScore: (f[\"bpScore\"] as number | undefined) ?? null,\n seoScore: (f[\"seoScore\"] as number | undefined) ?? null,\n lastLighthouseAuditAt: (f[\"Last lighthouse audit at\"] as string | undefined) ?? null,\n a11yViolations: (f[\"A11y Violations\"] as number | undefined) ?? null,\n depsDrifted: (f[\"Deps Drifted\"] as number | undefined) ?? null,\n depsMajorBehind: (f[\"Deps Major Behind\"] as number | undefined) ?? null,\n depsOutdated: (f[\"Deps Outdated\"] as number | undefined) ?? null,\n depsMajorOutdated: (f[\"Deps Major Outdated\"] as number | undefined) ?? null,\n securityVulnsCritical: (f[\"Security Vulns Critical\"] as number | undefined) ?? null,\n securityVulnsHigh: (f[\"Security Vulns High\"] as number | undefined) ?? null,\n securityVulnsModerate: (f[\"Security Vulns Moderate\"] as number | undefined) ?? null,\n securityVulnsLow: (f[\"Security Vulns Low\"] as number | undefined) ?? null,\n securityAutoFixAttempts: (f[\"Security Auto-Fix Attempts\"] as number | undefined) ?? null,\n lastSecurityAuditAt: (f[\"Last security audit at\"] as string | undefined) ?? null,\n securityAdvisories: parseSecurityAdvisories(f[\"Security advisories\"]),\n certDaysRemaining: (f[\"Cert days remaining\"] as number | undefined) ?? null,\n domainCheckedAt: (f[\"Domain checked at\"] as string | undefined) ?? null,\n netlifyId: trimToNull(f[\"Netlify ID\"]),\n deployStatus: (f[\"Deploy status\"] as string | undefined) ?? null,\n lastDeployAt: (f[\"Last deploy at\"] as string | undefined) ?? null,\n deployLogUrl: (f[\"Deploy log URL\"] as string | undefined) ?? null,\n deployCheckedAt: (f[\"Deploy checked at\"] as string | undefined) ?? null,\n functionHealth: toVerdict(f[\"Function health\"]),\n cmsReachable: toVerdict(f[\"CMS Reachable\"]),\n functionHealthCheckedAt: (f[\"Function health checked at\"] as string | undefined) ?? null,\n crossbrowserOk:\n typeof f[\"Crossbrowser OK\"] === \"boolean\" ? (f[\"Crossbrowser OK\"] as boolean) : null,\n mobileOk: typeof f[\"Mobile OK\"] === \"boolean\" ? (f[\"Mobile OK\"] as boolean) : null,\n linksOk: typeof f[\"Links OK\"] === \"boolean\" ? (f[\"Links OK\"] as boolean) : null,\n brokenLinks: typeof f[\"Broken links\"] === \"number\" ? (f[\"Broken links\"] as number) : null,\n browserCheckedAt: (f[\"Browser checked at\"] as string | undefined) ?? null,\n reachableOk: toVerdict(f[\"Uptime Reachable\"]),\n titleMetaOk: toVerdict(f[\"Titles & Meta OK\"]),\n copyIntro: trimToNull(f[\"Copy — Intro\"]),\n copyContact: trimToNull(f[\"Copy — Contact\"]),\n copyFooter: trimToNull(f[\"Copy — Footer\"]),\n launchedAt: (f[\"Launched at\"] as string | undefined) ?? null,\n newsletterWebhook: trimToNull(f[\"Newsletter Webhook\"]),\n notifyRouting: parseNotifyRouting(f[\"Notify Routing\"]),\n mailchimpApiKey: trimToNull(f[\"Mailchimp API Key\"]),\n mailchimpAudienceId: trimToNull(f[\"Mailchimp Audience ID\"]),\n // Boolean guard like crossbrowserOk, but defaults FALSE (not null) when absent: an\n // unset/unknown column must read as \"not required\" so the feature ships dark.\n requireTurnstile:\n typeof f[\"Require Turnstile\"] === \"boolean\" ? (f[\"Require Turnstile\"] as boolean) : false,\n renovateFailingCis: (f[\"Renovate Failing CIs\"] as number | undefined) ?? null,\n defaultBranchCi: (f[\"Default Branch CI\"] as string | undefined) ?? null,\n lastCommitAt: (f[\"Last Commit At\"] as string | undefined) ?? null,\n githubSignalsAt: (f[\"GitHub Signals At\"] as string | undefined) ?? null,\n smokeOk: toVerdict(f[\"Smoke OK\"]),\n lastSmokeAt: (f[\"Last Smoke At\"] as string | undefined) ?? null,\n formE2eOk: toVerdict(f[\"Form E2E OK\"]),\n formE2eCheckedAt: (f[\"Form E2E checked at\"] as string | undefined) ?? null,\n };\n}\n\nexport async function listWebsites(base: AirtableBase): Promise<WebsiteRow[]> {\n const out: WebsiteRow[] = [];\n await base(WEBSITES_TABLE)\n .select({ pageSize: 100 })\n .eachPage((records, fetchNextPage) => {\n for (const rec of records) out.push(mapRow({ id: rec.id, fields: rec.fields }));\n fetchNextPage();\n });\n return out;\n}\n\nexport async function getWebsiteBySlug(\n base: AirtableBase,\n slug: string,\n): Promise<WebsiteRow | null> {\n // Slugs are siteSlug() output: [a-z0-9] segments joined by single hyphens.\n // Reject anything else — it can't match a real row, and it keeps URL-supplied\n // input out of the filter formula below (formula-injection guard).\n if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(slug)) return null;\n\n // Narrow the fetch to the slug-matching row server-side instead of paging the\n // whole table per request (MEDIUM-H). The formula replicates siteSlug() on\n // {Name} — lowercase → non-alnum runs to \"-\" → strip leading/trailing \"-\" —\n // verified against the live base. maxRecords caps it (slug collisions keep the\n // prior first-match-wins behavior).\n const formula = `REGEX_REPLACE(REGEX_REPLACE(LOWER({Name}),\"[^a-z0-9]+\",\"-\"),\"^-|-$\",\"\")=${JSON.stringify(\n slug,\n )}`;\n const rows: WebsiteRow[] = [];\n await base(WEBSITES_TABLE)\n .select({ filterByFormula: formula, maxRecords: 1 })\n .eachPage((records, fetchNextPage) => {\n for (const rec of records) rows.push(mapRow({ id: rec.id, fields: rec.fields }));\n fetchNextPage();\n });\n // Confirm the match in JS too: keeps the function correct if the formula and\n // siteSlug() ever drift, and under test fakes that don't evaluate the formula.\n return rows.find((w) => siteSlug(w.name) === slug) ?? null;\n}\n\n// ── audit-field builders ─────────────────────────────────────────────────────\n// One source of truth for the column-name → value mappings of each audit type.\n// The per-audit `updateXxxCounts` writers delegate to these (for their other\n// callers), and `updateAuditFields` merges whichever are present into ONE write —\n// so the field-name magic strings live in exactly one place.\n\nexport type A11yCounts = { violations: number };\nexport type DepsCounts = {\n drifted: number;\n majorBehind: number;\n outdated: number | null;\n majorOutdated: number | null;\n};\nexport type SecurityCounts = { critical: number; high: number; moderate: number; low: number };\nexport type Severity = \"low\" | \"moderate\" | \"high\" | \"critical\";\n/** One known vulnerability behind the security counts, as persisted/rendered. */\nexport type SecurityAdvisory = {\n module: string;\n severity: Severity;\n title: string;\n cves: string[];\n url: string | null;\n /** GitHub Dependabot dependency scope (\"runtime\" | \"development\"), when known. Lets the\n * dashboard flag build-time-only (\"development\") vulns. Omitted for advisories from the\n * lockfile `pnpm audit` fallback, which carries no per-package graph scope. */\n scope?: \"runtime\" | \"development\";\n};\nexport type DomainResult = { certDaysRemaining: number | null; checkedAt: string };\nexport type NetlifyDeployResult = {\n /** Netlify deploy state lower-cased (`ready`/`error`/`building`/…), null = none. */\n state: string | null;\n /** When the latest production deploy was published/created (ISO), null = unknown. */\n deployedAt: string | null;\n /** Link to the deploy / its build log, null = unknown. */\n logUrl: string | null;\n /** When the audit last ran. */\n checkedAt: string;\n};\nexport type BrowserAuditFields = {\n desktopOk: boolean;\n mobileOk: boolean;\n linksOk: boolean;\n reachableOk: boolean;\n titleMetaOk: boolean;\n brokenLinks: number;\n checkedAt: string;\n};\nexport type FunctionHealthResult = {\n /** `pass` when `/health` answered `ok:true`, else `fail`. Never null — the audit only produces a\n * result when it ran (a self-skip carries no details, so this extractor isn't reached). */\n functionHealth: \"pass\" | \"fail\";\n /** From the same body's `prismic` sub-status (R2.2): `\"ok\"` → `\"pass\"`, `\"error\"` → `\"fail\"`.\n * Anything else (`\"skipped\"` — a placeholder repo with no live Prismic — or a raw `null`, e.g.\n * the synthetic \"deployed but erroring\" body) → `null`: the CMS probe never actually ran, so it\n * must NOT red CMS reachability for a site that simply hasn't wired Prismic yet. */\n cmsReachable: \"pass\" | \"fail\" | null;\n /** When the audit ran (freshness stamp for both verdicts). */\n checkedAt: string;\n};\n\nexport type SmokeResult = { ok: \"pass\" | \"fail\"; checkedAt: string };\n\n/** `ok` null clears the single-select cell (n/a — no contact form); a fresh\n * `checkedAt` still stamps the row so Plan 4 reads null+fresh as n/a. */\nexport type FormE2eResult = { ok: \"pass\" | \"fail\" | null; checkedAt: string };\n\nfunction scoreFields(scores: LighthouseScoreWriteback): FieldSet {\n // A null score CLEARS the cell (→ dashboard \"—\"), distinguishing a metric that\n // errored this run (e.g. NO_LCP → null performance) from a real low score. This\n // intentionally overwrites a prior value: a run that couldn't measure the metric\n // shouldn't keep showing a stale number. Writing null to clear mirrors\n // updateAnalyticsHealth; the `as FieldSet` cast is needed because airtable's\n // FieldSet type omits null.\n const fields: Record<string, number | string | null> = {\n pScore: scores.performance,\n rScore: scores.accessibility,\n bpScore: scores.bestPractices,\n seoScore: scores.seo,\n \"Last lighthouse audit at\": new Date().toISOString(),\n };\n return fields as FieldSet;\n}\n\nfunction a11yFields(counts: A11yCounts): FieldSet {\n return { \"A11y Violations\": counts.violations };\n}\n\nfunction depsFields(counts: DepsCounts): FieldSet {\n const fields: FieldSet = {\n \"Deps Drifted\": counts.drifted,\n \"Deps Major Behind\": counts.majorBehind,\n };\n // Only write the outdated count when it was determined — a null (no/stale\n // lockfile this run) must not clobber a previously-good value.\n if (counts.outdated !== null) {\n fields[\"Deps Outdated\"] = counts.outdated;\n }\n // Same null-guard for the registry-major breakdown (same source signal).\n if (counts.majorOutdated !== null) {\n fields[\"Deps Major Outdated\"] = counts.majorOutdated;\n }\n return fields;\n}\n\n/** Critical first → low last; the persist cap and the dashboard list both lean on this. */\nexport const SEVERITY_RANK: Record<Severity, number> = {\n critical: 0,\n high: 1,\n moderate: 2,\n low: 3,\n};\n/** Cap persisted advisories so the JSON field can't blow up on a badly-neglected site. */\nconst MAX_PERSISTED_ADVISORIES = 25;\n\n/** Coerce one untrusted value into a SecurityAdvisory, or null if it isn't shaped like one.\n * Shared by the read path (`parseSecurityAdvisories`) and the write path so both validate\n * identically. A missing module or unrecognized severity drops the entry entirely. */\nexport function normalizeSecurityAdvisory(raw: unknown): SecurityAdvisory | null {\n if (!raw || typeof raw !== \"object\") return null;\n const e = raw as Record<string, unknown>;\n const module = typeof e[\"module\"] === \"string\" ? (e[\"module\"] as string) : null;\n const severity = e[\"severity\"];\n if (module === null) return null;\n if (\n severity !== \"low\" &&\n severity !== \"moderate\" &&\n severity !== \"high\" &&\n severity !== \"critical\"\n )\n return null;\n const cves = Array.isArray(e[\"cves\"])\n ? (e[\"cves\"] as unknown[]).filter((c): c is string => typeof c === \"string\")\n : [];\n const scope =\n e[\"scope\"] === \"runtime\" || e[\"scope\"] === \"development\"\n ? (e[\"scope\"] as \"runtime\" | \"development\")\n : undefined;\n return {\n module,\n severity,\n title: typeof e[\"title\"] === \"string\" ? (e[\"title\"] as string) : \"\",\n cves,\n url: typeof e[\"url\"] === \"string\" ? (e[\"url\"] as string) : null,\n ...(scope ? { scope } : {}),\n };\n}\n\n/** Parse the `Security advisories` JSON cell. null when absent/blank/unparseable/not-an-array\n * (treated as \"never audited\"); a valid array (possibly empty = audited clean) otherwise. */\nexport function parseSecurityAdvisories(raw: unknown): SecurityAdvisory[] | null {\n if (typeof raw !== \"string\" || raw.trim() === \"\") return null;\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n return null;\n }\n if (!Array.isArray(parsed)) return null;\n return parsed.map(normalizeSecurityAdvisory).filter((a): a is SecurityAdvisory => a !== null);\n}\n\nfunction securityAdvisoryFields(advisories: SecurityAdvisory[]): FieldSet {\n const capped = [...advisories]\n .sort((a, b) => SEVERITY_RANK[a.severity] - SEVERITY_RANK[b.severity])\n .slice(0, MAX_PERSISTED_ADVISORIES);\n // Always write — an empty array (\"[]\") clears a stale list when a once-vulnerable site goes clean.\n return { \"Security advisories\": JSON.stringify(capped) };\n}\n\nfunction securityFields(counts: SecurityCounts): FieldSet {\n return {\n \"Security Vulns Critical\": counts.critical,\n \"Security Vulns High\": counts.high,\n \"Security Vulns Moderate\": counts.moderate,\n \"Security Vulns Low\": counts.low,\n // Stamp freshness alongside the counts so the Security Updates auto-tick can require a recent\n // audit (a clean count from months ago must not silently keep ticking the box).\n \"Last security audit at\": new Date().toISOString(),\n };\n}\n\nfunction domainFields(result: DomainResult): FieldSet {\n const fields: FieldSet = { \"Domain checked at\": result.checkedAt };\n // Write the cert days UNCONDITIONALLY: a null (unresolved / no usable cert) must CLEAR any\n // previously-good value. Leaving a stale number in place — next to a freshly-stamped \"Domain\n // checked at\" — false-passes the Domain/DNS/SSL auto-tick (domainEvidence reads the stale\n // non-null value as a current pass) for a site that's actually down. null clears the cell in\n // Airtable; FieldSet's type doesn't model null, hence the cast through a widened record.\n (fields as Record<string, number | null>)[\"Cert days remaining\"] = result.certDaysRemaining;\n return fields;\n}\n\nfunction netlifyDeployFields(result: NetlifyDeployResult): FieldSet {\n // Write all three deploy fields UNCONDITIONALLY (null clears the cell): a null state /\n // deployedAt / logUrl this run means \"couldn't read it\" and must not leave a STALE value\n // sitting next to a fresh \"Deploy checked at\" — the dashboard would otherwise render a green\n // \"ready\" badge for a site whose latest deploy actually errored. FieldSet's type doesn't model\n // null, hence the cast through a widened record (same approach as domainFields).\n const fields: Record<string, string | null> = {\n \"Deploy status\": result.state,\n \"Last deploy at\": result.deployedAt,\n \"Deploy log URL\": result.logUrl,\n \"Deploy checked at\": result.checkedAt,\n };\n return fields as FieldSet;\n}\n\nfunction browserFields(r: BrowserAuditFields): FieldSet {\n return {\n \"Crossbrowser OK\": r.desktopOk,\n \"Mobile OK\": r.mobileOk,\n \"Links OK\": r.linksOk,\n \"Broken links\": r.brokenLinks,\n \"Browser checked at\": r.checkedAt,\n // NEW tri-state single-select verdicts (empty = never ran). The browser audit only produces a\n // BrowserAuditFields when it actually ran (hasBrowserResult guards on checkedAt), so each verdict\n // is always a concrete boolean here — serialize true→\"pass\", false→\"fail\". The existing boolean\n // columns above are deliberately NOT retrofitted (out of scope).\n \"Uptime Reachable\": r.reachableOk ? \"pass\" : \"fail\",\n \"Titles & Meta OK\": r.titleMetaOk ? \"pass\" : \"fail\",\n };\n}\n\nfunction functionHealthFields(r: FunctionHealthResult): FieldSet {\n // \"CMS Reachable\" is written UNCONDITIONALLY (null clears the cell): the audit only supplies a\n // result when it ran, but `cmsReachable` itself can legitimately be null this run (R2.2 — the CMS\n // probe never actually happened, e.g. a placeholder repo with no live Prismic). Clearing rather\n // than leaving a stale pass/fail sitting next to a freshly-stamped checked-at is what keeps a\n // placeholder site from showing a stale CMS verdict. FieldSet's type doesn't model null, hence the\n // cast through a widened record (same approach as domainFields/netlifyDeployFields).\n // \"Function health\" is never null — the audit only writes when it ran, so it's always a concrete\n // pass/fail. Written SEPARATELY from \"Deploy status\" so the Netlify build state keeps its own\n // meaning.\n const fields: Record<string, string | null> = {\n \"Function health\": r.functionHealth,\n \"CMS Reachable\": r.cmsReachable,\n \"Function health checked at\": r.checkedAt,\n };\n return fields as FieldSet;\n}\n\nfunction smokeFields(r: SmokeResult): FieldSet {\n // The verdict is stored as the literal single-select option (\"pass\"/\"fail\"), so\n // no boolean→string coercion is needed. A skip never reaches here (it produces no\n // SmokeResult), so this column is only ever written with a concrete verdict.\n return { \"Smoke OK\": r.ok, \"Last Smoke At\": r.checkedAt };\n}\n\nfunction formE2eFields(r: FormE2eResult): FieldSet {\n // `ok` is already the single-select value (\"pass\"/\"fail\") or null. Writing null\n // CLEARS the cell (→ n/a, distinguished from \"never ran\" by the fresh checked-at\n // stamped alongside). FieldSet's type omits null, hence the widened-record cast\n // (same approach as domainFields / netlifyDeployFields).\n const fields: Record<string, string | null> = {\n \"Form E2E OK\": r.ok,\n \"Form E2E checked at\": r.checkedAt,\n };\n return fields as FieldSet;\n}\n\n/**\n * Write the four Lighthouse scores + a refreshed-at timestamp onto a Websites row.\n * Called by `audit lighthouse --write-airtable` after a successful audit run, so\n * the operator never has to paste numbers manually before drafting a report.\n */\nexport async function updateScores(\n base: AirtableBase,\n recordId: string,\n scores: LighthouseScores,\n): Promise<void> {\n await base(WEBSITES_TABLE).update([{ id: recordId, fields: scoreFields(scores) }]);\n}\n\n/**\n * Record (or clear) the per-site GA/Search enrichment health on the `Analytics\n * soft-fail at` column. `at` is an ISO timestamp when the site's last draft had a\n * GA/Search soft-failure, or `null` to clear it after a clean enrichment. The\n * caller (drafting) swallows errors: this column is operator-added, so until it\n * exists Airtable throws UNKNOWN_FIELD_NAME — which must not break a draft.\n */\nexport async function updateAnalyticsHealth(\n base: AirtableBase,\n recordId: string,\n at: string | null,\n): Promise<void> {\n const fields: Record<string, string | null> = { \"Analytics soft-fail at\": at };\n await base(WEBSITES_TABLE).update([{ id: recordId, fields: fields as FieldSet }]);\n}\n\n/** Persist a11y violation count. */\nexport async function updateA11yCounts(\n base: AirtableBase,\n recordId: string,\n counts: A11yCounts,\n): Promise<void> {\n await base(WEBSITES_TABLE).update([{ id: recordId, fields: a11yFields(counts) }]);\n}\n\n/** Persist deps drift counts (declared-range drift + real outdated installs). */\nexport async function updateDepsCounts(\n base: AirtableBase,\n recordId: string,\n counts: DepsCounts,\n): Promise<void> {\n await base(WEBSITES_TABLE).update([{ id: recordId, fields: depsFields(counts) }]);\n}\n\n/** Persist security vulnerability counts by severity. */\nexport async function updateSecurityCounts(\n base: AirtableBase,\n recordId: string,\n counts: SecurityCounts,\n): Promise<void> {\n await base(WEBSITES_TABLE).update([{ id: recordId, fields: securityFields(counts) }]);\n}\n\n/** Persist a site's auto-fix attempt counter. Its own one-field writer so the\n * nightly Renovate dispatch can update it without touching the audit's counts. */\nexport async function updateAutoFixAttempts(\n base: AirtableBase,\n recordId: string,\n attempts: number,\n): Promise<void> {\n await base(WEBSITES_TABLE).update([\n { id: recordId, fields: { \"Security Auto-Fix Attempts\": attempts } },\n ]);\n}\n\n/**\n * Persist the code-computed next-due dates (date-only `YYYY-MM-DD`, or `null` to\n * clear) for the maintenance + testing schedules. Owned by the nightly `--due` sweep\n * so the \"next\" dates shown in Airtable come from the SAME logic as the scheduler\n * (`nextDueDate`) — no Airtable-side formula or automation. Best-effort at the call\n * site: the `Next … at` columns are operator-added, so until they exist Airtable\n * throws UNKNOWN_FIELD_NAME, which must not break the nightly draft run.\n */\nexport async function updateNextDueDates(\n base: AirtableBase,\n recordId: string,\n dates: { maintenanceAt: string | null; testingAt: string | null },\n): Promise<void> {\n const fields: Record<string, string | null> = {\n \"Next maintenance at\": dates.maintenanceAt,\n \"Next testing at\": dates.testingAt,\n };\n await base(WEBSITES_TABLE).update([{ id: recordId, fields: fields as FieldSet }]);\n}\n\n/** Generic single-field writer for the dashboard site-details editor. The caller\n * (setSiteDetail) restricts `column` to the EDITABLE_SITE_FIELDS allowlist, so this\n * never writes an arbitrary column from request input. */\nexport async function updateSiteField(\n base: AirtableBase,\n recordId: string,\n column: string,\n value: string,\n): Promise<void> {\n await base(WEBSITES_TABLE).update([{ id: recordId, fields: { [column]: value } }]);\n}\n\n/**\n * Persist all of a single audit run's results to one Websites row in ONE atomic\n * `update()` — instead of up to four sequential updates on the same id (which left\n * a row half-written on a mid-sequence failure and quadrupled the request volume).\n * Pass only the audit slices that produced real values; each present slice is merged\n * via the SAME field mappings the per-audit writers use. Omit a slice (or pass\n * undefined) to leave those columns untouched. Returns the merged FieldSet so the\n * caller can enumerate what was written.\n */\nexport async function updateAuditFields(\n base: AirtableBase,\n recordId: string,\n audits: {\n scores?: LighthouseScoreWriteback;\n a11y?: A11yCounts;\n deps?: DepsCounts;\n security?: SecurityCounts;\n securityAdvisories?: SecurityAdvisory[];\n domain?: DomainResult;\n browser?: BrowserAuditFields;\n netlifyDeploy?: NetlifyDeployResult;\n functionHealth?: FunctionHealthResult;\n smoke?: SmokeResult;\n formE2e?: FormE2eResult;\n },\n): Promise<FieldSet> {\n const fields: FieldSet = {};\n if (audits.scores) Object.assign(fields, scoreFields(audits.scores));\n if (audits.a11y) Object.assign(fields, a11yFields(audits.a11y));\n if (audits.deps) Object.assign(fields, depsFields(audits.deps));\n if (audits.security) Object.assign(fields, securityFields(audits.security));\n // Separate slice (not folded into `security`) so the advisory list and the counts can be\n // written independently, but in practice the security audit supplies both together.\n if (audits.securityAdvisories)\n Object.assign(fields, securityAdvisoryFields(audits.securityAdvisories));\n if (audits.domain) Object.assign(fields, domainFields(audits.domain));\n if (audits.browser) Object.assign(fields, browserFields(audits.browser));\n if (audits.netlifyDeploy) Object.assign(fields, netlifyDeployFields(audits.netlifyDeploy));\n if (audits.functionHealth) Object.assign(fields, functionHealthFields(audits.functionHealth));\n if (audits.smoke) Object.assign(fields, smokeFields(audits.smoke));\n if (audits.formE2e) Object.assign(fields, formE2eFields(audits.formE2e));\n await base(WEBSITES_TABLE).update([{ id: recordId, fields }]);\n return fields;\n}\n\n/** Persist the GitHub-signals sweep onto a Websites row (slice 2a). A null\n * `lastCommitAt` is OMITTED so a not-determined-this-run value never clobbers a\n * previously-good timestamp (mirrors updateDepsCounts' outdated handling). */\nexport async function updateGitHubSignals(\n base: AirtableBase,\n recordId: string,\n signals: {\n renovateFailingCis: number;\n ciState: string;\n lastCommitAt: string | null;\n sweptAt: string;\n },\n): Promise<void> {\n const fields: FieldSet = {\n \"Renovate Failing CIs\": signals.renovateFailingCis,\n \"Default Branch CI\": signals.ciState,\n \"GitHub Signals At\": signals.sweptAt,\n };\n if (signals.lastCommitAt !== null) {\n fields[\"Last Commit At\"] = signals.lastCommitAt;\n }\n await base(WEBSITES_TABLE).update([{ id: recordId, fields }]);\n}\n\n/** Mark a site launched: flip Status → maintenance + stamp Launched at (M6b).\n * The first code that writes Status. Called after a Launch report sends. */\nexport async function updateLaunched(\n base: AirtableBase,\n recordId: string,\n at: string,\n): Promise<void> {\n const fields: FieldSet = { Status: \"maintenance\", \"Launched at\": at };\n await base(WEBSITES_TABLE).update([{ id: recordId, fields }]);\n}\n"],"mappings":";AAIO,IAAM,iBAAiB;AA2LvB,SAAS,SAAS,MAAsB;AAC7C,SAAO,KACJ,YAAY,EACZ,QAAQ,eAAe,GAAG,EAC1B,QAAQ,UAAU,EAAE;AACzB;AAIA,SAAS,WAAW,KAA6B;AAC/C,MAAI,OAAO,QAAQ,SAAU,QAAO;AACpC,QAAM,UAAU,IAAI,KAAK;AACzB,SAAO,QAAQ,SAAS,IAAI,UAAU;AACxC;AAQO,SAAS,mBAAmB,KAAoC;AACrE,MAAI,OAAO,QAAQ,SAAU,QAAO;AACpC,QAAM,UAAU,IAAI,KAAK;AACzB,MAAI,CAAC,QAAS,QAAO;AACrB,MAAI;AACJ,MAAI;AACF,aAAS,KAAK,MAAM,OAAO;AAAA,EAC7B,QAAQ;AACN,WAAO;AAAA,EACT;AACA,MAAI,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