@reddoorla/maintenance 0.97.0 → 0.98.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/dist/{announce-5ZD2SBGD.js → announce-2FH2KBQQ.js} +4 -4
  2. package/dist/{bump-deps-775VLDYB.js → bump-deps-54K4ECP3.js} +2 -2
  3. package/dist/{chunk-YXWBM26P.js → chunk-3YALLSBF.js} +2 -2
  4. package/dist/{chunk-LAJ3FF54.js → chunk-5UI4FERC.js} +16 -5
  5. package/dist/chunk-5UI4FERC.js.map +1 -0
  6. package/dist/{chunk-VMGHQUTV.js → chunk-B2BRFWJY.js} +2 -2
  7. package/dist/{chunk-IOTOOTII.js → chunk-CP6MVZ5X.js} +16 -1
  8. package/dist/{chunk-IOTOOTII.js.map → chunk-CP6MVZ5X.js.map} +1 -1
  9. package/dist/{chunk-L3S3QZXL.js → chunk-DXZRWW2F.js} +64 -9
  10. package/dist/chunk-DXZRWW2F.js.map +1 -0
  11. package/dist/chunk-DZZ5KRTB.js +23 -0
  12. package/dist/chunk-DZZ5KRTB.js.map +1 -0
  13. package/dist/{chunk-U2ZI6G7H.js → chunk-GRF2RYEO.js} +2 -2
  14. package/dist/{chunk-QFSL2L2B.js → chunk-L5F3WYIY.js} +81 -31
  15. package/dist/chunk-L5F3WYIY.js.map +1 -0
  16. package/dist/{chunk-MMSMZC7S.js → chunk-MNRWHSFS.js} +2 -2
  17. package/dist/{chunk-PARKXDXI.js → chunk-ORTOMEYR.js} +2 -2
  18. package/dist/{chunk-FP6HOW6J.js → chunk-S2PLX4XK.js} +2 -2
  19. package/dist/{chunk-A5QKNOXW.js → chunk-TTT6HYPW.js} +47 -10
  20. package/dist/chunk-TTT6HYPW.js.map +1 -0
  21. package/dist/{chunk-BIYQN7FH.js → chunk-VCPTOZ56.js} +31 -1
  22. package/dist/{chunk-BIYQN7FH.js.map → chunk-VCPTOZ56.js.map} +1 -1
  23. package/dist/{chunk-LDHRIQUW.js → chunk-ZEE5WQYU.js} +2 -2
  24. package/dist/cli/bin.js +27 -27
  25. package/dist/cli/commands/audit.js +10 -10
  26. package/dist/client-3XGSZMLU.js +11 -0
  27. package/dist/{convert-to-pnpm-KLWA53N5.js → convert-to-pnpm-U2CRNKNY.js} +2 -2
  28. package/dist/{db-II5WAK4D.js → db-7XYTBIPH.js} +20 -13
  29. package/dist/db-7XYTBIPH.js.map +1 -0
  30. package/dist/{deadletter-G4M3HSVM.js → deadletter-A7RQVNG3.js} +8 -4
  31. package/dist/{digest-CWKK2DMR.js → digest-AMXRGWZA.js} +20 -20
  32. package/dist/{digest-collectors-CYTN2EUX.js → digest-collectors-CX2NCGS7.js} +7 -7
  33. package/dist/{ensure-site-2QZHFVQ3.js → ensure-site-F2WFCWWA.js} +2 -2
  34. package/dist/{forms-notify-target-X6UEOI2M.js → forms-notify-target-DK5R326N.js} +3 -3
  35. package/dist/{github-signals-QIRTHHET.js → github-signals-RGRPYTUB.js} +6 -6
  36. package/dist/{header-image-H7ZJAV26.js → header-image-43ZIEJKP.js} +3 -3
  37. package/dist/{health-endpoint-BJ6BKRHF.js → health-endpoint-K5LXDPGE.js} +2 -2
  38. package/dist/{health-mirror-KU3G7V2Y.js → health-mirror-WZUHWCCV.js} +3 -3
  39. package/dist/index.js +10 -11
  40. package/dist/index.js.map +1 -1
  41. package/dist/{init-GOWDA5QS.js → init-OFITGMOP.js} +5 -5
  42. package/dist/{launch-7N3X2MXB.js → launch-AJY3TGTQ.js} +7 -7
  43. package/dist/{lighthouse-52WSPZ5D.js → lighthouse-RFMFREEX.js} +2 -2
  44. package/dist/{match-harness-GBCDSVPS.js → match-harness-CFELJA57.js} +2 -2
  45. package/dist/migrate-EZL55AWA.js +7 -0
  46. package/dist/{onboard-JQQIMQW7.js → onboard-F7RTLMDZ.js} +2 -2
  47. package/dist/{orchestrate-L2A5BZFY.js → orchestrate-SAIFXZIW.js} +5 -5
  48. package/dist/{pipeline-UUPXOS2J.js → pipeline-TCSNVDQZ.js} +3 -3
  49. package/dist/{preflight-O7Q6FWHU.js → preflight-6XGVVO2U.js} +7 -7
  50. package/dist/{prismic-ci-NAPWOXXD.js → prismic-ci-XMX7A5E4.js} +2 -2
  51. package/dist/{prismic-models-LL6ORTQ2.js → prismic-models-7GKFAAFA.js} +4 -4
  52. package/dist/prospect/types.d.ts +44 -2
  53. package/dist/prospect/types.js +1 -1
  54. package/dist/{prospect-audit-FMPGQIRQ.js → prospect-audit-KWP5P5U2.js} +37 -5
  55. package/dist/prospect-audit-KWP5P5U2.js.map +1 -0
  56. package/dist/{render-MHUUHPLN.js → render-NWUAX6RN.js} +3 -3
  57. package/dist/{renovate-dispatch-2IHAZDVA.js → renovate-dispatch-ZZQXT7DA.js} +2 -2
  58. package/dist/replay-HB44TAII.js +77 -0
  59. package/dist/replay-HB44TAII.js.map +1 -0
  60. package/dist/{report-IAHXN5CW.js → report-MVPWS7WP.js} +13 -13
  61. package/dist/{report-mirror-4QM57LMS.js → report-mirror-O6IDFDWU.js} +3 -3
  62. package/dist/{roster-GDNSIRAK.js → roster-EJ3ILR52.js} +2 -2
  63. package/dist/{screenouts-7P5GOZMV.js → screenouts-7NQUWHOJ.js} +14 -1
  64. package/dist/screenouts-7NQUWHOJ.js.map +1 -0
  65. package/dist/{self-updating-ZUWPGYUP.js → self-updating-KX5FMGEO.js} +2 -2
  66. package/dist/{selftest-G4W3LIBQ.js → selftest-KABY2CYJ.js} +5 -5
  67. package/dist/{site-mirror-WR7ACXOV.js → site-mirror-TKTDWYP3.js} +3 -3
  68. package/dist/{smoke-suite-WAUPI6EJ.js → smoke-suite-QQMV7TNA.js} +2 -2
  69. package/dist/{submissions-JDZP35JM.js → submissions-4I66W6QK.js} +11 -1
  70. package/dist/{submissions-JDZP35JM.js.map → submissions-4I66W6QK.js.map} +1 -1
  71. package/dist/{submissions-2SHCFOKD.js → submissions-K5UXGZUN.js} +4 -4
  72. package/dist/{svelte-codemods-VOLOKKFI.js → svelte-codemods-YFN4TEGV.js} +2 -2
  73. package/dist/{sync-configs-OXSWKVZ2.js → sync-configs-HBXS3D7C.js} +2 -2
  74. package/dist/{upgrade-EVAL3JTO.js → upgrade-XOJMDIT4.js} +2 -2
  75. package/package.json +1 -1
  76. package/dist/chunk-A5QKNOXW.js.map +0 -1
  77. package/dist/chunk-L3S3QZXL.js.map +0 -1
  78. package/dist/chunk-LAJ3FF54.js.map +0 -1
  79. package/dist/chunk-QFSL2L2B.js.map +0 -1
  80. package/dist/client-DGTO65WB.js +0 -11
  81. package/dist/db-II5WAK4D.js.map +0 -1
  82. package/dist/migrate-XZ7U5DFC.js +0 -7
  83. package/dist/prospect-audit-FMPGQIRQ.js.map +0 -1
  84. package/dist/replay-4FVFOMHH.js +0 -54
  85. package/dist/replay-4FVFOMHH.js.map +0 -1
  86. package/dist/screenouts-7P5GOZMV.js.map +0 -1
  87. /package/dist/{announce-5ZD2SBGD.js.map → announce-2FH2KBQQ.js.map} +0 -0
  88. /package/dist/{bump-deps-775VLDYB.js.map → bump-deps-54K4ECP3.js.map} +0 -0
  89. /package/dist/{chunk-YXWBM26P.js.map → chunk-3YALLSBF.js.map} +0 -0
  90. /package/dist/{chunk-VMGHQUTV.js.map → chunk-B2BRFWJY.js.map} +0 -0
  91. /package/dist/{chunk-U2ZI6G7H.js.map → chunk-GRF2RYEO.js.map} +0 -0
  92. /package/dist/{chunk-MMSMZC7S.js.map → chunk-MNRWHSFS.js.map} +0 -0
  93. /package/dist/{chunk-PARKXDXI.js.map → chunk-ORTOMEYR.js.map} +0 -0
  94. /package/dist/{chunk-FP6HOW6J.js.map → chunk-S2PLX4XK.js.map} +0 -0
  95. /package/dist/{chunk-LDHRIQUW.js.map → chunk-ZEE5WQYU.js.map} +0 -0
  96. /package/dist/{client-DGTO65WB.js.map → client-3XGSZMLU.js.map} +0 -0
  97. /package/dist/{convert-to-pnpm-KLWA53N5.js.map → convert-to-pnpm-U2CRNKNY.js.map} +0 -0
  98. /package/dist/{deadletter-G4M3HSVM.js.map → deadletter-A7RQVNG3.js.map} +0 -0
  99. /package/dist/{digest-CWKK2DMR.js.map → digest-AMXRGWZA.js.map} +0 -0
  100. /package/dist/{digest-collectors-CYTN2EUX.js.map → digest-collectors-CX2NCGS7.js.map} +0 -0
  101. /package/dist/{ensure-site-2QZHFVQ3.js.map → ensure-site-F2WFCWWA.js.map} +0 -0
  102. /package/dist/{forms-notify-target-X6UEOI2M.js.map → forms-notify-target-DK5R326N.js.map} +0 -0
  103. /package/dist/{github-signals-QIRTHHET.js.map → github-signals-RGRPYTUB.js.map} +0 -0
  104. /package/dist/{header-image-H7ZJAV26.js.map → header-image-43ZIEJKP.js.map} +0 -0
  105. /package/dist/{health-endpoint-BJ6BKRHF.js.map → health-endpoint-K5LXDPGE.js.map} +0 -0
  106. /package/dist/{health-mirror-KU3G7V2Y.js.map → health-mirror-WZUHWCCV.js.map} +0 -0
  107. /package/dist/{init-GOWDA5QS.js.map → init-OFITGMOP.js.map} +0 -0
  108. /package/dist/{launch-7N3X2MXB.js.map → launch-AJY3TGTQ.js.map} +0 -0
  109. /package/dist/{lighthouse-52WSPZ5D.js.map → lighthouse-RFMFREEX.js.map} +0 -0
  110. /package/dist/{match-harness-GBCDSVPS.js.map → match-harness-CFELJA57.js.map} +0 -0
  111. /package/dist/{migrate-XZ7U5DFC.js.map → migrate-EZL55AWA.js.map} +0 -0
  112. /package/dist/{onboard-JQQIMQW7.js.map → onboard-F7RTLMDZ.js.map} +0 -0
  113. /package/dist/{orchestrate-L2A5BZFY.js.map → orchestrate-SAIFXZIW.js.map} +0 -0
  114. /package/dist/{pipeline-UUPXOS2J.js.map → pipeline-TCSNVDQZ.js.map} +0 -0
  115. /package/dist/{preflight-O7Q6FWHU.js.map → preflight-6XGVVO2U.js.map} +0 -0
  116. /package/dist/{prismic-ci-NAPWOXXD.js.map → prismic-ci-XMX7A5E4.js.map} +0 -0
  117. /package/dist/{prismic-models-LL6ORTQ2.js.map → prismic-models-7GKFAAFA.js.map} +0 -0
  118. /package/dist/{render-MHUUHPLN.js.map → render-NWUAX6RN.js.map} +0 -0
  119. /package/dist/{renovate-dispatch-2IHAZDVA.js.map → renovate-dispatch-ZZQXT7DA.js.map} +0 -0
  120. /package/dist/{report-IAHXN5CW.js.map → report-MVPWS7WP.js.map} +0 -0
  121. /package/dist/{report-mirror-4QM57LMS.js.map → report-mirror-O6IDFDWU.js.map} +0 -0
  122. /package/dist/{roster-GDNSIRAK.js.map → roster-EJ3ILR52.js.map} +0 -0
  123. /package/dist/{self-updating-ZUWPGYUP.js.map → self-updating-KX5FMGEO.js.map} +0 -0
  124. /package/dist/{selftest-G4W3LIBQ.js.map → selftest-KABY2CYJ.js.map} +0 -0
  125. /package/dist/{site-mirror-WR7ACXOV.js.map → site-mirror-TKTDWYP3.js.map} +0 -0
  126. /package/dist/{smoke-suite-WAUPI6EJ.js.map → smoke-suite-QQMV7TNA.js.map} +0 -0
  127. /package/dist/{submissions-2SHCFOKD.js.map → submissions-K5UXGZUN.js.map} +0 -0
  128. /package/dist/{svelte-codemods-VOLOKKFI.js.map → svelte-codemods-YFN4TEGV.js.map} +0 -0
  129. /package/dist/{sync-configs-OXSWKVZ2.js.map → sync-configs-HBXS3D7C.js.map} +0 -0
  130. /package/dist/{upgrade-EVAL3JTO.js.map → upgrade-XOJMDIT4.js.map} +0 -0
@@ -5,7 +5,7 @@ import {
5
5
  import {
6
6
  isProbablyEmail,
7
7
  parseAddresses
8
- } from "./chunk-LDHRIQUW.js";
8
+ } from "./chunk-ZEE5WQYU.js";
9
9
  import {
10
10
  gatingHealth,
11
11
  isSendOverridden
@@ -332,4 +332,4 @@ export {
332
332
  preflight,
333
333
  approveBlockers
334
334
  };
335
- //# sourceMappingURL=chunk-VMGHQUTV.js.map
335
+ //# sourceMappingURL=chunk-B2BRFWJY.js.map
@@ -528,6 +528,21 @@ var MIGRATIONS = [
528
528
  // submissions.resend_message_id for the bounce lookup. Single statement.
529
529
  id: "0027_reports_resend_message_index",
530
530
  sql: `CREATE INDEX IF NOT EXISTS idx_reports_resend_message ON reports (resend_message_id);`
531
+ },
532
+ {
533
+ // MED-11 of the 2026-09-02 review: `/s/:slug` built the fleet-wide unreplayed
534
+ // dead-letter map on every load and read one key out of it. The per-slug
535
+ // replacement (`countUnreplayedDeadLettersForSlug`) needs an index that
536
+ // starts with `site_slug` — served by 0005's `idx_deadletter_unreplayed
537
+ // (replayed_at)` it would visit every unreplayed row in the fleet and then
538
+ // do a rowid lookup into the payload-bearing table for each, which is what
539
+ // the grouped query's docblock says it exists to avoid.
540
+ //
541
+ // COVERING for the count: all three columns are in the index, so the query
542
+ // never touches a row carrying a client's lead payload. Single statement.
543
+ id: "0028_deadletter_slug_unreplayed_index",
544
+ sql: `CREATE INDEX IF NOT EXISTS idx_deadletter_slug_unreplayed
545
+ ON submission_deadletter (site_slug, replayed_at, abandoned_at);`
531
546
  }
532
547
  ];
533
548
 
@@ -562,4 +577,4 @@ async function runMigrations(client) {
562
577
  export {
563
578
  runMigrations
564
579
  };
565
- //# sourceMappingURL=chunk-IOTOOTII.js.map
580
+ //# sourceMappingURL=chunk-CP6MVZ5X.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 // #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 // `url` is stored exactly as audited, which makes it a record of the run and\n // a bad thing to group by: the table already holds beachfrontdentistry.com\n // and beachfrontdentistry.com/ as two histories of one practice, and both\n // spellings of ludlowkingsley.com. That costs nothing today because nothing\n // compares two audits of one site — and becomes a returning client with no\n // history the day the report offers a before and an after.\n //\n // Deliberately no SQL backfill. Doing it with lower()/replace()/rtrim()\n // would mangle any URL containing \"www.\" or \"http://\" away from its start,\n // and a key that is quietly wrong is worse than one that is null. Existing\n // rows are backfilled once with the real siteKey().\n // Same ADD COLUMN caveat as 0003: no IF NOT EXISTS in SQLite, so the runner\n // treats \"duplicate column name\" as already-applied. Kept as its own\n // migration, separate from its index below, so that recovery path stays a\n // single statement.\n id: \"0013_prospect_audits_site_key\",\n sql: `ALTER TABLE prospect_audits ADD COLUMN site_key TEXT;`,\n },\n {\n id: \"0014_prospect_audits_site_key_index\",\n sql: `\n CREATE INDEX IF NOT EXISTS idx_prospect_audits_site_key\n ON prospect_audits (site_key, created_at DESC);\n `,\n },\n {\n // Operator edits on a prospect report. One JSON blob rather than a side\n // table: the map is always read and written whole, and no query wants a\n // single override in isolation. Same shape of decision as `result_json`.\n //\n // THREE MIGRATIONS, NOT ONE. Verified against migrate.ts: it runs\n // `executeMultiple(m.sql)` inside a try, swallows any \"duplicate column\n // name\" error, then records the marker unconditionally. That recovery is\n // sound for ONE statement. With three, a crash partway through leaves the\n // marker unwritten; the re-run's first statement then throws duplicate,\n // executeMultiple aborts before the later statements, the catch swallows\n // it, and the marker IS written — leaving the remaining columns\n // permanently missing on a migration recorded as applied. Same rule as\n // 0003 and 0013.\n id: \"0015_prospect_audits_overrides\",\n sql: `ALTER TABLE prospect_audits ADD COLUMN overrides_json TEXT;`,\n },\n {\n id: \"0016_prospect_audits_edited_at\",\n sql: `ALTER TABLE prospect_audits ADD COLUMN edited_at TEXT;`,\n },\n {\n id: \"0017_prospect_audits_opened_at\",\n sql: `ALTER TABLE prospect_audits ADD COLUMN opened_at TEXT;`,\n },\n {\n // #783. Resend's `email.bounced` payload carries `data.bounce = { message,\n // subType, type }`; the webhook read only `data.email_id`, so the\n // classification was dropped and a dead mailbox stored identically to a\n // receiving server refusing our CONTENT. Espada sat under a CRITICAL\n // \"check the point-of-contact address\" for three days in September 2026\n // over an address that was fine — their inbound filter was refusing lead\n // notifications whose spam_score (30 and 55) sat under our auto-filter line.\n //\n // Nullable and never backfilled: every row written before this migration\n // has no classification, and `permanent` is counted only where the payload\n // actually SAID so. Inferring a diagnosis for the historical rows would\n // re-manufacture the exact wrong answer this change exists to stop.\n //\n // FOUR MIGRATIONS, NOT ONE — the same rule 0003, 0013 and 0015 carry, and\n // for the reason spelled out on 0015: `migrate.ts` swallows \"duplicate\n // column name\" and then records the marker unconditionally, which is sound\n // for ONE statement. Batched, a crash partway leaves the marker unwritten,\n // the re-run's first statement throws duplicate, `executeMultiple` aborts\n // before the rest, the catch swallows it and the marker IS written —\n // leaving the remaining columns permanently missing on a migration recorded\n // as applied.\n id: \"0018_submissions_bounce_type\",\n sql: `ALTER TABLE submissions ADD COLUMN bounce_type TEXT;`,\n },\n {\n id: \"0019_submissions_bounce_subtype\",\n sql: `ALTER TABLE submissions ADD COLUMN bounce_subtype TEXT;`,\n },\n {\n id: \"0020_submissions_bounce_message\",\n sql: `ALTER TABLE submissions ADD COLUMN bounce_message TEXT;`,\n },\n {\n // #783 item 3: the operator's exit. Before this, a diagnosed false alarm\n // could only be cleared by 14 days of aging or by a hand-written UPDATE\n // against the production `submissions` table — which is what actually\n // happened on 2026-09-14, flipping the two in-window rows from `bounced`\n // back to `sent` and destroying the evidence in the process.\n //\n // A stamp on the ROW rather than an `ack_until` on `sites` (the issue\n // offers both). The row marker clears the alarm EXACTLY — only the bounces\n // the operator actually looked at stop counting — where a site-level\n // window would mute every future bounce for its whole duration, including\n // a genuinely dead address appearing the next day. It also keeps the bounce\n // record intact, which the production workaround did not.\n id: \"0021_submissions_bounce_ack_at\",\n sql: `ALTER TABLE submissions ADD COLUMN bounce_ack_at TEXT;`,\n },\n {\n // #786, the other half of #785. That PR made `unknown-site` NON-terminal on\n // replay so both recovery orders are safe (`ensure-site` then replay, or\n // replay then `ensure-site`) — without it, replay-before-heal silently burns\n // every queued lead, and that is the order a person reaches for first.\n //\n // The cost, named at the time: a slug that is genuinely dead but still\n // deployed and posting grows the queue without bound, holds\n // `db replay-deadletters` at exit 1, and leaves a standing CRITICAL cockpit\n // item with no escape short of deleting rows by hand.\n //\n // `abandoned` is that escape — resolved by DECISION rather than by outcome.\n // Deliberately NOT reusing `replayed_at`/`replay_outcome`: those mean \"the\n // pipeline gave this lead an answer\", and a row marked replayed reads as a\n // lead that was placed, which is the opposite of what happened to it.\n //\n // who/when/why are three columns because the decision has to outlive the\n // person who made it; a bare timestamp would leave the next operator\n // guessing why a client's lead was written off.\n //\n // THREE MIGRATIONS, NOT ONE — the rule 0003, 0013 and 0015 already carry:\n // `migrate.ts` swallows \"duplicate column name\" then records the marker\n // unconditionally, which is only sound for a single statement.\n id: \"0022_deadletter_abandoned_at\",\n sql: `ALTER TABLE submission_deadletter ADD COLUMN abandoned_at TEXT;`,\n },\n {\n id: \"0023_deadletter_abandoned_by\",\n sql: `ALTER TABLE submission_deadletter ADD COLUMN abandoned_by TEXT;`,\n },\n {\n id: \"0024_deadletter_abandoned_reason\",\n sql: `ALTER TABLE submission_deadletter ADD COLUMN abandoned_reason TEXT;`,\n },\n {\n // #676. The searches behind \"Where you stand\" were chosen entirely by the\n // analyze stage from what it read on the site. For a client we know, better\n // ones can be written in two minutes — and a comparison over time needs the\n // terms to stay FIXED, which a model re-reading the site cannot promise.\n //\n // Stored on the ROW rather than only inside `result_json` for the two\n // reasons the issue names: a re-run can reuse them, and the /audits listing\n // can show which audits used chosen terms — that listing deliberately never\n // selects `result_json` (large, and useless to a list), so a value only\n // present in the blob could not reach it.\n //\n // JSON arrays in TEXT, NULL when nothing was chosen. Null is the load-\n // bearing state: it means the audit chose its own, which is not the same as\n // an operator supplying an empty list.\n //\n // TWO MIGRATIONS, NOT ONE — the rule 0003, 0013, 0015 and 0018 carry:\n // `migrate.ts` swallows \"duplicate column name\" and then records the marker\n // unconditionally, which is sound only for a single statement.\n id: \"0025_prospect_audits_chosen_terms\",\n sql: `ALTER TABLE prospect_audits ADD COLUMN chosen_terms TEXT;`,\n },\n {\n id: \"0026_prospect_audits_chosen_questions\",\n sql: `ALTER TABLE prospect_audits ADD COLUMN chosen_questions TEXT;`,\n },\n {\n // #539 Phase 6 step 2 (#646): the resend-webhook's REPORT lookup moved from\n // Airtable (`{Resend message ID} = \"…\"`) to Turso, as\n // fleet-state's findReportByMessageId. Every Resend delivery/bounce event\n // that is not a lead notification runs it, so the EXPLAIN-query-plan gate\n // (tests/db/query-plans.test.ts) needs it served by an index rather than a\n // scan of the HTML-bearing reports table — the same reason 0008 indexed\n // submissions.resend_message_id for the bounce lookup. Single statement.\n id: \"0027_reports_resend_message_index\",\n sql: `CREATE INDEX IF NOT EXISTS idx_reports_resend_message ON reports (resend_message_id);`,\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;AAAA,IAME,IAAI;AAAA,IACJ,KAAK;AAAA,EACP;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAgBE,IAAI;AAAA,IACJ,KAAK;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAeP;AA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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 // `url` is stored exactly as audited, which makes it a record of the run and\n // a bad thing to group by: the table already holds beachfrontdentistry.com\n // and beachfrontdentistry.com/ as two histories of one practice, and both\n // spellings of ludlowkingsley.com. That costs nothing today because nothing\n // compares two audits of one site — and becomes a returning client with no\n // history the day the report offers a before and an after.\n //\n // Deliberately no SQL backfill. Doing it with lower()/replace()/rtrim()\n // would mangle any URL containing \"www.\" or \"http://\" away from its start,\n // and a key that is quietly wrong is worse than one that is null. Existing\n // rows are backfilled once with the real siteKey().\n // Same ADD COLUMN caveat as 0003: no IF NOT EXISTS in SQLite, so the runner\n // treats \"duplicate column name\" as already-applied. Kept as its own\n // migration, separate from its index below, so that recovery path stays a\n // single statement.\n id: \"0013_prospect_audits_site_key\",\n sql: `ALTER TABLE prospect_audits ADD COLUMN site_key TEXT;`,\n },\n {\n id: \"0014_prospect_audits_site_key_index\",\n sql: `\n CREATE INDEX IF NOT EXISTS idx_prospect_audits_site_key\n ON prospect_audits (site_key, created_at DESC);\n `,\n },\n {\n // Operator edits on a prospect report. One JSON blob rather than a side\n // table: the map is always read and written whole, and no query wants a\n // single override in isolation. Same shape of decision as `result_json`.\n //\n // THREE MIGRATIONS, NOT ONE. Verified against migrate.ts: it runs\n // `executeMultiple(m.sql)` inside a try, swallows any \"duplicate column\n // name\" error, then records the marker unconditionally. That recovery is\n // sound for ONE statement. With three, a crash partway through leaves the\n // marker unwritten; the re-run's first statement then throws duplicate,\n // executeMultiple aborts before the later statements, the catch swallows\n // it, and the marker IS written — leaving the remaining columns\n // permanently missing on a migration recorded as applied. Same rule as\n // 0003 and 0013.\n id: \"0015_prospect_audits_overrides\",\n sql: `ALTER TABLE prospect_audits ADD COLUMN overrides_json TEXT;`,\n },\n {\n id: \"0016_prospect_audits_edited_at\",\n sql: `ALTER TABLE prospect_audits ADD COLUMN edited_at TEXT;`,\n },\n {\n id: \"0017_prospect_audits_opened_at\",\n sql: `ALTER TABLE prospect_audits ADD COLUMN opened_at TEXT;`,\n },\n {\n // #783. Resend's `email.bounced` payload carries `data.bounce = { message,\n // subType, type }`; the webhook read only `data.email_id`, so the\n // classification was dropped and a dead mailbox stored identically to a\n // receiving server refusing our CONTENT. Espada sat under a CRITICAL\n // \"check the point-of-contact address\" for three days in September 2026\n // over an address that was fine — their inbound filter was refusing lead\n // notifications whose spam_score (30 and 55) sat under our auto-filter line.\n //\n // Nullable and never backfilled: every row written before this migration\n // has no classification, and `permanent` is counted only where the payload\n // actually SAID so. Inferring a diagnosis for the historical rows would\n // re-manufacture the exact wrong answer this change exists to stop.\n //\n // FOUR MIGRATIONS, NOT ONE — the same rule 0003, 0013 and 0015 carry, and\n // for the reason spelled out on 0015: `migrate.ts` swallows \"duplicate\n // column name\" and then records the marker unconditionally, which is sound\n // for ONE statement. Batched, a crash partway leaves the marker unwritten,\n // the re-run's first statement throws duplicate, `executeMultiple` aborts\n // before the rest, the catch swallows it and the marker IS written —\n // leaving the remaining columns permanently missing on a migration recorded\n // as applied.\n id: \"0018_submissions_bounce_type\",\n sql: `ALTER TABLE submissions ADD COLUMN bounce_type TEXT;`,\n },\n {\n id: \"0019_submissions_bounce_subtype\",\n sql: `ALTER TABLE submissions ADD COLUMN bounce_subtype TEXT;`,\n },\n {\n id: \"0020_submissions_bounce_message\",\n sql: `ALTER TABLE submissions ADD COLUMN bounce_message TEXT;`,\n },\n {\n // #783 item 3: the operator's exit. Before this, a diagnosed false alarm\n // could only be cleared by 14 days of aging or by a hand-written UPDATE\n // against the production `submissions` table — which is what actually\n // happened on 2026-09-14, flipping the two in-window rows from `bounced`\n // back to `sent` and destroying the evidence in the process.\n //\n // A stamp on the ROW rather than an `ack_until` on `sites` (the issue\n // offers both). The row marker clears the alarm EXACTLY — only the bounces\n // the operator actually looked at stop counting — where a site-level\n // window would mute every future bounce for its whole duration, including\n // a genuinely dead address appearing the next day. It also keeps the bounce\n // record intact, which the production workaround did not.\n id: \"0021_submissions_bounce_ack_at\",\n sql: `ALTER TABLE submissions ADD COLUMN bounce_ack_at TEXT;`,\n },\n {\n // #786, the other half of #785. That PR made `unknown-site` NON-terminal on\n // replay so both recovery orders are safe (`ensure-site` then replay, or\n // replay then `ensure-site`) — without it, replay-before-heal silently burns\n // every queued lead, and that is the order a person reaches for first.\n //\n // The cost, named at the time: a slug that is genuinely dead but still\n // deployed and posting grows the queue without bound, holds\n // `db replay-deadletters` at exit 1, and leaves a standing CRITICAL cockpit\n // item with no escape short of deleting rows by hand.\n //\n // `abandoned` is that escape — resolved by DECISION rather than by outcome.\n // Deliberately NOT reusing `replayed_at`/`replay_outcome`: those mean \"the\n // pipeline gave this lead an answer\", and a row marked replayed reads as a\n // lead that was placed, which is the opposite of what happened to it.\n //\n // who/when/why are three columns because the decision has to outlive the\n // person who made it; a bare timestamp would leave the next operator\n // guessing why a client's lead was written off.\n //\n // THREE MIGRATIONS, NOT ONE — the rule 0003, 0013 and 0015 already carry:\n // `migrate.ts` swallows \"duplicate column name\" then records the marker\n // unconditionally, which is only sound for a single statement.\n id: \"0022_deadletter_abandoned_at\",\n sql: `ALTER TABLE submission_deadletter ADD COLUMN abandoned_at TEXT;`,\n },\n {\n id: \"0023_deadletter_abandoned_by\",\n sql: `ALTER TABLE submission_deadletter ADD COLUMN abandoned_by TEXT;`,\n },\n {\n id: \"0024_deadletter_abandoned_reason\",\n sql: `ALTER TABLE submission_deadletter ADD COLUMN abandoned_reason TEXT;`,\n },\n {\n // #676. The searches behind \"Where you stand\" were chosen entirely by the\n // analyze stage from what it read on the site. For a client we know, better\n // ones can be written in two minutes — and a comparison over time needs the\n // terms to stay FIXED, which a model re-reading the site cannot promise.\n //\n // Stored on the ROW rather than only inside `result_json` for the two\n // reasons the issue names: a re-run can reuse them, and the /audits listing\n // can show which audits used chosen terms — that listing deliberately never\n // selects `result_json` (large, and useless to a list), so a value only\n // present in the blob could not reach it.\n //\n // JSON arrays in TEXT, NULL when nothing was chosen. Null is the load-\n // bearing state: it means the audit chose its own, which is not the same as\n // an operator supplying an empty list.\n //\n // TWO MIGRATIONS, NOT ONE — the rule 0003, 0013, 0015 and 0018 carry:\n // `migrate.ts` swallows \"duplicate column name\" and then records the marker\n // unconditionally, which is sound only for a single statement.\n id: \"0025_prospect_audits_chosen_terms\",\n sql: `ALTER TABLE prospect_audits ADD COLUMN chosen_terms TEXT;`,\n },\n {\n id: \"0026_prospect_audits_chosen_questions\",\n sql: `ALTER TABLE prospect_audits ADD COLUMN chosen_questions TEXT;`,\n },\n {\n // #539 Phase 6 step 2 (#646): the resend-webhook's REPORT lookup moved from\n // Airtable (`{Resend message ID} = \"…\"`) to Turso, as\n // fleet-state's findReportByMessageId. Every Resend delivery/bounce event\n // that is not a lead notification runs it, so the EXPLAIN-query-plan gate\n // (tests/db/query-plans.test.ts) needs it served by an index rather than a\n // scan of the HTML-bearing reports table — the same reason 0008 indexed\n // submissions.resend_message_id for the bounce lookup. Single statement.\n id: \"0027_reports_resend_message_index\",\n sql: `CREATE INDEX IF NOT EXISTS idx_reports_resend_message ON reports (resend_message_id);`,\n },\n {\n // MED-11 of the 2026-09-02 review: `/s/:slug` built the fleet-wide unreplayed\n // dead-letter map on every load and read one key out of it. The per-slug\n // replacement (`countUnreplayedDeadLettersForSlug`) needs an index that\n // starts with `site_slug` — served by 0005's `idx_deadletter_unreplayed\n // (replayed_at)` it would visit every unreplayed row in the fleet and then\n // do a rowid lookup into the payload-bearing table for each, which is what\n // the grouped query's docblock says it exists to avoid.\n //\n // COVERING for the count: all three columns are in the index, so the query\n // never touches a row carrying a client's lead payload. Single statement.\n id: \"0028_deadletter_slug_unreplayed_index\",\n sql: `CREATE INDEX IF NOT EXISTS idx_deadletter_slug_unreplayed\n ON submission_deadletter (site_slug, replayed_at, abandoned_at);`,\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;AAAA,IAME,IAAI;AAAA,IACJ,KAAK;AAAA,EACP;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAgBE,IAAI;AAAA,IACJ,KAAK;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA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AAK,IAAI,CAAC,MAAM,OAAO,EAAE,EAAE,CAAC,CAAC;AAC9D,QAAM,MAAgB,CAAC;AACvB,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":[]}
@@ -9,8 +9,9 @@ import {
9
9
  } from "./chunk-43SW3FGW.js";
10
10
  import {
11
11
  lighthouseAudit,
12
- readSiteConfig
13
- } from "./chunk-BIYQN7FH.js";
12
+ readSiteConfig,
13
+ readsPlaceholderPrismicRepo
14
+ } from "./chunk-VCPTOZ56.js";
14
15
  import {
15
16
  smokeAudit
16
17
  } from "./chunk-UDRHAQT7.js";
@@ -653,6 +654,12 @@ async function securityAudit(ctx) {
653
654
  // src/audits/a11y.ts
654
655
  import { readFile as readFile3, writeFile, mkdtemp, rm } from "fs/promises";
655
656
  import { join as join4 } from "path";
657
+ var PLACEHOLDER_SKIP_REASON = "placeholder Prismic repo";
658
+ function classifyRouteResponse(input) {
659
+ if (input.status === 200) return "scan";
660
+ if (input.placeholder404Ok && input.status === 404) return "skip";
661
+ return "missing";
662
+ }
656
663
  var RESULTS_REL = ".reddoor-a11y/results.json";
657
664
  async function readJsonMaybe(path) {
658
665
  try {
@@ -722,6 +729,10 @@ import AxeBuilder from "@axe-core/playwright";
722
729
  import { mkdir, writeFile } from "node:fs/promises";
723
730
  import { dirname } from "node:path";
724
731
 
732
+ // Injected, not transcribed \u2014 see classifyRouteResponse in src/audits/a11y.ts.
733
+ const classifyRouteResponse = ${classifyRouteResponse.toString()};
734
+ const SKIP_REASON = ${JSON.stringify(PLACEHOLDER_SKIP_REASON)};
735
+
725
736
  const pages = ${JSON.stringify(axePages)};
726
737
  const smokePages = ${JSON.stringify(smokeRoutes)};
727
738
  // Absolute origin for the hydration smoke when the site has opted its gates
@@ -739,6 +750,10 @@ test.setTimeout(5 * 60_000);
739
750
 
740
751
  test("a11y + hydration across configured routes", async ({ page }) => {
741
752
  const violations = [];
753
+ // Routes navigated but deliberately not scanned. Separate from violations so
754
+ // they cannot fail the run, and written to the artifact so they cannot vanish
755
+ // from the summary either.
756
+ const skipped = [];
742
757
 
743
758
  // Capture uncaught client-side exceptions across every route we visit. A page
744
759
  // that builds + SSRs cleanly can still throw on hydrate and blank itself
@@ -754,9 +769,10 @@ test("a11y + hydration across configured routes", async ({ page }) => {
754
769
  });
755
770
  });
756
771
 
757
- for (const { path, name } of pages) {
772
+ for (const { path, name, placeholder404Ok } of pages) {
758
773
  currentRoute = name;
759
774
  const response = await page.goto(path);
775
+ const status = response ? response.status() : null;
760
776
  // A route that does not exist is a config problem, not a markup one. The
761
777
  // audit used to navigate, get a 404, run axe over whatever the error page
762
778
  // was and report the count -- for months that page was a bare fallback with
@@ -764,12 +780,24 @@ test("a11y + hydration across configured routes", async ({ page }) => {
764
780
  // gave its 404 page a designed watermark the count went to 1 with no route
765
781
  // and no rule in the summary, and the "violation" was bisected as markup
766
782
  // (#680). Name it as a missing route and do not scan the error page.
767
- if (!response || response.status() !== 200) {
783
+ //
784
+ // The one exception (#863): a site still on the starter's Prismic sentinel
785
+ // has no content to serve, so a 404 on ITS OWN routes is the designed
786
+ // answer. Those carry placeholder404Ok; the /dev fixtures never do.
787
+ const verdict = classifyRouteResponse({
788
+ status,
789
+ placeholder404Ok: placeholder404Ok === true,
790
+ });
791
+ if (verdict === "skip") {
792
+ skipped.push({ route: name, path, status, reason: SKIP_REASON });
793
+ continue;
794
+ }
795
+ if (verdict === "missing") {
768
796
  violations.push({
769
797
  id: "route-missing",
770
798
  impact: "serious",
771
799
  route: name,
772
- help: \`\${path} returned \${response ? response.status() : "no response"}\`,
800
+ help: \`\${path} returned \${status === null ? "no response" : status}\`,
773
801
  });
774
802
  continue;
775
803
  }
@@ -818,7 +846,11 @@ test("a11y + hydration across configured routes", async ({ page }) => {
818
846
  await mkdir(dirname(OUTPUT), { recursive: true });
819
847
  await writeFile(
820
848
  OUTPUT,
821
- JSON.stringify({ totalViolations: violations.length, byImpact, violations }, null, 2),
849
+ JSON.stringify(
850
+ { totalViolations: violations.length, byImpact, violations, skipped },
851
+ null,
852
+ 2,
853
+ ),
822
854
  );
823
855
  }
824
856
  expect(violations).toEqual([]);
@@ -843,6 +875,19 @@ function describeViolations(violations) {
843
875
  const rest = entries.length - shown.length;
844
876
  return shown.join(", ") + (rest > 0 ? `, +${rest} more` : "");
845
877
  }
878
+ var NAMED_SKIPS_MAX = 4;
879
+ function describeSkipped(skipped) {
880
+ if (skipped.length === 0) return "";
881
+ const shown = skipped.slice(0, NAMED_SKIPS_MAX).map((s) => s.route);
882
+ const rest = skipped.length - shown.length;
883
+ const names = shown.join(", ") + (rest > 0 ? `, +${rest} more` : "");
884
+ const reasons = [
885
+ ...new Set(
886
+ skipped.map((s) => s.reason).filter((r) => typeof r === "string" && r.length > 0)
887
+ )
888
+ ];
889
+ return `${skipped.length} skipped: ${names}${reasons.length > 0 ? ` \u2014 ${reasons.join(", ")}` : ""}`;
890
+ }
846
891
  async function a11yAudit(ctx) {
847
892
  const spawn = ctx.spawn ?? defaultSpawn;
848
893
  const site = ctx.site;
@@ -850,9 +895,14 @@ async function a11yAudit(ctx) {
850
895
  const specDir = await mkdtemp(join4(site.path, ".reddoor-a11y-spec-"));
851
896
  try {
852
897
  const { a11yRoutes: siteRoutes, gateServer } = await readSiteConfig(site.path);
898
+ const placeholderRepo = await readsPlaceholderPrismicRepo(site.path);
853
899
  const axePages = [
854
900
  ...a11yRoutes,
855
- ...(siteRoutes ?? []).map((path) => ({ path, name: path }))
901
+ ...(siteRoutes ?? []).map((path) => ({
902
+ path,
903
+ name: path,
904
+ ...placeholderRepo ? { placeholder404Ok: true } : {}
905
+ }))
856
906
  ];
857
907
  const port = await findFreePort();
858
908
  const previewPort = gateServer === "preview" ? await allocateDistinctPort(port) : void 0;
@@ -909,7 +959,12 @@ async function a11yAudit(ctx) {
909
959
  const hasAny = artifact.totalViolations > 0;
910
960
  const status = hasSerious ? "fail" : hasAny ? "warn" : "pass";
911
961
  const siteRouteCount = axePages.length - a11yRoutes.length;
912
- const scanned = siteRouteCount > 0 ? `${axePages.length} routes (${a11yRoutes.length} fixtures + ${siteRouteCount} from package.json)` : `${axePages.length} routes`;
962
+ const splitNote = siteRouteCount > 0 ? `${a11yRoutes.length} fixtures + ${siteRouteCount} from package.json` : "";
963
+ const skippedRoutes = Array.isArray(artifact.skipped) ? artifact.skipped : [];
964
+ const skipNote = describeSkipped(skippedRoutes);
965
+ const countPhrase = skippedRoutes.length > 0 ? `${axePages.length - skippedRoutes.length} of ${axePages.length} routes` : `${axePages.length} routes`;
966
+ const notes = [splitNote, skipNote].filter((n) => n.length > 0).join("; ");
967
+ const scanned = notes.length > 0 ? `${countPhrase} (${notes})` : countPhrase;
913
968
  const smokeNote = previewPort === void 0 ? `+${smokeRoutes.length} hydration smoke` : `+${smokeRoutes.length} hydration smoke on a production preview`;
914
969
  const named = describeViolations(artifact.violations ?? []);
915
970
  const summary = status === "pass" ? `a11y: 0 violations across ${scanned} (${smokeNote})` : `a11y: ${artifact.totalViolations} violations across ${scanned}${named ? ` \u2014 ${named}` : ""}`;
@@ -2195,4 +2250,4 @@ export {
2195
2250
  runAudits,
2196
2251
  runAuditsAcross
2197
2252
  };
2198
- //# sourceMappingURL=chunk-L3S3QZXL.js.map
2253
+ //# sourceMappingURL=chunk-DXZRWW2F.js.map