@reddoorla/maintenance 0.85.2 → 0.86.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 (245) hide show
  1. package/README.md +8 -0
  2. package/dist/airtable-G7WBQQMI.js +9 -0
  3. package/dist/{announce-GIAYN67S.js → announce-MXTUQ6C7.js} +26 -19
  4. package/dist/announce-MXTUQ6C7.js.map +1 -0
  5. package/dist/{bump-deps-SWJB6H5V.js → bump-deps-EC74CPLS.js} +9 -9
  6. package/dist/chunk-2EVEFOZY.js +129 -0
  7. package/dist/chunk-2EVEFOZY.js.map +1 -0
  8. package/dist/{chunk-COZPL62X.js → chunk-2NDRHXMR.js} +25 -17
  9. package/dist/chunk-2NDRHXMR.js.map +1 -0
  10. package/dist/{chunk-SDUJIANJ.js → chunk-2NJQLSEU.js} +3 -3
  11. package/dist/chunk-2NQUCS7O.js +243 -0
  12. package/dist/chunk-2NQUCS7O.js.map +1 -0
  13. package/dist/{chunk-DTTIFYAM.js → chunk-2ZPT7GLV.js} +42 -403
  14. package/dist/chunk-2ZPT7GLV.js.map +1 -0
  15. package/dist/{chunk-ZTPPCHDB.js → chunk-3G25KIWW.js} +4 -4
  16. package/dist/chunk-3SF7D4DY.js +359 -0
  17. package/dist/chunk-3SF7D4DY.js.map +1 -0
  18. package/dist/{chunk-Q276MZ7E.js → chunk-3VQWSE3F.js} +4 -4
  19. package/dist/{chunk-37S6L6G4.js → chunk-5UINJNAJ.js} +72 -2
  20. package/dist/chunk-5UINJNAJ.js.map +1 -0
  21. package/dist/{chunk-THEFTZ7F.js → chunk-62CMMGEO.js} +5 -5
  22. package/dist/{chunk-FDIFTIXC.js → chunk-6TWWY7ZU.js} +2 -2
  23. package/dist/{chunk-UYCAF77E.js → chunk-7RJ2HMMJ.js} +3 -3
  24. package/dist/chunk-ACBRLLFT.js +198 -0
  25. package/dist/chunk-ACBRLLFT.js.map +1 -0
  26. package/dist/chunk-BNM5POSJ.js +284 -0
  27. package/dist/chunk-BNM5POSJ.js.map +1 -0
  28. package/dist/{chunk-R6FPFMOS.js → chunk-BQRFQSGY.js} +3 -3
  29. package/dist/{chunk-MGR2H7F4.js → chunk-BYK66EWO.js} +19 -12
  30. package/dist/chunk-BYK66EWO.js.map +1 -0
  31. package/dist/{chunk-6QRLRT3P.js → chunk-CQR4LIM7.js} +12 -265
  32. package/dist/chunk-CQR4LIM7.js.map +1 -0
  33. package/dist/{chunk-SEEA6RXF.js → chunk-DJZWYIPP.js} +2 -2
  34. package/dist/chunk-DJZWYIPP.js.map +1 -0
  35. package/dist/chunk-EVBCK2KC.js +68 -0
  36. package/dist/chunk-EVBCK2KC.js.map +1 -0
  37. package/dist/{chunk-TP5M2NQB.js → chunk-F5KM4LEQ.js} +3 -3
  38. package/dist/{chunk-62VF32IC.js → chunk-ILUNZHYV.js} +2 -2
  39. package/dist/chunk-ITIOFN7A.js +396 -0
  40. package/dist/chunk-ITIOFN7A.js.map +1 -0
  41. package/dist/{chunk-LS6QPANO.js → chunk-IYSEC543.js} +2 -2
  42. package/dist/{chunk-DC5H7KEQ.js → chunk-JHGHLKFS.js} +2 -2
  43. package/dist/{chunk-PBWDDDQH.js → chunk-KTH5ZODA.js} +2 -2
  44. package/dist/{chunk-4DHQCN5H.js → chunk-LBYOLBW7.js} +17 -2
  45. package/dist/chunk-LBYOLBW7.js.map +1 -0
  46. package/dist/{chunk-577HCGZO.js → chunk-LDWZSLSU.js} +38 -23
  47. package/dist/chunk-LDWZSLSU.js.map +1 -0
  48. package/dist/{chunk-LTB6KVJW.js → chunk-N45M3FDK.js} +13 -11
  49. package/dist/{chunk-LTB6KVJW.js.map → chunk-N45M3FDK.js.map} +1 -1
  50. package/dist/chunk-NYUYNYQL.js +48 -0
  51. package/dist/chunk-NYUYNYQL.js.map +1 -0
  52. package/dist/{chunk-7J53SUT6.js → chunk-P2FE5AI6.js} +4 -4
  53. package/dist/{chunk-3YXDSCM6.js → chunk-PPE5KZJK.js} +29 -11
  54. package/dist/chunk-PPE5KZJK.js.map +1 -0
  55. package/dist/chunk-PTDMVGKL.js +31 -0
  56. package/dist/chunk-PTDMVGKL.js.map +1 -0
  57. package/dist/{chunk-D4FVAIEJ.js → chunk-PZR4EBPY.js} +5 -2
  58. package/dist/chunk-PZR4EBPY.js.map +1 -0
  59. package/dist/{chunk-NWB4O5EY.js → chunk-SLUQ7R6I.js} +3 -3
  60. package/dist/chunk-SLUQ7R6I.js.map +1 -0
  61. package/dist/{chunk-GZNBCHAZ.js → chunk-TERE5SDF.js} +4 -4
  62. package/dist/{chunk-ZMIPG6TR.js → chunk-TVL5MVUF.js} +4 -4
  63. package/dist/chunk-UDRHAQT7.js +172 -0
  64. package/dist/chunk-UDRHAQT7.js.map +1 -0
  65. package/dist/chunk-VAD43MOR.js +72 -0
  66. package/dist/chunk-VAD43MOR.js.map +1 -0
  67. package/dist/chunk-VSBFM7DS.js +229 -0
  68. package/dist/chunk-VSBFM7DS.js.map +1 -0
  69. package/dist/chunk-W7Z3BGCI.js +274 -0
  70. package/dist/chunk-W7Z3BGCI.js.map +1 -0
  71. package/dist/chunk-X3B723J4.js +1209 -0
  72. package/dist/chunk-X3B723J4.js.map +1 -0
  73. package/dist/{chunk-VRWUL4TR.js → chunk-XHHMM5HX.js} +2 -2
  74. package/dist/{chunk-RJB3QUSP.js → chunk-XIDUYLSR.js} +3 -3
  75. package/dist/{chunk-QG6OSL4M.js → chunk-XUGSZP7Z.js} +2 -2
  76. package/dist/{chunk-S56JQJ4F.js → chunk-Y53WOQIJ.js} +3 -3
  77. package/dist/{chunk-ICXV25N7.js → chunk-Z3KYFUN6.js} +3 -3
  78. package/dist/{chunk-MPBXOJ3N.js → chunk-Z7AXYKQB.js} +33 -2
  79. package/dist/chunk-Z7AXYKQB.js.map +1 -0
  80. package/dist/{chunk-WYYQK4D3.js → chunk-ZKXSX4LO.js} +11 -11
  81. package/dist/cli/bin.js +46 -28
  82. package/dist/cli/bin.js.map +1 -1
  83. package/dist/cli/commands/audit.d.ts +30 -1
  84. package/dist/cli/commands/audit.js +62 -30
  85. package/dist/cli/commands/audit.js.map +1 -1
  86. package/dist/client-AUE3XUPO.js +11 -0
  87. package/dist/{convert-to-pnpm-AT52NWZB.js → convert-to-pnpm-6L6P74WR.js} +9 -9
  88. package/dist/db-B35OGV3G.js +217 -0
  89. package/dist/db-B35OGV3G.js.map +1 -0
  90. package/dist/{digest-UVHYZUYE.js → digest-BL6UJYKH.js} +23 -20
  91. package/dist/{digest-UVHYZUYE.js.map → digest-BL6UJYKH.js.map} +1 -1
  92. package/dist/dump-P6EBSIOH.js +68 -0
  93. package/dist/dump-P6EBSIOH.js.map +1 -0
  94. package/dist/email-VTTTKKL5.js +195 -0
  95. package/dist/email-VTTTKKL5.js.map +1 -0
  96. package/dist/{ensure-site-S25MDDHW.js → ensure-site-DFTB7MN3.js} +8 -7
  97. package/dist/ensure-site-DFTB7MN3.js.map +1 -0
  98. package/dist/fleet-events-cF2Om88w.d.ts +24 -0
  99. package/dist/{forms-notify-target-TWN4EH6K.js → forms-notify-target-75U6OU7L.js} +38 -132
  100. package/dist/forms-notify-target-75U6OU7L.js.map +1 -0
  101. package/dist/{github-signals-G4ILZAJ6.js → github-signals-IJUPGCUX.js} +40 -19
  102. package/dist/github-signals-IJUPGCUX.js.map +1 -0
  103. package/dist/{header-image-T7XD37JL.js → header-image-AWLLQA4L.js} +34 -11
  104. package/dist/header-image-AWLLQA4L.js.map +1 -0
  105. package/dist/header-images-335L2AKB.js +68 -0
  106. package/dist/header-images-335L2AKB.js.map +1 -0
  107. package/dist/{health-endpoint-242WG2OJ.js → health-endpoint-WJC2UMYS.js} +9 -9
  108. package/dist/health-mirror-4B2L7T2Y.js +75 -0
  109. package/dist/health-mirror-4B2L7T2Y.js.map +1 -0
  110. package/dist/import-airtable-HE43FB4H.js +35 -0
  111. package/dist/index.d.ts +175 -21
  112. package/dist/index.js +115 -73
  113. package/dist/index.js.map +1 -1
  114. package/dist/{init-JN26NTWF.js → init-NJEOEO7I.js} +20 -17
  115. package/dist/{init-JN26NTWF.js.map → init-NJEOEO7I.js.map} +1 -1
  116. package/dist/{launch-JA7Z4CIM.js → launch-XNAX427U.js} +31 -25
  117. package/dist/{launch-JA7Z4CIM.js.map → launch-XNAX427U.js.map} +1 -1
  118. package/dist/lighthouse-VHI77PFB.js +11 -0
  119. package/dist/{lighthouse-airtable-BIPM26SZ.js → lighthouse-airtable-LBVIYYP5.js} +3 -3
  120. package/dist/mailchimp-XYCTEEJY.js +72 -0
  121. package/dist/mailchimp-XYCTEEJY.js.map +1 -0
  122. package/dist/migrate-GQH237A6.js +7 -0
  123. package/dist/notify-C645PGD5.js +22 -0
  124. package/dist/{onboard-53CITIM7.js → onboard-GK4PHPNI.js} +9 -9
  125. package/dist/orchestrate-77UO4BYJ.js +30 -0
  126. package/dist/orchestrate-77UO4BYJ.js.map +1 -0
  127. package/dist/parity-MWS24A3H.js +12 -0
  128. package/dist/parity-MWS24A3H.js.map +1 -0
  129. package/dist/pipeline-S6CVHDGB.js +12 -0
  130. package/dist/pipeline-S6CVHDGB.js.map +1 -0
  131. package/dist/{preflight-3XPDUHFJ.js → preflight-6WBNU2GZ.js} +16 -13
  132. package/dist/{preflight-3XPDUHFJ.js.map → preflight-6WBNU2GZ.js.map} +1 -1
  133. package/dist/{prismic-ci-UTQ6LRR3.js → prismic-ci-3RHOZUUT.js} +15 -15
  134. package/dist/{prismic-models-PVES6R5V.js → prismic-models-QBGUT2Q3.js} +10 -10
  135. package/dist/prospect-audit-IUNCJ2LV.js +174 -0
  136. package/dist/prospect-audit-IUNCJ2LV.js.map +1 -0
  137. package/dist/prospect-audits-3PMIO73D.js +19 -0
  138. package/dist/prospect-audits-3PMIO73D.js.map +1 -0
  139. package/dist/{protection-audit-64PLLBLI.js → protection-audit-SJO53MEQ.js} +3 -3
  140. package/dist/recipes/sync-configs.js +3 -3
  141. package/dist/render-AQAVQDPZ.js +10 -0
  142. package/dist/render-AQAVQDPZ.js.map +1 -0
  143. package/dist/{renovate-dispatch-ICJGSFCE.js → renovate-dispatch-QJY75ODR.js} +8 -8
  144. package/dist/replay-C2LXMJZP.js +66 -0
  145. package/dist/replay-C2LXMJZP.js.map +1 -0
  146. package/dist/{report-6CKSWJNG.js → report-4EVNDHOZ.js} +55 -29
  147. package/dist/report-4EVNDHOZ.js.map +1 -0
  148. package/dist/reports/header-image/assets/headline-announcement.png +0 -0
  149. package/dist/reports/header-image/assets/headline-launch.png +0 -0
  150. package/dist/reports/header-image/assets/headline-maintenance.png +0 -0
  151. package/dist/reports/header-image/assets/headline-testing.png +0 -0
  152. package/dist/reports/header-image/assets/plate-clean.png +0 -0
  153. package/dist/{self-updating-PPQVV6UA.js → self-updating-6DWI2Z56.js} +9 -9
  154. package/dist/{selftest-CQ6NOX52.js → selftest-RC36MTKP.js} +25 -20
  155. package/dist/selftest-RC36MTKP.js.map +1 -0
  156. package/dist/smoke-B2GQOSIZ.js +20 -0
  157. package/dist/smoke-B2GQOSIZ.js.map +1 -0
  158. package/dist/{smoke-suite-TMCSOYRK.js → smoke-suite-VYY2LXM2.js} +9 -9
  159. package/dist/{submissions-GJ6ITBRH.js → submissions-Q7DRFOCD.js} +3 -3
  160. package/dist/{svelte-codemods-ZOBDHIES.js → svelte-codemods-25J2FO22.js} +9 -9
  161. package/dist/sync-34HNZZ56.js +44 -0
  162. package/dist/sync-34HNZZ56.js.map +1 -0
  163. package/dist/{sync-configs-CJXUX6MD.js → sync-configs-3SE6PSCO.js} +9 -9
  164. package/dist/{upgrade-WLX27UPC.js → upgrade-WBRQ62FX.js} +9 -9
  165. package/dist/{webflow-624FEBFD.js → webflow-IRKOIT7S.js} +4 -4
  166. package/dist/webhook-VOGOW3W6.js +38 -0
  167. package/dist/webhook-VOGOW3W6.js.map +1 -0
  168. package/dist/{websites-SADZR4XQ.js → websites-SXWTP72S.js} +6 -2
  169. package/dist/websites-SXWTP72S.js.map +1 -0
  170. package/dist/{write-audits-to-airtable-7PH75YWY.js → write-audits-to-airtable-MBEILLPU.js} +4 -4
  171. package/dist/write-audits-to-airtable-MBEILLPU.js.map +1 -0
  172. package/package.json +5 -2
  173. package/dist/airtable-HRKSA7V4.js +0 -9
  174. package/dist/announce-GIAYN67S.js.map +0 -1
  175. package/dist/chunk-37S6L6G4.js.map +0 -1
  176. package/dist/chunk-3YXDSCM6.js.map +0 -1
  177. package/dist/chunk-4DHQCN5H.js.map +0 -1
  178. package/dist/chunk-4SOCPK7A.js +0 -108
  179. package/dist/chunk-4SOCPK7A.js.map +0 -1
  180. package/dist/chunk-577HCGZO.js.map +0 -1
  181. package/dist/chunk-6QRLRT3P.js.map +0 -1
  182. package/dist/chunk-COZPL62X.js.map +0 -1
  183. package/dist/chunk-D4FVAIEJ.js.map +0 -1
  184. package/dist/chunk-DTTIFYAM.js.map +0 -1
  185. package/dist/chunk-MGR2H7F4.js.map +0 -1
  186. package/dist/chunk-MPBXOJ3N.js.map +0 -1
  187. package/dist/chunk-NWB4O5EY.js.map +0 -1
  188. package/dist/chunk-SEEA6RXF.js.map +0 -1
  189. package/dist/chunk-U5SZ4FOP.js +0 -26
  190. package/dist/chunk-U5SZ4FOP.js.map +0 -1
  191. package/dist/client-X5WUJWDE.js +0 -11
  192. package/dist/db-JSIZYT23.js +0 -23
  193. package/dist/db-JSIZYT23.js.map +0 -1
  194. package/dist/ensure-site-S25MDDHW.js.map +0 -1
  195. package/dist/forms-notify-target-TWN4EH6K.js.map +0 -1
  196. package/dist/github-signals-G4ILZAJ6.js.map +0 -1
  197. package/dist/header-image-T7XD37JL.js.map +0 -1
  198. package/dist/migrate-LJUFGXQZ.js +0 -7
  199. package/dist/orchestrate-KDNXZQX7.js +0 -27
  200. package/dist/report-6CKSWJNG.js.map +0 -1
  201. package/dist/reports/header-image/assets/plate.png +0 -0
  202. package/dist/selftest-CQ6NOX52.js.map +0 -1
  203. /package/dist/{airtable-HRKSA7V4.js.map → airtable-G7WBQQMI.js.map} +0 -0
  204. /package/dist/{bump-deps-SWJB6H5V.js.map → bump-deps-EC74CPLS.js.map} +0 -0
  205. /package/dist/{chunk-SDUJIANJ.js.map → chunk-2NJQLSEU.js.map} +0 -0
  206. /package/dist/{chunk-ZTPPCHDB.js.map → chunk-3G25KIWW.js.map} +0 -0
  207. /package/dist/{chunk-Q276MZ7E.js.map → chunk-3VQWSE3F.js.map} +0 -0
  208. /package/dist/{chunk-THEFTZ7F.js.map → chunk-62CMMGEO.js.map} +0 -0
  209. /package/dist/{chunk-FDIFTIXC.js.map → chunk-6TWWY7ZU.js.map} +0 -0
  210. /package/dist/{chunk-UYCAF77E.js.map → chunk-7RJ2HMMJ.js.map} +0 -0
  211. /package/dist/{chunk-R6FPFMOS.js.map → chunk-BQRFQSGY.js.map} +0 -0
  212. /package/dist/{chunk-TP5M2NQB.js.map → chunk-F5KM4LEQ.js.map} +0 -0
  213. /package/dist/{chunk-62VF32IC.js.map → chunk-ILUNZHYV.js.map} +0 -0
  214. /package/dist/{chunk-LS6QPANO.js.map → chunk-IYSEC543.js.map} +0 -0
  215. /package/dist/{chunk-DC5H7KEQ.js.map → chunk-JHGHLKFS.js.map} +0 -0
  216. /package/dist/{chunk-PBWDDDQH.js.map → chunk-KTH5ZODA.js.map} +0 -0
  217. /package/dist/{chunk-7J53SUT6.js.map → chunk-P2FE5AI6.js.map} +0 -0
  218. /package/dist/{chunk-GZNBCHAZ.js.map → chunk-TERE5SDF.js.map} +0 -0
  219. /package/dist/{chunk-ZMIPG6TR.js.map → chunk-TVL5MVUF.js.map} +0 -0
  220. /package/dist/{chunk-VRWUL4TR.js.map → chunk-XHHMM5HX.js.map} +0 -0
  221. /package/dist/{chunk-RJB3QUSP.js.map → chunk-XIDUYLSR.js.map} +0 -0
  222. /package/dist/{chunk-QG6OSL4M.js.map → chunk-XUGSZP7Z.js.map} +0 -0
  223. /package/dist/{chunk-S56JQJ4F.js.map → chunk-Y53WOQIJ.js.map} +0 -0
  224. /package/dist/{chunk-ICXV25N7.js.map → chunk-Z3KYFUN6.js.map} +0 -0
  225. /package/dist/{chunk-WYYQK4D3.js.map → chunk-ZKXSX4LO.js.map} +0 -0
  226. /package/dist/{client-X5WUJWDE.js.map → client-AUE3XUPO.js.map} +0 -0
  227. /package/dist/{convert-to-pnpm-AT52NWZB.js.map → convert-to-pnpm-6L6P74WR.js.map} +0 -0
  228. /package/dist/{health-endpoint-242WG2OJ.js.map → health-endpoint-WJC2UMYS.js.map} +0 -0
  229. /package/dist/{lighthouse-airtable-BIPM26SZ.js.map → import-airtable-HE43FB4H.js.map} +0 -0
  230. /package/dist/{migrate-LJUFGXQZ.js.map → lighthouse-VHI77PFB.js.map} +0 -0
  231. /package/dist/{orchestrate-KDNXZQX7.js.map → lighthouse-airtable-LBVIYYP5.js.map} +0 -0
  232. /package/dist/{websites-SADZR4XQ.js.map → migrate-GQH237A6.js.map} +0 -0
  233. /package/dist/{write-audits-to-airtable-7PH75YWY.js.map → notify-C645PGD5.js.map} +0 -0
  234. /package/dist/{onboard-53CITIM7.js.map → onboard-GK4PHPNI.js.map} +0 -0
  235. /package/dist/{prismic-ci-UTQ6LRR3.js.map → prismic-ci-3RHOZUUT.js.map} +0 -0
  236. /package/dist/{prismic-models-PVES6R5V.js.map → prismic-models-QBGUT2Q3.js.map} +0 -0
  237. /package/dist/{protection-audit-64PLLBLI.js.map → protection-audit-SJO53MEQ.js.map} +0 -0
  238. /package/dist/{renovate-dispatch-ICJGSFCE.js.map → renovate-dispatch-QJY75ODR.js.map} +0 -0
  239. /package/dist/{self-updating-PPQVV6UA.js.map → self-updating-6DWI2Z56.js.map} +0 -0
  240. /package/dist/{smoke-suite-TMCSOYRK.js.map → smoke-suite-VYY2LXM2.js.map} +0 -0
  241. /package/dist/{submissions-GJ6ITBRH.js.map → submissions-Q7DRFOCD.js.map} +0 -0
  242. /package/dist/{svelte-codemods-ZOBDHIES.js.map → svelte-codemods-25J2FO22.js.map} +0 -0
  243. /package/dist/{sync-configs-CJXUX6MD.js.map → sync-configs-3SE6PSCO.js.map} +0 -0
  244. /package/dist/{upgrade-WLX27UPC.js.map → upgrade-WBRQ62FX.js.map} +0 -0
  245. /package/dist/{webflow-624FEBFD.js.map → webflow-IRKOIT7S.js.map} +0 -0
@@ -16,36 +16,39 @@ import {
16
16
  diffAttention,
17
17
  readDigestState,
18
18
  writeDigestState
19
- } from "./chunk-TP5M2NQB.js";
20
- import "./chunk-LTB6KVJW.js";
21
- import "./chunk-D4FVAIEJ.js";
19
+ } from "./chunk-F5KM4LEQ.js";
20
+ import "./chunk-N45M3FDK.js";
21
+ import "./chunk-PZR4EBPY.js";
22
22
  import {
23
23
  isIdempotencyConflict
24
- } from "./chunk-COZPL62X.js";
24
+ } from "./chunk-2NDRHXMR.js";
25
25
  import "./chunk-GECESMVS.js";
26
+ import "./chunk-5UINJNAJ.js";
27
+ import "./chunk-CQR4LIM7.js";
28
+ import "./chunk-Z7AXYKQB.js";
29
+ import {
30
+ escapeHtml
31
+ } from "./chunk-DJZWYIPP.js";
26
32
  import {
27
33
  isPendingApproval,
28
34
  listAllReports
29
- } from "./chunk-6QRLRT3P.js";
30
- import "./chunk-MPBXOJ3N.js";
35
+ } from "./chunk-ACBRLLFT.js";
36
+ import "./chunk-VAD43MOR.js";
31
37
  import {
32
- escapeHtml
33
- } from "./chunk-SEEA6RXF.js";
38
+ openBase,
39
+ readAirtableConfig
40
+ } from "./chunk-HN6I2XWI.js";
34
41
  import {
35
42
  defaultResendClient
36
43
  } from "./chunk-WEKL2HYJ.js";
37
- import "./chunk-QG6OSL4M.js";
38
- import "./chunk-DC5H7KEQ.js";
39
- import "./chunk-4SOCPK7A.js";
40
- import "./chunk-U5SZ4FOP.js";
44
+ import "./chunk-XUGSZP7Z.js";
45
+ import "./chunk-EVBCK2KC.js";
46
+ import "./chunk-JHGHLKFS.js";
47
+ import "./chunk-3SF7D4DY.js";
41
48
  import {
42
49
  listWebsites,
43
50
  siteSlug
44
- } from "./chunk-577HCGZO.js";
45
- import {
46
- openBase,
47
- readAirtableConfig
48
- } from "./chunk-HN6I2XWI.js";
51
+ } from "./chunk-LDWZSLSU.js";
49
52
  import "./chunk-6VAL7XJT.js";
50
53
 
51
54
  // src/reports/digest.ts
@@ -144,7 +147,7 @@ async function listPendingApproval(base) {
144
147
  async function fetchNotifyBounceCounts(now) {
145
148
  try {
146
149
  const [{ openDb, readDbConfig }, { countNotifyBouncedBySite }, { screenOutsSince }] = await Promise.all([
147
- import("./client-X5WUJWDE.js"),
150
+ import("./client-AUE3XUPO.js"),
148
151
  import("./submissions-3I3GAQAX.js"),
149
152
  import("./screenouts-7P5GOZMV.js")
150
153
  ]);
@@ -159,7 +162,7 @@ var SUBMISSIONS_DIGEST_WINDOW_MS = 24 * 60 * 60 * 1e3;
159
162
  async function fetchSubmissionsDigestCounts(now) {
160
163
  try {
161
164
  const [{ openDb, readDbConfig }, { countSubmissionsSinceBySite }] = await Promise.all([
162
- import("./client-X5WUJWDE.js"),
165
+ import("./client-AUE3XUPO.js"),
163
166
  import("./submissions-3I3GAQAX.js")
164
167
  ]);
165
168
  const db = await openDb(readDbConfig());
@@ -339,4 +342,4 @@ export {
339
342
  renderDigestHtml,
340
343
  runDigest
341
344
  };
342
- //# sourceMappingURL=digest-UVHYZUYE.js.map
345
+ //# sourceMappingURL=digest-BL6UJYKH.js.map
@@ -1 +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, readDigestState, writeDigestState } 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 \"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 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 const prior = await readDigestState(base);\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 try {\n await writeDigestState(base, next);\n } catch (e) {\n console.warn(`⚠ digest state write failed: ${(e as Error).message}`);\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 try {\n await writeDigestState(base, next);\n } catch (e) {\n console.warn(`⚠ digest state write failed: ${(e as Error).message}`);\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,IAAM,OAAO;AACb,IAAM,MAAM;AAGZ,IAAM,eAAe,SAAS,GAAG;AAEjC,SAAS,aAAa,OAA4B;AAChD,QAAM,UAAU,oBAAoB,GAAG;AACvC,MAAI,MAAM,WAAW,GAAG;AACtB,WAAO,GAAG,OAAO,mBAAmB,IAAI;AAAA,EAC1C;AACA,QAAM,OAAO,MACV,IAAI,CAAC,OAAO;AACX,UAAM,UAAU,GAAG,aAAa,WAAW,UAAU,IAAI,GAAG,eAAe;AAC3E,UAAM,OAAO,UACT,YAAY,WAAI,OAAO,CAAC,YAAY,YAAY,+BAChD;AACJ,WAAO;AAAA;AAAA,2BAEc,IAAI;AAAA,uCACQ,WAAI,GAAG,QAAQ,CAAC,oBAAe,WAAI,GAAG,UAAU,CAAC,KAAK,WAAI,GAAG,MAAM,CAAC;AAAA,mBAC7F,IAAI;AAAA;AAAA;AAAA,EAGd,CAAC,EACA,KAAK,EAAE;AACV,SAAO,GAAG,OAAO,wEAAwE,IAAI;AAC/F;AAEA,IAAM,iBAAoD,EAAE,UAAU,GAAG,SAAS,EAAE;AAGpF,SAAS,eAAe,QAAkC;AACxD,MAAI,WAAW;AACb,WAAO,wBAAwB,GAAG;AACpC,MAAI,WAAW;AACb,WAAO,wBAAwB,GAAG;AACpC,SAAO;AACT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AM,EAAE;AAAA,EACpF,SAAS,KAAK;AAGZ,QAAI,OAAQ,IAA+B,aAAa,UAAU;AAChE,YAAM;AAAA,IACR;AACA,UAAM,UAAU,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAC/D,WAAO,EAAE,QAAQ,kBAAkB,OAAO,IAAI,MAAM,EAAE;AAAA,EACxD;AACF;AAIO,SAAS,iBAAiB,UAAkC;AACjE,SAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mCAU0B,GAAG;AAAA,kBACpB,aAAa,SAAS,eAAe,CAAC;AAAA,kBACtC,iBAAiB,SAAS,cAAc,CAAC;AAAA,kBACzC,mBAAmB,SAAS,WAAW,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAS1D;","names":[]}
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, readDigestState, writeDigestState } 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 \"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 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 const prior = await readDigestState(base);\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 try {\n await writeDigestState(base, next);\n } catch (e) {\n console.warn(`⚠ digest state write failed: ${(e as Error).message}`);\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 try {\n await writeDigestState(base, next);\n } catch (e) {\n console.warn(`⚠ digest state write failed: ${(e as Error).message}`);\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 ${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AAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mCAU0B,GAAG;AAAA,kBACpB,aAAa,SAAS,eAAe,CAAC;AAAA,kBACtC,iBAAiB,SAAS,cAAc,CAAC;AAAA,kBACzC,mBAAmB,SAAS,WAAW,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAS1D;","names":[]}
@@ -0,0 +1,68 @@
1
+ // src/db/dump.ts
2
+ var IDENT = /^[A-Za-z_][A-Za-z0-9_]*$/;
3
+ function quoteIdent(name) {
4
+ return IDENT.test(name) ? name : `"${name.replaceAll('"', '""')}"`;
5
+ }
6
+ function sqlLiteral(v) {
7
+ if (v === null || v === void 0) return "NULL";
8
+ if (typeof v === "number") return Number.isFinite(v) ? String(v) : "NULL";
9
+ if (typeof v === "bigint") return v.toString();
10
+ if (v instanceof Uint8Array || v instanceof ArrayBuffer) {
11
+ const bytes = v instanceof ArrayBuffer ? new Uint8Array(v) : v;
12
+ let hex = "";
13
+ for (const b of bytes) hex += b.toString(16).padStart(2, "0");
14
+ return `X'${hex}'`;
15
+ }
16
+ return `'${String(v).replaceAll("\0", "").replaceAll("'", "''")}'`;
17
+ }
18
+ async function dumpDatabase(db) {
19
+ const out = ["PRAGMA foreign_keys=OFF;", "BEGIN TRANSACTION;"];
20
+ const schema = await db.execute(
21
+ "SELECT name, type, sql FROM sqlite_master WHERE sql IS NOT NULL AND name NOT LIKE 'sqlite_%' ORDER BY CASE type WHEN 'table' THEN 0 ELSE 1 END, name"
22
+ );
23
+ const tables = [];
24
+ for (const row of schema.rows) {
25
+ out.push(`${String(row.sql).trim().replace(/;?$/, "")};`);
26
+ if (row.type === "table") tables.push(String(row.name));
27
+ }
28
+ for (const table of tables) {
29
+ const data = await db.execute(`SELECT * FROM ${quoteIdent(table)} ORDER BY rowid`);
30
+ if (data.rows.length === 0) continue;
31
+ const cols = data.columns.map(quoteIdent).join(", ");
32
+ for (const row of data.rows) {
33
+ const values = data.columns.map((c) => sqlLiteral(row[c])).join(", ");
34
+ out.push(`INSERT INTO ${quoteIdent(table)} (${cols}) VALUES (${values});`);
35
+ }
36
+ }
37
+ out.push("COMMIT;");
38
+ return out.join("\n") + "\n";
39
+ }
40
+ function countInsertsInDump(sql) {
41
+ const counts = {};
42
+ const re = /^INSERT INTO ("(?:[^"]|"")+"|[A-Za-z_][A-Za-z0-9_]*) /gm;
43
+ for (const m of sql.matchAll(re)) {
44
+ const raw = m[1];
45
+ const name = raw.startsWith('"') ? raw.slice(1, -1).replaceAll('""', '"') : raw;
46
+ counts[name] = (counts[name] ?? 0) + 1;
47
+ }
48
+ return counts;
49
+ }
50
+ async function tableCounts(db) {
51
+ const schema = await db.execute(
52
+ "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name"
53
+ );
54
+ const counts = {};
55
+ for (const row of schema.rows) {
56
+ const name = String(row.name);
57
+ const r = await db.execute(`SELECT COUNT(*) AS c FROM ${quoteIdent(name)}`);
58
+ counts[name] = Number(r.rows[0]?.c ?? 0);
59
+ }
60
+ return counts;
61
+ }
62
+ export {
63
+ countInsertsInDump,
64
+ dumpDatabase,
65
+ sqlLiteral,
66
+ tableCounts
67
+ };
68
+ //# sourceMappingURL=dump-P6EBSIOH.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/db/dump.ts"],"sourcesContent":["/**\n * Phase 1.5 of #539: a platform-auth-free SQL dump of the whole database.\n *\n * `turso db dump` needs a PLATFORM login (browser OAuth) — a nightly workflow\n * has only the DATABASE-level url+token it already holds for every other job.\n * So the dump speaks plain SQL through the same client: schema straight from\n * `sqlite_master`, then every row as an INSERT. The output loads into stock\n * `sqlite3` (libSQL IS SQLite), which is exactly how the rehearsed restore\n * proves it — and how a real disaster would replay it into a fresh database.\n *\n * Determinism: tables and rows are emitted in stable order (name, then rowid)\n * so two dumps of an unchanged database are byte-identical — a diffable backup.\n */\n\n/** Minimal execute surface: the @libsql/client `execute` we need. Injectable so\n * tests run against :memory: without the real network client. */\nexport type SqlExecutor = {\n execute: (sql: string) => Promise<{\n columns: string[];\n rows: Array<Record<string, unknown>>;\n }>;\n};\n\nconst IDENT = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\nfunction quoteIdent(name: string): string {\n return IDENT.test(name) ? name : `\"${name.replaceAll('\"', '\"\"')}\"`;\n}\n\nexport function sqlLiteral(v: unknown): string {\n if (v === null || v === undefined) return \"NULL\";\n if (typeof v === \"number\") return Number.isFinite(v) ? String(v) : \"NULL\";\n if (typeof v === \"bigint\") return v.toString();\n if (v instanceof Uint8Array || v instanceof ArrayBuffer) {\n const bytes = v instanceof ArrayBuffer ? new Uint8Array(v) : v;\n let hex = \"\";\n for (const b of bytes) hex += b.toString(16).padStart(2, \"0\");\n return `X'${hex}'`;\n }\n // Strings: standard SQL escaping — double the single quotes. NUL bytes cannot\n // ride a SQL literal; strip them (they cannot legitimately appear in this\n // schema's TEXT columns).\n return `'${String(v).replaceAll(\"\\u0000\", \"\").replaceAll(\"'\", \"''\")}'`;\n}\n\n/**\n * Dump schema + data as executable SQL. Skips SQLite's internal tables\n * (`sqlite_*`); includes indexes. Wrapped in a transaction so a partial load\n * fails atomically instead of leaving a half-restored scratch that could be\n * mistaken for a good one.\n */\nexport async function dumpDatabase(db: SqlExecutor): Promise<string> {\n const out: string[] = [\"PRAGMA foreign_keys=OFF;\", \"BEGIN TRANSACTION;\"];\n\n const schema = await db.execute(\n \"SELECT name, type, sql FROM sqlite_master \" +\n \"WHERE sql IS NOT NULL AND name NOT LIKE 'sqlite_%' \" +\n \"ORDER BY CASE type WHEN 'table' THEN 0 ELSE 1 END, name\",\n );\n\n const tables: string[] = [];\n for (const row of schema.rows) {\n out.push(`${String(row.sql).trim().replace(/;?$/, \"\")};`);\n if (row.type === \"table\") tables.push(String(row.name));\n }\n\n for (const table of tables) {\n const data = await db.execute(`SELECT * FROM ${quoteIdent(table)} ORDER BY rowid`);\n if (data.rows.length === 0) continue;\n const cols = data.columns.map(quoteIdent).join(\", \");\n for (const row of data.rows) {\n const values = data.columns.map((c) => sqlLiteral(row[c])).join(\", \");\n out.push(`INSERT INTO ${quoteIdent(table)} (${cols}) VALUES (${values});`);\n }\n }\n\n out.push(\"COMMIT;\");\n return out.join(\"\\n\") + \"\\n\";\n}\n\n/** Expected per-table row counts, read from the dump TEXT itself (one INSERT\n * per row, by construction). Lets the restore rehearsal verify without a\n * second network read of the origin — the dump is compared against itself. */\nexport function countInsertsInDump(sql: string): Record<string, number> {\n const counts: Record<string, number> = {};\n const re = /^INSERT INTO (\"(?:[^\"]|\"\")+\"|[A-Za-z_][A-Za-z0-9_]*) /gm;\n for (const m of sql.matchAll(re)) {\n const raw = m[1] as string;\n const name = raw.startsWith('\"') ? raw.slice(1, -1).replaceAll('\"\"', '\"') : raw;\n counts[name] = (counts[name] ?? 0) + 1;\n }\n return counts;\n}\n\n/** Per-table row counts — the cheap integrity check the restore rehearsal\n * compares across original vs restored. */\nexport async function tableCounts(db: SqlExecutor): Promise<Record<string, number>> {\n const schema = await db.execute(\n \"SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name\",\n );\n const counts: Record<string, number> = {};\n for (const row of schema.rows) {\n const name = String(row.name);\n const r = await db.execute(`SELECT COUNT(*) AS c FROM ${quoteIdent(name)}`);\n counts[name] = Number(r.rows[0]?.c ?? 0);\n }\n return counts;\n}\n"],"mappings":";AAuBA,IAAM,QAAQ;AAEd,SAAS,WAAW,MAAsB;AACxC,SAAO,MAAM,KAAK,IAAI,IAAI,OAAO,IAAI,KAAK,WAAW,KAAK,IAAI,CAAC;AACjE;AAEO,SAAS,WAAW,GAAoB;AAC7C,MAAI,MAAM,QAAQ,MAAM,OAAW,QAAO;AAC1C,MAAI,OAAO,MAAM,SAAU,QAAO,OAAO,SAAS,CAAC,IAAI,OAAO,CAAC,IAAI;AACnE,MAAI,OAAO,MAAM,SAAU,QAAO,EAAE,SAAS;AAC7C,MAAI,aAAa,cAAc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,GAAG;AAChC,UAAM,MAAM,EAAE,CAAC;AACf,UAAM,OAAO,IAAI,WAAW,GAAG,IAAI,IAAI,MAAM,GAAG,EAAE,EAAE,WAAW,MAAM,GAAG,IAAI;AAC5E,WAAO,IAAI,KAAK,OAAO,IAAI,KAAK,KAAK;AAAA,EACvC;AACA,SAAO;AACT;AAIA,eAAsB,YAAY,IAAkD;AAClF,QAAM,SAAS,MAAM,GAAG;AAAA,IACtB;AAAA,EACF;AACA,QAAM,SAAiC,CAAC;AACxC,aAAW,OAAO,OAAO,MAAM;AAC7B,UAAM,OAAO,OAAO,IAAI,IAAI;AAC5B,UAAM,IAAI,MAAM,GAAG,QAAQ,6BAA6B,WAAW,IAAI,CAAC,EAAE;AAC1E,WAAO,IAAI,IAAI,OAAO,EAAE,KAAK,CAAC,GAAG,KAAK,CAAC;AAAA,EACzC;AACA,SAAO;AACT;","names":[]}
@@ -0,0 +1,195 @@
1
+ import {
2
+ renderProspectReport
3
+ } from "./chunk-W7Z3BGCI.js";
4
+ import "./chunk-X3B723J4.js";
5
+ import {
6
+ escapeHtml,
7
+ safeUrl
8
+ } from "./chunk-DJZWYIPP.js";
9
+ import {
10
+ defaultResendClient
11
+ } from "./chunk-WEKL2HYJ.js";
12
+ import {
13
+ hostnameOf
14
+ } from "./chunk-EVBCK2KC.js";
15
+
16
+ // src/prospect/email.ts
17
+ var FROM_ADDRESS = "Reddoor Reports <reports@reddoorla.com>";
18
+ var IMPACT_ORDER = { high: 0, medium: 1, low: 2 };
19
+ var TOP_FIX_COUNT = 3;
20
+ function resolveName(result) {
21
+ return result.businessName && result.businessName.trim() ? result.businessName : hostnameOf(result.url);
22
+ }
23
+ function subjectSafe(s) {
24
+ return s.replace(/\s+/g, " ").trim();
25
+ }
26
+ function formatIsoDate(iso) {
27
+ const d = new Date(iso);
28
+ if (Number.isNaN(d.getTime())) return iso;
29
+ return d.toLocaleDateString("en-US", {
30
+ year: "numeric",
31
+ month: "long",
32
+ day: "numeric",
33
+ timeZone: "UTC"
34
+ });
35
+ }
36
+ function notMeasuredLines(result) {
37
+ const lines = [];
38
+ if (!result.checks.ok) {
39
+ lines.push({
40
+ label: "Findability",
41
+ reason: `the checks stage failed \u2014 ${result.checks.error}`
42
+ });
43
+ lines.push({
44
+ label: "Readability",
45
+ reason: `the checks stage failed \u2014 ${result.checks.error}`
46
+ });
47
+ } else {
48
+ const c = result.checks.data;
49
+ if (result.scores.findability === null) {
50
+ lines.push({
51
+ label: "Findability",
52
+ reason: !c.crawlerAccessMeasured ? "robots.txt could not be fetched, so crawler access wasn't measured" : "every crawled page failed to produce readable content"
53
+ });
54
+ }
55
+ if (result.scores.readability === null) {
56
+ lines.push({
57
+ label: "Readability",
58
+ reason: "no page produced a comparable raw/rendered pair to measure JavaScript dependence"
59
+ });
60
+ }
61
+ }
62
+ if (!result.lighthouse.ok) {
63
+ lines.push({ label: "Lighthouse", reason: result.lighthouse.error });
64
+ }
65
+ if (!result.analyze.ok) {
66
+ lines.push({ label: "Answers", reason: result.analyze.error });
67
+ } else if (result.scores.answers === null) {
68
+ lines.push({ label: "Answers", reason: "the model found no buyer questions to check" });
69
+ }
70
+ if (!result.probes.ok) {
71
+ lines.push({ label: "AI Visibility", reason: result.probes.error });
72
+ } else if (result.scores.aiVisibility === null) {
73
+ lines.push({ label: "AI Visibility", reason: "no category (buyer-question) query ran" });
74
+ }
75
+ return lines;
76
+ }
77
+ var SCORE_FIELDS = [
78
+ { key: "findability", label: "Findability" },
79
+ { key: "readability", label: "Readability" },
80
+ { key: "answers", label: "Answers" },
81
+ { key: "aiVisibility", label: "AI Visibility" }
82
+ ];
83
+ function scoresTableHtml(scores) {
84
+ const cells = SCORE_FIELDS.map(({ key, label }) => {
85
+ const value = scores[key];
86
+ const display = value === null ? "Not measured" : String(value);
87
+ const valueStyle = value === null ? "color:#8a857e;font-size:14px;" : "color:#d71920;font-size:28px;";
88
+ return `<td style="padding:12px 16px;border:1px solid #e6e1da;text-align:center;">
89
+ <div style="font-weight:600;${valueStyle}">${escapeHtml(display)}</div>
90
+ <div style="font-size:12px;letter-spacing:.04em;text-transform:uppercase;color:#57544f;margin-top:4px;">${escapeHtml(label)}</div>
91
+ </td>`;
92
+ }).join("");
93
+ return `<table role="presentation" style="border-collapse:collapse;margin:16px 0;"><tr>${cells}</tr></table>`;
94
+ }
95
+ function notMeasuredHtml(lines) {
96
+ if (lines.length === 0) return "";
97
+ const items = lines.map((l) => `<li><strong>${escapeHtml(l.label)}</strong> \u2014 ${escapeHtml(l.reason)}</li>`).join("");
98
+ return `<h2 style="font-size:16px;margin:24px 0 8px;">Not measured</h2><ul style="margin:0;padding-left:20px;">${items}</ul>`;
99
+ }
100
+ function fixesHtml(analyze) {
101
+ if (!analyze.ok) {
102
+ return `<p style="color:#8a857e;margin:8px 0 0;">Fixes not available \u2014 ${escapeHtml(analyze.error)}</p>`;
103
+ }
104
+ const top = [...analyze.data.fixes].sort((a, b) => IMPACT_ORDER[a.impact] - IMPACT_ORDER[b.impact]).slice(0, TOP_FIX_COUNT);
105
+ if (top.length === 0) {
106
+ return `<p style="margin:8px 0 0;">Nothing urgent \u2014 the essentials are already in place.</p>`;
107
+ }
108
+ const items = top.map(
109
+ (f) => `<li><strong>${escapeHtml(f.title)}</strong> \u2014 ${escapeHtml(f.why)} <span style="color:#8a857e;">(${escapeHtml(f.impact)} impact, ${escapeHtml(f.effort)} effort)</span></li>`
110
+ ).join("");
111
+ return `<ol style="margin:8px 0 0;padding-left:20px;">${items}</ol>`;
112
+ }
113
+ function linkHtml(link) {
114
+ if (!link) {
115
+ return `<p style="margin:24px 0 0;color:#8a857e;">No shareable link \u2014 the audit could not be saved to the database. The full report is attached to this email instead.</p>`;
116
+ }
117
+ const safe = safeUrl(link);
118
+ return `<p style="margin:24px 0 0;"><strong>Full report:</strong> <a href="${escapeHtml(safe)}">${escapeHtml(link)}</a></p>`;
119
+ }
120
+ var INTERNAL_NOTE = `<p style="margin:24px 0 0;padding:12px 14px;background:#f4f2ef;border-left:3px solid #d71920;color:#57544f;font-size:14px;">
121
+ Internal sheet \u2014 it names the reasons a section could not be measured. The
122
+ version to send a prospect is the linked report, also attached to this email.
123
+ </p>`;
124
+ function buildAuditEmail(result, opts) {
125
+ const name = resolveName(result);
126
+ const subject = `Prospect audit \u2014 ${subjectSafe(name)}`;
127
+ const html = `<!doctype html>
128
+ <html lang="en">
129
+ <head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /></head>
130
+ <body style="margin:0;padding:24px;background:#faf8f5;color:#1a1a1a;font:15px/1.5 -apple-system,BlinkMacSystemFont,'Segoe UI',Helvetica,Arial,sans-serif;">
131
+ <h1 style="font-size:22px;margin:0 0 4px;">Prospect audit \u2014 ${escapeHtml(name)}</h1>
132
+ <p style="margin:0 0 16px;color:#57544f;">
133
+ <a href="${escapeHtml(safeUrl(result.url))}">${escapeHtml(result.url)}</a> \xB7 audited ${escapeHtml(formatIsoDate(result.generatedAt))}
134
+ </p>
135
+ ${scoresTableHtml(result.scores)}
136
+ ${notMeasuredHtml(notMeasuredLines(result))}
137
+ <h2 style="font-size:16px;margin:24px 0 8px;">Top fixes</h2>
138
+ ${fixesHtml(result.analyze)}
139
+ ${linkHtml(opts.link)}
140
+ ${INTERNAL_NOTE}
141
+ </body>
142
+ </html>`;
143
+ return { subject, html, attachmentHtml: renderProspectReport(result) };
144
+ }
145
+ function parseProspectAuditRecipients(raw) {
146
+ if (!raw) return [];
147
+ const seen = /* @__PURE__ */ new Set();
148
+ const list = [];
149
+ for (const part of raw.split(",")) {
150
+ const trimmed = part.trim().toLowerCase();
151
+ if (!trimmed) continue;
152
+ if (seen.has(trimmed)) continue;
153
+ seen.add(trimmed);
154
+ list.push(trimmed);
155
+ }
156
+ return list;
157
+ }
158
+ function slugify(s) {
159
+ const slug = s.toLowerCase().replace(/[^a-z0-9.-]+/g, "-").replace(/^-+|-+$/g, "");
160
+ return slug || "prospect";
161
+ }
162
+ async function sendAuditEmail(result, opts) {
163
+ if (opts.recipients.length === 0) {
164
+ return {
165
+ sent: false,
166
+ reason: "no recipients configured (PROSPECT_AUDIT_RECIPIENTS is unset or empty)"
167
+ };
168
+ }
169
+ const built = buildAuditEmail(result, { link: opts.link });
170
+ const attachmentHtml = opts.renderReport ? opts.renderReport(result) : built.attachmentHtml;
171
+ const client = opts.client ?? defaultResendClient();
172
+ const idempotencyKey = `prospect-audit:${opts.auditId ?? `${result.url}#${result.generatedAt}`}`;
173
+ const filename = `prospect-audit-${slugify(hostnameOf(result.url))}.html`;
174
+ const { messageId } = await client.send({
175
+ from: FROM_ADDRESS,
176
+ to: opts.recipients,
177
+ subject: built.subject,
178
+ html: built.html,
179
+ attachments: [
180
+ {
181
+ filename,
182
+ content: Buffer.from(attachmentHtml, "utf-8").toString("base64"),
183
+ contentType: "text/html"
184
+ }
185
+ ],
186
+ idempotencyKey
187
+ });
188
+ return { sent: true, messageId, recipients: opts.recipients };
189
+ }
190
+ export {
191
+ buildAuditEmail,
192
+ parseProspectAuditRecipients,
193
+ sendAuditEmail
194
+ };
195
+ //# sourceMappingURL=email-VTTTKKL5.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/prospect/email.ts"],"sourcesContent":["import { escapeHtml, safeUrl } from \"../util/html.js\";\nimport { hostnameOf } from \"../util/url.js\";\nimport { renderProspectReport } from \"./render.js\";\nimport { defaultResendClient, type ResendClient } from \"../reports/send/resend.js\";\nimport type { AnalyzeResult, Fix, ProspectAuditResult, StageResult } from \"./types.js\";\n\n/**\n * Mirrors `reports/send/orchestrate.ts`'s `FROM_ADDRESS` (its line 18) — copied,\n * not imported, exactly like `digest.ts` and `recipes/selftest-email.ts` already\n * do. orchestrate.ts's own `FROM_ADDRESS` isn't exported, and importing it would\n * drag its whole Airtable/MJML dependency chain into this module's graph, which\n * stays lazy-loaded on purpose (see bin.ts's central-dep-blocker comment — this\n * module reaches `resend`, a devDependency, and must only ever be reached via a\n * dynamic `import()` from the CLI).\n */\nconst FROM_ADDRESS = \"Reddoor Reports <reports@reddoorla.com>\";\n\nconst IMPACT_ORDER: Record<Fix[\"impact\"], number> = { high: 0, medium: 1, low: 2 };\n\n/** \"top few fixes\" per the design — enough to be useful on an internal sheet\n * without turning it into the full client report. */\nconst TOP_FIX_COUNT = 3;\n\nexport type AuditEmailContent = {\n subject: string;\n html: string;\n /** The FULL client-facing report (render.ts's `renderProspectReport`, pure\n * and deterministic like this function), so `sendAuditEmail` can attach it\n * without a second render call on the default path. */\n attachmentHtml: string;\n};\n\n/** The searchable business name when the pipeline resolved one, else the\n * hostname — mirrors render.ts's identical fallback (types.ts's businessName\n * doc: \"Null when no name was ever resolved... itself a finding, not an\n * error\"). Used for both the subject line and the sheet's own heading. */\nfunction resolveName(result: ProspectAuditResult): string {\n return result.businessName && result.businessName.trim()\n ? result.businessName\n : hostnameOf(result.url);\n}\n\n/**\n * Mail subject headers are plain text, never HTML-rendered by a client — no\n * `escapeHtml` needed there (that would wrongly show literal \"&lt;\" etc. in\n * the subject line). A raw newline/control character IS worth collapsing:\n * a business name that embeds one (scraped page title, model output) would\n * otherwise visibly break the subject, and a stray CR/LF in a header value\n * is the classic email-header-injection vector — defense-in-depth even\n * though the Resend API's JSON transport already neutralizes it here.\n */\nfunction subjectSafe(s: string): string {\n return s.replace(/\\s+/g, \" \").trim();\n}\n\n/** Local copy of render.ts's date formatter — small enough that importing it\n * (render.ts doesn't export it) isn't worth the coupling. */\nfunction formatIsoDate(iso: string): string {\n const d = new Date(iso);\n if (Number.isNaN(d.getTime())) return iso;\n return d.toLocaleDateString(\"en-US\", {\n year: \"numeric\",\n month: \"long\",\n day: \"numeric\",\n timeZone: \"UTC\",\n });\n}\n\ntype NotMeasuredLine = { label: string; reason: string };\n\n/**\n * Everything on the sheet that reads \"not measured\", and why — in plain\n * words. Unlike render.ts's client-facing report (which collapses every\n * stage failure to STAGE_FAILED_MESSAGE so a stranger never sees operator\n * vocabulary), this email goes to Tucker/Tim/Erik: the real diagnostic\n * (a fetch error, an LLM timeout) is more useful to them than a sanitized\n * phrase, so stage `error` strings are surfaced verbatim (still escaped —\n * they can embed arbitrary text from a fetch response).\n *\n * The four-Scores branches mirror checks.ts's `computeScores` exactly: which\n * stage feeds which score, and the cases where that stage's OWN data still\n * nulls the score even though the stage itself succeeded (crawlerAccessMeasured\n * false, avgMissing null, empty buyerQuestions, a null visibilityScore). If\n * computeScores' conditions change, this needs the matching update.\n */\nfunction notMeasuredLines(result: ProspectAuditResult): NotMeasuredLine[] {\n const lines: NotMeasuredLine[] = [];\n\n if (!result.checks.ok) {\n lines.push({\n label: \"Findability\",\n reason: `the checks stage failed — ${result.checks.error}`,\n });\n lines.push({\n label: \"Readability\",\n reason: `the checks stage failed — ${result.checks.error}`,\n });\n } else {\n const c = result.checks.data;\n if (result.scores.findability === null) {\n lines.push({\n label: \"Findability\",\n reason: !c.crawlerAccessMeasured\n ? \"robots.txt could not be fetched, so crawler access wasn't measured\"\n : \"every crawled page failed to produce readable content\",\n });\n }\n if (result.scores.readability === null) {\n lines.push({\n label: \"Readability\",\n reason: \"no page produced a comparable raw/rendered pair to measure JavaScript dependence\",\n });\n }\n }\n\n if (!result.lighthouse.ok) {\n lines.push({ label: \"Lighthouse\", reason: result.lighthouse.error });\n }\n\n if (!result.analyze.ok) {\n lines.push({ label: \"Answers\", reason: result.analyze.error });\n } else if (result.scores.answers === null) {\n lines.push({ label: \"Answers\", reason: \"the model found no buyer questions to check\" });\n }\n\n if (!result.probes.ok) {\n lines.push({ label: \"AI Visibility\", reason: result.probes.error });\n } else if (result.scores.aiVisibility === null) {\n lines.push({ label: \"AI Visibility\", reason: \"no category (buyer-question) query ran\" });\n }\n\n return lines;\n}\n\nconst SCORE_FIELDS: { key: keyof ProspectAuditResult[\"scores\"]; label: string }[] = [\n { key: \"findability\", label: \"Findability\" },\n { key: \"readability\", label: \"Readability\" },\n { key: \"answers\", label: \"Answers\" },\n { key: \"aiVisibility\", label: \"AI Visibility\" },\n];\n\nfunction scoresTableHtml(scores: ProspectAuditResult[\"scores\"]): string {\n const cells = SCORE_FIELDS.map(({ key, label }) => {\n const value = scores[key];\n const display = value === null ? \"Not measured\" : String(value);\n const valueStyle =\n value === null ? \"color:#8a857e;font-size:14px;\" : \"color:#d71920;font-size:28px;\";\n return `<td style=\"padding:12px 16px;border:1px solid #e6e1da;text-align:center;\">\n <div style=\"font-weight:600;${valueStyle}\">${escapeHtml(display)}</div>\n <div style=\"font-size:12px;letter-spacing:.04em;text-transform:uppercase;color:#57544f;margin-top:4px;\">${escapeHtml(label)}</div>\n </td>`;\n }).join(\"\");\n return `<table role=\"presentation\" style=\"border-collapse:collapse;margin:16px 0;\"><tr>${cells}</tr></table>`;\n}\n\nfunction notMeasuredHtml(lines: NotMeasuredLine[]): string {\n if (lines.length === 0) return \"\";\n const items = lines\n .map((l) => `<li><strong>${escapeHtml(l.label)}</strong> — ${escapeHtml(l.reason)}</li>`)\n .join(\"\");\n return `<h2 style=\"font-size:16px;margin:24px 0 8px;\">Not measured</h2><ul style=\"margin:0;padding-left:20px;\">${items}</ul>`;\n}\n\n/** analyze.error and fix titles/why are untrusted (LLM output, or text lifted\n * from the prospect's own site) — every interpolation below is escaped. */\nfunction fixesHtml(analyze: StageResult<AnalyzeResult>): string {\n if (!analyze.ok) {\n return `<p style=\"color:#8a857e;margin:8px 0 0;\">Fixes not available — ${escapeHtml(analyze.error)}</p>`;\n }\n const top = [...analyze.data.fixes]\n .sort((a, b) => IMPACT_ORDER[a.impact] - IMPACT_ORDER[b.impact])\n .slice(0, TOP_FIX_COUNT);\n if (top.length === 0) {\n return `<p style=\"margin:8px 0 0;\">Nothing urgent — the essentials are already in place.</p>`;\n }\n const items = top\n .map(\n (f) =>\n `<li><strong>${escapeHtml(f.title)}</strong> — ${escapeHtml(f.why)} <span style=\"color:#8a857e;\">(${escapeHtml(f.impact)} impact, ${escapeHtml(f.effort)} effort)</span></li>`,\n )\n .join(\"\");\n return `<ol style=\"margin:8px 0 0;padding-left:20px;\">${items}</ol>`;\n}\n\nfunction linkHtml(link: string | null): string {\n if (!link) {\n return `<p style=\"margin:24px 0 0;color:#8a857e;\">No shareable link — the audit could not be saved to the database. The full report is attached to this email instead.</p>`;\n }\n const safe = safeUrl(link);\n return `<p style=\"margin:24px 0 0;\"><strong>Full report:</strong> <a href=\"${escapeHtml(safe)}\">${escapeHtml(link)}</a></p>`;\n}\n\n/** This sheet is for us, and it says so. It carries the real reasons a stage did\n * not run — useful internally, wrong in front of a prospect — so it has to be\n * obvious that the shareable artefact is the attachment and the link, not this\n * body. Without the label, the natural thing to do with a useful email is\n * forward it. */\nconst INTERNAL_NOTE = `<p style=\"margin:24px 0 0;padding:12px 14px;background:#f4f2ef;border-left:3px solid #d71920;color:#57544f;font-size:14px;\">\n Internal sheet — it names the reasons a section could not be measured. The\n version to send a prospect is the linked report, also attached to this email.\n</p>`;\n\n/**\n * Build the internal sheet — a SHORT summary for Tucker/Tim/Erik, distinct\n * from the client-facing report render.ts builds. Pure: no IO, so it's safe\n * to call from a test with no network. `attachmentHtml` is the full report\n * (render.ts's `renderProspectReport`, itself pure), included here so\n * `sendAuditEmail`'s default path doesn't need a second render call.\n *\n * Every value that can trace back to the prospect's site or the model —\n * the business name, fixes, stage error text, the narrative-adjacent bits —\n * is escaped with `escapeHtml`/`safeUrl`, the same honesty-and-safety rule\n * render.ts follows for the client-facing report.\n */\nexport function buildAuditEmail(\n result: ProspectAuditResult,\n opts: { link: string | null },\n): AuditEmailContent {\n const name = resolveName(result);\n const subject = `Prospect audit — ${subjectSafe(name)}`;\n\n const html = `<!doctype html>\n<html lang=\"en\">\n<head><meta charset=\"utf-8\" /><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" /></head>\n<body style=\"margin:0;padding:24px;background:#faf8f5;color:#1a1a1a;font:15px/1.5 -apple-system,BlinkMacSystemFont,'Segoe UI',Helvetica,Arial,sans-serif;\">\n <h1 style=\"font-size:22px;margin:0 0 4px;\">Prospect audit — ${escapeHtml(name)}</h1>\n <p style=\"margin:0 0 16px;color:#57544f;\">\n <a href=\"${escapeHtml(safeUrl(result.url))}\">${escapeHtml(result.url)}</a> · audited ${escapeHtml(formatIsoDate(result.generatedAt))}\n </p>\n ${scoresTableHtml(result.scores)}\n ${notMeasuredHtml(notMeasuredLines(result))}\n <h2 style=\"font-size:16px;margin:24px 0 8px;\">Top fixes</h2>\n ${fixesHtml(result.analyze)}\n ${linkHtml(opts.link)}\n ${INTERNAL_NOTE}\n</body>\n</html>`;\n\n return { subject, html, attachmentHtml: renderProspectReport(result) };\n}\n\n/**\n * Parse `PROSPECT_AUDIT_RECIPIENTS` (comma-separated) into a clean address\n * list: trimmed, empties dropped, case-insensitively deduped — mirrors\n * `reports/send/orchestrate.ts`'s `parseAddresses` for the same reasons (an\n * operator-typed env var, same typo surface). No address is ever hardcoded\n * anywhere in this module; an unset or empty var yields `[]`, which\n * `sendAuditEmail` treats as \"skip, and say why\" rather than an error.\n */\nexport function parseProspectAuditRecipients(raw: string | undefined | null): string[] {\n if (!raw) return [];\n const seen = new Set<string>();\n const list: string[] = [];\n for (const part of raw.split(\",\")) {\n const trimmed = part.trim().toLowerCase();\n if (!trimmed) continue;\n if (seen.has(trimmed)) continue;\n seen.add(trimmed);\n list.push(trimmed);\n }\n return list;\n}\n\n/** Filesystem-safe attachment-filename fragment. Tiny local copy of the CLI's\n * private `slugify` (prospect-audit.ts) — not worth exporting/sharing one\n * three-line predicate across a module boundary. */\nfunction slugify(s: string): string {\n const slug = s\n .toLowerCase()\n .replace(/[^a-z0-9.-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n return slug || \"prospect\";\n}\n\nexport type SendAuditEmailOptions = {\n link: string | null;\n recipients: string[];\n /**\n * The persisted `prospect_audits` row id (from `createProspectAudit`), when\n * persistence succeeded. Mirrors orchestrate.ts's\n * `idempotencyKey: \\`report:${report.id}\\`` pattern, so re-sending for the\n * SAME already-persisted audit dedupes at Resend instead of double-mailing.\n * Null when persistence failed — the sheet can still be sent (it's built to\n * survive independently of Turso), but then there is no stable row id, so\n * the key falls back to `url`+`generatedAt`: that still protects a\n * same-process double-call, though — unlike a DB id — it can't survive an\n * entire pipeline rerun, which mints genuinely new content anyway.\n */\n auditId?: string | null;\n /** Defaults to `defaultResendClient()`. */\n client?: ResendClient;\n /** Test seam for the ATTACHMENT content only (production omits it and gets\n * the real `renderProspectReport` output `buildAuditEmail` already\n * computed) — lets a test of this function's sending mechanics (recipients,\n * idempotency key, attachment shape) skip re-deriving the full report. */\n renderReport?: (result: ProspectAuditResult) => string;\n};\n\nexport type SendAuditEmailResult =\n { sent: true; messageId: string; recipients: string[] } | { sent: false; reason: string };\n\n/**\n * Send the audit sheet with the full rendered report attached as an `.html`\n * file (base64), so the sheet survives independently of the link and of\n * Turso. Empty `recipients` is a legitimate, non-exceptional outcome (no\n * `PROSPECT_AUDIT_RECIPIENTS` configured) — returns `{sent:false}` rather\n * than throwing, so a caller can report it as a warning; a genuine send\n * failure (a throwing `client.send`) still propagates as a real exception.\n */\nexport async function sendAuditEmail(\n result: ProspectAuditResult,\n opts: SendAuditEmailOptions,\n): Promise<SendAuditEmailResult> {\n if (opts.recipients.length === 0) {\n return {\n sent: false,\n reason: \"no recipients configured (PROSPECT_AUDIT_RECIPIENTS is unset or empty)\",\n };\n }\n\n const built = buildAuditEmail(result, { link: opts.link });\n const attachmentHtml = opts.renderReport ? opts.renderReport(result) : built.attachmentHtml;\n const client = opts.client ?? defaultResendClient();\n const idempotencyKey = `prospect-audit:${opts.auditId ?? `${result.url}#${result.generatedAt}`}`;\n const filename = `prospect-audit-${slugify(hostnameOf(result.url))}.html`;\n\n const { messageId } = await client.send({\n from: FROM_ADDRESS,\n to: opts.recipients,\n subject: built.subject,\n html: built.html,\n attachments: [\n {\n filename,\n content: Buffer.from(attachmentHtml, \"utf-8\").toString(\"base64\"),\n contentType: \"text/html\",\n },\n ],\n idempotencyKey,\n });\n\n return { sent: true, messageId, recipients: opts.recipients };\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAeA,IAAM,eA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AAAA,QACE;AAAA,QACA,SAAS,OAAO,KAAK,gBAAgB,OAAO,EAAE,SAAS,QAAQ;AAAA,QAC/D,aAAa;AAAA,MACf;AAAA,IACF;AAAA,IACA;AAAA,EACF,CAAC;AAED,SAAO,EAAE,MAAM,MAAM,WAAW,YAAY,KAAK,WAAW;AAC9D;","names":[]}
@@ -1,12 +1,13 @@
1
- import {
2
- WEBSITES_TABLE,
3
- listWebsites,
4
- siteSlug
5
- } from "./chunk-577HCGZO.js";
6
1
  import {
7
2
  openBase,
8
3
  readAirtableConfig
9
4
  } from "./chunk-HN6I2XWI.js";
5
+ import {
6
+ WEBSITES_TABLE,
7
+ listWebsites,
8
+ siteSlug,
9
+ toAirtableStatus
10
+ } from "./chunk-LDWZSLSU.js";
10
11
  import "./chunk-6VAL7XJT.js";
11
12
 
12
13
  // src/reports/airtable/ensure-site.ts
@@ -26,7 +27,7 @@ async function ensureSite(base, input) {
26
27
  if (!existing) {
27
28
  const fields = {
28
29
  Name: input.displayName ?? slug,
29
- Status: "in development",
30
+ Status: toAirtableStatus("building"),
30
31
  [COLS.gitRepo]: input.gitRepo ?? `reddoorla/${slug}`
31
32
  };
32
33
  if (input.url) fields[COLS.url] = input.url;
@@ -84,4 +85,4 @@ async function runEnsureSiteCommand(slug, opts) {
84
85
  export {
85
86
  runEnsureSiteCommand
86
87
  };
87
- //# sourceMappingURL=ensure-site-S25MDDHW.js.map
88
+ //# sourceMappingURL=ensure-site-DFTB7MN3.js.map