@reddoorla/maintenance 0.90.1 → 0.92.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/dist/{announce-NDTLRQCN.js → announce-6OS4C57D.js} +3 -3
  2. package/dist/{blux-YGBGS24U.js → blux-NXQLMS4W.js} +4 -4
  3. package/dist/blux-NXQLMS4W.js.map +1 -0
  4. package/dist/{bump-deps-KGH5UYSF.js → bump-deps-GI7PHMOC.js} +6 -6
  5. package/dist/{chunk-WS6NU475.js → chunk-22GKJO5F.js} +2 -2
  6. package/dist/{chunk-A6T2R63Z.js → chunk-3HS6LPFX.js} +2 -2
  7. package/dist/{chunk-UXJZU23T.js → chunk-4NUKMPOO.js} +9 -9
  8. package/dist/{chunk-BQRFQSGY.js → chunk-4R3YAQNV.js} +2 -2
  9. package/dist/{chunk-JRHIFA5R.js → chunk-5XMKJX74.js} +10 -4
  10. package/dist/chunk-5XMKJX74.js.map +1 -0
  11. package/dist/{chunk-XIDUYLSR.js → chunk-7CJ3DVZW.js} +2 -2
  12. package/dist/{chunk-NYUYNYQL.js → chunk-7MKT4I5T.js} +15 -1
  13. package/dist/chunk-7MKT4I5T.js.map +1 -0
  14. package/dist/{chunk-Z3KYFUN6.js → chunk-B6NUZ2ZX.js} +2 -2
  15. package/dist/chunk-BJQCIJOY.js +3534 -0
  16. package/dist/chunk-BJQCIJOY.js.map +1 -0
  17. package/dist/{chunk-Y53WOQIJ.js → chunk-CVJF2IC5.js} +2 -2
  18. package/dist/{chunk-W45FZEGE.js → chunk-DMPHP7UP.js} +2 -2
  19. package/dist/{chunk-KGUKL3CV.js → chunk-E22WAIF2.js} +2 -2
  20. package/dist/{chunk-VBEKL445.js → chunk-FCS36FDT.js} +2 -2
  21. package/dist/{chunk-QD427NIO.js → chunk-JB4Q3C3M.js} +7 -7
  22. package/dist/{chunk-IYSEC543.js → chunk-LS6QPANO.js} +2 -2
  23. package/dist/{chunk-SJOXWJ5Y.js → chunk-M2XF6JAI.js} +80 -9
  24. package/dist/chunk-M2XF6JAI.js.map +1 -0
  25. package/dist/{chunk-ZOCJBJQV.js → chunk-MVDMKKBN.js} +2 -2
  26. package/dist/{chunk-7RJ2HMMJ.js → chunk-NTLSMJHW.js} +2 -2
  27. package/dist/{chunk-MFHS7IQ2.js → chunk-OCNSIBMP.js} +27 -1
  28. package/dist/{chunk-MFHS7IQ2.js.map → chunk-OCNSIBMP.js.map} +1 -1
  29. package/dist/chunk-PJ23RDHT.js +48 -0
  30. package/dist/chunk-PJ23RDHT.js.map +1 -0
  31. package/dist/{chunk-2NJQLSEU.js → chunk-PPIZHDJL.js} +2 -2
  32. package/dist/chunk-T7ZUUOZ2.js +496 -0
  33. package/dist/chunk-T7ZUUOZ2.js.map +1 -0
  34. package/dist/{chunk-TVL5MVUF.js → chunk-TCF6S7AD.js} +4 -4
  35. package/dist/{chunk-GSWTT2J6.js → chunk-WHWVYL7B.js} +4 -4
  36. package/dist/{chunk-3G25KIWW.js → chunk-ZTPPCHDB.js} +4 -4
  37. package/dist/cli/bin.js +30 -27
  38. package/dist/cli/bin.js.map +1 -1
  39. package/dist/cli/commands/audit.js +14 -14
  40. package/dist/client-M2V6FHH5.js +11 -0
  41. package/dist/{convert-to-pnpm-NWB5FCQ2.js → convert-to-pnpm-ONFP3JKF.js} +6 -6
  42. package/dist/{db-LOSJ74ZJ.js → db-DJVW6ZSE.js} +11 -11
  43. package/dist/{digest-CS6KLCZB.js → digest-EOA4JLTV.js} +13 -13
  44. package/dist/{digest-collectors-NI2M3UTC.js → digest-collectors-ZA3BTS3R.js} +7 -7
  45. package/dist/{email-LJQT5J7F.js → email-I4BCETI4.js} +16 -64
  46. package/dist/email-I4BCETI4.js.map +1 -0
  47. package/dist/{ensure-site-FFDUMY6E.js → ensure-site-SF6KICTN.js} +2 -2
  48. package/dist/forms/index.d.ts +5 -1
  49. package/dist/forms/index.js +1 -1
  50. package/dist/forms/index.js.map +1 -1
  51. package/dist/forms/prismic.d.ts +69 -0
  52. package/dist/forms/prismic.js +75 -0
  53. package/dist/forms/prismic.js.map +1 -0
  54. package/dist/{forms-notify-target-IHJX7NWA.js → forms-notify-target-MNNOGSJ7.js} +5 -4
  55. package/dist/{forms-notify-target-IHJX7NWA.js.map → forms-notify-target-MNNOGSJ7.js.map} +1 -1
  56. package/dist/{github-signals-FCLNHKMF.js → github-signals-3WLIJ5RR.js} +5 -5
  57. package/dist/{header-image-7A7XLVEU.js → header-image-DOCDFFRO.js} +2 -2
  58. package/dist/{health-endpoint-UVX6R5N5.js → health-endpoint-DHKJUPRM.js} +6 -6
  59. package/dist/{health-mirror-GMSF3Z5R.js → health-mirror-55RRU6BI.js} +3 -3
  60. package/dist/index.js +36 -29
  61. package/dist/index.js.map +1 -1
  62. package/dist/{init-NXZ4NXTL.js → init-ZRKWYCKA.js} +15 -15
  63. package/dist/{launch-5V7RLUV7.js → launch-6X5OXPF2.js} +13 -13
  64. package/dist/migrate-K4JETR36.js +7 -0
  65. package/dist/{notify-4HP4GZ2H.js → notify-FYSOWKMJ.js} +4 -3
  66. package/dist/{onboard-BKCYBAVW.js → onboard-6NHGCKGB.js} +6 -6
  67. package/dist/{orchestrate-6HROYTM6.js → orchestrate-KMQIUP3H.js} +5 -5
  68. package/dist/pipeline-AQBFG5WM.js +31 -0
  69. package/dist/{preflight-LIN5NCYU.js → preflight-VPHQYWTY.js} +6 -6
  70. package/dist/{prismic-ci-6YGRIOHT.js → prismic-ci-A2HI7NNJ.js} +8 -8
  71. package/dist/{prismic-models-VNGIKS2B.js → prismic-models-QTKIMFBC.js} +5 -5
  72. package/dist/prospect/types.d.ts +809 -2
  73. package/dist/prospect/types.js +8 -0
  74. package/dist/{prospect-audit-JCWTKJTS.js → prospect-audit-RKUVSTLN.js} +27 -6
  75. package/dist/prospect-audit-RKUVSTLN.js.map +1 -0
  76. package/dist/{prospect-audits-3PMIO73D.js → prospect-audits-RVYEA4KH.js} +6 -4
  77. package/dist/recipes/sync-configs.js +3 -3
  78. package/dist/{chunk-5PWB3JHJ.js → render-7G43BSK5.js} +28 -9
  79. package/dist/render-7G43BSK5.js.map +1 -0
  80. package/dist/{replay-4S6ENYCH.js → replay-HV7MGKBU.js} +3 -2
  81. package/dist/{replay-4S6ENYCH.js.map → replay-HV7MGKBU.js.map} +1 -1
  82. package/dist/{report-AAY2HZZR.js → report-Y4LXDHRV.js} +11 -11
  83. package/dist/{report-mirror-GMNSH5HF.js → report-mirror-6ZDCAQZB.js} +3 -3
  84. package/dist/{schema-75PJECAE.js → schema-2V7BGYVT.js} +1 -1
  85. package/dist/{schema-75PJECAE.js.map → schema-2V7BGYVT.js.map} +1 -1
  86. package/dist/{self-updating-VQIW24RZ.js → self-updating-D5XOWS7V.js} +5 -5
  87. package/dist/{selftest-CUX2FIQD.js → selftest-IFGSJP4X.js} +5 -5
  88. package/dist/{site-mirror-GCFLBBWK.js → site-mirror-3E7JYTJG.js} +3 -3
  89. package/dist/{smoke-suite-4JFZZYVW.js → smoke-suite-GXC5JZPH.js} +6 -6
  90. package/dist/{submissions-7LGJJSDL.js → submissions-UMJS3YST.js} +2 -2
  91. package/dist/{svelte-codemods-QAPDZC6F.js → svelte-codemods-A3EARSRP.js} +6 -6
  92. package/dist/{sync-configs-PVRLZRKL.js → sync-configs-KSESOHFF.js} +6 -6
  93. package/dist/{upgrade-IR2OO3KP.js → upgrade-ZLNVEIEA.js} +6 -6
  94. package/dist/{webflow-624FEBFD.js → webflow-IRKOIT7S.js} +4 -4
  95. package/package.json +6 -1
  96. package/dist/blux-YGBGS24U.js.map +0 -1
  97. package/dist/chunk-5PWB3JHJ.js.map +0 -1
  98. package/dist/chunk-DXKF552B.js +0 -1630
  99. package/dist/chunk-DXKF552B.js.map +0 -1
  100. package/dist/chunk-JRHIFA5R.js.map +0 -1
  101. package/dist/chunk-NYUYNYQL.js.map +0 -1
  102. package/dist/chunk-SJOXWJ5Y.js.map +0 -1
  103. package/dist/client-JYKPVCJX.js +0 -11
  104. package/dist/email-LJQT5J7F.js.map +0 -1
  105. package/dist/migrate-YITCXBLS.js +0 -7
  106. package/dist/pipeline-MQJD4CKN.js +0 -16
  107. package/dist/prospect-audit-JCWTKJTS.js.map +0 -1
  108. package/dist/render-P3SBUFVB.js +0 -10
  109. package/dist/render-P3SBUFVB.js.map +0 -1
  110. /package/dist/{announce-NDTLRQCN.js.map → announce-6OS4C57D.js.map} +0 -0
  111. /package/dist/{bump-deps-KGH5UYSF.js.map → bump-deps-GI7PHMOC.js.map} +0 -0
  112. /package/dist/{chunk-WS6NU475.js.map → chunk-22GKJO5F.js.map} +0 -0
  113. /package/dist/{chunk-A6T2R63Z.js.map → chunk-3HS6LPFX.js.map} +0 -0
  114. /package/dist/{chunk-UXJZU23T.js.map → chunk-4NUKMPOO.js.map} +0 -0
  115. /package/dist/{chunk-BQRFQSGY.js.map → chunk-4R3YAQNV.js.map} +0 -0
  116. /package/dist/{chunk-XIDUYLSR.js.map → chunk-7CJ3DVZW.js.map} +0 -0
  117. /package/dist/{chunk-Z3KYFUN6.js.map → chunk-B6NUZ2ZX.js.map} +0 -0
  118. /package/dist/{chunk-Y53WOQIJ.js.map → chunk-CVJF2IC5.js.map} +0 -0
  119. /package/dist/{chunk-W45FZEGE.js.map → chunk-DMPHP7UP.js.map} +0 -0
  120. /package/dist/{chunk-KGUKL3CV.js.map → chunk-E22WAIF2.js.map} +0 -0
  121. /package/dist/{chunk-VBEKL445.js.map → chunk-FCS36FDT.js.map} +0 -0
  122. /package/dist/{chunk-QD427NIO.js.map → chunk-JB4Q3C3M.js.map} +0 -0
  123. /package/dist/{chunk-IYSEC543.js.map → chunk-LS6QPANO.js.map} +0 -0
  124. /package/dist/{chunk-ZOCJBJQV.js.map → chunk-MVDMKKBN.js.map} +0 -0
  125. /package/dist/{chunk-7RJ2HMMJ.js.map → chunk-NTLSMJHW.js.map} +0 -0
  126. /package/dist/{chunk-2NJQLSEU.js.map → chunk-PPIZHDJL.js.map} +0 -0
  127. /package/dist/{chunk-TVL5MVUF.js.map → chunk-TCF6S7AD.js.map} +0 -0
  128. /package/dist/{chunk-GSWTT2J6.js.map → chunk-WHWVYL7B.js.map} +0 -0
  129. /package/dist/{chunk-3G25KIWW.js.map → chunk-ZTPPCHDB.js.map} +0 -0
  130. /package/dist/{client-JYKPVCJX.js.map → client-M2V6FHH5.js.map} +0 -0
  131. /package/dist/{convert-to-pnpm-NWB5FCQ2.js.map → convert-to-pnpm-ONFP3JKF.js.map} +0 -0
  132. /package/dist/{db-LOSJ74ZJ.js.map → db-DJVW6ZSE.js.map} +0 -0
  133. /package/dist/{digest-CS6KLCZB.js.map → digest-EOA4JLTV.js.map} +0 -0
  134. /package/dist/{digest-collectors-NI2M3UTC.js.map → digest-collectors-ZA3BTS3R.js.map} +0 -0
  135. /package/dist/{ensure-site-FFDUMY6E.js.map → ensure-site-SF6KICTN.js.map} +0 -0
  136. /package/dist/{github-signals-FCLNHKMF.js.map → github-signals-3WLIJ5RR.js.map} +0 -0
  137. /package/dist/{header-image-7A7XLVEU.js.map → header-image-DOCDFFRO.js.map} +0 -0
  138. /package/dist/{health-endpoint-UVX6R5N5.js.map → health-endpoint-DHKJUPRM.js.map} +0 -0
  139. /package/dist/{health-mirror-GMSF3Z5R.js.map → health-mirror-55RRU6BI.js.map} +0 -0
  140. /package/dist/{init-NXZ4NXTL.js.map → init-ZRKWYCKA.js.map} +0 -0
  141. /package/dist/{launch-5V7RLUV7.js.map → launch-6X5OXPF2.js.map} +0 -0
  142. /package/dist/{migrate-YITCXBLS.js.map → migrate-K4JETR36.js.map} +0 -0
  143. /package/dist/{notify-4HP4GZ2H.js.map → notify-FYSOWKMJ.js.map} +0 -0
  144. /package/dist/{onboard-BKCYBAVW.js.map → onboard-6NHGCKGB.js.map} +0 -0
  145. /package/dist/{orchestrate-6HROYTM6.js.map → orchestrate-KMQIUP3H.js.map} +0 -0
  146. /package/dist/{pipeline-MQJD4CKN.js.map → pipeline-AQBFG5WM.js.map} +0 -0
  147. /package/dist/{preflight-LIN5NCYU.js.map → preflight-VPHQYWTY.js.map} +0 -0
  148. /package/dist/{prismic-ci-6YGRIOHT.js.map → prismic-ci-A2HI7NNJ.js.map} +0 -0
  149. /package/dist/{prismic-models-VNGIKS2B.js.map → prismic-models-QTKIMFBC.js.map} +0 -0
  150. /package/dist/{prospect-audits-3PMIO73D.js.map → prospect-audits-RVYEA4KH.js.map} +0 -0
  151. /package/dist/{report-AAY2HZZR.js.map → report-Y4LXDHRV.js.map} +0 -0
  152. /package/dist/{report-mirror-GMNSH5HF.js.map → report-mirror-6ZDCAQZB.js.map} +0 -0
  153. /package/dist/{self-updating-VQIW24RZ.js.map → self-updating-D5XOWS7V.js.map} +0 -0
  154. /package/dist/{selftest-CUX2FIQD.js.map → selftest-IFGSJP4X.js.map} +0 -0
  155. /package/dist/{site-mirror-GCFLBBWK.js.map → site-mirror-3E7JYTJG.js.map} +0 -0
  156. /package/dist/{smoke-suite-4JFZZYVW.js.map → smoke-suite-GXC5JZPH.js.map} +0 -0
  157. /package/dist/{submissions-7LGJJSDL.js.map → submissions-UMJS3YST.js.map} +0 -0
  158. /package/dist/{svelte-codemods-QAPDZC6F.js.map → svelte-codemods-A3EARSRP.js.map} +0 -0
  159. /package/dist/{sync-configs-PVRLZRKL.js.map → sync-configs-KSESOHFF.js.map} +0 -0
  160. /package/dist/{upgrade-IR2OO3KP.js.map → upgrade-ZLNVEIEA.js.map} +0 -0
  161. /package/dist/{webflow-624FEBFD.js.map → webflow-IRKOIT7S.js.map} +0 -0
@@ -5,19 +5,19 @@ import {
5
5
  appendSkipNotice,
6
6
  fleetWorkdir,
7
7
  prepareFleetSites
8
- } from "./chunk-TVL5MVUF.js";
8
+ } from "./chunk-TCF6S7AD.js";
9
9
  import {
10
10
  resolveSites
11
11
  } from "./chunk-Q47DU255.js";
12
12
  import {
13
13
  bumpDeps
14
- } from "./chunk-2NJQLSEU.js";
15
- import "./chunk-3G25KIWW.js";
14
+ } from "./chunk-PPIZHDJL.js";
15
+ import "./chunk-ZTPPCHDB.js";
16
16
  import "./chunk-Z3JXLULD.js";
17
- import "./chunk-RARREDQE.js";
18
- import "./chunk-XTK5VIQB.js";
19
17
  import "./chunk-LBYOLBW7.js";
18
+ import "./chunk-RARREDQE.js";
20
19
  import "./chunk-XXTZBPUY.js";
20
+ import "./chunk-XTK5VIQB.js";
21
21
 
22
22
  // src/cli/commands/bump-deps.ts
23
23
  import { resolve } from "path";
@@ -57,4 +57,4 @@ async function runBumpDepsCommand(site, opts) {
57
57
  export {
58
58
  runBumpDepsCommand
59
59
  };
60
- //# sourceMappingURL=bump-deps-KGH5UYSF.js.map
60
+ //# sourceMappingURL=bump-deps-GI7PHMOC.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  runMigrations
3
- } from "./chunk-MFHS7IQ2.js";
3
+ } from "./chunk-OCNSIBMP.js";
4
4
  import {
5
5
  defaultCredentialsPath
6
6
  } from "./chunk-6VAL7XJT.js";
@@ -48,4 +48,4 @@ export {
48
48
  readDbConfig,
49
49
  openDb
50
50
  };
51
- //# sourceMappingURL=chunk-WS6NU475.js.map
51
+ //# sourceMappingURL=chunk-22GKJO5F.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  withRecipe
3
- } from "./chunk-3G25KIWW.js";
3
+ } from "./chunk-ZTPPCHDB.js";
4
4
  import {
5
5
  ALL_TEMPLATES,
6
6
  RENOVATE_ACTION_CONFIG,
@@ -229,4 +229,4 @@ export {
229
229
  planTemplateDiffs,
230
230
  syncConfigs
231
231
  };
232
- //# sourceMappingURL=chunk-A6T2R63Z.js.map
232
+ //# sourceMappingURL=chunk-3HS6LPFX.js.map
@@ -1,27 +1,27 @@
1
1
  import {
2
2
  convertToPnpm
3
- } from "./chunk-XIDUYLSR.js";
3
+ } from "./chunk-7CJ3DVZW.js";
4
4
  import {
5
5
  svelteCodemods
6
- } from "./chunk-IYSEC543.js";
6
+ } from "./chunk-LS6QPANO.js";
7
7
  import {
8
8
  healthEndpoint
9
- } from "./chunk-BQRFQSGY.js";
9
+ } from "./chunk-4R3YAQNV.js";
10
10
  import {
11
11
  smokeSuite
12
- } from "./chunk-Y53WOQIJ.js";
12
+ } from "./chunk-CVJF2IC5.js";
13
13
  import {
14
14
  onboard
15
- } from "./chunk-7RJ2HMMJ.js";
15
+ } from "./chunk-NTLSMJHW.js";
16
16
  import {
17
17
  syncConfigs
18
- } from "./chunk-A6T2R63Z.js";
18
+ } from "./chunk-3HS6LPFX.js";
19
19
  import {
20
20
  withRecipe
21
- } from "./chunk-3G25KIWW.js";
21
+ } from "./chunk-ZTPPCHDB.js";
22
22
  import {
23
23
  runAudits
24
- } from "./chunk-QD427NIO.js";
24
+ } from "./chunk-JB4Q3C3M.js";
25
25
  import {
26
26
  siteLabel
27
27
  } from "./chunk-XXTZBPUY.js";
@@ -143,4 +143,4 @@ export {
143
143
  DEFAULT_INIT_STEPS,
144
144
  init
145
145
  };
146
- //# sourceMappingURL=chunk-UXJZU23T.js.map
146
+ //# sourceMappingURL=chunk-4NUKMPOO.js.map
@@ -4,7 +4,7 @@ import {
4
4
  } from "./chunk-R53VL3RI.js";
5
5
  import {
6
6
  withRecipe
7
- } from "./chunk-3G25KIWW.js";
7
+ } from "./chunk-ZTPPCHDB.js";
8
8
  import {
9
9
  defaultSpawn
10
10
  } from "./chunk-LBYOLBW7.js";
@@ -142,4 +142,4 @@ async function healthEndpoint(site, deps = { spawn: defaultSpawn }) {
142
142
  export {
143
143
  healthEndpoint
144
144
  };
145
- //# sourceMappingURL=chunk-BQRFQSGY.js.map
145
+ //# sourceMappingURL=chunk-4R3YAQNV.js.map
@@ -1,6 +1,9 @@
1
1
  import {
2
2
  SPAM_THRESHOLD
3
3
  } from "./chunk-NO74DXDP.js";
4
+ import {
5
+ parseReplyCopy
6
+ } from "./chunk-PJ23RDHT.js";
4
7
  import {
5
8
  SUBMISSION_FORM_TYPES
6
9
  } from "./chunk-2OP4JKIQ.js";
@@ -17,7 +20,8 @@ var KNOWN_KEYS = /* @__PURE__ */ new Set([
17
20
  "sourceUrl",
18
21
  "utm",
19
22
  "extra",
20
- "_meta"
23
+ "_meta",
24
+ "_reply"
21
25
  ]);
22
26
  var DANGEROUS_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
23
27
  var EMAIL_RE = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
@@ -47,12 +51,14 @@ function normalizeSubmission(payload) {
47
51
  const extra = p.extra;
48
52
  if (typeof extra === "object" && extra !== null) {
49
53
  for (const [k, v] of Object.entries(extra)) {
50
- if (!DANGEROUS_KEYS.has(k)) extraFields[k] = v;
54
+ if (!DANGEROUS_KEYS.has(k) && !k.startsWith("_")) extraFields[k] = v;
51
55
  }
52
56
  }
53
57
  for (const [k, v] of Object.entries(p)) {
54
- if (!KNOWN_KEYS.has(k) && !DANGEROUS_KEYS.has(k)) extraFields[k] = v;
58
+ if (!KNOWN_KEYS.has(k) && !DANGEROUS_KEYS.has(k) && !k.startsWith("_")) extraFields[k] = v;
55
59
  }
60
+ const reply = parseReplyCopy(p._reply);
61
+ if (reply) extraFields._reply = reply;
56
62
  const value = {
57
63
  formType,
58
64
  name,
@@ -281,4 +287,4 @@ export {
281
287
  ingestSubmission,
282
288
  hostsMatch
283
289
  };
284
- //# sourceMappingURL=chunk-JRHIFA5R.js.map
290
+ //# sourceMappingURL=chunk-5XMKJX74.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/forms/payload.ts","../src/forms/ingest.ts"],"sourcesContent":["import { SUBMISSION_FORM_TYPES, type FormType } from \"./types.js\";\nimport type { SubmissionMeta } from \"./meta.js\";\nimport { parseReplyCopy, type ReplyCopy } from \"./reply-copy.js\";\n\n/** The JSON wire format a fleet site forwards to the ingest endpoint.\n *\n * Underscore-prefixed keys are RESERVED for transport concerns and are never\n * lead data: `_meta` (below) and `_screenOut` (the bot screen-out beacon —\n * a `{ _screenOut: \"honeypot\" | \"too-fast\" }` body is a counter ping, not a\n * submission; see ingest.ts `parseScreenOut`). Site field names must not\n * start with `_`. */\nexport type SubmissionPayload = {\n formType?: string;\n name?: string;\n firstName?: string;\n lastName?: string;\n email?: string;\n phone?: string;\n message?: string;\n sourceUrl?: string;\n utm?: string;\n /** Any additional, site-specific fields. */\n extra?: Record<string, unknown>;\n /** Reserved transport envelope (token/IP/UA); stripped by normalizeSubmission, never persisted. */\n _meta?: SubmissionMeta;\n /** Reserved: confirmation-email copy the SITE resolved from its own CMS.\n * Validated by parseReplyCopy, then stored under the same key in extraFields\n * so a replayed submission sends the same email it would have sent live. */\n _reply?: ReplyCopy;\n};\n\nexport type NormalizedSubmission = {\n formType: FormType;\n name: string;\n email: string;\n phone?: string;\n message?: string;\n sourceUrl?: string;\n utm?: string;\n extraFields: Record<string, unknown>;\n};\n\nexport type NormalizeResult =\n { ok: true; value: NormalizedSubmission } | { ok: false; errors: string[] };\n\nconst KNOWN_KEYS = new Set([\n \"formType\",\n \"name\",\n \"firstName\",\n \"lastName\",\n \"email\",\n \"phone\",\n \"message\",\n \"sourceUrl\",\n \"utm\",\n \"extra\",\n \"_meta\",\n \"_reply\",\n]);\n\n// Keys that, copied as own-properties into the captured object, could surprise a\n// downstream consumer (template/DB layer). This is an untrusted boundary, so the\n// extraFields merge drops them rather than trusting the caller.\nconst DANGEROUS_KEYS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\nconst EMAIL_RE = /^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$/;\n\nfunction str(v: unknown): string {\n return typeof v === \"string\" ? v.trim() : \"\";\n}\n\n/**\n * Resolve the submission's formType. An ABSENT/blank value defaults to \"contact\"\n * (the long-standing minimal-form contract). A PRESENT but unrecognized value\n * (e.g. a typo'd \"news\") returns null → the caller rejects it, rather than\n * silently storing it as contact — which would, for a newsletter signup, drop the\n * Mailchimp fan-out. Mirrors createIngestEndpoint's reject-invalid behavior.\n */\nfunction resolveFormType(raw: unknown): FormType | null {\n const s = str(raw);\n if (s === \"\") return \"contact\";\n return (SUBMISSION_FORM_TYPES as readonly string[]).includes(s) ? (s as FormType) : null;\n}\n\n/**\n * Defensively normalize an untrusted ingest payload into typed fields. Folds\n * name/first+last, lowercases email, and dumps every unclaimed key into\n * extraFields so no site-specific data is lost. Rejects only when there's\n * nothing to act on (no email AND no message) or a present email is malformed.\n */\nexport function normalizeSubmission(payload: unknown): NormalizeResult {\n if (typeof payload !== \"object\" || payload === null) {\n return { ok: false, errors: [\"payload must be a JSON object\"] };\n }\n const p = payload as Record<string, unknown>;\n const name = str(p.name) || [str(p.firstName), str(p.lastName)].filter(Boolean).join(\" \");\n const email = str(p.email).toLowerCase();\n const message = str(p.message);\n\n const formType = resolveFormType(p.formType);\n const errors: string[] = [];\n if (!email && !message) errors.push(\"at least one of email or message is required\");\n if (email && !EMAIL_RE.test(email)) errors.push(\"email is not a valid address\");\n if (formType === null) errors.push(\"formType is not a recognized form type\");\n // The `|| formType === null` is redundant for control flow (the push above\n // already made errors non-empty) but narrows formType to FormType past this line.\n if (errors.length > 0 || formType === null) return { ok: false, errors };\n\n const extraFields: Record<string, unknown> = {};\n const extra = p.extra;\n if (typeof extra === \"object\" && extra !== null) {\n for (const [k, v] of Object.entries(extra)) {\n if (!DANGEROUS_KEYS.has(k) && !k.startsWith(\"_\")) extraFields[k] = v;\n }\n }\n for (const [k, v] of Object.entries(p)) {\n if (!KNOWN_KEYS.has(k) && !DANGEROUS_KEYS.has(k) && !k.startsWith(\"_\")) extraFields[k] = v;\n }\n // The ONE underscore key a caller may set. Both loops above dropped the rest,\n // including any `_reply` smuggled in through `extra` — this is the only way a\n // value reaches that key, and it is validated on the way through. Without it,\n // a bot could POST its own copy and dictate the text of an email we send from\n // a domain with real sending reputation.\n const reply = parseReplyCopy(p._reply);\n if (reply) extraFields._reply = reply;\n\n const value: NormalizedSubmission = {\n formType,\n name,\n email,\n extraFields,\n };\n const phone = str(p.phone);\n if (phone) value.phone = phone;\n if (message) value.message = message;\n const sourceUrl = str(p.sourceUrl);\n if (sourceUrl) value.sourceUrl = sourceUrl;\n const utm = str(p.utm);\n if (utm) value.utm = utm;\n return { ok: true, value };\n}\n","import type { WebsiteRow } from \"../reports/airtable/websites.js\";\nimport type {\n SubmissionRow,\n SubmissionInput,\n NotifyStatus,\n SubmissionStatus,\n} from \"../reports/submission-row.js\";\nimport { normalizeSubmission, type NormalizedSubmission } from \"./payload.js\";\nimport type { TurnstileOutcome, TurnstileVerification } from \"./turnstile.js\";\nimport { SPAM_THRESHOLD, type SpamVerdict } from \"./spam-classifier.js\";\n\n/** How far back the duplicate-spray AND repeat-sender lookups scan. Sprays arrive in\n * bursts but bots also re-run for weeks; 30 days catches repeats without an unbounded\n * table scan. */\nconst DUPLICATE_WINDOW_MS = 30 * 24 * 60 * 60 * 1000;\n\nexport type IngestDeps = {\n getWebsiteBySlug: (slug: string) => Promise<WebsiteRow | null>;\n createSubmission: (input: SubmissionInput) => Promise<SubmissionRow>;\n /** Optional last-resort capture for a lead whose site lookup THREW (a store\n * outage, not an unknown slug). When present, the lead is persisted here and\n * the visitor still gets \"accepted\"; `db replay-deadletters` re-runs it once\n * the lookup recovers. Absent → the error propagates exactly as before, so\n * callers that never wired it are byte-for-byte unchanged. */\n deadLetter?: (input: {\n siteSlug: string;\n payload: unknown;\n turnstile: TurnstileVerification;\n error: string;\n receivedAt: Date;\n }) => Promise<{ id: string }>;\n notify: (\n site: WebsiteRow,\n submission: SubmissionRow,\n ) => Promise<{ status: NotifyStatus; messageId: string | null }>;\n stampNotified: (id: string, status: NotifyStatus, messageId: string | null) => Promise<void>;\n now: () => Date;\n /** Optional spam classifier. When present, its verdict drives the stored\n * status/score/reason; absent → every submission scores 0 (fail-open, clean).\n * Injected so the classifier stays a pure, transport-agnostic leaf. */\n classifySpam?: (n: NormalizedSubmission, turnstile: TurnstileOutcome) => SpamVerdict;\n /** Optional: fleet-wide duplicate/near-duplicate body lookup since `since`. Drives\n * the duplicate-spray signal — the same pitch blasted to many sites shows up as\n * identical (`exact`) or template-substituted (`similar`, token-set Jaccard) bodies.\n * Statuses let the retro re-bucket pick still-'new' prior copies; siteId+email let\n * the caller exempt a genuine same-sender resubmission on the same site. Absent →\n * the check is skipped (fail-open clean). */\n findRecentDuplicates?: (\n message: string,\n since: Date,\n ) => Promise<{\n exact: Array<{ id: string; status: string; siteId: string; email: string }>;\n similar: Array<{ id: string; status: string; siteId: string; email: string }>;\n }>;\n /** Optional: recent non-newsletter submissions from the same email since `since`.\n * Drives the cross-site repeat-sender signal — the fleet's sites are unrelated\n * businesses, so one address contacting 2+ of them within the window is a\n * solicitation tell. Absent → the check is skipped (fail-open clean). */\n listRecentSubmissionsForEmail?: (\n email: string,\n since: Date,\n ) => Promise<Array<{ id: string; siteId: string; status: string }>>;\n /** Optional: retroactively re-bucket prior still-'new' rows once a later copy\n * identifies a spray (the first copy is delivered by design). Implementations\n * must only touch status='new' rows. Best-effort — failures are swallowed. */\n retroBucket?: (ids: string[], reason: string) => Promise<void>;\n /** Optional: POST a newsletter submission to the site's configured webhook\n * (best-effort). Omitted in tests/handlers that don't need it. */\n forwardNewsletter?: (\n webhookUrl: string,\n submission: SubmissionRow,\n site: WebsiteRow,\n ) => Promise<{ ok: boolean; status: number }>;\n /** Optional: add a newsletter submitter to the site's Mailchimp audience\n * (best-effort). Omitted where unused. `tagged:false` reports a member who was\n * upserted but could NOT be tagged — recorded separately, see FANOUT below. */\n addToMailchimp?: (\n site: WebsiteRow,\n submission: SubmissionRow,\n ) => Promise<{ ok: boolean; status: number; tagged?: boolean }>;\n /** Optional: persist the newsletter fan-out outcome on the row (see FANOUT below).\n * Best-effort — failures are swallowed. Absent → the fan-out still runs, just\n * unrecorded (older callers and most tests). */\n stampFanout?: (id: string, fanoutStatus: string) => Promise<void>;\n /** Optional: run the best-effort tail (notify → stamp → fan-out) AFTER the\n * response instead of before it. Production passes Netlify's\n * `context.waitUntil`, which keeps the invocation alive until the promise\n * settles. Absent → the tail runs inline, exactly as it always did; this is a\n * latency change, never a behavioural one.\n *\n * Why it matters: the submitting site waits on this response under an abort\n * budget (forms/client.ts `INGEST_TIMEOUT_MS`). Once the row is written the\n * lead is captured, so every further second spent on email/webhook providers\n * is time in which a captured lead can still be reported to the visitor as a\n * failed submission — which is exactly what happened to 1836dig on\n * 2026-08-03. */\n defer?: (work: Promise<unknown>) => void;\n};\n\nexport type IngestResult =\n | { status: \"accepted\"; submissionId: string; notifyStatus: NotifyStatus | \"deferred\" }\n | { status: \"rejected\"; reason: \"invalid-payload\"; errors: string[] }\n | { status: \"unknown-site\"; slug: string };\n\nexport type ScreenOutDeps = {\n getWebsiteBySlug: (slug: string) => Promise<WebsiteRow | null>;\n recordScreenOut: (siteId: string, reason: \"honeypot\" | \"too-fast\") => Promise<void>;\n};\n\nexport type ScreenOutResult =\n { status: \"recorded\"; slug: string } | { status: \"unknown-site\"; slug: string };\n\n/** Extract the screen-out reason from a beacon body, or null if it isn't one.\n * The beacon key is the reserved `_screenOut` (underscore-namespaced like `_meta`,\n * see payload.ts). The bare `screenOut` key is the DEPRECATED pre-namespacing wire\n * shape — sites run older package versions for a while, so the central receiver\n * keeps accepting it. `_screenOut` wins when both are present. */\nexport function parseScreenOut(payload: unknown): \"honeypot\" | \"too-fast\" | null {\n if (!payload || typeof payload !== \"object\") return null;\n const body = payload as Record<string, unknown>;\n const v = \"_screenOut\" in body ? body[\"_screenOut\"] : body[\"screenOut\"];\n return v === \"honeypot\" || v === \"too-fast\" ? v : null;\n}\n\n/** Resolve the site and record a caught screen-out. Best-effort: a record failure is\n * the caller's to swallow — a missed count must never error a screened bot. */\nexport async function ingestScreenOut(\n deps: ScreenOutDeps,\n slug: string,\n reason: \"honeypot\" | \"too-fast\",\n): Promise<ScreenOutResult> {\n const site = await deps.getWebsiteBySlug(slug);\n if (!site) return { status: \"unknown-site\", slug };\n await deps.recordScreenOut(site.id, reason);\n return { status: \"recorded\", slug };\n}\n\n/**\n * Normalize → resolve site → persist → notify → stamp. The order is load-bearing:\n * the row is written BEFORE notify, and notify/stamp failures are swallowed (logged)\n * so a Resend or Airtable-write-back hiccup can never turn an accepted lead into a 502.\n */\nexport async function ingestSubmission(\n deps: IngestDeps,\n slug: string,\n rawPayload: unknown,\n turnstileInput: TurnstileOutcome | TurnstileVerification = \"unverifiable\",\n): Promise<IngestResult> {\n // Accept either the full verification (the production handler) or a bare outcome\n // string (older callers and virtually every test) — a string simply has no solved-\n // hostname to check. Normalized once so the body has a single shape to reason about.\n const verification: TurnstileVerification =\n typeof turnstileInput === \"string\"\n ? { outcome: turnstileInput, hostname: null }\n : turnstileInput;\n const turnstile = verification.outcome;\n const normalized = normalizeSubmission(rawPayload);\n if (!normalized.ok) {\n return { status: \"rejected\", reason: \"invalid-payload\", errors: normalized.errors };\n }\n // Persist before enrich (#539 Phase 0). The lookup THROWING is a store outage,\n // not an answer — and until 2026-08-23 it was the one await that could cost a\n // lead: the row write comes later, so a thrown lookup 502'd the visitor with\n // nothing recorded anywhere (the 2026-08-17 Airtable quota outage did exactly\n // that, while the submissions store itself was healthy the whole time). With\n // `deadLetter` wired, the lead lands there and the visitor gets an honest\n // \"accepted\"; `db replay-deadletters` runs it through this same function once\n // the lookup recovers, producing a normal row with real classification+notify.\n //\n // Three deliberate boundaries:\n // - A lookup that RESOLVES to null is still `unknown-site` — the store answered,\n // and a junk slug is a rejection, not a lead to save.\n // - A testMode probe rethrows: it persists nothing by design, so there is\n // nothing to save, and swallowing the outage would green the form-e2e audit\n // precisely when central ingest is degraded.\n // - `deadLetter` itself throwing propagates: both stores are down, and the 502\n // is honest — there is nowhere left to put the lead.\n let site: WebsiteRow | null;\n try {\n site = await deps.getWebsiteBySlug(slug);\n } catch (err) {\n if (!deps.deadLetter || isTestMode(rawPayload)) throw err;\n const dl = await deps.deadLetter({\n siteSlug: slug,\n payload: rawPayload,\n turnstile: verification,\n error: String(err),\n receivedAt: deps.now(),\n });\n console.error(\n `[ingest] site lookup failed for '${slug}' — lead dead-lettered as ${dl.id}: ${String(err)}`,\n );\n return { status: \"accepted\", submissionId: dl.id, notifyStatus: \"skipped\" };\n }\n if (!site) return { status: \"unknown-site\", slug };\n\n // Synthetic end-to-end probe (the `form-e2e` fleet audit). A central-only marker\n // on the payload routes the submission away from EVERY real sink: no row is\n // persisted, no spam classification, no operator/autoresponder email, no\n // newsletter fan-out — and Turnstile enforcement is bypassed (the short-circuit\n // sits before that check). The marker therefore grants a bot NO benefit: it\n // reaches no inbox/DB/webhook, so skipping Turnstile costs nothing. This\n // suppression MUST be central — the submitting site alone cannot stop the real\n // inbox firing. Validity + site resolution are still enforced above (a junk body\n // is rejected, an unknown slug is unknown-site), so the marker can't smuggle\n // anything through. Return accepted+skipped so the probe asserts success.\n if (isTestMode(rawPayload)) {\n return { status: \"accepted\", submissionId: \"test-mode\", notifyStatus: \"skipped\" };\n }\n\n const n = normalized.value;\n\n // A site still under construction is where the operator tests their OWN forms:\n // one address, several unrelated sites, minutes apart. That is byte-for-byte the\n // cross-site repeat-sender signature below, so a site in development reliably\n // auto-spams its own builder's test submissions — the row lands `spam_auto`,\n // notify is skipped and the cockpit hides it, which reads exactly like \"the form\n // is broken\" (it did, on 2026-08-17). Spam handling on a site with no real\n // visitors protects nothing, so skip ALL of it: content scoring, the Turnstile\n // escalation, the repeat-sender scan and the duplicate/spray scan — including\n // their retroactive re-bucketing of OTHER sites' rows, which a test submission\n // has no business triggering. Re-enabled the moment the site leaves development.\n const spamHandlingEnabled = site.status !== \"building\";\n\n // Fold the content signals + the Turnstile verdict into ONE spam decision.\n // Absent classifier → treat as clean (fail-open). A throwing classifier is\n // swallowed the same way — a bug in the heuristic must never turn an\n // otherwise-good lead into a 500; it just scores clean. On a `requireTurnstile`\n // site, both an ACTUAL \"fail\" (forged token) AND an \"absent\" token escalate to\n // auto-spam regardless of score — a real browser that renders the widget ALWAYS\n // sends a token, so a completely missing one is the direct-POST-bot signature. A\n // present-but-\"unverifiable\" token (expired/duplicate — a real browser DID render\n // the widget) stays neutral, as does anything on a site that hasn't opted in.\n let verdict: SpamVerdict = { score: 0, reasons: [] };\n if (spamHandlingEnabled && deps.classifySpam) {\n try {\n verdict = deps.classifySpam(n, turnstile);\n } catch (err) {\n console.error(`[ingest] classifySpam threw: ${String(err)}`);\n }\n }\n const reasons = [...verdict.reasons];\n let status: SubmissionStatus = verdict.score >= SPAM_THRESHOLD ? \"spam_auto\" : \"new\";\n if (\n spamHandlingEnabled &&\n site.requireTurnstile &&\n (turnstile === \"fail\" || turnstile === \"absent\")\n ) {\n status = \"spam_auto\";\n const reason = turnstile === \"fail\" ? \"turnstile-required-failed\" : \"turnstile-required-absent\";\n if (!reasons.includes(reason)) reasons.push(reason);\n } else if (\n spamHandlingEnabled &&\n site.requireTurnstile &&\n turnstile === \"pass\" &&\n verification.hostname !== null &&\n !turnstileHostnameAcceptable(verification.hostname, site.url)\n ) {\n // Defense-in-depth vs token farming: the token PASSED, but Cloudflare says it was\n // solved on a host unrelated to this site. Cloudflare domain-binds sitekeys, so\n // this only trips on a loose widget allowlist — still, a passing token from a\n // foreign host accompanying a gated site's submission is not a real visitor. A\n // null hostname (older responses) or an unparseable site.url skips the check\n // entirely (fail-open); subdomains of the site's host (www., previews) match.\n status = \"spam_auto\";\n if (!reasons.includes(\"turnstile-required-hostname\"))\n reasons.push(\"turnstile-required-hostname\");\n }\n\n // Cross-site repeat-sender signal: the fleet's sites are UNRELATED businesses\n // (art gallery, realtor, home builder…), so the same email writing to 2+ different\n // sites within the window is a solicitation tell no single-message scan can see.\n // Same-site repeats alone must NOT trigger — those are genuine follow-ups. The\n // operator explicitly accepts overblocking here (spam_auto is recoverable). Prior\n // still-'new' rows on OTHER sites are retro-bucketed too: the first copy of a\n // spray is delivered by design, so the copy that identifies it also cleans the\n // queue. The scan runs EVEN WHEN the incoming copy is already spam_auto — after the\n // classifier began catching whole spray families, an already-bucketed copy was\n // skipping this scan and the retro cleanup never fired for exactly the sprays it\n // was built for; escalation/reason still only applies when not already spam.\n // Best-effort — a lookup failure never blocks a lead.\n if (spamHandlingEnabled && n.formType !== \"newsletter\" && deps.listRecentSubmissionsForEmail) {\n try {\n const since = new Date(deps.now().getTime() - DUPLICATE_WINDOW_MS);\n const prior = await deps.listRecentSubmissionsForEmail(n.email, since);\n const otherSites = prior.filter((p) => p.siteId !== site.id);\n if (otherSites.length > 0) {\n if (status !== \"spam_auto\") {\n status = \"spam_auto\";\n if (!reasons.includes(\"repeat-sender\")) reasons.push(\"repeat-sender\");\n }\n const retroIds = otherSites.filter((p) => p.status === \"new\").map((p) => p.id);\n if (deps.retroBucket && retroIds.length > 0) {\n try {\n await deps.retroBucket(retroIds, \"retro:repeat-sender\");\n } catch (err) {\n console.error(`[ingest] retroBucket (repeat-sender) threw: ${String(err)}`);\n }\n }\n }\n } catch (err) {\n console.error(`[ingest] listRecentSubmissionsForEmail threw: ${String(err)}`);\n }\n }\n\n // Duplicate/spray signal: the same pitch blasted across the fleet (or repeated) is\n // a bot tell a lone content scan can't see. An identical body ('exact') OR a\n // template-substituted near-copy ('similar' — the live dog-harness spray differed\n // only in greeting; SEO sprays swap the target domain per site) → auto-spam\n // (recoverable). Prior still-'new' copies are retro-bucketed for the same reason\n // as above, and the scan runs even when the incoming copy is already spam_auto\n // (see the repeat-sender note). GENUINE-RESUBMIT EXEMPTION: a match from the SAME\n // sender on the SAME site is a real visitor double-submitting or resending after\n // silence, not spray evidence — without this exemption the resend was silently\n // bucketed AND retro-flipped the delivered original, vanishing an active lead\n // with no signal. Only cross-site or different-sender copies count. Guarded:\n // non-newsletter forms with a real body; the db helper ignores short bodies /\n // small token sets. Best-effort — a lookup failure never blocks a lead.\n if (\n spamHandlingEnabled &&\n n.formType !== \"newsletter\" &&\n n.message !== undefined &&\n deps.findRecentDuplicates\n ) {\n try {\n const since = new Date(deps.now().getTime() - DUPLICATE_WINDOW_MS);\n const dupes = await deps.findRecentDuplicates(n.message, since);\n const senderEmail = n.email.trim().toLowerCase();\n const isOwnResend = (m: { siteId: string; email: string }) =>\n m.siteId === site.id && m.email.trim().toLowerCase() === senderEmail;\n const exact = dupes.exact.filter((m) => !isOwnResend(m));\n const similar = dupes.similar.filter((m) => !isOwnResend(m));\n const reason =\n exact.length > 0 ? \"duplicate-body\" : similar.length > 0 ? \"similar-body\" : null;\n if (reason !== null) {\n if (status !== \"spam_auto\") {\n status = \"spam_auto\";\n if (!reasons.includes(reason)) reasons.push(reason);\n }\n const retroIds = [...exact, ...similar].filter((m) => m.status === \"new\").map((m) => m.id);\n if (deps.retroBucket && retroIds.length > 0) {\n try {\n await deps.retroBucket(retroIds, \"retro:duplicate-body\");\n } catch (err) {\n console.error(`[ingest] retroBucket (duplicate-body) threw: ${String(err)}`);\n }\n }\n }\n } catch (err) {\n console.error(`[ingest] findRecentDuplicates threw: ${String(err)}`);\n }\n }\n const spamReason = reasons.length > 0 ? reasons.join(\",\") : null;\n\n const row = await deps.createSubmission({\n siteId: site.id,\n formType: n.formType,\n name: n.name,\n email: n.email,\n extraFields: n.extraFields,\n status,\n spamScore: verdict.score,\n spamReason,\n // Optional fields spread only when present — exactOptionalPropertyTypes\n // forbids assigning `undefined` to an optional `phone?: string` etc.\n ...(n.phone !== undefined ? { phone: n.phone } : {}),\n ...(n.message !== undefined ? { message: n.message } : {}),\n ...(n.sourceUrl !== undefined ? { sourceUrl: n.sourceUrl } : {}),\n ...(n.utm !== undefined ? { utm: n.utm } : {}),\n submittedAt: deps.now(),\n });\n\n // Auto-spam (and operator-marked spam) is captured but silent: no operator\n // email, no autoresponder, no newsletter fan-out. Skip notify entirely and\n // record the honest \"skipped\" stamp. notify.ts also nulls both builders for\n // these statuses (defense in depth), but short-circuiting here means the\n // injected notify dep is never even invoked for a spam row.\n const isSpam = row.status === \"spam_auto\" || row.status === \"spam\";\n\n // ── best-effort tail ───────────────────────────────────────────────────────\n // notify → stamp → newsletter fan-out. NOTHING below can cost the lead: the\n // row is already durable, and every step here is swallowed+logged rather than\n // allowed to turn an accepted lead into a 502. That is precisely why it does\n // not belong on the visitor's critical path — the submitting site waits on\n // this response under an abort budget (forms/client.ts INGEST_TIMEOUT_MS), so\n // Resend latency used to be able to make a captured lead read as a failed\n // submission in the visitor's browser (1836dig, 2026-08-03).\n //\n // `deps.defer` (Netlify's `context.waitUntil` in production) runs the tail\n // AFTER the response goes out. Absent — every test, and any runtime without\n // post-response execution — it runs inline exactly as before, so this is a\n // latency change and never a behavioural one.\n const runTail = async (): Promise<NotifyStatus> => {\n let notify: { status: NotifyStatus; messageId: string | null };\n if (isSpam) {\n notify = { status: \"skipped\", messageId: null };\n } else {\n try {\n notify = await deps.notify(site, row);\n } catch (err) {\n console.error(`[ingest] notify threw: ${String(err)}`);\n notify = { status: \"failed\", messageId: null };\n }\n }\n try {\n await deps.stampNotified(row.id, notify.status, notify.messageId);\n } catch (err) {\n console.error(`[ingest] stampNotified failed: ${String(err)}`);\n }\n\n await runFanout();\n return notify.status;\n };\n\n // Newsletter fan-out: each configured destination fires best-effort and is\n // swallowed+logged — the lead is already persisted; never turn it into a 502.\n // Guarded on the row status so a spam signup is never forwarded to a site\n // webhook or added to a Mailchimp audience.\n //\n // FANOUT provenance (2026-07-31): the outcome is ALSO recorded on the row, one\n // `<destination>:<outcome>` token per attempt, comma-joined in attempt order —\n // `webhook:ok,mailchimp:401`. Outcome is `ok`, the HTTP status of a non-2xx\n // (`0` for a network error / misconfiguration, see mailchimp.ts), or `threw`.\n // `mailchimp-tags:failed` is appended when the member was upserted but the tag\n // write did not land. Until this existed the results were console.error-only, so\n // an expired Mailchimp key stopped signups reaching the audience while the row\n // still read `notify=sent` — healthy-looking, with the failure visible nowhere the\n // operator ever looks. Nothing attempted → nothing stamped (null stays \"no\n // destination configured\", NOT \"we tried and lost the answer\"). The stamp is\n // best-effort like everything else here: a provenance write must never cost a lead.\n // A const arrow, not a hoisted declaration: `site` is narrowed non-null above,\n // and that narrowing only survives into a closure created after it. Declared\n // below runTail (which calls it) but before either call site, so there is no TDZ.\n const runFanout = async (): Promise<void> => {\n const fanout: string[] = [];\n if (n.formType === \"newsletter\" && !isSpam) {\n if (site.newsletterWebhook && deps.forwardNewsletter) {\n try {\n const fwd = await deps.forwardNewsletter(site.newsletterWebhook, row, site);\n if (!fwd.ok)\n console.error(`[ingest] newsletter webhook → ${fwd.status} for ${site.name}`);\n fanout.push(fwd.ok ? \"webhook:ok\" : `webhook:${fwd.status}`);\n } catch (err) {\n console.error(`[ingest] newsletter webhook threw: ${String(err)}`);\n fanout.push(\"webhook:threw\");\n }\n }\n if (site.mailchimpApiKey && site.mailchimpAudienceId && deps.addToMailchimp) {\n try {\n const mc = await deps.addToMailchimp(site, row);\n if (!mc.ok) console.error(`[ingest] mailchimp add → ${mc.status} for ${site.name}`);\n fanout.push(mc.ok ? \"mailchimp:ok\" : `mailchimp:${mc.status}`);\n // Only meaningful alongside a successful add — a failed add was never tagged\n // either, and one token per real problem keeps the row readable.\n if (mc.ok && mc.tagged === false) {\n console.error(`[ingest] mailchimp tags not applied for ${site.name}`);\n fanout.push(\"mailchimp-tags:failed\");\n }\n } catch (err) {\n console.error(`[ingest] mailchimp add threw: ${String(err)}`);\n fanout.push(\"mailchimp:threw\");\n }\n }\n }\n if (fanout.length > 0 && deps.stampFanout) {\n try {\n await deps.stampFanout(row.id, fanout.join(\",\"));\n } catch (err) {\n console.error(`[ingest] stampFanout failed: ${String(err)}`);\n }\n }\n };\n\n if (deps.defer) {\n // A rejection escaping here would land as an unhandled rejection in the\n // platform's post-response context, where nothing is left to catch it — so\n // the boundary is made unrejectable. Everything inside is already swallowed;\n // this guards the shape, not a known throw.\n deps.defer(\n runTail().catch((err) => {\n console.error(`[ingest] deferred tail threw: ${String(err)}`);\n }),\n );\n // The lead is durable and the response can go out now. The real notify\n // outcome lands on the ROW via stampNotified moments later — this field is\n // only ever read by callers wanting the in-request outcome, which by\n // definition does not exist once the tail is deferred.\n return { status: \"accepted\", submissionId: row.id, notifyStatus: \"deferred\" };\n }\n return { status: \"accepted\", submissionId: row.id, notifyStatus: await runTail() };\n}\n\n/** True when `a` and `b` are the same host or one is a subdomain of the other\n * (case-insensitive): `www.reddoorla.com` vs `reddoorla.com` matches both ways.\n * Exported for tests. PURE. */\nexport function hostsMatch(a: string, b: string): boolean {\n const ha = a.trim().toLowerCase();\n const hb = b.trim().toLowerCase();\n if (ha.length === 0 || hb.length === 0) return false;\n return ha === hb || ha.endsWith(`.${hb}`) || hb.endsWith(`.${ha}`);\n}\n\n/** Whether a passing token's solved-hostname is acceptable for the site at `siteUrl`.\n * An unparseable/hostless `siteUrl` returns TRUE — the check self-disables rather\n * than punishing a possibly-real visitor for an operator data problem (fail-open,\n * same philosophy as verifyTurnstile). PURE. */\nexport function turnstileHostnameAcceptable(tokenHostname: string, siteUrl: string): boolean {\n let siteHost: string;\n try {\n siteHost = new URL(siteUrl).hostname;\n } catch {\n return true;\n }\n if (!siteHost) return true;\n return hostsMatch(tokenHostname, siteHost);\n}\n\n/** True when an untrusted ingest payload carries the synthetic-probe marker\n * (top-level `testMode: true`). Read from the RAW payload so the branch never\n * depends on normalization internals; any non-`true` value is ignored (a real\n * visitor's form never sets it — the starter only forwards it when the submitted\n * form field `testMode` equals \"true\"). */\nexport function isTestMode(rawPayload: unknown): boolean {\n if (!rawPayload || typeof rawPayload !== \"object\") return false;\n return (rawPayload as Record<string, unknown>).testMode === true;\n}\n"],"mappings":";;;;;;;;;;;AA6CA,IAAM,aAAa,oBAAI,IAAI;AAAA,EACzB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAKD,IAAM,iBAAiB,oBAAI,IAAI,CAAC,aAAa,eAAe,WAAW,CAAC;AAExE,IAAM,WAAW;AAEjB,SAAS,IAAI,GAAoB;AAC/B,SAAO,OAAO,MAAM,WAAW,EAAE,KAAK,IAAI;AAC5C;AASA,SAAS,gBAAgB,KAA+B;AACtD,QAAM,IAAI,IAAI,GAAG;AACjB,MAAI,MAAM,GAAI,QAAO;AACrB,SAAQ,sBAA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names":[]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  withRecipe
3
- } from "./chunk-3G25KIWW.js";
3
+ } from "./chunk-ZTPPCHDB.js";
4
4
  import {
5
5
  readPackageJson,
6
6
  writePackageJson
@@ -96,4 +96,4 @@ async function convertToPnpm(site, opts = {}) {
96
96
  export {
97
97
  convertToPnpm
98
98
  };
99
- //# sourceMappingURL=chunk-XIDUYLSR.js.map
99
+ //# sourceMappingURL=chunk-7CJ3DVZW.js.map
@@ -9,6 +9,18 @@ function isValidToken(s) {
9
9
  function newProspectAuditId() {
10
10
  return `pa_${crypto.randomUUID()}`;
11
11
  }
12
+ function siteKey(url) {
13
+ const raw = url.trim();
14
+ if (raw === "") return "";
15
+ try {
16
+ const u = new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(raw) ? raw : `https://${raw}`);
17
+ const host = u.hostname.toLowerCase().replace(/^www\./, "");
18
+ const path = u.pathname.replace(/\/+$/, "");
19
+ return `${host}${path}`;
20
+ } catch {
21
+ return raw;
22
+ }
23
+ }
12
24
  async function createProspectAudit(db, audit) {
13
25
  const id = newProspectAuditId();
14
26
  const token = generateToken();
@@ -16,6 +28,7 @@ async function createProspectAudit(db, audit) {
16
28
  id,
17
29
  token,
18
30
  url: audit.url,
31
+ site_key: siteKey(audit.url),
19
32
  business: audit.business,
20
33
  created_at: (/* @__PURE__ */ new Date()).toISOString(),
21
34
  status: audit.status ?? "complete",
@@ -40,9 +53,10 @@ export {
40
53
  generateToken,
41
54
  isValidToken,
42
55
  newProspectAuditId,
56
+ siteKey,
43
57
  createProspectAudit,
44
58
  getProspectAuditByToken,
45
59
  MAX_RECENT_PROSPECT_AUDITS,
46
60
  listRecentProspectAudits
47
61
  };
48
- //# sourceMappingURL=chunk-NYUYNYQL.js.map
62
+ //# sourceMappingURL=chunk-7MKT4I5T.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/db/prospect-audits.ts"],"sourcesContent":["import { randomBytes } from \"node:crypto\";\nimport type { Db } from \"./client.js\";\n\n/** 16 random bytes → 22-char base64url string: unguessable, URL-safe. */\nexport function generateToken(): string {\n return randomBytes(16).toString(\"base64url\");\n}\n\n/** Anything not exactly generateToken()-shaped is a probe, not a report. */\nexport function isValidToken(s: string): boolean {\n return /^[A-Za-z0-9_-]{22}$/.test(s);\n}\n\n/** Opaque, collision-free id (mirrors newSubmissionId / newDeadLetterId).\n * crypto is a Node 20 global — no new dep. Nothing reads this format; `token`\n * is the public handle. */\nexport function newProspectAuditId(): string {\n return `pa_${crypto.randomUUID()}`;\n}\n\n/** \"complete\" when every pipeline stage succeeded; \"partial\" when any stage\n * failed or was deliberately skipped (StageResult's `ok: false` covers\n * both — the pipeline doesn't distinguish them at this layer). The report\n * itself already degrades each failed section to \"not measured\"; this is\n * what lets a future dashboard tell complete from partial without\n * deserializing the whole result_json. */\nexport type ProspectAuditStatus = \"complete\" | \"partial\";\n\n/**\n * The lineage handle for a site: one key for every way of writing its address.\n *\n * `url` is kept exactly as it was given, because what we audited is a fact\n * about the run. It is the wrong thing to group by, though, and the corpus\n * already proves it — `beachfrontdentistry.com` and `beachfrontdentistry.com/`\n * are two separate histories in the table today, as are the two spellings of\n * ludlowkingsley.com. Nothing has broken only because nothing yet compares two\n * audits of one site. The moment the report offers a before and an after, a\n * trailing slash turns a returning client into a stranger.\n *\n * Scheme, a leading \"www.\", a trailing slash, a query string and a fragment all\n * go: none of them distinguish one site from another. The path stays, because a\n * site living in a subdirectory genuinely is a different site.\n *\n * Never throws. A key we cannot compute must not take an audit down with it —\n * an unparseable input falls back to its trimmed self, which groups nothing and\n * so is no worse than having no key at all.\n */\nexport function siteKey(url: string): string {\n const raw = url.trim();\n if (raw === \"\") return \"\";\n try {\n const u = new URL(/^[a-z][a-z0-9+.-]*:\\/\\//i.test(raw) ? raw : `https://${raw}`);\n const host = u.hostname.toLowerCase().replace(/^www\\./, \"\");\n const path = u.pathname.replace(/\\/+$/, \"\");\n return `${host}${path}`;\n } catch {\n return raw;\n }\n}\n\nexport type NewProspectAudit = {\n url: string;\n business: string | null;\n resultJson: string;\n /** Defaults to \"complete\" — the column's own SQL default — for callers\n * (tests, ad-hoc scripts) that don't track per-stage outcomes. The\n * prospect-audit CLI, the only real writer, always computes and passes\n * this explicitly. */\n status?: ProspectAuditStatus;\n};\n\nexport async function createProspectAudit(\n db: Db,\n audit: NewProspectAudit,\n): Promise<{ id: string; token: string }> {\n const id = newProspectAuditId();\n const token = generateToken();\n await db\n .insertInto(\"prospect_audits\")\n .values({\n id,\n token,\n url: audit.url,\n site_key: siteKey(audit.url),\n business: audit.business,\n created_at: new Date().toISOString(),\n status: audit.status ?? \"complete\",\n result_json: audit.resultJson,\n })\n .execute();\n return { id, token };\n}\n\nexport type ProspectAuditRow = {\n id: string;\n url: string;\n business: string | null;\n created_at: string;\n status: string;\n result_json: string;\n};\n\nexport async function getProspectAuditByToken(\n db: Db,\n token: string,\n): Promise<ProspectAuditRow | null> {\n const row = await db\n .selectFrom(\"prospect_audits\")\n .select([\"id\", \"url\", \"business\", \"created_at\", \"status\", \"result_json\"])\n .where(\"token\", \"=\", token)\n .executeTakeFirst();\n return row ?? null;\n}\n\n/** The columns the cockpit's /audits listing page shows. Deliberately NOT\n * `result_json` — large, and useless to a list — but `token` IS selected:\n * the listing needs it to build each row's `/r/{token}` link, so it's\n * rendered only into an href, never displayed as a raw value. */\nexport type ProspectAuditListItem = {\n id: string;\n token: string;\n url: string;\n business: string | null;\n status: string;\n created_at: string;\n};\n\n/** Ceiling on `listRecentProspectAudits`' `limit`, enforced defensively (a\n * caller passing 10_000 must not get 10_000 rows) — well past anything a\n * listing page would ever render on one screen. */\nexport const MAX_RECENT_PROSPECT_AUDITS = 100;\n\n/** Clamp a caller-supplied limit into [1, MAX_RECENT_PROSPECT_AUDITS], with a\n * safe fallback of 1 for anything non-finite (NaN, ±Infinity) rather than\n * letting a bad input reach the query unclamped. */\nfunction clampLimit(limit: number): number {\n const n = Number.isFinite(limit) ? Math.trunc(limit) : 1;\n return Math.min(Math.max(n, 1), MAX_RECENT_PROSPECT_AUDITS);\n}\n\n/** Newest-first audits for the cockpit's /audits listing page, capped both\n * defensively (see clampLimit) and by an index (migration 0010) so the\n * ORDER BY never falls back to a raw scan + a temp b-tree sort — see the\n * EXPLAIN-query-plan gate, tests/db/query-plans.test.ts. */\nexport async function listRecentProspectAudits(\n db: Db,\n limit: number,\n): Promise<ProspectAuditListItem[]> {\n return db\n .selectFrom(\"prospect_audits\")\n .select([\"id\", \"token\", \"url\", \"business\", \"status\", \"created_at\"])\n .orderBy(\"created_at\", \"desc\")\n .limit(clampLimit(limit))\n .execute();\n}\n"],"mappings":";AAAA,SAAS,mBAAmB;AAIrB,SAAS,gBAAwB;AACtC,SAAO,YAAY,EAAE,EAAE,SAAS,WAAW;AAC7C;AAGO,SAAS,aAAa,GAAoB;AAC/C,SAAO,sBAAsB,KAAK,CAAC;AACrC;AAKO,SAAS,qBAA6B;AAC3C,SAAO,MAAM,OAAO,WAAW,CAAC;AAClC;AA6BO,SAAS,QAAQ,KAAqB;AAC3C,QAAM,MAAM,IAAI,KAAK;AACrB,MAAI,QAAQ,GAAI,QAAO;AACvB,MAAI;AACF,UAAM,IAAI,IAAI,IAAI,2BAA2B,KAAK,GAAG,IAAI,MAAM,WAAW,GAAG,EAAE;AAC/E,UAAM,OAAO,EAAE,SAAS,YAAY,EAAE,QAAQ,UAAU,EAAE;AAC1D,UAAM,OAAO,EAAE,SAAS,QAAQ,QAAQ,EAAE;AAC1C,WAAO,GAAG,IAAI,GAAG,IAAI;AAAA,EACvB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAaA,eAAsB,oBACpB,IACA,OACwC;AACxC,QAAM,KAAK,mBAAmB;AAC9B,QAAM,QAAQ,cAAc;AAC5B,QAAM,GACH,WAAW,iBAAiB,EAC5B,OAAO;AAAA,IACN;AAAA,IACA;AAAA,IACA,KAAK,MAAM;AAAA,IACX,UAAU,QAAQ,MAAM,GAAG;AAAA,IAC3B,UAAU,MAAM;AAAA,IAChB,aAAY,oBAAI,KAAK,GAAE,YAAY;AAAA,IACnC,QAAQ,MAAM,UAAU;AAAA,IACxB,aAAa,MAAM;AAAA,EACrB,CAAC,EACA,QAAQ;AACX,SAAO,EAAE,IAAI,MAAM;AACrB;AAWA,eAAsB,wBACpB,IACA,OACkC;AAClC,QAAM,MAAM,MAAM,GACf,WAAW,iBAAiB,EAC5B,OAAO,CAAC,MAAM,OAAO,YAAY,cAAc,UAAU,aAAa,CAAC,EACvE,MAAM,SAAS,KAAK,KAAK,EACzB,iBAAiB;AACpB,SAAO,OAAO;AAChB;AAkBO,IAAM,6BAA6B;AAK1C,SAAS,WAAW,OAAuB;AACzC,QAAM,IAAI,OAAO,SAAS,KAAK,IAAI,KAAK,MAAM,KAAK,IAAI;AACvD,SAAO,KAAK,IAAI,KAAK,IAAI,GAAG,CAAC,GAAG,0BAA0B;AAC5D;AAMA,eAAsB,yBACpB,IACA,OACkC;AAClC,SAAO,GACJ,WAAW,iBAAiB,EAC5B,OAAO,CAAC,MAAM,SAAS,OAAO,YAAY,UAAU,YAAY,CAAC,EACjE,QAAQ,cAAc,MAAM,EAC5B,MAAM,WAAW,KAAK,CAAC,EACvB,QAAQ;AACb;","names":[]}
@@ -3,7 +3,7 @@ import {
3
3
  } from "./chunk-J7SZQUCW.js";
4
4
  import {
5
5
  withRecipe
6
- } from "./chunk-3G25KIWW.js";
6
+ } from "./chunk-ZTPPCHDB.js";
7
7
  import {
8
8
  bumpDep,
9
9
  readPackageJson,
@@ -243,4 +243,4 @@ async function upgradeSvelte4to5(site, opts = {}) {
243
243
  export {
244
244
  upgradeSvelte4to5
245
245
  };
246
- //# sourceMappingURL=chunk-Z3KYFUN6.js.map
246
+ //# sourceMappingURL=chunk-B6NUZ2ZX.js.map