@reddoorla/maintenance 0.87.0 → 0.88.3

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 (189) hide show
  1. package/dist/airtable-QG5ICI3Y.js +9 -0
  2. package/dist/{announce-I2Z4JN3I.js → announce-GKD5YJNB.js} +9 -9
  3. package/dist/{blux-ZGDSHI3U.js → blux-EATHOHKK.js} +5 -5
  4. package/dist/{bump-deps-CGVELRLK.js → bump-deps-KGH5UYSF.js} +4 -4
  5. package/dist/{chunk-SDDPUAWH.js → chunk-6I6L3CMX.js} +2 -2
  6. package/dist/{chunk-NXNPDCF3.js → chunk-6UCVWYDA.js} +11 -1
  7. package/dist/chunk-6UCVWYDA.js.map +1 -0
  8. package/dist/{chunk-ZBDZTJUO.js → chunk-7FFUBF4I.js} +5 -2
  9. package/dist/chunk-7FFUBF4I.js.map +1 -0
  10. package/dist/{chunk-3JQ2FO3D.js → chunk-B23FFWU4.js} +2 -2
  11. package/dist/{chunk-DJZWYIPP.js → chunk-BGTYPVLT.js} +1 -1
  12. package/dist/chunk-BGTYPVLT.js.map +1 -0
  13. package/dist/chunk-BRYXFH77.js +70 -0
  14. package/dist/chunk-BRYXFH77.js.map +1 -0
  15. package/dist/{chunk-HSI6Q7MI.js → chunk-CEW5PEHZ.js} +168 -31
  16. package/dist/chunk-CEW5PEHZ.js.map +1 -0
  17. package/dist/{chunk-NDWYJLRF.js → chunk-DGZWFI2G.js} +3 -3
  18. package/dist/{chunk-HHMMUR4P.js → chunk-GQDDWYU2.js} +45 -8
  19. package/dist/chunk-GQDDWYU2.js.map +1 -0
  20. package/dist/{chunk-BBUSGEES.js → chunk-J3WEZGIN.js} +6 -6
  21. package/dist/{chunk-BNM5POSJ.js → chunk-JRHIFA5R.js} +2 -2
  22. package/dist/{chunk-MT2JINSS.js → chunk-KJGKZLCT.js} +3 -3
  23. package/dist/{chunk-3SF7D4DY.js → chunk-MFHS7IQ2.js} +36 -1
  24. package/dist/{chunk-3SF7D4DY.js.map → chunk-MFHS7IQ2.js.map} +1 -1
  25. package/dist/{chunk-SNSTJLQW.js → chunk-NO74DXDP.js} +48 -2
  26. package/dist/chunk-NO74DXDP.js.map +1 -0
  27. package/dist/{chunk-C6B4RHXR.js → chunk-O3GT46R2.js} +8 -2
  28. package/dist/chunk-O3GT46R2.js.map +1 -0
  29. package/dist/{chunk-C6CLRKPV.js → chunk-PR343K7F.js} +2 -2
  30. package/dist/{chunk-CROKUHJB.js → chunk-Q47DU255.js} +4 -4
  31. package/dist/{chunk-EVBCK2KC.js → chunk-RARREDQE.js} +2 -1
  32. package/dist/{chunk-EVBCK2KC.js.map → chunk-RARREDQE.js.map} +1 -1
  33. package/dist/chunk-RUPPWAD6.js +7 -0
  34. package/dist/chunk-RUPPWAD6.js.map +1 -0
  35. package/dist/{chunk-VSBFM7DS.js → chunk-SJOXWJ5Y.js} +3 -3
  36. package/dist/{chunk-HEWSRXYV.js → chunk-ULHPALI5.js} +3 -3
  37. package/dist/{chunk-XUGSZP7Z.js → chunk-W45FZEGE.js} +2 -2
  38. package/dist/{chunk-NCMZMLY7.js → chunk-WPL5GERE.js} +5 -69
  39. package/dist/chunk-WPL5GERE.js.map +1 -0
  40. package/dist/{chunk-JHGHLKFS.js → chunk-WS6NU475.js} +2 -2
  41. package/dist/{chunk-DEWJMMG3.js → chunk-XKDCR4UE.js} +19 -8
  42. package/dist/chunk-XKDCR4UE.js.map +1 -0
  43. package/dist/{chunk-ZGBEIWSC.js → chunk-XP5WM2LV.js} +5 -5
  44. package/dist/{chunk-TD2NNXLZ.js → chunk-XSOINOPY.js} +8 -8
  45. package/dist/{chunk-6TWWY7ZU.js → chunk-Z3JXLULD.js} +2 -2
  46. package/dist/cli/bin.js +31 -28
  47. package/dist/cli/bin.js.map +1 -1
  48. package/dist/cli/commands/audit.d.ts +4 -0
  49. package/dist/cli/commands/audit.js +16 -13
  50. package/dist/cli/commands/audit.js.map +1 -1
  51. package/dist/client-JYKPVCJX.js +11 -0
  52. package/dist/configs/playwright-a11y.js +1 -1
  53. package/dist/{convert-to-pnpm-QFJOEP5V.js → convert-to-pnpm-NWB5FCQ2.js} +4 -4
  54. package/dist/{db-UXNIZ2RG.js → db-DXUUAMXT.js} +121 -26
  55. package/dist/db-DXUUAMXT.js.map +1 -0
  56. package/dist/{digest-FW6QMZZJ.js → digest-NBLECFM7.js} +110 -29
  57. package/dist/digest-NBLECFM7.js.map +1 -0
  58. package/dist/digest-collectors-NM7WUWQP.js +50 -0
  59. package/dist/digest-state-3KHZF7GD.js +50 -0
  60. package/dist/digest-state-3KHZF7GD.js.map +1 -0
  61. package/dist/digest-state-F37XUCS5.js +13 -0
  62. package/dist/{dump-P6EBSIOH.js → dump-EPL7AZFR.js} +38 -13
  63. package/dist/dump-EPL7AZFR.js.map +1 -0
  64. package/dist/{email-KJXASVH5.js → email-FMMEUPX6.js} +16 -6
  65. package/dist/{email-KJXASVH5.js.map → email-FMMEUPX6.js.map} +1 -1
  66. package/dist/{ensure-site-4DCEBAPM.js → ensure-site-FU6527OU.js} +2 -2
  67. package/dist/{fleet-state-7TJ2GYT2.js → fleet-state-R5LU7IC3.js} +4 -2
  68. package/dist/{forms-notify-target-2EAWCWBW.js → forms-notify-target-SGDGXXK5.js} +6 -6
  69. package/dist/{github-signals-E2WPYTBK.js → github-signals-DB25UWY4.js} +7 -6
  70. package/dist/{github-signals-E2WPYTBK.js.map → github-signals-DB25UWY4.js.map} +1 -1
  71. package/dist/{header-image-6IC53W27.js → header-image-7A7XLVEU.js} +2 -2
  72. package/dist/{health-endpoint-RFXL2F4A.js → health-endpoint-UVX6R5N5.js} +4 -4
  73. package/dist/{health-mirror-L5JBEJVA.js → health-mirror-GCDN7BJL.js} +11 -6
  74. package/dist/health-mirror-GCDN7BJL.js.map +1 -0
  75. package/dist/index.d.ts +3 -0
  76. package/dist/index.js +136 -95
  77. package/dist/index.js.map +1 -1
  78. package/dist/{init-XRAQZYID.js → init-32AWPS7A.js} +9 -9
  79. package/dist/{launch-IX4Y5JJC.js → launch-52WUE4TZ.js} +12 -11
  80. package/dist/{launch-IX4Y5JJC.js.map → launch-52WUE4TZ.js.map} +1 -1
  81. package/dist/migrate-YITCXBLS.js +7 -0
  82. package/dist/{notify-C645PGD5.js → notify-4HP4GZ2H.js} +5 -5
  83. package/dist/{onboard-O4IAHJMO.js → onboard-BKCYBAVW.js} +4 -4
  84. package/dist/{orchestrate-YLWQ6KK2.js → orchestrate-JNKCWU5K.js} +9 -9
  85. package/dist/{parity-56KA2DGR.js → parity-NBYZUBFU.js} +4 -2
  86. package/dist/pdf-N5QLQ5ZQ.js +38 -0
  87. package/dist/pdf-N5QLQ5ZQ.js.map +1 -0
  88. package/dist/{pipeline-3AANZFCR.js → pipeline-YIBIQ7XK.js} +3 -3
  89. package/dist/{preflight-TNORKGCX.js → preflight-IMTYDDD4.js} +10 -10
  90. package/dist/{prismic-ci-G2AK53VL.js → prismic-ci-MY2U6NN7.js} +4 -4
  91. package/dist/{prismic-models-O6Z3OK3A.js → prismic-models-IJWZW2EO.js} +6 -6
  92. package/dist/prospect/types.d.ts +33 -0
  93. package/dist/{prospect-audit-KSXUNQ5J.js → prospect-audit-WJQI7V5V.js} +32 -13
  94. package/dist/prospect-audit-WJQI7V5V.js.map +1 -0
  95. package/dist/render-CVKE7IWC.js +10 -0
  96. package/dist/{render-from-row-BWSOIYDS.js → render-from-row-DOYJDO2L.js} +5 -5
  97. package/dist/{replay-C2LXMJZP.js → replay-4S6ENYCH.js} +3 -3
  98. package/dist/{report-R3E3Y7HR.js → report-2LM2SX67.js} +20 -20
  99. package/dist/{report-mirror-4MNORYQ4.js → report-mirror-AAK3MXHY.js} +12 -6
  100. package/dist/report-mirror-AAK3MXHY.js.map +1 -0
  101. package/dist/schema-75PJECAE.js +18 -0
  102. package/dist/schema-75PJECAE.js.map +1 -0
  103. package/dist/{self-updating-UCIWESAX.js → self-updating-NTCCWJYZ.js} +4 -4
  104. package/dist/{selftest-VGHWPN72.js → selftest-DIZ5JD2X.js} +12 -12
  105. package/dist/{site-mirror-NIREX5ME.js → site-mirror-Q763PLGG.js} +17 -7
  106. package/dist/site-mirror-Q763PLGG.js.map +1 -0
  107. package/dist/{smoke-suite-U3UKD3NS.js → smoke-suite-4JFZZYVW.js} +4 -4
  108. package/dist/{spam-classifier-XLBFCO7G.js → spam-classifier-T5H4VTP6.js} +4 -2
  109. package/dist/spam-classifier-T5H4VTP6.js.map +1 -0
  110. package/dist/{submissions-IQEJX6FK.js → submissions-TEHPBSZJ.js} +4 -4
  111. package/dist/{svelte-codemods-GOKXTBHW.js → svelte-codemods-QAPDZC6F.js} +4 -4
  112. package/dist/{sync-CTUVXMCK.js → sync-GBFV45WX.js} +4 -2
  113. package/dist/{sync-CTUVXMCK.js.map → sync-GBFV45WX.js.map} +1 -1
  114. package/dist/{sync-configs-SPTLFJCC.js → sync-configs-34JIA6KZ.js} +4 -4
  115. package/dist/{upgrade-W6ZR3FJH.js → upgrade-IR2OO3KP.js} +4 -4
  116. package/dist/{webhook-VOGOW3W6.js → webhook-XM6EV4XT.js} +2 -2
  117. package/dist/{write-audits-to-airtable-CMKHGJNQ.js → write-audits-to-airtable-OPBJXGS4.js} +5 -2
  118. package/dist/write-audits-to-airtable-OPBJXGS4.js.map +1 -0
  119. package/package.json +1 -1
  120. package/dist/airtable-ZBUPQJSC.js +0 -9
  121. package/dist/chunk-C6B4RHXR.js.map +0 -1
  122. package/dist/chunk-DEWJMMG3.js.map +0 -1
  123. package/dist/chunk-DJZWYIPP.js.map +0 -1
  124. package/dist/chunk-HHMMUR4P.js.map +0 -1
  125. package/dist/chunk-HSI6Q7MI.js.map +0 -1
  126. package/dist/chunk-NCMZMLY7.js.map +0 -1
  127. package/dist/chunk-NXNPDCF3.js.map +0 -1
  128. package/dist/chunk-SNSTJLQW.js.map +0 -1
  129. package/dist/chunk-ZBDZTJUO.js.map +0 -1
  130. package/dist/client-AUE3XUPO.js +0 -11
  131. package/dist/db-UXNIZ2RG.js.map +0 -1
  132. package/dist/digest-FW6QMZZJ.js.map +0 -1
  133. package/dist/dump-P6EBSIOH.js.map +0 -1
  134. package/dist/health-mirror-L5JBEJVA.js.map +0 -1
  135. package/dist/migrate-GQH237A6.js +0 -7
  136. package/dist/prospect-audit-KSXUNQ5J.js.map +0 -1
  137. package/dist/render-IFOGFB5T.js +0 -10
  138. package/dist/report-mirror-4MNORYQ4.js.map +0 -1
  139. package/dist/site-mirror-NIREX5ME.js.map +0 -1
  140. /package/dist/{airtable-ZBUPQJSC.js.map → airtable-QG5ICI3Y.js.map} +0 -0
  141. /package/dist/{announce-I2Z4JN3I.js.map → announce-GKD5YJNB.js.map} +0 -0
  142. /package/dist/{blux-ZGDSHI3U.js.map → blux-EATHOHKK.js.map} +0 -0
  143. /package/dist/{bump-deps-CGVELRLK.js.map → bump-deps-KGH5UYSF.js.map} +0 -0
  144. /package/dist/{chunk-SDDPUAWH.js.map → chunk-6I6L3CMX.js.map} +0 -0
  145. /package/dist/{chunk-3JQ2FO3D.js.map → chunk-B23FFWU4.js.map} +0 -0
  146. /package/dist/{chunk-NDWYJLRF.js.map → chunk-DGZWFI2G.js.map} +0 -0
  147. /package/dist/{chunk-BBUSGEES.js.map → chunk-J3WEZGIN.js.map} +0 -0
  148. /package/dist/{chunk-BNM5POSJ.js.map → chunk-JRHIFA5R.js.map} +0 -0
  149. /package/dist/{chunk-MT2JINSS.js.map → chunk-KJGKZLCT.js.map} +0 -0
  150. /package/dist/{chunk-C6CLRKPV.js.map → chunk-PR343K7F.js.map} +0 -0
  151. /package/dist/{chunk-CROKUHJB.js.map → chunk-Q47DU255.js.map} +0 -0
  152. /package/dist/{chunk-VSBFM7DS.js.map → chunk-SJOXWJ5Y.js.map} +0 -0
  153. /package/dist/{chunk-HEWSRXYV.js.map → chunk-ULHPALI5.js.map} +0 -0
  154. /package/dist/{chunk-XUGSZP7Z.js.map → chunk-W45FZEGE.js.map} +0 -0
  155. /package/dist/{chunk-JHGHLKFS.js.map → chunk-WS6NU475.js.map} +0 -0
  156. /package/dist/{chunk-ZGBEIWSC.js.map → chunk-XP5WM2LV.js.map} +0 -0
  157. /package/dist/{chunk-TD2NNXLZ.js.map → chunk-XSOINOPY.js.map} +0 -0
  158. /package/dist/{chunk-6TWWY7ZU.js.map → chunk-Z3JXLULD.js.map} +0 -0
  159. /package/dist/{client-AUE3XUPO.js.map → client-JYKPVCJX.js.map} +0 -0
  160. /package/dist/{convert-to-pnpm-QFJOEP5V.js.map → convert-to-pnpm-NWB5FCQ2.js.map} +0 -0
  161. /package/dist/{fleet-state-7TJ2GYT2.js.map → digest-collectors-NM7WUWQP.js.map} +0 -0
  162. /package/dist/{migrate-GQH237A6.js.map → digest-state-F37XUCS5.js.map} +0 -0
  163. /package/dist/{ensure-site-4DCEBAPM.js.map → ensure-site-FU6527OU.js.map} +0 -0
  164. /package/dist/{notify-C645PGD5.js.map → fleet-state-R5LU7IC3.js.map} +0 -0
  165. /package/dist/{forms-notify-target-2EAWCWBW.js.map → forms-notify-target-SGDGXXK5.js.map} +0 -0
  166. /package/dist/{header-image-6IC53W27.js.map → header-image-7A7XLVEU.js.map} +0 -0
  167. /package/dist/{health-endpoint-RFXL2F4A.js.map → health-endpoint-UVX6R5N5.js.map} +0 -0
  168. /package/dist/{init-XRAQZYID.js.map → init-32AWPS7A.js.map} +0 -0
  169. /package/dist/{orchestrate-YLWQ6KK2.js.map → migrate-YITCXBLS.js.map} +0 -0
  170. /package/dist/{parity-56KA2DGR.js.map → notify-4HP4GZ2H.js.map} +0 -0
  171. /package/dist/{onboard-O4IAHJMO.js.map → onboard-BKCYBAVW.js.map} +0 -0
  172. /package/dist/{pipeline-3AANZFCR.js.map → orchestrate-JNKCWU5K.js.map} +0 -0
  173. /package/dist/{render-IFOGFB5T.js.map → parity-NBYZUBFU.js.map} +0 -0
  174. /package/dist/{render-from-row-BWSOIYDS.js.map → pipeline-YIBIQ7XK.js.map} +0 -0
  175. /package/dist/{preflight-TNORKGCX.js.map → preflight-IMTYDDD4.js.map} +0 -0
  176. /package/dist/{prismic-ci-G2AK53VL.js.map → prismic-ci-MY2U6NN7.js.map} +0 -0
  177. /package/dist/{prismic-models-O6Z3OK3A.js.map → prismic-models-IJWZW2EO.js.map} +0 -0
  178. /package/dist/{spam-classifier-XLBFCO7G.js.map → render-CVKE7IWC.js.map} +0 -0
  179. /package/dist/{write-audits-to-airtable-CMKHGJNQ.js.map → render-from-row-DOYJDO2L.js.map} +0 -0
  180. /package/dist/{replay-C2LXMJZP.js.map → replay-4S6ENYCH.js.map} +0 -0
  181. /package/dist/{report-R3E3Y7HR.js.map → report-2LM2SX67.js.map} +0 -0
  182. /package/dist/{self-updating-UCIWESAX.js.map → self-updating-NTCCWJYZ.js.map} +0 -0
  183. /package/dist/{selftest-VGHWPN72.js.map → selftest-DIZ5JD2X.js.map} +0 -0
  184. /package/dist/{smoke-suite-U3UKD3NS.js.map → smoke-suite-4JFZZYVW.js.map} +0 -0
  185. /package/dist/{submissions-IQEJX6FK.js.map → submissions-TEHPBSZJ.js.map} +0 -0
  186. /package/dist/{svelte-codemods-GOKXTBHW.js.map → svelte-codemods-QAPDZC6F.js.map} +0 -0
  187. /package/dist/{sync-configs-SPTLFJCC.js.map → sync-configs-34JIA6KZ.js.map} +0 -0
  188. /package/dist/{upgrade-W6ZR3FJH.js.map → upgrade-IR2OO3KP.js.map} +0 -0
  189. /package/dist/{webhook-VOGOW3W6.js.map → webhook-XM6EV4XT.js.map} +0 -0
@@ -1,9 +1,9 @@
1
1
  // src/cli/commands/db.ts
2
2
  async function runDbCommand(action, opts) {
3
3
  if (action === "migrate") {
4
- const { readDbConfig } = await import("./client-AUE3XUPO.js");
4
+ const { readDbConfig } = await import("./client-JYKPVCJX.js");
5
5
  const cfg = opts.url ? { url: opts.url } : readDbConfig();
6
- const { runMigrations } = await import("./migrate-GQH237A6.js");
6
+ const { runMigrations } = await import("./migrate-YITCXBLS.js");
7
7
  const { createClient } = await import("@libsql/client");
8
8
  const client = createClient(cfg.url === ":memory:" ? { url: ":memory:" } : cfg);
9
9
  const ran = await runMigrations(client);
@@ -13,7 +13,7 @@ async function runDbCommand(action, opts) {
13
13
  };
14
14
  }
15
15
  if (action === "replay-deadletters") {
16
- const { readDbConfig, openDb } = await import("./client-AUE3XUPO.js");
16
+ const { readDbConfig, openDb } = await import("./client-JYKPVCJX.js");
17
17
  const db = await openDb(opts.url ? { url: opts.url } : readDbConfig());
18
18
  const { openBase, readAirtableConfig } = await import("./client-EPVO3FEH.js");
19
19
  const { getWebsiteBySlug } = await import("./websites-D6WYFAES.js");
@@ -26,12 +26,12 @@ async function runDbCommand(action, opts) {
26
26
  listRecentSubmissionsForEmail,
27
27
  markSubmissionsSpamRetro
28
28
  } = await import("./submissions-3I3GAQAX.js");
29
- const { makeNotify } = await import("./notify-C645PGD5.js");
30
- const { classifySpam } = await import("./spam-classifier-XLBFCO7G.js");
31
- const { forwardNewsletterToWebhook } = await import("./webhook-VOGOW3W6.js");
29
+ const { makeNotify } = await import("./notify-4HP4GZ2H.js");
30
+ const { classifySpam } = await import("./spam-classifier-T5H4VTP6.js");
31
+ const { forwardNewsletterToWebhook } = await import("./webhook-XM6EV4XT.js");
32
32
  const { addMailchimpMember, mailchimpTagsFor } = await import("./mailchimp-XYCTEEJY.js");
33
33
  const { defaultResendClient } = await import("./resend-G2BJMAQV.js");
34
- const { replayDeadLetters } = await import("./replay-C2LXMJZP.js");
34
+ const { replayDeadLetters } = await import("./replay-4S6ENYCH.js");
35
35
  let send = null;
36
36
  try {
37
37
  send = defaultResendClient().send;
@@ -75,7 +75,7 @@ async function runDbCommand(action, opts) {
75
75
  return { output: lines.join("\n"), code: result.stillFailing.length > 0 ? 1 : 0 };
76
76
  }
77
77
  if (action === "import-airtable" || action === "parity" || action === "sync") {
78
- const { readDbConfig, openDb } = await import("./client-AUE3XUPO.js");
78
+ const { readDbConfig, openDb } = await import("./client-JYKPVCJX.js");
79
79
  const db = await openDb(opts.url ? { url: opts.url } : readDbConfig());
80
80
  const { openBase, readAirtableConfig } = await import("./client-EPVO3FEH.js");
81
81
  const base = openBase(readAirtableConfig());
@@ -116,7 +116,7 @@ async function runDbCommand(action, opts) {
116
116
  return { output: lines.join("\n"), code: 0 };
117
117
  }
118
118
  if (action === "sync") {
119
- const { syncFleetState, formatSyncResult } = await import("./sync-CTUVXMCK.js");
119
+ const { syncFleetState, formatSyncResult } = await import("./sync-GBFV45WX.js");
120
120
  const result2 = await syncFleetState(db, {
121
121
  ...io,
122
122
  fetchAttachment: async (url) => {
@@ -133,12 +133,12 @@ async function runDbCommand(action, opts) {
133
133
  code: result2.parity.mismatches.length > 0 ? 1 : 0
134
134
  };
135
135
  }
136
- const { checkFleetParity, formatParityResult } = await import("./parity-56KA2DGR.js");
136
+ const { checkFleetParity, formatParityResult } = await import("./parity-NBYZUBFU.js");
137
137
  const result = await checkFleetParity(db, io);
138
138
  return { output: formatParityResult(result), code: result.mismatches.length > 0 ? 1 : 0 };
139
139
  }
140
140
  if (action === "backfill-header-images") {
141
- const { readDbConfig, openDb } = await import("./client-AUE3XUPO.js");
141
+ const { readDbConfig, openDb } = await import("./client-JYKPVCJX.js");
142
142
  const db = await openDb(opts.url ? { url: opts.url } : readDbConfig());
143
143
  const { openBase, readAirtableConfig } = await import("./client-EPVO3FEH.js");
144
144
  const base = openBase(readAirtableConfig());
@@ -159,19 +159,94 @@ async function runDbCommand(action, opts) {
159
159
  });
160
160
  return { output: formatBackfillResult(result), code: result.failed.length > 0 ? 1 : 0 };
161
161
  }
162
+ if (action === "backfill-digest-state") {
163
+ const { readDbConfig, openDb } = await import("./client-JYKPVCJX.js");
164
+ const db = await openDb(opts.url ? { url: opts.url } : readDbConfig());
165
+ const { readDigestState: readTurso, writeDigestState: writeTurso } = await import("./digest-state-3KHZF7GD.js");
166
+ const existing = await readTurso(db);
167
+ if (Object.keys(existing).length > 0) {
168
+ return {
169
+ output: `DIGEST_BACKFILL skipped=1 reason=turso-already-populated keys=${Object.keys(existing).length}`,
170
+ code: 0
171
+ };
172
+ }
173
+ const { openBase, readAirtableConfig } = await import("./client-EPVO3FEH.js");
174
+ const base = openBase(readAirtableConfig());
175
+ const { readDigestState: readAirtable, DIGEST_STATE_TABLE } = await import("./digest-state-F37XUCS5.js");
176
+ const rows = await base(DIGEST_STATE_TABLE).select({ maxRecords: 1, pageSize: 1 }).all();
177
+ const snap = await readAirtable(base);
178
+ const keys = Object.keys(snap).length;
179
+ await writeTurso(db, snap);
180
+ const stored = (await db.selectFrom("digest_state").selectAll().execute()).length;
181
+ const after = Object.keys(await readTurso(db)).length;
182
+ return {
183
+ output: `DIGEST_BACKFILL source=${rows.length > 0 ? "row" : "absent"} copied=${keys} verified=${after} rows=${stored}`,
184
+ code: after === keys && stored === 1 ? 0 : 1
185
+ };
186
+ }
162
187
  if (action === "dump") {
163
- const { readDbConfig } = await import("./client-AUE3XUPO.js");
188
+ const { readDbConfig } = await import("./client-JYKPVCJX.js");
164
189
  const cfg = opts.url ? { url: opts.url } : readDbConfig();
165
190
  const { createClient } = await import("@libsql/client");
166
191
  const client = createClient(cfg.url === ":memory:" ? { url: ":memory:" } : cfg);
167
- const { dumpDatabase } = await import("./dump-P6EBSIOH.js");
168
- const sql = await dumpDatabase({
192
+ const { dumpDatabase } = await import("./dump-EPL7AZFR.js");
193
+ const sql = await dumpDatabase(
194
+ {
195
+ execute: async (q) => {
196
+ const r = await client.execute(q);
197
+ return { columns: r.columns, rows: r.rows };
198
+ }
199
+ },
200
+ (/* @__PURE__ */ new Date()).toISOString()
201
+ );
202
+ return { output: sql, code: 0 };
203
+ }
204
+ if (action === "restore") {
205
+ const file = opts.file;
206
+ if (!file) return { output: "restore: pass the dump path via --file", code: 1 };
207
+ if (!opts.url) {
208
+ return {
209
+ output: "restore: pass the TARGET database via --url (never defaults, to keep production out of reach)",
210
+ code: 1
211
+ };
212
+ }
213
+ const { readFile } = await import("fs/promises");
214
+ const sql = await readFile(file, "utf-8");
215
+ const { parseDumpManifest } = await import("./dump-EPL7AZFR.js");
216
+ const manifest = parseDumpManifest(sql);
217
+ if (!manifest) return { output: "RESTORE refused=manifest-absent", code: 1 };
218
+ const { createClient } = await import("@libsql/client");
219
+ const target = createClient({ url: opts.url });
220
+ const existing = await target.execute(
221
+ "SELECT COUNT(*) AS n FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'"
222
+ );
223
+ if (Number(existing.rows[0]?.n ?? 0) > 0) {
224
+ return { output: "RESTORE refused=target-not-empty", code: 1 };
225
+ }
226
+ await target.executeMultiple(sql);
227
+ const { tableCounts, headerImageBytes } = await import("./dump-EPL7AZFR.js");
228
+ const exec = {
169
229
  execute: async (q) => {
170
- const r = await client.execute(q);
230
+ const r = await target.execute(q);
171
231
  return { columns: r.columns, rows: r.rows };
172
232
  }
173
- });
174
- return { output: sql, code: 0 };
233
+ };
234
+ const counts = await tableCounts(exec);
235
+ const bytes = await headerImageBytes(exec);
236
+ const bad = [];
237
+ for (const [t, want] of Object.entries(manifest.tables)) {
238
+ if ((counts[t] ?? 0) !== want) bad.push(`${t}: origin=${want} restored=${counts[t] ?? 0}`);
239
+ }
240
+ if (bytes !== manifest.blobBytes)
241
+ bad.push(`header_image bytes: origin=${manifest.blobBytes} restored=${bytes}`);
242
+ const rows = Object.values(counts).reduce((a, b) => a + b, 0);
243
+ return {
244
+ output: [
245
+ ...bad.map((b) => `\u2717 ${b}`),
246
+ `RESTORE loaded=true tables=${Object.keys(counts).length} rows=${rows} blob_bytes=${bytes} mismatches=${bad.length}`
247
+ ].join("\n"),
248
+ code: bad.length > 0 ? 1 : 0
249
+ };
175
250
  }
176
251
  if (action === "verify-dump") {
177
252
  const file = opts.file;
@@ -185,33 +260,53 @@ async function runDbCommand(action, opts) {
185
260
  } catch (err) {
186
261
  return { output: `DUMP_VERIFY loaded=false error=${String(err)}`, code: 1 };
187
262
  }
188
- const { tableCounts, countInsertsInDump } = await import("./dump-P6EBSIOH.js");
189
- const restored = await tableCounts({
263
+ const { tableCounts, headerImageBytes, parseDumpManifest } = await import("./dump-EPL7AZFR.js");
264
+ const manifest = parseDumpManifest(sql);
265
+ if (!manifest) {
266
+ return {
267
+ output: "DUMP_VERIFY loaded=true manifest=absent \u2014 dump predates the origin manifest",
268
+ code: 1
269
+ };
270
+ }
271
+ const exec = {
190
272
  execute: async (q) => {
191
273
  const r = await scratch.execute(q);
192
274
  return { columns: r.columns, rows: r.rows };
193
275
  }
194
- });
195
- const expected = countInsertsInDump(sql);
276
+ };
277
+ const restored = await tableCounts(exec);
278
+ const restoredBlobBytes = await headerImageBytes(exec);
196
279
  const mismatches = [];
197
- for (const [table, want] of Object.entries(expected)) {
280
+ for (const [table, want] of Object.entries(manifest.tables)) {
198
281
  if ((restored[table] ?? 0) !== want) {
199
- mismatches.push(`${table}: dump=${want} restored=${restored[table] ?? 0}`);
282
+ mismatches.push(`${table}: origin=${want} restored=${restored[table] ?? 0}`);
200
283
  }
201
284
  }
285
+ for (const table of Object.keys(restored)) {
286
+ if (!(table in manifest.tables)) mismatches.push(`${table}: not in origin manifest`);
287
+ }
288
+ const { DATABASE_TABLES } = await import("./schema-75PJECAE.js");
289
+ for (const table of DATABASE_TABLES) {
290
+ if (!(table in restored)) mismatches.push(`${table}: MISSING from the backup entirely`);
291
+ }
292
+ if (restoredBlobBytes !== manifest.blobBytes) {
293
+ mismatches.push(
294
+ `header_image bytes: origin=${manifest.blobBytes} restored=${restoredBlobBytes}`
295
+ );
296
+ }
202
297
  const total = Object.values(restored).reduce((a, b) => a + b, 0);
203
298
  const lines = [
204
299
  ...mismatches.map((m) => `\u2717 ${m}`),
205
- `DUMP_VERIFY loaded=true tables=${Object.keys(restored).length} rows=${total} mismatches=${mismatches.length}`
300
+ `DUMP_VERIFY loaded=true tables=${Object.keys(restored).length} rows=${total} blob_bytes=${restoredBlobBytes} mismatches=${mismatches.length}`
206
301
  ];
207
302
  return { output: lines.join("\n"), code: mismatches.length > 0 ? 1 : 0 };
208
303
  }
209
304
  return {
210
- output: `unknown db action '${action}'. Use: migrate, replay-deadletters, import-airtable, parity, sync, backfill-header-images, dump, verify-dump.`,
305
+ output: `unknown db action '${action}'. Use: migrate, replay-deadletters, import-airtable, parity, sync, backfill-header-images, backfill-digest-state, dump, verify-dump, restore.`,
211
306
  code: 1
212
307
  };
213
308
  }
214
309
  export {
215
310
  runDbCommand
216
311
  };
217
- //# sourceMappingURL=db-UXNIZ2RG.js.map
312
+ //# sourceMappingURL=db-DXUUAMXT.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cli/commands/db.ts"],"sourcesContent":["export type DbCommandOptions = {\n /** Override the libSQL url (tests use \":memory:\"); otherwise read from env. */\n url?: string;\n /** verify-dump: path to the dump file to load into a scratch engine. */\n file?: string;\n cwd?: string;\n verbose?: boolean;\n};\n\n/** `db <action>` — migrate | replay-deadletters | import-airtable | parity | sync | dump | verify-dump. The db layer is imported\n * dynamically so a non-db CLI invocation (and `--help`) never loads\n * @libsql/client. Config is resolved inside each branch so an unknown action\n * returns without needing any Turso env. */\nexport async function runDbCommand(\n action: string,\n opts: DbCommandOptions,\n): Promise<{ output: string; code: number }> {\n if (action === \"migrate\") {\n const { readDbConfig } = await import(\"../../db/client.js\");\n const cfg = opts.url ? { url: opts.url } : readDbConfig();\n const { runMigrations } = await import(\"../../db/migrate.js\");\n const { createClient } = await import(\"@libsql/client\");\n const client = createClient(cfg.url === \":memory:\" ? { url: \":memory:\" } : cfg);\n const ran = await runMigrations(client);\n return {\n output: ran.length ? `Applied migrations: ${ran.join(\", \")}` : \"Already up to date.\",\n code: 0,\n };\n }\n\n // Re-run every lead that dead-lettered during a site-lookup outage (#539\n // Phase 0) through the normal ingest pipeline. Exit 1 while any row is STILL\n // failing — the store hasn't recovered and the operator should not read the\n // run as \"all leads landed\". Zero rows is a clean 0: nothing owed.\n if (action === \"replay-deadletters\") {\n const { readDbConfig, openDb } = await import(\"../../db/client.js\");\n const db = await openDb(opts.url ? { url: opts.url } : readDbConfig());\n const { openBase, readAirtableConfig } = await import(\"../../reports/airtable/client.js\");\n const { getWebsiteBySlug } = await import(\"../../reports/airtable/websites.js\");\n const base = openBase(readAirtableConfig());\n const {\n createSubmission,\n stampNotified,\n stampFanout,\n findRecentDuplicateSubmissions,\n listRecentSubmissionsForEmail,\n markSubmissionsSpamRetro,\n } = await import(\"../../db/submissions.js\");\n const { makeNotify } = await import(\"../../forms/notify.js\");\n const { classifySpam } = await import(\"../../forms/spam-classifier.js\");\n const { forwardNewsletterToWebhook } = await import(\"../../forms/webhook.js\");\n const { addMailchimpMember, mailchimpTagsFor } = await import(\"../../forms/mailchimp.js\");\n const { defaultResendClient } = await import(\"../../reports/send/resend.js\");\n const { replayDeadLetters } = await import(\"../../forms/replay.js\");\n\n // Same degradation as the ingest handler: an unconfigured Resend key means\n // replayed leads land un-emailed (notify=failed) rather than blocking replay.\n let send = null;\n try {\n send = defaultResendClient().send;\n } catch (err) {\n console.error(`[db] Resend unconfigured; replaying without email: ${String(err)}`);\n }\n\n // Mirrors the production handler's deps minus `deadLetter` (replayDeadLetters\n // forbids and strips it — a throwing lookup must retry, not duplicate) and\n // minus `defer` (a CLI has no post-response phase; the inline tail is fine).\n const result = await replayDeadLetters(db, {\n getWebsiteBySlug: (s) => getWebsiteBySlug(base, s),\n createSubmission: (input) => createSubmission(db, input),\n notify: makeNotify(send),\n stampNotified: (id, status, messageId) => stampNotified(db, id, status, messageId),\n now: () => new Date(),\n classifySpam: (n, outcome) =>\n classifySpam({\n name: n.name,\n email: n.email,\n ...(n.message !== undefined ? { message: n.message } : {}),\n formType: n.formType,\n extraFields: n.extraFields,\n turnstile: outcome,\n }),\n findRecentDuplicates: (message, since) =>\n findRecentDuplicateSubmissions(db, message, since.toISOString()),\n listRecentSubmissionsForEmail: (email, since) =>\n listRecentSubmissionsForEmail(db, email, since.toISOString()),\n retroBucket: (ids, reason) => markSubmissionsSpamRetro(db, ids, reason),\n forwardNewsletter: (url, submission, site) =>\n forwardNewsletterToWebhook(url, submission, site),\n addToMailchimp: (site, submission) =>\n addMailchimpMember({\n apiKey: site.mailchimpApiKey ?? \"\",\n audienceId: site.mailchimpAudienceId ?? \"\",\n email: submission.email,\n name: submission.name,\n tags: mailchimpTagsFor(submission.formType),\n }),\n stampFanout: (id, fanoutStatus) => stampFanout(db, id, fanoutStatus),\n });\n\n const lines = [\n ...result.replayed.map(\n (r) => `replayed ${r.id} → ${r.outcome}${r.submissionId ? ` (${r.submissionId})` : \"\"}`,\n ),\n ...result.stillFailing.map((r) => `still failing ${r.id}: ${r.error}`),\n `DEADLETTER_REPLAY replayed=${result.replayed.length} still_failing=${result.stillFailing.length}`,\n ];\n return { output: lines.join(\"\\n\"), code: result.stillFailing.length > 0 ? 1 : 0 };\n }\n\n // Phase 1.3/1.4 of #539. Both read the same two Airtable tables raw (id +\n // fields, no mapRow coercion — the importer's mapping is the authority) and\n // share that mapping, so parity is definitionally checked against what the\n // importer writes.\n if (action === \"import-airtable\" || action === \"parity\" || action === \"sync\") {\n const { readDbConfig, openDb } = await import(\"../../db/client.js\");\n const db = await openDb(opts.url ? { url: opts.url } : readDbConfig());\n const { openBase, readAirtableConfig } = await import(\"../../reports/airtable/client.js\");\n const base = openBase(readAirtableConfig());\n const listRaw = async (table: string) =>\n (await base(table).select().all()).map((r) => ({\n id: r.id,\n fields: r.fields as Record<string, unknown>,\n }));\n const io = {\n listWebsiteRecords: () => listRaw(\"Websites\"),\n listReportRecords: () => listRaw(\"Reports\"),\n now: () => new Date(),\n };\n\n if (action === \"import-airtable\") {\n const { importFleetState, formatReapSummary } = await import(\"../../db/import-airtable.js\");\n const summary = await importFleetState(db, {\n ...io,\n // Attachment bodies ride expiring signed URLs; a failed fetch imports the\n // row with rendered_html null and is NAMED in the summary, never silent.\n fetchAttachment: async (url) => {\n try {\n const res = await fetch(url);\n return res.ok ? await res.text() : null;\n } catch {\n return null;\n }\n },\n });\n const lines = [\n `imported ${summary.sites} site(s) → sites/site_health/site_schedule`,\n `imported ${summary.reports} report(s)`,\n ];\n if (summary.renderedHtmlMisses.length > 0) {\n lines.push(\n `⚠ ${summary.renderedHtmlMisses.length} report(s) imported WITHOUT Rendered HTML ` +\n `(fetch failed / URL expired): ${summary.renderedHtmlMisses.join(\", \")}`,\n );\n }\n // The import deletes rows Airtable no longer has, so this one-shot path\n // reports the reap exactly as `db sync` does — same formatter, no second\n // copy to fall out of step.\n lines.push(...formatReapSummary(summary.reaped));\n return { output: lines.join(\"\\n\"), code: 0 };\n }\n\n // Phase 2 backbone (#539): one hourly pass = import (attachment fetches\n // only where the stored row lacks a body) + parity + one retry to absorb\n // the import-read/parity-read race. Exit 1 on persistent mismatch.\n if (action === \"sync\") {\n const { syncFleetState, formatSyncResult } = await import(\"../../db/sync.js\");\n const result = await syncFleetState(db, {\n ...io,\n fetchAttachment: async (url) => {\n try {\n const res = await fetch(url);\n return res.ok ? await res.text() : null;\n } catch {\n return null;\n }\n },\n });\n return {\n output: formatSyncResult(result),\n code: result.parity.mismatches.length > 0 ? 1 : 0,\n };\n }\n\n const { checkFleetParity, formatParityResult } = await import(\"../../db/parity.js\");\n const result = await checkFleetParity(db, io);\n return { output: formatParityResult(result), code: result.mismatches.length > 0 ? 1 : 0 };\n }\n\n // One-shot completion of design D5 (#539 Phase 2): copy every site's CURRENT\n // Airtable \"Header image\" attachment into sites.header_image*. Idempotent —\n // an already-populated BLOB is never overwritten (a re-run must not clobber\n // a freshly generated image with a stale Airtable copy). Exit 1 when any\n // fetch failed, so a partial backfill is never read as complete.\n if (action === \"backfill-header-images\") {\n const { readDbConfig, openDb } = await import(\"../../db/client.js\");\n const db = await openDb(opts.url ? { url: opts.url } : readDbConfig());\n const { openBase, readAirtableConfig } = await import(\"../../reports/airtable/client.js\");\n const base = openBase(readAirtableConfig());\n const { backfillHeaderImages, formatBackfillResult } =\n await import(\"../../db/header-images.js\");\n const result = await backfillHeaderImages(db, {\n listWebsiteRecords: async () =>\n (await base(\"Websites\").select().all()).map((r) => ({\n id: r.id,\n fields: r.fields as Record<string, unknown>,\n })),\n fetchBytes: async (url) => {\n try {\n const res = await fetch(url);\n return res.ok ? new Uint8Array(await res.arrayBuffer()) : null;\n } catch {\n return null;\n }\n },\n });\n return { output: formatBackfillResult(result), code: result.failed.length > 0 ? 1 : 0 };\n }\n\n // #609: one-shot copy of the single Airtable \"Digest State\" row into Turso,\n // so the first digest run after the read repoint sees yesterday's snapshot\n // instead of an empty one. An empty read is not a crash — it badges EVERY\n // item NEW, which lands in the operator's inbox reading as \"the whole fleet\n // degraded overnight\". REFUSES to overwrite a snapshot Turso already holds:\n // a re-run must never replace a fresher snapshot with a stale Airtable copy.\n if (action === \"backfill-digest-state\") {\n const { readDbConfig, openDb } = await import(\"../../db/client.js\");\n const db = await openDb(opts.url ? { url: opts.url } : readDbConfig());\n const { readDigestState: readTurso, writeDigestState: writeTurso } =\n await import(\"../../db/digest-state.js\");\n const existing = await readTurso(db);\n if (Object.keys(existing).length > 0) {\n return {\n output: `DIGEST_BACKFILL skipped=1 reason=turso-already-populated keys=${Object.keys(existing).length}`,\n code: 0,\n };\n }\n const { openBase, readAirtableConfig } = await import(\"../../reports/airtable/client.js\");\n const base = openBase(readAirtableConfig());\n const { readDigestState: readAirtable, DIGEST_STATE_TABLE } =\n await import(\"../../alerts/digest-state.js\");\n // `source` separates \"Airtable has no row\" from \"Airtable has a row holding\n // an empty snapshot\" — the reader collapses BOTH to {}, so copied=0 alone\n // cannot tell a quiet fleet from a failed read. Learned by running this: the\n // first real run printed copied=0 and only a hand probe showed the row was\n // there and genuinely empty.\n const rows = await base(DIGEST_STATE_TABLE).select({ maxRecords: 1, pageSize: 1 }).all();\n const snap = await readAirtable(base);\n const keys = Object.keys(snap).length;\n await writeTurso(db, snap);\n // Read it BACK. A returning write is not evidence the row landed — the same\n // rule forms-notify-target learned on 2026-08-03. `stored` counts the ROW,\n // not its keys, so an empty-but-present snapshot verifies as written.\n const stored = (await db.selectFrom(\"digest_state\").selectAll().execute()).length;\n const after = Object.keys(await readTurso(db)).length;\n return {\n output:\n `DIGEST_BACKFILL source=${rows.length > 0 ? \"row\" : \"absent\"} ` +\n `copied=${keys} verified=${after} rows=${stored}`,\n code: after === keys && stored === 1 ? 0 : 1,\n };\n }\n\n // Phase 1.5 of #539: platform-auth-free SQL dump to stdout-adjacent output.\n // The nightly backup workflow redirects this to a file, encrypts, uploads;\n // the rehearsed restore loads it into stock sqlite3 and compares row counts.\n if (action === \"dump\") {\n const { readDbConfig } = await import(\"../../db/client.js\");\n const cfg = opts.url ? { url: opts.url } : readDbConfig();\n const { createClient } = await import(\"@libsql/client\");\n const client = createClient(cfg.url === \":memory:\" ? { url: \":memory:\" } : cfg);\n const { dumpDatabase } = await import(\"../../db/dump.js\");\n const sql = await dumpDatabase(\n {\n execute: async (q) => {\n const r = await client.execute(q);\n return { columns: r.columns, rows: r.rows as Array<Record<string, unknown>> };\n },\n },\n new Date().toISOString(),\n );\n return { output: sql, code: 0 };\n }\n\n // Load a dump back into a REAL libSQL target (#612 review). The nightly\n // rehearsal loads into `:memory:`, which proves the SQL parses — it does not\n // prove you can get the data back into Turso, and that is the operation an\n // actual recovery needs. Replaying ~17 MB of SQL with megabytes of inline hex\n // over HTTP is materially different from an in-process load, and it had never\n // been done. Refuses to touch a database that already holds rows: a restore\n // is for an EMPTY target, and pointing this at production by mistake should\n // cost nothing.\n if (action === \"restore\") {\n const file = opts.file;\n if (!file) return { output: \"restore: pass the dump path via --file\", code: 1 };\n if (!opts.url) {\n return {\n output:\n \"restore: pass the TARGET database via --url (never defaults, to keep production out of reach)\",\n code: 1,\n };\n }\n const { readFile } = await import(\"node:fs/promises\");\n const sql = await readFile(file, \"utf-8\");\n const { parseDumpManifest } = await import(\"../../db/dump.js\");\n const manifest = parseDumpManifest(sql);\n if (!manifest) return { output: \"RESTORE refused=manifest-absent\", code: 1 };\n const { createClient } = await import(\"@libsql/client\");\n const target = createClient({ url: opts.url });\n const existing = await target.execute(\n \"SELECT COUNT(*) AS n FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'\",\n );\n if (Number(existing.rows[0]?.n ?? 0) > 0) {\n return { output: \"RESTORE refused=target-not-empty\", code: 1 };\n }\n await target.executeMultiple(sql);\n const { tableCounts, headerImageBytes } = await import(\"../../db/dump.js\");\n const exec = {\n execute: async (q: string) => {\n const r = await target.execute(q);\n return { columns: r.columns, rows: r.rows as Array<Record<string, unknown>> };\n },\n };\n const counts = await tableCounts(exec);\n const bytes = await headerImageBytes(exec);\n // Same origin-anchored comparison as verify-dump: a restore that \"succeeded\"\n // with fewer rows than the origin held is not a restore.\n const bad: string[] = [];\n for (const [t, want] of Object.entries(manifest.tables)) {\n if ((counts[t] ?? 0) !== want) bad.push(`${t}: origin=${want} restored=${counts[t] ?? 0}`);\n }\n if (bytes !== manifest.blobBytes)\n bad.push(`header_image bytes: origin=${manifest.blobBytes} restored=${bytes}`);\n const rows = Object.values(counts).reduce((a, b) => a + b, 0);\n return {\n output: [\n ...bad.map((b) => `✗ ${b}`),\n `RESTORE loaded=true tables=${Object.keys(counts).length} rows=${rows} blob_bytes=${bytes} mismatches=${bad.length}`,\n ].join(\"\\n\"),\n code: bad.length > 0 ? 1 : 0,\n };\n }\n\n // The restore rehearsal (Phase 1.5's hard gate), runnable every night: load\n // the dump into a FRESH in-memory engine and compare what came back against\n // the ORIGIN MANIFEST the dump carries.\n //\n // It used to compare against INSERT counts parsed out of the dump text — i.e.\n // the dump against itself. Both sides derived from one artifact, so a dump\n // that collected 5 of 44 sites shrank both numbers together and verified\n // clean. The manifest is read from the live database before any row is\n // serialised, which is the only measurement that can notice a short dump.\n //\n // A dump that cannot restore is not a backup — and per the repo's instrument\n // rule the check emits its machine line on every run, clean included.\n if (action === \"verify-dump\") {\n const file = opts.file;\n if (!file) return { output: \"verify-dump: pass the dump path via --file\", code: 1 };\n const { readFile } = await import(\"node:fs/promises\");\n const sql = await readFile(file, \"utf-8\");\n const { createClient } = await import(\"@libsql/client\");\n const scratch = createClient({ url: \":memory:\" });\n try {\n await scratch.executeMultiple(sql);\n } catch (err) {\n return { output: `DUMP_VERIFY loaded=false error=${String(err)}`, code: 1 };\n }\n const { tableCounts, headerImageBytes, parseDumpManifest } = await import(\"../../db/dump.js\");\n const manifest = parseDumpManifest(sql);\n if (!manifest) {\n // Refuse rather than fall back to self-comparison. Falling back would\n // re-enable exactly the blind spot the manifest exists to close, and it\n // would do so silently on the one artifact nobody was watching.\n return {\n output: \"DUMP_VERIFY loaded=true manifest=absent — dump predates the origin manifest\",\n code: 1,\n };\n }\n const exec = {\n execute: async (q: string) => {\n const r = await scratch.execute(q);\n return { columns: r.columns, rows: r.rows as Array<Record<string, unknown>> };\n },\n };\n const restored = await tableCounts(exec);\n const restoredBlobBytes = await headerImageBytes(exec);\n const mismatches: string[] = [];\n for (const [table, want] of Object.entries(manifest.tables)) {\n if ((restored[table] ?? 0) !== want) {\n mismatches.push(`${table}: origin=${want} restored=${restored[table] ?? 0}`);\n }\n }\n // A table the origin held and the dump never mentioned would otherwise be\n // invisible: absent from `restored` AND absent from the loop above.\n for (const table of Object.keys(restored)) {\n if (!(table in manifest.tables)) mismatches.push(`${table}: not in origin manifest`);\n }\n // Coverage: every table the APP owns must be present. `tables=N` used to be\n // printed and never asserted, so a table a migration failed to create — or\n // that the dump lost — rode green forever. `digest_state` and\n // `prospect_audits` were both absent from every artifact the night this was\n // found, purely because they postdated the last run.\n const { DATABASE_TABLES } = await import(\"../../db/schema.js\");\n for (const table of DATABASE_TABLES) {\n if (!(table in restored)) mismatches.push(`${table}: MISSING from the backup entirely`);\n }\n if (restoredBlobBytes !== manifest.blobBytes) {\n mismatches.push(\n `header_image bytes: origin=${manifest.blobBytes} restored=${restoredBlobBytes}`,\n );\n }\n const total = Object.values(restored).reduce((a, b) => a + b, 0);\n const lines = [\n ...mismatches.map((m) => `✗ ${m}`),\n `DUMP_VERIFY loaded=true tables=${Object.keys(restored).length} rows=${total} blob_bytes=${restoredBlobBytes} mismatches=${mismatches.length}`,\n ];\n return { output: lines.join(\"\\n\"), code: mismatches.length > 0 ? 1 : 0 };\n }\n\n return {\n output: `unknown db action '${action}'. Use: migrate, replay-deadletters, import-airtable, parity, sync, backfill-header-images, backfill-digest-state, dump, verify-dump, restore.`,\n code: 1,\n };\n}\n"],"mappings":";AAaA,eAAsB,aACpB,QACA,MAC2C;AAC3C,MAAI,WAAW,WAAW;AACxB,UAAM,EAAE,aAAa,IAAI,MAAM,OAAO,sBAAoB;AAC1D,UAAM,MAAM,KAAK,MAAM,EAAE,KAAK,KAAK,IAAI,IAAI,aAAa;AACxD,UAAM,EAAE,cAAc,IAAI,MAAM,OAAO,uBAAqB;AAC5D,UAAM,EAAE,aAAa,IAAI,MAAM,OAAO,gBAAgB;AACtD,UAAM,SAAS,aAAa,IAAI,QAAQ,aAAa,EAAE,KAAK,WAAW,IAAI,GAAG;AAC9E,UAAM,MAAM,MAAM,cAAc,MAAM;AACtC,WAAO;AAAA,MACL,QAAQ,IAAI,SAAS,uBAAuB,IAAI,KAAK,IAAI,CAAC,KAAK;AAAA,MAC/D,MAAM;AAAA,IACR;AAAA,EACF;AAMA,MAAI,WAAW,sBAAsB;AACnC,UAAM,EAAE,cAAc,OAAO,IAAI,MAAM,OAAO,sBAAoB;AAClE,UAAM,KAAK,MAAM,OAAO,KAAK,MAAM,EAAE,KAAK,KAAK,IAAI,IAAI,aAAa,CAAC;AACrE,UAAM,EAAE,UAAU,mBAAmB,IAAI,MAAM,OAAO,sBAAkC;AACxF,UAAM,EAAE,iBAAiB,IAAI,MAAM,OAAO,wBAAoC;AAC9E,UAAM,OAAO,SAAS,mBAAmB,CAAC;AAC1C,UAAM;AAAA,MACJ;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF,IAAI,MAAM,OAAO,2BAAyB;AAC1C,UAAM,EAAE,WAAW,IAAI,MAAM,OAAO,sBAAuB;AAC3D,UAAM,EAAE,aAAa,IAAI,MAAM,OAAO,+BAAgC;AACtE,UAAM,EAAE,2BAA2B,IAAI,MAAM,O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AA,MACZ,GAAG,WAAW,IAAI,CAAC,MAAM,UAAK,CAAC,EAAE;AAAA,MACjC,kCAAkC,OAAO,KAAK,QAAQ,EAAE,MAAM,SAAS,KAAK,eAAe,iBAAiB,eAAe,WAAW,MAAM;AAAA,IAC9I;AACA,WAAO,EAAE,QAAQ,MAAM,KAAK,IAAI,GAAG,MAAM,WAAW,SAAS,IAAI,IAAI,EAAE;AAAA,EACzE;AAEA,SAAO;AAAA,IACL,QAAQ,sBAAsB,MAAM;AAAA,IACpC,MAAM;AAAA,EACR;AACF;","names":["result"]}
@@ -12,16 +12,17 @@ import {
12
12
  collectPrismicDriftAlerts,
13
13
  collectRenovateAlerts,
14
14
  collectTurnstileGuardrailAlerts,
15
- collectVulnAlerts,
16
- diffAttention,
17
- readDigestState,
18
- writeDigestState
19
- } from "./chunk-NCMZMLY7.js";
20
- import "./chunk-SDDPUAWH.js";
15
+ collectVulnAlerts
16
+ } from "./chunk-WPL5GERE.js";
17
+ import "./chunk-6I6L3CMX.js";
21
18
  import "./chunk-PZR4EBPY.js";
22
19
  import {
23
20
  isIdempotencyConflict
24
- } from "./chunk-NDWYJLRF.js";
21
+ } from "./chunk-DGZWFI2G.js";
22
+ import {
23
+ diffAttention,
24
+ writeDigestState
25
+ } from "./chunk-BRYXFH77.js";
25
26
  import {
26
27
  isPendingApproval,
27
28
  listAllReports
@@ -32,13 +33,13 @@ import {
32
33
  openBase,
33
34
  readAirtableConfig
34
35
  } from "./chunk-HN6I2XWI.js";
35
- import "./chunk-ZGBEIWSC.js";
36
+ import "./chunk-XP5WM2LV.js";
36
37
  import "./chunk-GECESMVS.js";
37
- import "./chunk-MT2JINSS.js";
38
+ import "./chunk-5UINJNAJ.js";
39
+ import "./chunk-KJGKZLCT.js";
38
40
  import {
39
41
  escapeHtml
40
- } from "./chunk-DJZWYIPP.js";
41
- import "./chunk-5UINJNAJ.js";
42
+ } from "./chunk-BGTYPVLT.js";
42
43
  import {
43
44
  listWebsites,
44
45
  siteSlug
@@ -46,10 +47,10 @@ import {
46
47
  import {
47
48
  defaultResendClient
48
49
  } from "./chunk-WEKL2HYJ.js";
49
- import "./chunk-XUGSZP7Z.js";
50
- import "./chunk-EVBCK2KC.js";
51
- import "./chunk-JHGHLKFS.js";
52
- import "./chunk-3SF7D4DY.js";
50
+ import "./chunk-W45FZEGE.js";
51
+ import "./chunk-RARREDQE.js";
52
+ import "./chunk-WS6NU475.js";
53
+ import "./chunk-MFHS7IQ2.js";
53
54
  import "./chunk-6VAL7XJT.js";
54
55
 
55
56
  // src/reports/digest.ts
@@ -148,7 +149,7 @@ async function listPendingApproval(base) {
148
149
  async function fetchNotifyBounceCounts(now) {
149
150
  try {
150
151
  const [{ openDb, readDbConfig }, { countNotifyBouncedBySite }, { screenOutsSince }] = await Promise.all([
151
- import("./client-AUE3XUPO.js"),
152
+ import("./client-JYKPVCJX.js"),
152
153
  import("./submissions-3I3GAQAX.js"),
153
154
  import("./screenouts-7P5GOZMV.js")
154
155
  ]);
@@ -159,11 +160,89 @@ async function fetchNotifyBounceCounts(now) {
159
160
  return /* @__PURE__ */ new Map();
160
161
  }
161
162
  }
163
+ async function readDigestStateFromDb() {
164
+ const [{ openDb, readDbConfig }, { readDigestState }] = await Promise.all([
165
+ import("./client-JYKPVCJX.js"),
166
+ import("./digest-state-3KHZF7GD.js")
167
+ ]);
168
+ return readDigestState(await openDb(readDbConfig()));
169
+ }
170
+ async function writeRollupOnce(options, now) {
171
+ if (options.cockpitRollup) {
172
+ await options.cockpitRollup.write(now);
173
+ return "written";
174
+ }
175
+ return writeCockpitRollupToDb(now);
176
+ }
177
+ async function writeDigestStateToDb(next) {
178
+ const [{ openDb, readDbConfig }, { writeDigestState: writeDigestState2 }] = await Promise.all([
179
+ import("./client-JYKPVCJX.js"),
180
+ import("./digest-state-3KHZF7GD.js")
181
+ ]);
182
+ await writeDigestState2(await openDb(readDbConfig()), next);
183
+ }
184
+ async function writeCockpitRollupToDb(now) {
185
+ if (!process.env.TURSO_DATABASE_URL) return "absent";
186
+ const [{ openDb, readDbConfig }, { writeCockpitRollup }, screenouts, submissions, collectors] = await Promise.all([
187
+ import("./client-JYKPVCJX.js"),
188
+ import("./digest-state-3KHZF7GD.js"),
189
+ import("./screenouts-7P5GOZMV.js"),
190
+ import("./submissions-3I3GAQAX.js"),
191
+ import("./digest-collectors-NM7WUWQP.js")
192
+ ]);
193
+ const db = await openDb(readDbConfig());
194
+ const SCREEN_OUT_WINDOW_DAYS = 30;
195
+ const screenOutSince = screenouts.screenOutsSince(now, SCREEN_OUT_WINDOW_DAYS);
196
+ const bounceSince = screenouts.screenOutsSince(now, collectors.NOTIFY_BOUNCE_WINDOW_DAYS);
197
+ const totals = { honeypot: 0, tooFast: 0, markedSpam: 0 };
198
+ for (const t of (await screenouts.listScreenOutsSince(db, screenOutSince)).values()) {
199
+ totals.honeypot += t.honeypot;
200
+ totals.tooFast += t.tooFast;
201
+ totals.markedSpam += t.markedSpam;
202
+ }
203
+ const bounces = await submissions.countNotifyBouncedBySite(db, bounceSince);
204
+ await writeCockpitRollup(db, {
205
+ spamTotals: totals,
206
+ notifyBounces: Object.fromEntries(bounces),
207
+ windowDays: {
208
+ screenOuts: SCREEN_OUT_WINDOW_DAYS,
209
+ bounces: collectors.NOTIFY_BOUNCE_WINDOW_DAYS
210
+ },
211
+ computedAt: now.toISOString()
212
+ });
213
+ return "written";
214
+ }
215
+ async function persistDigestState(base, next, writeState, writeRollup) {
216
+ let turso = 0;
217
+ let airtable = 0;
218
+ let rollup = "0";
219
+ try {
220
+ await (writeState ?? writeDigestStateToDb)(next);
221
+ turso = 1;
222
+ } catch (e) {
223
+ console.warn(`\u26A0 digest state write failed (turso): ${e.message}`);
224
+ }
225
+ try {
226
+ await writeDigestState(base, next);
227
+ airtable = 1;
228
+ } catch (e) {
229
+ console.warn(`\u26A0 digest state write failed (airtable): ${e.message}`);
230
+ }
231
+ if (writeRollup) {
232
+ try {
233
+ rollup = await writeRollup() === "absent" ? "absent" : "1";
234
+ } catch (e) {
235
+ rollup = "0";
236
+ console.warn(`\u26A0 cockpit rollup write failed: ${e.message}`);
237
+ }
238
+ }
239
+ console.log(`DIGEST_STATE_WRITE turso=${turso} airtable=${airtable} rollup=${rollup}`);
240
+ }
162
241
  var SUBMISSIONS_DIGEST_WINDOW_MS = 24 * 60 * 60 * 1e3;
163
242
  async function fetchSubmissionsDigestCounts(now) {
164
243
  try {
165
244
  const [{ openDb, readDbConfig }, { countSubmissionsSinceBySite }] = await Promise.all([
166
- import("./client-AUE3XUPO.js"),
245
+ import("./client-JYKPVCJX.js"),
167
246
  import("./submissions-3I3GAQAX.js")
168
247
  ]);
169
248
  const db = await openDb(readDbConfig());
@@ -260,17 +339,18 @@ async function runDigest(options) {
260
339
  reports,
261
340
  now: today
262
341
  });
263
- const prior = await readDigestState(base);
342
+ const prior = await (options.digestState?.read ?? readDigestStateFromDb)();
264
343
  const { tagged, next } = diffAttention(collected, prior, digestDateKey(today));
265
344
  const needsAttention = tagged.filter(
266
345
  (it) => it.kind !== "vuln" || it.autoFixExhausted === true
267
346
  );
268
347
  if (readyForYourYes.length === 0 && needsAttention.length === 0) {
269
- try {
270
- await writeDigestState(base, next);
271
- } catch (e) {
272
- console.warn(`\u26A0 digest state write failed: ${e.message}`);
273
- }
348
+ await persistDigestState(
349
+ base,
350
+ next,
351
+ options.digestState?.write,
352
+ () => writeRollupOnce(options, today)
353
+ );
274
354
  return { output: "Digest skipped (nothing ready, nothing needs attention).", code: 0 };
275
355
  }
276
356
  const counts = options.submissionCounts !== void 0 ? options.submissionCounts : await fetchSubmissionsDigestCounts(today);
@@ -298,11 +378,12 @@ async function runDigest(options) {
298
378
  }
299
379
  throw err;
300
380
  }
301
- try {
302
- await writeDigestState(base, next);
303
- } catch (e) {
304
- console.warn(`\u26A0 digest state write failed: ${e.message}`);
305
- }
381
+ await persistDigestState(
382
+ base,
383
+ next,
384
+ options.digestState?.write,
385
+ () => writeRollupOnce(options, today)
386
+ );
306
387
  return { output: `Digest sent to ${to.join(", ")} (${result.messageId})`, code: 0 };
307
388
  } catch (err) {
308
389
  if (typeof err.exitCode === "number") {
@@ -343,4 +424,4 @@ export {
343
424
  renderDigestHtml,
344
425
  runDigest
345
426
  };
346
- //# sourceMappingURL=digest-FW6QMZZJ.js.map
427
+ //# sourceMappingURL=digest-NBLECFM7.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/reports/digest.ts"],"sourcesContent":["// src/reports/digest.ts\nimport { openBase, readAirtableConfig, type AirtableBase } from \"./airtable/client.js\";\nimport { listAllReports, isPendingApproval } from \"./airtable/reports.js\";\nimport type { ReportRow } from \"./airtable/reports.js\";\nimport { listWebsites, siteSlug, type WebsiteRow } from \"./airtable/websites.js\";\nimport { defaultResendClient, type ResendClient } from \"./send/resend.js\";\nimport { isIdempotencyConflict } from \"./send/idempotency.js\";\nimport {\n collectVulnAlerts,\n collectDeliveryFailures,\n collectPreflightBlocked,\n collectLighthouseAlerts,\n collectRenovateAlerts,\n collectCiAlerts,\n collectAnalyticsFailures,\n collectTurnstileGuardrailAlerts,\n collectNotifyBounceAlerts,\n collectPrismicDriftAlerts,\n NOTIFY_BOUNCE_WINDOW_DAYS,\n} from \"../alerts/digest-collectors.js\";\nimport { diffAttention } from \"../alerts/digest-state.js\";\nimport {\n writeDigestState as writeAirtableDigestState,\n type DigestSnapshot,\n} from \"../alerts/digest-state.js\";\nimport { escapeHtml as esc } from \"../util/html.js\";\nimport { operatorEmail } from \"../util/operator.js\";\nimport type {\n AttentionItem,\n AttentionSeverity,\n AttentionStatus,\n ReadyItem,\n DigestSections,\n SubmissionsDigestSection,\n} from \"../alerts/attention.js\";\n// Type-only: erased at compile time, so the kysely/libsql devDependency never loads\n// in a consuming fleet site (the runtime read is the dynamic import in\n// fetchSubmissionsDigestCounts, same rule as fetchNotifyBounceCounts).\nimport type { SiteSubmissionCounts } from \"../db/submissions.js\";\n\n// The attention/digest contract lives in `../alerts/attention.ts` (a dependency-free\n// types module) so the `alerts/*` collectors can depend on it without importing back\n// from this renderer/IO module — see attention.ts for the cycle it breaks. Re-exported\n// here so existing `from \"./digest.js\"` type importers keep resolving.\nexport type {\n AttentionItem,\n AttentionSeverity,\n AttentionStatus,\n ReadyItem,\n DigestSections,\n SubmissionsDigestSection,\n} from \"../alerts/attention.js\";\n\nconst GREY = \"#757575\";\nconst RED = \"#C00\";\n\n/** Shared anchor style — Gmail does not inherit font-family into <a> tags. */\nconst ANCHOR_STYLE = `color:${RED};font-family:helvetica,sans-serif`;\n\nfunction readySection(items: ReadyItem[]): string {\n const heading = `<h2 style=\"color:${RED};font-family:helvetica,sans-serif;font-size:20px;font-weight:700;margin:32px 0 8px\">Ready for your yes</h2>`;\n if (items.length === 0) {\n return `${heading}<p style=\"color:${GREY};font-family:helvetica,sans-serif;font-size:16px;margin:0\">Nothing waiting on you.</p>`;\n }\n const rows = items\n .map((it) => {\n const safeUrl = it.dashboardUrl.startsWith(\"https://\") ? it.dashboardUrl : undefined;\n const link = safeUrl\n ? `<a href=\"${esc(safeUrl)}\" style=\"${ANCHOR_STYLE}\">review &amp; approve</a>`\n : `review &amp; approve`;\n return `\n <tr>\n <td style=\"color:${GREY};font-family:helvetica,sans-serif;font-size:16px;line-height:24px;padding-bottom:8px\">\n <strong style=\"color:#222\">${esc(it.siteName)}</strong> — ${esc(it.reportType)} (${esc(it.period)})\n — ${link}\n </td>\n </tr>`;\n })\n .join(\"\");\n return `${heading}<table role=\"presentation\" style=\"border-collapse:collapse;margin:0\">${rows}</table>`;\n}\n\nconst SEVERITY_ORDER: Record<AttentionSeverity, number> = { critical: 0, warning: 1 };\n\n/** Render the per-item status badge (\"NEW\"/\"WORSE\"); standing items get nothing. */\nfunction attentionBadge(status?: AttentionStatus): string {\n if (status === \"new\")\n return `<strong style=\"color:${RED};font-family:helvetica,sans-serif\">NEW</strong> `;\n if (status === \"worse\")\n return `<strong style=\"color:${RED};font-family:helvetica,sans-serif\">WORSE</strong> `;\n return \"\";\n}\n\nfunction attentionSection(items: AttentionItem[]): string {\n const heading = `<h2 style=\"color:${RED};font-family:helvetica,sans-serif;font-size:20px;font-weight:700;margin:32px 0 8px\">Needs attention</h2>`;\n if (items.length === 0) {\n return `${heading}<p style=\"color:${GREY};font-family:helvetica,sans-serif;font-size:16px;margin:0\">All clear — nothing needs attention.</p>`;\n }\n\n // Group by siteName, preserving first-seen site order; sort within a site by\n // severity (critical first).\n const bySite = new Map<string, AttentionItem[]>();\n for (const it of items) {\n const bucket = bySite.get(it.siteName);\n if (bucket) bucket.push(it);\n else bySite.set(it.siteName, [it]);\n }\n\n const groups = [...bySite.entries()]\n .map(([siteName, siteItems]) => {\n const sorted = [...siteItems].sort(\n (a, b) => SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity],\n );\n const rows = sorted\n .map((it) => {\n const safeUrl = it.url?.startsWith(\"https://\") ? it.url : undefined;\n const titleHtml = safeUrl\n ? `<a href=\"${esc(safeUrl)}\" style=\"${ANCHOR_STYLE}\">${esc(it.title)}</a>`\n : esc(it.title);\n return `\n <tr>\n <td style=\"color:${GREY};font-family:helvetica,sans-serif;font-size:16px;line-height:24px;padding-bottom:8px\">${attentionBadge(it.status)}${titleHtml}</td>\n </tr>`;\n })\n .join(\"\");\n return `\n <tr>\n <td style=\"color:#222;font-family:helvetica,sans-serif;font-size:16px;font-weight:700;padding:8px 0 4px\">${esc(siteName)}</td>\n </tr>\n ${rows}`;\n })\n .join(\"\");\n\n return `${heading}<table role=\"presentation\" style=\"border-collapse:collapse;margin:0\">${groups}</table>`;\n}\n\n/** The \"Submissions (24h)\" telemetry block: fleet totals + a per-site glance line.\n * Context, not an alarm — absent/null section or all-zero totals render nothing\n * (no-noise), and the section never triggers a send on its own (see runDigest). */\nfunction submissionsSection(s: SubmissionsDigestSection | null | undefined): string {\n if (!s) return \"\";\n if (s.leads === 0 && s.signups === 0 && s.spamAuto === 0) return \"\";\n const heading = `<h2 style=\"color:${RED};font-family:helvetica,sans-serif;font-size:20px;font-weight:700;margin:32px 0 8px\">Submissions (24h)</h2>`;\n // All three terms always render together — omitting a zero term next to a nonzero\n // one reads as \"not measured\" rather than \"none\"; simplest honest form.\n const totals = [\n `${s.leads} new lead${s.leads === 1 ? \"\" : \"s\"}`,\n `${s.signups} newsletter/RSVP signup${s.signups === 1 ? \"\" : \"s\"}`,\n `${s.spamAuto} auto-filtered spam`,\n ].join(\" · \");\n const totalLine = `<p style=\"color:${GREY};font-family:helvetica,sans-serif;font-size:16px;margin:0\">${totals}</p>`;\n if (s.bySite.length === 0) return `${heading}${totalLine}`;\n const rows = s.bySite\n .map((site) => {\n const parts: string[] = [];\n if (site.leads > 0) parts.push(`${site.leads} lead${site.leads === 1 ? \"\" : \"s\"}`);\n if (site.signups > 0) parts.push(`${site.signups} signup${site.signups === 1 ? \"\" : \"s\"}`);\n if (site.spamAuto > 0) parts.push(`${site.spamAuto} auto-filtered`);\n return `\n <tr>\n <td style=\"color:${GREY};font-family:helvetica,sans-serif;font-size:16px;line-height:24px;padding-bottom:8px\">\n <strong style=\"color:#222\">${esc(site.siteName)}</strong> — ${parts.join(\" · \")}\n </td>\n </tr>`;\n })\n .join(\"\");\n return `${heading}${totalLine}<table role=\"presentation\" style=\"border-collapse:collapse;margin:8px 0 0\">${rows}</table>`;\n}\n\nconst FROM_ADDRESS = \"Reddoor Reports <reports@reddoorla.com>\";\n\n/** UTC \"YYYY-MM-DD\" — the Resend idempotency key suffix, so a same-day cron re-fire dedupes. */\nfunction digestDateKey(d: Date): string {\n return d.toISOString().slice(0, 10);\n}\n\n/**\n * The gate for \"Ready for your yes\": Draft ready ∧ ¬Approved to send ∧ Sent at BLANK.\n *\n * Implemented as `listAllReports(base).filter(...)` (the authorized deviation from the plan's\n * draft, which pre-dated Slice 1's merged fix): `listAllReports` already calls `mapRow`, which\n * handles `Period` correctly, so no local `rawToReportRow` duplicate is needed. The JS filter\n * does real work — the test fake does NOT evaluate `filterByFormula` — so correctness is\n * test-provable here.\n *\n * Exported: the fleet homepage (Task 3.5b) reuses it for the pending-approval count.\n */\nexport async function listPendingApproval(base: AirtableBase): Promise<ReportRow[]> {\n return (await listAllReports(base)).filter(isPendingApproval);\n}\n\n// ── collectAttention (IO wrapper, sibling to runDigest) ──────────────────────\n\nexport type CollectAttentionDeps = {\n base: AirtableBase;\n /** Same baseUrl value runDigest threads; used for the /s/<slug> links. */\n baseUrl: string;\n /** Pre-fetched Websites rows. When supplied (runDigest already read them),\n * collectAttention reuses them instead of issuing a second `listWebsites`. */\n websites?: WebsiteRow[];\n /** Pre-fetched Reports rows. When supplied (runDigest already read them),\n * collectAttention reuses them instead of issuing a second `listAllReports`. */\n reports?: ReportRow[];\n /** Clock for the GitHub-signals staleness gate (collectCiAlerts /\n * collectRenovateAlerts skip a >3-day-stale sweep). Defaults to wall-clock;\n * runDigest threads its run-start `today` so a quiet repo's frozen CI/Renovate\n * signal stops badging once its sweep goes stale. */\n now?: Date;\n /** Pre-fetched per-site bounced-lead-notification counts (tests, or a caller with\n * an open db). When omitted, collectAttention reads them from libSQL itself —\n * defensively, so a missing TURSO env or a Turso blip drops just this signal. */\n notifyBounces?: ReadonlyMap<string, number>;\n};\n\n/** Per-site bounced-notification counts for the notify-bounce collector, read from\n * libSQL over the collector's own window. The db modules are imported DYNAMICALLY:\n * src/db/submissions.ts pulls kysely at top level, and kysely/libsql live in\n * devDependencies consuming fleet sites don't install — a static import here would\n * crash their CLI at require time (same rule as openDb's own lazy loads). Any\n * failure (no TURSO env, Turso down) logs and yields an empty map: the digest\n * must never blank over a missing optional signal. */\nasync function fetchNotifyBounceCounts(now: Date): Promise<ReadonlyMap<string, number>> {\n try {\n const [{ openDb, readDbConfig }, { countNotifyBouncedBySite }, { screenOutsSince }] =\n await Promise.all([\n import(\"../db/client.js\"),\n import(\"../db/submissions.js\"),\n import(\"../db/screenouts.js\"),\n ]);\n const db = await openDb(readDbConfig());\n return await countNotifyBouncedBySite(db, screenOutsSince(now, NOTIFY_BOUNCE_WINDOW_DAYS));\n } catch (e) {\n console.warn(`⚠ notify-bounce counts unavailable (libSQL): ${(e as Error).message}`);\n return new Map();\n }\n}\n\n/** The prior snapshot, from Turso (#609). Dynamically imported for the same\n * reason as fetchNotifyBounceCounts: kysely/libsql are devDependencies that\n * consuming fleet sites do not install, so a static import would crash their\n * CLI at require time.\n *\n * NOT defensive, deliberately — the Airtable read it replaces was not either.\n * Swallowing a failure here would silently badge every item NEW, which reads\n * as \"the whole fleet degraded overnight\" in the operator's inbox. A thrown\n * error is the honest outcome. */\nasync function readDigestStateFromDb(): Promise<DigestSnapshot> {\n const [{ openDb, readDbConfig }, { readDigestState }] = await Promise.all([\n import(\"../db/client.js\"),\n import(\"../db/digest-state.js\"),\n ]);\n return readDigestState(await openDb(readDbConfig()));\n}\n\n/** Bridge the injectable seam (returns void) onto the three-state contract the\n * log line reports. An injected writer that resolves is a real write. */\nasync function writeRollupOnce(\n options: DigestRunOptions,\n now: Date,\n): Promise<\"written\" | \"absent\"> {\n if (options.cockpitRollup) {\n await options.cockpitRollup.write(now);\n return \"written\";\n }\n return writeCockpitRollupToDb(now);\n}\n\n/** The write half of {@link readDigestStateFromDb}, same lazy-import rule. */\nasync function writeDigestStateToDb(next: DigestSnapshot): Promise<void> {\n const [{ openDb, readDbConfig }, { writeDigestState }] = await Promise.all([\n import(\"../db/client.js\"),\n import(\"../db/digest-state.js\"),\n ]);\n await writeDigestState(await openDb(readDbConfig()), next);\n}\n\n/**\n * Compute the cockpit's \"since a window\" roll-ups once, here, instead of on\n * every page load (MED-16 of the 2026-08-26 review).\n *\n * Both aggregates read the whole `submissions` table — the one unbounded-growth\n * table in the schema — and the cockpit root is the operator's most-loaded page.\n * Turso meters row scans, so recomputing them per request is a cost that grows\n * forever against numbers that move once a day.\n *\n * The trade is explicit: the figures become up to 24h old. That is why the\n * payload carries `computedAt` and the windows it used, and why an absent\n * roll-up reads as null rather than zero — a stale or unmeasured number\n * presented as live is worse than no number.\n *\n * Best-effort, like the snapshot write beside it: the digest has already been\n * sent by the time this runs, and a failed roll-up costs one strip on one page\n * until tomorrow, never the digest.\n */\nasync function writeCockpitRollupToDb(now: Date): Promise<\"written\" | \"absent\"> {\n // No Turso configured is a THIRD state, not a failure: it is what every unit\n // test looks like, and reporting it as `rollup=0` would train the eye to\n // ignore the number that is supposed to catch a dead writer. Same three-state\n // vocabulary the site mirrors already use (`mirrored=1|0|absent`).\n if (!process.env.TURSO_DATABASE_URL) return \"absent\";\n const [{ openDb, readDbConfig }, { writeCockpitRollup }, screenouts, submissions, collectors] =\n await Promise.all([\n import(\"../db/client.js\"),\n import(\"../db/digest-state.js\"),\n import(\"../db/screenouts.js\"),\n import(\"../db/submissions.js\"),\n import(\"../alerts/digest-collectors.js\"),\n ]);\n const db = await openDb(readDbConfig());\n const SCREEN_OUT_WINDOW_DAYS = 30;\n const screenOutSince = screenouts.screenOutsSince(now, SCREEN_OUT_WINDOW_DAYS);\n const bounceSince = screenouts.screenOutsSince(now, collectors.NOTIFY_BOUNCE_WINDOW_DAYS);\n\n const totals = { honeypot: 0, tooFast: 0, markedSpam: 0 };\n for (const t of (await screenouts.listScreenOutsSince(db, screenOutSince)).values()) {\n totals.honeypot += t.honeypot;\n totals.tooFast += t.tooFast;\n totals.markedSpam += t.markedSpam;\n }\n const bounces = await submissions.countNotifyBouncedBySite(db, bounceSince);\n\n await writeCockpitRollup(db, {\n spamTotals: totals,\n notifyBounces: Object.fromEntries(bounces),\n windowDays: {\n screenOuts: SCREEN_OUT_WINDOW_DAYS,\n bounces: collectors.NOTIFY_BOUNCE_WINDOW_DAYS,\n },\n computedAt: now.toISOString(),\n });\n return \"written\";\n}\n\n/** Persist the next snapshot to BOTH stores (#609 dual-write).\n *\n * Turso is the read side, so a failure there is the one that actually costs\n * correct NEW badges tomorrow — but Airtable keeps being written so the move\n * stays reversible while Phase 5 is in flight. Both are best-effort: the\n * digest has already been sent (or deliberately skipped) by the time this\n * runs, and a snapshot write failure re-news at worst.\n *\n * The DIGEST_STATE_WRITE line exists because of #585: a dual-write that\n * silently stopped running looked identical to a healthy one for weeks. One\n * line, always emitted, naming both halves. */\nasync function persistDigestState(\n base: AirtableBase,\n next: DigestSnapshot,\n writeState?: (snap: DigestSnapshot) => Promise<void>,\n writeRollup?: () => Promise<\"written\" | \"absent\">,\n): Promise<void> {\n let turso = 0;\n let airtable = 0;\n let rollup: \"1\" | \"0\" | \"absent\" = \"0\";\n try {\n await (writeState ?? writeDigestStateToDb)(next);\n turso = 1;\n } catch (e) {\n console.warn(`⚠ digest state write failed (turso): ${(e as Error).message}`);\n }\n try {\n await writeAirtableDigestState(base, next);\n airtable = 1;\n } catch (e) {\n console.warn(`⚠ digest state write failed (airtable): ${(e as Error).message}`);\n }\n // The cockpit roll-up rides the same \"already sent, best-effort\" contract, and\n // gets its own counter on the line for the #585 reason: a dual-write that\n // silently stopped running looked identical to a healthy one for weeks. An\n // ABSENT `rollup=` is a different failure from `rollup=0`.\n if (writeRollup) {\n try {\n rollup = (await writeRollup()) === \"absent\" ? \"absent\" : \"1\";\n } catch (e) {\n rollup = \"0\";\n console.warn(`⚠ cockpit rollup write failed: ${(e as Error).message}`);\n }\n }\n console.log(`DIGEST_STATE_WRITE turso=${turso} airtable=${airtable} rollup=${rollup}`);\n}\n\n/** The \"Submissions (24h)\" telemetry window — a precise 24h ISO-timestamp compare\n * (unlike screenOutsSince's date-only strings). */\nconst SUBMISSIONS_DIGEST_WINDOW_MS = 24 * 60 * 60 * 1000;\n\n/** Per-site submission counts for the digest telemetry section, read from libSQL.\n * Dynamic imports + fail-soft for the same reason as fetchNotifyBounceCounts:\n * kysely/libsql are devDependencies consuming fleet sites don't install, and a\n * Turso blip must drop just this section, never the digest. Returns null (not an\n * empty map) on failure so the renderer can omit the section rather than claim a\n * quiet fleet. */\nasync function fetchSubmissionsDigestCounts(\n now: Date,\n): Promise<ReadonlyMap<string, SiteSubmissionCounts> | null> {\n try {\n const [{ openDb, readDbConfig }, { countSubmissionsSinceBySite }] = await Promise.all([\n import(\"../db/client.js\"),\n import(\"../db/submissions.js\"),\n ]);\n const db = await openDb(readDbConfig());\n return await countSubmissionsSinceBySite(\n db,\n new Date(now.getTime() - SUBMISSIONS_DIGEST_WINDOW_MS).toISOString(),\n );\n } catch (e) {\n console.warn(`⚠ submissions telemetry unavailable (libSQL): ${(e as Error).message}`);\n return null;\n }\n}\n\n/** Assemble the \"Submissions (24h)\" section from the per-site counts. PURE (exported\n * for direct tests). Totals sum ALL map entries — an orphan site id still counts in\n * the fleet totals. bySite lists only ids that resolve in `sitesById` AND carry any\n * nonzero count, sorted by total volume desc then siteName A-Z. null counts (libSQL\n * unavailable) → null (section omitted). */\nexport function buildSubmissionsDigestSection(\n counts: ReadonlyMap<string, SiteSubmissionCounts> | null,\n sitesById: ReadonlyMap<string, WebsiteRow>,\n): SubmissionsDigestSection | null {\n if (counts === null) return null;\n let leads = 0;\n let signups = 0;\n let spamAuto = 0;\n const bySite: SubmissionsDigestSection[\"bySite\"] = [];\n for (const [siteId, c] of counts) {\n leads += c.leads;\n signups += c.signups;\n spamAuto += c.spamAuto;\n const site = sitesById.get(siteId);\n if (site && c.leads + c.signups + c.spamAuto > 0) {\n bySite.push({ siteName: site.name, ...c });\n }\n }\n bySite.sort(\n (a, b) =>\n b.leads + b.signups + b.spamAuto - (a.leads + a.signups + a.spamAuto) ||\n a.siteName.localeCompare(b.siteName),\n );\n return { leads, signups, spamAuto, bySite };\n}\n\n/** Run a single collector under a try/catch: a thrown collector logs and yields []\n * so one broken signal never blanks the whole \"Needs attention\" section. */\nfunction runCollector(label: string, fn: () => AttentionItem[]): AttentionItem[] {\n try {\n return fn();\n } catch (e) {\n console.warn(`⚠ attention collector \"${label}\" failed: ${(e as Error).message}`);\n return [];\n }\n}\n\n/**\n * Fetch the free signals once (listAllReports + listWebsites) — or reuse the\n * `reports`/`websites` arrays runDigest already read, so a single run reads each\n * table once — build the sitesById map the delivery collector needs, and run each\n * pure collector isolated. Returns the union of items; diffing/badging happens in\n * runDigest.\n *\n * The Renovate + CI signals come from the SAME persisted collectors the operator\n * cockpit (`buildCockpitModel`) runs — `collectRenovateAlerts` (key\n * `renovate:<siteId>`) and `collectCiAlerts` (key `ci:<siteId>`), reading the\n * nightly-persisted `renovateFailingCis`/`defaultBranchCi` fields. This is the\n * key-space unification: because the digest writes the shared Digest State\n * snapshot with these same keys, the cockpit's NEW/WORSE diff finds them and the\n * two surfaces agree (the prior live per-PR `renovate:<repo>#<n>` sweep never\n * matched the cockpit's keys, so its cards badged NEW forever).\n */\nexport async function collectAttention(deps: CollectAttentionDeps): Promise<AttentionItem[]> {\n const reports = deps.reports ?? (await listAllReports(deps.base));\n const websites = deps.websites ?? (await listWebsites(deps.base));\n const now = deps.now ?? new Date();\n const notifyBounces = deps.notifyBounces ?? (await fetchNotifyBounceCounts(now));\n const sitesById = new Map<string, WebsiteRow>(websites.map((w) => [w.id, w]));\n return [\n ...runCollector(\"vuln\", () => collectVulnAlerts(websites, deps.baseUrl)),\n ...runCollector(\"delivery\", () => collectDeliveryFailures(reports, sitesById, deps.baseUrl)),\n ...runCollector(\"preflight\", () => collectPreflightBlocked(reports, sitesById, deps.baseUrl)),\n ...runCollector(\"lighthouse\", () => collectLighthouseAlerts(websites, deps.baseUrl)),\n ...runCollector(\"renovate\", () => collectRenovateAlerts(websites, deps.baseUrl, now)),\n ...runCollector(\"ci\", () => collectCiAlerts(websites, deps.baseUrl, now)),\n ...runCollector(\"analytics\", () => collectAnalyticsFailures(websites, deps.baseUrl, now)),\n ...runCollector(\"turnstile\", () =>\n collectTurnstileGuardrailAlerts(websites, deps.baseUrl, now),\n ),\n ...runCollector(\"notify-bounce\", () =>\n collectNotifyBounceAlerts(websites, notifyBounces, deps.baseUrl),\n ),\n // Same collector the cockpit runs, over the same persisted `Prismic Models`\n // columns and the same keys — so the snapshot this digest writes is the one\n // the cockpit diffs NEW/WORSE against, and the two surfaces agree.\n ...runCollector(\"prismic-drift\", () => collectPrismicDriftAlerts(websites, deps.baseUrl, now)),\n ];\n}\n\nexport type DigestRunOptions = {\n resend?: ResendClient;\n /** Dashboard origin for the /s/<slug> links, e.g. \"https://reddoor-maintenance.netlify.app\". */\n baseUrl: string;\n /**\n * Inject a pre-opened Airtable base (tests, server handlers).\n * When omitted, `openBase(readAirtableConfig())` is called from the environment.\n */\n base?: AirtableBase;\n /** Per-site submission counts for the \"Submissions (24h)\" section. undefined =\n * fetch from libSQL; null = simulate unavailable (section omitted); a Map =\n * injected (tests). */\n submissionCounts?: ReadonlyMap<string, SiteSubmissionCounts> | null;\n /**\n * The prior-run snapshot store (#609). Production omits it and gets Turso.\n *\n * Injectable because the read is deliberately NOT defensive: swallowing a\n * failure would badge every item NEW, which lands in the operator's inbox\n * reading as \"the whole fleet degraded overnight\". That makes Turso a hard\n * requirement of a real run — so tests, which have no libSQL, need a seam\n * rather than an env var.\n */\n digestState?: {\n read: () => Promise<DigestSnapshot>;\n write: (snap: DigestSnapshot) => Promise<void>;\n };\n /**\n * The cockpit roll-up writer (MED-16). Same seam and same reason as\n * `digestState`: production omits it and gets Turso, tests inject.\n *\n * Without a seam this would be untestable in exactly the way that matters —\n * `writeCockpitRollupToDb` opens a db from env, so in a test it throws and is\n * caught, and the run reports `rollup=0` forever while looking healthy. That\n * is the #585 shape the counter on the log line exists to expose.\n */\n cockpitRollup?: { write: (now: Date) => Promise<void> };\n /**\n * The run clock. Production omits it and gets `new Date()`.\n *\n * Injectable because several collectors this run feeds are AGE-SENSITIVE —\n * `collectPrismicDriftAlerts` alone changes an item's key and its wording once\n * a verdict crosses `PRISMIC_DRIFT_STALE_DAYS` — so a digest test that cannot\n * fix the clock is asserting on the day it happens to run. Two did, and both\n * went red four days after they were written, reporting the staleness wording\n * as if the drift wiring had broken. `collectAttention` already takes a `now`\n * for exactly this reason; this threads the same lever one layer out.\n */\n now?: Date;\n};\n\nexport async function runDigest(\n options: DigestRunOptions,\n): Promise<{ output: string; code: number }> {\n // Capture clock BEFORE any await so the idempotency key can't roll past midnight mid-run.\n const today = options.now ?? new Date();\n try {\n const base = options.base ?? openBase(readAirtableConfig());\n // Read each table ONCE for the whole run, then thread the arrays into\n // collectAttention so it doesn't re-fetch (was: listWebsites ×2, listAllReports\n // ×2). Pending is derived in-line with listPendingApproval's exact predicate.\n const reports = await listAllReports(base);\n const websites = await listWebsites(base);\n const sites = new Map(websites.map((w) => [w.id, w]));\n\n const pending = reports.filter(isPendingApproval);\n\n const readyForYourYes: ReadyItem[] = [];\n const baseUrl = options.baseUrl.replace(/\\/$/, \"\");\n for (const r of pending) {\n const site = sites.get(r.siteId);\n if (!site) continue; // orphan report → skip rather than render a broken link\n // An empty Name slugs to \"\" → `/s/` is a dead link (getWebsiteBySlug can't\n // match it). Fall back to the fleet homepage so the operator still lands\n // somewhere usable instead of a 404.\n const slug = siteSlug(site.name);\n readyForYourYes.push({\n siteName: site.name,\n reportType: r.reportType,\n period: r.period ?? \"—\",\n dashboardUrl: slug ? `${baseUrl}/s/${slug}` : baseUrl,\n });\n }\n\n // M5: collect the free signals (isolated), diff against yesterday's snapshot.\n // Renovate + CI come from the persisted collectors (the same ones the cockpit\n // runs), so the snapshot this digest writes carries the `renovate:<siteId>` /\n // `ci:<siteId>` keys the cockpit diffs against — no live GitHub sweep here.\n const collected = await collectAttention({\n base,\n baseUrl: options.baseUrl,\n websites,\n reports,\n now: today,\n });\n // #609: Turso is the read side now. Airtable keeps being WRITTEN below\n // (dual-write, Phase 5's pattern everywhere else) so the move stays\n // reversible, but nothing reads it any more.\n const prior = await (options.digestState?.read ?? readDigestStateFromDb)();\n const { tagged, next } = diffAttention(collected, prior, digestDateKey(today));\n // The operator only HEARS about a vuln once Renovate's auto-fix is exhausted\n // (tried and failed a couple of nightly cycles) — before that the fleet is\n // still self-patching and the cockpit's amber Watch band is the only surface.\n // Filter the EMAIL list only: `next` (written below) must keep every vuln key\n // so the cockpit's diff against this same snapshot stays consistent, and so\n // the exhausted-flip diffs as WORSE instead of arriving pre-badged-away.\n const needsAttention = tagged.filter(\n (it) => it.kind !== \"vuln\" || it.autoFixExhausted === true,\n );\n\n // No-noise default: skip entirely when there's nothing to report.\n if (readyForYourYes.length === 0 && needsAttention.length === 0) {\n // Persist `next` even on a skip: a key that resolved on a quiet day clears so a\n // later recurrence diffs as NEW (spec §10), and — since the skip can now fire\n // with muted pre-exhaustion vulns collected — their keys keep snapshotting so\n // the eventual exhausted-flip diffs as WORSE. Wrapped: a write failure can't\n // fail the skip.\n await persistDigestState(base, next, options.digestState?.write, () =>\n writeRollupOnce(options, today),\n );\n return { output: \"Digest skipped (nothing ready, nothing needs attention).\", code: 0 };\n }\n\n // Submissions telemetry rides only on a digest that is ALREADY sending — the\n // skip predicate above is deliberately unchanged (leads already fire their own\n // ingest-time notification; this is context, not an alarm), and fetching AFTER\n // the skip check keeps quiet days from touching libSQL at all.\n const counts =\n options.submissionCounts !== undefined\n ? options.submissionCounts\n : await fetchSubmissionsDigestCounts(today);\n const submissions = buildSubmissionsDigestSection(counts, sites);\n\n const html = renderDigestHtml({ readyForYourYes, needsAttention, submissions });\n const client = options.resend ?? defaultResendClient();\n const to = [operatorEmail()];\n const n = readyForYourYes.length;\n const reportWord = n === 1 ? \"report\" : \"reports\";\n let result: Awaited<ReturnType<typeof client.send>>;\n try {\n result = await client.send({\n from: FROM_ADDRESS,\n to,\n subject: `Your fleet — ${digestDateKey(today)}: ${n} ${reportWord} ready for your yes`,\n html,\n idempotencyKey: `digest-${digestDateKey(today)}`,\n });\n } catch (err) {\n // A same-UTC-day re-run whose content changed re-sends with the same\n // `digest-<date>` idempotency key but a DIFFERENT body. Resend rejects that\n // with a 409 (`invalid_idempotent_request`) — \"This idempotency key has been\n // used ... but the request body was modified ...\". The operator already got\n // today's digest on the first send, so re-sending a changed version same-day\n // would just be a duplicate: treat it as an \"already sent today\" no-op.\n //\n // ResendClient (send/resend.ts) wraps the API error as a plain Error and only\n // preserves the *message* string (no name/statusCode), so the message\n // substring is the only reliable discriminator — match defensively on it.\n // Any OTHER send error re-throws to the outer catch → {code:1}, so a genuine\n // Resend/network failure still fails loudly.\n if (isIdempotencyConflict(err)) {\n // Do NOT write the snapshot: the first send already persisted it; writing\n // this run's `next` would diff against the first run's snapshot and mis-badge.\n return {\n output:\n \"Digest already sent today (content changed since the first send) — skipped to avoid a duplicate.\",\n code: 0,\n };\n }\n throw err;\n }\n // Persist the next snapshot AFTER a successful send. A write failure is caught +\n // logged: the digest already went out, tomorrow re-news at worst. (The send-FAILURE\n // path never reaches here — the outer catch returns code 1 with no write, preserving\n // the NEW badge for the retry.)\n await persistDigestState(base, next, options.digestState?.write, () =>\n writeRollupOnce(options, today),\n );\n return { output: `Digest sent to ${to.join(\", \")} (${result.messageId})`, code: 0 };\n } catch (err) {\n // Re-throw config errors (exitCode=2: missing env vars, bad config) so runOrExit\n // surfaces them with the correct process exit code rather than collapsing to 1.\n if (typeof (err as { exitCode?: unknown }).exitCode === \"number\") {\n throw err;\n }\n const message = err instanceof Error ? err.message : String(err);\n return { output: `digest failed: ${message}`, code: 1 };\n }\n}\n\n/** Pure render of the unified daily operator digest. No IO — the caller (runDigest)\n * collects the rows and decides whether to send. */\nexport function renderDigestHtml(sections: DigestSections): string {\n return `<!doctype html>\n<html>\n <head><meta charset=\"utf-8\"></head>\n <body style=\"margin:0;padding:0;background:#ffffff\">\n <table width=\"100%\" style=\"border-collapse:collapse\">\n <tr>\n <td align=\"center\" style=\"padding:24px\">\n <table width=\"600\" style=\"border-collapse:collapse\">\n <tr>\n <td>\n <h1 style=\"color:${RED};font-family:helvetica,sans-serif;font-size:24px;font-weight:700;margin:0 0 8px\">Your fleet today</h1>\n ${readySection(sections.readyForYourYes)}\n ${attentionSection(sections.needsAttention)}\n ${submissionsSection(sections.submissions)}\n </td>\n </tr>\n </table>\n </td>\n </tr>\n </table>\n </body>\n</html>`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqDA,IAAM,OAAO;AACb,IAAM,MAAM;AAGZ,IAAM,eAAe,SAA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