@reddoorla/maintenance 0.86.0 → 0.88.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/airtable-QG5ICI3Y.js +9 -0
- package/dist/{announce-MXTUQ6C7.js → announce-GKD5YJNB.js} +49 -28
- package/dist/announce-GKD5YJNB.js.map +1 -0
- package/dist/attachments-NLZIJ5NU.js +9 -0
- package/dist/{blux-ZGDSHI3U.js → blux-DN4MI532.js} +5 -5
- package/dist/{bump-deps-EC74CPLS.js → bump-deps-KGH5UYSF.js} +4 -4
- package/dist/{chunk-N45M3FDK.js → chunk-6I6L3CMX.js} +4 -4
- package/dist/{chunk-KTH5ZODA.js → chunk-7BZUOZPU.js} +2 -2
- package/dist/{chunk-2EVEFOZY.js → chunk-7FFUBF4I.js} +6 -3
- package/dist/chunk-7FFUBF4I.js.map +1 -0
- package/dist/{chunk-LDWZSLSU.js → chunk-7NYN2P6I.js} +7 -4
- package/dist/{chunk-LDWZSLSU.js.map → chunk-7NYN2P6I.js.map} +1 -1
- package/dist/{chunk-X3B723J4.js → chunk-7TMWBXX7.js} +184 -25
- package/dist/chunk-7TMWBXX7.js.map +1 -0
- package/dist/{chunk-3VQWSE3F.js → chunk-7UAYMAKR.js} +4 -4
- package/dist/{chunk-W7Z3BGCI.js → chunk-A2UNJIKH.js} +15 -7
- package/dist/chunk-A2UNJIKH.js.map +1 -0
- package/dist/{chunk-F5KM4LEQ.js → chunk-ANJNTAMM.js} +4 -70
- package/dist/chunk-ANJNTAMM.js.map +1 -0
- package/dist/{chunk-2ZPT7GLV.js → chunk-B23FFWU4.js} +4 -4
- package/dist/chunk-B23FFWU4.js.map +1 -0
- package/dist/{chunk-DJZWYIPP.js → chunk-BGTYPVLT.js} +1 -1
- package/dist/chunk-BGTYPVLT.js.map +1 -0
- package/dist/chunk-BRYXFH77.js +70 -0
- package/dist/chunk-BRYXFH77.js.map +1 -0
- package/dist/{chunk-2NDRHXMR.js → chunk-DGZWFI2G.js} +18 -141
- package/dist/chunk-DGZWFI2G.js.map +1 -0
- package/dist/{chunk-ACBRLLFT.js → chunk-F3JWOPTG.js} +7 -3
- package/dist/chunk-F3JWOPTG.js.map +1 -0
- package/dist/chunk-GQDDWYU2.js +372 -0
- package/dist/chunk-GQDDWYU2.js.map +1 -0
- package/dist/{chunk-Z7AXYKQB.js → chunk-IY6256GK.js} +1 -1
- package/dist/{chunk-BYK66EWO.js → chunk-J3WEZGIN.js} +52 -46
- package/dist/chunk-J3WEZGIN.js.map +1 -0
- package/dist/{chunk-BNM5POSJ.js → chunk-JRHIFA5R.js} +2 -2
- package/dist/{chunk-ZKXSX4LO.js → chunk-K6SLF6GI.js} +6 -6
- package/dist/{chunk-CQR4LIM7.js → chunk-KJGKZLCT.js} +7 -3
- package/dist/{chunk-CQR4LIM7.js.map → chunk-KJGKZLCT.js.map} +1 -1
- package/dist/{chunk-PPE5KZJK.js → chunk-KMCZA7CH.js} +13 -3
- package/dist/chunk-KMCZA7CH.js.map +1 -0
- package/dist/{chunk-3SF7D4DY.js → chunk-MFHS7IQ2.js} +36 -1
- package/dist/{chunk-3SF7D4DY.js.map → chunk-MFHS7IQ2.js.map} +1 -1
- package/dist/{chunk-SNSTJLQW.js → chunk-NO74DXDP.js} +48 -2
- package/dist/chunk-NO74DXDP.js.map +1 -0
- package/dist/{chunk-C6B4RHXR.js → chunk-O3GT46R2.js} +8 -2
- package/dist/chunk-O3GT46R2.js.map +1 -0
- package/dist/{chunk-ITIOFN7A.js → chunk-P6AORG32.js} +29 -10
- package/dist/chunk-P6AORG32.js.map +1 -0
- package/dist/{chunk-SLUQ7R6I.js → chunk-PR343K7F.js} +5 -5
- package/dist/{chunk-P2FE5AI6.js → chunk-Q47DU255.js} +4 -4
- package/dist/{chunk-EVBCK2KC.js → chunk-RARREDQE.js} +2 -1
- package/dist/{chunk-EVBCK2KC.js.map → chunk-RARREDQE.js.map} +1 -1
- package/dist/chunk-RUPPWAD6.js +7 -0
- package/dist/chunk-RUPPWAD6.js.map +1 -0
- package/dist/{chunk-VSBFM7DS.js → chunk-SJOXWJ5Y.js} +3 -3
- package/dist/{chunk-TERE5SDF.js → chunk-ULHPALI5.js} +4 -4
- package/dist/{chunk-XUGSZP7Z.js → chunk-W45FZEGE.js} +2 -2
- package/dist/{chunk-JHGHLKFS.js → chunk-WS6NU475.js} +2 -2
- package/dist/chunk-XP5WM2LV.js +146 -0
- package/dist/chunk-XP5WM2LV.js.map +1 -0
- package/dist/{chunk-ILUNZHYV.js → chunk-YFAXOD7Z.js} +10 -6
- package/dist/chunk-YFAXOD7Z.js.map +1 -0
- package/dist/{chunk-6TWWY7ZU.js → chunk-Z3JXLULD.js} +2 -2
- package/dist/cli/bin.js +34 -29
- package/dist/cli/bin.js.map +1 -1
- package/dist/cli/commands/audit.d.ts +4 -0
- package/dist/cli/commands/audit.js +25 -18
- package/dist/cli/commands/audit.js.map +1 -1
- package/dist/client-JYKPVCJX.js +11 -0
- package/dist/configs/playwright-a11y.js +1 -1
- package/dist/{convert-to-pnpm-6L6P74WR.js → convert-to-pnpm-NWB5FCQ2.js} +4 -4
- package/dist/{db-B35OGV3G.js → db-V6UIS433.js} +124 -29
- package/dist/db-V6UIS433.js.map +1 -0
- package/dist/{digest-BL6UJYKH.js → digest-2JEAEJK6.js} +60 -35
- package/dist/digest-2JEAEJK6.js.map +1 -0
- package/dist/digest-state-CRZRNGDI.js +25 -0
- package/dist/digest-state-CRZRNGDI.js.map +1 -0
- package/dist/digest-state-F37XUCS5.js +13 -0
- package/dist/{dump-P6EBSIOH.js → dump-EPL7AZFR.js} +38 -13
- package/dist/dump-EPL7AZFR.js.map +1 -0
- package/dist/{email-VTTTKKL5.js → email-SL7464YI.js} +16 -6
- package/dist/{email-VTTTKKL5.js.map → email-SL7464YI.js.map} +1 -1
- package/dist/{ensure-site-DFTB7MN3.js → ensure-site-FU6527OU.js} +19 -11
- package/dist/ensure-site-FU6527OU.js.map +1 -0
- package/dist/fleet-state-R5LU7IC3.js +41 -0
- package/dist/{forms-notify-target-75U6OU7L.js → forms-notify-target-SGDGXXK5.js} +10 -7
- package/dist/forms-notify-target-SGDGXXK5.js.map +1 -0
- package/dist/{github-signals-IJUPGCUX.js → github-signals-GWGCKEE2.js} +13 -12
- package/dist/{github-signals-IJUPGCUX.js.map → github-signals-GWGCKEE2.js.map} +1 -1
- package/dist/{header-image-AWLLQA4L.js → header-image-7A7XLVEU.js} +8 -8
- package/dist/{header-images-335L2AKB.js → header-images-SQBCE5OD.js} +21 -1
- package/dist/header-images-SQBCE5OD.js.map +1 -0
- package/dist/{health-endpoint-WJC2UMYS.js → health-endpoint-UVX6R5N5.js} +4 -4
- package/dist/health-mirror-GCDN7BJL.js +46 -0
- package/dist/health-mirror-GCDN7BJL.js.map +1 -0
- package/dist/{import-airtable-HE43FB4H.js → import-airtable-OHVY344G.js} +7 -5
- package/dist/index.d.ts +149 -0
- package/dist/index.js +245 -108
- package/dist/index.js.map +1 -1
- package/dist/{init-NJEOEO7I.js → init-FGTYNGUI.js} +11 -11
- package/dist/{launch-XNAX427U.js → launch-5H7LPEGP.js} +59 -29
- package/dist/launch-5H7LPEGP.js.map +1 -0
- package/dist/{lighthouse-airtable-LBVIYYP5.js → lighthouse-airtable-3GUWHETW.js} +3 -3
- package/dist/migrate-YITCXBLS.js +7 -0
- package/dist/{notify-C645PGD5.js → notify-4HP4GZ2H.js} +5 -5
- package/dist/{onboard-GK4PHPNI.js → onboard-BKCYBAVW.js} +4 -4
- package/dist/{orchestrate-77UO4BYJ.js → orchestrate-JNKCWU5K.js} +14 -13
- package/dist/parity-NBYZUBFU.js +14 -0
- package/dist/pdf-N5QLQ5ZQ.js +38 -0
- package/dist/pdf-N5QLQ5ZQ.js.map +1 -0
- package/dist/{pipeline-S6CVHDGB.js → pipeline-WYTXSLHX.js} +3 -3
- package/dist/{preflight-6WBNU2GZ.js → preflight-IMTYDDD4.js} +15 -14
- package/dist/{preflight-6WBNU2GZ.js.map → preflight-IMTYDDD4.js.map} +1 -1
- package/dist/{prismic-ci-3RHOZUUT.js → prismic-ci-MY2U6NN7.js} +7 -7
- package/dist/{prismic-models-QBGUT2Q3.js → prismic-models-NJN5JORF.js} +15 -10
- package/dist/prismic-models-NJN5JORF.js.map +1 -0
- package/dist/prospect/types.d.ts +281 -0
- package/dist/prospect/types.js +1 -0
- package/dist/{prospect-audit-IUNCJ2LV.js → prospect-audit-JMBRVXSG.js} +32 -13
- package/dist/prospect-audit-JMBRVXSG.js.map +1 -0
- package/dist/recipes/sync-configs.js +2 -2
- package/dist/render-VX72AESY.js +10 -0
- package/dist/render-VX72AESY.js.map +1 -0
- package/dist/render-from-row-DOYJDO2L.js +17 -0
- package/dist/render-from-row-DOYJDO2L.js.map +1 -0
- package/dist/{renovate-dispatch-QJY75ODR.js → renovate-dispatch-6GQWTRKX.js} +10 -10
- package/dist/{renovate-dispatch-QJY75ODR.js.map → renovate-dispatch-6GQWTRKX.js.map} +1 -1
- package/dist/{replay-C2LXMJZP.js → replay-4S6ENYCH.js} +3 -3
- package/dist/{report-4EVNDHOZ.js → report-TALY5P3L.js} +63 -21
- package/dist/report-TALY5P3L.js.map +1 -0
- package/dist/report-mirror-AAK3MXHY.js +55 -0
- package/dist/report-mirror-AAK3MXHY.js.map +1 -0
- package/dist/rerender-3FM6DNRH.js +32 -0
- package/dist/rerender-3FM6DNRH.js.map +1 -0
- package/dist/schema-75PJECAE.js +18 -0
- package/dist/schema-75PJECAE.js.map +1 -0
- package/dist/{self-updating-6DWI2Z56.js → self-updating-NTCCWJYZ.js} +4 -4
- package/dist/{selftest-RC36MTKP.js → selftest-NZTR4SM2.js} +26 -24
- package/dist/{selftest-RC36MTKP.js.map → selftest-NZTR4SM2.js.map} +1 -1
- package/dist/site-mirror-Q763PLGG.js +62 -0
- package/dist/site-mirror-Q763PLGG.js.map +1 -0
- package/dist/{smoke-suite-VYY2LXM2.js → smoke-suite-4JFZZYVW.js} +4 -4
- package/dist/{spam-classifier-XLBFCO7G.js → spam-classifier-T5H4VTP6.js} +4 -2
- package/dist/spam-classifier-T5H4VTP6.js.map +1 -0
- package/dist/{submissions-Q7DRFOCD.js → submissions-TEHPBSZJ.js} +5 -5
- package/dist/{svelte-codemods-25J2FO22.js → svelte-codemods-QAPDZC6F.js} +4 -4
- package/dist/{sync-34HNZZ56.js → sync-GBFV45WX.js} +6 -4
- package/dist/{sync-34HNZZ56.js.map → sync-GBFV45WX.js.map} +1 -1
- package/dist/{sync-configs-3SE6PSCO.js → sync-configs-34JIA6KZ.js} +6 -6
- package/dist/{upgrade-WBRQ62FX.js → upgrade-IR2OO3KP.js} +4 -4
- package/dist/{webflow-IRKOIT7S.js → webflow-624FEBFD.js} +4 -4
- package/dist/{webhook-VOGOW3W6.js → webhook-XM6EV4XT.js} +2 -2
- package/dist/{websites-SXWTP72S.js → websites-D6WYFAES.js} +2 -2
- package/dist/websites-D6WYFAES.js.map +1 -0
- package/dist/write-audits-to-airtable-OBHGR7DQ.js +17 -0
- package/dist/write-audits-to-airtable-OBHGR7DQ.js.map +1 -0
- package/package.json +5 -1
- package/dist/airtable-G7WBQQMI.js +0 -9
- package/dist/announce-MXTUQ6C7.js.map +0 -1
- package/dist/chunk-2EVEFOZY.js.map +0 -1
- package/dist/chunk-2NDRHXMR.js.map +0 -1
- package/dist/chunk-2ZPT7GLV.js.map +0 -1
- package/dist/chunk-ACBRLLFT.js.map +0 -1
- package/dist/chunk-BYK66EWO.js.map +0 -1
- package/dist/chunk-C6B4RHXR.js.map +0 -1
- package/dist/chunk-DJZWYIPP.js.map +0 -1
- package/dist/chunk-F5KM4LEQ.js.map +0 -1
- package/dist/chunk-ILUNZHYV.js.map +0 -1
- package/dist/chunk-ITIOFN7A.js.map +0 -1
- package/dist/chunk-PPE5KZJK.js.map +0 -1
- package/dist/chunk-SNSTJLQW.js.map +0 -1
- package/dist/chunk-W7Z3BGCI.js.map +0 -1
- package/dist/chunk-X3B723J4.js.map +0 -1
- package/dist/client-AUE3XUPO.js +0 -11
- package/dist/db-B35OGV3G.js.map +0 -1
- package/dist/digest-BL6UJYKH.js.map +0 -1
- package/dist/dump-P6EBSIOH.js.map +0 -1
- package/dist/ensure-site-DFTB7MN3.js.map +0 -1
- package/dist/forms-notify-target-75U6OU7L.js.map +0 -1
- package/dist/header-images-335L2AKB.js.map +0 -1
- package/dist/health-mirror-4B2L7T2Y.js +0 -75
- package/dist/health-mirror-4B2L7T2Y.js.map +0 -1
- package/dist/launch-XNAX427U.js.map +0 -1
- package/dist/migrate-GQH237A6.js +0 -7
- package/dist/parity-MWS24A3H.js +0 -12
- package/dist/prismic-models-QBGUT2Q3.js.map +0 -1
- package/dist/prospect-audit-IUNCJ2LV.js.map +0 -1
- package/dist/render-AQAVQDPZ.js +0 -10
- package/dist/report-4EVNDHOZ.js.map +0 -1
- package/dist/write-audits-to-airtable-MBEILLPU.js +0 -14
- /package/dist/{airtable-G7WBQQMI.js.map → airtable-QG5ICI3Y.js.map} +0 -0
- /package/dist/{client-AUE3XUPO.js.map → attachments-NLZIJ5NU.js.map} +0 -0
- /package/dist/{blux-ZGDSHI3U.js.map → blux-DN4MI532.js.map} +0 -0
- /package/dist/{bump-deps-EC74CPLS.js.map → bump-deps-KGH5UYSF.js.map} +0 -0
- /package/dist/{chunk-N45M3FDK.js.map → chunk-6I6L3CMX.js.map} +0 -0
- /package/dist/{chunk-KTH5ZODA.js.map → chunk-7BZUOZPU.js.map} +0 -0
- /package/dist/{chunk-3VQWSE3F.js.map → chunk-7UAYMAKR.js.map} +0 -0
- /package/dist/{chunk-Z7AXYKQB.js.map → chunk-IY6256GK.js.map} +0 -0
- /package/dist/{chunk-BNM5POSJ.js.map → chunk-JRHIFA5R.js.map} +0 -0
- /package/dist/{chunk-ZKXSX4LO.js.map → chunk-K6SLF6GI.js.map} +0 -0
- /package/dist/{chunk-SLUQ7R6I.js.map → chunk-PR343K7F.js.map} +0 -0
- /package/dist/{chunk-P2FE5AI6.js.map → chunk-Q47DU255.js.map} +0 -0
- /package/dist/{chunk-VSBFM7DS.js.map → chunk-SJOXWJ5Y.js.map} +0 -0
- /package/dist/{chunk-TERE5SDF.js.map → chunk-ULHPALI5.js.map} +0 -0
- /package/dist/{chunk-XUGSZP7Z.js.map → chunk-W45FZEGE.js.map} +0 -0
- /package/dist/{chunk-JHGHLKFS.js.map → chunk-WS6NU475.js.map} +0 -0
- /package/dist/{chunk-6TWWY7ZU.js.map → chunk-Z3JXLULD.js.map} +0 -0
- /package/dist/{import-airtable-HE43FB4H.js.map → client-JYKPVCJX.js.map} +0 -0
- /package/dist/{convert-to-pnpm-6L6P74WR.js.map → convert-to-pnpm-NWB5FCQ2.js.map} +0 -0
- /package/dist/{lighthouse-airtable-LBVIYYP5.js.map → digest-state-F37XUCS5.js.map} +0 -0
- /package/dist/{migrate-GQH237A6.js.map → fleet-state-R5LU7IC3.js.map} +0 -0
- /package/dist/{header-image-AWLLQA4L.js.map → header-image-7A7XLVEU.js.map} +0 -0
- /package/dist/{health-endpoint-WJC2UMYS.js.map → health-endpoint-UVX6R5N5.js.map} +0 -0
- /package/dist/{notify-C645PGD5.js.map → import-airtable-OHVY344G.js.map} +0 -0
- /package/dist/{init-NJEOEO7I.js.map → init-FGTYNGUI.js.map} +0 -0
- /package/dist/{orchestrate-77UO4BYJ.js.map → lighthouse-airtable-3GUWHETW.js.map} +0 -0
- /package/dist/{parity-MWS24A3H.js.map → migrate-YITCXBLS.js.map} +0 -0
- /package/dist/{pipeline-S6CVHDGB.js.map → notify-4HP4GZ2H.js.map} +0 -0
- /package/dist/{onboard-GK4PHPNI.js.map → onboard-BKCYBAVW.js.map} +0 -0
- /package/dist/{render-AQAVQDPZ.js.map → orchestrate-JNKCWU5K.js.map} +0 -0
- /package/dist/{spam-classifier-XLBFCO7G.js.map → parity-NBYZUBFU.js.map} +0 -0
- /package/dist/{websites-SXWTP72S.js.map → pipeline-WYTXSLHX.js.map} +0 -0
- /package/dist/{prismic-ci-3RHOZUUT.js.map → prismic-ci-MY2U6NN7.js.map} +0 -0
- /package/dist/{write-audits-to-airtable-MBEILLPU.js.map → prospect/types.js.map} +0 -0
- /package/dist/{replay-C2LXMJZP.js.map → replay-4S6ENYCH.js.map} +0 -0
- /package/dist/{self-updating-6DWI2Z56.js.map → self-updating-NTCCWJYZ.js.map} +0 -0
- /package/dist/{smoke-suite-VYY2LXM2.js.map → smoke-suite-4JFZZYVW.js.map} +0 -0
- /package/dist/{submissions-Q7DRFOCD.js.map → submissions-TEHPBSZJ.js.map} +0 -0
- /package/dist/{svelte-codemods-25J2FO22.js.map → svelte-codemods-QAPDZC6F.js.map} +0 -0
- /package/dist/{sync-configs-3SE6PSCO.js.map → sync-configs-34JIA6KZ.js.map} +0 -0
- /package/dist/{upgrade-WBRQ62FX.js.map → upgrade-IR2OO3KP.js.map} +0 -0
- /package/dist/{webflow-IRKOIT7S.js.map → webflow-624FEBFD.js.map} +0 -0
- /package/dist/{webhook-VOGOW3W6.js.map → webhook-XM6EV4XT.js.map} +0 -0
|
@@ -4,7 +4,7 @@ import {
|
|
|
4
4
|
import {
|
|
5
5
|
draftReportForSite,
|
|
6
6
|
readGaConfig
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-J3WEZGIN.js";
|
|
8
8
|
import {
|
|
9
9
|
findDueReports,
|
|
10
10
|
nextDueDate,
|
|
@@ -12,27 +12,27 @@ import {
|
|
|
12
12
|
} from "./chunk-PZR4EBPY.js";
|
|
13
13
|
import {
|
|
14
14
|
reportTier
|
|
15
|
-
} from "./chunk-
|
|
16
|
-
import "./chunk-5UINJNAJ.js";
|
|
17
|
-
import "./chunk-CQR4LIM7.js";
|
|
18
|
-
import "./chunk-Z7AXYKQB.js";
|
|
19
|
-
import {
|
|
20
|
-
escapeHtml
|
|
21
|
-
} from "./chunk-DJZWYIPP.js";
|
|
15
|
+
} from "./chunk-YFAXOD7Z.js";
|
|
22
16
|
import {
|
|
23
17
|
listAllReports
|
|
24
|
-
} from "./chunk-
|
|
18
|
+
} from "./chunk-F3JWOPTG.js";
|
|
25
19
|
import "./chunk-VAD43MOR.js";
|
|
20
|
+
import "./chunk-IY6256GK.js";
|
|
26
21
|
import {
|
|
27
22
|
openBase,
|
|
28
23
|
readAirtableConfig
|
|
29
24
|
} from "./chunk-HN6I2XWI.js";
|
|
30
|
-
import "./chunk-
|
|
25
|
+
import "./chunk-5UINJNAJ.js";
|
|
26
|
+
import "./chunk-KJGKZLCT.js";
|
|
27
|
+
import {
|
|
28
|
+
escapeHtml
|
|
29
|
+
} from "./chunk-BGTYPVLT.js";
|
|
31
30
|
import {
|
|
32
31
|
listWebsites,
|
|
33
32
|
siteSlug,
|
|
34
33
|
updateNextDueDates
|
|
35
|
-
} from "./chunk-
|
|
34
|
+
} from "./chunk-7NYN2P6I.js";
|
|
35
|
+
import "./chunk-RARREDQE.js";
|
|
36
36
|
import "./chunk-6VAL7XJT.js";
|
|
37
37
|
|
|
38
38
|
// src/alerts/analytics-health.ts
|
|
@@ -78,12 +78,34 @@ function dashboardBaseUrl() {
|
|
|
78
78
|
}
|
|
79
79
|
async function runReportCommand(slug, opts) {
|
|
80
80
|
if (opts.digest) {
|
|
81
|
-
const { runDigest } = await import("./digest-
|
|
81
|
+
const { runDigest } = await import("./digest-2JEAEJK6.js");
|
|
82
82
|
return runDigest({ baseUrl: dashboardBaseUrl() });
|
|
83
83
|
}
|
|
84
84
|
if (opts.sendReady) {
|
|
85
|
-
const { sendApprovedReports } = await import("./orchestrate-
|
|
86
|
-
|
|
85
|
+
const { sendApprovedReports } = await import("./orchestrate-JNKCWU5K.js");
|
|
86
|
+
const { makeSiteMirror } = await import("./site-mirror-Q763PLGG.js");
|
|
87
|
+
return sendApprovedReports({ siteMirror: await makeSiteMirror() });
|
|
88
|
+
}
|
|
89
|
+
if (opts.rerender) {
|
|
90
|
+
const { rerenderReport, formatRerenderResult } = await import("./rerender-3FM6DNRH.js");
|
|
91
|
+
const { renderReportFromRow } = await import("./render-from-row-DOYJDO2L.js");
|
|
92
|
+
const { openDb, readDbConfig } = await import("./client-JYKPVCJX.js");
|
|
93
|
+
const { getReportById, getSiteById, storeRenderedHtml } = await import("./fleet-state-R5LU7IC3.js");
|
|
94
|
+
const { loadHeaderImage } = await import("./header-images-SQBCE5OD.js");
|
|
95
|
+
const { fetchAttachmentBytes } = await import("./attachments-NLZIJ5NU.js");
|
|
96
|
+
const db = await openDb(readDbConfig());
|
|
97
|
+
const result = await rerenderReport(
|
|
98
|
+
{
|
|
99
|
+
getReport: (id) => getReportById(db, id),
|
|
100
|
+
getSite: (id) => getSiteById(db, id),
|
|
101
|
+
loadHeaderPlate: async (id) => (await loadHeaderImage(db, id))?.bytes ?? null,
|
|
102
|
+
fetchAirtableHeader: async (url) => (await fetchAttachmentBytes(url)).bytes,
|
|
103
|
+
render: (site, report, plate) => renderReportFromRow(site, report, plate),
|
|
104
|
+
store: (id, html) => storeRenderedHtml(db, id, html)
|
|
105
|
+
},
|
|
106
|
+
opts.rerender
|
|
107
|
+
);
|
|
108
|
+
return { output: formatRerenderResult(result), code: result.status === "rendered" ? 0 : 1 };
|
|
87
109
|
}
|
|
88
110
|
if (opts.due) {
|
|
89
111
|
return runDueDraft();
|
|
@@ -107,8 +129,16 @@ async function runReportCommand(slug, opts) {
|
|
|
107
129
|
}
|
|
108
130
|
async function runDueDraft() {
|
|
109
131
|
const base = openBase(readAirtableConfig());
|
|
110
|
-
const { makeScheduleMirrorBestEffort } = await import("./health-mirror-
|
|
111
|
-
const
|
|
132
|
+
const { makeScheduleMirrorBestEffort } = await import("./health-mirror-GCDN7BJL.js");
|
|
133
|
+
const { makeReportMirror } = await import("./report-mirror-AAK3MXHY.js");
|
|
134
|
+
const { makeSiteMirror } = await import("./site-mirror-Q763PLGG.js");
|
|
135
|
+
const result = await draftDueReports(
|
|
136
|
+
base,
|
|
137
|
+
/* @__PURE__ */ new Date(),
|
|
138
|
+
await makeScheduleMirrorBestEffort(),
|
|
139
|
+
await makeReportMirror(),
|
|
140
|
+
await makeSiteMirror()
|
|
141
|
+
);
|
|
112
142
|
await alertOnFleetAnalyticsFailure(result.health);
|
|
113
143
|
return { output: result.output, code: result.code };
|
|
114
144
|
}
|
|
@@ -165,7 +195,11 @@ async function writeNextDueDates(base, websites, reports, today, scheduleMirror
|
|
|
165
195
|
const mirrorNote = scheduleMirror ? ` mirrored=${mirrored} mirror_failed=${mirrorFailed} mirror_missed=${mirrorMissed}` : " mirror=absent";
|
|
166
196
|
console.log(`NEXT_DUE_WRITE wrote=${wrote} skipped=${skipped} failed=${failed}${mirrorNote}`);
|
|
167
197
|
}
|
|
168
|
-
async function draftDueReports(base, today, scheduleMirror = null) {
|
|
198
|
+
async function draftDueReports(base, today, scheduleMirror = null, reportMirror, siteMirror) {
|
|
199
|
+
const mirrorOpt = {
|
|
200
|
+
...reportMirror ? { reportMirror } : {},
|
|
201
|
+
...siteMirror ? { siteMirror } : {}
|
|
202
|
+
};
|
|
169
203
|
const websites = await listWebsites(base);
|
|
170
204
|
const reports = await listAllReports(base);
|
|
171
205
|
await writeNextDueDates(base, websites, reports, today, scheduleMirror);
|
|
@@ -210,7 +244,8 @@ async function draftDueReports(base, today, scheduleMirror = null) {
|
|
|
210
244
|
const result = await draftReportForSite(base, item.site, item.reportType, {
|
|
211
245
|
period,
|
|
212
246
|
completeRowId: existing.id,
|
|
213
|
-
existingRow: existing
|
|
247
|
+
existingRow: existing,
|
|
248
|
+
...mirrorOpt
|
|
214
249
|
});
|
|
215
250
|
existing.draftReady = result.queued === true;
|
|
216
251
|
lines.push(
|
|
@@ -241,7 +276,10 @@ async function draftDueReports(base, today, scheduleMirror = null) {
|
|
|
241
276
|
continue;
|
|
242
277
|
}
|
|
243
278
|
try {
|
|
244
|
-
const result = await draftReportForSite(base, item.site, item.reportType, {
|
|
279
|
+
const result = await draftReportForSite(base, item.site, item.reportType, {
|
|
280
|
+
period,
|
|
281
|
+
...mirrorOpt
|
|
282
|
+
});
|
|
245
283
|
lines.push(draftLine(result.reportRow?.reportId, result.queued, result.supersededIds));
|
|
246
284
|
if (result.reportRow) reports.push(result.reportRow);
|
|
247
285
|
if (isAnalyticsConfigured(item.site)) gaConfiguredSites++;
|
|
@@ -283,11 +321,15 @@ async function runSingleSiteDraft(slug, opts) {
|
|
|
283
321
|
if (!site) {
|
|
284
322
|
throw Object.assign(new Error(`No Websites row matched slug "${slug}"`), { exitCode: 2 });
|
|
285
323
|
}
|
|
324
|
+
const reportMirror = opts.previewOnly ? null : await (await import("./report-mirror-AAK3MXHY.js")).makeReportMirror();
|
|
325
|
+
const siteMirror = opts.previewOnly ? null : await (await import("./site-mirror-Q763PLGG.js")).makeSiteMirror();
|
|
286
326
|
const result = await draftReportForSite(opts.previewOnly ? null : base, site, opts.reportType, {
|
|
287
327
|
previewOnly: opts.previewOnly,
|
|
288
328
|
// Only forced on. Left undefined, draftReportForSite keeps its default
|
|
289
329
|
// (enrich iff there is a base), so the real drafting path is untouched.
|
|
290
|
-
...opts.enrich ? { enrich: true } : {}
|
|
330
|
+
...opts.enrich ? { enrich: true } : {},
|
|
331
|
+
...reportMirror ? { reportMirror } : {},
|
|
332
|
+
...siteMirror ? { siteMirror } : {}
|
|
291
333
|
});
|
|
292
334
|
if (opts.previewOnly) {
|
|
293
335
|
return { output: `Preview written to ${result.htmlPath}`, code: 0 };
|
|
@@ -308,4 +350,4 @@ export {
|
|
|
308
350
|
runReportCommand,
|
|
309
351
|
writeNextDueDates
|
|
310
352
|
};
|
|
311
|
-
//# sourceMappingURL=report-
|
|
353
|
+
//# sourceMappingURL=report-TALY5P3L.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/alerts/analytics-health.ts","../src/cli/commands/report.ts"],"sourcesContent":["import { escapeHtml } from \"../util/html.js\";\n\n/**\n * The GA/Search enrichment outcome of one `report --due` draft run, aggregated\n * across the sites it drafted. `softFailedSites` is how many drafted sites had GA\n * OR Search enrichment ERROR (not \"not configured\" — that's a legitimate skip);\n * `configuredSites` is how many drafted sites had analytics configured at all\n * (the subject is set AND the site has a GA4 property or a search query). The ratio\n * is what distinguishes a fleet-wide subject outage from a single transient blip.\n */\nexport type AnalyticsRunHealth = {\n softFailedSites: number;\n configuredSites: number;\n};\n\nexport type AnalyticsAlert = { fire: boolean; reason: string };\n\n/** A lone failure never alerts — that's a per-site config issue, not the shared-\n * subject SPOF. Two-plus AND a majority of configured sites is the fleet signature. */\nconst MIN_FAILED_SITES = 2;\n\n/**\n * Decide whether a draft run's GA/Search soft-failures look FLEET-WIDE — i.e. the\n * one impersonated subject (`GA_SUBJECT`) lost access — rather than one site's\n * transient blip. PURE. Fires when at least {@link MIN_FAILED_SITES} configured\n * sites failed AND they are a majority (≥ half) of the analytics-configured sites\n * this run. With <2 configured sites it can't distinguish a SPOF from a one-off, so\n * it never fires (at fleet scale there are always many configured sites).\n */\nexport function assessAnalyticsAlert(h: AnalyticsRunHealth): AnalyticsAlert {\n const { softFailedSites, configuredSites } = h;\n const fire =\n configuredSites >= 2 &&\n softFailedSites >= MIN_FAILED_SITES &&\n softFailedSites * 2 >= configuredSites;\n const reason = fire\n ? `${softFailedSites} of ${configuredSites} analytics-configured sites had GA/Search enrichment fail this run — the shared GA_SUBJECT likely lost access (an offboarded user, revoked property access, or a botched role-account cutover). Reports were drafted with BLANK analytics.`\n : \"\";\n return { fire, reason };\n}\n\n/**\n * Compose the operator alert email for a fleet-wide analytics failure. PURE — the\n * caller (the `report --due` cron) sends it best-effort via Resend only when\n * {@link assessAnalyticsAlert} fires. `dashboardUrl` is the fleet homepage link.\n */\nexport function composeAnalyticsAlertEmail(\n h: AnalyticsRunHealth,\n dashboardUrl: string,\n): { subject: string; html: string } {\n const subject = `⚠ Fleet analytics enrichment failing — ${h.softFailedSites}/${h.configuredSites} sites`;\n const { reason } = assessAnalyticsAlert(h);\n const html = `<p><strong>${escapeHtml(reason)}</strong></p>\n<p>This usually means the Google Workspace user the service account impersonates can no longer read the GA4 / Search Console properties. Reports still send — but with blank analytics — until the subject is restored.</p>\n<p>Next step: follow the GA/Search subject runbook (<code>docs/runbooks/ga-search-role-account-cutover.md</code>) to restore or move the subject, then re-run <code>reddoor-maint report --due</code> and confirm the warning clears.</p>\n<p><a href=\"${escapeHtml(dashboardUrl)}\">Open the fleet dashboard →</a></p>`;\n return { subject, html };\n}\n","import { openBase, readAirtableConfig, type AirtableBase } from \"../../reports/airtable/client.js\";\nimport {\n listWebsites,\n siteSlug,\n updateNextDueDates,\n type WebsiteRow,\n} from \"../../reports/airtable/websites.js\";\nimport { listAllReports, type ReportRow } from \"../../reports/airtable/reports.js\";\nimport { findDueReports, nextDueDate, reportPeriodKey } from \"../../reports/due.js\";\nimport { draftReportForSite } from \"../../reports/draft.js\";\nimport { reportTier } from \"../../reports/queue.js\";\nimport { readGaConfig } from \"../../reports/ga/config.js\";\nimport {\n assessAnalyticsAlert,\n composeAnalyticsAlertEmail,\n type AnalyticsRunHealth,\n} from \"../../alerts/analytics-health.js\";\nimport type { ReportType } from \"../../reports/types.js\";\nimport type { ScheduleMirror } from \"../../audits/health-mirror.js\";\nimport type { ReportMirror } from \"../../reports/report-mirror.js\";\nimport type { SiteMirror } from \"../../db/site-mirror.js\";\nimport { operatorEmail } from \"../../util/operator.js\";\n\nexport type ReportCommandOptions = {\n due?: boolean;\n preview?: boolean;\n enrich?: boolean;\n sendReady?: boolean;\n digest?: boolean;\n rerender?: string;\n type?: string;\n cwd?: string;\n};\n\n/**\n * Summary line for a drafted report, reflecting the single-queue outcome. `queued === false`\n * means a higher-or-equal-tier report was already pending for the site, so this draft was\n * created but deliberately left OUT of the approve queue. A non-empty `supersededIds` means it\n * un-queued that many lower-tier drafts. `null` is the previewOnly path (no Airtable queue).\n */\nfunction draftLine(\n reportId: string | undefined,\n queued: boolean | null,\n supersededIds: string[],\n verb = \"drafted\",\n): string {\n const id = reportId ?? \"(unknown)\";\n if (queued === false) {\n return `• ${verb} but NOT queued: ${id} — a higher-or-equal-tier report is already pending approval`;\n }\n const sup =\n supersededIds.length > 0\n ? ` (superseded ${supersededIds.length} lower-tier draft${supersededIds.length > 1 ? \"s\" : \"\"})`\n : \"\";\n return `✓ ${verb}: ${id}${sup}`;\n}\n\n/**\n * Parse the single-site `--type` flag. Only Maintenance and Testing are draftable\n * this way — Launch has the `launch <site>` command and Announcement has\n * `announce <site>`, each with its own purpose-built flow. Case-insensitive;\n * defaults to Maintenance (the historical single-site behaviour). Throws an\n * exitCode-2 usage error on anything else. PURE.\n */\nexport function parseSingleSiteReportType(raw: string | undefined): ReportType {\n if (raw === undefined || raw.trim() === \"\") return \"Maintenance\";\n const norm = raw.trim().toLowerCase();\n if (norm === \"maintenance\") return \"Maintenance\";\n if (norm === \"testing\") return \"Testing\";\n const hint =\n norm === \"launch\"\n ? \" — use the `launch <site>` command\"\n : norm === \"announcement\"\n ? \" — use the `announce <site>` command\"\n : \"\";\n throw Object.assign(\n new Error(`--type must be Maintenance or Testing (got ${JSON.stringify(raw)})${hint}`),\n { exitCode: 2 },\n );\n}\n\n/** Dashboard origin for digest /s/<slug> links. DASHBOARD_BASE_URL overrides the\n * production default; the trailing slash (if any) is trimmed by runDigest. */\nfunction dashboardBaseUrl(): string {\n return process.env.DASHBOARD_BASE_URL?.trim() || \"https://reddoor-maintenance.netlify.app\";\n}\n\nexport async function runReportCommand(\n slug: string | undefined,\n opts: ReportCommandOptions,\n): Promise<{ output: string; code: number }> {\n if (opts.digest) {\n const { runDigest } = await import(\"../../reports/digest.js\");\n return runDigest({ baseUrl: dashboardBaseUrl() });\n }\n\n if (opts.sendReady) {\n const { sendApprovedReports } = await import(\"../../reports/send/orchestrate.js\");\n // #539 Phase 5: a Launch send flips Status + stamps `Launched at` on the\n // Websites row; without this it reaches Turso only via the hourly sync.\n const { makeSiteMirror } = await import(\"../../db/site-mirror.js\");\n return sendApprovedReports({ siteMirror: await makeSiteMirror() });\n }\n\n // Refresh ONE unsent report's stored body so the console preview reflects\n // commentary edited after drafting. Runs here rather than in a Netlify\n // function because rendering needs sharp — see rerender.ts.\n if (opts.rerender) {\n const { rerenderReport, formatRerenderResult } = await import(\"../../reports/send/rerender.js\");\n const { renderReportFromRow } = await import(\"../../reports/send/render-from-row.js\");\n const { openDb, readDbConfig } = await import(\"../../db/client.js\");\n const { getReportById, getSiteById, storeRenderedHtml } =\n await import(\"../../db/fleet-state.js\");\n const { loadHeaderImage } = await import(\"../../db/header-images.js\");\n const { fetchAttachmentBytes } = await import(\"../../reports/airtable/attachments.js\");\n const db = await openDb(readDbConfig());\n const result = await rerenderReport(\n {\n getReport: (id) => getReportById(db, id),\n getSite: (id) => getSiteById(db, id),\n loadHeaderPlate: async (id) => (await loadHeaderImage(db, id))?.bytes ?? null,\n fetchAirtableHeader: async (url) => (await fetchAttachmentBytes(url)).bytes,\n render: (site, report, plate) => renderReportFromRow(site, report, plate),\n store: (id, html) => storeRenderedHtml(db, id, html),\n },\n opts.rerender,\n );\n // Exit 1 on anything but a render, so a dispatched run that refused is RED\n // rather than a green run that silently changed nothing.\n return { output: formatRerenderResult(result), code: result.status === \"rendered\" ? 0 : 1 };\n }\n\n if (opts.due) {\n return runDueDraft();\n }\n\n if (slug) {\n // Validate the type BEFORE any Airtable access so a bad --type fails fast (and\n // without needing credentials).\n const reportType = parseSingleSiteReportType(opts.type);\n return runSingleSiteDraft(slug, {\n previewOnly: Boolean(opts.preview),\n enrich: Boolean(opts.enrich),\n reportType,\n });\n }\n\n throw Object.assign(\n new Error(\n \"Usage: reddoor-maint report [<slug>] [--type <Maintenance|Testing>] [--due] [--preview] [--enrich] [--send-ready] [--digest]\",\n ),\n {\n exitCode: 2,\n },\n );\n}\n\nasync function runDueDraft(): Promise<{ output: string; code: number }> {\n const base = openBase(readAirtableConfig());\n // Phase 3 dual-write (#539): mirror real next-due writes into site_schedule.\n // Null when libSQL creds are absent — the Airtable path is unchanged.\n const { makeScheduleMirrorBestEffort } = await import(\"../../audits/health-mirror.js\");\n // Phase 5 dual-write (#539): mirror this batch's report writes — the created\n // rows, their bodies, and the queue flags. Unlike the schedule mirror this is\n // never null — creds-absent is reported on the REPORT_MIRROR line rather than\n // being indistinguishable from success, the failure mode that hid #585.\n const { makeReportMirror } = await import(\"../../reports/report-mirror.js\");\n const { makeSiteMirror } = await import(\"../../db/site-mirror.js\");\n const result = await draftDueReports(\n base,\n new Date(),\n await makeScheduleMirrorBestEffort(),\n await makeReportMirror(),\n await makeSiteMirror(),\n );\n await alertOnFleetAnalyticsFailure(result.health);\n return { output: result.output, code: result.code };\n}\n\n/** Best-effort: when a draft run's GA/Search soft-failures look FLEET-WIDE (the shared\n * GA_SUBJECT lost access — see assessAnalyticsAlert), email the operator one alert.\n * NEVER throws — a Resend or config hiccup must not fail the nightly draft cron; the\n * per-site `⚠ GA skipped` warnings + the run-output line still carry the signal. The\n * daily idempotency key dedupes multiple runs in one day (Resend dedupes 24h). */\nasync function alertOnFleetAnalyticsFailure(health: AnalyticsRunHealth): Promise<void> {\n if (!assessAnalyticsAlert(health).fire) return;\n try {\n const to = operatorEmail();\n const { subject, html } = composeAnalyticsAlertEmail(health, dashboardBaseUrl());\n const { defaultResendClient } = await import(\"../../reports/send/resend.js\");\n await defaultResendClient().send({\n from: \"Reddoor Reports <reports@reddoorla.com>\",\n to: [to],\n subject,\n html,\n idempotencyKey: `analytics-alert-${new Date().toISOString().slice(0, 10)}`,\n });\n console.warn(`⚠ ${subject} — operator alerted (${to})`);\n } catch (e) {\n console.warn(`⚠ analytics-failure alert send failed: ${(e as Error).message}`);\n }\n}\n\n/**\n * Write each site's code-computed next-maintenance / next-testing date back to Airtable\n * (date-only, or null when there's no schedule), so the \"next\" dates shown there derive\n * from the SAME `nextDueDate` the scheduler uses — replacing the old Airtable formula +\n * automation. Best-effort and per-site isolated: a missing `Next … at` column or one bad\n * row warns and is skipped, never aborting the nightly draft run.\n *\n * The diff-guard (#539 Phase 3): a site whose computed dates equal what its row\n * already holds is SKIPPED — before it, every one of the 44 sites got a nightly\n * write while only the handful whose schedule actually moved needed one (a\n * never-maintained site re-wrote null over null forever). This also scopes the\n * write to maintained sites by construction: no schedule → computed null →\n * equal to the stored null → skipped. Each real write dual-writes through\n * `scheduleMirror` into site_schedule (null mirror = Turso creds absent; the\n * hourly sync converges either way). The NEXT_DUE_WRITE line is observability,\n * not a CI gate — nothing greps it yet.\n */\nexport async function writeNextDueDates(\n base: AirtableBase,\n websites: WebsiteRow[],\n reports: ReportRow[],\n today: Date,\n scheduleMirror: ScheduleMirror | null = null,\n): Promise<void> {\n const ymd = (d: Date | null): string | null => (d ? d.toISOString().slice(0, 10) : null);\n let wrote = 0;\n let skipped = 0;\n let failed = 0;\n let mirrored = 0;\n let mirrorFailed = 0;\n let mirrorMissed = 0;\n for (const site of websites) {\n // The whole per-site body sits in ONE try — compute included — so a bad\n // row can only cost its own write, exactly the pre-diff-guard blast radius.\n try {\n const maintenanceAt = ymd(nextDueDate(site, reports, \"Maintenance\", today));\n const testingAt = ymd(nextDueDate(site, reports, \"Testing\", today));\n if (maintenanceAt === site.nextMaintenanceAt && testingAt === site.nextTestingAt) {\n skipped++;\n continue;\n }\n const fields = await updateNextDueDates(base, site.id, { maintenanceAt, testingAt });\n wrote++;\n if (scheduleMirror) {\n try {\n // false = the UPDATE matched no site_schedule row (site created in\n // Airtable since the last hourly import) — missed, not mirrored.\n if (await scheduleMirror(site.id, fields, today.toISOString())) mirrored++;\n else mirrorMissed++;\n } catch (e) {\n mirrorFailed++;\n console.warn(`⚠ [schedule-mirror] ${site.name}: ${(e as Error).message}`);\n }\n }\n } catch (e) {\n failed++;\n console.warn(`⚠ next-due write skipped for ${site.name}: ${(e as Error).message}`);\n }\n }\n // failed= keeps a write outage visible: without it wrote+skipped silently\n // undercounts, and a FULL outage prints wrote=0 skipped=0 — indistinguishable\n // from an empty fleet.\n // A null mirror writes nothing and throws nothing, so its only trace used to\n // be an ABSENT suffix — which reads exactly like a healthy run. `mirror=absent`\n // states it instead. Counters stay off in that case deliberately: `mirrored=0`\n // would claim a write that returned nothing, not one that was never attempted.\n const mirrorNote = scheduleMirror\n ? ` mirrored=${mirrored} mirror_failed=${mirrorFailed} mirror_missed=${mirrorMissed}`\n : \" mirror=absent\";\n console.log(`NEXT_DUE_WRITE wrote=${wrote} skipped=${skipped} failed=${failed}${mirrorNote}`);\n}\n\nexport async function draftDueReports(\n base: AirtableBase,\n today: Date,\n scheduleMirror: ScheduleMirror | null = null,\n /** #539 Phase 5: Turso write-through for rows this batch CREATES. Forwarded\n * to every draftReportForSite call — the nightly batch is the only unattended\n * creator of report rows, so a dropped pass-through leaves each new draft\n * invisible to the Turso-backed console. */\n reportMirror?: ReportMirror,\n /** #539 Phase 5: the Websites-row twin — drafting stamps `Analytics soft-fail\n * at` on the SITE row, a different Turso table from the report. */\n siteMirror?: SiteMirror,\n): Promise<{ output: string; code: number; health: AnalyticsRunHealth }> {\n const mirrorOpt = {\n ...(reportMirror ? { reportMirror } : {}),\n ...(siteMirror ? { siteMirror } : {}),\n };\n const websites = await listWebsites(base);\n // ONE unfiltered fetch for the whole fleet. Per-site queries can't be pushed to\n // Airtable anyway (linked-record fields aren't formula-filterable by record id),\n // and findDueReports + the period guard below match on siteId in memory.\n const reports = await listAllReports(base);\n\n // Refresh every site's code-owned next-due dates first, so they stay current even on\n // a run where nothing is due (the early return below).\n await writeNextDueDates(base, websites, reports, today, scheduleMirror);\n\n const due = findDueReports(websites, reports, today);\n\n // GA/Search enrichment is configured globally (the impersonation subject) AND\n // per-site (a GA4 property or a search query). `gaConfigured` is the global half;\n // the per-site half is checked as each draft runs, to build the fleet-wide\n // analytics-failure alert's denominator (see alertOnFleetAnalyticsFailure).\n const gaConfigured = readGaConfig() !== null;\n // Truthy (not `!== null`) to mirror fetchGaUsers/fetchSearch's own gate exactly\n // (`!siteRow.ga4PropertyId`), so an empty-string cell counts as not-configured in\n // BOTH places and can't inflate the alert denominator.\n const isAnalyticsConfigured = (s: WebsiteRow): boolean =>\n gaConfigured && Boolean(s.ga4PropertyId || s.searchQuery);\n\n if (due.length === 0) {\n return {\n output: \"No reports due.\",\n code: 0,\n health: { softFailedSites: 0, configuredSites: 0 },\n };\n }\n\n const lines: string[] = [];\n let softFailedSites = 0;\n let searchDefaultMisses = 0;\n let searchPropertiesMissing = 0;\n let gaConfiguredSites = 0;\n let skipped = 0;\n for (const item of due) {\n // Idempotency: a re-run must not re-draft a (site, type) already drafted this\n // recurrence. The dueDate's YYYY-MM is the stable per-cycle key. Match against the\n // reports we already fetched — no extra query on the hot path.\n const period = reportPeriodKey(item.dueDate);\n const existing = reports.find(\n (r) => r.siteId === item.site.id && r.reportType === item.reportType && r.period === period,\n );\n\n // A row already exists for THIS period. Two cases:\n // - Draft ready → truly done, skip (the idempotent re-run path).\n // - NOT ready → a crash between createDraft and setDraftReady wedged it: the\n // row exists (so we never re-draft) yet it's never sendable (listSendable\n // needs Draft ready). COMPLETE it in place instead of skipping forever —\n // re-render → re-upload the HTML → flip Draft ready on the EXISTING row.\n if (existing) {\n if (existing.draftReady) {\n skipped++;\n lines.push(`• skipped (already drafted ${period}): ${item.site.name} ${item.reportType}`);\n continue;\n }\n // A not-ready row is normally a crash between createDraft and setDraftReady — re-complete\n // it in place. BUT queueDraft also clears Draft ready on rows it supersedes/blocks, and\n // those must NOT be re-completed: doing so would re-render and APPEND a duplicate HTML\n // attachment every nightly run, only to be re-blocked. Distinguish the two: if a\n // higher-or-equal-tier report is still pending for this site, this row was intentionally\n // un-queued (not crashed) — skip it until the blocker is sent/approved or the month rolls.\n const blockedByPending = reports.some(\n (r) =>\n r.siteId === item.site.id &&\n r.id !== existing.id &&\n r.sentAt === null &&\n r.draftReady &&\n reportTier(r.reportType) >= reportTier(item.reportType),\n );\n if (blockedByPending) {\n skipped++;\n lines.push(\n `• skipped (superseded — a higher-or-equal-tier report is pending): ${item.site.name} ${item.reportType}`,\n );\n continue;\n }\n try {\n const result = await draftReportForSite(base, item.site, item.reportType, {\n period,\n completeRowId: existing.id,\n existingRow: existing,\n ...mirrorOpt,\n });\n existing.draftReady = result.queued === true;\n lines.push(\n draftLine(\n result.reportRow?.reportId ?? existing.reportId,\n result.queued,\n result.supersededIds,\n \"completed half-made draft\",\n ),\n );\n if (isAnalyticsConfigured(item.site)) gaConfiguredSites++;\n if (result.softFailures.length > 0) softFailedSites++;\n if (result.searchDefaultMissed) searchDefaultMisses++;\n if (result.searchPropertyMissing) searchPropertiesMissing++;\n } catch (e) {\n lines.push(`✗ failed: ${item.site.name} ${item.reportType} — ${(e as Error).message}`);\n }\n continue;\n }\n\n // Pile-up guard: don't accrue a fresh new-period draft every recurrence for a\n // site nobody ever approves. The period key follows the DUE month, so each\n // recurrence wants a new (later-period) draft — but if a PRIOR draft is still\n // pending approval, a new one just stacks. Skip creating the new one while an\n // earlier-period draft for this (site, type) sits ready-but-unsent.\n //\n // `r.draftReady` is load-bearing: a draft a higher tier SUPERSEDED has\n // draftReady=false and never gets a Sent at, so without this clause it would\n // match (sentAt null + earlier period) and block EVERY future draft for the\n // site forever. Pending-approval means draftReady=true AND sentAt=null.\n const pendingEarlier = reports.find(\n (r) =>\n r.siteId === item.site.id &&\n r.reportType === item.reportType &&\n r.draftReady &&\n r.sentAt === null &&\n r.period !== null &&\n r.period < period,\n );\n if (pendingEarlier) {\n skipped++;\n lines.push(\n `• skipped: ${item.site.name} ${item.reportType} already has an unsent ${pendingEarlier.period} draft pending approval`,\n );\n continue;\n }\n\n try {\n // Pass the SAME key the guard searches by, so the stamped Period always\n // matches a future run's reportPeriodKey(dueDate) — even if this run lags\n // into a later month than the dueDate.\n const result = await draftReportForSite(base, item.site, item.reportType, {\n period,\n ...mirrorOpt,\n });\n lines.push(draftLine(result.reportRow?.reportId, result.queued, result.supersededIds));\n // Keep the in-memory snapshot current so the guard's `.some()` check on the\n // NEXT iteration of this same run catches a row we JUST created — rather than\n // relying on findDueReports never emitting two items for the same (site, type).\n if (result.reportRow) reports.push(result.reportRow);\n // Count sites (not individual GA/Search failures) so a fleet-wide enrichment\n // outage is one obvious line at the bottom, not 200 buried console.warns.\n if (isAnalyticsConfigured(item.site)) gaConfiguredSites++;\n if (result.softFailures.length > 0) softFailedSites++;\n if (result.searchDefaultMissed) searchDefaultMisses++;\n if (result.searchPropertyMissing) searchPropertiesMissing++;\n } catch (e) {\n lines.push(`✗ failed: ${item.site.name} ${item.reportType} — ${(e as Error).message}`);\n }\n }\n if (skipped > 0) {\n lines.push(`• ${skipped} already drafted or pending this period`);\n }\n if (softFailedSites > 0) {\n lines.push(\n `⚠ ${softFailedSites} site${softFailedSites === 1 ? \"\" : \"s\"} had GA/Search enrichment fail — drafted with blank analytics; check the logs above`,\n );\n }\n if (searchDefaultMisses > 0) {\n lines.push(\n `⚑ ${searchDefaultMisses} site${searchDefaultMisses === 1 ? \"\" : \"s\"} returned no Search Console data for their name — set an explicit \"Search query\" in Airtable to track brand presence.`,\n );\n }\n if (searchPropertiesMissing > 0) {\n lines.push(\n `⚑ ${searchPropertiesMissing} site${searchPropertiesMissing === 1 ? \"\" : \"s\"} matched NO Search Console property — verify the domain property exists and the service account has access (a \"Search query\" change cannot fix this).`,\n );\n }\n return {\n output: lines.join(\"\\n\"),\n code: lines.some((l) => l.startsWith(\"✗\")) ? 1 : 0,\n health: { softFailedSites, configuredSites: gaConfiguredSites },\n };\n}\n\nasync function runSingleSiteDraft(\n slug: string,\n opts: { previewOnly: boolean; enrich: boolean; reportType: ReportType },\n): Promise<{ output: string; code: number }> {\n const base = openBase(readAirtableConfig());\n const websites = await listWebsites(base);\n const site = websites.find((w) => siteSlug(w.name) === slug);\n if (!site) {\n throw Object.assign(new Error(`No Websites row matched slug \"${slug}\"`), { exitCode: 2 });\n }\n // Phase 5 dual-write (#539) — but only on the path that actually creates a\n // row. A preview writes nothing to Airtable, so opening a libSQL handle for\n // it would be pure cost (and `report --preview` is the one draft path that\n // deliberately does no store IO at all).\n const reportMirror = opts.previewOnly\n ? null\n : await (await import(\"../../reports/report-mirror.js\")).makeReportMirror();\n const siteMirror = opts.previewOnly\n ? null\n : await (await import(\"../../db/site-mirror.js\")).makeSiteMirror();\n const result = await draftReportForSite(opts.previewOnly ? null : base, site, opts.reportType, {\n previewOnly: opts.previewOnly,\n // Only forced on. Left undefined, draftReportForSite keeps its default\n // (enrich iff there is a base), so the real drafting path is untouched.\n ...(opts.enrich ? { enrich: true } : {}),\n ...(reportMirror ? { reportMirror } : {}),\n ...(siteMirror ? { siteMirror } : {}),\n });\n if (opts.previewOnly) {\n return { output: `Preview written to ${result.htmlPath}`, code: 0 };\n }\n return {\n output: draftLine(\n result.reportRow?.reportId,\n result.queued,\n result.supersededIds,\n \"Draft created\",\n ),\n code: 0,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmBA,IAAM,mBAAmB;AAUlB,SAAS,qBAAqB,GAAuC;AAC1E,QAAM,EAAE,iBAAiB,gBAAgB,IAAI;AAC7C,QAAM,OACJ,mBAAmB,KACnB,mBAAmB,oBACnB,kBAAkB,KAAK;AACzB,QAAM,SAAS,OACX,GAAG,eAAe,OAAO,eAAe,oPACxC;AACJ,SAAO,EAAE,MAAM,OAAO;AACxB;AAOO,SAAS,2BACd,GACA,cACmC;AACnC,QAAM,UAAU,oDAA0C,EAAE,eAAe,IAAI,EAAE,eAAe;AAChG,QAAM,EAAE,OAAO,IAAI,qBAAqB,CAAC;AACzC,QAAM,OAAO,cAAc,WAAW,MAAM,CAAC;AAAA;AAAA;AAAA,cAGjC,WAAW,YAAY,CAAC;AACpC,SAAO,EAAE,SAAS,KAAK;AACzB;;;ACjBA,SAAS,UACP,UACA,QACA,eACA,OAAO,WACC;AACR,QAAM,KAAK,YAAY;AACvB,MAAI,WAAW,OAAO;AACpB,WAAO,UAAK,IAAI,oBAAoB,EAAE;AAAA,EACxC;AACA,QAAM,MACJ,cAAc,SAAS,IACnB,gBAAgB,cAAc,MAAM,oBAAoB,cAAc,SAAS,IAAI,MAAM,EAAE,MAC3F;AACN,SAAO,UAAK,IAAI,KAAK,EAAE,GAAG,GAAG;AAC/B;AASO,SAAS,0BAA0B,KAAqC;AAC7E,MAAI,QAA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S_AUTHORITATIVE
|
|
3
|
+
} from "./chunk-RUPPWAD6.js";
|
|
4
|
+
import {
|
|
5
|
+
mirrorReportInsert,
|
|
6
|
+
mirrorReportPatch,
|
|
7
|
+
storeRenderedHtml
|
|
8
|
+
} from "./chunk-GQDDWYU2.js";
|
|
9
|
+
import "./chunk-P6AORG32.js";
|
|
10
|
+
import "./chunk-F3JWOPTG.js";
|
|
11
|
+
import "./chunk-VAD43MOR.js";
|
|
12
|
+
import "./chunk-7NYN2P6I.js";
|
|
13
|
+
import {
|
|
14
|
+
openDb,
|
|
15
|
+
readDbConfig
|
|
16
|
+
} from "./chunk-WS6NU475.js";
|
|
17
|
+
import "./chunk-MFHS7IQ2.js";
|
|
18
|
+
import "./chunk-6VAL7XJT.js";
|
|
19
|
+
|
|
20
|
+
// src/reports/report-mirror.ts
|
|
21
|
+
async function makeReportMirror(open = () => openDb(readDbConfig()), strict = TURSO_IS_AUTHORITATIVE) {
|
|
22
|
+
let db = null;
|
|
23
|
+
let why = "";
|
|
24
|
+
try {
|
|
25
|
+
db = await open();
|
|
26
|
+
} catch (e) {
|
|
27
|
+
why = e.message;
|
|
28
|
+
}
|
|
29
|
+
if (strict && !db) throw new Error(`REPORT_MIRROR unavailable: ${why}`);
|
|
30
|
+
const run = async (reportId, op, work) => {
|
|
31
|
+
if (!db) {
|
|
32
|
+
console.log(`REPORT_MIRROR report=${reportId} op=${op} mirrored=absent reason=${why}`);
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
try {
|
|
36
|
+
await work(db);
|
|
37
|
+
} catch (e) {
|
|
38
|
+
console.log(
|
|
39
|
+
`REPORT_MIRROR report=${reportId} op=${op} mirrored=0 error=${e.message}`
|
|
40
|
+
);
|
|
41
|
+
if (strict) throw e;
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
console.log(`REPORT_MIRROR report=${reportId} op=${op} mirrored=1`);
|
|
45
|
+
};
|
|
46
|
+
return {
|
|
47
|
+
created: (rec) => run(rec.id, "created", (d) => mirrorReportInsert(d, rec)),
|
|
48
|
+
body: (reportId, html) => run(reportId, "body", (d) => storeRenderedHtml(d, reportId, html)),
|
|
49
|
+
patch: (reportId, patch) => run(reportId, "patch", (d) => mirrorReportPatch(d, reportId, patch))
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
export {
|
|
53
|
+
makeReportMirror
|
|
54
|
+
};
|
|
55
|
+
//# sourceMappingURL=report-mirror-AAK3MXHY.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/reports/report-mirror.ts"],"sourcesContent":["/** #539 Phase 5: the Turso write-through for the Reports write surface.\n *\n * Before this, the only report mirrors were UPDATEs on the request path\n * (approve, override, delivery status, commentary). Everything the DRAFTING\n * path writes — the row itself, the rendered body, the queue flag, a re-run's\n * refreshed scores — reached Turso only via the hourly sync. Two of those are\n * visible to the operator today: a fresh draft's row does not exist, and its\n * preview route answers \"No rendered body stored\" for up to an hour. At the\n * freeze they stop being windows.\n *\n * Deliberately UNLIKE `makeHealthMirrorBestEffort`, this never returns null.\n * #585 is the reason: Phase 3's next-due mirror silently no-opped in production\n * for weeks because the factory returned null without creds, and a dead\n * dual-write then looked exactly like a healthy one — the only tell was an\n * ABSENT log suffix nobody was watching for. Here creds-absent is a state the\n * mirror REPORTS, so every write emits one REPORT_MIRROR line and an absent\n * line means the wiring is gone, not that conditions were quiet.\n */\nimport { openDb, readDbConfig, type Db } from \"../db/client.js\";\nimport {\n mirrorReportInsert,\n mirrorReportPatch,\n storeRenderedHtml,\n type ReportMirrorPatch,\n} from \"../db/fleet-state.js\";\nimport type { CreatedDraftMirror } from \"./airtable/reports.js\";\nimport { TURSO_IS_AUTHORITATIVE } from \"../db/freeze.js\";\n\n/** The three shapes a report write takes. Injected as ONE object rather than\n * three parameters because they share a db handle and always travel together:\n * a caller holding `created` but not `body` produces exactly the half-mirrored\n * state (row present, preview 404) this module exists to prevent. */\nexport type ReportMirror = {\n /** A row Airtable just CREATED, as Airtable echoed it back. */\n created: CreatedDraftMirror;\n /** A freshly rendered body for an existing row. */\n body: (reportId: string, html: string) => Promise<void>;\n /** Columns just written to an existing row. */\n patch: (reportId: string, patch: ReportMirrorPatch) => Promise<void>;\n};\n\n/** Build the drafting-path mirror. Never throws and never returns null:\n * Airtable is still authoritative through Phase 5, so a mirror problem must\n * not cost a draft the operator is waiting on — the hourly sync converges\n * whatever this misses. `open` is injectable for tests. */\nexport async function makeReportMirror(\n open: () => Promise<Db> = () => openDb(readDbConfig()),\n /** #612. `true` = Turso is the store that must succeed, so every failure\n * throws instead of being logged and swallowed. Defaulted from the shipped\n * constant and injected by tests, so both sides stay proven. */\n strict: boolean = TURSO_IS_AUTHORITATIVE,\n): Promise<ReportMirror> {\n let db: Db | null = null;\n let why = \"\";\n try {\n db = await open();\n } catch (e) {\n why = (e as Error).message;\n }\n // Frozen: refuse to hand back a mirror that cannot write — see makeSiteMirror\n // for why this fails at construction rather than per write.\n if (strict && !db) throw new Error(`REPORT_MIRROR unavailable: ${why}`);\n\n const run = async (reportId: string, op: string, work: (db: Db) => Promise<void>) => {\n if (!db) {\n console.log(`REPORT_MIRROR report=${reportId} op=${op} mirrored=absent reason=${why}`);\n return;\n }\n try {\n await work(db);\n } catch (e) {\n console.log(\n `REPORT_MIRROR report=${reportId} op=${op} mirrored=0 error=${(e as Error).message}`,\n );\n if (strict) throw e;\n return;\n }\n console.log(`REPORT_MIRROR report=${reportId} op=${op} mirrored=1`);\n };\n\n return {\n created: (rec) => run(rec.id, \"created\", (d) => mirrorReportInsert(d, rec)),\n body: (reportId, html) => run(reportId, \"body\", (d) => storeRenderedHtml(d, reportId, html)),\n patch: (reportId, patch) =>\n run(reportId, \"patch\", (d) => mirrorReportPatch(d, reportId, patch)),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA6CA,eAAsB,iBACpB,OAA0B,MAAM,OAAO,aAAa,CAAC,GAIrD,SAAkB,wBACK;AACvB,MAAI,KAAgB;AACpB,MAAI,MAAM;AACV,MAAI;AACF,SAAK,MAAM,KAAK;AAAA,EAClB,SAAS,GAAG;AACV,UAAO,EAAY;AAAA,EACrB;AAGA,MAAI,UAAU,CAAC,GAAI,OAAM,IAAI,MAAM,8BAA8B,GAAG,EAAE;AAEtE,QAAM,MAAM,OAAO,UAAkB,IAAY,SAAoC;AACnF,QAAI,CAAC,IAAI;AACP,cAAQ,IAAI,wBAAwB,QAAQ,OAAO,EAAE,2BAA2B,GAAG,EAAE;AACrF;AAAA,IACF;AACA,QAAI;AACF,YAAM,KAAK,EAAE;AAAA,IACf,SAAS,GAAG;AACV,cAAQ;AAAA,QACN,wBAAwB,QAAQ,OAAO,EAAE,qBAAsB,EAAY,OAAO;AAAA,MACpF;AACA,UAAI,OAAQ,OAAM;AAClB;AAAA,IACF;AACA,YAAQ,IAAI,wBAAwB,QAAQ,OAAO,EAAE,aAAa;AAAA,EACpE;AAEA,SAAO;AAAA,IACL,SAAS,CAAC,QAAQ,IAAI,IAAI,IAAI,WAAW,CAAC,MAAM,mBAAmB,GAAG,GAAG,CAAC;AAAA,IAC1E,MAAM,CAAC,UAAU,SAAS,IAAI,UAAU,QAAQ,CAAC,MAAM,kBAAkB,GAAG,UAAU,IAAI,CAAC;AAAA,IAC3F,OAAO,CAAC,UAAU,UAChB,IAAI,UAAU,SAAS,CAAC,MAAM,kBAAkB,GAAG,UAAU,KAAK,CAAC;AAAA,EACvE;AACF;","names":[]}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
// src/reports/send/rerender.ts
|
|
2
|
+
async function rerenderReport(deps, reportId) {
|
|
3
|
+
const report = await deps.getReport(reportId);
|
|
4
|
+
if (!report) return { status: "not-found", reportId };
|
|
5
|
+
if (report.sentAt !== null) return { status: "already-sent", reportId };
|
|
6
|
+
const site = await deps.getSite(report.siteId);
|
|
7
|
+
if (!site) return { status: "not-found", reportId };
|
|
8
|
+
const stored = await deps.loadHeaderPlate(site.id);
|
|
9
|
+
let plate;
|
|
10
|
+
let headerSource;
|
|
11
|
+
if (stored) {
|
|
12
|
+
plate = stored;
|
|
13
|
+
headerSource = "turso";
|
|
14
|
+
} else if (site.headerImage) {
|
|
15
|
+
plate = await deps.fetchAirtableHeader(site.headerImage.url);
|
|
16
|
+
headerSource = "airtable";
|
|
17
|
+
} else {
|
|
18
|
+
return { status: "no-header", reportId };
|
|
19
|
+
}
|
|
20
|
+
const { html } = await deps.render(site, report, plate);
|
|
21
|
+
await deps.store(reportId, html);
|
|
22
|
+
return { status: "rendered", reportId, bytes: html.length, headerSource };
|
|
23
|
+
}
|
|
24
|
+
function formatRerenderResult(r) {
|
|
25
|
+
const suffix = r.status === "rendered" ? ` bytes=${r.bytes} header=${r.headerSource}` : "";
|
|
26
|
+
return `REPORT_RERENDER report=${r.reportId} status=${r.status}${suffix}`;
|
|
27
|
+
}
|
|
28
|
+
export {
|
|
29
|
+
formatRerenderResult,
|
|
30
|
+
rerenderReport
|
|
31
|
+
};
|
|
32
|
+
//# sourceMappingURL=rerender-3FM6DNRH.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/reports/send/rerender.ts"],"sourcesContent":["import type { WebsiteRow } from \"../airtable/websites.js\";\nimport type { ReportRow } from \"../airtable/reports.js\";\n\n/**\n * Refresh a report's stored HTML body on demand (#539 Phase 4 report review).\n *\n * The console's preview serves `reports.rendered_html`, which is written once at\n * draft time — so commentary edited afterwards does not appear. This regenerates\n * it through `renderReportFromRow`, the same path `sendOne` uses, so the preview\n * is what the client will actually receive rather than an approximation of it.\n *\n * It runs as a batch job (Actions), not in a Netlify function, and that is a\n * deliberate constraint rather than an accident: rendering needs sharp, a native\n * module no function currently bundles, and the alternative — approximating the\n * header geometry to avoid sharp — trades away exactly the fidelity a preview\n * exists to provide.\n *\n * IO is injected so the decision logic is testable without sharp, Airtable or a\n * database; the CLI binds the real implementations.\n */\nexport type RerenderDeps = {\n getReport: (reportId: string) => Promise<ReportRow | null>;\n getSite: (siteId: string) => Promise<WebsiteRow | null>;\n /** The clean header plate from Turso (design D5), or null when unstored. */\n loadHeaderPlate: (siteId: string) => Promise<Uint8Array | null>;\n /** Fallback: the site's Airtable header attachment. */\n fetchAirtableHeader: (url: string) => Promise<Uint8Array>;\n render: (\n site: WebsiteRow,\n report: ReportRow,\n headerPlate: Uint8Array,\n ) => Promise<{ html: string }>;\n store: (reportId: string, html: string) => Promise<void>;\n};\n\nexport type RerenderResult =\n | { status: \"rendered\"; reportId: string; bytes: number; headerSource: \"turso\" | \"airtable\" }\n /** Already sent: its stored body is the record of what the client received. */\n | { status: \"already-sent\"; reportId: string }\n | { status: \"no-header\"; reportId: string }\n | { status: \"not-found\"; reportId: string };\n\nexport async function rerenderReport(\n deps: RerenderDeps,\n reportId: string,\n): Promise<RerenderResult> {\n const report = await deps.getReport(reportId);\n if (!report) return { status: \"not-found\", reportId };\n\n // Refuse a sent report BEFORE doing any work. Its stored body is the record of\n // what the client actually received; regenerating it would overwrite that with\n // something nobody was sent — and today's row would not even reproduce it,\n // since commentary and scores have moved on since.\n if (report.sentAt !== null) return { status: \"already-sent\", reportId };\n\n const site = await deps.getSite(report.siteId);\n if (!site) return { status: \"not-found\", reportId };\n\n // Turso first: the bytes are already local, and the Airtable attachment URL is\n // signed and expiring, so fetching it when we hold the same image is pure\n // latency plus a dependency on a URL that may already be dead.\n const stored = await deps.loadHeaderPlate(site.id);\n let plate: Uint8Array;\n let headerSource: \"turso\" | \"airtable\";\n if (stored) {\n plate = stored;\n headerSource = \"turso\";\n } else if (site.headerImage) {\n plate = await deps.fetchAirtableHeader(site.headerImage.url);\n headerSource = \"airtable\";\n } else {\n // Named, not rendered around: a report with no header is already blocked at\n // approve, and a preview that quietly omitted it would disagree with both\n // the email and that block.\n return { status: \"no-header\", reportId };\n }\n\n const { html } = await deps.render(site, report, plate);\n await deps.store(reportId, html);\n return { status: \"rendered\", reportId, bytes: html.length, headerSource };\n}\n\n/** One line per run, machine-greppable, emitted for every outcome — an absent\n * line means the job never ran, never that it ran and did nothing. */\nexport function formatRerenderResult(r: RerenderResult): string {\n const suffix = r.status === \"rendered\" ? ` bytes=${r.bytes} header=${r.headerSource}` : \"\";\n return `REPORT_RERENDER report=${r.reportId} status=${r.status}${suffix}`;\n}\n"],"mappings":";AA0CA,eAAsB,eACpB,MACA,UACyB;AACzB,QAAM,SAAS,MAAM,KAAK,UAAU,QAAQ;AAC5C,MAAI,CAAC,OAAQ,QAAO,EAAE,QAAQ,aAAa,SAAS;AAMpD,MAAI,OAAO,WAAW,KAAM,QAAO,EAAE,QAAQ,gBAAgB,SAAS;AAEtE,QAAM,OAAO,MAAM,KAAK,QAAQ,OAAO,MAAM;AAC7C,MAAI,CAAC,KAAM,QAAO,EAAE,QAAQ,aAAa,SAAS;AAKlD,QAAM,SAAS,MAAM,KAAK,gBAAgB,KAAK,EAAE;AACjD,MAAI;AACJ,MAAI;AACJ,MAAI,QAAQ;AACV,YAAQ;AACR,mBAAe;AAAA,EACjB,WAAW,KAAK,aAAa;AAC3B,YAAQ,MAAM,KAAK,oBAAoB,KAAK,YAAY,GAAG;AAC3D,mBAAe;AAAA,EACjB,OAAO;AAIL,WAAO,EAAE,QAAQ,aAAa,SAAS;AAAA,EACzC;AAEA,QAAM,EAAE,KAAK,IAAI,MAAM,KAAK,OAAO,MAAM,QAAQ,KAAK;AACtD,QAAM,KAAK,MAAM,UAAU,IAAI;AAC/B,SAAO,EAAE,QAAQ,YAAY,UAAU,OAAO,KAAK,QAAQ,aAAa;AAC1E;AAIO,SAAS,qBAAqB,GAA2B;AAC9D,QAAM,SAAS,EAAE,WAAW,aAAa,UAAU,EAAE,KAAK,WAAW,EAAE,YAAY,KAAK;AACxF,SAAO,0BAA0B,EAAE,QAAQ,WAAW,EAAE,MAAM,GAAG,MAAM;AACzE;","names":[]}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
// src/db/schema.ts
|
|
2
|
+
var DATABASE_TABLES = [
|
|
3
|
+
"submissions",
|
|
4
|
+
"spam_screenouts",
|
|
5
|
+
"fleet_events",
|
|
6
|
+
"_migrations",
|
|
7
|
+
"submission_deadletter",
|
|
8
|
+
"sites",
|
|
9
|
+
"site_health",
|
|
10
|
+
"site_schedule",
|
|
11
|
+
"reports",
|
|
12
|
+
"prospect_audits",
|
|
13
|
+
"digest_state"
|
|
14
|
+
];
|
|
15
|
+
export {
|
|
16
|
+
DATABASE_TABLES
|
|
17
|
+
};
|
|
18
|
+
//# sourceMappingURL=schema-75PJECAE.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/db/schema.ts"],"sourcesContent":["// The hand-written shape Kysely types every query from. SQLite stores TEXT/INTEGER\n// only, so these are the column *shapes* — the value domains (form_type, status,\n// notify_status) are still narrowed at read time by the validators in\n// src/reports/submission-row.ts. Keep this in lockstep with src/db/migrations.ts;\n// drift is caught by the in-memory tests in tests/db/, not by codegen.\n\nexport interface SubmissionsTable {\n id: string;\n submission_id: number | null;\n site_id: string;\n form_type: string;\n name: string;\n email: string;\n phone: string | null;\n message: string | null;\n extra_fields: string | null;\n source_url: string | null;\n utm: string | null;\n submitted_at: string | null;\n status: string;\n notify_status: string;\n resend_message_id: string | null;\n spam_score: number | null;\n spam_reason: string | null;\n fanout_status: string | null;\n}\n\nexport interface SpamScreenoutsTable {\n site_id: string;\n date: string;\n honeypot: number;\n too_fast: number;\n marked_spam: number;\n}\n\nexport interface FleetEventsTable {\n id: string;\n ts: string;\n type: string;\n site_id: string | null;\n site_name: string | null;\n summary: string;\n data: string | null;\n created_at: string;\n}\n\nexport interface MigrationsTable {\n id: string;\n applied_at: string;\n}\n\n/** A lead whose site lookup threw mid-ingest (migration 0006). `payload` and\n * `turnstile` are JSON — the raw wire body and the verification computed at\n * receipt — exactly what `db replay-deadletters` feeds back through\n * `ingestSubmission` once the lookup recovers. */\nexport interface SubmissionDeadletterTable {\n id: string;\n site_slug: string;\n payload: string;\n turnstile: string;\n error: string;\n received_at: string;\n replayed_at: string | null;\n replay_outcome: string | null;\n replay_submission_id: string | null;\n}\n\n/** Operator-owned fleet config (migration 0007). PK = Airtable rec id (D1).\n * `legacy` holds the 33 populated-but-code-unreferenced Airtable columns as a\n * JSON object keyed by original column name; the plaintext DNS/cms credential\n * cells never migrate (operator ruling 2026-08-23). */\nexport interface SitesTable {\n id: string;\n slug: string;\n name: string;\n url: string | null;\n status: string | null;\n point_of_contact: string | null;\n maintenance_freq: string | null;\n testing_freq: string | null;\n maintenance_day: string | null;\n testing_day: string | null;\n ga4_property_id: string | null;\n search_query: string | null;\n search_console_property: string | null;\n git_repo: string | null;\n netlify_id: string | null;\n report_recipients_to: string | null;\n report_recipients_cc: string | null;\n copy_intro: string | null;\n copy_contact: string | null;\n copy_footer: string | null;\n newsletter_webhook: string | null;\n mailchimp_api_key: string | null;\n mailchimp_audience_id: string | null;\n notify_routing: string | null;\n require_turnstile: number;\n accepted_watch_conditions: string | null;\n prismic_ack_until: string | null;\n launched_at: string | null;\n header_image: Uint8Array | null;\n header_image_filename: string | null;\n header_image_type: string | null;\n header_image_generated_at: string | null;\n legacy: string | null;\n}\n\n/** Nightly-cron-owned health/telemetry (migration 0007) — one row per site,\n * written as one batched upsert per sweep family. `analytics_soft_fail_at` is\n * the \"Analytics soft-fail at\" column code always wrote best-effort but no\n * operator ever created in Airtable. */\nexport interface SiteHealthTable {\n site_id: string;\n p_score: number | null;\n r_score: number | null;\n bp_score: number | null;\n seo_score: number | null;\n lighthouse_at: string | null;\n a11y_violations: number | null;\n deps_drifted: number | null;\n deps_major_behind: number | null;\n deps_outdated: number | null;\n deps_major_outdated: number | null;\n vulns_critical: number | null;\n vulns_high: number | null;\n vulns_moderate: number | null;\n vulns_low: number | null;\n security_audit_at: string | null;\n security_advisories: string | null;\n auto_fix_attempts: number | null;\n analytics_soft_fail_at: string | null;\n cert_days_remaining: number | null;\n domain_checked_at: string | null;\n deploy_status: string | null;\n last_deploy_at: string | null;\n deploy_log_url: string | null;\n deploy_checked_at: string | null;\n function_health: string | null;\n cms_reachable: string | null;\n turnstile_widget: string | null;\n function_health_checked_at: string | null;\n crossbrowser_ok: number | null;\n mobile_ok: number | null;\n links_ok: number | null;\n broken_links: number | null;\n browser_checked_at: string | null;\n uptime_reachable: string | null;\n titles_meta_ok: string | null;\n smoke_ok: string | null;\n last_smoke_at: string | null;\n form_e2e_ok: string | null;\n form_e2e_checked_at: string | null;\n renovate_failing_cis: number | null;\n default_branch_ci: string | null;\n last_commit_at: string | null;\n github_signals_at: string | null;\n prismic_models: string | null;\n prismic_models_checked_at: string | null;\n prismic_models_drift: string | null;\n}\n\n/** Code-derived schedule (migration 0007) — written by updateNextDueDates. */\nexport interface SiteScheduleTable {\n site_id: string;\n next_maintenance_at: string | null;\n next_testing_at: string | null;\n computed_at: string | null;\n}\n\n/** Report rows (migration 0007). PK = Airtable rec id. `checklist` is JSON\n * keyed by the STABLE checklist key (src/reports/checklist.ts), not the\n * Airtable column name; `rendered_html` is the downloaded attachment body. */\nexport interface ReportsTable {\n id: string;\n site_id: string | null;\n report_id: string | null;\n report_type: string | null;\n period: string | null;\n period_start: string | null;\n period_end: string | null;\n completed_on: string | null;\n lighthouse_performance: number | null;\n lighthouse_accessibility: number | null;\n lighthouse_best_practices: number | null;\n lighthouse_seo: number | null;\n ga_users_current: number | null;\n ga_users_previous: number | null;\n search_found_page1: number | null;\n search_position: number | null;\n last_tested_date: string | null;\n commentary: string | null;\n subject_override: string | null;\n draft_ready: number;\n approved_to_send: number;\n approved_at: string | null;\n approved_by: string | null;\n send_override: number;\n override_reason: string | null;\n override_by: string | null;\n override_at: string | null;\n sent_at: string | null;\n delivery_status: string | null;\n resend_message_id: string | null;\n checklist: string | null;\n checklist_auto_evidence: string | null;\n rendered_html: string | null;\n}\n\n/** One prospect-audit run (migration 0009). `token` is the 128-bit unguessable\n * public handle for GET /r/{token}; `result_json` holds the full\n * ProspectAuditResult (src/prospect/types.ts). */\nexport interface ProspectAuditsTable {\n id: string;\n token: string;\n url: string;\n business: string | null;\n created_at: string;\n status: string;\n result_json: string;\n}\n\n/** The digest's prior-run snapshot (migration 0011). One row, `id` = the\n * constant singleton key; `snapshot` is the whole DigestSnapshot as JSON. */\nexport interface DigestStateTable {\n id: string;\n snapshot: string;\n updated_at: string | null;\n}\n\n/** Every table the app owns, as a RUNTIME value (#612 review).\n *\n * The `Database` interface below is types-only, so nothing could assert that a\n * backup actually covered it — `tables=N` was printed by the verifier and never\n * checked, meaning a table a migration failed to create would ride green\n * forever. The compile-time check under this list makes forgetting an entry a\n * build error naming the missing table. */\nexport const DATABASE_TABLES = [\n \"submissions\",\n \"spam_screenouts\",\n \"fleet_events\",\n \"_migrations\",\n \"submission_deadletter\",\n \"sites\",\n \"site_health\",\n \"site_schedule\",\n \"reports\",\n \"prospect_audits\",\n \"digest_state\",\n] as const;\n\nexport type DatabaseTable = (typeof DATABASE_TABLES)[number];\n\nexport interface Database {\n submissions: SubmissionsTable;\n spam_screenouts: SpamScreenoutsTable;\n fleet_events: FleetEventsTable;\n _migrations: MigrationsTable;\n submission_deadletter: SubmissionDeadletterTable;\n sites: SitesTable;\n site_health: SiteHealthTable;\n site_schedule: SiteScheduleTable;\n reports: ReportsTable;\n prospect_audits: ProspectAuditsTable;\n digest_state: DigestStateTable;\n}\n\n/** Compile-time exhaustiveness: if a table is added to `Database` and not to\n * `DATABASE_TABLES`, this errors and NAMES it. */\ntype MissingFromDatabaseTables = Exclude<keyof Database, DatabaseTable>;\nconst _everyTableIsListed: MissingFromDatabaseTables extends never\n ? true\n : MissingFromDatabaseTables = true;\nvoid _everyTableIsListed;\n"],"mappings":";AA4OO,IAAM,kBAAkB;AAAA,EAC7B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;","names":[]}
|
|
@@ -12,12 +12,12 @@ import {
|
|
|
12
12
|
} from "./chunk-TVL5MVUF.js";
|
|
13
13
|
import {
|
|
14
14
|
resolveSites
|
|
15
|
-
} from "./chunk-
|
|
15
|
+
} from "./chunk-Q47DU255.js";
|
|
16
16
|
import "./chunk-73UFRZKY.js";
|
|
17
17
|
import "./chunk-GASBX52O.js";
|
|
18
18
|
import "./chunk-XHHMM5HX.js";
|
|
19
|
-
import "./chunk-
|
|
20
|
-
import "./chunk-
|
|
19
|
+
import "./chunk-Z3JXLULD.js";
|
|
20
|
+
import "./chunk-RARREDQE.js";
|
|
21
21
|
import "./chunk-XTK5VIQB.js";
|
|
22
22
|
import "./chunk-LBYOLBW7.js";
|
|
23
23
|
import "./chunk-XXTZBPUY.js";
|
|
@@ -62,4 +62,4 @@ async function runSelfUpdatingCommand(site, opts) {
|
|
|
62
62
|
export {
|
|
63
63
|
runSelfUpdatingCommand
|
|
64
64
|
};
|
|
65
|
-
//# sourceMappingURL=self-updating-
|
|
65
|
+
//# sourceMappingURL=self-updating-NTCCWJYZ.js.map
|
|
@@ -1,47 +1,49 @@
|
|
|
1
1
|
import {
|
|
2
2
|
buildReportDataForSite,
|
|
3
3
|
scoresFromRow
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-ULHPALI5.js";
|
|
5
5
|
import {
|
|
6
6
|
operatorEmail
|
|
7
7
|
} from "./chunk-5ML7FMBD.js";
|
|
8
|
-
import "./chunk-
|
|
8
|
+
import "./chunk-J3WEZGIN.js";
|
|
9
9
|
import {
|
|
10
10
|
ELIGIBLE_STATUSES
|
|
11
11
|
} from "./chunk-PZR4EBPY.js";
|
|
12
|
-
import "./chunk-
|
|
12
|
+
import "./chunk-YFAXOD7Z.js";
|
|
13
13
|
import {
|
|
14
14
|
isProbablyEmail,
|
|
15
|
-
parseAddresses
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
import "./chunk-GECESMVS.js";
|
|
20
|
-
import {
|
|
21
|
-
applyReportTypeHeadline
|
|
22
|
-
} from "./chunk-5UINJNAJ.js";
|
|
23
|
-
import "./chunk-CQR4LIM7.js";
|
|
15
|
+
parseAddresses
|
|
16
|
+
} from "./chunk-DGZWFI2G.js";
|
|
17
|
+
import "./chunk-F3JWOPTG.js";
|
|
18
|
+
import "./chunk-VAD43MOR.js";
|
|
24
19
|
import {
|
|
25
20
|
fetchAttachmentBytes
|
|
26
|
-
} from "./chunk-
|
|
27
|
-
import "./chunk-DJZWYIPP.js";
|
|
28
|
-
import "./chunk-ACBRLLFT.js";
|
|
29
|
-
import "./chunk-VAD43MOR.js";
|
|
21
|
+
} from "./chunk-IY6256GK.js";
|
|
30
22
|
import {
|
|
31
23
|
openBase,
|
|
32
24
|
readAirtableConfig
|
|
33
25
|
} from "./chunk-HN6I2XWI.js";
|
|
34
26
|
import {
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
import "./chunk-
|
|
39
|
-
import
|
|
40
|
-
|
|
27
|
+
prepareHeaderImage,
|
|
28
|
+
renderReportEmail
|
|
29
|
+
} from "./chunk-XP5WM2LV.js";
|
|
30
|
+
import "./chunk-GECESMVS.js";
|
|
31
|
+
import {
|
|
32
|
+
applyReportTypeHeadline
|
|
33
|
+
} from "./chunk-5UINJNAJ.js";
|
|
34
|
+
import "./chunk-KJGKZLCT.js";
|
|
35
|
+
import "./chunk-BGTYPVLT.js";
|
|
41
36
|
import {
|
|
42
37
|
listWebsites,
|
|
43
38
|
siteSlug
|
|
44
|
-
} from "./chunk-
|
|
39
|
+
} from "./chunk-7NYN2P6I.js";
|
|
40
|
+
import {
|
|
41
|
+
defaultResendClient
|
|
42
|
+
} from "./chunk-WEKL2HYJ.js";
|
|
43
|
+
import "./chunk-W45FZEGE.js";
|
|
44
|
+
import "./chunk-RARREDQE.js";
|
|
45
|
+
import "./chunk-WS6NU475.js";
|
|
46
|
+
import "./chunk-MFHS7IQ2.js";
|
|
45
47
|
import "./chunk-6VAL7XJT.js";
|
|
46
48
|
|
|
47
49
|
// src/recipes/selftest-email.ts
|
|
@@ -170,4 +172,4 @@ async function runSelftestCommand(kind, site, opts) {
|
|
|
170
172
|
export {
|
|
171
173
|
runSelftestCommand
|
|
172
174
|
};
|
|
173
|
-
//# sourceMappingURL=selftest-
|
|
175
|
+
//# sourceMappingURL=selftest-NZTR4SM2.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/recipes/selftest-email.ts","../src/cli/commands/selftest.ts"],"sourcesContent":["import { mkdir, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport { openBase, readAirtableConfig } from \"../reports/airtable/client.js\";\nimport type { AirtableBase } from \"../reports/airtable/client.js\";\nimport { listWebsites, siteSlug } from \"../reports/airtable/websites.js\";\nimport { ELIGIBLE_STATUSES } from \"../reports/due.js\";\nimport type { WebsiteRow } from \"../reports/airtable/websites.js\";\nimport { fetchAttachmentBytes } from \"../reports/airtable/attachments.js\";\nimport { prepareHeaderImage } from \"../reports/maintenance-email/header-image.js\";\nimport { applyReportTypeHeadline } from \"../reports/header-image/index.js\";\nimport { buildReportDataForSite, scoresFromRow } from \"../reports/report-data.js\";\nimport { renderReportEmail } from \"../reports/send/render-email.js\";\nimport { defaultResendClient, type ResendClient } from \"../reports/send/resend.js\";\nimport { parseAddresses, isProbablyEmail } from \"../reports/send/orchestrate.js\";\nimport { operatorEmail } from \"../util/operator.js\";\nimport type { ReportType } from \"../reports/types.js\";\n\nconst FROM_ADDRESS = \"Reddoor Reports <reports@reddoorla.com>\";\nconst REPLY_TO = \"info@reddoorla.com\";\n\nexport type SelftestEmailDeps = {\n /** Airtable handle (read-only here). Defaults to the live base from credentials. */\n base?: AirtableBase;\n /** Resend client. Defaults to the real client. */\n resend?: ResendClient;\n /** Single-site slug. Mutually exclusive with `all`. */\n site?: string;\n /** All `maintenance` sites (one email each). Mutually exclusive with `site`. */\n all?: boolean;\n /** Report type to preview. Default \"Announcement\". */\n type?: ReportType;\n /** Raw `--to` (comma- or newline-separated). Default: the operator inbox. */\n to?: string;\n /** Render only; write reports/<slug>/selftest-<type>.html, never send. */\n dryRun?: boolean;\n /** Single timestamp driving the window + completedOn. */\n now?: Date;\n};\n\nexport type SelftestEmailSiteResult =\n | { site: string; status: \"sent\" | \"dry-run\"; subject: string; recipients: string[] }\n | { site: string; status: \"skipped\"; reason: string }\n | { site: string; status: \"error\"; message: string };\n\nexport type SelftestEmailResult = { results: SelftestEmailSiteResult[] };\n\n/** Resolve the recipient list: explicit `--to` (validated) else the operator default. */\nfunction resolveRecipients(to: string | undefined): string[] {\n const operator = operatorEmail();\n const parsed = to ? parseAddresses(to) : null;\n const list = parsed ?? [operator];\n for (const addr of list) {\n if (!isProbablyEmail(addr)) {\n throw Object.assign(new Error(`--to has a malformed address: ${addr}`), { exitCode: 2 });\n }\n }\n return list;\n}\n\n/**\n * Send (or dry-render) a single report email per target site to the operator/`--to`, with NO\n * Airtable side effects (no draft, queue, or stamp). Mirrors the production render+send via the\n * shared `renderReportEmail` seam, so the preview matches a real send. One bad site never aborts\n * `--all` (per-site try/catch). Sites missing stored scores or a header image are skipped.\n */\nexport async function selftestEmail(deps: SelftestEmailDeps): Promise<SelftestEmailResult> {\n const base = deps.base ?? openBase(readAirtableConfig());\n const resend = deps.resend ?? defaultResendClient();\n const type: ReportType = deps.type ?? \"Announcement\";\n const now = deps.now ?? new Date();\n const recipients = resolveRecipients(deps.to);\n\n const websites = await listWebsites(base);\n let targets: WebsiteRow[];\n if (deps.all) {\n // The report-eligible set (maintained + hosted-only), not a hard-coded \"maintained\" —\n // the latter silently excluded hosting sites and implied a type↔status coupling that\n // doesn't exist (the requested --type drives the rendered template; single-site mode\n // applies no status filter at all).\n targets = websites.filter((w) => w.status !== null && ELIGIBLE_STATUSES.has(w.status));\n } else if (deps.site) {\n const wanted = siteSlug(deps.site);\n targets = websites.filter((w) => siteSlug(w.name) === wanted);\n } else {\n throw Object.assign(new Error(\"Provide a site slug or --all\"), { exitCode: 2 });\n }\n\n const results: SelftestEmailSiteResult[] = [];\n for (const w of targets) {\n try {\n const scores = scoresFromRow(w);\n if (!scores) {\n results.push({ site: w.name, status: \"skipped\", reason: \"missing Lighthouse scores\" });\n continue;\n }\n if (!w.headerImage) {\n results.push({ site: w.name, status: \"skipped\", reason: \"no Header image\" });\n continue;\n }\n const original = await fetchAttachmentBytes(w.headerImage.url);\n // Mirror orchestrate.ts exactly: the stored header is the CLEAN plate, so the\n // report type's headline has to be stamped on before downscaling. Omitting this\n // step made every selftest preview ship a header with an EMPTY headline band —\n // the one thing a preview exists to catch, silently wrong in the preview itself.\n const withHeadline = await applyReportTypeHeadline(original.bytes, type);\n const header = await prepareHeaderImage(withHeadline);\n const slug = siteSlug(w.name);\n const reportData = await buildReportDataForSite(w, type, now, { scores, header });\n const { html, attachments, subject } = await renderReportEmail(reportData, {\n header,\n cidName: `${slug}-header`,\n });\n\n if (deps.dryRun) {\n const path = `reports/${slug}/selftest-${type.toLowerCase()}.html`;\n await mkdir(dirname(path), { recursive: true });\n await writeFile(path, html, \"utf-8\");\n results.push({ site: w.name, status: \"dry-run\", subject, recipients });\n continue;\n }\n\n await resend.send({\n from: FROM_ADDRESS,\n to: recipients,\n replyTo: REPLY_TO,\n subject,\n html,\n attachments,\n });\n results.push({ site: w.name, status: \"sent\", subject, recipients });\n } catch (err) {\n results.push({\n site: w.name,\n status: \"error\",\n message: err instanceof Error ? err.message : String(err),\n });\n }\n }\n\n return { results };\n}\n","import { selftestEmail, type SelftestEmailSiteResult } from \"../../recipes/selftest-email.js\";\nimport type { ReportType } from \"../../reports/types.js\";\n\nexport type SelftestCommandOptions = {\n type?: string;\n to?: string;\n all?: boolean;\n dryRun?: boolean;\n cwd?: string;\n};\n\nconst TYPES: Record<string, ReportType> = {\n announcement: \"Announcement\",\n maintenance: \"Maintenance\",\n testing: \"Testing\",\n launch: \"Launch\",\n};\n\nfunction formatResult(r: SelftestEmailSiteResult): string {\n if (r.status === \"skipped\") return `[${r.site}] skipped — ${r.reason}`;\n if (r.status === \"error\") return `[${r.site}] error: ${r.message}`;\n return `[${r.site}] ${r.status} — \"${r.subject}\" → ${r.recipients.join(\", \")}`;\n}\n\n/**\n * `selftest <kind> [site]` — operator self-tests. The only kind today is `email`: preview a\n * report email for one site (or `--all` maintenance sites) to the operator/`--to`, with no\n * Airtable side effects. Validates kind/type and the site-xor-all rule before doing any work.\n */\nexport async function runSelftestCommand(\n kind: string,\n site: string | undefined,\n opts: SelftestCommandOptions,\n): Promise<{ output: string; code: number }> {\n if (kind !== \"email\") {\n return { output: `Unknown selftest kind '${kind}'. Supported: email`, code: 2 };\n }\n if (Boolean(site) === Boolean(opts.all)) {\n return { output: \"Provide exactly one of <site> or --all.\", code: 2 };\n }\n const typeKey = (opts.type ?? \"announcement\").toLowerCase();\n const type = TYPES[typeKey];\n if (!type) {\n return {\n output: `Unknown --type '${opts.type}'. Supported: ${Object.keys(TYPES).join(\", \")}`,\n code: 2,\n };\n }\n\n try {\n const { results } = await selftestEmail({\n ...(site ? { site } : {}),\n ...(opts.all ? { all: true } : {}),\n type,\n ...(opts.to ? { to: opts.to } : {}),\n ...(opts.dryRun ? { dryRun: true } : {}),\n });\n const output =\n results.length === 0 ? \"No matching sites.\" : results.map(formatResult).join(\"\\n\");\n const code = results.some((r) => r.status === \"error\") ? 1 : 0;\n return { output, code };\n } catch (err) {\n const e = err as { message?: string; exitCode?: number };\n return { output: e.message ?? String(err), code: e.exitCode ?? 1 };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,OAAO,iBAAiB;AACjC,SAAS,eAAe;AAgBxB,IAAM,eAAe;AACrB,IAAM,WAAW;AA6BjB,SAAS,kBAAkB,IAAkC;AAC3D,QAAM,WAAW,cAAc;AAC/B,QAAM,SAAS,KAAK,eAAe,EAAE,IAAI;AACzC,QAAM,OAAO,UAAU,CAAC,QAAQ;AAChC,aAAW,QAAQ,MAAM;AACvB,QAAI,CAAC,gBAAgB,IAAI,GAAG;AAC1B,YAAM,OAAO,OAAO,IAAI,MAAM,iCAAiC,IAAI,E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mkdir, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport { openBase, readAirtableConfig } from \"../reports/airtable/client.js\";\nimport type { AirtableBase } from \"../reports/airtable/client.js\";\nimport { listWebsites, siteSlug } from \"../reports/airtable/websites.js\";\nimport { ELIGIBLE_STATUSES } from \"../reports/due.js\";\nimport type { WebsiteRow } from \"../reports/airtable/websites.js\";\nimport { fetchAttachmentBytes } from \"../reports/airtable/attachments.js\";\nimport { prepareHeaderImage } from \"../reports/maintenance-email/header-image.js\";\nimport { applyReportTypeHeadline } from \"../reports/header-image/index.js\";\nimport { buildReportDataForSite, scoresFromRow } from \"../reports/report-data.js\";\nimport { renderReportEmail } from \"../reports/send/render-email.js\";\nimport { defaultResendClient, type ResendClient } from \"../reports/send/resend.js\";\nimport { parseAddresses, isProbablyEmail } from \"../reports/send/orchestrate.js\";\nimport { operatorEmail } from \"../util/operator.js\";\nimport type { ReportType } from \"../reports/types.js\";\n\nconst FROM_ADDRESS = \"Reddoor Reports <reports@reddoorla.com>\";\nconst REPLY_TO = \"info@reddoorla.com\";\n\nexport type SelftestEmailDeps = {\n /** Airtable handle (read-only here). Defaults to the live base from credentials. */\n base?: AirtableBase;\n /** Resend client. Defaults to the real client. */\n resend?: ResendClient;\n /** Single-site slug. Mutually exclusive with `all`. */\n site?: string;\n /** All `maintenance` sites (one email each). Mutually exclusive with `site`. */\n all?: boolean;\n /** Report type to preview. Default \"Announcement\". */\n type?: ReportType;\n /** Raw `--to` (comma- or newline-separated). Default: the operator inbox. */\n to?: string;\n /** Render only; write reports/<slug>/selftest-<type>.html, never send. */\n dryRun?: boolean;\n /** Single timestamp driving the window + completedOn. */\n now?: Date;\n};\n\nexport type SelftestEmailSiteResult =\n | { site: string; status: \"sent\" | \"dry-run\"; subject: string; recipients: string[] }\n | { site: string; status: \"skipped\"; reason: string }\n | { site: string; status: \"error\"; message: string };\n\nexport type SelftestEmailResult = { results: SelftestEmailSiteResult[] };\n\n/** Resolve the recipient list: explicit `--to` (validated) else the operator default. */\nfunction resolveRecipients(to: string | undefined): string[] {\n const operator = operatorEmail();\n const parsed = to ? parseAddresses(to) : null;\n const list = parsed ?? [operator];\n for (const addr of list) {\n if (!isProbablyEmail(addr)) {\n throw Object.assign(new Error(`--to has a malformed address: ${addr}`), { exitCode: 2 });\n }\n }\n return list;\n}\n\n/**\n * Send (or dry-render) a single report email per target site to the operator/`--to`, with NO\n * Airtable side effects (no draft, queue, or stamp). Mirrors the production render+send via the\n * shared `renderReportEmail` seam, so the preview matches a real send. One bad site never aborts\n * `--all` (per-site try/catch). Sites missing stored scores or a header image are skipped.\n */\nexport async function selftestEmail(deps: SelftestEmailDeps): Promise<SelftestEmailResult> {\n const base = deps.base ?? openBase(readAirtableConfig());\n const resend = deps.resend ?? defaultResendClient();\n const type: ReportType = deps.type ?? \"Announcement\";\n const now = deps.now ?? new Date();\n const recipients = resolveRecipients(deps.to);\n\n const websites = await listWebsites(base);\n let targets: WebsiteRow[];\n if (deps.all) {\n // The report-eligible set (maintained + hosted-only), not a hard-coded \"maintained\" —\n // the latter silently excluded hosting sites and implied a type↔status coupling that\n // doesn't exist (the requested --type drives the rendered template; single-site mode\n // applies no status filter at all).\n targets = websites.filter((w) => w.status !== null && ELIGIBLE_STATUSES.has(w.status));\n } else if (deps.site) {\n const wanted = siteSlug(deps.site);\n targets = websites.filter((w) => siteSlug(w.name) === wanted);\n } else {\n throw Object.assign(new Error(\"Provide a site slug or --all\"), { exitCode: 2 });\n }\n\n const results: SelftestEmailSiteResult[] = [];\n for (const w of targets) {\n try {\n const scores = scoresFromRow(w);\n if (!scores) {\n results.push({ site: w.name, status: \"skipped\", reason: \"missing Lighthouse scores\" });\n continue;\n }\n if (!w.headerImage) {\n results.push({ site: w.name, status: \"skipped\", reason: \"no Header image\" });\n continue;\n }\n const original = await fetchAttachmentBytes(w.headerImage.url);\n // Mirror orchestrate.ts exactly: the stored header is the CLEAN plate, so the\n // report type's headline has to be stamped on before downscaling. Omitting this\n // step made every selftest preview ship a header with an EMPTY headline band —\n // the one thing a preview exists to catch, silently wrong in the preview itself.\n const withHeadline = await applyReportTypeHeadline(original.bytes, type);\n const header = await prepareHeaderImage(withHeadline);\n const slug = siteSlug(w.name);\n const reportData = await buildReportDataForSite(w, type, now, { scores, header });\n const { html, attachments, subject } = await renderReportEmail(reportData, {\n header,\n cidName: `${slug}-header`,\n });\n\n if (deps.dryRun) {\n const path = `reports/${slug}/selftest-${type.toLowerCase()}.html`;\n await mkdir(dirname(path), { recursive: true });\n await writeFile(path, html, \"utf-8\");\n results.push({ site: w.name, status: \"dry-run\", subject, recipients });\n continue;\n }\n\n await resend.send({\n from: FROM_ADDRESS,\n to: recipients,\n replyTo: REPLY_TO,\n subject,\n html,\n attachments,\n });\n results.push({ site: w.name, status: \"sent\", subject, recipients });\n } catch (err) {\n results.push({\n site: w.name,\n status: \"error\",\n message: err instanceof Error ? err.message : String(err),\n });\n }\n }\n\n return { results };\n}\n","import { selftestEmail, type SelftestEmailSiteResult } from \"../../recipes/selftest-email.js\";\nimport type { ReportType } from \"../../reports/types.js\";\n\nexport type SelftestCommandOptions = {\n type?: string;\n to?: string;\n all?: boolean;\n dryRun?: boolean;\n cwd?: string;\n};\n\nconst TYPES: Record<string, ReportType> = {\n announcement: \"Announcement\",\n maintenance: \"Maintenance\",\n testing: \"Testing\",\n launch: \"Launch\",\n};\n\nfunction formatResult(r: SelftestEmailSiteResult): string {\n if (r.status === \"skipped\") return `[${r.site}] skipped — ${r.reason}`;\n if (r.status === \"error\") return `[${r.site}] error: ${r.message}`;\n return `[${r.site}] ${r.status} — \"${r.subject}\" → ${r.recipients.join(\", \")}`;\n}\n\n/**\n * `selftest <kind> [site]` — operator self-tests. The only kind today is `email`: preview a\n * report email for one site (or `--all` maintenance sites) to the operator/`--to`, with no\n * Airtable side effects. Validates kind/type and the site-xor-all rule before doing any work.\n */\nexport async function runSelftestCommand(\n kind: string,\n site: string | undefined,\n opts: SelftestCommandOptions,\n): Promise<{ output: string; code: number }> {\n if (kind !== \"email\") {\n return { output: `Unknown selftest kind '${kind}'. Supported: email`, code: 2 };\n }\n if (Boolean(site) === Boolean(opts.all)) {\n return { output: \"Provide exactly one of <site> or --all.\", code: 2 };\n }\n const typeKey = (opts.type ?? \"announcement\").toLowerCase();\n const type = TYPES[typeKey];\n if (!type) {\n return {\n output: `Unknown --type '${opts.type}'. Supported: ${Object.keys(TYPES).join(\", \")}`,\n code: 2,\n };\n }\n\n try {\n const { results } = await selftestEmail({\n ...(site ? { site } : {}),\n ...(opts.all ? { all: true } : {}),\n type,\n ...(opts.to ? { to: opts.to } : {}),\n ...(opts.dryRun ? { dryRun: true } : {}),\n });\n const output =\n results.length === 0 ? \"No matching sites.\" : results.map(formatResult).join(\"\\n\");\n const code = results.some((r) => r.status === \"error\") ? 1 : 0;\n return { output, code };\n } catch (err) {\n const e = err as { message?: string; exitCode?: number };\n return { output: e.message ?? String(err), code: e.exitCode ?? 1 };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,OAAO,iBAAiB;AACjC,SAAS,eAAe;AAgBxB,IAAM,eAAe;AACrB,IAAM,WAAW;AA6BjB,SAAS,kBAAkB,IAAkC;AAC3D,QAAM,WAAW,cAAc;AAC/B,QAAM,SAAS,KAAK,eAAe,EAAE,IAAI;AACzC,QAAM,OAAO,UAAU,CAAC,QAAQ;AAChC,aAAW,QAAQ,MAAM;AACvB,QAAI,CAAC,gBAAgB,IAAI,GAAG;AAC1B,YAAM,OAAO,OAAO,IAAI,MAAM,iCAAiC,IAAI,EAAE,GAAG,EAAE,UAAU,EAAE,CAAC;AAAA,IACzF;AAAA,EACF;AACA,SAAO;AACT;AAQA,eAAsB,cAAc,MAAuD;AACzF,QAAM,OAAO,KAAK,QAAQ,SAAS,mBAAmB,CAAC;AACvD,QAAM,SAAS,KAAK,UAAU,oBAAoB;AAClD,QAAM,OAAmB,KAAK,QAAQ;AACtC,Q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|
|
11
|
+
import "./chunk-VAD43MOR.js";
|
|
12
|
+
import "./chunk-7NYN2P6I.js";
|
|
13
|
+
import {
|
|
14
|
+
openDb,
|
|
15
|
+
readDbConfig
|
|
16
|
+
} from "./chunk-WS6NU475.js";
|
|
17
|
+
import "./chunk-MFHS7IQ2.js";
|
|
18
|
+
import "./chunk-6VAL7XJT.js";
|
|
19
|
+
|
|
20
|
+
// src/db/site-mirror.ts
|
|
21
|
+
async function makeSiteMirror(open = () => openDb(readDbConfig()), strict = TURSO_IS_AUTHORITATIVE) {
|
|
22
|
+
let db = null;
|
|
23
|
+
let why = "";
|
|
24
|
+
try {
|
|
25
|
+
db = await open();
|
|
26
|
+
} catch (e) {
|
|
27
|
+
why = e.message;
|
|
28
|
+
}
|
|
29
|
+
if (strict && !db) throw new Error(`SITE_MIRROR unavailable: ${why}`);
|
|
30
|
+
const run = async (siteId, op, work) => {
|
|
31
|
+
if (!db) {
|
|
32
|
+
console.log(`SITE_MIRROR site=${siteId} op=${op} mirrored=absent reason=${why}`);
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
let matched;
|
|
36
|
+
try {
|
|
37
|
+
matched = await work(db);
|
|
38
|
+
} catch (e) {
|
|
39
|
+
console.log(`SITE_MIRROR site=${siteId} op=${op} mirrored=0 error=${e.message}`);
|
|
40
|
+
if (strict) throw e;
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
console.log(`SITE_MIRROR site=${siteId} op=${op} mirrored=${matched ? "1" : "missed"}`);
|
|
44
|
+
if (strict && !matched) {
|
|
45
|
+
throw new Error(`SITE_MIRROR site=${siteId} op=${op}: no such row in Turso`);
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
return {
|
|
49
|
+
// An INSERT always lands, so it reports 1 rather than routing a row count
|
|
50
|
+
// through `missed` — there was nothing to match in the first place.
|
|
51
|
+
created: (rec) => run(rec.id, "created", async (d) => {
|
|
52
|
+
await mirrorSiteInsert(d, rec, (/* @__PURE__ */ new Date()).toISOString());
|
|
53
|
+
return true;
|
|
54
|
+
}),
|
|
55
|
+
health: (siteId, fields) => run(siteId, "health", (d) => mirrorHealthFields(d, siteId, fields)),
|
|
56
|
+
site: (siteId, fields) => run(siteId, "site", (d) => mirrorSiteFields(d, siteId, fields))
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
export {
|
|
60
|
+
makeSiteMirror
|
|
61
|
+
};
|
|
62
|
+
//# sourceMappingURL=site-mirror-Q763PLGG.js.map
|