@reddoorla/maintenance 0.87.0 → 0.88.2
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-QG5ICI3Y.js +9 -0
- package/dist/{announce-I2Z4JN3I.js → announce-GKD5YJNB.js} +9 -9
- package/dist/{blux-ZGDSHI3U.js → blux-DN4MI532.js} +5 -5
- package/dist/{bump-deps-CGVELRLK.js → bump-deps-KGH5UYSF.js} +4 -4
- package/dist/{chunk-SDDPUAWH.js → chunk-6I6L3CMX.js} +2 -2
- package/dist/{chunk-ZBDZTJUO.js → chunk-7FFUBF4I.js} +5 -2
- package/dist/chunk-7FFUBF4I.js.map +1 -0
- package/dist/{chunk-HSI6Q7MI.js → chunk-7TMWBXX7.js} +159 -29
- package/dist/chunk-7TMWBXX7.js.map +1 -0
- package/dist/{chunk-DEWJMMG3.js → chunk-A2UNJIKH.js} +15 -7
- package/dist/chunk-A2UNJIKH.js.map +1 -0
- package/dist/{chunk-NCMZMLY7.js → chunk-ANJNTAMM.js} +3 -69
- package/dist/chunk-ANJNTAMM.js.map +1 -0
- package/dist/{chunk-3JQ2FO3D.js → chunk-B23FFWU4.js} +2 -2
- package/dist/{chunk-DJZWYIPP.js → chunk-BGTYPVLT.js} +1 -1
- package/dist/chunk-BGTYPVLT.js.map +1 -0
- package/dist/chunk-BRYXFH77.js +70 -0
- package/dist/chunk-BRYXFH77.js.map +1 -0
- package/dist/{chunk-NDWYJLRF.js → chunk-DGZWFI2G.js} +3 -3
- package/dist/{chunk-HHMMUR4P.js → chunk-GQDDWYU2.js} +45 -8
- package/dist/chunk-GQDDWYU2.js.map +1 -0
- package/dist/{chunk-BBUSGEES.js → chunk-J3WEZGIN.js} +6 -6
- package/dist/{chunk-BNM5POSJ.js → chunk-JRHIFA5R.js} +2 -2
- package/dist/{chunk-TD2NNXLZ.js → chunk-K6SLF6GI.js} +5 -5
- package/dist/{chunk-MT2JINSS.js → chunk-KJGKZLCT.js} +3 -3
- package/dist/{chunk-NXNPDCF3.js → chunk-KMCZA7CH.js} +11 -1
- package/dist/chunk-KMCZA7CH.js.map +1 -0
- package/dist/{chunk-3SF7D4DY.js → chunk-MFHS7IQ2.js} +36 -1
- package/dist/{chunk-3SF7D4DY.js.map → chunk-MFHS7IQ2.js.map} +1 -1
- package/dist/{chunk-SNSTJLQW.js → chunk-NO74DXDP.js} +48 -2
- package/dist/chunk-NO74DXDP.js.map +1 -0
- package/dist/{chunk-C6B4RHXR.js → chunk-O3GT46R2.js} +8 -2
- package/dist/chunk-O3GT46R2.js.map +1 -0
- package/dist/{chunk-C6CLRKPV.js → chunk-PR343K7F.js} +2 -2
- package/dist/{chunk-CROKUHJB.js → chunk-Q47DU255.js} +4 -4
- package/dist/{chunk-EVBCK2KC.js → chunk-RARREDQE.js} +2 -1
- package/dist/{chunk-EVBCK2KC.js.map → chunk-RARREDQE.js.map} +1 -1
- package/dist/chunk-RUPPWAD6.js +7 -0
- package/dist/chunk-RUPPWAD6.js.map +1 -0
- package/dist/{chunk-VSBFM7DS.js → chunk-SJOXWJ5Y.js} +3 -3
- package/dist/{chunk-HEWSRXYV.js → chunk-ULHPALI5.js} +3 -3
- package/dist/{chunk-XUGSZP7Z.js → chunk-W45FZEGE.js} +2 -2
- package/dist/{chunk-JHGHLKFS.js → chunk-WS6NU475.js} +2 -2
- package/dist/{chunk-ZGBEIWSC.js → chunk-XP5WM2LV.js} +5 -5
- package/dist/{chunk-6TWWY7ZU.js → chunk-Z3JXLULD.js} +2 -2
- package/dist/cli/bin.js +27 -27
- package/dist/cli/bin.js.map +1 -1
- package/dist/cli/commands/audit.d.ts +4 -0
- package/dist/cli/commands/audit.js +16 -13
- package/dist/cli/commands/audit.js.map +1 -1
- package/dist/client-JYKPVCJX.js +11 -0
- package/dist/configs/playwright-a11y.js +1 -1
- package/dist/{convert-to-pnpm-QFJOEP5V.js → convert-to-pnpm-NWB5FCQ2.js} +4 -4
- package/dist/{db-UXNIZ2RG.js → db-V6UIS433.js} +121 -26
- package/dist/db-V6UIS433.js.map +1 -0
- package/dist/{digest-FW6QMZZJ.js → digest-2JEAEJK6.js} +53 -29
- package/dist/digest-2JEAEJK6.js.map +1 -0
- package/dist/digest-state-CRZRNGDI.js +25 -0
- package/dist/digest-state-CRZRNGDI.js.map +1 -0
- package/dist/digest-state-F37XUCS5.js +13 -0
- package/dist/{dump-P6EBSIOH.js → dump-EPL7AZFR.js} +38 -13
- package/dist/dump-EPL7AZFR.js.map +1 -0
- package/dist/{email-KJXASVH5.js → email-SL7464YI.js} +16 -6
- package/dist/{email-KJXASVH5.js.map → email-SL7464YI.js.map} +1 -1
- package/dist/{ensure-site-4DCEBAPM.js → ensure-site-FU6527OU.js} +2 -2
- package/dist/{fleet-state-7TJ2GYT2.js → fleet-state-R5LU7IC3.js} +4 -2
- package/dist/{forms-notify-target-2EAWCWBW.js → forms-notify-target-SGDGXXK5.js} +6 -6
- package/dist/{github-signals-E2WPYTBK.js → github-signals-GWGCKEE2.js} +7 -6
- package/dist/{github-signals-E2WPYTBK.js.map → github-signals-GWGCKEE2.js.map} +1 -1
- package/dist/{header-image-6IC53W27.js → header-image-7A7XLVEU.js} +2 -2
- package/dist/{health-endpoint-RFXL2F4A.js → health-endpoint-UVX6R5N5.js} +4 -4
- package/dist/{health-mirror-L5JBEJVA.js → health-mirror-GCDN7BJL.js} +11 -6
- package/dist/health-mirror-GCDN7BJL.js.map +1 -0
- package/dist/index.js +128 -88
- package/dist/index.js.map +1 -1
- package/dist/{init-XRAQZYID.js → init-FGTYNGUI.js} +9 -9
- package/dist/{launch-IX4Y5JJC.js → launch-5H7LPEGP.js} +12 -11
- package/dist/{launch-IX4Y5JJC.js.map → launch-5H7LPEGP.js.map} +1 -1
- package/dist/migrate-YITCXBLS.js +7 -0
- package/dist/{notify-C645PGD5.js → notify-4HP4GZ2H.js} +5 -5
- package/dist/{onboard-O4IAHJMO.js → onboard-BKCYBAVW.js} +4 -4
- package/dist/{orchestrate-YLWQ6KK2.js → orchestrate-JNKCWU5K.js} +9 -9
- package/dist/{parity-56KA2DGR.js → parity-NBYZUBFU.js} +4 -2
- package/dist/pdf-N5QLQ5ZQ.js +38 -0
- package/dist/pdf-N5QLQ5ZQ.js.map +1 -0
- package/dist/{pipeline-3AANZFCR.js → pipeline-WYTXSLHX.js} +3 -3
- package/dist/{preflight-TNORKGCX.js → preflight-IMTYDDD4.js} +10 -10
- package/dist/{prismic-ci-G2AK53VL.js → prismic-ci-MY2U6NN7.js} +4 -4
- package/dist/{prismic-models-O6Z3OK3A.js → prismic-models-NJN5JORF.js} +6 -6
- package/dist/prospect/types.d.ts +14 -0
- package/dist/{prospect-audit-KSXUNQ5J.js → prospect-audit-JMBRVXSG.js} +32 -13
- package/dist/prospect-audit-JMBRVXSG.js.map +1 -0
- package/dist/render-VX72AESY.js +10 -0
- package/dist/{render-from-row-BWSOIYDS.js → render-from-row-DOYJDO2L.js} +5 -5
- package/dist/{replay-C2LXMJZP.js → replay-4S6ENYCH.js} +3 -3
- package/dist/{report-R3E3Y7HR.js → report-TALY5P3L.js} +17 -17
- package/dist/{report-mirror-4MNORYQ4.js → report-mirror-AAK3MXHY.js} +12 -6
- package/dist/report-mirror-AAK3MXHY.js.map +1 -0
- package/dist/schema-75PJECAE.js +18 -0
- package/dist/schema-75PJECAE.js.map +1 -0
- package/dist/{self-updating-UCIWESAX.js → self-updating-NTCCWJYZ.js} +4 -4
- package/dist/{selftest-VGHWPN72.js → selftest-NZTR4SM2.js} +11 -11
- package/dist/{site-mirror-NIREX5ME.js → site-mirror-Q763PLGG.js} +17 -7
- package/dist/site-mirror-Q763PLGG.js.map +1 -0
- package/dist/{smoke-suite-U3UKD3NS.js → smoke-suite-4JFZZYVW.js} +4 -4
- package/dist/{spam-classifier-XLBFCO7G.js → spam-classifier-T5H4VTP6.js} +4 -2
- package/dist/{submissions-IQEJX6FK.js → submissions-TEHPBSZJ.js} +4 -4
- package/dist/{svelte-codemods-GOKXTBHW.js → svelte-codemods-QAPDZC6F.js} +4 -4
- package/dist/{sync-CTUVXMCK.js → sync-GBFV45WX.js} +4 -2
- package/dist/{sync-CTUVXMCK.js.map → sync-GBFV45WX.js.map} +1 -1
- package/dist/{sync-configs-SPTLFJCC.js → sync-configs-34JIA6KZ.js} +4 -4
- package/dist/{upgrade-W6ZR3FJH.js → upgrade-IR2OO3KP.js} +4 -4
- package/dist/{webhook-VOGOW3W6.js → webhook-XM6EV4XT.js} +2 -2
- package/dist/{write-audits-to-airtable-CMKHGJNQ.js → write-audits-to-airtable-OBHGR7DQ.js} +5 -2
- package/dist/write-audits-to-airtable-OBHGR7DQ.js.map +1 -0
- package/package.json +1 -1
- package/dist/airtable-ZBUPQJSC.js +0 -9
- package/dist/chunk-C6B4RHXR.js.map +0 -1
- package/dist/chunk-DEWJMMG3.js.map +0 -1
- package/dist/chunk-DJZWYIPP.js.map +0 -1
- package/dist/chunk-HHMMUR4P.js.map +0 -1
- package/dist/chunk-HSI6Q7MI.js.map +0 -1
- package/dist/chunk-NCMZMLY7.js.map +0 -1
- package/dist/chunk-NXNPDCF3.js.map +0 -1
- package/dist/chunk-SNSTJLQW.js.map +0 -1
- package/dist/chunk-ZBDZTJUO.js.map +0 -1
- package/dist/client-AUE3XUPO.js +0 -11
- package/dist/db-UXNIZ2RG.js.map +0 -1
- package/dist/digest-FW6QMZZJ.js.map +0 -1
- package/dist/dump-P6EBSIOH.js.map +0 -1
- package/dist/health-mirror-L5JBEJVA.js.map +0 -1
- package/dist/migrate-GQH237A6.js +0 -7
- package/dist/prospect-audit-KSXUNQ5J.js.map +0 -1
- package/dist/render-IFOGFB5T.js +0 -10
- package/dist/report-mirror-4MNORYQ4.js.map +0 -1
- package/dist/site-mirror-NIREX5ME.js.map +0 -1
- /package/dist/{airtable-ZBUPQJSC.js.map → airtable-QG5ICI3Y.js.map} +0 -0
- /package/dist/{announce-I2Z4JN3I.js.map → announce-GKD5YJNB.js.map} +0 -0
- /package/dist/{blux-ZGDSHI3U.js.map → blux-DN4MI532.js.map} +0 -0
- /package/dist/{bump-deps-CGVELRLK.js.map → bump-deps-KGH5UYSF.js.map} +0 -0
- /package/dist/{chunk-SDDPUAWH.js.map → chunk-6I6L3CMX.js.map} +0 -0
- /package/dist/{chunk-3JQ2FO3D.js.map → chunk-B23FFWU4.js.map} +0 -0
- /package/dist/{chunk-NDWYJLRF.js.map → chunk-DGZWFI2G.js.map} +0 -0
- /package/dist/{chunk-BBUSGEES.js.map → chunk-J3WEZGIN.js.map} +0 -0
- /package/dist/{chunk-BNM5POSJ.js.map → chunk-JRHIFA5R.js.map} +0 -0
- /package/dist/{chunk-TD2NNXLZ.js.map → chunk-K6SLF6GI.js.map} +0 -0
- /package/dist/{chunk-MT2JINSS.js.map → chunk-KJGKZLCT.js.map} +0 -0
- /package/dist/{chunk-C6CLRKPV.js.map → chunk-PR343K7F.js.map} +0 -0
- /package/dist/{chunk-CROKUHJB.js.map → chunk-Q47DU255.js.map} +0 -0
- /package/dist/{chunk-VSBFM7DS.js.map → chunk-SJOXWJ5Y.js.map} +0 -0
- /package/dist/{chunk-HEWSRXYV.js.map → chunk-ULHPALI5.js.map} +0 -0
- /package/dist/{chunk-XUGSZP7Z.js.map → chunk-W45FZEGE.js.map} +0 -0
- /package/dist/{chunk-JHGHLKFS.js.map → chunk-WS6NU475.js.map} +0 -0
- /package/dist/{chunk-ZGBEIWSC.js.map → chunk-XP5WM2LV.js.map} +0 -0
- /package/dist/{chunk-6TWWY7ZU.js.map → chunk-Z3JXLULD.js.map} +0 -0
- /package/dist/{client-AUE3XUPO.js.map → client-JYKPVCJX.js.map} +0 -0
- /package/dist/{convert-to-pnpm-QFJOEP5V.js.map → convert-to-pnpm-NWB5FCQ2.js.map} +0 -0
- /package/dist/{fleet-state-7TJ2GYT2.js.map → digest-state-F37XUCS5.js.map} +0 -0
- /package/dist/{ensure-site-4DCEBAPM.js.map → ensure-site-FU6527OU.js.map} +0 -0
- /package/dist/{migrate-GQH237A6.js.map → fleet-state-R5LU7IC3.js.map} +0 -0
- /package/dist/{forms-notify-target-2EAWCWBW.js.map → forms-notify-target-SGDGXXK5.js.map} +0 -0
- /package/dist/{header-image-6IC53W27.js.map → header-image-7A7XLVEU.js.map} +0 -0
- /package/dist/{health-endpoint-RFXL2F4A.js.map → health-endpoint-UVX6R5N5.js.map} +0 -0
- /package/dist/{init-XRAQZYID.js.map → init-FGTYNGUI.js.map} +0 -0
- /package/dist/{notify-C645PGD5.js.map → migrate-YITCXBLS.js.map} +0 -0
- /package/dist/{orchestrate-YLWQ6KK2.js.map → notify-4HP4GZ2H.js.map} +0 -0
- /package/dist/{onboard-O4IAHJMO.js.map → onboard-BKCYBAVW.js.map} +0 -0
- /package/dist/{parity-56KA2DGR.js.map → orchestrate-JNKCWU5K.js.map} +0 -0
- /package/dist/{pipeline-3AANZFCR.js.map → parity-NBYZUBFU.js.map} +0 -0
- /package/dist/{render-IFOGFB5T.js.map → pipeline-WYTXSLHX.js.map} +0 -0
- /package/dist/{preflight-TNORKGCX.js.map → preflight-IMTYDDD4.js.map} +0 -0
- /package/dist/{prismic-ci-G2AK53VL.js.map → prismic-ci-MY2U6NN7.js.map} +0 -0
- /package/dist/{prismic-models-O6Z3OK3A.js.map → prismic-models-NJN5JORF.js.map} +0 -0
- /package/dist/{render-from-row-BWSOIYDS.js.map → render-VX72AESY.js.map} +0 -0
- /package/dist/{spam-classifier-XLBFCO7G.js.map → render-from-row-DOYJDO2L.js.map} +0 -0
- /package/dist/{replay-C2LXMJZP.js.map → replay-4S6ENYCH.js.map} +0 -0
- /package/dist/{report-R3E3Y7HR.js.map → report-TALY5P3L.js.map} +0 -0
- /package/dist/{self-updating-UCIWESAX.js.map → self-updating-NTCCWJYZ.js.map} +0 -0
- /package/dist/{selftest-VGHWPN72.js.map → selftest-NZTR4SM2.js.map} +0 -0
- /package/dist/{smoke-suite-U3UKD3NS.js.map → smoke-suite-4JFZZYVW.js.map} +0 -0
- /package/dist/{write-audits-to-airtable-CMKHGJNQ.js.map → spam-classifier-T5H4VTP6.js.map} +0 -0
- /package/dist/{submissions-IQEJX6FK.js.map → submissions-TEHPBSZJ.js.map} +0 -0
- /package/dist/{svelte-codemods-GOKXTBHW.js.map → svelte-codemods-QAPDZC6F.js.map} +0 -0
- /package/dist/{sync-configs-SPTLFJCC.js.map → sync-configs-34JIA6KZ.js.map} +0 -0
- /package/dist/{upgrade-W6ZR3FJH.js.map → upgrade-IR2OO3KP.js.map} +0 -0
- /package/dist/{webhook-VOGOW3W6.js.map → webhook-XM6EV4XT.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/audits/a11y-airtable.ts","../src/audits/deps-airtable.ts","../src/audits/security-airtable.ts","../src/audits/domain-airtable.ts","../src/audits/browser-airtable.ts","../src/audits/netlify-deploy-airtable.ts","../src/audits/function-health-airtable.ts","../src/audits/smoke-airtable.ts","../src/audits/form-e2e-airtable.ts","../src/audits/write-audits-to-airtable.ts"],"sourcesContent":["import type { AuditResult } from \"../types.js\";\n\ntype A11yDetails = {\n totalViolations: number;\n byImpact: Partial<Record<\"minor\" | \"moderate\" | \"serious\" | \"critical\", number>>;\n};\n\n/** True when an a11y AuditResult carries real counts worth persisting.\n * Mirrors the `hasRealScores` policy on lighthouse: write whenever real\n * data exists, regardless of status (a \"warn\" or \"fail\" with concrete\n * violation counts is exactly what the dashboard needs to track). */\nexport function hasA11yCounts(result: AuditResult): boolean {\n if (result.audit !== \"a11y\") return false;\n const details = result.details as A11yDetails | undefined;\n return typeof details?.totalViolations === \"number\";\n}\n\nexport function a11yCountsFromResult(result: AuditResult): { violations: number } {\n if (result.audit !== \"a11y\") {\n throw new Error(`Expected an 'a11y' AuditResult, got '${result.audit}'`);\n }\n const details = result.details as A11yDetails | undefined;\n return { violations: details?.totalViolations ?? 0 };\n}\n","import type { AuditResult } from \"../types.js\";\nimport type { DepsDetails, DepsDriftEntry } from \"./deps.js\";\n\n/** True when a deps AuditResult carries the structured details (an entries\n * array, per {@link DepsDetails}). */\nexport function hasDepsCounts(result: AuditResult): boolean {\n if (result.audit !== \"deps\") return false;\n const d = result.details as Partial<DepsDetails> | undefined;\n return Array.isArray(d?.entries);\n}\n\nexport function depsCountsFromResult(result: AuditResult): {\n drifted: number;\n majorBehind: number;\n outdated: number | null;\n majorOutdated: number | null;\n} {\n if (result.audit !== \"deps\") {\n throw new Error(`Expected a 'deps' AuditResult, got '${result.audit}'`);\n }\n const details = (result.details ?? {}) as Partial<DepsDetails>;\n const entries = (details.entries ?? []) as DepsDriftEntry[];\n // \"drifted\" = drift !== \"same\", which intentionally includes \"newer\" (ahead of\n // baseline) — parity with the deps audit summary text.\n const drifted = entries.filter((e) => e.drift !== \"same\").length;\n const majorBehind = entries.filter((e) => e.drift === \"major\").length;\n // The real installed-version drift, distinct from declared-range drift. Null\n // when the audit couldn't determine it (no/stale lockfile) — kept null (not 0)\n // so the dashboard shows \"—\" rather than a misleading \"clean\".\n const outdated = details.outdated?.outdated ?? null;\n // How many of those outdated installs are a *major* behind the registry's\n // latest — surfaced separately from the total so the cockpit can show\n // \"N major\" available, distinct from the baseline-drift \"major\" count. Shares\n // the outdated signal's null-when-undetermined semantics.\n const majorOutdated = details.outdated?.major ?? null;\n return { drifted, majorBehind, outdated, majorOutdated };\n}\n","import type { AuditResult } from \"../types.js\";\nimport { normalizeSecurityAdvisory, type SecurityAdvisory } from \"../reports/airtable/websites.js\";\n\ntype SecurityDetails = {\n counts: { low: number; moderate: number; high: number; critical: number };\n advisories?: unknown;\n};\n\n/** True when a security AuditResult carries a counts object. Skipped runs\n * (no pnpm + no npm) have no details and return false. */\nexport function hasSecurityCounts(result: AuditResult): boolean {\n if (result.audit !== \"security\") return false;\n const details = result.details as SecurityDetails | undefined;\n return !!details && typeof details.counts === \"object\";\n}\n\nexport function securityCountsFromResult(result: AuditResult): {\n critical: number;\n high: number;\n moderate: number;\n low: number;\n} {\n if (result.audit !== \"security\") {\n throw new Error(`Expected a 'security' AuditResult, got '${result.audit}'`);\n }\n const details = result.details as SecurityDetails | undefined;\n const c = details?.counts ?? { low: 0, moderate: 0, high: 0, critical: 0 };\n return { critical: c.critical, high: c.high, moderate: c.moderate, low: c.low };\n}\n\n/** The known advisories behind the counts, normalized for persistence. Empty when the\n * run was clean or carried no advisory detail (npm/pnpm sometimes omit it). Malformed\n * entries are dropped via the shared `normalizeSecurityAdvisory`. */\nexport function advisoriesFromResult(result: AuditResult): SecurityAdvisory[] {\n if (result.audit !== \"security\") {\n throw new Error(`Expected a 'security' AuditResult, got '${result.audit}'`);\n }\n const details = result.details as SecurityDetails | undefined;\n const raw = details?.advisories;\n if (!Array.isArray(raw)) return [];\n return raw.map(normalizeSecurityAdvisory).filter((a): a is SecurityAdvisory => a !== null);\n}\n","import type { AuditResult } from \"../types.js\";\nimport type { DomainResult } from \"../reports/airtable/websites.js\";\n\ntype DomainDetails = { resolved: boolean; certDaysRemaining: number | null; checkedAt: string };\n\n/** True when an AuditResult is a `domain` audit carrying a usable details payload (i.e. it\n * actually ran — a \"skip\" for a site with no deployed URL has no details). */\nexport function hasDomainResult(result: AuditResult): boolean {\n if (result.audit !== \"domain\") return false;\n const d = result.details as DomainDetails | undefined;\n return !!d && typeof d.checkedAt === \"string\";\n}\n\n/** Extract the Airtable-writable domain result (cert days + checked-at) from a `domain` audit. */\nexport function domainResultFromAudit(result: AuditResult): DomainResult {\n if (result.audit !== \"domain\") {\n throw new Error(`Expected a 'domain' AuditResult, got '${result.audit}'`);\n }\n const d = result.details as DomainDetails | undefined;\n return {\n certDaysRemaining: typeof d?.certDaysRemaining === \"number\" ? d.certDaysRemaining : null,\n checkedAt: typeof d?.checkedAt === \"string\" ? d.checkedAt : new Date().toISOString(),\n };\n}\n","import type { AuditResult } from \"../types.js\";\nimport type { BrowserAuditFields } from \"../reports/airtable/websites.js\";\n\ntype BrowserDetails = {\n desktopOk: boolean;\n mobileOk: boolean;\n linksOk: boolean;\n reachableOk: boolean;\n titleMetaOk: boolean;\n brokenLinks: number;\n checkedAt: string;\n};\n\n/** True when an AuditResult is a `browser` audit that actually ran (has a details payload — a\n * \"skip\" for a site with no deployed URL has none). */\nexport function hasBrowserResult(result: AuditResult): boolean {\n if (result.audit !== \"browser\") return false;\n const d = result.details as BrowserDetails | undefined;\n return !!d && typeof d.checkedAt === \"string\";\n}\n\n/** Extract the Airtable-writable browser verdicts from a `browser` audit. */\nexport function browserFieldsFromAudit(result: AuditResult): BrowserAuditFields {\n if (result.audit !== \"browser\") {\n throw new Error(`Expected a 'browser' AuditResult, got '${result.audit}'`);\n }\n const d = result.details as BrowserDetails | undefined;\n return {\n desktopOk: d?.desktopOk === true,\n mobileOk: d?.mobileOk === true,\n linksOk: d?.linksOk === true,\n reachableOk: d?.reachableOk === true,\n titleMetaOk: d?.titleMetaOk === true,\n brokenLinks: typeof d?.brokenLinks === \"number\" ? d.brokenLinks : 0,\n checkedAt: typeof d?.checkedAt === \"string\" ? d.checkedAt : new Date().toISOString(),\n };\n}\n","import type { AuditResult } from \"../types.js\";\nimport type { NetlifyDeployResult } from \"../reports/airtable/websites.js\";\n\ntype NetlifyDeployDetails = {\n state: string | null;\n deployedAt: string | null;\n logUrl: string | null;\n checkedAt: string;\n};\n\n/** True when an AuditResult is a `netlify-deploy` audit carrying a usable details\n * payload (i.e. it actually ran — a \"skip\" for a site with no Netlify id / no\n * token has no details). */\nexport function hasNetlifyDeployResult(result: AuditResult): boolean {\n if (result.audit !== \"netlify-deploy\") return false;\n const d = result.details as NetlifyDeployDetails | undefined;\n return !!d && typeof d.checkedAt === \"string\";\n}\n\n/** Extract the Airtable-writable deploy result (state + deployedAt + logUrl +\n * checkedAt) from a `netlify-deploy` audit. */\nexport function netlifyDeployResultFromAudit(result: AuditResult): NetlifyDeployResult {\n if (result.audit !== \"netlify-deploy\") {\n throw new Error(`Expected a 'netlify-deploy' AuditResult, got '${result.audit}'`);\n }\n const d = result.details as NetlifyDeployDetails | undefined;\n return {\n state: typeof d?.state === \"string\" ? d.state : null,\n deployedAt: typeof d?.deployedAt === \"string\" ? d.deployedAt : null,\n logUrl: typeof d?.logUrl === \"string\" ? d.logUrl : null,\n checkedAt: typeof d?.checkedAt === \"string\" ? d.checkedAt : new Date().toISOString(),\n };\n}\n","import type { AuditResult } from \"../types.js\";\nimport type { FunctionHealthResult } from \"../reports/airtable/websites.js\";\n\ntype FunctionHealthDetails = {\n ok: boolean;\n prismic: \"ok\" | \"error\" | \"skipped\" | null;\n forms: unknown;\n checkedAt: string;\n};\n\n/** True when an AuditResult is a `function-health` audit carrying a usable details payload (i.e. it\n * actually ran — a self-skip for an unreachable / non-JSON `/health`, or a site with no deployed\n * URL, has no details, so the writer preserves the prior verdict). */\nexport function hasFunctionHealthResult(result: AuditResult): boolean {\n if (result.audit !== \"function-health\") return false;\n const d = result.details as FunctionHealthDetails | undefined;\n return !!d && typeof d.checkedAt === \"string\";\n}\n\n/** Extract the Airtable-writable function-health verdicts. `functionHealth` from `ok`; `cmsReachable`\n * from the same body's `prismic` sub-status (R2.2): `\"ok\"` → `\"pass\"`, `\"error\"` → `\"fail\"`, and\n * anything else (`\"skipped\"` — a placeholder repo, or a raw `null` from a \"deployed but erroring\"\n * body / an unrecognized value) → `null` — the CMS probe never actually ran, so it must not red CMS\n * reachability for a site that simply hasn't wired Prismic yet. Only `functionHealth` keys off\n * `ok`. */\nexport function functionHealthResultFromAudit(result: AuditResult): FunctionHealthResult {\n if (result.audit !== \"function-health\") {\n throw new Error(`Expected a 'function-health' AuditResult, got '${result.audit}'`);\n }\n const d = result.details as FunctionHealthDetails | undefined;\n const cmsReachable: \"pass\" | \"fail\" | null =\n d?.prismic === \"ok\" ? \"pass\" : d?.prismic === \"error\" ? \"fail\" : null;\n // `forms` is untyped on the details payload (unknown) — validate defensively. A boolean\n // `turnstile` inside an object → concrete verdict; anything else (null forms from an older\n // site package or a \"deployed but erroring\" body, a malformed shape) → null: the widget\n // state is simply unknown this run, never a fail. Powers the Require-Turnstile guardrail.\n const formsRaw = d?.forms;\n const turnstileFlag =\n formsRaw && typeof formsRaw === \"object\"\n ? (formsRaw as Record<string, unknown>)[\"turnstile\"]\n : undefined;\n const turnstileWidget: \"pass\" | \"fail\" | null =\n typeof turnstileFlag === \"boolean\" ? (turnstileFlag ? \"pass\" : \"fail\") : null;\n return {\n functionHealth: d?.ok === true ? \"pass\" : \"fail\",\n cmsReachable,\n turnstileWidget,\n checkedAt: typeof d?.checkedAt === \"string\" ? d.checkedAt : new Date().toISOString(),\n };\n}\n","import type { AuditResult } from \"../types.js\";\nimport type { SmokeResult } from \"../reports/airtable/websites.js\";\n\ntype SmokeDetails = { ok: \"pass\" | \"fail\"; checkedAt: string };\n\n/** True when an AuditResult is a `smoke` audit that actually ran (has details with\n * a checkedAt — a \"skip\" for a missing `pnpm`/`test:smoke` script has none, so the\n * writer preserves the prior verdict). */\nexport function hasSmokeResult(result: AuditResult): boolean {\n if (result.audit !== \"smoke\") return false;\n const d = result.details as SmokeDetails | undefined;\n return !!d && typeof d.checkedAt === \"string\";\n}\n\n/** Extract the Airtable-writable smoke verdict (pass/fail + checked-at). */\nexport function smokeResultFromAudit(result: AuditResult): SmokeResult {\n if (result.audit !== \"smoke\") {\n throw new Error(`Expected a 'smoke' AuditResult, got '${result.audit}'`);\n }\n const d = result.details as SmokeDetails | undefined;\n return {\n ok: d?.ok === \"fail\" ? \"fail\" : \"pass\",\n checkedAt: typeof d?.checkedAt === \"string\" ? d.checkedAt : new Date().toISOString(),\n };\n}\n","import type { AuditResult } from \"../types.js\";\nimport type { FormE2eResult } from \"../reports/airtable/websites.js\";\n\ntype FormE2eDetails = { ok: \"pass\" | \"fail\" | null; formPresent: boolean; checkedAt: string };\n\n/** True when an AuditResult is a `form-e2e` audit that actually RAN (has details\n * with a checkedAt). Both a real verdict AND the no-form n/a case carry a checkedAt,\n * so both persist; only a no-deployed-URL skip (no details) is preserved-prior. */\nexport function hasFormE2eResult(result: AuditResult): boolean {\n if (result.audit !== \"form-e2e\") return false;\n const d = result.details as FormE2eDetails | undefined;\n return !!d && typeof d.checkedAt === \"string\";\n}\n\n/** Extract the Airtable-writable form-e2e verdict (pass/fail/null + checked-at). */\nexport function formE2eResultFromAudit(result: AuditResult): FormE2eResult {\n if (result.audit !== \"form-e2e\") {\n throw new Error(`Expected a 'form-e2e' AuditResult, got '${result.audit}'`);\n }\n const d = result.details as FormE2eDetails | undefined;\n const ok = d?.ok === \"pass\" ? \"pass\" : d?.ok === \"fail\" ? \"fail\" : null;\n return {\n ok,\n checkedAt: typeof d?.checkedAt === \"string\" ? d.checkedAt : new Date().toISOString(),\n };\n}\n","import type { FieldSet } from \"airtable\";\nimport type { AuditResult } from \"../types.js\";\nimport type { AirtableBase } from \"../reports/airtable/client.js\";\nimport type { HealthMirror } from \"./health-mirror.js\";\nimport { TURSO_IS_AUTHORITATIVE } from \"../db/freeze.js\";\nimport { type WebsiteRow, siteSlug, updateAuditFields } from \"../reports/airtable/websites.js\";\nimport type {\n A11yCounts,\n DepsCounts,\n SecurityCounts,\n SecurityAdvisory,\n DomainResult,\n BrowserAuditFields,\n NetlifyDeployResult,\n FunctionHealthResult,\n SmokeResult,\n FormE2eResult,\n} from \"../reports/airtable/websites.js\";\nimport type { LighthouseScoreWriteback } from \"../reports/types.js\";\nimport { hasRealScores, lighthouseScoresFromResult } from \"./lighthouse-airtable.js\";\nimport { hasA11yCounts, a11yCountsFromResult } from \"./a11y-airtable.js\";\nimport { hasDepsCounts, depsCountsFromResult } from \"./deps-airtable.js\";\nimport {\n hasSecurityCounts,\n securityCountsFromResult,\n advisoriesFromResult,\n} from \"./security-airtable.js\";\nimport { hasDomainResult, domainResultFromAudit } from \"./domain-airtable.js\";\nimport { hasBrowserResult, browserFieldsFromAudit } from \"./browser-airtable.js\";\nimport { hasNetlifyDeployResult, netlifyDeployResultFromAudit } from \"./netlify-deploy-airtable.js\";\nimport {\n hasFunctionHealthResult,\n functionHealthResultFromAudit,\n} from \"./function-health-airtable.js\";\nimport { hasSmokeResult, smokeResultFromAudit } from \"./smoke-airtable.js\";\nimport { hasFormE2eResult, formE2eResultFromAudit } from \"./form-e2e-airtable.js\";\nimport { detectAuditEvents } from \"./fleet-event-detectors.js\";\nimport type { FleetEvent } from \"../db/fleet-events.js\";\n\ntype WriteSummary = {\n siteName: string;\n writes: Array<{\n audit:\n | \"lighthouse\"\n | \"a11y\"\n | \"deps\"\n | \"security\"\n | \"github-signals\"\n | \"domain\"\n | \"browser\"\n | \"netlify-deploy\"\n | \"function-health\"\n | \"smoke\"\n | \"form-e2e\"\n // Not an audit: the nightly Prismic model sweep reuses this result shape so\n // its write-back reports through the same `FLEET_WRITE_SUMMARY` line every\n // other fleet writer emits, rather than inventing a second contract for CI\n // to grep.\n | \"prismic-models\";\n counts: object;\n }>;\n /** Fleet-activity events detected from this site's prior row vs the fresh audits.\n * Optional: only the fleet path records them; the single-site path ignores them. */\n events?: FleetEvent[];\n /** The Websites rec id + the merged FieldSet actually written — what the\n * Phase 3 Turso mirror consumes, so mirror and Airtable write share ONE\n * payload. Populated by writeAuditsToAirtable; other WriteSummary\n * producers (prismic-models, github-signals) don't carry them. */\n siteId?: string;\n fields?: FieldSet;\n};\n\n/** Orchestrates the per-audit Airtable writes for `audit --write-airtable`.\n * Extracted from the CLI command so it can be unit-tested with a fake base\n * and so adding new audit types is a one-line addition here rather than\n * growing the CLI handler.\n *\n * Throws (with .exitCode set) on the failure modes the CLI surfaces today:\n * - 2: --only ran without lighthouse, or no Websites row matched the slug\n * - 1: lighthouse ran but produced no real scores (infrastructure failure).\n * The a11y/deps/security writes still complete FIRST — a Lighthouse\n * miss flags the site without discarding its other audit data.\n *\n * Precedence note: the Websites-row lookup (exitCode 2) is checked BEFORE the\n * no-scores gate (exitCode 1), so the rare no-row + no-scores combo surfaces\n * as exitCode 2. */\nexport async function writeAuditsToAirtable(args: {\n base: AirtableBase;\n websites: WebsiteRow[];\n slug: string;\n results: AuditResult[];\n}): Promise<WriteSummary> {\n const { base, websites, slug, results } = args;\n\n // Lighthouse is OPTIONAL. The checkout-free `--only lighthouse,domain,browser` nightly includes\n // it, but a standalone `--only security` (checkout-ful) sweep legitimately has none. We write\n // whatever audits produced values; only the lighthouse-MISS flag below is lighthouse-specific\n // (so a real Lighthouse infra failure still reds the run without discarding other audit data).\n const lhResult = results.find((r) => r.audit === \"lighthouse\");\n const target = websites.find((w) => siteSlug(w.name) === slug);\n if (!target) {\n throw Object.assign(new Error(`No Websites row matched slug \"${slug}\"`), { exitCode: 2 });\n }\n\n const writes: WriteSummary[\"writes\"] = [];\n const 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\n // Collect every audit that produced real values into ONE merged input, then do a\n // SINGLE atomic Airtable update (was: up to four sequential updates on the same\n // row — a mid-sequence failure left it half-written yet reported fully failed, at\n // 4× the request volume). Lighthouse is the most timeout-prone audit: a Lighthouse\n // miss must NOT discard the site's valid a11y/deps/security results (morning-brief\n // 2026-06-10 MEDIUM-E). So include Lighthouse scores only when real, include the\n // other audits whenever present, write all of them in one update, then — if\n // Lighthouse missed — throw AFTER that atomic write so the site is still flagged\n // (exitCode 1 / collected in FleetWriteResult.failed) without losing its other data.\n const lhHasScores = lhResult ? hasRealScores(lhResult) : false;\n if (lhResult && lhHasScores) {\n const scores = lighthouseScoresFromResult(lhResult);\n audits.scores = scores;\n writes.push({ audit: \"lighthouse\", counts: scores });\n }\n\n const a11y = results.find((r) => r.audit === \"a11y\");\n if (a11y && hasA11yCounts(a11y)) {\n const counts = a11yCountsFromResult(a11y);\n audits.a11y = counts;\n writes.push({ audit: \"a11y\", counts });\n }\n\n const deps = results.find((r) => r.audit === \"deps\");\n if (deps && hasDepsCounts(deps)) {\n const counts = depsCountsFromResult(deps);\n audits.deps = counts;\n writes.push({ audit: \"deps\", counts });\n }\n\n const sec = results.find((r) => r.audit === \"security\");\n if (sec && hasSecurityCounts(sec)) {\n const counts = securityCountsFromResult(sec);\n audits.security = counts;\n // Persist the advisory list alongside the counts so the dashboard can show which packages\n // are vulnerable. An empty array (clean run) clears any stale list.\n audits.securityAdvisories = advisoriesFromResult(sec);\n writes.push({ audit: \"security\", counts });\n }\n\n const dom = results.find((r) => r.audit === \"domain\");\n if (dom && hasDomainResult(dom)) {\n const result = domainResultFromAudit(dom);\n audits.domain = result;\n writes.push({ audit: \"domain\", counts: result });\n }\n\n const browser = results.find((r) => r.audit === \"browser\");\n if (browser && hasBrowserResult(browser)) {\n const fields = browserFieldsFromAudit(browser);\n audits.browser = fields;\n writes.push({ audit: \"browser\", counts: fields });\n }\n\n const netlifyDeploy = results.find((r) => r.audit === \"netlify-deploy\");\n if (netlifyDeploy && hasNetlifyDeployResult(netlifyDeploy)) {\n const result = netlifyDeployResultFromAudit(netlifyDeploy);\n audits.netlifyDeploy = result;\n writes.push({ audit: \"netlify-deploy\", counts: result });\n }\n\n const functionHealth = results.find((r) => r.audit === \"function-health\");\n if (functionHealth && hasFunctionHealthResult(functionHealth)) {\n const result = functionHealthResultFromAudit(functionHealth);\n audits.functionHealth = result;\n writes.push({ audit: \"function-health\", counts: result });\n }\n\n const smoke = results.find((r) => r.audit === \"smoke\");\n if (smoke && hasSmokeResult(smoke)) {\n const result = smokeResultFromAudit(smoke);\n audits.smoke = result;\n writes.push({ audit: \"smoke\", counts: result });\n }\n\n const formE2e = results.find((r) => r.audit === \"form-e2e\");\n if (formE2e && hasFormE2eResult(formE2e)) {\n const result = formE2eResultFromAudit(formE2e);\n audits.formE2e = result;\n writes.push({ audit: \"form-e2e\", counts: result });\n }\n\n // One atomic write of everything that ran. Skip the call only if there is nothing\n // to write at all (no real scores AND no other audit produced values) — an empty\n // update is a wasted request.\n let fields: FieldSet = {};\n if (Object.keys(audits).length > 0) {\n fields = await updateAuditFields(base, target.id, audits);\n }\n\n // Detect fleet-activity transitions from the prior row (`target`, loaded before this\n // write) vs the fresh audits. Computed here where both are in hand; recorded by the\n // caller (fleet path) — single-site callers simply ignore `events`.\n const events = detectAuditEvents(\n target,\n {\n ...(audits.security !== undefined ? { security: audits.security } : {}),\n ...(audits.domain !== undefined ? { domain: audits.domain } : {}),\n },\n new Date().toISOString(),\n );\n\n // Lighthouse-miss flag: only when lighthouse WAS requested (in results) but produced no scores —\n // an infra failure worth reding the run, AFTER persisting the other audits. A sweep that never\n // ran lighthouse (e.g. `--only security`) skips this entirely.\n if (lhResult && !lhHasScores) {\n // Enumerate what WAS persisted so the failure (surfaced to the single-site\n // CLI operator via console.error) reads as a partial write, not a total one.\n const persisted = writes.map((w) => w.audit);\n throw Object.assign(\n new Error(\n `Lighthouse audit produced no scores; ${\n persisted.length ? `wrote ${persisted.join(\"/\")} but refused Lighthouse` : \"wrote nothing\"\n }. Summary: ${lhResult.summary}`,\n ),\n { exitCode: 1 },\n );\n }\n\n return { siteName: target.name, writes, events, siteId: target.id, fields };\n}\n\nexport type FleetWriteResult = {\n written: WriteSummary[];\n failed: Array<{ slug: string; error: string }>;\n /** Turso write-through counts (#539 Phase 3 dual-write). Present ONLY when a\n * mirror was wired — absent means mirroring was not attempted (no libSQL\n * creds), which must stay distinguishable from `mirrored=0` (a wired mirror\n * that landed nothing = the fleet-wide outage alarm). */\n mirrored?: number;\n mirrorFailed?: number;\n /** Mirror UPDATEs that matched no site_health row (site created in Airtable\n * after the last hourly import). Not a failure — the row converges on the\n * next sync — but not mirrored either: counted apart so `mirrored=` stays\n * an honest Phase 5 cutover signal instead of overcounting by the no-row\n * sites. */\n mirrorMissed?: number;\n};\n\n/** Render the fleet write-back outcome for the CLI/CI. Beyond the human-readable\n * lines, it emits a single deterministic, machine-parseable line —\n * `FLEET_WRITE_SUMMARY wrote=N failed=M total=T` — that the nightly workflow\n * greps to decide pass/fail. Keying CI on this line (not the prose, and not a\n * \"wrote ≥ 1\" heuristic) lets the gate tolerate a single known flake while\n * still reding on a total or mass write-back failure. */\n/** Did this sweep fail, for exit-code purposes (#612)?\n *\n * Pre-freeze, only an Airtable write failure counts. Mirror failures and missed\n * rows are real but survivable: the hourly import converges them, and going red\n * over a transient the system already handles would train the alarm to be\n * ignored.\n *\n * Post-freeze there is no import to converge anything, so all three become\n * fatal — including an ABSENT mirror, which is the worst of the three and the\n * easiest to misread as success: no counters at all means no libSQL creds,\n * which means the sweep wrote nothing to the only store there is.\n *\n * Note what this deliberately does NOT change: `writeFleetAuditsToAirtable`\n * still catches per-site mirror failures rather than throwing. One bad site\n * must not abort a 44-site sweep. This gates the RUN, not the loop. */\nexport function fleetWriteFailed(\n result: FleetWriteResult,\n strict: boolean = TURSO_IS_AUTHORITATIVE,\n): boolean {\n if (result.failed.length > 0) return true;\n if (!strict) return false;\n if (result.mirrored === undefined) return true; // no mirror was wired at all\n return (result.mirrorFailed ?? 0) > 0 || (result.mirrorMissed ?? 0) > 0;\n}\n\nexport function formatFleetWriteSummary(result: FleetWriteResult): string {\n const wrote = result.written.length;\n const failed = result.failed.length;\n const total = wrote + failed;\n let out = `→ wrote ${wrote} site(s) to Airtable`;\n if (failed > 0) {\n out += `\\n⚠ ${failed} site(s) not written: ${result.failed\n .map((f) => `${f.slug} (${f.error})`)\n .join(\"; \")}`;\n }\n out += `\\nFLEET_WRITE_SUMMARY wrote=${wrote} failed=${failed} total=${total}`;\n // Mirror counts APPEND so the fleet workflows' `grep -oE \"FLEET_WRITE_SUMMARY\n // wrote=... total=[0-9]+\"` extraction still matches its prefix untouched.\n if (result.mirrored !== undefined) {\n out += ` mirrored=${result.mirrored} mirror_failed=${result.mirrorFailed ?? 0}`;\n out += ` mirror_missed=${result.mirrorMissed ?? 0}`;\n }\n return out;\n}\n\n/** Write each site's pooled audit results back to its own Websites row,\n * best-effort. Results are grouped by `result.site` (the slug the fleet\n * inventory stamped as Site.name). A per-site failure (no scores, no matching\n * row) is collected — not thrown — so one bad site never aborts the batch. */\nexport async function writeFleetAuditsToAirtable(args: {\n base: AirtableBase;\n websites: WebsiteRow[];\n results: AuditResult[];\n /** Optional Turso write-through (#539 Phase 3 dual-write). Each site's\n * just-written FieldSet mirrors into site_health right after its Airtable\n * write; a mirror failure is counted, never thrown — Airtable stays\n * authoritative and the hourly sync converges what the mirror missed.\n * (The lighthouse-miss partial write lands in `failed` and is deliberately\n * NOT mirrored — same convergence path.) */\n mirror?: HealthMirror;\n}): Promise<FleetWriteResult> {\n const { base, websites, results, mirror } = args;\n\n const bySlug = new Map<string, AuditResult[]>();\n for (const r of results) {\n const arr = bySlug.get(r.site) ?? [];\n arr.push(r);\n bySlug.set(r.site, arr);\n }\n\n const written: WriteSummary[] = [];\n const failed: FleetWriteResult[\"failed\"] = [];\n let mirrored = 0;\n let mirrorFailed = 0;\n let mirrorMissed = 0;\n // Serial on purpose: even at one (now atomic) update call per site, Airtable's\n // ~5 req/sec limit means a Promise.all fan-out across the fleet would burst and\n // trip 429s (silently filed as failures). Below a few dozen sites, serial trades\n // wall-clock for safety. (morning-brief 2026-06-09 MEDIUM-3.) Add a bounded pool\n // when the fleet grows.\n for (const [slug, siteResults] of bySlug) {\n try {\n const summary = await writeAuditsToAirtable({ base, websites, slug, results: siteResults });\n written.push(summary);\n if (mirror && summary.siteId && summary.fields && Object.keys(summary.fields).length > 0) {\n try {\n if (await mirror(summary.siteId, summary.fields)) mirrored++;\n else mirrorMissed++;\n } catch (e) {\n mirrorFailed++;\n console.error(`[health-mirror] ${slug}: ${(e as Error).message}`);\n }\n }\n } catch (e) {\n failed.push({ slug, error: (e as Error).message });\n }\n }\n return { written, failed, ...(mirror ? { mirrored, mirrorFailed, mirrorMissed } : {}) };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAWO,SAAS,cAAc,QAA8B;AAC1D,MAAI,OAAO,UAAU,OAAQ,QAAO;AACpC,QAAM,UAAU,OAAO;AACvB,SAAO,OAAO,SAAS,oBAAoB;AAC7C;AAEO,SAAS,qBAAqB,QA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;","names":["fields"]}
|
|
@@ -322,6 +322,41 @@ var MIGRATIONS = [
|
|
|
322
322
|
CREATE INDEX IF NOT EXISTS idx_prospect_audits_created
|
|
323
323
|
ON prospect_audits (created_at DESC);
|
|
324
324
|
`
|
|
325
|
+
},
|
|
326
|
+
{
|
|
327
|
+
// #609 (#539 Phase 5): the digest's prior-run snapshot moves off Airtable.
|
|
328
|
+
// Unlike the rest of Phase 5 this is a MIGRATION, not a dual-write — there
|
|
329
|
+
// is no Airtable counterpart left afterwards, so parity does not cover it.
|
|
330
|
+
//
|
|
331
|
+
// A single row holding the whole snapshot as JSON, keyed by a constant id.
|
|
332
|
+
// Both readers (runDigest's diff and the fleet homepage's NEW badges) need
|
|
333
|
+
// the ENTIRE map, so a keyed table would buy nothing on reads and its
|
|
334
|
+
// "give me everything" query would be a raw scan needing a justified entry
|
|
335
|
+
// in the EXPLAIN gate's allowlist. One row by primary key needs neither.
|
|
336
|
+
id: "0011_digest_state",
|
|
337
|
+
sql: `
|
|
338
|
+
CREATE TABLE IF NOT EXISTS digest_state (
|
|
339
|
+
id TEXT PRIMARY KEY,
|
|
340
|
+
snapshot TEXT NOT NULL,
|
|
341
|
+
updated_at TEXT
|
|
342
|
+
);
|
|
343
|
+
`
|
|
344
|
+
},
|
|
345
|
+
{
|
|
346
|
+
// form_type was the one SubmissionFilter key with an equality predicate and no
|
|
347
|
+
// index — countSubmissionsFiltered({formType}) raw-scanned `submissions`, twice
|
|
348
|
+
// per load of the submissions page. It shipped green because the EXPLAIN gate
|
|
349
|
+
// named its scenarios by hand and never wrote one for this shape; the gate is
|
|
350
|
+
// now driven by a filter matrix, which is what surfaced it.
|
|
351
|
+
//
|
|
352
|
+
// `submissions` is the one unbounded-growth table in the schema — append-only,
|
|
353
|
+
// one row per fleet lead forever — and Turso meters ROW SCANS, so this is the
|
|
354
|
+
// cost that grows without a ceiling.
|
|
355
|
+
id: "0012_submissions_form_type_index",
|
|
356
|
+
sql: `
|
|
357
|
+
CREATE INDEX IF NOT EXISTS idx_submissions_form_type
|
|
358
|
+
ON submissions (form_type);
|
|
359
|
+
`
|
|
325
360
|
}
|
|
326
361
|
];
|
|
327
362
|
|
|
@@ -356,4 +391,4 @@ async function runMigrations(client) {
|
|
|
356
391
|
export {
|
|
357
392
|
runMigrations
|
|
358
393
|
};
|
|
359
|
-
//# sourceMappingURL=chunk-
|
|
394
|
+
//# sourceMappingURL=chunk-MFHS7IQ2.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/db/migrations.ts","../src/db/migrate.ts"],"sourcesContent":["/** Ordered, append-only list of standard-SQL migration scripts. Each runs once,\n * tracked by `id` in the `_migrations` table (see migrate.ts). Statements use\n * IF NOT EXISTS so even a partial re-apply is safe. Never edit a shipped script —\n * add a new one. Every statement in a script MUST be independently idempotent:\n * `migrate.ts` runs each script via `executeMultiple`, which is NOT transactional,\n * so a mid-script failure can leave earlier statements applied and the id unrecorded\n * — a re-run then re-executes the whole script. Standard SQLite SQL only (no\n * Turso-specific syntax) so the host stays a connection-string swap. */\nexport type Migration = { id: string; sql: string };\n\nexport const MIGRATIONS: Migration[] = [\n {\n id: \"0001_init\",\n sql: `\n CREATE TABLE IF NOT EXISTS submissions (\n id TEXT PRIMARY KEY,\n submission_id INTEGER,\n site_id TEXT NOT NULL,\n form_type TEXT NOT NULL,\n name TEXT NOT NULL,\n email TEXT NOT NULL,\n phone TEXT,\n message TEXT,\n extra_fields TEXT,\n source_url TEXT,\n utm TEXT,\n submitted_at TEXT,\n status TEXT NOT NULL DEFAULT 'new',\n notify_status TEXT NOT NULL DEFAULT 'skipped',\n resend_message_id TEXT\n );\n CREATE INDEX IF NOT EXISTS idx_submissions_site_submitted\n ON submissions (site_id, submitted_at DESC);\n CREATE INDEX IF NOT EXISTS idx_submissions_status\n ON submissions (status);\n CREATE TABLE IF NOT EXISTS spam_screenouts (\n site_id TEXT NOT NULL,\n date TEXT NOT NULL,\n honeypot INTEGER NOT NULL DEFAULT 0,\n too_fast INTEGER NOT NULL DEFAULT 0,\n marked_spam INTEGER NOT NULL DEFAULT 0,\n PRIMARY KEY (site_id, date)\n );\n `,\n },\n {\n id: \"0002_fleet_events\",\n sql: `\n CREATE TABLE IF NOT EXISTS fleet_events (\n id TEXT PRIMARY KEY,\n ts TEXT NOT NULL,\n type TEXT NOT NULL,\n site_id TEXT,\n site_name TEXT,\n summary TEXT NOT NULL,\n data TEXT,\n created_at TEXT NOT NULL\n );\n CREATE INDEX IF NOT EXISTS idx_fleet_events_ts ON fleet_events (ts);\n `,\n },\n {\n id: \"0003_add_spam_score\",\n // SQLite `ADD COLUMN` has no `IF NOT EXISTS`, so it is NOT self-idempotent: if the\n // `_migrations` marker is lost after the column is added (crash between statement\n // and marker write), a re-run would throw `duplicate column name`. `migrate.ts`\n // recognizes that error as already-applied and records the marker, keeping the\n // runner idempotent (see `isAlreadyAppliedError`).\n sql: `ALTER TABLE submissions ADD COLUMN spam_score REAL;`,\n },\n {\n id: \"0004_add_spam_reason\",\n sql: `ALTER TABLE submissions ADD COLUMN spam_reason TEXT;`,\n },\n {\n // Outcome of the newsletter fan-out (site webhook + Mailchimp). Before this the\n // results were console.error-only, so a rotated Mailchimp key or an outage would\n // silently stop signups reaching the audience with no trace anywhere the operator\n // looks — the row still read `notify=sent`, healthy. Same non-idempotent\n // ADD COLUMN caveat as 0003.\n id: \"0005_add_fanout_status\",\n sql: `ALTER TABLE submissions ADD COLUMN fanout_status TEXT;`,\n },\n {\n // Phase 0 of the Airtable → Turso migration (#539): a lead whose SITE LOOKUP\n // fails must still land somewhere durable. On 2026-08-17 the Airtable quota\n // outage made `getWebsiteBySlug` throw before `createSubmission` ran, so every\n // lead in the window 502'd away unrecorded — while THIS store (which holds\n // submissions) was healthy the whole time. Rows here are written only on that\n // path and replayed through the normal pipeline once the lookup recovers\n // (`db replay-deadletters`), producing an ordinary submissions row with real\n // spam classification and notify. Deliberately a separate table rather than a\n // nullable `submissions.site_id`: site_id is NOT NULL, every reader assumes a\n // real rec id, and a sentinel would collapse dashboard grouping (the \"\" key\n // hazard audit.ts already documents).\n //\n // `turnstile` stores the verification COMPUTED AT RECEIPT ({outcome, hostname}\n // JSON) — tokens expire in 300s, so replay could never re-verify; it replays\n // with the answer we already had.\n id: \"0006_submission_deadletter\",\n sql: `\n CREATE TABLE IF NOT EXISTS submission_deadletter (\n id TEXT PRIMARY KEY,\n site_slug TEXT NOT NULL,\n payload TEXT NOT NULL,\n turnstile TEXT NOT NULL,\n error TEXT NOT NULL,\n received_at TEXT NOT NULL,\n replayed_at TEXT,\n replay_outcome TEXT,\n replay_submission_id TEXT\n );\n CREATE INDEX IF NOT EXISTS idx_deadletter_unreplayed\n ON submission_deadletter (replayed_at);\n `,\n },\n {\n // Phase 1.2 of the Airtable → Turso migration (#539): the fleet-state tables.\n // Split by WRITER, not topic (design D2, confirmed by the 2026-08-23 writer\n // map — every code-written column has exactly one writer):\n // sites — operator (dashboard editor / console / launch flow)\n // site_health — the nightly audit write-back, one batched upsert\n // site_schedule — updateNextDueDates (report cron, derived)\n // reports — report drafting + the operator approve flow\n // PKs are the Airtable `rec…` ids (design D1): 278+ submissions rows already\n // reference them, and the parity harness diffs the two stores row-for-row.\n //\n // Naming: snake_case throughout; Airtable's misspellings (\"maintenence\") and\n // display quirks die here. `sites.legacy` is a JSON object holding the 33\n // populated-but-code-unreferenced columns (launch-era checklist, hosting\n // reference cells) keyed by their original Airtable column name — data kept,\n // schema not fossilized. The plaintext DNS/cms credential cells deliberately\n // do NOT migrate at all (operator ruling 2026-08-23); they live on only in\n // the frozen base. `site_health.analytics_soft_fail_at` is the column code\n // always wanted (\"Analytics soft-fail at\") but no operator ever created in\n // Airtable — it ships real here.\n //\n // reports.checklist is JSON keyed by the STABLE checklist key (\"deploy\",\n // \"cms\", …, from src/reports/checklist.ts), not the Airtable column name —\n // the importer translates, so \"Test: Verified After Updates\" stops leaking\n // its legacy name into a second store.\n id: \"0007_fleet_state\",\n sql: `\n CREATE TABLE IF NOT EXISTS sites (\n id TEXT PRIMARY KEY,\n slug TEXT NOT NULL UNIQUE,\n name TEXT NOT NULL,\n url TEXT,\n status TEXT,\n point_of_contact TEXT,\n maintenance_freq TEXT,\n testing_freq TEXT,\n maintenance_day TEXT,\n testing_day TEXT,\n ga4_property_id TEXT,\n search_query TEXT,\n search_console_property TEXT,\n git_repo TEXT,\n netlify_id TEXT,\n report_recipients_to TEXT,\n report_recipients_cc TEXT,\n copy_intro TEXT,\n copy_contact TEXT,\n copy_footer TEXT,\n newsletter_webhook TEXT,\n mailchimp_api_key TEXT,\n mailchimp_audience_id TEXT,\n notify_routing TEXT,\n require_turnstile INTEGER NOT NULL DEFAULT 0,\n accepted_watch_conditions TEXT,\n prismic_ack_until TEXT,\n launched_at TEXT,\n header_image BLOB,\n header_image_filename TEXT,\n header_image_type TEXT,\n header_image_generated_at TEXT,\n legacy TEXT\n );\n CREATE INDEX IF NOT EXISTS idx_sites_status ON sites (status);\n\n CREATE TABLE IF NOT EXISTS site_health (\n site_id TEXT PRIMARY KEY,\n p_score INTEGER,\n r_score INTEGER,\n bp_score INTEGER,\n seo_score INTEGER,\n lighthouse_at TEXT,\n a11y_violations INTEGER,\n deps_drifted INTEGER,\n deps_major_behind INTEGER,\n deps_outdated INTEGER,\n deps_major_outdated INTEGER,\n vulns_critical INTEGER,\n vulns_high INTEGER,\n vulns_moderate INTEGER,\n vulns_low INTEGER,\n security_audit_at TEXT,\n security_advisories TEXT,\n auto_fix_attempts INTEGER,\n analytics_soft_fail_at TEXT,\n cert_days_remaining INTEGER,\n domain_checked_at TEXT,\n deploy_status TEXT,\n last_deploy_at TEXT,\n deploy_log_url TEXT,\n deploy_checked_at TEXT,\n function_health TEXT,\n cms_reachable TEXT,\n turnstile_widget TEXT,\n function_health_checked_at TEXT,\n crossbrowser_ok INTEGER,\n mobile_ok INTEGER,\n links_ok INTEGER,\n broken_links INTEGER,\n browser_checked_at TEXT,\n uptime_reachable TEXT,\n titles_meta_ok TEXT,\n smoke_ok TEXT,\n last_smoke_at TEXT,\n form_e2e_ok TEXT,\n form_e2e_checked_at TEXT,\n renovate_failing_cis INTEGER,\n default_branch_ci TEXT,\n last_commit_at TEXT,\n github_signals_at TEXT,\n prismic_models TEXT,\n prismic_models_checked_at TEXT,\n prismic_models_drift TEXT\n );\n\n CREATE TABLE IF NOT EXISTS site_schedule (\n site_id TEXT PRIMARY KEY,\n next_maintenance_at TEXT,\n next_testing_at TEXT,\n computed_at TEXT\n );\n\n CREATE TABLE IF NOT EXISTS reports (\n id TEXT PRIMARY KEY,\n site_id TEXT,\n report_id TEXT,\n report_type TEXT,\n period TEXT,\n period_start TEXT,\n period_end TEXT,\n completed_on TEXT,\n lighthouse_performance INTEGER,\n lighthouse_accessibility INTEGER,\n lighthouse_best_practices INTEGER,\n lighthouse_seo INTEGER,\n ga_users_current INTEGER,\n ga_users_previous INTEGER,\n search_found_page1 INTEGER,\n search_position REAL,\n last_tested_date TEXT,\n commentary TEXT,\n subject_override TEXT,\n draft_ready INTEGER NOT NULL DEFAULT 0,\n approved_to_send INTEGER NOT NULL DEFAULT 0,\n approved_at TEXT,\n approved_by TEXT,\n send_override INTEGER NOT NULL DEFAULT 0,\n override_reason TEXT,\n override_by TEXT,\n override_at TEXT,\n sent_at TEXT,\n delivery_status TEXT,\n resend_message_id TEXT,\n checklist TEXT,\n checklist_auto_evidence TEXT,\n rendered_html TEXT\n );\n CREATE INDEX IF NOT EXISTS idx_reports_site ON reports (site_id, period_start DESC);\n `,\n },\n {\n // Indexes the EXPLAIN-query-plan gate (tests/db/query-plans.test.ts) proved the\n // hot paths need — each serves a named query shape that otherwise full-scans\n // submissions, the one unbounded-growth table:\n // submitted_at — every windowed read (/submissions default page, digest\n // per-site counts, duplicate/repeat-sender scans)\n // resend_message_id — the resend-webhook bounce lookup (markNotifyBouncedByMessageId)\n // submission_id — createSubmission's MAX(submission_id)+1 display number,\n // O(1) off the index instead of a scan per insert\n // spam_reason (partial, covering) — listSpamReasonsFiltered's facet tally\n // reads ONLY spam_reason WHERE spam_reason IS NOT NULL;\n // partial keeps it to the spam subset\n // spam_screenouts(date) — listScreenOutsSince windows on date, which the\n // (site_id, date) PK can't serve\n id: \"0008_query_plan_indexes\",\n sql: `\n CREATE INDEX IF NOT EXISTS idx_submissions_submitted\n ON submissions (submitted_at DESC);\n CREATE INDEX IF NOT EXISTS idx_submissions_spam_reason\n ON submissions (spam_reason) WHERE spam_reason IS NOT NULL;\n CREATE INDEX IF NOT EXISTS idx_submissions_resend_message\n ON submissions (resend_message_id);\n CREATE INDEX IF NOT EXISTS idx_submissions_display_number\n ON submissions (submission_id);\n CREATE INDEX IF NOT EXISTS idx_screenouts_date\n ON spam_screenouts (date);\n `,\n },\n {\n // Prospect audits (spec 2026-08-24): one row per `prospect-audit` CLI run.\n // `token` is the unguessable public handle for GET /r/{token}; `result_json`\n // is the full ProspectAuditResult, re-rendered on every request so report\n // styling updates apply to already-shared links.\n id: \"0009_prospect_audits\",\n sql: `\n CREATE TABLE IF NOT EXISTS prospect_audits (\n id TEXT PRIMARY KEY,\n token TEXT NOT NULL UNIQUE,\n url TEXT NOT NULL,\n business TEXT,\n created_at TEXT NOT NULL,\n status TEXT NOT NULL DEFAULT 'complete',\n result_json TEXT NOT NULL\n );\n `,\n },\n {\n // Cockpit /audits listing page (spec 2026-08-25, Piece 5):\n // listRecentProspectAudits orders by created_at DESC with no WHERE clause —\n // without this index that's a raw SCAN of prospect_audits followed by a temp\n // b-tree sort, which the EXPLAIN-query-plan gate (tests/db/query-plans.test.ts)\n // fails the build on. DESC matches the query's own ORDER BY so SQLite can walk\n // the index directly instead of sorting.\n id: \"0010_prospect_audits_created_index\",\n sql: `\n CREATE INDEX IF NOT EXISTS idx_prospect_audits_created\n ON prospect_audits (created_at DESC);\n `,\n },\n];\n","import type { Client } from \"@libsql/client\";\nimport { MIGRATIONS } from \"./migrations.js\";\n\n/** True when an error means \"this DDL was already applied\" and re-applying is a\n * no-op we can safely ignore. `CREATE ... IF NOT EXISTS` never throws, but SQLite\n * `ALTER TABLE ... ADD COLUMN` has no `IF NOT EXISTS`, so a re-run after a lost\n * `_migrations` marker throws `duplicate column name: …`. Treating that as\n * already-applied keeps `runMigrations` idempotent for `ADD COLUMN` migrations —\n * without it a lost marker would boot-loop `openDb()` on every call. */\nfunction isAlreadyAppliedError(err: unknown): boolean {\n const message = err instanceof Error ? err.message : String(err);\n return /duplicate column name/i.test(message);\n}\n\n/** Apply every not-yet-applied migration in order against a raw libSQL client,\n * tracking applied ids in `_migrations`. Idempotent: ids already present are\n * skipped, the DDL uses IF NOT EXISTS where it can, and an already-applied\n * `ADD COLUMN` (recognized by its error) is swallowed so the marker is still\n * recorded. Returns the ids applied this run. Runs on every openDb() — cheap\n * (one indexed SELECT) and the gate every fresh Turso database needs before its\n * first write. */\nexport async function runMigrations(client: Client): Promise<string[]> {\n await client.execute(\n \"CREATE TABLE IF NOT EXISTS _migrations (id TEXT PRIMARY KEY, applied_at TEXT NOT NULL)\",\n );\n const existing = await client.execute(\"SELECT id FROM _migrations\");\n const applied = new Set(existing.rows.map((r) => String(r.id)));\n const ran: string[] = [];\n for (const m of MIGRATIONS) {\n if (applied.has(m.id)) continue;\n try {\n await client.executeMultiple(m.sql);\n } catch (err) {\n // A re-run after a lost marker can re-execute a non-idempotent `ADD COLUMN`;\n // treat \"already applied\" as success so we still record the marker below and\n // never boot-loop. Any other error propagates unchanged.\n if (!isAlreadyAppliedError(err)) throw err;\n }\n await client.execute({\n sql: \"INSERT INTO _migrations (id, applied_at) VALUES (?, ?)\",\n args: [m.id, new Date().toISOString()],\n });\n ran.push(m.id);\n }\n return ran;\n}\n"],"mappings":";AAUO,IAAM,aAA0B;AAAA,EACrC;AAAA,IACE,IAAI;AAAA,IACJ,KAAK;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA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aAAW,KAAK,YAAY;AAC1B,QAAI,QAAQ,IAAI,EAAE,EAAE,EAAG;AACvB,QAAI;AACF,YAAM,OAAO,gBAAgB,EAAE,GAAG;AAAA,IACpC,SAAS,KAAK;AAIZ,UAAI,CAAC,sBAAsB,GAAG,EAAG,OAAM;AAAA,IACzC;AACA,UAAM,OAAO,QAAQ;AAAA,MACnB,KAAK;AAAA,MACL,MAAM,CAAC,EAAE,KAAI,oBAAI,KAAK,GAAE,YAAY,CAAC;AAAA,IACvC,CAAC;AACD,QAAI,KAAK,EAAE,EAAE;AAAA,EACf;AACA,SAAO;AACT;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/db/migrations.ts","../src/db/migrate.ts"],"sourcesContent":["/** Ordered, append-only list of standard-SQL migration scripts. Each runs once,\n * tracked by `id` in the `_migrations` table (see migrate.ts). Statements use\n * IF NOT EXISTS so even a partial re-apply is safe. Never edit a shipped script —\n * add a new one. Every statement in a script MUST be independently idempotent:\n * `migrate.ts` runs each script via `executeMultiple`, which is NOT transactional,\n * so a mid-script failure can leave earlier statements applied and the id unrecorded\n * — a re-run then re-executes the whole script. Standard SQLite SQL only (no\n * Turso-specific syntax) so the host stays a connection-string swap. */\nexport type Migration = { id: string; sql: string };\n\nexport const MIGRATIONS: Migration[] = [\n {\n id: \"0001_init\",\n sql: `\n CREATE TABLE IF NOT EXISTS submissions (\n id TEXT PRIMARY KEY,\n submission_id INTEGER,\n site_id TEXT NOT NULL,\n form_type TEXT NOT NULL,\n name TEXT NOT NULL,\n email TEXT NOT NULL,\n phone TEXT,\n message TEXT,\n extra_fields TEXT,\n source_url TEXT,\n utm TEXT,\n submitted_at TEXT,\n status TEXT NOT NULL DEFAULT 'new',\n notify_status TEXT NOT NULL DEFAULT 'skipped',\n resend_message_id TEXT\n );\n CREATE INDEX IF NOT EXISTS idx_submissions_site_submitted\n ON submissions (site_id, submitted_at DESC);\n CREATE INDEX IF NOT EXISTS idx_submissions_status\n ON submissions (status);\n CREATE TABLE IF NOT EXISTS spam_screenouts (\n site_id TEXT NOT NULL,\n date TEXT NOT NULL,\n honeypot INTEGER NOT NULL DEFAULT 0,\n too_fast INTEGER NOT NULL DEFAULT 0,\n marked_spam INTEGER NOT NULL DEFAULT 0,\n PRIMARY KEY (site_id, date)\n );\n `,\n },\n {\n id: \"0002_fleet_events\",\n sql: `\n CREATE TABLE IF NOT EXISTS fleet_events (\n id TEXT PRIMARY KEY,\n ts TEXT NOT NULL,\n type TEXT NOT NULL,\n site_id TEXT,\n site_name TEXT,\n summary TEXT NOT NULL,\n data TEXT,\n created_at TEXT NOT NULL\n );\n CREATE INDEX IF NOT EXISTS idx_fleet_events_ts ON fleet_events (ts);\n `,\n },\n {\n id: \"0003_add_spam_score\",\n // SQLite `ADD COLUMN` has no `IF NOT EXISTS`, so it is NOT self-idempotent: if the\n // `_migrations` marker is lost after the column is added (crash between statement\n // and marker write), a re-run would throw `duplicate column name`. `migrate.ts`\n // recognizes that error as already-applied and records the marker, keeping the\n // runner idempotent (see `isAlreadyAppliedError`).\n sql: `ALTER TABLE submissions ADD COLUMN spam_score REAL;`,\n },\n {\n id: \"0004_add_spam_reason\",\n sql: `ALTER TABLE submissions ADD COLUMN spam_reason TEXT;`,\n },\n {\n // Outcome of the newsletter fan-out (site webhook + Mailchimp). Before this the\n // results were console.error-only, so a rotated Mailchimp key or an outage would\n // silently stop signups reaching the audience with no trace anywhere the operator\n // looks — the row still read `notify=sent`, healthy. Same non-idempotent\n // ADD COLUMN caveat as 0003.\n id: \"0005_add_fanout_status\",\n sql: `ALTER TABLE submissions ADD COLUMN fanout_status TEXT;`,\n },\n {\n // Phase 0 of the Airtable → Turso migration (#539): a lead whose SITE LOOKUP\n // fails must still land somewhere durable. On 2026-08-17 the Airtable quota\n // outage made `getWebsiteBySlug` throw before `createSubmission` ran, so every\n // lead in the window 502'd away unrecorded — while THIS store (which holds\n // submissions) was healthy the whole time. Rows here are written only on that\n // path and replayed through the normal pipeline once the lookup recovers\n // (`db replay-deadletters`), producing an ordinary submissions row with real\n // spam classification and notify. Deliberately a separate table rather than a\n // nullable `submissions.site_id`: site_id is NOT NULL, every reader assumes a\n // real rec id, and a sentinel would collapse dashboard grouping (the \"\" key\n // hazard audit.ts already documents).\n //\n // `turnstile` stores the verification COMPUTED AT RECEIPT ({outcome, hostname}\n // JSON) — tokens expire in 300s, so replay could never re-verify; it replays\n // with the answer we already had.\n id: \"0006_submission_deadletter\",\n sql: `\n CREATE TABLE IF NOT EXISTS submission_deadletter (\n id TEXT PRIMARY KEY,\n site_slug TEXT NOT NULL,\n payload TEXT NOT NULL,\n turnstile TEXT NOT NULL,\n error TEXT NOT NULL,\n received_at TEXT NOT NULL,\n replayed_at TEXT,\n replay_outcome TEXT,\n replay_submission_id TEXT\n );\n CREATE INDEX IF NOT EXISTS idx_deadletter_unreplayed\n ON submission_deadletter (replayed_at);\n `,\n },\n {\n // Phase 1.2 of the Airtable → Turso migration (#539): the fleet-state tables.\n // Split by WRITER, not topic (design D2, confirmed by the 2026-08-23 writer\n // map — every code-written column has exactly one writer):\n // sites — operator (dashboard editor / console / launch flow)\n // site_health — the nightly audit write-back, one batched upsert\n // site_schedule — updateNextDueDates (report cron, derived)\n // reports — report drafting + the operator approve flow\n // PKs are the Airtable `rec…` ids (design D1): 278+ submissions rows already\n // reference them, and the parity harness diffs the two stores row-for-row.\n //\n // Naming: snake_case throughout; Airtable's misspellings (\"maintenence\") and\n // display quirks die here. `sites.legacy` is a JSON object holding the 33\n // populated-but-code-unreferenced columns (launch-era checklist, hosting\n // reference cells) keyed by their original Airtable column name — data kept,\n // schema not fossilized. The plaintext DNS/cms credential cells deliberately\n // do NOT migrate at all (operator ruling 2026-08-23); they live on only in\n // the frozen base. `site_health.analytics_soft_fail_at` is the column code\n // always wanted (\"Analytics soft-fail at\") but no operator ever created in\n // Airtable — it ships real here.\n //\n // reports.checklist is JSON keyed by the STABLE checklist key (\"deploy\",\n // \"cms\", …, from src/reports/checklist.ts), not the Airtable column name —\n // the importer translates, so \"Test: Verified After Updates\" stops leaking\n // its legacy name into a second store.\n id: \"0007_fleet_state\",\n sql: `\n CREATE TABLE IF NOT EXISTS sites (\n id TEXT PRIMARY KEY,\n slug TEXT NOT NULL UNIQUE,\n name TEXT NOT NULL,\n url TEXT,\n status TEXT,\n point_of_contact TEXT,\n maintenance_freq TEXT,\n testing_freq TEXT,\n maintenance_day TEXT,\n testing_day TEXT,\n ga4_property_id TEXT,\n search_query TEXT,\n search_console_property TEXT,\n git_repo TEXT,\n netlify_id TEXT,\n report_recipients_to TEXT,\n report_recipients_cc TEXT,\n copy_intro TEXT,\n copy_contact TEXT,\n copy_footer TEXT,\n newsletter_webhook TEXT,\n mailchimp_api_key TEXT,\n mailchimp_audience_id TEXT,\n notify_routing TEXT,\n require_turnstile INTEGER NOT NULL DEFAULT 0,\n accepted_watch_conditions TEXT,\n prismic_ack_until TEXT,\n launched_at TEXT,\n header_image BLOB,\n header_image_filename TEXT,\n header_image_type TEXT,\n header_image_generated_at TEXT,\n legacy TEXT\n );\n CREATE INDEX IF NOT EXISTS idx_sites_status ON sites (status);\n\n CREATE TABLE IF NOT EXISTS site_health (\n site_id TEXT PRIMARY KEY,\n p_score INTEGER,\n r_score INTEGER,\n bp_score INTEGER,\n seo_score INTEGER,\n lighthouse_at TEXT,\n a11y_violations INTEGER,\n deps_drifted INTEGER,\n deps_major_behind INTEGER,\n deps_outdated INTEGER,\n deps_major_outdated INTEGER,\n vulns_critical INTEGER,\n vulns_high INTEGER,\n vulns_moderate INTEGER,\n vulns_low INTEGER,\n security_audit_at TEXT,\n security_advisories TEXT,\n auto_fix_attempts INTEGER,\n analytics_soft_fail_at TEXT,\n cert_days_remaining INTEGER,\n domain_checked_at TEXT,\n deploy_status TEXT,\n last_deploy_at TEXT,\n deploy_log_url TEXT,\n deploy_checked_at TEXT,\n function_health TEXT,\n cms_reachable TEXT,\n turnstile_widget TEXT,\n function_health_checked_at TEXT,\n crossbrowser_ok INTEGER,\n mobile_ok INTEGER,\n links_ok INTEGER,\n broken_links INTEGER,\n browser_checked_at TEXT,\n uptime_reachable TEXT,\n titles_meta_ok TEXT,\n smoke_ok TEXT,\n last_smoke_at TEXT,\n form_e2e_ok TEXT,\n form_e2e_checked_at TEXT,\n renovate_failing_cis INTEGER,\n default_branch_ci TEXT,\n last_commit_at TEXT,\n github_signals_at TEXT,\n prismic_models TEXT,\n prismic_models_checked_at TEXT,\n prismic_models_drift TEXT\n );\n\n CREATE TABLE IF NOT EXISTS site_schedule (\n site_id TEXT PRIMARY KEY,\n next_maintenance_at TEXT,\n next_testing_at TEXT,\n computed_at TEXT\n );\n\n CREATE TABLE IF NOT EXISTS reports (\n id TEXT PRIMARY KEY,\n site_id TEXT,\n report_id TEXT,\n report_type TEXT,\n period TEXT,\n period_start TEXT,\n period_end TEXT,\n completed_on TEXT,\n lighthouse_performance INTEGER,\n lighthouse_accessibility INTEGER,\n lighthouse_best_practices INTEGER,\n lighthouse_seo INTEGER,\n ga_users_current INTEGER,\n ga_users_previous INTEGER,\n search_found_page1 INTEGER,\n search_position REAL,\n last_tested_date TEXT,\n commentary TEXT,\n subject_override TEXT,\n draft_ready INTEGER NOT NULL DEFAULT 0,\n approved_to_send INTEGER NOT NULL DEFAULT 0,\n approved_at TEXT,\n approved_by TEXT,\n send_override INTEGER NOT NULL DEFAULT 0,\n override_reason TEXT,\n override_by TEXT,\n override_at TEXT,\n sent_at TEXT,\n delivery_status TEXT,\n resend_message_id TEXT,\n checklist TEXT,\n checklist_auto_evidence TEXT,\n rendered_html TEXT\n );\n CREATE INDEX IF NOT EXISTS idx_reports_site ON reports (site_id, period_start DESC);\n `,\n },\n {\n // Indexes the EXPLAIN-query-plan gate (tests/db/query-plans.test.ts) proved the\n // hot paths need — each serves a named query shape that otherwise full-scans\n // submissions, the one unbounded-growth table:\n // submitted_at — every windowed read (/submissions default page, digest\n // per-site counts, duplicate/repeat-sender scans)\n // resend_message_id — the resend-webhook bounce lookup (markNotifyBouncedByMessageId)\n // submission_id — createSubmission's MAX(submission_id)+1 display number,\n // O(1) off the index instead of a scan per insert\n // spam_reason (partial, covering) — listSpamReasonsFiltered's facet tally\n // reads ONLY spam_reason WHERE spam_reason IS NOT NULL;\n // partial keeps it to the spam subset\n // spam_screenouts(date) — listScreenOutsSince windows on date, which the\n // (site_id, date) PK can't serve\n id: \"0008_query_plan_indexes\",\n sql: `\n CREATE INDEX IF NOT EXISTS idx_submissions_submitted\n ON submissions (submitted_at DESC);\n CREATE INDEX IF NOT EXISTS idx_submissions_spam_reason\n ON submissions (spam_reason) WHERE spam_reason IS NOT NULL;\n CREATE INDEX IF NOT EXISTS idx_submissions_resend_message\n ON submissions (resend_message_id);\n CREATE INDEX IF NOT EXISTS idx_submissions_display_number\n ON submissions (submission_id);\n CREATE INDEX IF NOT EXISTS idx_screenouts_date\n ON spam_screenouts (date);\n `,\n },\n {\n // Prospect audits (spec 2026-08-24): one row per `prospect-audit` CLI run.\n // `token` is the unguessable public handle for GET /r/{token}; `result_json`\n // is the full ProspectAuditResult, re-rendered on every request so report\n // styling updates apply to already-shared links.\n id: \"0009_prospect_audits\",\n sql: `\n CREATE TABLE IF NOT EXISTS prospect_audits (\n id TEXT PRIMARY KEY,\n token TEXT NOT NULL UNIQUE,\n url TEXT NOT NULL,\n business TEXT,\n created_at TEXT NOT NULL,\n status TEXT NOT NULL DEFAULT 'complete',\n result_json TEXT NOT NULL\n );\n `,\n },\n {\n // Cockpit /audits listing page (spec 2026-08-25, Piece 5):\n // listRecentProspectAudits orders by created_at DESC with no WHERE clause —\n // without this index that's a raw SCAN of prospect_audits followed by a temp\n // b-tree sort, which the EXPLAIN-query-plan gate (tests/db/query-plans.test.ts)\n // fails the build on. DESC matches the query's own ORDER BY so SQLite can walk\n // the index directly instead of sorting.\n id: \"0010_prospect_audits_created_index\",\n sql: `\n CREATE INDEX IF NOT EXISTS idx_prospect_audits_created\n ON prospect_audits (created_at DESC);\n `,\n },\n {\n // #609 (#539 Phase 5): the digest's prior-run snapshot moves off Airtable.\n // Unlike the rest of Phase 5 this is a MIGRATION, not a dual-write — there\n // is no Airtable counterpart left afterwards, so parity does not cover it.\n //\n // A single row holding the whole snapshot as JSON, keyed by a constant id.\n // Both readers (runDigest's diff and the fleet homepage's NEW badges) need\n // the ENTIRE map, so a keyed table would buy nothing on reads and its\n // \"give me everything\" query would be a raw scan needing a justified entry\n // in the EXPLAIN gate's allowlist. One row by primary key needs neither.\n id: \"0011_digest_state\",\n sql: `\n CREATE TABLE IF NOT EXISTS digest_state (\n id TEXT PRIMARY KEY,\n snapshot TEXT NOT NULL,\n updated_at TEXT\n );\n `,\n },\n {\n // form_type was the one SubmissionFilter key with an equality predicate and no\n // index — countSubmissionsFiltered({formType}) raw-scanned `submissions`, twice\n // per load of the submissions page. It shipped green because the EXPLAIN gate\n // named its scenarios by hand and never wrote one for this shape; the gate is\n // now driven by a filter matrix, which is what surfaced it.\n //\n // `submissions` is the one unbounded-growth table in the schema — append-only,\n // one row per fleet lead forever — and Turso meters ROW SCANS, so this is the\n // cost that grows without a ceiling.\n id: \"0012_submissions_form_type_index\",\n sql: `\n CREATE INDEX IF NOT EXISTS idx_submissions_form_type\n ON submissions (form_type);\n `,\n },\n];\n","import type { Client } from \"@libsql/client\";\nimport { MIGRATIONS } from \"./migrations.js\";\n\n/** True when an error means \"this DDL was already applied\" and re-applying is a\n * no-op we can safely ignore. `CREATE ... IF NOT EXISTS` never throws, but SQLite\n * `ALTER TABLE ... ADD COLUMN` has no `IF NOT EXISTS`, so a re-run after a lost\n * `_migrations` marker throws `duplicate column name: …`. Treating that as\n * already-applied keeps `runMigrations` idempotent for `ADD COLUMN` migrations —\n * without it a lost marker would boot-loop `openDb()` on every call. */\nfunction isAlreadyAppliedError(err: unknown): boolean {\n const message = err instanceof Error ? err.message : String(err);\n return /duplicate column name/i.test(message);\n}\n\n/** Apply every not-yet-applied migration in order against a raw libSQL client,\n * tracking applied ids in `_migrations`. Idempotent: ids already present are\n * skipped, the DDL uses IF NOT EXISTS where it can, and an already-applied\n * `ADD COLUMN` (recognized by its error) is swallowed so the marker is still\n * recorded. Returns the ids applied this run. Runs on every openDb() — cheap\n * (one indexed SELECT) and the gate every fresh Turso database needs before its\n * first write. */\nexport async function runMigrations(client: Client): Promise<string[]> {\n await client.execute(\n \"CREATE TABLE IF NOT EXISTS _migrations (id TEXT PRIMARY KEY, applied_at TEXT NOT NULL)\",\n );\n const existing = await client.execute(\"SELECT id FROM _migrations\");\n const applied = new Set(existing.rows.map((r) => String(r.id)));\n const ran: string[] = [];\n for (const m of MIGRATIONS) {\n if (applied.has(m.id)) continue;\n try {\n await client.executeMultiple(m.sql);\n } catch (err) {\n // A re-run after a lost marker can re-execute a non-idempotent `ADD COLUMN`;\n // treat \"already applied\" as success so we still record the marker below and\n // never boot-loop. Any other error propagates unchanged.\n if (!isAlreadyAppliedError(err)) throw err;\n }\n await client.execute({\n sql: \"INSERT INTO _migrations (id, applied_at) VALUES (?, ?)\",\n args: [m.id, new Date().toISOString()],\n });\n ran.push(m.id);\n }\n return ran;\n}\n"],"mappings":";AAUO,IAAM,aAA0B;AAAA,EACrC;AAAA,IACE,IAAI;AAAA,IACJ,KAAK;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA+BP;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,KAAK;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAaP;AAAA,EACA;AAAA,IACE,IAAI;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAMJ,KAAK;AAAA,EACP;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,KAAK;AAAA,EACP;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA;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OAAO,gBAAgB,EAAE,GAAG;AAAA,IACpC,SAAS,KAAK;AAIZ,UAAI,CAAC,sBAAsB,GAAG,EAAG,OAAM;AAAA,IACzC;AACA,UAAM,OAAO,QAAQ;AAAA,MACnB,KAAK;AAAA,MACL,MAAM,CAAC,EAAE,KAAI,oBAAI,KAAK,GAAE,YAAY,CAAC;AAAA,IACvC,CAAC;AACD,QAAI,KAAK,EAAE,EAAE;AAAA,EACf;AACA,SAAO;AACT;","names":[]}
|
|
@@ -65,6 +65,42 @@ var SPAM_KEYWORDS = [
|
|
|
65
65
|
"free shipping"
|
|
66
66
|
];
|
|
67
67
|
var BUYER_KEYWORDS = ["within 24 hours", "free consultation"];
|
|
68
|
+
var BLOCKED_EMAIL_DOMAINS = [
|
|
69
|
+
// 17/17 spam, 2026-06-17 → 2026-08-25, across four unrelated sites: MSOT (5),
|
|
70
|
+
// Reddoor's own site (5), Vineyard Custom Homes (4), Espada (3). Rotating
|
|
71
|
+
// `firstname.lastname@` sender identities — 11 addresses over those 17 sends.
|
|
72
|
+
"jmailservice.com",
|
|
73
|
+
// The MAVIS virtual-assistant flood, whose body invariants already sit in
|
|
74
|
+
// SPAM_KEYWORDS ("mavis", "virtual intelligent system", "tried emailing you").
|
|
75
|
+
// Seven sender domains, 35 submissions, 2026-06-17 → 2026-08-25, every one a VA
|
|
76
|
+
// pitch and 12 of them emailed to the operator. Each domain rotates first-name
|
|
77
|
+
// identities across unrelated client sites exactly as jmailservice.com does, so
|
|
78
|
+
// the email-exact repeat-sender signal cannot see the pattern. Counts are
|
|
79
|
+
// sends/addresses at the time of listing.
|
|
80
|
+
"trustedvirtualteam.com",
|
|
81
|
+
// 9 / 5
|
|
82
|
+
"toptalentvas.com",
|
|
83
|
+
// 7 / 4
|
|
84
|
+
"virtualhandsupport.com",
|
|
85
|
+
// 5 / 4
|
|
86
|
+
"vas4hire.com",
|
|
87
|
+
// 4 / 2
|
|
88
|
+
"vettedvas.com",
|
|
89
|
+
// 4 / 3
|
|
90
|
+
"thevirtualassistanthub.net",
|
|
91
|
+
// 3 / 2
|
|
92
|
+
"yourvachoice.com"
|
|
93
|
+
// 3 / 1
|
|
94
|
+
// DELIBERATELY NOT LISTED, checked 2026-08-26 — both would pass a naive
|
|
95
|
+
// "100% of its submissions are spam" query, which is why rule 1 says read the
|
|
96
|
+
// rows rather than trust the ratio:
|
|
97
|
+
//
|
|
98
|
+
// - lemos.com — 10/10 "spam", and all ten are the OPERATOR's own landing-page
|
|
99
|
+
// test submissions from tucker@lemos.com. Blocking it would bucket his own
|
|
100
|
+
// testing.
|
|
101
|
+
// - melottogroup.com — 3/3 genuine cold outreach, but one fixed address with no
|
|
102
|
+
// rotation, which repeat-sender already catches. Nothing to add.
|
|
103
|
+
];
|
|
68
104
|
var DISPOSABLE_EMAIL_DOMAINS = [
|
|
69
105
|
"mailinator.com",
|
|
70
106
|
"guerrillamail.com",
|
|
@@ -115,6 +151,10 @@ function emailDomain(email) {
|
|
|
115
151
|
const at = email.lastIndexOf("@");
|
|
116
152
|
return at === -1 ? "" : email.slice(at + 1).trim().toLowerCase();
|
|
117
153
|
}
|
|
154
|
+
function isBlockedDomain(domain) {
|
|
155
|
+
if (domain === "") return false;
|
|
156
|
+
return BLOCKED_EMAIL_DOMAINS.some((b) => domain === b || domain.endsWith(`.${b}`));
|
|
157
|
+
}
|
|
118
158
|
function isAllCaps(text) {
|
|
119
159
|
if (text.length <= 20) return false;
|
|
120
160
|
const letters = text.match(/[a-zA-Z]/g) ?? [];
|
|
@@ -187,7 +227,12 @@ function classifySpam(input) {
|
|
|
187
227
|
score += 35;
|
|
188
228
|
reasons.push("gibberish-name");
|
|
189
229
|
}
|
|
190
|
-
|
|
230
|
+
const domain = emailDomain(email);
|
|
231
|
+
if (isBlockedDomain(domain)) {
|
|
232
|
+
score += SPAM_THRESHOLD;
|
|
233
|
+
reasons.push("blocked-domain");
|
|
234
|
+
}
|
|
235
|
+
if (DISPOSABLE_EMAIL_DOMAINS.includes(domain)) {
|
|
191
236
|
score += 45;
|
|
192
237
|
reasons.push("disposable-email");
|
|
193
238
|
}
|
|
@@ -212,7 +257,8 @@ export {
|
|
|
212
257
|
SPAM_THRESHOLD,
|
|
213
258
|
SPAM_KEYWORDS,
|
|
214
259
|
BUYER_KEYWORDS,
|
|
260
|
+
BLOCKED_EMAIL_DOMAINS,
|
|
215
261
|
DISPOSABLE_EMAIL_DOMAINS,
|
|
216
262
|
classifySpam
|
|
217
263
|
};
|
|
218
|
-
//# sourceMappingURL=chunk-
|
|
264
|
+
//# sourceMappingURL=chunk-NO74DXDP.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/forms/spam-classifier.ts"],"sourcesContent":["import type { FormType } from \"./types.js\";\nimport type { TurnstileOutcome } from \"./turnstile.js\";\n\n/**\n * A submission at or above this score is classified auto-spam by ingest.\n *\n * Lowered 100 → 60 (2026-07-15): live data showed the classifier auto-bucketed\n * essentially nothing while ~1-in-4 delivered messages were spam. The dominant\n * bypass — human-plausible Latin-script cold outreach (SEO / virtual-assistant\n * pitches) with 0-1 links — sums only 25-55 from content signals. 60 lets the\n * high-precision multi-word keyword phrases + the gibberish/bare-domain signals\n * below actually bite. No single signal buckets alone (each needs corroboration),\n * with ONE deliberate exception: lorem-ipsum filler (+60) is machine-generated\n * content with zero genuine use. `spam_auto` is recoverable, so a false positive\n * is a nuisance the operator can undo, not a lost lead.\n */\nexport const SPAM_THRESHOLD = 60;\n\nexport type SpamVerdict = { score: number; reasons: string[] };\n\n/**\n * Maintained SELLER-VOICE spam-keyword list (case-insensitive substring match on\n * hyphen-normalized text — see countKeywordHits). Tunable from the `spam_score` /\n * `spam_reason` data the pipeline records. Keep entries specific enough to avoid\n * false positives: where a term is also legitimate business vocabulary (casino\n * resorts, weight-loss studios, transport escorts, payday lenders), list only the\n * clearly-promotional phrasing, never the bare term.\n *\n * SEO/marketing-topic policy (operator decision 2026-07-15): the fleet's sites are\n * niche and specific — they rank top for their own names — and clients who want\n * SEO/marketing help ask the agency DIRECTLY, so SEO-topic content arriving through\n * a public contact form is near-always solicitation. SEO-topic phrases therefore\n * live HERE at full weight (an SEO-help ask through the form is deliberately\n * filtered; `spam_auto` is recoverable and the operator prefers hand-delivering the\n * rare real one over receiving the flood). Each entry is +30, so TWO seller phrases\n * bucket; no single phrase can (max single non-lorem signal is turnstile-fail's 50).\n *\n * NOTE: entries must not be substrings of each other (\"page one\" + \"page one of\n * google\" would double-count one occurrence) and must be written hyphen-free (the\n * matcher folds `-–—` to spaces, so \"link-building\" in a message matches\n * \"link building\" here).\n */\nexport const SPAM_KEYWORDS: readonly string[] = [\n \"viagra\",\n \"cialis\",\n \"online casino\",\n \"casino bonus\",\n \"porn\",\n \"payday loans online\",\n \"buy crypto\",\n \"crypto wallet\",\n \"bitcoin investment\",\n \"cheap seo\",\n \"forex signals\",\n \"escort girls\",\n \"replica watches\",\n \"weight loss pills\",\n // Cold-outreach / SEO-pitch vertical (2026-07-15, expanded from the live miss\n // corpus the same day). Multi-word and solicitation-shaped: a real lead describing\n // their OWN site/needs occasionally grazes one of these, but never two.\n \"guest post\",\n \"guest article\",\n \"article for your website\",\n \"link building\",\n \"backlinks\",\n \"page one\", // \"You're not on page one. Your competitors are.\" (covers \"page one of google\" too)\n \"first page\", // covers \"first page of google\"\n \"1st page\", // \"The Wiki links show up on the 1st page of Google 97% of the time\"\n \"google ranking\",\n \"rank higher\",\n \"drive traffic\",\n \"increase your traffic\",\n \"top of search results\",\n \"people already searching\",\n \"seo problem\",\n \"seo process\", // \"no long SEO process, no delay\"\n \"leads and sales\",\n \"position your brand\",\n \"above competitors\",\n \"businesses like yours\",\n \"no obligation\",\n \"would you be interested\",\n \"would you be open\",\n \"tried emailing you\", // the \"I tried emailing you, but it seems it didn't go through\" opener\n // Virtual-assistant flood (MAVIS et al. — rotating sender names/domains with\n // reworded bodies, so the exact-duplicate velocity signal can't see it; these are\n // the template's invariants).\n \"virtual assistant\",\n \"virtual intelligent system\", // \"MAVIS (My Advanced Virtual Intelligent System)\" — in every copy\n \"mavis\",\n \"overtake and handle\",\n \"custom built ai\", // matches \"custom-built AI\" via hyphen folding\n // Wikipedia-page-creation vertical.\n \"wikipedia page\",\n \"wiki links\",\n // Product-blast ad copy (the dog-harness family).\n \"get yours today\",\n \"free shipping\",\n];\n\n/**\n * BUYER-COMPATIBLE outreach phrases: common in cold pitches but also plausible in a\n * genuine prospect's own words (\"do you offer a free consultation?\", \"we need it\n * within 24 hours\"). Alone they score a weak +10 (capped at 2 hits / +20) so they\n * can never carry a message toward the threshold — but when at least one\n * seller-voice phrase is present the message is demonstrably a pitch, and these\n * PROMOTE to full keyword weight as corroboration.\n */\nexport const BUYER_KEYWORDS: readonly string[] = [\"within 24 hours\", \"free consultation\"];\n\n/**\n * Sender domains where EVERY submission the fleet has ever received was spam.\n *\n * A second, stricter tier than DISPOSABLE_EMAIL_DOMAINS. The disposable list says\n * \"a throwaway provider — be suspicious\", so it scores a corroborating +45 and\n * cannot bucket alone. This list says \"we have looked at the traffic from this\n * domain and there is no legitimate traffic\", so it buckets on its own.\n *\n * Why the weaker tier was not enough (the case that created this list): 17\n * submissions arrived from `jmailservice.com` between 2026-06-17 and 2026-08-25\n * across FOUR unrelated client sites, none legitimate — and 10 of them were\n * emailed to the operator. They dodged every existing signal in turn:\n *\n * - the content scorer, because the bodies vary and most sum under 60 (the last\n * two scored 30 and 0);\n * - the cross-site `repeat-sender` signal, because the sender rotates a plausible\n * `firstname.lastname@` local part — 11 distinct addresses across 17 sends, so\n * the email-exact lookup almost never saw a repeat;\n * - and the disposable list's +45, which even if the domain were listed there\n * would have bucketed only the 5 sends that already carried a corroborating\n * signal, and none of the ones that reached the inbox.\n *\n * The rotation is the point: the identity changes every time, the DOMAIN does not.\n *\n * ENTRY BAR — this list is deliberately hard to add to, because it is the only\n * signal with no corroboration requirement:\n *\n * 1. Query the live traffic for the domain and read EVERY row. Not a sample.\n * 2. Every one must be spam. One genuine lead disqualifies the domain — put it on\n * the disposable list instead, where it needs corroboration.\n * 3. Never list a shared mailbox provider (gmail.com, outlook.com, a webmail host,\n * an ISP domain). Those carry real leads by definition, and a single entry here\n * would silently bucket every genuine lead using it.\n *\n * Matching is by registrable domain OR any subdomain of it, so a move to\n * `mail.<domain>` does not reopen the hole. Entries must be bare lowercase\n * domains; `spam-classifier.test.ts` enforces the shape and that no domain\n * appears on both lists.\n */\nexport const BLOCKED_EMAIL_DOMAINS: readonly string[] = [\n // 17/17 spam, 2026-06-17 → 2026-08-25, across four unrelated sites: MSOT (5),\n // Reddoor's own site (5), Vineyard Custom Homes (4), Espada (3). Rotating\n // `firstname.lastname@` sender identities — 11 addresses over those 17 sends.\n \"jmailservice.com\",\n\n // The MAVIS virtual-assistant flood, whose body invariants already sit in\n // SPAM_KEYWORDS (\"mavis\", \"virtual intelligent system\", \"tried emailing you\").\n // Seven sender domains, 35 submissions, 2026-06-17 → 2026-08-25, every one a VA\n // pitch and 12 of them emailed to the operator. Each domain rotates first-name\n // identities across unrelated client sites exactly as jmailservice.com does, so\n // the email-exact repeat-sender signal cannot see the pattern. Counts are\n // sends/addresses at the time of listing.\n \"trustedvirtualteam.com\", // 9 / 5\n \"toptalentvas.com\", // 7 / 4\n \"virtualhandsupport.com\", // 5 / 4\n \"vas4hire.com\", // 4 / 2\n \"vettedvas.com\", // 4 / 3\n \"thevirtualassistanthub.net\", // 3 / 2\n \"yourvachoice.com\", // 3 / 1\n\n // DELIBERATELY NOT LISTED, checked 2026-08-26 — both would pass a naive\n // \"100% of its submissions are spam\" query, which is why rule 1 says read the\n // rows rather than trust the ratio:\n //\n // - lemos.com — 10/10 \"spam\", and all ten are the OPERATOR's own landing-page\n // test submissions from tucker@lemos.com. Blocking it would bucket his own\n // testing.\n // - melottogroup.com — 3/3 genuine cold outreach, but one fixed address with no\n // rotation, which repeat-sender already catches. Nothing to add.\n];\n\n/** Maintained disposable / throwaway email domains. */\nexport const DISPOSABLE_EMAIL_DOMAINS: readonly string[] = [\n \"mailinator.com\",\n \"guerrillamail.com\",\n \"10minutemail.com\",\n \"tempmail.com\",\n \"trashmail.com\",\n \"yopmail.com\",\n \"sharklasers.com\",\n \"getnada.com\",\n \"throwawaymail.com\",\n \"maildrop.cc\",\n];\n\n// A URL candidate ends at whitespace, `,` or `;` so comma/semicolon-glued\n// URLs (\"a.com,b.com\") count individually instead of matching as one.\nconst URL_RE = /https?:\\/\\/[^\\s,;]+|www\\.[^\\s,;]+/gi;\nconst LINK_MARKUP_RE = /<a\\s[^>]*href|\\[url[=\\]]/i;\nconst ONLY_URL_RE = /^(https?:\\/\\/\\S+|www\\.\\S+)$/i;\n\n/** Count of bare http(s)/www URLs in a string. */\nfunction countUrls(text: string): number {\n return (text.match(URL_RE) ?? []).length;\n}\n\n/** How many of `keywords` appear in `text` (each counted once). Hyphens/dashes fold\n * to spaces first so \"link-building\" / \"custom-built AI\" match their space-separated\n * list entries — the hyphenated spelling was a live keyword dodge. */\nfunction countKeywordHits(text: string, keywords: readonly string[]): number {\n const lower = text.toLowerCase().replace(/[-–—]/g, \" \");\n return keywords.filter((kw) => lower.includes(kw)).length;\n}\n\n/** Distinct lorem-ipsum vocabulary stems. Form-tester bots submit truncated filler\n * (\"Velit ullam reprehen\", \"Dolore harum volupta\") — too short for the velocity\n * signal and invisible to gibberish (they're real Latin words). Two DISTINCT stems\n * are required so a lone romance-language cognate (voluptuous, tempora) can never\n * fire; no human writes two lorem-ipsum words in a genuine inquiry. */\nconst LOREM_STEMS: readonly RegExp[] = [\n /\\blorem\\b/i,\n /\\bipsum\\b/i,\n /\\bvelit\\b/i,\n /\\bullam/i,\n /\\bharum\\b/i,\n /\\breprehen/i,\n /\\bvolupt/i,\n /\\bnostrud\\b/i,\n /\\badipisc/i,\n /\\beiusmod\\b/i,\n /\\bincididunt\\b/i,\n /\\bconsectetur\\b/i,\n /\\baliqua\\b/i,\n];\n\nfunction countLoremStems(text: string): number {\n return LOREM_STEMS.filter((re) => re.test(text)).length;\n}\n\n/** Fraction of letters that are outside the Latin script (0..1). */\nfunction nonLatinRatio(text: string): number {\n const letters = text.match(/\\p{L}/gu) ?? [];\n if (letters.length === 0) return 0;\n const nonLatin = letters.filter((ch) => !/\\p{Script=Latin}/u.test(ch)).length;\n return nonLatin / letters.length;\n}\n\n/** Domain part of an email, lowercased; \"\" when unparseable. */\nfunction emailDomain(email: string): string {\n const at = email.lastIndexOf(\"@\");\n return at === -1\n ? \"\"\n : email\n .slice(at + 1)\n .trim()\n .toLowerCase();\n}\n\n/**\n * True when `domain` is a blocked sender domain or any subdomain of one.\n *\n * Suffix-matched on a label boundary, so `mail.jmailservice.com` is blocked while\n * `notjmailservice.com` (an unrelated registration that merely ends in the same\n * letters) is not. `domain` is already lowercased by emailDomain().\n */\nfunction isBlockedDomain(domain: string): boolean {\n if (domain === \"\") return false;\n return BLOCKED_EMAIL_DOMAINS.some((b) => domain === b || domain.endsWith(`.${b}`));\n}\n\n/** len > 20 and > 70% of its letters uppercase. */\nfunction isAllCaps(text: string): boolean {\n if (text.length <= 20) return false;\n const letters = text.match(/[a-zA-Z]/g) ?? [];\n if (letters.length === 0) return false;\n const upper = letters.filter((c) => c >= \"A\" && c <= \"Z\").length;\n return upper / letters.length > 0.7;\n}\n\n/**\n * True when `text` has a token of >= `minLen` ASCII letters that looks like random\n * keyboard mash, via EITHER of two discriminators (measured 2026-07-15 against\n * /usr/share/dict/words + the live mash corpus — each alone misses live samples the\n * other catches, and together they flag ZERO dictionary words or common brand names):\n *\n * 1. A run of >= 7 consecutive non-vowels, with `y` counted as a VOWEL\n * (`OsDMQohNGefhfCqqQCwr` has a 10-run, `zddDVjhArCJ` a 7-run). The original\n * >=5-with-y-as-consonant rule fired on ordinary English — every psych* word\n * >= 10 letters (p-s-y-c-h is itself a 5-run), \"worthwhile\", \"nightclubs\",\n * 3,138 dictionary words in all — i.e. gibberish(+35) + one pasted link(+25)\n * silently bucketed whole genuine-lead verticals (a psychology practice!).\n * 2. >= 3 interior lower→upper case flips (`IjIiJuhkojCYrNDFTXe`, `XiwkUDgrboTgMSVX`\n * — live samples whose longest y-as-vowel run is only 6). Real CamelCase tokens\n * (JavaScript, SquareSpace, MailChimp) have at most 1-2 humps.\n *\n * LATIN a-z ONLY: a native-script name (王小明, Владимир) has no a-z letters here and\n * is never flagged — that is the non-latin signal's job, deliberately de-weighted so\n * a real foreign name isn't spam.\n */\nfunction hasGibberishToken(text: string, minLen: number): boolean {\n for (const run of text.match(/[A-Za-z]+/g) ?? []) {\n if (run.length < minLen) continue;\n if (/[^aeiouyAEIOUY]{7,}/.test(run)) return true;\n let flips = 0;\n for (let i = 1; i < run.length; i++) {\n const prev = run[i - 1]!;\n const cur = run[i]!;\n if (prev >= \"a\" && prev <= \"z\" && cur >= \"A\" && cur <= \"Z\") flips++;\n }\n if (flips >= 3) return true;\n }\n return false;\n}\n\n// A domain-like token with a known TLD but NO scheme/`www` (those are already caught by\n// URL_RE). The leading `(?<![@\\w.])` excludes an email's domain (`a@foo.com`), a\n// sub-label continuation, and file-ish `name.ext` runs. Curated TLD set keeps it from\n// firing on `node.js` / `index.html`. Used only when no real URL was found.\nconst BARE_DOMAIN_RE =\n /(?<![@\\w.])[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.(?:com|net|org|io|co|biz|info|online|site|shop|store|xyz|agency|digital|marketing|dev|app)\\b/i;\n\n/**\n * Pure content spam scorer. Folds message/name/email content signals plus the\n * Turnstile verdict into a numeric score with human-readable reason strings.\n * Never throws; `formType` is accepted for future per-type tuning.\n */\nexport function classifySpam(input: {\n name: string;\n email: string;\n message?: string;\n formType: FormType;\n extraFields: Record<string, unknown>;\n turnstile: TurnstileOutcome;\n}): SpamVerdict {\n const name = input.name ?? \"\";\n const email = input.email ?? \"\";\n const message = input.message ?? \"\";\n const reasons: string[] = [];\n let score = 0;\n\n // Site-specific free-text fields (e.g. extra.comments) carry the same spam\n // signals as message — fold every STRING extraFields value into the scanned\n // body so a site with a custom \"comments\"/\"details\" field isn't a blind spot.\n // Non-string values (numbers, booleans, nested objects) are ignored.\n const extraText = Object.values(input.extraFields ?? {})\n .filter((v): v is string => typeof v === \"string\")\n .join(\" \");\n const body = extraText ? `${message} ${extraText}` : message;\n\n // 50: post-#400 a \"fail\" is a FORGED token (invalid-input-response), near-certainly a\n // bot — but kept below the 60 threshold so a forged token alone still needs one\n // corroborating content signal before auto-bucketing (fail-open caution). A benign\n // human never reaches here: expired/duplicate tokens are \"unverifiable\", not \"fail\".\n if (input.turnstile === \"fail\") {\n score += 50;\n reasons.push(\"turnstile-fail\");\n }\n\n const urls = countUrls(body);\n if (urls > 0) {\n // Capped at 2 (max +50) so a genuine lead pasting two links (site + portfolio) stays\n // under 60 on URLs alone; a third adds nothing. 25/link keeps one link well shy of a\n // solo bucket.\n score += Math.min(urls, 2) * 25;\n reasons.push(`links:${urls}`);\n } else if (BARE_DOMAIN_RE.test(body)) {\n // No real http/www URL, but a bare \"brand.com\" is pasted — the exact dodge spammers\n // use to slip past URL_RE. +20, needs corroboration to bucket.\n score += 20;\n reasons.push(\"bare-domain\");\n }\n\n if (LINK_MARKUP_RE.test(body)) {\n score += 40;\n reasons.push(\"link-markup\");\n }\n\n // Two-tier keywords. Seller-voice phrases are unambiguous pitch language: +30\n // each (capped at 3 hits / +90) — TWO seller phrases bucket outright, per the\n // operator's 2026-07-15 steer (see the SPAM_KEYWORDS docstring): genuine leads on\n // this fleet write zero solicitor phrases, and SEO/marketing-help asks through\n // the public form are deliberately filtered. A seller hit also PROMOTES any\n // buyer-compatible phrases in the same message to full weight — a pitch that says\n // \"would you be interested\" AND \"within 24 hours\" is corroborating itself.\n // WITHOUT a seller-voice phrase, buyer-compatible hits alone score a weak +10\n // capped at +20, never enough to carry a message toward the threshold.\n const seller = countKeywordHits(body, SPAM_KEYWORDS);\n const buyer = countKeywordHits(body, BUYER_KEYWORDS);\n if (seller > 0) {\n const hits = seller + buyer;\n score += Math.min(hits, 3) * 30;\n reasons.push(`keywords:${hits}`);\n } else if (buyer > 0) {\n score += Math.min(buyer, 2) * 10;\n reasons.push(`keywords-buyer:${buyer}`);\n }\n\n // Lorem-ipsum form-tester bots: >=2 distinct filler stems is machine-generated\n // content with zero genuine use, so this is the one signal allowed to bucket\n // alone (+60) — the bodies are too short for the velocity signal and are real\n // Latin words, invisible to the gibberish detector.\n if (countLoremStems(body) >= 2) {\n score += 60;\n reasons.push(\"lorem-ipsum\");\n }\n\n // Body only — a native-script NAME (王小明, Владимир) is not a spam signal.\n // 25 (not 50): non-Latin alone must need corroboration from other signals\n // before it can reach SPAM_THRESHOLD.\n if (nonLatinRatio(body) > 0.3) {\n score += 25;\n reasons.push(\"non-latin\");\n }\n\n // Random keyboard-mash tokens (form-filler bots): body is the strong tell (+35); the\n // NAME corroborates only under a stricter rule (single token, >=12 chars). A real\n // consonant-heavy surname (Krzysztofowicz — max 3-run with y as vowel) no longer trips\n // at all under the 7-run rule. A bot with both name and body mashed sums 70 and is caught.\n if (hasGibberishToken(body, 10)) {\n score += 35;\n reasons.push(\"gibberish-body\");\n }\n if (!name.trim().includes(\" \") && hasGibberishToken(name, 12)) {\n score += 35;\n reasons.push(\"gibberish-name\");\n }\n\n const domain = emailDomain(email);\n\n // A domain proven to send only spam buckets ALONE. Scored as SPAM_THRESHOLD\n // rather than a literal so the property survives a future threshold change:\n // this signal is defined as \"enough on its own\", not as \"worth 60 points\".\n // See the BLOCKED_EMAIL_DOMAINS docstring for the (deliberately high) bar an\n // entry has to clear.\n if (isBlockedDomain(domain)) {\n score += SPAM_THRESHOLD;\n reasons.push(\"blocked-domain\");\n }\n\n if (DISPOSABLE_EMAIL_DOMAINS.includes(domain)) {\n score += 45;\n reasons.push(\"disposable-email\");\n }\n\n if (countUrls(name) > 0) {\n score += 45;\n reasons.push(\"url-in-name\");\n }\n\n const trimmedMsg = body.trim();\n const degenerate =\n (trimmedMsg.length > 0 && trimmedMsg === name.trim()) || ONLY_URL_RE.test(trimmedMsg);\n if (degenerate) {\n score += 40;\n reasons.push(\"degenerate\");\n }\n\n if (isAllCaps(body)) {\n score += 15;\n reasons.push(\"all-caps\");\n }\n\n return { score, reasons };\n}\n"],"mappings":";AAgBO,IAAM,iBAAiB;AA0BvB,IAAM,gBAAmC;AAAA,EAC9C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA;AAAA,EAIA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA,EAIA;AAAA,EACA;AAAA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AACF;AAUO,IAAM,iBAAoC,CAAC,mBAAmB,mBAAmB;AAyCjF,IAAM,wBAA2C;AAAA;AAAA;AAAA;AAAA,EAItD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAWF;AAGO,IAAM,2BAA8C;AAAA,EACzD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAIA,IAAM,SAAS;AACf,IAAM,iBAAiB;AACvB,IAAM,cAAc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YAAY;AAAA,EAC3B;AAEA,MAAI,UAAU,IAAI,GAAG;AACnB,aAAS;AACT,YAAQ,KAAK,UAAU;AAAA,EACzB;AAEA,SAAO,EAAE,OAAO,QAAQ;AAC1B;","names":[]}
|
|
@@ -22,7 +22,13 @@ function allocateFreePortSync() {
|
|
|
22
22
|
return null;
|
|
23
23
|
}
|
|
24
24
|
}
|
|
25
|
-
|
|
25
|
+
function resolvePort() {
|
|
26
|
+
if (smokePort) return smokePort;
|
|
27
|
+
const allocated = allocateFreePortSync() || "5173";
|
|
28
|
+
process.env.REDDOOR_SMOKE_PORT = allocated;
|
|
29
|
+
return allocated;
|
|
30
|
+
}
|
|
31
|
+
var port = resolvePort();
|
|
26
32
|
var playwrightA11yConfig = defineConfig({
|
|
27
33
|
testDir: "tests",
|
|
28
34
|
testMatch: /.*\.spec\.ts$/,
|
|
@@ -87,4 +93,4 @@ export {
|
|
|
87
93
|
smokeRoutes,
|
|
88
94
|
playwright_a11y_default
|
|
89
95
|
};
|
|
90
|
-
//# sourceMappingURL=chunk-
|
|
96
|
+
//# sourceMappingURL=chunk-O3GT46R2.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/configs/playwright-a11y.ts"],"sourcesContent":["import { execFileSync } from \"node:child_process\";\nimport { defineConfig, devices, type PlaywrightTestConfig } from \"@playwright/test\";\n\nexport type A11yRoute = { path: string; name: string };\n\nexport const a11yRoutes: A11yRoute[] = [\n { path: \"/dev/a11y-fixtures\", name: \"a11y fixtures\" },\n { path: \"/dev/animate-in\", name: \"animate-in demo\" },\n];\n\n// Routes smoke-loaded for client-side (hydration) errors only — NOT axe-scanned.\n// Catches the class of bug where build + SSR succeed but client hydration throws\n// and blanks the page (data-dynamiq 2026-06-09: a Svelte 4->5 `run()` referenced\n// a `$state` declared after it → TDZ ReferenceError on hydrate). `/` is the one\n// route every site has; real routes carry a11y debt we don't gate on here, so we\n// assert only that they don't crash on hydrate.\nexport const smokeRoutes: A11yRoute[] = [{ path: \"/\", name: \"home\" }];\n\n// R1.1 (health-gate): the central `smoke` audit (src/audits/smoke.ts) allocates\n// a free port and passes it as REDDOOR_SMOKE_PORT so a zombie vite already\n// squatting the default 5173 can't silently hijack the run and green a stale\n// build. The per-site R1.1 config template honors it, but sites whose\n// playwright.config.ts merely re-exports this shared base (pre-R1.1 adopters\n// the smoke-suite recipe flags-but-never-rewrites) would otherwise ignore it —\n// so honor it here too and every re-exporter inherits the port binding on its\n// next package bump. Unset (local `pnpm test:smoke`) → the fixed 5173.\nconst smokePort = process.env.REDDOOR_SMOKE_PORT;\n\n/**\n * Allocate a free port SYNCHRONOUSLY, for the local path where nothing handed\n * us one. Same trick as src/util/free-port.ts (bind :0, read the assigned port,\n * release it) — but that is async, and this value is needed at module scope\n * while Playwright is still building the config object.\n *\n * It cannot be an async default export instead: sites consume this base by\n * SPREADING it (`{ ...base, use: { ...base.use } }` — see the smoke-suite\n * recipe template). Spreading a Promise yields none of its properties, so the\n * site would get a silently empty config — the exact false-green this whole\n * change exists to remove. The export must stay a plain object.\n *\n * A subprocess is the cost of that constraint: ~30-50ms, once per Playwright\n * run. On any failure we return null and the caller falls back to 5173, which\n * (with reuseExistingServer now false) degrades to a loud \"port already in use\"\n * rather than a silent wrong-server run.\n */\nfunction allocateFreePortSync(): string | null {\n try {\n const out = execFileSync(\n process.execPath,\n [\n \"-e\",\n 'const s=require(\"node:net\").createServer();s.on(\"error\",()=>process.exit(1));' +\n 's.listen(0,\"127.0.0.1\",()=>{const p=s.address().port;s.close(()=>process.stdout.write(String(p)))});',\n ],\n { encoding: \"utf8\", timeout: 5_000, stdio: [\"ignore\", \"pipe\", \"ignore\"] },\n ).trim();\n return /^\\d+$/.test(out) ? out : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Resolve the port this run binds to, ONCE per run rather than once per\n * evaluation of this file.\n *\n * REDDOOR_SMOKE_PORT (the central audit already allocated one) wins; otherwise\n * this run allocates its own. The old fallback was the fixed 5173 — the same\n * port a dev server sits on, which is what let `reuseExistingServer` silently\n * hijack local runs (#524).\n *\n * The allocation is pinned back into the environment, and that is the whole\n * point. Playwright re-evaluates the config file in EVERY worker process, not\n * just the main one. Allocating per evaluation gave each worker a different\n * port: the main process started the dev server on one, every worker aimed\n * `baseURL` at another, and the run died with ERR_CONNECTION_REFUSED against a\n * handful of ports nothing was ever serving. Workers are forked and inherit\n * this environment, so writing it back makes every later evaluation agree.\n *\n * It broke on the site suites and not on `audit --only a11y`, which writes its\n * own config and never reads this file — so nothing here caught it.\n */\nfunction resolvePort(): string {\n if (smokePort) return smokePort;\n const allocated = allocateFreePortSync() || \"5173\";\n process.env.REDDOOR_SMOKE_PORT = allocated;\n return allocated;\n}\n\nconst port = resolvePort();\n\n// NOTE: default export only — sites consume this as `import base from\n// \"@reddoorla/maintenance/configs/playwright-a11y\"` (or re-export the default).\n// The old `playwrightA11yConfig` named alias had zero importers and was removed.\nconst playwrightA11yConfig: PlaywrightTestConfig = defineConfig({\n testDir: \"tests\",\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 projects: [\n {\n name: \"chromium\",\n use: { ...devices[\"Desktop Chrome\"] },\n },\n ],\n webServer: {\n // Portable across pnpm and npm sites — pnpm respects `npm run` too.\n //\n // `--port ... --strictPort` in BOTH cases. It used to be applied only when\n // REDDOOR_SMOKE_PORT allocated one, on the reasoning that we should \"fail\n // loudly rather than let vite drift to a free port the baseURL doesn't\n // point at\" — but that argument covers the unset case just as well. 5173 is\n // equally a fixed port that `baseURL` and the readiness probe below are\n // pinned to, and vite left to itself drifts off it whenever something else\n // holds it.\n //\n // The symptom that exposed this: a non-vite process on 5173 sends vite to\n // 5174 while the probe keeps polling 5173, so the run dies on\n // \"Timed out waiting 120000ms from config.webServer\" — 120 seconds of\n // nothing, naming neither the port nor the squatter. With --strictPort it\n // is an immediate \"Port 5173 is already in use\".\n //\n // --strictPort now only bites if the allocated port is taken in the window\n // between releasing and binding it, which is exactly the case worth failing\n // on.\n command: `npm run vite:dev -- --port ${port} --strictPort`,\n url: `http://localhost:${port}/dev/a11y-fixtures`,\n // NEVER reuse (#524). This used to be `!process.env.CI`, so local runs\n // reused whatever answered the probe URL. The probe only asks \"does this\n // respond?\" — never \"is this serving the code I am about to test?\" — so a\n // dev server left open, or one whose tree changed under it after a\n // checkout, silently became the system under test. That fails in both\n // directions: a false red blamed on the code (beachfront 2026-08-12, where\n // it was investigated as a macOS-vs-Linux difference and written up as one\n // before being caught), and a false green where a passing suite ran against\n // an old build. CI already had it false, and that asymmetry is precisely\n // what made the failure read as a platform bug.\n //\n // The cost is a fresh vite boot per run (~10-20s against a ~2min suite).\n // Because the port above is allocated rather than fixed, your own dev\n // server on 5173 keeps running untouched.\n reuseExistingServer: false,\n timeout: 120_000,\n },\n});\n\nexport default playwrightA11yConfig;\n"],"mappings":";AAAA,SAAS,oBAAoB;AAC7B,SAAS,cAAc,eAA0C;AAI1D,IAAM,aAA0B;AAAA,EACrC,EAAE,MAAM,sBAAsB,MAAM,gBAAgB;AAAA,EACpD,EAAE,MAAM,mBAAmB,MAAM,kBAAkB;AACrD;AAQO,IAAM,cAA2B,CAAC,EAAE,MAAM,KAAK,MAAM,OAAO,CAAC;AAUpE,IAAM,YAAY,QAAQ,IAAI;AAmB9B,SAAS,uBAAsC;AAC7C,MAAI;AACF,UAAM,MAAM;AAAA,MACV,QAAQ;AAAA,MACR;AAAA,QACE;AAAA,QACA;AAAA,MAEF;AAAA,MACA,EAAE,UAAU,QAAQ,SAAS,KAAO,OAAO,CAAC,UAAU,QAAQ,QAAQ,EAAE;AAAA,IAC1E,EAAE,KAAK;AACP,WAAO,QAAQ,KAAK,GAAG,IAAI,MAAM;AAAA,EACnC,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAsBA,SAAS,cAAsB;AAC7B,MAAI,UAAW,QAAO;AACtB,QAAM,YAAY,qBAAqB,KAAK;AAC5C,UAAQ,IAAI,qBAAqB;AACjC,SAAO;AACT;AAEA,IAAM,OAAO,YAAY;AAKzB,IAAM,uBAA6C,aAAa;AAAA,EAC9D,SAAS;AAAA,EACT,WAAW;AAAA,EACX,eAAe;AAAA,EACf,YAAY,CAAC,CAAC,QAAQ,IAAI;AAAA,EAC1B,SAAS,QAAQ,IAAI,KAAK,IAAI;AAAA,EAC9B,UAAU,QAAQ,IAAI,KAAK,WAAW;AAAA,EACtC,KAAK;AAAA,IACH,SAAS,oBAAoB,IAAI;AAAA,IACjC,OAAO;AAAA,EACT;AAAA,EACA,UAAU;AAAA,IACR;AAAA,MACE,MAAM;AAAA,MACN,KAAK,EAAE,GAAG,QAAQ,gBAAgB,EAAE;AAAA,IACtC;AAAA,EACF;AAAA,EACA,WAAW;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAoBT,SAAS,8BAA8B,IAAI;AAAA,IAC3C,KAAK,oBAAoB,IAAI;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAe7B,qBAAqB;AAAA,IACrB,SAAS;AAAA,EACX;AACF,CAAC;AAED,IAAO,0BAAQ;","names":[]}
|
|
@@ -6,7 +6,7 @@ import {
|
|
|
6
6
|
} from "./chunk-7NYN2P6I.js";
|
|
7
7
|
import {
|
|
8
8
|
isHttpUrl
|
|
9
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-RARREDQE.js";
|
|
10
10
|
|
|
11
11
|
// src/inventory/airtable.ts
|
|
12
12
|
function fromAirtableBase(base, opts = {}) {
|
|
@@ -50,4 +50,4 @@ function fromAirtableBase(base, opts = {}) {
|
|
|
50
50
|
export {
|
|
51
51
|
fromAirtableBase
|
|
52
52
|
};
|
|
53
|
-
//# sourceMappingURL=chunk-
|
|
53
|
+
//# sourceMappingURL=chunk-PR343K7F.js.map
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import {
|
|
2
2
|
fromJsonFile,
|
|
3
3
|
localPath
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-Z3JXLULD.js";
|
|
5
5
|
import {
|
|
6
6
|
isHttpUrl
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-RARREDQE.js";
|
|
8
8
|
|
|
9
9
|
// src/cli/fleet/resolve-sites.ts
|
|
10
10
|
import { pathToFileURL } from "url";
|
|
@@ -30,7 +30,7 @@ async function resolveSites(input) {
|
|
|
30
30
|
}
|
|
31
31
|
if (input.fleet === "airtable") {
|
|
32
32
|
const { openBase, readAirtableConfig } = await import("./client-EPVO3FEH.js");
|
|
33
|
-
const { fromAirtableBase } = await import("./airtable-
|
|
33
|
+
const { fromAirtableBase } = await import("./airtable-QG5ICI3Y.js");
|
|
34
34
|
const base = openBase(readAirtableConfig());
|
|
35
35
|
const provider = fromAirtableBase(base, input.workdir ? { workdir: input.workdir } : {});
|
|
36
36
|
return provider();
|
|
@@ -61,4 +61,4 @@ async function resolveSites(input) {
|
|
|
61
61
|
export {
|
|
62
62
|
resolveSites
|
|
63
63
|
};
|
|
64
|
-
//# sourceMappingURL=chunk-
|
|
64
|
+
//# sourceMappingURL=chunk-Q47DU255.js.map
|
|
@@ -34,6 +34,7 @@ function isPrivateOrLoopbackHost(hostname) {
|
|
|
34
34
|
if (/^fe[89ab]/.test(host)) return true;
|
|
35
35
|
if (/^f[cd]/.test(host)) return true;
|
|
36
36
|
if (host.startsWith("::ffff:") || host.startsWith("64:ff9b:")) return true;
|
|
37
|
+
if (/^::(?!$)(?!0*:?$)[0-9a-f]{0,4}:?[0-9a-f]{0,4}$/.test(host)) return true;
|
|
37
38
|
return false;
|
|
38
39
|
}
|
|
39
40
|
if (/^\d{1,3}(\.\d{1,3}){3}$/.test(host)) {
|
|
@@ -65,4 +66,4 @@ export {
|
|
|
65
66
|
isPrivateOrLoopbackHost,
|
|
66
67
|
isPublicHttpsUrl
|
|
67
68
|
};
|
|
68
|
-
//# sourceMappingURL=chunk-
|
|
69
|
+
//# sourceMappingURL=chunk-RARREDQE.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/util/url.ts"],"sourcesContent":["/**\n * True when `s` parses as an absolute URL whose scheme is `http:` or `https:`.\n *\n * The single allowlist gate for any value we hand to Chrome/Lighthouse. A\n * deployed-audit URL flows in from Airtable's `url` column (or a JSON\n * inventory's `deployedUrl`), so a `file://`/`gopher://`/`data:` value — or a\n * value pointing at an internal host — would otherwise become a local-file read\n * or SSRF when lhci drives a headless browser at it. Restricting to http(s)\n * keeps the audit to the real, network-reachable site.\n */\nexport function isHttpUrl(s: string): boolean {\n let parsed: URL;\n try {\n parsed = new URL(s);\n } catch {\n return false;\n }\n return parsed.protocol === \"http:\" || parsed.protocol === \"https:\";\n}\n\n/**\n * The hostname of `s`, or `s` itself when it doesn't parse as a URL — a\n * human-facing fallback label, never a thrown error. Used anywhere a short\n * site label is wanted and the full URL would be noisy: the prospect-audit\n * CLI's summary line and its report's <h1>/title both fall back to this when\n * no business name was resolved.\n */\nexport function hostnameOf(s: string): string {\n try {\n return new URL(s).hostname;\n } catch {\n return s;\n }\n}\n\n/**\n * True when `s` is a URL served from Netlify's default `*.netlify.app` host —\n * i.e. the site has no custom domain. Matches the apex `netlify.app` and any\n * subdomain of it (including deploy-preview hosts like `branch--site.netlify.app`),\n * but is not fooled by a look-alike such as `foo.netlify.app.evil.com` (the host\n * must END at `.netlify.app`). An unparseable/empty value is not a match.\n */\nexport function isNetlifyAppUrl(s: string): boolean {\n let parsed: URL;\n try {\n parsed = new URL(s);\n } catch {\n return false;\n }\n const host = parsed.hostname.toLowerCase();\n return host === \"netlify.app\" || host.endsWith(\".netlify.app\");\n}\n\n/**\n * True when `hostname` is a loopback, private, link-local, unique-local, or\n * CGNAT literal address (or the `localhost` name) — the address-literal core\n * that used to live only inside `isPublicHttpsUrl`, pulled out so a caller\n * that legitimately handles non-https schemes (the prospect-audit crawler\n * audits plain http sites too) can still refuse to follow a redirect onto an\n * internal target. Scheme-agnostic on purpose: the caller decides which\n * protocols are acceptable, this only judges the host.\n *\n * Best-effort by literal address — it does NOT resolve DNS, so a hostname\n * that resolves to a private IP is not caught. That is a deliberate,\n * proportionate bound for an operator-run CLI, not a complete SSRF guard.\n */\nexport function isPrivateOrLoopbackHost(hostname: string): boolean {\n let host = hostname.toLowerCase();\n if (host === \"localhost\" || host.endsWith(\".localhost\")) return true;\n // Strip IPv6 brackets (`[::1]` → `::1`).\n if (host.startsWith(\"[\") && host.endsWith(\"]\")) host = host.slice(1, -1);\n if (host.includes(\":\")) {\n // IPv6 literal: block loopback (::1), unspecified (::), link-local (fe80::/10),\n // and unique-local (fc00::/7).\n if (host === \"::1\" || host === \"::\") return true;\n if (/^fe[89ab]/.test(host)) return true;\n if (/^f[cd]/.test(host)) return true;\n // IPv4-mapped (`::ffff:a.b.c.d`, normalized by URL to `::ffff:aabb:ccdd`) and\n // NAT64 (`64:ff9b::/96`) embed a v4 address the dotted-quad block below never\n // sees — refuse both wholesale (no legitimate target uses these forms).\n if (host.startsWith(\"::ffff:\") || host.startsWith(\"64:ff9b:\")) return true;\n return false;\n }\n // IPv4 dotted-quad: block the private/loopback/link-local/CGNAT ranges.\n if (/^\\d{1,3}(\\.\\d{1,3}){3}$/.test(host)) {\n const [a, b] = host.split(\".\").map(Number);\n if (a === 0 || a === 10 || a === 127) return true;\n if (a === 169 && b === 254) return true; // link-local\n if (a === 172 && b !== undefined && b >= 16 && b <= 31) return true; // 172.16/12\n if (a === 192 && b === 168) return true; // 192.168/16\n if (a === 100 && b !== undefined && b >= 64 && b <= 127) return true; // CGNAT 100.64/10\n return false;\n }\n // A registered hostname (not a literal IP) — accept; DNS isn't resolved here.\n return false;\n}\n\n/**\n * True when `s` is an `https:` URL whose host is NOT an obviously-internal target\n * (loopback / private / link-local / unique-local / CGNAT). The newsletter\n * webhook URL is operator-set in Airtable but fires server-side, so this blocks\n * the SSRF vector of pointing it at `127.0.0.1` / `10.x` / `169.254.x` / `::1`.\n *\n * Best-effort by host literal — it does NOT resolve DNS, so a hostname that\n * resolves to a private IP is not caught. Defense-in-depth, not a complete SSRF\n * guard (the response is never returned to the caller either, so it's a log\n * oracle at most).\n */\nexport function isPublicHttpsUrl(s: string): boolean {\n let parsed: URL;\n try {\n parsed = new URL(s);\n } catch {\n return false;\n }\n if (parsed.protocol !== \"https:\") return false;\n return !isPrivateOrLoopbackHost(parsed.hostname);\n}\n"],"mappings":";AAUO,SAAS,UAAU,GAAoB;AAC5C,MAAI;AACJ,MAAI;AACF,aAAS,IAAI,IAAI,CAAC;AAAA,EACpB,QAAQ;AACN,WAAO;AAAA,EACT;AACA,SAAO,OAAO,aAAa,WAAW,OAAO,aAAa;AAC5D;AASO,SAAS,WAAW,GAAmB;AAC5C,MAAI;AACF,WAAO,IAAI,IAAI,CAAC,EAAE;AAAA,EACpB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AASO,SAAS,gBAAgB,GAAoB;AAClD,MAAI;AACJ,MAAI;AACF,aAAS,IAAI,IAAI,CAAC;AAAA,EACpB,QAAQ;AACN,WAAO;AAAA,EACT;AACA,QAAM,OAAO,OAAO,SAAS,YAAY;AACzC,SAAO,SAAS,iBAAiB,KAAK,SAAS,cAAc;AAC/D;AAeO,SAAS,wBAAwB,UAA2B;AACjE,MAAI,OAAO,SAAS,YAAY;AAChC,MAAI,SAAS,eAAe,KAAK,SAAS,YAAY,EAAG,QAAO;AAEhE,MAAI,KAAK,WAAW,GAAG,KAAK,KAAK,SAAS,GAAG,EAAG,QAAO,KAAK,MAAM,GAAG,EAAE;AACvE,MAAI,KAAK,SAAS,GAAG,GAAG;AAGtB,QAAI,SAAS,SAAS,SAAS,KAAM,QAAO;AAC5C,QAAI,YAAY,KAAK,IAAI,EAAG,QAAO;AACnC,QAAI,SAAS,KAAK,IAAI,EAAG,QAAO;AAIhC,QAAI,KAAK,WAAW,SAAS,KAAK,KAAK,WAAW,UAAU,EAAG,QAAO;
|
|
1
|
+
{"version":3,"sources":["../src/util/url.ts"],"sourcesContent":["/**\n * True when `s` parses as an absolute URL whose scheme is `http:` or `https:`.\n *\n * The single allowlist gate for any value we hand to Chrome/Lighthouse. A\n * deployed-audit URL flows in from Airtable's `url` column (or a JSON\n * inventory's `deployedUrl`), so a `file://`/`gopher://`/`data:` value — or a\n * value pointing at an internal host — would otherwise become a local-file read\n * or SSRF when lhci drives a headless browser at it. Restricting to http(s)\n * keeps the audit to the real, network-reachable site.\n */\nexport function isHttpUrl(s: string): boolean {\n let parsed: URL;\n try {\n parsed = new URL(s);\n } catch {\n return false;\n }\n return parsed.protocol === \"http:\" || parsed.protocol === \"https:\";\n}\n\n/**\n * The hostname of `s`, or `s` itself when it doesn't parse as a URL — a\n * human-facing fallback label, never a thrown error. Used anywhere a short\n * site label is wanted and the full URL would be noisy: the prospect-audit\n * CLI's summary line and its report's <h1>/title both fall back to this when\n * no business name was resolved.\n */\nexport function hostnameOf(s: string): string {\n try {\n return new URL(s).hostname;\n } catch {\n return s;\n }\n}\n\n/**\n * True when `s` is a URL served from Netlify's default `*.netlify.app` host —\n * i.e. the site has no custom domain. Matches the apex `netlify.app` and any\n * subdomain of it (including deploy-preview hosts like `branch--site.netlify.app`),\n * but is not fooled by a look-alike such as `foo.netlify.app.evil.com` (the host\n * must END at `.netlify.app`). An unparseable/empty value is not a match.\n */\nexport function isNetlifyAppUrl(s: string): boolean {\n let parsed: URL;\n try {\n parsed = new URL(s);\n } catch {\n return false;\n }\n const host = parsed.hostname.toLowerCase();\n return host === \"netlify.app\" || host.endsWith(\".netlify.app\");\n}\n\n/**\n * True when `hostname` is a loopback, private, link-local, unique-local, or\n * CGNAT literal address (or the `localhost` name) — the address-literal core\n * that used to live only inside `isPublicHttpsUrl`, pulled out so a caller\n * that legitimately handles non-https schemes (the prospect-audit crawler\n * audits plain http sites too) can still refuse to follow a redirect onto an\n * internal target. Scheme-agnostic on purpose: the caller decides which\n * protocols are acceptable, this only judges the host.\n *\n * Best-effort by literal address — it does NOT resolve DNS, so a hostname\n * that resolves to a private IP is not caught. That is a deliberate,\n * proportionate bound for an operator-run CLI, not a complete SSRF guard.\n */\nexport function isPrivateOrLoopbackHost(hostname: string): boolean {\n let host = hostname.toLowerCase();\n if (host === \"localhost\" || host.endsWith(\".localhost\")) return true;\n // Strip IPv6 brackets (`[::1]` → `::1`).\n if (host.startsWith(\"[\") && host.endsWith(\"]\")) host = host.slice(1, -1);\n if (host.includes(\":\")) {\n // IPv6 literal: block loopback (::1), unspecified (::), link-local (fe80::/10),\n // and unique-local (fc00::/7).\n if (host === \"::1\" || host === \"::\") return true;\n if (/^fe[89ab]/.test(host)) return true;\n if (/^f[cd]/.test(host)) return true;\n // IPv4-mapped (`::ffff:a.b.c.d`, normalized by URL to `::ffff:aabb:ccdd`) and\n // NAT64 (`64:ff9b::/96`) embed a v4 address the dotted-quad block below never\n // sees — refuse both wholesale (no legitimate target uses these forms).\n if (host.startsWith(\"::ffff:\") || host.startsWith(\"64:ff9b:\")) return true;\n // The deprecated IPv4-COMPATIBLE form (`::a.b.c.d`) normalizes to a bare\n // `::x:y` with no `ffff:` marker, so the branch above misses it. Not\n // routable to loopback on Linux, but it costs one line to stop reasoning\n // about which stacks honour it: anything in `::/96` other than the\n // unspecified address embeds a v4 literal the dotted-quad block never sees.\n if (/^::(?!$)(?!0*:?$)[0-9a-f]{0,4}:?[0-9a-f]{0,4}$/.test(host)) return true;\n return false;\n }\n // IPv4 dotted-quad: block the private/loopback/link-local/CGNAT ranges.\n if (/^\\d{1,3}(\\.\\d{1,3}){3}$/.test(host)) {\n const [a, b] = host.split(\".\").map(Number);\n if (a === 0 || a === 10 || a === 127) return true;\n if (a === 169 && b === 254) return true; // link-local\n if (a === 172 && b !== undefined && b >= 16 && b <= 31) return true; // 172.16/12\n if (a === 192 && b === 168) return true; // 192.168/16\n if (a === 100 && b !== undefined && b >= 64 && b <= 127) return true; // CGNAT 100.64/10\n return false;\n }\n // A registered hostname (not a literal IP) — accept; DNS isn't resolved here.\n return false;\n}\n\n/**\n * True when `s` is an `https:` URL whose host is NOT an obviously-internal target\n * (loopback / private / link-local / unique-local / CGNAT). The newsletter\n * webhook URL is operator-set in Airtable but fires server-side, so this blocks\n * the SSRF vector of pointing it at `127.0.0.1` / `10.x` / `169.254.x` / `::1`.\n *\n * Best-effort by host literal — it does NOT resolve DNS, so a hostname that\n * resolves to a private IP is not caught. Defense-in-depth, not a complete SSRF\n * guard (the response is never returned to the caller either, so it's a log\n * oracle at most).\n */\nexport function isPublicHttpsUrl(s: string): boolean {\n let parsed: URL;\n try {\n parsed = new URL(s);\n } catch {\n return false;\n }\n if (parsed.protocol !== \"https:\") return false;\n return !isPrivateOrLoopbackHost(parsed.hostname);\n}\n"],"mappings":";AAUO,SAAS,UAAU,GAAoB;AAC5C,MAAI;AACJ,MAAI;AACF,aAAS,IAAI,IAAI,CAAC;AAAA,EACpB,QAAQ;AACN,WAAO;AAAA,EACT;AACA,SAAO,OAAO,aAAa,WAAW,OAAO,aAAa;AAC5D;AASO,SAAS,WAAW,GAAmB;AAC5C,MAAI;AACF,WAAO,IAAI,IAAI,CAAC,EAAE;AAAA,EACpB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AASO,SAAS,gBAAgB,GAAoB;AAClD,MAAI;AACJ,MAAI;AACF,aAAS,IAAI,IAAI,CAAC;AAAA,EACpB,QAAQ;AACN,WAAO;AAAA,EACT;AACA,QAAM,OAAO,OAAO,SAAS,YAAY;AACzC,SAAO,SAAS,iBAAiB,KAAK,SAAS,cAAc;AAC/D;AAeO,SAAS,wBAAwB,UAA2B;AACjE,MAAI,OAAO,SAAS,YAAY;AAChC,MAAI,SAAS,eAAe,KAAK,SAAS,YAAY,EAAG,QAAO;AAEhE,MAAI,KAAK,WAAW,GAAG,KAAK,KAAK,SAAS,GAAG,EAAG,QAAO,KAAK,MAAM,GAAG,EAAE;AACvE,MAAI,KAAK,SAAS,GAAG,GAAG;AAGtB,QAAI,SAAS,SAAS,SAAS,KAAM,QAAO;AAC5C,QAAI,YAAY,KAAK,IAAI,EAAG,QAAO;AACnC,QAAI,SAAS,KAAK,IAAI,EAAG,QAAO;AAIhC,QAAI,KAAK,WAAW,SAAS,KAAK,KAAK,WAAW,UAAU,EAAG,QAAO;AAMtE,QAAI,iDAAiD,KAAK,IAAI,EAAG,QAAO;AACxE,WAAO;AAAA,EACT;AAEA,MAAI,0BAA0B,KAAK,IAAI,GAAG;AACxC,UAAM,CAAC,GAAG,CAAC,IAAI,KAAK,MAAM,GAAG,EAAE,IAAI,MAAM;AACzC,QAAI,MAAM,KAAK,MAAM,MAAM,MAAM,IAAK,QAAO;AAC7C,QAAI,MAAM,OAAO,MAAM,IAAK,QAAO;AACnC,QAAI,MAAM,OAAO,MAAM,UAAa,KAAK,MAAM,KAAK,GAAI,QAAO;AAC/D,QAAI,MAAM,OAAO,MAAM,IAAK,QAAO;AACnC,QAAI,MAAM,OAAO,MAAM,UAAa,KAAK,MAAM,KAAK,IAAK,QAAO;AAChE,WAAO;AAAA,EACT;AAEA,SAAO;AACT;AAaO,SAAS,iBAAiB,GAAoB;AACnD,MAAI;AACJ,MAAI;AACF,aAAS,IAAI,IAAI,CAAC;AAAA,EACpB,QAAQ;AACN,WAAO;AAAA,EACT;AACA,MAAI,OAAO,aAAa,SAAU,QAAO;AACzC,SAAO,CAAC,wBAAwB,OAAO,QAAQ;AACjD;","names":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/db/freeze.ts"],"sourcesContent":["/** #612 (#539 Phase 5): the one switch that says which store is allowed to fail.\n *\n * ## Why a switch exists at all\n *\n * Through Phase 5 the mirrors are best-effort by design: Airtable is\n * authoritative, so a Turso write that fails is caught, logged and swallowed,\n * and the hourly `fleet-db-sync` import converges whatever it missed. That is\n * correct — right up until the freeze stops the import.\n *\n * After that, nothing converges anything. The same swallowed failure becomes\n * permanent data loss announced only by a log line nobody is grepping. Three\n * outcomes change meaning at the flip:\n *\n * | outcome | before the freeze | after |\n * |-------------------|--------------------------------|------------------------------|\n * | `mirrored=0` | the sync will fix it | that write is gone |\n * | `mirrored=missed` | the site isn't imported yet | impossible, therefore a bug |\n * | `mirrored=absent` | no creds; Airtable still has it| every write was discarded |\n *\n * So the freeze is not a config change. It is: invert which store is allowed\n * to fail.\n *\n * ## Why a code constant rather than an env var\n *\n * The same built artifact runs in Netlify functions and in Actions runners. An\n * env var could be set in one and missed in the other, giving a PARTIAL freeze\n * — half the fleet treating Turso as authoritative and half not — which is a\n * worse state than either end. A constant is uniform by construction, and\n * flipping it is a one-line pull request with a diff a reviewer can see.\n *\n * This is the same shape the site-status vocabulary migration used: code\n * handles both worlds, then one reviewed commit flips the switch.\n *\n * ## Reading this correctly\n *\n * Consumers take it as a DEFAULT parameter rather than reading it inline, so\n * tests can exercise both sides as fixtures. Exactly one test asserts the\n * shipped value; every behavioural test injects. A suite that only ever read\n * the shipped constant would prove nothing about the state it is not in.\n */\n\n/** `false` until the freeze. Flipping this to `true` is the freeze: Turso\n * becomes the store that must succeed, and the Airtable write becomes the\n * best-effort shadow kept for the one-week rollback window.\n *\n * Do not flip it before the hourly import is stopped — with the import still\n * running, a strict mirror would fail runs over rows the import was about to\n * reconcile anyway. */\nexport const TURSO_IS_AUTHORITATIVE = false;\n\n/**\n * Run one Turso mirror write with the error semantics the current world calls\n * for: swallowed while Airtable is authoritative, fatal once Turso is.\n *\n * The mirror FACTORIES (`makeSiteMirror`, `makeReportMirror`, the health mirrors)\n * already do this internally. The Netlify request handlers do not use those\n * factories — `approve-report`, `report-commentary`, `resend-webhook` and\n * `site-details` each call `mirrorReportPatch` / `mirrorSiteField` directly,\n * wrapped in a hand-rolled `try { … } catch { console.error }`. Four independent\n * copies of the swallow, none of which consulted the switch, each carrying a\n * comment saying \"the sync converges it\".\n *\n * **That comment stops being true at the freeze.** With the hourly import\n * stopped, a swallowed mirror failure on an approve, a commentary edit, a\n * delivery-status webhook or a site-detail edit is permanent data loss whose only\n * trace is a log line nobody greps — and the Airtable write it shadows will have\n * already succeeded, so the two stores diverge silently.\n *\n * Under `strict` the failure is raised instead. The caller's own error handling\n * decides what that means for the response; what it must not mean is \"logged and\n * forgotten\". `strict` is a parameter with the constant as its default so tests\n * exercise both worlds as fixtures rather than only the shipped one.\n */\nexport async function mirrorWrite(\n label: string,\n run: () => Promise<void>,\n strict: boolean = TURSO_IS_AUTHORITATIVE,\n): Promise<void> {\n try {\n await run();\n } catch (err) {\n if (strict) {\n throw new Error(\n `[${label}] Turso mirror failed and Turso is authoritative — ` +\n `the write is NOT recoverable by the hourly sync: ${String(err)}`,\n { cause: err },\n );\n }\n console.error(`[${label}] Turso mirror failed (sync will converge it): ${String(err)}`);\n }\n}\n"],"mappings":";AAgDO,IAAM,yBAAyB;","names":[]}
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import {
|
|
2
2
|
hostsMatch
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-JRHIFA5R.js";
|
|
4
4
|
import {
|
|
5
5
|
operatorEmail
|
|
6
6
|
} from "./chunk-5ML7FMBD.js";
|
|
7
7
|
import {
|
|
8
8
|
escapeHtml
|
|
9
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-BGTYPVLT.js";
|
|
10
10
|
|
|
11
11
|
// src/forms/notify.ts
|
|
12
12
|
var FORMS_FROM = "forms@reddoorla.com";
|
|
@@ -226,4 +226,4 @@ export {
|
|
|
226
226
|
notifySubmission,
|
|
227
227
|
makeNotify
|
|
228
228
|
};
|
|
229
|
-
//# sourceMappingURL=chunk-
|
|
229
|
+
//# sourceMappingURL=chunk-SJOXWJ5Y.js.map
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import {
|
|
2
2
|
fetchGaUsers,
|
|
3
3
|
fetchSearch
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-J3WEZGIN.js";
|
|
5
5
|
import {
|
|
6
6
|
announcementSiteExtras,
|
|
7
7
|
resolveCopy
|
|
8
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-KJGKZLCT.js";
|
|
9
9
|
import {
|
|
10
10
|
siteSlug
|
|
11
11
|
} from "./chunk-7NYN2P6I.js";
|
|
@@ -60,4 +60,4 @@ export {
|
|
|
60
60
|
scoresFromRow,
|
|
61
61
|
buildReportDataForSite
|
|
62
62
|
};
|
|
63
|
-
//# sourceMappingURL=chunk-
|
|
63
|
+
//# sourceMappingURL=chunk-ULHPALI5.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
openDb,
|
|
3
3
|
readDbConfig
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-WS6NU475.js";
|
|
5
5
|
|
|
6
6
|
// src/db/fleet-events.ts
|
|
7
7
|
async function recordFleetEvent(db, e) {
|
|
@@ -47,4 +47,4 @@ async function recordFleetEventsBestEffort(events, now, open = () => openDb(read
|
|
|
47
47
|
export {
|
|
48
48
|
recordFleetEventsBestEffort
|
|
49
49
|
};
|
|
50
|
-
//# sourceMappingURL=chunk-
|
|
50
|
+
//# sourceMappingURL=chunk-W45FZEGE.js.map
|