@canonry/canonry 7.110.0 → 7.112.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 (149) hide show
  1. package/README.md +3 -2
  2. package/assets/agent-workspace/skills/aero/SKILL.md +12 -3
  3. package/assets/agent-workspace/skills/aero/references/agent-operations.md +7 -2
  4. package/assets/agent-workspace/skills/aero/references/ai-traffic-tracking.md +5 -3
  5. package/assets/agent-workspace/skills/aero/references/getting-started.md +326 -0
  6. package/assets/agent-workspace/skills/aero/soul.md +1 -1
  7. package/assets/agent-workspace/skills/canonry/SKILL.md +9 -3
  8. package/assets/agent-workspace/skills/canonry/references/aeo-analysis.md +1 -1
  9. package/assets/agent-workspace/skills/canonry/references/ai-traffic-tracking.md +5 -3
  10. package/assets/agent-workspace/skills/canonry/references/canonry-cli.md +5 -2
  11. package/assets/agent-workspace/skills/canonry/references/getting-started.md +328 -0
  12. package/assets/agent-workspace/skills/canonry/references/server-side-traffic.md +4 -0
  13. package/assets/assets/{AccessControls-DmKPF5t5.js → AccessControls-BxtFDXYH.js} +1 -1
  14. package/assets/assets/{AgentSetupPage-BvoJ7cu0.js → AgentSetupPage-q1Ku1PAd.js} +1 -1
  15. package/assets/assets/{AuditHistoryPanel-GHjaPPXk.js → AuditHistoryPanel-6EnlABwM.js} +1 -1
  16. package/assets/assets/{BacklinksPage-Ca3l7bel.js → BacklinksPage-BaHCJEuK.js} +1 -1
  17. package/assets/assets/{ChartPrimitives-CJLgYfSw.js → ChartPrimitives-C3lJj3eO.js} +1 -1
  18. package/assets/assets/{HistoryPage-HqdlYIsd.js → HistoryPage-B_NVeDCn.js} +1 -1
  19. package/assets/assets/{MeasurementPropertyPage-D71Ki-q4.js → MeasurementPropertyPage-DxCRxoIF.js} +1 -1
  20. package/assets/assets/{ProjectPage-wGYGNnLC.js → ProjectPage-BjGsilZJ.js} +3 -3
  21. package/assets/assets/{RunsPage-CeXFTDg4.js → RunsPage-9T1OrQw3.js} +1 -1
  22. package/assets/assets/{ServerTrafficSection-BZVlcCO2.js → ServerTrafficSection-iUdFKWEc.js} +1 -1
  23. package/assets/assets/{SettingsPage-MiW1TGtF.js → SettingsPage-BswQYkkB.js} +1 -1
  24. package/assets/assets/{ToneBadge-BXxSLZUc.js → ToneBadge-CWufDJgM.js} +2 -2
  25. package/assets/assets/{TrafficPage-1ZXZ2BLa.js → TrafficPage-DN9DxoWm.js} +1 -1
  26. package/assets/assets/{TrafficSourceDetailPage-BJPiUWus.js → TrafficSourceDetailPage-D6TdTyP-.js} +1 -1
  27. package/assets/assets/{account-context-DHUo7ntg.js → account-context-CyE8qMvH.js} +1 -1
  28. package/assets/assets/{agent-trust-copy-x8ECjEJu.js → agent-trust-copy-CinW-f_8.js} +1 -1
  29. package/assets/assets/{card-bE38V9NH.js → card-CI9gz2Hb.js} +1 -1
  30. package/assets/assets/{index-Ce3zYiH3.js → index-DshFRkPM.js} +3 -3
  31. package/assets/assets/{query-client-CBtgvGgy.js → query-client-BlAtm9zS.js} +1 -1
  32. package/assets/assets/{react-query-CsgUn_pT.js → react-query-DE_LaZkX.js} +1 -1
  33. package/assets/assets/{react-sigma_core.esm.min-DeLn6mIk.js → react-sigma_core.esm.min-CZkN6sL0.js} +1 -1
  34. package/assets/assets/{server-traffic-Dwwd7cw6.js → server-traffic-Ci9JbS2U.js} +1 -1
  35. package/assets/assets/{service-Bq_5mBI4.js → service-CiYDMju_.js} +1 -1
  36. package/assets/index.html +8 -8
  37. package/dist/{ads-VITOHLIW.js → ads-WRMNYPJ7.js} +3 -3
  38. package/dist/{agent-N57IKFTH.js → agent-V4PAGAPZ.js} +7 -7
  39. package/dist/{agent-ask-VPK4ED7D.js → agent-ask-3LAAT4WN.js} +3 -3
  40. package/dist/{agent-conversations-DPEGQ5NJ.js → agent-conversations-TVNDZY54.js} +3 -3
  41. package/dist/{agent-journeys-7AS543HY.js → agent-journeys-UB7ZGAKP.js} +3 -3
  42. package/dist/{agent-memory-OKKNU2MA.js → agent-memory-RWF2WODB.js} +3 -3
  43. package/dist/{agent-providers-JZGGMH5H.js → agent-providers-77A45KZD.js} +3 -3
  44. package/dist/{agent-transcript-AICHEB4B.js → agent-transcript-K5WZJHJX.js} +3 -3
  45. package/dist/{analytics-FXNYSIAY.js → analytics-RNSYOGUP.js} +3 -3
  46. package/dist/{apply-DYYB2I2S.js → apply-UU6GFYIJ.js} +3 -3
  47. package/dist/{backfill-CXKKDOST.js → backfill-DOYPYZJL.js} +10 -10
  48. package/dist/{backlinks-442C4H4M.js → backlinks-UKRILGDJ.js} +3 -3
  49. package/dist/{bing-HRSXPL7O.js → bing-P6GTLGIP.js} +3 -3
  50. package/dist/{bootstrap-U5UVQDHJ.js → bootstrap-BRXDKCNB.js} +10 -10
  51. package/dist/{cdp-JSOEQZJJ.js → cdp-CPGVPWTU.js} +7 -7
  52. package/dist/{chunk-JXFFKZOI.js → chunk-2LXLJXTG.js} +2 -2
  53. package/dist/{chunk-OJYY6W5S.js → chunk-4ALKLWSQ.js} +631 -391
  54. package/dist/{chunk-ZVKWDSKW.js → chunk-4PMS7CAF.js} +2 -2
  55. package/dist/{chunk-7GU4F2QO.js → chunk-4WXNCSYL.js} +2 -2
  56. package/dist/{chunk-FRKHFU6D.js → chunk-7IF576RC.js} +5 -5
  57. package/dist/{chunk-JJ7RXQ2W.js → chunk-AZPWF42S.js} +7 -3
  58. package/dist/{chunk-EU6JYD3C.js → chunk-B27F7C6S.js} +5 -5
  59. package/dist/{chunk-TV6BFBRI.js → chunk-C44S7EE7.js} +4 -4
  60. package/dist/{chunk-YW6J3STO.js → chunk-CIDXBCEW.js} +1 -1
  61. package/dist/{chunk-YKEXZBB4.js → chunk-DZCJNSBY.js} +1 -1
  62. package/dist/{chunk-5RMDU4MM.js → chunk-F6CYO37C.js} +7 -7
  63. package/dist/{chunk-HX4KJWQO.js → chunk-I4YRKF6G.js} +3 -3
  64. package/dist/{chunk-FEIDW5BU.js → chunk-JCK5TDIU.js} +73 -5
  65. package/dist/{chunk-QXBHZSOW.js → chunk-JHAG6DEG.js} +4 -4
  66. package/dist/{chunk-UC2LPOW4.js → chunk-KYZ5A7AX.js} +1 -1
  67. package/dist/{chunk-Q3IXAH34.js → chunk-LGAQXH3L.js} +1 -1
  68. package/dist/{chunk-A334LHJ7.js → chunk-M2RTTCLC.js} +3 -3
  69. package/dist/{chunk-VYPDVWRG.js → chunk-N5K35MDQ.js} +1 -1
  70. package/dist/{chunk-S2I5FPQC.js → chunk-NICTKJ3O.js} +1 -1
  71. package/dist/{chunk-5SN2O7QH.js → chunk-NLU2MMFA.js} +1 -1
  72. package/dist/{chunk-3AVO5OWE.js → chunk-OBDRDAIK.js} +1 -1
  73. package/dist/{chunk-ZVLZ7YFW.js → chunk-PT3VROG7.js} +378 -370
  74. package/dist/{chunk-ES7XSOBY.js → chunk-Q4XHWZDT.js} +1 -1
  75. package/dist/{chunk-XS3S3UQE.js → chunk-R4PQ7D32.js} +7 -7
  76. package/dist/{chunk-ME74SV2T.js → chunk-S6ULO6H5.js} +1 -1
  77. package/dist/{chunk-RHY7GL5R.js → chunk-SJD3ZAEH.js} +2 -2
  78. package/dist/{chunk-M7R7GSO5.js → chunk-SNL4C4BV.js} +2 -2
  79. package/dist/{chunk-4CTVYOBQ.js → chunk-TDRPVIUB.js} +1 -1
  80. package/dist/{chunk-66OTF2QQ.js → chunk-TDSISMOJ.js} +25 -23
  81. package/dist/{chunk-3WAGCCAO.js → chunk-W3UYVNYQ.js} +1 -1
  82. package/dist/{chunk-HH4XK3FX.js → chunk-WHBLQJGZ.js} +1 -1
  83. package/dist/{chunk-DMCJJ5FT.js → chunk-Y6D7K63F.js} +3 -3
  84. package/dist/{chunk-HGKB6J7I.js → chunk-YN7OV22K.js} +4 -4
  85. package/dist/{chunk-QIGC5JGR.js → chunk-YWKALX6A.js} +4 -4
  86. package/dist/{chunk-VDAC54IW.js → chunk-YXCMVHYJ.js} +38 -7
  87. package/dist/{chunk-35H5E662.js → chunk-ZMCRVQ6Q.js} +1 -1
  88. package/dist/{chunk-ZABO7FFF.js → chunk-ZVDUBOE4.js} +17 -7
  89. package/dist/{citations-A6QP2QOT.js → citations-GW2ELWME.js} +4 -4
  90. package/dist/{cli-catalog-OJT3WVRE.js → cli-catalog-PDU4Z4IO.js} +3 -3
  91. package/dist/{cli-commands-KQQPOXIP.js → cli-commands-XWIWF4VG.js} +7 -7
  92. package/dist/cli.js +13 -13
  93. package/dist/{competitor-AY5SURO6.js → competitor-MS4P6GJ4.js} +3 -3
  94. package/dist/{content-UZJF7XQV.js → content-3QQRT3Q4.js} +3 -3
  95. package/dist/{dashboard-IXNMMT5P.js → dashboard-FDVY7CMI.js} +6 -6
  96. package/dist/{demo-Y7DDERG7.js → demo-WRF3ZSQ5.js} +1 -1
  97. package/dist/{demo-server-PNPTTPGQ.js → demo-server-Q77EUE5A.js} +12 -12
  98. package/dist/{discover-45FOFNGO.js → discover-BAKAHH5X.js} +4 -4
  99. package/dist/{discover-eval-CJ5G32A6.js → discover-eval-KMYMVZVX.js} +3 -3
  100. package/dist/{doctor-2R4J6QC7.js → doctor-OAYNGBBT.js} +3 -3
  101. package/dist/{evidence-HDUJMIIR.js → evidence-FEDSZTLW.js} +3 -3
  102. package/dist/{export-cmd-3AXP4C3S.js → export-cmd-OYQVBE5C.js} +3 -3
  103. package/dist/{ga-RYK2FEEH.js → ga-MWJQ2S4D.js} +3 -3
  104. package/dist/{gbp-TAA3TNDA.js → gbp-K4FXHF6N.js} +3 -3
  105. package/dist/{google-62PQ4SMC.js → google-B6VUPLQN.js} +4 -4
  106. package/dist/{google-marketing-UWGFDUUZ.js → google-marketing-3KKTACAA.js} +1 -1
  107. package/dist/{health-cmd-ZDHMZLYQ.js → health-cmd-YEHYFXEN.js} +4 -4
  108. package/dist/{history-RVBQUMCX.js → history-5EYU4PQT.js} +3 -3
  109. package/dist/index.d.ts +30 -30
  110. package/dist/index.js +26 -26
  111. package/dist/{init-XP3J3HPB.js → init-2HLTEB5Y.js} +12 -12
  112. package/dist/{insights-I2YS7U6L.js → insights-MW5VTF7N.js} +3 -3
  113. package/dist/intelligence-service-PTAA5WJB.js +16 -0
  114. package/dist/{journeys-BELWHYCZ.js → journeys-YW2IWDMN.js} +3 -3
  115. package/dist/{keys-XDILBZFM.js → keys-RRT26LGV.js} +3 -3
  116. package/dist/{keyword-BQ4ECK2Z.js → keyword-KSN3JTCX.js} +3 -3
  117. package/dist/{logs-UAZUYRCJ.js → logs-IPAE4F4W.js} +3 -3
  118. package/dist/{mcp-4262JRAS.js → mcp-WJR6RKYK.js} +4 -4
  119. package/dist/mcp.js +10 -10
  120. package/dist/{measurement-plan-D4DFV7XU.js → measurement-plan-DGLUEK7M.js} +5 -5
  121. package/dist/{notify-TIAGVEYL.js → notify-3QOG6NWS.js} +3 -3
  122. package/dist/{organic-evidence-2TUODD26.js → organic-evidence-M3VSSLQR.js} +3 -3
  123. package/dist/{overview-WP2DO3GW.js → overview-7RRCHUWZ.js} +5 -5
  124. package/dist/{project-OOUUH5QM.js → project-T3JZJPVK.js} +3 -3
  125. package/dist/{project-setup-HBKPIBNL.js → project-setup-Y6DSDF4V.js} +3 -3
  126. package/dist/{query-M7XT5UL3.js → query-24JZPB3M.js} +3 -3
  127. package/dist/{research-O36LMQ6N.js → research-ERVKTKMV.js} +3 -3
  128. package/dist/{results-export-EQWWL2FH.js → results-export-KSGIWPAM.js} +3 -3
  129. package/dist/{run-2I7SGZWI.js → run-XX6YUJRI.js} +5 -5
  130. package/dist/{schedule-UIPFPM64.js → schedule-JBZENJ2V.js} +3 -3
  131. package/dist/{search-L3BSPUWL.js → search-V67KUYIZ.js} +3 -3
  132. package/dist/{serve-CKQIXMZH.js → serve-HTQ76BFW.js} +27 -27
  133. package/dist/{session-JMUEO4JX.js → session-AJ6R6K4B.js} +14 -14
  134. package/dist/{settings-CCYLUD6M.js → settings-KVKWFTJZ.js} +3 -3
  135. package/dist/{sitemaps-QKEA3DLO.js → sitemaps-UDIC4YUU.js} +3 -3
  136. package/dist/{skills-6QCTDYJX.js → skills-35CPSNXM.js} +2 -2
  137. package/dist/{snapshot-SPVUDPYM.js → snapshot-OHGM7JBF.js} +3 -3
  138. package/dist/{src-TV6FYYJC.js → src-GNBUAHT7.js} +2 -2
  139. package/dist/{status-FU5K5ZIP.js → status-GKWSTMUV.js} +5 -5
  140. package/dist/{technical-aeo-A2UNMVHB.js → technical-aeo-IHQYV4TT.js} +3 -3
  141. package/dist/{telemetry-4UAREPKB.js → telemetry-AA2CONG2.js} +4 -4
  142. package/dist/{tools-OLOHKI7B.js → tools-CWNRV7PQ.js} +11 -11
  143. package/dist/{traffic-3TQUDBQB.js → traffic-F7WR32VB.js} +55 -13
  144. package/dist/{trends-IHC2MH5V.js → trends-YB2GNT75.js} +3 -3
  145. package/dist/{users-TYU5PIYM.js → users-PXTIUGXI.js} +3 -3
  146. package/dist/{visibility-stats-BWJF57ON.js → visibility-stats-KSPE4GHQ.js} +4 -4
  147. package/dist/{wordpress-T4CVB32J.js → wordpress-YGSH5MSK.js} +3 -3
  148. package/package.json +2 -2
  149. package/dist/intelligence-service-OHEFN77N.js +0 -16
@@ -19,14 +19,14 @@ import {
19
19
  normalizeTrafficPathPattern,
20
20
  sessionizeJourneyRequests,
21
21
  verifyRequestSignature
22
- } from "./chunk-ME74SV2T.js";
22
+ } from "./chunk-S6ULO6H5.js";
23
23
  import {
24
24
  currentOutcomeAttribution,
25
25
  getRequestContext,
26
26
  registerRequestContext,
27
27
  requestAuditIdentity,
28
28
  sanitizeRequestContext
29
- } from "./chunk-VYPDVWRG.js";
29
+ } from "./chunk-N5K35MDQ.js";
30
30
  import {
31
31
  RawEventSampleEventTypes,
32
32
  SentimentIdempotencyConflict,
@@ -190,7 +190,7 @@ import {
190
190
  userSessions,
191
191
  users,
192
192
  writeNegativeReviewMaxStars
193
- } from "./chunk-3AVO5OWE.js";
193
+ } from "./chunk-OBDRDAIK.js";
194
194
  import {
195
195
  ADS_ACTIVATE_SCOPE,
196
196
  ADS_ACTIVATION_ABSOLUTE_MAX_ENTITIES,
@@ -461,6 +461,7 @@ import {
461
461
  SiteCrawlUrlVersionFilters,
462
462
  SiteHealthLinkKinds,
463
463
  SiteHealthTemplateDetections,
464
+ TRAFFIC_EVENT_GROUP_BY_HINT,
464
465
  TRAFFIC_EVENT_KIND_FILTER_HINT,
465
466
  TREND_SURFACE_DEFAULT_WINDOW,
466
467
  TrafficEventConfidences,
@@ -1069,6 +1070,7 @@ import {
1069
1070
  parseRunError,
1070
1071
  parseStoredMeasurementPlanAnyVersion,
1071
1072
  parseTrafficAnalyticsPeriod,
1073
+ parseTrafficEventGroupBy,
1072
1074
  parseTrafficEventKindFilter,
1073
1075
  parseWindow,
1074
1076
  parseWindowIn,
@@ -1372,7 +1374,7 @@ import {
1372
1374
  wordpressSchemaDeployResultDtoSchema,
1373
1375
  wordpressSchemaStatusResultDtoSchema,
1374
1376
  wordpressStatusDtoSchema
1375
- } from "./chunk-FEIDW5BU.js";
1377
+ } from "./chunk-JCK5TDIU.js";
1376
1378
 
1377
1379
  // ../api-routes/src/user-session.ts
1378
1380
  import crypto2 from "crypto";
@@ -8996,7 +8998,7 @@ function simpleSourceQueries(definition2) {
8996
8998
  }
8997
8999
 
8998
9000
  // ../api-routes/src/sentiment-service.ts
8999
- var DISCLOSURE = "Experimental English sentiment classification. Enabling sends each stored answer's text to TypeSafe with the frozen subject identity (name, aliases, qualified aliases and URLs), the tracked query text and query class, the answer engine with its requested and served models, the location, and internal query, subject, Property, group and market identifiers.";
9001
+ var DISCLOSURE = "English sentiment classification. Enabling sends each stored answer's text to TypeSafe with the frozen subject identity (name, aliases, qualified aliases and URLs), the tracked query text and query class, the answer engine with its requested and served models, the location, and internal query, subject, Property, group and market identifiers.";
9000
9002
  var FULL_ROWS = { include: /* @__PURE__ */ new Set(["assessments", "locations"]), limit: null, after: null };
9001
9003
  var COMPACT_ROWS = { include: /* @__PURE__ */ new Set(), limit: null, after: null };
9002
9004
  var OPERATIONAL_OUTCOMES = /* @__PURE__ */ new Set([SentimentOutcomes.pending, SentimentOutcomes.running, SentimentOutcomes["waiting-to-retry"], SentimentOutcomes.failed, SentimentOutcomes.canceled]);
@@ -9042,7 +9044,7 @@ var SentimentService = class {
9042
9044
  evaluationDefinitionId: row?.evaluationDefinitionId ?? null,
9043
9045
  // A project that is still on can always be switched off, even while the install switch is off.
9044
9046
  actions: { configure: administrator && (install.enabled || Boolean(row?.enabled)), backfill: administrator && ready && Boolean(row?.enabled) },
9045
- experimental: true,
9047
+ experimental: false,
9046
9048
  disclosure: install.provider === "openrouter" ? DISCLOSURE.replace("to TypeSafe", "to OpenRouter for the pinned TypeSafe Jev evaluator") : DISCLOSURE
9047
9049
  };
9048
9050
  }
@@ -32629,7 +32631,10 @@ function retryAfterSeconds(header2, now = Date.now()) {
32629
32631
  const seconds = /^\d+$/u.test(value) ? Number(value) : (Date.parse(value) - now) / 1e3;
32630
32632
  return Number.isFinite(seconds) && seconds >= 0 ? Math.min(Math.ceil(seconds), 86400) : null;
32631
32633
  }
32632
- async function deliverWebhook(target, payload, webhookSecret) {
32634
+ function webhookUserAgent(version) {
32635
+ return version ? `Canonry/${version}` : "Canonry";
32636
+ }
32637
+ async function deliverWebhook(target, payload, webhookSecret, options = {}) {
32633
32638
  const body = JSON.stringify(payload);
32634
32639
  const isHttps = target.url.protocol === "https:";
32635
32640
  const port = target.url.port ? Number(target.url.port) : isHttps ? 443 : 80;
@@ -32638,7 +32643,7 @@ async function deliverWebhook(target, payload, webhookSecret) {
32638
32643
  "Content-Length": String(Buffer.byteLength(body)),
32639
32644
  "Content-Type": "application/json",
32640
32645
  "Host": target.url.host,
32641
- "User-Agent": "Canonry/0.1.0"
32646
+ "User-Agent": options.userAgent ?? webhookUserAgent()
32642
32647
  };
32643
32648
  if (webhookSecret) {
32644
32649
  headers["X-Canonry-Signature"] = "sha256=" + crypto31.createHmac("sha256", webhookSecret).update(body).digest("hex");
@@ -42266,7 +42271,7 @@ var routeCatalog = [
42266
42271
  {
42267
42272
  method: "put",
42268
42273
  path: "/api/v1/projects/{name}/sentiment/settings",
42269
- summary: "Configure experimental project sentiment",
42274
+ summary: "Configure project sentiment",
42270
42275
  tags: ["sentiment"],
42271
42276
  parameters: [nameParameter],
42272
42277
  description: "Install administrators only. Enabling processes future eligible completions; historical backfill is explicit. Stance-only evaluator definitions are immutable and comparisons preserve their identity. TypeSafe credentials remain local install configuration.",
@@ -48788,7 +48793,7 @@ var routeCatalog = [
48788
48793
  method: "get",
48789
48794
  path: "/api/v1/projects/{name}/traffic/events",
48790
48795
  summary: "List rolled-up crawler hits, AI user-fetch hits, and AI-referral sessions within a window",
48791
- description: "Returns full-window hourly or daily chart series plus newest-first detail rows from `crawler_events_hourly`, `ai_user_fetch_events_hourly`, and `ai_referral_events_hourly`. Defaults to the last 24h. Totals and `series.points` reflect the full window; only the `events` array is capped by `limit` (default 500, max 5000). `eventRows` reports the true pre-limit row count.",
48796
+ description: "Returns full-window hourly or daily chart series plus newest-first detail rows from `crawler_events_hourly`, `ai_user_fetch_events_hourly`, and `ai_referral_events_hourly`. Defaults to the last 24h. Totals and `series.points` reflect the full window; only the `events` array is capped by `limit` (default 500, max 5000). `eventRows` reports the true row count, and `eventRows.nextCursor` reads the next page. `path` and `agent` narrow totals, series, rows and groups alike. `groupBy` adds totals per agent, path, status or source over the whole filtered window, so one call can answer which bots read a page.",
48792
48797
  tags: ["traffic"],
48793
48798
  parameters: [
48794
48799
  nameParameter,
@@ -48797,7 +48802,11 @@ var routeCatalog = [
48797
48802
  { name: "kind", in: "query", description: 'Filter to "crawler", "ai-user-fetch", "ai-referral", a comma-separated list of them (e.g. "ai-user-fetch,ai-referral"), or "all" (default). Rows, totals and series cover only the kinds asked for.', schema: stringSchema },
48798
48803
  { name: "limit", in: "query", description: "Max newest combined detail rows in the events array (default 500, max 5000).", schema: stringSchema },
48799
48804
  { name: "sourceId", in: "query", description: "Restrict to a single traffic source.", schema: stringSchema },
48800
- { name: "granularity", in: "query", description: 'Full-window series bucket size: "hour" (default), "day" or "month" (UTC calendar months).', schema: { type: "string", enum: ["hour", "day", "month"] } }
48805
+ { name: "granularity", in: "query", description: 'Full-window series bucket size: "hour" (default), "day" or "month" (UTC calendar months).', schema: { type: "string", enum: ["hour", "day", "month"] } },
48806
+ { name: "path", in: "query", description: "A page and the pages under it: `/faq` matches `/faq` and `/faq/x`, never `/faqs`; case counts. The fetched path, or the landing path on AI-referral rows. Totals, series, rows and groups all honor it.", schema: stringSchema },
48807
+ { name: "agent", in: "query", description: "Exact bot ID (for example openai-searchbot), or the AI product on AI-referral rows. Totals, series, rows and groups all honor it.", schema: stringSchema },
48808
+ { name: "cursor", in: "query", description: "The previous page's `eventRows.nextCursor`. Repeat the first page's kind, sourceId, path and agent; the cursor keeps the first page's window.", schema: stringSchema },
48809
+ { name: "groupBy", in: "query", description: "Comma-separated totals over the whole filtered window: agent, path, status, source. Groups are always split by kind, sorted most hits first and capped by `limit`.", schema: stringSchema }
48801
48810
  ],
48802
48811
  responses: {
48803
48812
  200: jsonResponse("Events returned with windowed totals.", "TrafficEventsResponse"),
@@ -51546,7 +51555,7 @@ async function notificationRoutes(app, opts = {}) {
51546
51555
  const signingSecret = destination.signed ? notification.webhookSecret ?? null : null;
51547
51556
  const targetLabel = redactNotificationUrl(config.url).urlDisplay;
51548
51557
  request.log.info(`[Notification test] POST ${targetLabel} (${destination.destination})`);
51549
- const delivery = await deliverWebhook(urlCheck.target, body, signingSecret);
51558
+ const delivery = await deliverWebhook(urlCheck.target, body, signingSecret, { userAgent: webhookUserAgent(opts.appVersion) });
51550
51559
  const { status, error } = delivery;
51551
51560
  request.log.info(`[Notification test] Response: HTTP ${status} from ${targetLabel}`);
51552
51561
  const failure = webhookResponseReason(delivery);
@@ -69943,7 +69952,7 @@ async function queryBacklinks(opts) {
69943
69952
  const reversed = opts.targets.map(reverseDomain);
69944
69953
  const targetList = reversed.map(quote).join(", ");
69945
69954
  const limitClause = opts.limitPerTarget ? `QUALIFY row_number() OVER (PARTITION BY t.target_rev_domain ORDER BY v.num_hosts DESC) <= ${Math.floor(opts.limitPerTarget)}` : "";
69946
- const sql52 = `
69955
+ const sql53 = `
69947
69956
  WITH vertices AS (
69948
69957
  SELECT * FROM read_csv(
69949
69958
  ${quote(opts.vertexPath)},
@@ -69979,7 +69988,7 @@ async function queryBacklinks(opts) {
69979
69988
  const conn = await instance.connect();
69980
69989
  let rows;
69981
69990
  try {
69982
- const reader = await conn.runAndReadAll(sql52);
69991
+ const reader = await conn.runAndReadAll(sql53);
69983
69992
  rows = reader.getRowObjects();
69984
69993
  } finally {
69985
69994
  conn.disconnectSync?.();
@@ -70481,10 +70490,10 @@ async function backlinksRoutes(app, opts) {
70481
70490
  }
70482
70491
 
70483
70492
  // ../api-routes/src/traffic.ts
70484
- import crypto60 from "crypto";
70493
+ import crypto61 from "crypto";
70485
70494
  import { isIP as isIP3 } from "net";
70486
70495
  import { isDeepStrictEqual } from "util";
70487
- import { and as and89, desc as desc47, eq as eq103, gt as gt8, gte as gte27, inArray as inArray48, lt as lt20, lte as lte27, sql as sql47 } from "drizzle-orm";
70496
+ import { and as and89, desc as desc48, eq as eq104, gt as gt8, gte as gte27, inArray as inArray48, lt as lt20, lte as lte27, sql as sql48 } from "drizzle-orm";
70488
70497
 
70489
70498
  // ../api-routes/src/traffic-limits.ts
70490
70499
  var VERCEL_MAX_SYNC_WINDOW_MS = 24 * 60 * 6e4;
@@ -71864,6 +71873,158 @@ function releaseTrafficSyncLease(input) {
71864
71873
  }, { behavior: "immediate" });
71865
71874
  }
71866
71875
 
71876
+ // ../api-routes/src/traffic-events-read.ts
71877
+ import crypto60 from "crypto";
71878
+ import { desc as desc47, eq as eq103, or as or20, sql as sql47 } from "drizzle-orm";
71879
+ function keyColumns(table, fields) {
71880
+ return { keyFields: fields, keys: fields.map((field) => table[field]) };
71881
+ }
71882
+ var TRAFFIC_EVENT_TABLES = {
71883
+ [TrafficEventKinds.crawler]: {
71884
+ kind: TrafficEventKinds.crawler,
71885
+ rank: 0,
71886
+ table: crawlerEventsHourly,
71887
+ tsHour: crawlerEventsHourly.tsHour,
71888
+ ...keyColumns(crawlerEventsHourly, ["sourceId", "botId", "verificationStatus", "pathNormalized", "status"]),
71889
+ agent: crawlerEventsHourly.botId,
71890
+ path: crawlerEventsHourly.pathNormalized,
71891
+ status: crawlerEventsHourly.status,
71892
+ sourceId: crawlerEventsHourly.sourceId,
71893
+ hits: crawlerEventsHourly.hits
71894
+ },
71895
+ [TrafficEventKinds["ai-user-fetch"]]: {
71896
+ kind: TrafficEventKinds["ai-user-fetch"],
71897
+ rank: 1,
71898
+ table: aiUserFetchEventsHourly,
71899
+ tsHour: aiUserFetchEventsHourly.tsHour,
71900
+ ...keyColumns(aiUserFetchEventsHourly, ["sourceId", "botId", "verificationStatus", "pathNormalized", "status"]),
71901
+ agent: aiUserFetchEventsHourly.botId,
71902
+ path: aiUserFetchEventsHourly.pathNormalized,
71903
+ status: aiUserFetchEventsHourly.status,
71904
+ sourceId: aiUserFetchEventsHourly.sourceId,
71905
+ hits: aiUserFetchEventsHourly.hits
71906
+ },
71907
+ [TrafficEventKinds["ai-referral"]]: {
71908
+ kind: TrafficEventKinds["ai-referral"],
71909
+ rank: 2,
71910
+ table: aiReferralEventsHourly,
71911
+ tsHour: aiReferralEventsHourly.tsHour,
71912
+ ...keyColumns(aiReferralEventsHourly, ["sourceId", "product", "sourceDomain", "evidenceType", "landingPathNormalized", "status"]),
71913
+ agent: aiReferralEventsHourly.product,
71914
+ path: aiReferralEventsHourly.landingPathNormalized,
71915
+ status: aiReferralEventsHourly.status,
71916
+ sourceId: aiReferralEventsHourly.sourceId,
71917
+ hits: aiReferralEventsHourly.sessionsOrHits
71918
+ }
71919
+ };
71920
+ function trafficEventPathPredicate(column, path8) {
71921
+ const page2 = path8.length > 1 ? path8.replace(/\/+$/u, "") || "/" : path8;
71922
+ if (page2 === "/") return sql47`substr(${column}, 1, 1) = '/'`;
71923
+ const under = `${page2}/`;
71924
+ return or20(sql47`${column} = ${page2}`, sql47`substr(${column}, 1, ${under.length}) = ${under}`);
71925
+ }
71926
+ function trafficEventFilterPredicates(table, filters) {
71927
+ const predicates = [];
71928
+ if (filters.path !== null) predicates.push(trafficEventPathPredicate(table.path, filters.path));
71929
+ if (filters.agent !== null) predicates.push(eq103(table.agent, filters.agent));
71930
+ return predicates;
71931
+ }
71932
+ function optionalQueryString(value, name) {
71933
+ if (value === void 0) return null;
71934
+ if (typeof value !== "string" || value.trim() === "") throw validationError(`"${name}" must be one non-empty value`);
71935
+ return value;
71936
+ }
71937
+ function filterDigest(filters, since, until) {
71938
+ const basis = JSON.stringify([since, until, [...filters.kinds].sort(), filters.sourceId, filters.path, filters.agent]);
71939
+ return crypto60.createHash("sha256").update(basis).digest("hex").slice(0, 16);
71940
+ }
71941
+ function encodeTrafficEventCursor(filters, cursor) {
71942
+ const body = {
71943
+ v: 1,
71944
+ w: [cursor.since, cursor.until],
71945
+ f: filterDigest(filters, cursor.since, cursor.until),
71946
+ t: cursor.tsHour,
71947
+ r: cursor.rank,
71948
+ k: cursor.keys
71949
+ };
71950
+ return Buffer.from(JSON.stringify(body)).toString("base64url");
71951
+ }
71952
+ var CURSOR_REFUSED = '"cursor" is not a cursor from this read. Pass the nextCursor of the previous page unchanged.';
71953
+ function readTrafficEventCursorWindow(raw) {
71954
+ const body = parseCursor4(raw);
71955
+ return { since: body.w[0], until: body.w[1] };
71956
+ }
71957
+ function decodeTrafficEventCursor(raw, filters, since, until) {
71958
+ const body = parseCursor4(raw);
71959
+ if (body.w[0] !== since || body.w[1] !== until || body.f !== filterDigest(filters, since, until)) {
71960
+ throw validationError(`"cursor" belongs to a read with different filters or a different window. Repeat the first page's kind, sourceId, path and agent (since and until may be left out).`);
71961
+ }
71962
+ return { since, until, tsHour: body.t, rank: body.r, keys: body.k };
71963
+ }
71964
+ function parseCursor4(raw) {
71965
+ let body;
71966
+ try {
71967
+ body = JSON.parse(Buffer.from(raw, "base64url").toString("utf8"));
71968
+ } catch {
71969
+ throw validationError(CURSOR_REFUSED);
71970
+ }
71971
+ const value = body;
71972
+ const valid = value !== null && typeof value === "object" && value.v === 1 && Array.isArray(value.w) && value.w.length === 2 && value.w.every((part) => typeof part === "string") && typeof value.f === "string" && typeof value.t === "string" && typeof value.r === "number" && Number.isInteger(value.r) && Array.isArray(value.k) && value.k.every((part) => typeof part === "string" || typeof part === "number");
71973
+ if (!valid) throw validationError(CURSOR_REFUSED);
71974
+ return value;
71975
+ }
71976
+ function trafficEventCursorPredicate(table, cursor) {
71977
+ if (table.rank < cursor.rank) return sql47`${table.tsHour} < ${cursor.tsHour}`;
71978
+ if (table.rank > cursor.rank) return sql47`${table.tsHour} <= ${cursor.tsHour}`;
71979
+ if (cursor.keys.length !== table.keys.length) throw validationError(CURSOR_REFUSED);
71980
+ const columns = sql47.join([table.tsHour, ...table.keys].map((column) => sql47`${column}`), sql47`, `);
71981
+ const values = sql47.join([cursor.tsHour, ...cursor.keys].map((value) => sql47`${value}`), sql47`, `);
71982
+ return sql47`(${columns}) < (${values})`;
71983
+ }
71984
+ function trafficEventOrder(table) {
71985
+ return [desc47(table.tsHour), ...table.keys.map((column) => desc47(column))];
71986
+ }
71987
+ function mergeTrafficEventPages(pages, limit, filters, since, until) {
71988
+ const merged = pages.flat();
71989
+ merged.sort((a, b) => a.tsHour < b.tsHour ? 1 : a.tsHour > b.tsHour ? -1 : a.rank - b.rank);
71990
+ const page2 = merged.slice(0, limit);
71991
+ const last = page2[page2.length - 1];
71992
+ const nextCursor = merged.length > limit && last ? encodeTrafficEventCursor(filters, { since, until, tsHour: last.tsHour, rank: last.rank, keys: last.keys }) : null;
71993
+ return { page: page2, nextCursor };
71994
+ }
71995
+ function trafficEventGroupColumns(table, by) {
71996
+ const columns = {};
71997
+ if (by.includes("agent")) columns.agent = table.agent;
71998
+ if (by.includes("path")) columns.path = table.path;
71999
+ if (by.includes("status")) columns.status = table.status;
72000
+ if (by.includes("source")) columns.sourceId = table.sourceId;
72001
+ return columns;
72002
+ }
72003
+ function toTrafficEventGroup(kind, row) {
72004
+ const group = {
72005
+ kind,
72006
+ hits: Number(row.hits),
72007
+ rows: Number(row.rows),
72008
+ firstHour: row.firstHour,
72009
+ lastHour: row.lastHour
72010
+ };
72011
+ if (row.agent !== void 0) group.agent = row.agent;
72012
+ if (row.path !== void 0) group.path = row.path;
72013
+ if (row.status !== void 0) group.status = Number(row.status);
72014
+ if (row.sourceId !== void 0) group.sourceId = row.sourceId;
72015
+ return group;
72016
+ }
72017
+ function compareTrafficEventGroups(a, b) {
72018
+ if (a.hits !== b.hits) return b.hits - a.hits;
72019
+ if (a.kind !== b.kind) return TRAFFIC_EVENT_TABLES[a.kind].rank - TRAFFIC_EVENT_TABLES[b.kind].rank;
72020
+ for (const field of ["agent", "path", "sourceId"]) {
72021
+ const left = a[field] ?? "";
72022
+ const right = b[field] ?? "";
72023
+ if (left !== right) return left < right ? -1 : 1;
72024
+ }
72025
+ return (a.status ?? 0) - (b.status ?? 0);
72026
+ }
72027
+
71867
72028
  // ../api-routes/src/traffic.ts
71868
72029
  var DEFAULT_SYNC_WINDOW_MINUTES = 43200;
71869
72030
  var DEFAULT_PAGE_SIZE3 = 1e3;
@@ -71902,7 +72063,7 @@ function logBrowserAgentNonPageHits(log, fields) {
71902
72063
  );
71903
72064
  }
71904
72065
  function sha256Hex3(value) {
71905
- return crypto60.createHash("sha256").update(value).digest("hex");
72066
+ return crypto61.createHash("sha256").update(value).digest("hex");
71906
72067
  }
71907
72068
  function hashCloudflareBearerToken(value) {
71908
72069
  return sha256Hex3(value);
@@ -71912,7 +72073,7 @@ function timingSafeEqualHex(a, b) {
71912
72073
  if (!SHA256_HEX_PATTERN.test(a) || !SHA256_HEX_PATTERN.test(b)) return false;
71913
72074
  const left = Buffer.from(a, "hex");
71914
72075
  const right = Buffer.from(b, "hex");
71915
- return left.length === right.length && crypto60.timingSafeEqual(left, right);
72076
+ return left.length === right.length && crypto61.timingSafeEqual(left, right);
71916
72077
  }
71917
72078
  async function loadQueueReceiptPolicy(db, sourceId, readRetentionSeconds, warn2) {
71918
72079
  let liveTtlMs = null;
@@ -71932,14 +72093,14 @@ async function loadQueueReceiptPolicy(db, sourceId, readRetentionSeconds, warn2)
71932
72093
  if (liveTtlMs === null) return { ttlMsAt: () => CLOUDFLARE_QUEUE_RECEIPT_TTL_MS };
71933
72094
  const ttlMs = liveTtlMs;
71934
72095
  const now = (/* @__PURE__ */ new Date()).toISOString();
71935
- const alive = and89(eq103(trafficEventReceipts.sourceId, sourceId), gt8(trafficEventReceipts.expiresAt, now));
71936
- const lifetimeMs = sql47`(julianday(${trafficEventReceipts.expiresAt}) - julianday(${trafficEventReceipts.receivedAt})) * ${DAY_MS5}`;
71937
- const shortest = db.select({ ms: sql47`min(${lifetimeMs})` }).from(trafficEventReceipts).where(alive).get()?.ms ?? null;
72096
+ const alive = and89(eq104(trafficEventReceipts.sourceId, sourceId), gt8(trafficEventReceipts.expiresAt, now));
72097
+ const lifetimeMs = sql48`(julianday(${trafficEventReceipts.expiresAt}) - julianday(${trafficEventReceipts.receivedAt})) * ${DAY_MS5}`;
72098
+ const shortest = db.select({ ms: sql48`min(${lifetimeMs})` }).from(trafficEventReceipts).where(alive).get()?.ms ?? null;
71938
72099
  if (shortest !== null && shortest < ttlMs - 1e3) {
71939
- const extended = sql47`strftime('%Y-%m-%dT%H:%M:%fZ', julianday(${trafficEventReceipts.receivedAt}) + ${ttlMs / DAY_MS5})`;
72100
+ const extended = sql48`strftime('%Y-%m-%dT%H:%M:%fZ', julianday(${trafficEventReceipts.receivedAt}) + ${ttlMs / DAY_MS5})`;
71940
72101
  db.update(trafficEventReceipts).set({ expiresAt: extended }).where(and89(alive, lt20(trafficEventReceipts.expiresAt, extended))).run();
71941
72102
  }
71942
- const floorExpiry = db.select({ at: sql47`max(${trafficEventReceipts.expiresAt})` }).from(trafficEventReceipts).where(and89(alive, sql47`${lifetimeMs} < ${CLOUDFLARE_QUEUE_RECEIPT_TTL_MS - 1e3}`)).get()?.at ?? null;
72103
+ const floorExpiry = db.select({ at: sql48`max(${trafficEventReceipts.expiresAt})` }).from(trafficEventReceipts).where(and89(alive, sql48`${lifetimeMs} < ${CLOUDFLARE_QUEUE_RECEIPT_TTL_MS - 1e3}`)).get()?.at ?? null;
71943
72104
  const floorMs = floorExpiry ? Date.parse(floorExpiry) : 0;
71944
72105
  return { ttlMsAt: (receivedAt) => Math.max(ttlMs, floorMs - Date.parse(receivedAt)) };
71945
72106
  }
@@ -71994,7 +72155,7 @@ function cloudflareIngestRateLimitKey(request, store, db) {
71994
72155
  const authenticated = authenticateCloudflareIngest(request, store);
71995
72156
  const params = request.params;
71996
72157
  if (authenticated && typeof params.name === "string" && authenticated.credential.projectName === params.name) {
71997
- const source = db.select().from(trafficSources).where(eq103(trafficSources.id, authenticated.credential.sourceId)).get();
72158
+ const source = db.select().from(trafficSources).where(eq104(trafficSources.id, authenticated.credential.sourceId)).get();
71998
72159
  if (source && source.sourceType === TrafficSourceTypes.cloudflare && source.status === TrafficSourceStatuses.connected && parseDirectPushCloudflareSourceConfig(source.configJson) && timingSafeEqualHex(authenticated.bearerHash, source.ingestTokenHash)) {
71999
72160
  return `cloudflare-source:${authenticated.credential.sourceId}`;
72000
72161
  }
@@ -72073,7 +72234,7 @@ var SERIES_BUCKET_LENGTH = {
72073
72234
  };
72074
72235
  function seriesBucketSql(tsHour, granularity) {
72075
72236
  const length = SERIES_BUCKET_LENGTH[granularity];
72076
- return length === null ? tsHour : sql47`substr(${tsHour}, 1, ${sql47.raw(String(length))})`;
72237
+ return length === null ? tsHour : sql48`substr(${tsHour}, 1, ${sql48.raw(String(length))})`;
72077
72238
  }
72078
72239
  function seriesBucketOf(iso2, granularity) {
72079
72240
  const length = SERIES_BUCKET_LENGTH[granularity];
@@ -72165,7 +72326,7 @@ function crawlerVerificationProvenance(db, projectId, events) {
72165
72326
  manifestId: crawlerVerificationManifestsHourly.manifestId,
72166
72327
  manifest: crawlerVerificationManifestsHourly.manifestJson,
72167
72328
  hits: crawlerVerificationManifestsHourly.hits
72168
- }).from(crawlerVerificationManifestsHourly).where(sql47`(
72329
+ }).from(crawlerVerificationManifestsHourly).where(sql48`(
72169
72330
  ${crawlerVerificationManifestsHourly.projectId},
72170
72331
  ${crawlerVerificationManifestsHourly.sourceId},
72171
72332
  ${crawlerVerificationManifestsHourly.tsHour},
@@ -72199,7 +72360,7 @@ function aiUserFetchVerificationProvenance(db, projectId, events) {
72199
72360
  manifestId: aiUserFetchVerificationManifestsHourly.manifestId,
72200
72361
  manifest: aiUserFetchVerificationManifestsHourly.manifestJson,
72201
72362
  hits: aiUserFetchVerificationManifestsHourly.hits
72202
- }).from(aiUserFetchVerificationManifestsHourly).where(sql47`(
72363
+ }).from(aiUserFetchVerificationManifestsHourly).where(sql48`(
72203
72364
  ${aiUserFetchVerificationManifestsHourly.projectId},
72204
72365
  ${aiUserFetchVerificationManifestsHourly.sourceId},
72205
72366
  ${aiUserFetchVerificationManifestsHourly.tsHour},
@@ -72254,7 +72415,7 @@ async function defaultResolveAccessToken(record3) {
72254
72415
  );
72255
72416
  }
72256
72417
  function hasConnectedTrafficSourceSibling(db, projectId, sourceId) {
72257
- return db.select().from(trafficSources).where(eq103(trafficSources.projectId, projectId)).all().some((row) => row.id !== sourceId && row.status === TrafficSourceStatuses.connected);
72418
+ return db.select().from(trafficSources).where(eq104(trafficSources.projectId, projectId)).all().some((row) => row.id !== sourceId && row.status === TrafficSourceStatuses.connected);
72258
72419
  }
72259
72420
  function isAuthoritativeTrafficSource(db, source) {
72260
72421
  return (source.status === TrafficSourceStatuses.connected || source.status === TrafficSourceStatuses.error) && !hasConnectedTrafficSourceSibling(db, source.projectId, source.id);
@@ -72282,17 +72443,17 @@ function wordpressBaseUrlIdentity(value) {
72282
72443
  }
72283
72444
  function bindTrafficSyncSchedule(tx, projectId, sourceId, now, createIfMissing = true) {
72284
72445
  const schedule = tx.select().from(schedules).where(and89(
72285
- eq103(schedules.projectId, projectId),
72286
- eq103(schedules.kind, SchedulableRunKinds["traffic-sync"])
72446
+ eq104(schedules.projectId, projectId),
72447
+ eq104(schedules.kind, SchedulableRunKinds["traffic-sync"])
72287
72448
  )).get();
72288
72449
  if (schedule) {
72289
72450
  if (schedule.sourceId === sourceId) return { changed: false, created: false };
72290
- tx.update(schedules).set({ sourceId, updatedAt: nextScheduleUpdatedAt(schedule.updatedAt, Date.parse(now)) }).where(eq103(schedules.id, schedule.id)).run();
72451
+ tx.update(schedules).set({ sourceId, updatedAt: nextScheduleUpdatedAt(schedule.updatedAt, Date.parse(now)) }).where(eq104(schedules.id, schedule.id)).run();
72291
72452
  return { changed: true, created: false };
72292
72453
  }
72293
72454
  if (!createIfMissing) return { changed: false, created: false };
72294
72455
  tx.insert(schedules).values({
72295
- id: crypto60.randomUUID(),
72456
+ id: crypto61.randomUUID(),
72296
72457
  projectId,
72297
72458
  kind: SchedulableRunKinds["traffic-sync"],
72298
72459
  cronExpr: DEFAULT_TRAFFIC_SYNC_CRON,
@@ -72329,7 +72490,7 @@ async function runBackfillTask(options) {
72329
72490
  };
72330
72491
  const renewLease2 = setInterval(() => {
72331
72492
  try {
72332
- const latest = app.db.select().from(trafficSources).where(eq103(trafficSources.id, sourceRow2.id)).get();
72493
+ const latest = app.db.select().from(trafficSources).where(eq104(trafficSources.id, sourceRow2.id)).get();
72333
72494
  if (!latest || !isAuthoritativeTrafficSource(app.db, latest) || !isSameTrafficSourceGeneration(latest, sourceRow2)) {
72334
72495
  clearInterval(renewLease2);
72335
72496
  stopped.abort();
@@ -72377,10 +72538,10 @@ async function runBackfillTaskHoldingLease(options, signal) {
72377
72538
  const failedAt = (/* @__PURE__ */ new Date()).toISOString();
72378
72539
  try {
72379
72540
  app.db.transaction((tx) => {
72380
- tx.update(runs).set({ status: RunStatuses.failed, error: msg, finishedAt: failedAt }).where(eq103(runs.id, runId)).run();
72381
- const latestSource = tx.select().from(trafficSources).where(eq103(trafficSources.id, sourceRow2.id)).get();
72541
+ tx.update(runs).set({ status: RunStatuses.failed, error: msg, finishedAt: failedAt }).where(eq104(runs.id, runId)).run();
72542
+ const latestSource = tx.select().from(trafficSources).where(eq104(trafficSources.id, sourceRow2.id)).get();
72382
72543
  if (!preserveSourceState && latestSource && isAuthoritativeTrafficSource(tx, latestSource) && isSameBackfillSource(latestSource, sourceRow2, leaseOwner)) {
72383
- tx.update(trafficSources).set({ status: TrafficSourceStatuses.error, lastError: msg, updatedAt: failedAt }).where(eq103(trafficSources.id, sourceRow2.id)).run();
72544
+ tx.update(trafficSources).set({ status: TrafficSourceStatuses.error, lastError: msg, updatedAt: failedAt }).where(eq104(trafficSources.id, sourceRow2.id)).run();
72384
72545
  }
72385
72546
  });
72386
72547
  } catch {
@@ -72412,7 +72573,7 @@ async function runBackfillTaskHoldingLease(options, signal) {
72412
72573
  let emptyOutcome;
72413
72574
  try {
72414
72575
  const completed = app.db.transaction((tx) => {
72415
- const latestSource = tx.select().from(trafficSources).where(eq103(trafficSources.id, sourceRow2.id)).get();
72576
+ const latestSource = tx.select().from(trafficSources).where(eq104(trafficSources.id, sourceRow2.id)).get();
72416
72577
  const stillAuthoritative = latestSource && isAuthoritativeTrafficSource(tx, latestSource) && isSameBackfillSource(latestSource, sourceRow2, leaseOwner);
72417
72578
  if (stillAuthoritative) {
72418
72579
  enforceRawEventSampleRetention(tx, sourceRow2.id, finishedAt2);
@@ -72421,7 +72582,7 @@ async function runBackfillTaskHoldingLease(options, signal) {
72421
72582
  status: RunStatuses.failed,
72422
72583
  error: "Traffic source was deactivated or reconfigured during backfill",
72423
72584
  finishedAt: finishedAt2
72424
- }).where(eq103(runs.id, runId)).run();
72585
+ }).where(eq104(runs.id, runId)).run();
72425
72586
  return Boolean(stillAuthoritative);
72426
72587
  });
72427
72588
  emptyOutcome = completed ? { status: OutcomeStatuses.skipped, reasonCode: OutcomeReasonCodes.NO_DATA } : { status: OutcomeStatuses.failed, reasonCode: OutcomeReasonCodes.NOT_CONNECTED };
@@ -72453,13 +72614,13 @@ async function runBackfillTaskHoldingLease(options, signal) {
72453
72614
  const nextLastSyncedAt = Math.max(currentLastSyncedMs, windowEnd.getTime()) === windowEnd.getTime() ? windowEndIso : sourceRow2.lastSyncedAt;
72454
72615
  try {
72455
72616
  const commitOutcome = app.db.transaction((tx) => {
72456
- const latestSource = tx.select().from(trafficSources).where(eq103(trafficSources.id, sourceRow2.id)).get();
72617
+ const latestSource = tx.select().from(trafficSources).where(eq104(trafficSources.id, sourceRow2.id)).get();
72457
72618
  if (latestSource?.sourceType === TrafficSourceTypes.wordpress) {
72458
72619
  tx.update(runs).set({
72459
72620
  status: RunStatuses.failed,
72460
72621
  error: "Generic WordPress replace backfill is unavailable because retained coverage is unproven.",
72461
72622
  finishedAt
72462
- }).where(eq103(runs.id, runId)).run();
72623
+ }).where(eq104(runs.id, runId)).run();
72463
72624
  return "wordpress-backfill-unsupported";
72464
72625
  }
72465
72626
  if (!latestSource || !isAuthoritativeTrafficSource(tx, latestSource) || !isSameBackfillSource(latestSource, sourceRow2, leaseOwner)) {
@@ -72467,7 +72628,7 @@ async function runBackfillTaskHoldingLease(options, signal) {
72467
72628
  status: RunStatuses.failed,
72468
72629
  error: "Traffic source was deactivated or reconfigured during backfill",
72469
72630
  finishedAt
72470
- }).where(eq103(runs.id, runId)).run();
72631
+ }).where(eq104(runs.id, runId)).run();
72471
72632
  return "source-inactive";
72472
72633
  }
72473
72634
  const rawSampleCutoff = enforceRawEventSampleRetention(
@@ -72477,14 +72638,14 @@ async function runBackfillTaskHoldingLease(options, signal) {
72477
72638
  );
72478
72639
  tx.delete(crawlerEventsHourly).where(
72479
72640
  and89(
72480
- eq103(crawlerEventsHourly.sourceId, sourceRow2.id),
72641
+ eq104(crawlerEventsHourly.sourceId, sourceRow2.id),
72481
72642
  gte27(crawlerEventsHourly.tsHour, windowStartIso),
72482
72643
  lte27(crawlerEventsHourly.tsHour, windowEndIso)
72483
72644
  )
72484
72645
  ).run();
72485
72646
  tx.delete(aiUserFetchEventsHourly).where(
72486
72647
  and89(
72487
- eq103(aiUserFetchEventsHourly.sourceId, sourceRow2.id),
72648
+ eq104(aiUserFetchEventsHourly.sourceId, sourceRow2.id),
72488
72649
  gte27(aiUserFetchEventsHourly.tsHour, windowStartIso),
72489
72650
  lte27(aiUserFetchEventsHourly.tsHour, windowEndIso)
72490
72651
  )
@@ -72492,21 +72653,21 @@ async function runBackfillTaskHoldingLease(options, signal) {
72492
72653
  clearLikelyFakeAgentHits(tx, { sourceId: sourceRow2.id, windowStart: windowStartIso, windowEnd: windowEndIso });
72493
72654
  tx.delete(aiReferralEventsHourly).where(
72494
72655
  and89(
72495
- eq103(aiReferralEventsHourly.sourceId, sourceRow2.id),
72656
+ eq104(aiReferralEventsHourly.sourceId, sourceRow2.id),
72496
72657
  gte27(aiReferralEventsHourly.tsHour, windowStartIso),
72497
72658
  lte27(aiReferralEventsHourly.tsHour, windowEndIso)
72498
72659
  )
72499
72660
  ).run();
72500
72661
  tx.delete(rawEventSamples).where(
72501
72662
  and89(
72502
- eq103(rawEventSamples.sourceId, sourceRow2.id),
72663
+ eq104(rawEventSamples.sourceId, sourceRow2.id),
72503
72664
  gte27(rawEventSamples.ts, windowStartIso),
72504
72665
  lte27(rawEventSamples.ts, windowEndIso)
72505
72666
  )
72506
72667
  ).run();
72507
72668
  tx.delete(unrecognizedAgentEventsHourly).where(
72508
72669
  and89(
72509
- eq103(unrecognizedAgentEventsHourly.sourceId, sourceRow2.id),
72670
+ eq104(unrecognizedAgentEventsHourly.sourceId, sourceRow2.id),
72510
72671
  gte27(unrecognizedAgentEventsHourly.tsHour, windowStartIso),
72511
72672
  lte27(unrecognizedAgentEventsHourly.tsHour, windowEndIso)
72512
72673
  )
@@ -72537,7 +72698,7 @@ async function runBackfillTaskHoldingLease(options, signal) {
72537
72698
  crawlerEventsHourly.status
72538
72699
  ],
72539
72700
  set: {
72540
- hits: sql47`${crawlerEventsHourly.hits} + ${bucket.hits}`,
72701
+ hits: sql48`${crawlerEventsHourly.hits} + ${bucket.hits}`,
72541
72702
  sampledUserAgent: bucket.sampledUserAgent,
72542
72703
  updatedAt: finishedAt
72543
72704
  }
@@ -72568,7 +72729,7 @@ async function runBackfillTaskHoldingLease(options, signal) {
72568
72729
  crawlerVerificationManifestsHourly.manifestId
72569
72730
  ],
72570
72731
  set: {
72571
- hits: sql47`${crawlerVerificationManifestsHourly.hits} + ${bucket.hits}`,
72732
+ hits: sql48`${crawlerVerificationManifestsHourly.hits} + ${bucket.hits}`,
72572
72733
  manifestJson: bucket.verificationManifest,
72573
72734
  updatedAt: finishedAt
72574
72735
  }
@@ -72601,7 +72762,7 @@ async function runBackfillTaskHoldingLease(options, signal) {
72601
72762
  aiUserFetchEventsHourly.status
72602
72763
  ],
72603
72764
  set: {
72604
- hits: sql47`${aiUserFetchEventsHourly.hits} + ${bucket.hits}`,
72765
+ hits: sql48`${aiUserFetchEventsHourly.hits} + ${bucket.hits}`,
72605
72766
  sampledUserAgent: bucket.sampledUserAgent,
72606
72767
  updatedAt: finishedAt
72607
72768
  }
@@ -72632,7 +72793,7 @@ async function runBackfillTaskHoldingLease(options, signal) {
72632
72793
  aiUserFetchVerificationManifestsHourly.manifestId
72633
72794
  ],
72634
72795
  set: {
72635
- hits: sql47`${aiUserFetchVerificationManifestsHourly.hits} + ${bucket.hits}`,
72796
+ hits: sql48`${aiUserFetchVerificationManifestsHourly.hits} + ${bucket.hits}`,
72636
72797
  manifestJson: bucket.verificationManifest,
72637
72798
  updatedAt: finishedAt
72638
72799
  }
@@ -72673,7 +72834,7 @@ async function runBackfillTaskHoldingLease(options, signal) {
72673
72834
  }
72674
72835
  })();
72675
72836
  tx.insert(rawEventSamples).values({
72676
- id: crypto60.randomUUID(),
72837
+ id: crypto61.randomUUID(),
72677
72838
  projectId: project.id,
72678
72839
  sourceId: sourceRow2.id,
72679
72840
  ts: sampleTimestamp,
@@ -72709,13 +72870,13 @@ async function runBackfillTaskHoldingLease(options, signal) {
72709
72870
  const skipRecovered = sourceRow2.sourceType !== TrafficSourceTypes.wordpress && Number.isFinite(recordedSkipMs) && windowStart.getTime() <= recordedSkipMs;
72710
72871
  let olderCountUntil = latestSource.aiReferralOlderCountUntil;
72711
72872
  if (olderCountUntil !== null) {
72712
- const ruleChange = tx.get(sql47`
72873
+ const ruleChange = tx.get(sql48`
72713
72874
  SELECT strftime('%Y-%m-%dT%H:%M:%fZ', applied_at) AS appliedAt
72714
72875
  FROM _migrations WHERE version = 207
72715
72876
  `);
72716
72877
  if (ruleChange?.appliedAt) {
72717
72878
  const olderReferral = tx.select({ sourceId: aiReferralEventsHourly.sourceId }).from(aiReferralEventsHourly).where(and89(
72718
- eq103(aiReferralEventsHourly.sourceId, sourceRow2.id),
72879
+ eq104(aiReferralEventsHourly.sourceId, sourceRow2.id),
72719
72880
  lt20(aiReferralEventsHourly.createdAt, ruleChange.appliedAt)
72720
72881
  )).limit(1).get();
72721
72882
  if (!olderReferral) olderCountUntil = null;
@@ -72736,8 +72897,8 @@ async function runBackfillTaskHoldingLease(options, signal) {
72736
72897
  aiUserFetchOlderCountUntil: userFetchOlderCountUntil,
72737
72898
  ...skipRecovered ? { skippedThroughAt: null } : {},
72738
72899
  updatedAt: finishedAt
72739
- }).where(eq103(trafficSources.id, sourceRow2.id)).run();
72740
- tx.update(runs).set({ status: RunStatuses.completed, finishedAt }).where(eq103(runs.id, runId)).run();
72900
+ }).where(eq104(trafficSources.id, sourceRow2.id)).run();
72901
+ tx.update(runs).set({ status: RunStatuses.completed, finishedAt }).where(eq104(runs.id, runId)).run();
72741
72902
  return "committed";
72742
72903
  });
72743
72904
  reportBackfill(commitOutcome === "committed" ? {
@@ -72911,8 +73072,8 @@ async function trafficRoutes(app, opts) {
72911
73072
  };
72912
73073
  const fallbackName = displayName ?? `Cloud Run \xB7 ${gcpProjectId}${serviceName ? ` / ${serviceName}` : ""}`;
72913
73074
  const { sourceRow: sourceRow2, scheduleChanged } = app.db.transaction((tx) => {
72914
- const activeSource = tx.select().from(trafficSources).where(eq103(trafficSources.projectId, project.id)).all().find((row) => row.sourceType === TrafficSourceTypes["cloud-run"] && row.status !== TrafficSourceStatuses.archived);
72915
- const sourceId = activeSource?.id ?? crypto60.randomUUID();
73075
+ const activeSource = tx.select().from(trafficSources).where(eq104(trafficSources.projectId, project.id)).all().find((row) => row.sourceType === TrafficSourceTypes["cloud-run"] && row.status !== TrafficSourceStatuses.archived);
73076
+ const sourceId = activeSource?.id ?? crypto61.randomUUID();
72916
73077
  const sourceStatus = trafficConnectStatus(tx, project.id, activeSource);
72917
73078
  if (activeSource) {
72918
73079
  tx.update(trafficSources).set({
@@ -72921,7 +73082,7 @@ async function trafficRoutes(app, opts) {
72921
73082
  lastError: null,
72922
73083
  configJson: config,
72923
73084
  updatedAt: now
72924
- }).where(eq103(trafficSources.id, sourceId)).run();
73085
+ }).where(eq104(trafficSources.id, sourceId)).run();
72925
73086
  } else {
72926
73087
  tx.insert(trafficSources).values({
72927
73088
  id: sourceId,
@@ -72947,7 +73108,7 @@ async function trafficRoutes(app, opts) {
72947
73108
  entityId: sourceId
72948
73109
  });
72949
73110
  return {
72950
- sourceRow: tx.select().from(trafficSources).where(eq103(trafficSources.id, sourceId)).get(),
73111
+ sourceRow: tx.select().from(trafficSources).where(eq104(trafficSources.id, sourceId)).get(),
72951
73112
  scheduleChanged: scheduleBinding.changed
72952
73113
  };
72953
73114
  }, { behavior: "immediate" });
@@ -73002,9 +73163,9 @@ async function trafficRoutes(app, opts) {
73002
73163
  const config = { baseUrl, username };
73003
73164
  const fallbackName = displayName ?? `WordPress \xB7 ${new URL(baseUrl).host}`;
73004
73165
  const { sourceRow: sourceRow2, scheduleChanged } = app.db.transaction((tx) => {
73005
- const activeSource = tx.select().from(trafficSources).where(eq103(trafficSources.projectId, project.id)).all().find((row) => row.sourceType === TrafficSourceTypes.wordpress && row.status !== TrafficSourceStatuses.archived);
73166
+ const activeSource = tx.select().from(trafficSources).where(eq104(trafficSources.projectId, project.id)).all().find((row) => row.sourceType === TrafficSourceTypes.wordpress && row.status !== TrafficSourceStatuses.archived);
73006
73167
  const endpointChanged = activeSource !== void 0 && wordpressBaseUrlIdentity(activeSource.configJson.baseUrl) !== wordpressBaseUrlIdentity(baseUrl);
73007
- const sourceId = endpointChanged ? crypto60.randomUUID() : activeSource?.id ?? crypto60.randomUUID();
73168
+ const sourceId = endpointChanged ? crypto61.randomUUID() : activeSource?.id ?? crypto61.randomUUID();
73008
73169
  const sourceStatus = trafficConnectStatus(tx, project.id, activeSource);
73009
73170
  if (activeSource && !endpointChanged) {
73010
73171
  tx.update(trafficSources).set({
@@ -73013,14 +73174,14 @@ async function trafficRoutes(app, opts) {
73013
73174
  lastError: null,
73014
73175
  configJson: config,
73015
73176
  updatedAt: now
73016
- }).where(eq103(trafficSources.id, sourceId)).run();
73177
+ }).where(eq104(trafficSources.id, sourceId)).run();
73017
73178
  } else {
73018
73179
  if (activeSource) {
73019
73180
  tx.update(trafficSources).set({
73020
73181
  status: TrafficSourceStatuses.archived,
73021
73182
  archivedAt: now,
73022
73183
  updatedAt: now
73023
- }).where(eq103(trafficSources.id, activeSource.id)).run();
73184
+ }).where(eq104(trafficSources.id, activeSource.id)).run();
73024
73185
  }
73025
73186
  tx.insert(trafficSources).values({
73026
73187
  id: sourceId,
@@ -73046,7 +73207,7 @@ async function trafficRoutes(app, opts) {
73046
73207
  entityId: sourceId
73047
73208
  });
73048
73209
  return {
73049
- sourceRow: tx.select().from(trafficSources).where(eq103(trafficSources.id, sourceId)).get(),
73210
+ sourceRow: tx.select().from(trafficSources).where(eq104(trafficSources.id, sourceId)).get(),
73050
73211
  scheduleChanged: scheduleBinding.changed
73051
73212
  };
73052
73213
  }, { behavior: "immediate" });
@@ -73103,7 +73264,7 @@ async function trafficRoutes(app, opts) {
73103
73264
  const config = { projectId, teamId, environment };
73104
73265
  const fallbackName = displayName ?? `Vercel \xB7 ${projectId}`;
73105
73266
  const { sourceRow: sourceRow2, scheduleChanged } = app.db.transaction((tx) => {
73106
- const activeSource = tx.select().from(trafficSources).where(eq103(trafficSources.projectId, project.id)).all().find((row2) => row2.sourceType === TrafficSourceTypes.vercel && row2.status !== TrafficSourceStatuses.archived);
73267
+ const activeSource = tx.select().from(trafficSources).where(eq104(trafficSources.projectId, project.id)).all().find((row2) => row2.sourceType === TrafficSourceTypes.vercel && row2.status !== TrafficSourceStatuses.archived);
73107
73268
  const sourceStatus = trafficConnectStatus(tx, project.id, activeSource);
73108
73269
  let row;
73109
73270
  if (activeSource) {
@@ -73113,10 +73274,10 @@ async function trafficRoutes(app, opts) {
73113
73274
  lastError: null,
73114
73275
  configJson: config,
73115
73276
  updatedAt: now
73116
- }).where(eq103(trafficSources.id, activeSource.id)).run();
73117
- row = tx.select().from(trafficSources).where(eq103(trafficSources.id, activeSource.id)).get();
73277
+ }).where(eq104(trafficSources.id, activeSource.id)).run();
73278
+ row = tx.select().from(trafficSources).where(eq104(trafficSources.id, activeSource.id)).get();
73118
73279
  } else {
73119
- const newId = crypto60.randomUUID();
73280
+ const newId = crypto61.randomUUID();
73120
73281
  tx.insert(trafficSources).values({
73121
73282
  id: newId,
73122
73283
  projectId: project.id,
@@ -73139,7 +73300,7 @@ async function trafficRoutes(app, opts) {
73139
73300
  createdAt: now,
73140
73301
  updatedAt: now
73141
73302
  }).run();
73142
- row = tx.select().from(trafficSources).where(eq103(trafficSources.id, newId)).get();
73303
+ row = tx.select().from(trafficSources).where(eq104(trafficSources.id, newId)).get();
73143
73304
  }
73144
73305
  const scheduleBinding = sourceStatus === TrafficSourceStatuses.connected ? bindTrafficSyncSchedule(tx, project.id, row.id, now) : { changed: false, created: false };
73145
73306
  writeAuditLog(tx, {
@@ -73183,10 +73344,10 @@ async function trafficRoutes(app, opts) {
73183
73344
  const { displayName: displayName2, zoneId: zoneId2, accountId: accountId2, queueId, queueName, retentionSeconds, apiToken } = parsed.data;
73184
73345
  const workerRouteHost2 = resolveCloudflareWorkerRouteHost(project.canonicalDomain);
73185
73346
  const now2 = (/* @__PURE__ */ new Date()).toISOString();
73186
- const cloudflareSources = app.db.select().from(trafficSources).where(eq103(trafficSources.projectId, project.id)).all().filter((row) => row.sourceType === TrafficSourceTypes.cloudflare && row.status !== TrafficSourceStatuses.archived);
73347
+ const cloudflareSources = app.db.select().from(trafficSources).where(eq104(trafficSources.projectId, project.id)).all().filter((row) => row.sourceType === TrafficSourceTypes.cloudflare && row.status !== TrafficSourceStatuses.archived);
73187
73348
  const sameModeSource = cloudflareSources.find((row) => parseQueuePullCloudflareSourceConfig(row.configJson));
73188
73349
  if (sameModeSource) attempt.update({ action: "reauth" });
73189
- const sourceId2 = sameModeSource?.id ?? crypto60.randomUUID();
73350
+ const sourceId2 = sameModeSource?.id ?? crypto61.randomUUID();
73190
73351
  const previousCredential2 = credentialStore.getConnectionBySourceId(sourceId2);
73191
73352
  const forwardPageViews2 = parsed.data.forwardPageViews ?? (sameModeSource ? parseQueuePullCloudflareSourceConfig(sameModeSource.configJson)?.forwardPageViews : void 0) ?? false;
73192
73353
  const workerVersion2 = cloudflareWorkerVersionFor({ forwardPageViews: forwardPageViews2 });
@@ -73237,7 +73398,7 @@ async function trafficRoutes(app, opts) {
73237
73398
  let scheduleChanged = false;
73238
73399
  try {
73239
73400
  const result = app.db.transaction((tx) => {
73240
- const currentSameModeSource = tx.select().from(trafficSources).where(eq103(trafficSources.projectId, project.id)).all().find((row) => row.sourceType === TrafficSourceTypes.cloudflare && row.status !== TrafficSourceStatuses.archived && parseQueuePullCloudflareSourceConfig(row.configJson) !== null);
73401
+ const currentSameModeSource = tx.select().from(trafficSources).where(eq104(trafficSources.projectId, project.id)).all().find((row) => row.sourceType === TrafficSourceTypes.cloudflare && row.status !== TrafficSourceStatuses.archived && parseQueuePullCloudflareSourceConfig(row.configJson) !== null);
73241
73402
  if ((currentSameModeSource?.id ?? null) !== (sameModeSource?.id ?? null)) {
73242
73403
  throw operationInProgress("Cloudflare Queue source changed during connect; retry");
73243
73404
  }
@@ -73255,7 +73416,7 @@ async function trafficRoutes(app, opts) {
73255
73416
  queueBacklogObservedAt: null
73256
73417
  } : {},
73257
73418
  updatedAt: now2
73258
- }).where(eq103(trafficSources.id, sourceId2)).run();
73419
+ }).where(eq104(trafficSources.id, sourceId2)).run();
73259
73420
  } else {
73260
73421
  tx.insert(trafficSources).values({
73261
73422
  id: sourceId2,
@@ -73275,7 +73436,7 @@ async function trafficRoutes(app, opts) {
73275
73436
  }
73276
73437
  const changed = status === TrafficSourceStatuses.connected ? bindTrafficSyncSchedule(tx, project.id, sourceId2, now2).changed : false;
73277
73438
  return {
73278
- row: tx.select().from(trafficSources).where(eq103(trafficSources.id, sourceId2)).get(),
73439
+ row: tx.select().from(trafficSources).where(eq104(trafficSources.id, sourceId2)).get(),
73279
73440
  scheduleChanged: changed
73280
73441
  };
73281
73442
  }, { behavior: "immediate" });
@@ -73325,9 +73486,9 @@ async function trafficRoutes(app, opts) {
73325
73486
  const { deliveryMode, displayName, zoneId, accountId } = parsed.data;
73326
73487
  const workerRouteHost = resolveCloudflareWorkerRouteHost(project.canonicalDomain);
73327
73488
  const now = (/* @__PURE__ */ new Date()).toISOString();
73328
- const activeSource = app.db.select().from(trafficSources).where(eq103(trafficSources.projectId, project.id)).all().find((row) => row.sourceType === TrafficSourceTypes.cloudflare && row.status !== TrafficSourceStatuses.archived && parseDirectPushCloudflareSourceConfig(row.configJson) !== null);
73489
+ const activeSource = app.db.select().from(trafficSources).where(eq104(trafficSources.projectId, project.id)).all().find((row) => row.sourceType === TrafficSourceTypes.cloudflare && row.status !== TrafficSourceStatuses.archived && parseDirectPushCloudflareSourceConfig(row.configJson) !== null);
73329
73490
  if (activeSource) attempt.update({ action: "reauth" });
73330
- const sourceId = activeSource?.id ?? crypto60.randomUUID();
73491
+ const sourceId = activeSource?.id ?? crypto61.randomUUID();
73331
73492
  const parsedActiveConfig = activeSource ? parseDirectPushCloudflareSourceConfig(activeSource.configJson) : null;
73332
73493
  if (activeSource && !parsedActiveConfig) {
73333
73494
  throw validationError("Existing Cloudflare source is not configured for direct-push delivery");
@@ -73344,8 +73505,8 @@ async function trafficRoutes(app, opts) {
73344
73505
  const effectiveZoneId = zoneId ?? previousZoneId;
73345
73506
  const effectiveAccountId = accountId ?? previousAccountId;
73346
73507
  const forwardPageViews = parsed.data.forwardPageViews ?? parsedActiveConfig?.forwardPageViews ?? false;
73347
- const bearerToken = reusableCredential?.bearerToken ?? `cnry_cfw_${crypto60.randomBytes(32).toString("hex")}`;
73348
- const hmacSecret = reusableCredential?.hmacSecret ?? crypto60.randomBytes(32).toString("hex");
73508
+ const bearerToken = reusableCredential?.bearerToken ?? `cnry_cfw_${crypto61.randomBytes(32).toString("hex")}`;
73509
+ const hmacSecret = reusableCredential?.hmacSecret ?? crypto61.randomBytes(32).toString("hex");
73349
73510
  const ingestTokenHash = sha256Hex3(bearerToken);
73350
73511
  const ingestUrl = opts.cloudflareTrafficIngestUrl.replace("{name}", encodeURIComponent(project.name));
73351
73512
  assertCloudflareIngestUrlIsPublicHttps(ingestUrl);
@@ -73393,7 +73554,7 @@ async function trafficRoutes(app, opts) {
73393
73554
  let scheduleRemoved = false;
73394
73555
  try {
73395
73556
  const result = app.db.transaction((tx) => {
73396
- const currentActiveSource = tx.select().from(trafficSources).where(eq103(trafficSources.projectId, project.id)).all().find((row2) => row2.sourceType === TrafficSourceTypes.cloudflare && row2.status !== TrafficSourceStatuses.archived && parseDirectPushCloudflareSourceConfig(row2.configJson) !== null);
73557
+ const currentActiveSource = tx.select().from(trafficSources).where(eq104(trafficSources.projectId, project.id)).all().find((row2) => row2.sourceType === TrafficSourceTypes.cloudflare && row2.status !== TrafficSourceStatuses.archived && parseDirectPushCloudflareSourceConfig(row2.configJson) !== null);
73397
73558
  if ((currentActiveSource?.id ?? null) !== (activeSource?.id ?? null)) {
73398
73559
  throw operationInProgress("Cloudflare direct-push source changed during connect; retry");
73399
73560
  }
@@ -73407,8 +73568,8 @@ async function trafficRoutes(app, opts) {
73407
73568
  configJson: config,
73408
73569
  ingestTokenHash,
73409
73570
  updatedAt: now
73410
- }).where(eq103(trafficSources.id, currentActiveSource.id)).run();
73411
- row = tx.select().from(trafficSources).where(eq103(trafficSources.id, currentActiveSource.id)).get();
73571
+ }).where(eq104(trafficSources.id, currentActiveSource.id)).run();
73572
+ row = tx.select().from(trafficSources).where(eq104(trafficSources.id, currentActiveSource.id)).get();
73412
73573
  } else {
73413
73574
  tx.insert(trafficSources).values({
73414
73575
  id: sourceId,
@@ -73428,16 +73589,16 @@ async function trafficRoutes(app, opts) {
73428
73589
  createdAt: now,
73429
73590
  updatedAt: now
73430
73591
  }).run();
73431
- row = tx.select().from(trafficSources).where(eq103(trafficSources.id, sourceId)).get();
73592
+ row = tx.select().from(trafficSources).where(eq104(trafficSources.id, sourceId)).get();
73432
73593
  }
73433
73594
  let removed = false;
73434
73595
  if (row.status === TrafficSourceStatuses.connected) {
73435
73596
  const schedule = tx.select().from(schedules).where(and89(
73436
- eq103(schedules.projectId, project.id),
73437
- eq103(schedules.kind, SchedulableRunKinds["traffic-sync"])
73597
+ eq104(schedules.projectId, project.id),
73598
+ eq104(schedules.kind, SchedulableRunKinds["traffic-sync"])
73438
73599
  )).get();
73439
73600
  if (schedule) {
73440
- tx.delete(schedules).where(eq103(schedules.id, schedule.id)).run();
73601
+ tx.delete(schedules).where(eq104(schedules.id, schedule.id)).run();
73441
73602
  removed = true;
73442
73603
  }
73443
73604
  }
@@ -73493,47 +73654,47 @@ async function trafficRoutes(app, opts) {
73493
73654
  };
73494
73655
  }));
73495
73656
  app.post("/projects/:name/traffic/sources/:id/activate", connectionRoute(app, (request) => {
73496
- const source = app.db.select({ sourceType: trafficSources.sourceType }).from(trafficSources).where(eq103(trafficSources.id, request.params.id)).get();
73657
+ const source = app.db.select({ sourceType: trafficSources.sourceType }).from(trafficSources).where(eq104(trafficSources.id, request.params.id)).get();
73497
73658
  const integration = source ? TRAFFIC_SOURCE_INTEGRATIONS[source.sourceType] : void 0;
73498
73659
  return integration ? { integration, action: "select" } : void 0;
73499
73660
  }, async (request) => {
73500
73661
  const project = resolveProject(app.db, request.params.name);
73501
73662
  const now = (/* @__PURE__ */ new Date()).toISOString();
73502
73663
  const result = app.db.transaction((tx) => {
73503
- const target = tx.select().from(trafficSources).where(eq103(trafficSources.id, request.params.id)).get();
73664
+ const target = tx.select().from(trafficSources).where(eq104(trafficSources.id, request.params.id)).get();
73504
73665
  if (!target || target.projectId !== project.id || target.status === TrafficSourceStatuses.archived) {
73505
73666
  throw notFound("Traffic source", request.params.id);
73506
73667
  }
73507
73668
  const { usesPullSchedule } = validateTrafficSourceCredential(target, project.name);
73508
- const siblings = tx.select().from(trafficSources).where(eq103(trafficSources.projectId, project.id)).all();
73669
+ const siblings = tx.select().from(trafficSources).where(eq104(trafficSources.projectId, project.id)).all();
73509
73670
  for (const sibling of siblings) {
73510
73671
  if (sibling.id === target.id || sibling.status === TrafficSourceStatuses.archived) continue;
73511
73672
  tx.update(trafficSources).set({
73512
73673
  status: TrafficSourceStatuses.paused,
73513
73674
  updatedAt: now
73514
- }).where(eq103(trafficSources.id, sibling.id)).run();
73675
+ }).where(eq104(trafficSources.id, sibling.id)).run();
73515
73676
  }
73516
73677
  tx.update(trafficSources).set({
73517
73678
  status: TrafficSourceStatuses.connected,
73518
73679
  lastError: null,
73519
73680
  archivedAt: null,
73520
73681
  updatedAt: now
73521
- }).where(eq103(trafficSources.id, target.id)).run();
73682
+ }).where(eq104(trafficSources.id, target.id)).run();
73522
73683
  let scheduleAction = null;
73523
73684
  if (usesPullSchedule) {
73524
73685
  bindTrafficSyncSchedule(tx, project.id, target.id, now);
73525
73686
  scheduleAction = "upsert";
73526
73687
  } else {
73527
73688
  const schedule = tx.select().from(schedules).where(and89(
73528
- eq103(schedules.projectId, project.id),
73529
- eq103(schedules.kind, SchedulableRunKinds["traffic-sync"])
73689
+ eq104(schedules.projectId, project.id),
73690
+ eq104(schedules.kind, SchedulableRunKinds["traffic-sync"])
73530
73691
  )).get();
73531
73692
  if (schedule) {
73532
- tx.delete(schedules).where(eq103(schedules.id, schedule.id)).run();
73693
+ tx.delete(schedules).where(eq104(schedules.id, schedule.id)).run();
73533
73694
  scheduleAction = "delete";
73534
73695
  }
73535
73696
  }
73536
- const source = tx.select().from(trafficSources).where(eq103(trafficSources.id, target.id)).get();
73697
+ const source = tx.select().from(trafficSources).where(eq104(trafficSources.id, target.id)).get();
73537
73698
  writeAuditLog(tx, {
73538
73699
  projectId: project.id,
73539
73700
  actor: "api",
@@ -73601,7 +73762,7 @@ async function trafficRoutes(app, opts) {
73601
73762
  }
73602
73763
  const { bearerHash, credential } = authenticated;
73603
73764
  const sourceId = credential.sourceId;
73604
- const sourceRow2 = app.db.select().from(trafficSources).where(eq103(trafficSources.id, sourceId)).get();
73765
+ const sourceRow2 = app.db.select().from(trafficSources).where(eq104(trafficSources.id, sourceId)).get();
73605
73766
  if (!sourceRow2 || sourceRow2.sourceType !== TrafficSourceTypes.cloudflare || sourceRow2.status !== TrafficSourceStatuses.connected || !parseDirectPushCloudflareSourceConfig(sourceRow2.configJson) || !timingSafeEqualHex(bearerHash, sourceRow2.ingestTokenHash)) {
73606
73767
  throw authRequired();
73607
73768
  }
@@ -73681,7 +73842,7 @@ async function trafficRoutes(app, opts) {
73681
73842
  });
73682
73843
  app.post("/projects/:name/traffic/sources/:id/sync", async (request) => {
73683
73844
  const project = resolveProject(app.db, request.params.name);
73684
- const initialSourceRow = app.db.select().from(trafficSources).where(eq103(trafficSources.id, request.params.id)).get();
73845
+ const initialSourceRow = app.db.select().from(trafficSources).where(eq104(trafficSources.id, request.params.id)).get();
73685
73846
  if (!initialSourceRow || initialSourceRow.projectId !== project.id) {
73686
73847
  throw notFound("Traffic source", request.params.id);
73687
73848
  }
@@ -73701,7 +73862,7 @@ async function trafficRoutes(app, opts) {
73701
73862
  apiToken: credential.apiToken
73702
73863
  };
73703
73864
  const now = (/* @__PURE__ */ new Date()).toISOString();
73704
- const leaseOwner = crypto60.randomUUID();
73865
+ const leaseOwner = crypto61.randomUUID();
73705
73866
  if (!tryClaimTrafficSyncLease({
73706
73867
  db: app.db,
73707
73868
  sourceId: sourceRow2.id,
@@ -73711,7 +73872,7 @@ async function trafficRoutes(app, opts) {
73711
73872
  })) {
73712
73873
  throw operationInProgress("Cloudflare Queue source sync is already in progress", { sourceId: sourceRow2.id });
73713
73874
  }
73714
- const runId = crypto60.randomUUID();
73875
+ const runId = crypto61.randomUUID();
73715
73876
  const startedAt = (/* @__PURE__ */ new Date()).toISOString();
73716
73877
  const startedMs = Date.now();
73717
73878
  let acceptedEvents = 0;
@@ -73755,7 +73916,7 @@ async function trafficRoutes(app, opts) {
73755
73916
  });
73756
73917
  const finishSync = (status, error, stopReason) => {
73757
73918
  const queueDrain = drainSummary(stopReason);
73758
- app.db.update(runs).set({ status, finishedAt: committedAt, syncSummary: queueDrain, ...error ? { error } : {} }).where(eq103(runs.id, runId)).run();
73919
+ app.db.update(runs).set({ status, finishedAt: committedAt, syncSummary: queueDrain, ...error ? { error } : {} }).where(eq104(runs.id, runId)).run();
73759
73920
  writeAuditLog(app.db, {
73760
73921
  projectId: project.id,
73761
73922
  actor: "api",
@@ -73932,7 +74093,7 @@ async function trafficRoutes(app, opts) {
73932
74093
  now: (/* @__PURE__ */ new Date()).toISOString(),
73933
74094
  ttlMs: CLOUDFLARE_QUEUE_SYNC_LEASE_TTL_MS
73934
74095
  })) throw new Error("Queue sync lease was lost before acknowledgement");
73935
- const latestSource = app.db.select().from(trafficSources).where(eq103(trafficSources.id, sourceRow2.id)).get();
74096
+ const latestSource = app.db.select().from(trafficSources).where(eq104(trafficSources.id, sourceRow2.id)).get();
73936
74097
  if (!latestSource || latestSource.projectId !== project.id || latestSource.status !== TrafficSourceStatuses.connected || latestSource.syncLeaseOwner !== leaseOwner || !isDeepStrictEqual(latestSource.configJson, sourceRow2.configJson)) {
73937
74098
  throw validationError("Cloudflare Queue source was reconfigured before acknowledgement");
73938
74099
  }
@@ -74022,13 +74183,13 @@ async function trafficRoutes(app, opts) {
74022
74183
  error: safeError,
74023
74184
  finishedAt: failedAt,
74024
74185
  syncSummary: drainSummary(CloudflareQueueDrainStopReasons.error)
74025
- }).where(eq103(runs.id, runId)).run();
74026
- const latestSource = tx.select().from(trafficSources).where(eq103(trafficSources.id, sourceRow2.id)).get();
74186
+ }).where(eq104(runs.id, runId)).run();
74187
+ const latestSource = tx.select().from(trafficSources).where(eq104(trafficSources.id, sourceRow2.id)).get();
74027
74188
  if (latestSource && latestSource.status === TrafficSourceStatuses.connected && latestSource.syncLeaseOwner === leaseOwner && isDeepStrictEqual(latestSource.configJson, sourceRow2.configJson)) {
74028
74189
  tx.update(trafficSources).set({ lastError: safeError, updatedAt: failedAt }).where(and89(
74029
- eq103(trafficSources.id, sourceRow2.id),
74030
- eq103(trafficSources.status, TrafficSourceStatuses.connected),
74031
- eq103(trafficSources.syncLeaseOwner, leaseOwner)
74190
+ eq104(trafficSources.id, sourceRow2.id),
74191
+ eq104(trafficSources.status, TrafficSourceStatuses.connected),
74192
+ eq104(trafficSources.syncLeaseOwner, leaseOwner)
74032
74193
  )).run();
74033
74194
  }
74034
74195
  });
@@ -74047,12 +74208,12 @@ async function trafficRoutes(app, opts) {
74047
74208
  `Sync for source type "${sourceRow2.sourceType}" is not implemented yet \u2014 only cloud-run, wordpress, and vercel are supported in v1.`
74048
74209
  );
74049
74210
  }
74050
- const hasConnectedSibling = sourceRow2.status === TrafficSourceStatuses.error && app.db.select().from(trafficSources).where(eq103(trafficSources.projectId, project.id)).all().some((row) => row.id !== sourceRow2.id && row.status === TrafficSourceStatuses.connected);
74211
+ const hasConnectedSibling = sourceRow2.status === TrafficSourceStatuses.error && app.db.select().from(trafficSources).where(eq104(trafficSources.projectId, project.id)).all().some((row) => row.id !== sourceRow2.id && row.status === TrafficSourceStatuses.connected);
74051
74212
  if (sourceRow2.status === TrafficSourceStatuses.paused || sourceRow2.status === TrafficSourceStatuses.archived || hasConnectedSibling) {
74052
74213
  throw validationError("Traffic source must be active before it can sync");
74053
74214
  }
74054
74215
  const isWordpressSource = sourceRow2.sourceType === TrafficSourceTypes.wordpress;
74055
- const syncLeaseOwner = crypto60.randomUUID();
74216
+ const syncLeaseOwner = crypto61.randomUUID();
74056
74217
  if (!tryClaimTrafficSyncLease({
74057
74218
  db: app.db,
74058
74219
  sourceId: sourceRow2.id,
@@ -74070,7 +74231,7 @@ async function trafficRoutes(app, opts) {
74070
74231
  let windowEnd = syncWindowEnd;
74071
74232
  const startedAt = syncWindowEnd.toISOString();
74072
74233
  const syncStartedAtMs = syncWindowEnd.getTime();
74073
- const runId = crypto60.randomUUID();
74234
+ const runId = crypto61.randomUUID();
74074
74235
  app.db.insert(runs).values({
74075
74236
  id: runId,
74076
74237
  projectId: project.id,
@@ -74084,10 +74245,10 @@ async function trafficRoutes(app, opts) {
74084
74245
  const markFailed = (msg, errorCode2) => {
74085
74246
  const failedAt = (/* @__PURE__ */ new Date()).toISOString();
74086
74247
  app.db.transaction((tx) => {
74087
- tx.update(runs).set({ status: RunStatuses.failed, error: msg, finishedAt: failedAt }).where(eq103(runs.id, runId)).run();
74088
- const latestSource = tx.select().from(trafficSources).where(eq103(trafficSources.id, sourceRow2.id)).get();
74248
+ tx.update(runs).set({ status: RunStatuses.failed, error: msg, finishedAt: failedAt }).where(eq104(runs.id, runId)).run();
74249
+ const latestSource = tx.select().from(trafficSources).where(eq104(trafficSources.id, sourceRow2.id)).get();
74089
74250
  if (latestSource?.status === TrafficSourceStatuses.connected && isSameTrafficSourceGeneration(latestSource, sourceRow2) && latestSource.syncLeaseOwner === syncLeaseOwner) {
74090
- tx.update(trafficSources).set({ status: TrafficSourceStatuses.error, lastError: msg, updatedAt: failedAt }).where(eq103(trafficSources.id, sourceRow2.id)).run();
74251
+ tx.update(trafficSources).set({ status: TrafficSourceStatuses.error, lastError: msg, updatedAt: failedAt }).where(eq104(trafficSources.id, sourceRow2.id)).run();
74091
74252
  }
74092
74253
  });
74093
74254
  try {
@@ -74181,7 +74342,7 @@ async function trafficRoutes(app, opts) {
74181
74342
  }
74182
74343
  const credential = credentialStore.getConnection(project.name);
74183
74344
  if (!credential) {
74184
- app.db.delete(runs).where(eq103(runs.id, runId)).run();
74345
+ app.db.delete(runs).where(eq104(runs.id, runId)).run();
74185
74346
  throw validationError(
74186
74347
  `No WordPress credential found for project "${project.name}". Run "canonry traffic connect wordpress" first.`
74187
74348
  );
@@ -74215,14 +74376,14 @@ async function trafficRoutes(app, opts) {
74215
74376
  const windowEndIso2 = windowEnd.toISOString();
74216
74377
  const reservedAt = (/* @__PURE__ */ new Date()).toISOString();
74217
74378
  const reservedSource = app.db.transaction((tx) => {
74218
- const latestSource = tx.select().from(trafficSources).where(eq103(trafficSources.id, sourceRow2.id)).get();
74379
+ const latestSource = tx.select().from(trafficSources).where(eq104(trafficSources.id, sourceRow2.id)).get();
74219
74380
  if (!latestSource || !isAuthoritativeTrafficSource(tx, latestSource) || !isSameTrafficSourceGeneration(latestSource, sourceRow2) || latestSource.syncLeaseOwner !== syncLeaseOwner || latestSource.lastCursor || latestSource.wordpressPendingUntil) return void 0;
74220
74381
  tx.update(trafficSources).set({
74221
74382
  lastSyncedAt: windowStartIso2,
74222
74383
  wordpressPendingUntil: windowEndIso2,
74223
74384
  updatedAt: reservedAt
74224
- }).where(eq103(trafficSources.id, sourceRow2.id)).run();
74225
- return tx.select().from(trafficSources).where(eq103(trafficSources.id, sourceRow2.id)).get();
74385
+ }).where(eq104(trafficSources.id, sourceRow2.id)).run();
74386
+ return tx.select().from(trafficSources).where(eq104(trafficSources.id, sourceRow2.id)).get();
74226
74387
  }, { behavior: "immediate" });
74227
74388
  if (!reservedSource) {
74228
74389
  const message = "Traffic source changed while reserving the WordPress sync window; retry the sync.";
@@ -74282,12 +74443,12 @@ async function trafficRoutes(app, opts) {
74282
74443
  auditAction = "traffic.vercel.synced";
74283
74444
  const credentialStore = opts.vercelTrafficCredentialStore;
74284
74445
  if (!credentialStore) {
74285
- app.db.delete(runs).where(eq103(runs.id, runId)).run();
74446
+ app.db.delete(runs).where(eq104(runs.id, runId)).run();
74286
74447
  throw validationError("Vercel traffic credential storage is not configured for this deployment");
74287
74448
  }
74288
74449
  const credential = credentialStore.getConnection(project.name);
74289
74450
  if (!credential) {
74290
- app.db.delete(runs).where(eq103(runs.id, runId)).run();
74451
+ app.db.delete(runs).where(eq104(runs.id, runId)).run();
74291
74452
  throw validationError(
74292
74453
  `No Vercel credential found for project "${project.name}". Run "canonry traffic connect vercel" first.`
74293
74454
  );
@@ -74305,7 +74466,7 @@ async function trafficRoutes(app, opts) {
74305
74466
  if (cappedStartMs > clampedStartMs) {
74306
74467
  const previousSkip = sourceRow2.skippedThroughAt ? Date.parse(sourceRow2.skippedThroughAt) : Number.NaN;
74307
74468
  const skippedThrough = Number.isFinite(previousSkip) ? new Date(Math.max(previousSkip, cappedStartMs)) : new Date(cappedStartMs);
74308
- app.db.update(trafficSources).set({ skippedThroughAt: skippedThrough.toISOString() }).where(eq103(trafficSources.id, sourceRow2.id)).run();
74469
+ app.db.update(trafficSources).set({ skippedThroughAt: skippedThrough.toISOString() }).where(eq104(trafficSources.id, sourceRow2.id)).run();
74309
74470
  request.log.warn(
74310
74471
  {
74311
74472
  sourceId: sourceRow2.id,
@@ -74400,15 +74561,15 @@ async function trafficRoutes(app, opts) {
74400
74561
  throw providerError(`WordPress sync failed: ${msg}`);
74401
74562
  }
74402
74563
  const commitOutcome = app.db.transaction((tx) => {
74403
- const latestRow = tx.select().from(trafficSources).where(eq103(trafficSources.id, sourceRow2.id)).get();
74404
- const latestHasConnectedSibling = tx.select().from(trafficSources).where(eq103(trafficSources.projectId, project.id)).all().some((row) => row.id !== sourceRow2.id && row.status === TrafficSourceStatuses.connected);
74564
+ const latestRow = tx.select().from(trafficSources).where(eq104(trafficSources.id, sourceRow2.id)).get();
74565
+ const latestHasConnectedSibling = tx.select().from(trafficSources).where(eq104(trafficSources.projectId, project.id)).all().some((row) => row.id !== sourceRow2.id && row.status === TrafficSourceStatuses.connected);
74405
74566
  if (!latestRow || latestRow.status !== TrafficSourceStatuses.connected && latestRow.status !== TrafficSourceStatuses.error || latestHasConnectedSibling || latestRow.syncLeaseOwner !== syncLeaseOwner || !isSameTrafficSourceGeneration(latestRow, sourceRow2)) {
74406
74567
  const abortedAt = (/* @__PURE__ */ new Date()).toISOString();
74407
74568
  tx.update(runs).set({
74408
74569
  status: RunStatuses.failed,
74409
74570
  error: "Traffic source was deactivated or reconfigured during sync",
74410
74571
  finishedAt: abortedAt
74411
- }).where(eq103(runs.id, runId)).run();
74572
+ }).where(eq104(runs.id, runId)).run();
74412
74573
  return "source-inactive";
74413
74574
  }
74414
74575
  const previousIds = latestRow.lastEventIds ?? [];
@@ -74473,7 +74634,7 @@ async function trafficRoutes(app, opts) {
74473
74634
  crawlerEventsHourly.status
74474
74635
  ],
74475
74636
  set: {
74476
- hits: sql47`${crawlerEventsHourly.hits} + ${bucket.hits}`,
74637
+ hits: sql48`${crawlerEventsHourly.hits} + ${bucket.hits}`,
74477
74638
  sampledUserAgent: bucket.sampledUserAgent,
74478
74639
  updatedAt: finishedAt
74479
74640
  }
@@ -74504,7 +74665,7 @@ async function trafficRoutes(app, opts) {
74504
74665
  crawlerVerificationManifestsHourly.manifestId
74505
74666
  ],
74506
74667
  set: {
74507
- hits: sql47`${crawlerVerificationManifestsHourly.hits} + ${bucket.hits}`,
74668
+ hits: sql48`${crawlerVerificationManifestsHourly.hits} + ${bucket.hits}`,
74508
74669
  manifestJson: bucket.verificationManifest,
74509
74670
  updatedAt: finishedAt
74510
74671
  }
@@ -74538,7 +74699,7 @@ async function trafficRoutes(app, opts) {
74538
74699
  aiUserFetchEventsHourly.status
74539
74700
  ],
74540
74701
  set: {
74541
- hits: sql47`${aiUserFetchEventsHourly.hits} + ${bucket.hits}`,
74702
+ hits: sql48`${aiUserFetchEventsHourly.hits} + ${bucket.hits}`,
74542
74703
  sampledUserAgent: bucket.sampledUserAgent,
74543
74704
  updatedAt: finishedAt
74544
74705
  }
@@ -74569,7 +74730,7 @@ async function trafficRoutes(app, opts) {
74569
74730
  aiUserFetchVerificationManifestsHourly.manifestId
74570
74731
  ],
74571
74732
  set: {
74572
- hits: sql47`${aiUserFetchVerificationManifestsHourly.hits} + ${bucket.hits}`,
74733
+ hits: sql48`${aiUserFetchVerificationManifestsHourly.hits} + ${bucket.hits}`,
74573
74734
  manifestJson: bucket.verificationManifest,
74574
74735
  updatedAt: finishedAt
74575
74736
  }
@@ -74611,9 +74772,9 @@ async function trafficRoutes(app, opts) {
74611
74772
  // colliding bucket adds its paid and organic arrivals to the ones
74612
74773
  // already there rather than overwriting a single label.
74613
74774
  set: {
74614
- sessionsOrHits: sql47`${aiReferralEventsHourly.sessionsOrHits} + ${bucket.hits}`,
74615
- paidSessionsOrHits: sql47`${aiReferralEventsHourly.paidSessionsOrHits} + ${bucket.paidHits}`,
74616
- organicSessionsOrHits: sql47`${aiReferralEventsHourly.organicSessionsOrHits} + ${bucket.organicHits}`,
74775
+ sessionsOrHits: sql48`${aiReferralEventsHourly.sessionsOrHits} + ${bucket.hits}`,
74776
+ paidSessionsOrHits: sql48`${aiReferralEventsHourly.paidSessionsOrHits} + ${bucket.paidHits}`,
74777
+ organicSessionsOrHits: sql48`${aiReferralEventsHourly.organicSessionsOrHits} + ${bucket.organicHits}`,
74617
74778
  updatedAt: finishedAt
74618
74779
  }
74619
74780
  }).run();
@@ -74633,7 +74794,7 @@ async function trafficRoutes(app, opts) {
74633
74794
  }
74634
74795
  })();
74635
74796
  tx.insert(rawEventSamples).values({
74636
- id: crypto60.randomUUID(),
74797
+ id: crypto61.randomUUID(),
74637
74798
  projectId: project.id,
74638
74799
  sourceId: sourceRow2.id,
74639
74800
  ts: sampleTimestamp,
@@ -74695,8 +74856,8 @@ async function trafficRoutes(app, opts) {
74695
74856
  sourceUpdate.lastCursor = nextCursor ?? null;
74696
74857
  sourceUpdate.wordpressPendingUntil = nextCursor ? windowEnd.toISOString() : null;
74697
74858
  }
74698
- tx.update(trafficSources).set(sourceUpdate).where(eq103(trafficSources.id, sourceRow2.id)).run();
74699
- tx.update(runs).set({ status: RunStatuses.completed, finishedAt }).where(eq103(runs.id, runId)).run();
74859
+ tx.update(trafficSources).set(sourceUpdate).where(eq104(trafficSources.id, sourceRow2.id)).run();
74860
+ tx.update(runs).set({ status: RunStatuses.completed, finishedAt }).where(eq104(runs.id, runId)).run();
74700
74861
  return "committed";
74701
74862
  }, { behavior: "immediate" });
74702
74863
  if (commitOutcome === "source-inactive") {
@@ -74767,7 +74928,7 @@ async function trafficRoutes(app, opts) {
74767
74928
  });
74768
74929
  app.post("/projects/:name/traffic/sources/:id/backfill", async (request) => withFeatureOutcome(app, { feature: "server_traffic", operation: "backfill" }, async (recordOutcome) => {
74769
74930
  const project = resolveProject(app.db, request.params.name);
74770
- const sourceRow2 = app.db.select().from(trafficSources).where(eq103(trafficSources.id, request.params.id)).get();
74931
+ const sourceRow2 = app.db.select().from(trafficSources).where(eq104(trafficSources.id, request.params.id)).get();
74771
74932
  if (!sourceRow2 || sourceRow2.projectId !== project.id) {
74772
74933
  throw notFound("Traffic source", request.params.id);
74773
74934
  }
@@ -74879,8 +75040,8 @@ async function trafficRoutes(app, opts) {
74879
75040
  };
74880
75041
  }
74881
75042
  const startedAt = windowEnd.toISOString();
74882
- const runId = crypto60.randomUUID();
74883
- const leaseOwner = crypto60.randomUUID();
75043
+ const runId = crypto61.randomUUID();
75044
+ const leaseOwner = crypto61.randomUUID();
74884
75045
  if (!tryClaimTrafficSyncLease({
74885
75046
  db: app.db,
74886
75047
  sourceId: sourceRow2.id,
@@ -74892,7 +75053,7 @@ async function trafficRoutes(app, opts) {
74892
75053
  }
74893
75054
  try {
74894
75055
  app.db.transaction((tx) => {
74895
- const latestSource = tx.select().from(trafficSources).where(eq103(trafficSources.id, sourceRow2.id)).get();
75056
+ const latestSource = tx.select().from(trafficSources).where(eq104(trafficSources.id, sourceRow2.id)).get();
74896
75057
  if (!latestSource || !isAuthoritativeTrafficSource(tx, latestSource) || !isSameTrafficSourceGeneration(latestSource, sourceRow2)) {
74897
75058
  throw validationError("Traffic source must remain active and unchanged before it can backfill");
74898
75059
  }
@@ -74940,10 +75101,10 @@ async function trafficRoutes(app, opts) {
74940
75101
  function buildSourceDetail(projectId, row, since) {
74941
75102
  const crawlerPathRows = app.db.select({
74942
75103
  pathNormalized: crawlerEventsHourly.pathNormalized,
74943
- hits: sql47`COALESCE(SUM(${crawlerEventsHourly.hits}), 0)`
75104
+ hits: sql48`COALESCE(SUM(${crawlerEventsHourly.hits}), 0)`
74944
75105
  }).from(crawlerEventsHourly).where(
74945
75106
  and89(
74946
- eq103(crawlerEventsHourly.sourceId, row.id),
75107
+ eq104(crawlerEventsHourly.sourceId, row.id),
74947
75108
  gte27(crawlerEventsHourly.tsHour, since)
74948
75109
  )
74949
75110
  ).groupBy(crawlerEventsHourly.pathNormalized).all();
@@ -74951,41 +75112,41 @@ async function trafficRoutes(app, opts) {
74951
75112
  crawlerPathRows.map((r) => ({ pathNormalized: r.pathNormalized, hits: Number(r.hits) }))
74952
75113
  );
74953
75114
  const crawlerTotal = crawlerSegments.content + crawlerSegments.sitemap + crawlerSegments.robots + crawlerSegments.asset + crawlerSegments.other;
74954
- const aiUserFetchTotals = app.db.select({ total: sql47`COALESCE(SUM(${aiUserFetchEventsHourly.hits}), 0)` }).from(aiUserFetchEventsHourly).where(
75115
+ const aiUserFetchTotals = app.db.select({ total: sql48`COALESCE(SUM(${aiUserFetchEventsHourly.hits}), 0)` }).from(aiUserFetchEventsHourly).where(
74955
75116
  and89(
74956
- eq103(aiUserFetchEventsHourly.sourceId, row.id),
75117
+ eq104(aiUserFetchEventsHourly.sourceId, row.id),
74957
75118
  gte27(aiUserFetchEventsHourly.tsHour, since)
74958
75119
  )
74959
75120
  ).get();
74960
- const likelyFakeTotals = app.db.select({ total: sql47`COALESCE(SUM(${aiUserFetchLikelyFakeHourly.hits}), 0)` }).from(aiUserFetchLikelyFakeHourly).where(
75121
+ const likelyFakeTotals = app.db.select({ total: sql48`COALESCE(SUM(${aiUserFetchLikelyFakeHourly.hits}), 0)` }).from(aiUserFetchLikelyFakeHourly).where(
74961
75122
  and89(
74962
- eq103(aiUserFetchLikelyFakeHourly.sourceId, row.id),
75123
+ eq104(aiUserFetchLikelyFakeHourly.sourceId, row.id),
74963
75124
  gte27(aiUserFetchLikelyFakeHourly.tsHour, since)
74964
75125
  )
74965
75126
  ).get();
74966
75127
  const aiTotals = app.db.select({
74967
- total: sql47`COALESCE(SUM(${aiReferralEventsHourly.sessionsOrHits}), 0)`,
74968
- nonhop: sql47`COALESCE(SUM(CASE WHEN ${referralLandedCondition()} THEN ${aiReferralEventsHourly.sessionsOrHits} ELSE 0 END), 0)`,
74969
- landed: sql47`COALESCE(SUM(CASE WHEN ${countableReferralCondition()} THEN ${aiReferralEventsHourly.sessionsOrHits} ELSE 0 END), 0)`
75128
+ total: sql48`COALESCE(SUM(${aiReferralEventsHourly.sessionsOrHits}), 0)`,
75129
+ nonhop: sql48`COALESCE(SUM(CASE WHEN ${referralLandedCondition()} THEN ${aiReferralEventsHourly.sessionsOrHits} ELSE 0 END), 0)`,
75130
+ landed: sql48`COALESCE(SUM(CASE WHEN ${countableReferralCondition()} THEN ${aiReferralEventsHourly.sessionsOrHits} ELSE 0 END), 0)`
74970
75131
  }).from(aiReferralEventsHourly).where(
74971
75132
  and89(
74972
- eq103(aiReferralEventsHourly.sourceId, row.id),
75133
+ eq104(aiReferralEventsHourly.sourceId, row.id),
74973
75134
  gte27(aiReferralEventsHourly.tsHour, since)
74974
75135
  )
74975
75136
  ).get();
74976
- const sampleTotals = app.db.select({ total: sql47`COUNT(*)` }).from(rawEventSamples).where(
75137
+ const sampleTotals = app.db.select({ total: sql48`COUNT(*)` }).from(rawEventSamples).where(
74977
75138
  and89(
74978
- eq103(rawEventSamples.sourceId, row.id),
75139
+ eq104(rawEventSamples.sourceId, row.id),
74979
75140
  gte27(rawEventSamples.ts, since)
74980
75141
  )
74981
75142
  ).get();
74982
75143
  const latestRun2 = app.db.select().from(runs).where(
74983
75144
  and89(
74984
- eq103(runs.projectId, projectId),
74985
- eq103(runs.kind, RunKinds["traffic-sync"]),
74986
- eq103(runs.sourceId, row.id)
75145
+ eq104(runs.projectId, projectId),
75146
+ eq104(runs.kind, RunKinds["traffic-sync"]),
75147
+ eq104(runs.sourceId, row.id)
74987
75148
  )
74988
- ).orderBy(desc47(runs.startedAt)).limit(1).get();
75149
+ ).orderBy(desc48(runs.startedAt)).limit(1).get();
74989
75150
  return {
74990
75151
  ...rowToDto(row),
74991
75152
  totals24h: {
@@ -75021,7 +75182,7 @@ async function trafficRoutes(app, opts) {
75021
75182
  const now = (/* @__PURE__ */ new Date()).toISOString();
75022
75183
  let updatedRow;
75023
75184
  app.db.transaction((tx) => {
75024
- const sourceRow2 = tx.select().from(trafficSources).where(and89(eq103(trafficSources.projectId, project.id), eq103(trafficSources.id, request.params.id))).get();
75185
+ const sourceRow2 = tx.select().from(trafficSources).where(and89(eq104(trafficSources.projectId, project.id), eq104(trafficSources.id, request.params.id))).get();
75025
75186
  if (!sourceRow2) {
75026
75187
  throw notFound("traffic source", request.params.id);
75027
75188
  }
@@ -75035,7 +75196,7 @@ async function trafficRoutes(app, opts) {
75035
75196
  `Traffic source "${sourceRow2.id}" is staged. Activate it explicitly instead of resetting it.`
75036
75197
  );
75037
75198
  }
75038
- const hasConnectedSibling = tx.select().from(trafficSources).where(eq103(trafficSources.projectId, project.id)).all().some((row) => row.id !== sourceRow2.id && row.status === TrafficSourceStatuses.connected);
75199
+ const hasConnectedSibling = tx.select().from(trafficSources).where(eq104(trafficSources.projectId, project.id)).all().some((row) => row.id !== sourceRow2.id && row.status === TrafficSourceStatuses.connected);
75039
75200
  if (hasConnectedSibling) {
75040
75201
  throw validationError(
75041
75202
  `Traffic source "${sourceRow2.id}" is not authoritative. Activate it explicitly instead of resetting it.`
@@ -75052,7 +75213,7 @@ async function trafficRoutes(app, opts) {
75052
75213
  status: TrafficSourceStatuses.connected,
75053
75214
  lastError: null,
75054
75215
  updatedAt: now
75055
- }).where(eq103(trafficSources.id, sourceRow2.id)).run();
75216
+ }).where(eq104(trafficSources.id, sourceRow2.id)).run();
75056
75217
  writeAuditLog(tx, auditFromRequest(request, {
75057
75218
  projectId: project.id,
75058
75219
  actor: "api",
@@ -75060,7 +75221,7 @@ async function trafficRoutes(app, opts) {
75060
75221
  entityType: "traffic_source",
75061
75222
  entityId: sourceRow2.id
75062
75223
  }));
75063
- updatedRow = tx.select().from(trafficSources).where(eq103(trafficSources.id, sourceRow2.id)).get();
75224
+ updatedRow = tx.select().from(trafficSources).where(eq104(trafficSources.id, sourceRow2.id)).get();
75064
75225
  });
75065
75226
  return buildSourceDetail(project.id, updatedRow, new Date(Date.now() - 24 * 60 * 6e4).toISOString());
75066
75227
  }));
@@ -75072,7 +75233,7 @@ async function trafficRoutes(app, opts) {
75072
75233
  }
75073
75234
  let updatedRow;
75074
75235
  app.db.transaction((tx) => {
75075
- const sourceRow2 = tx.select().from(trafficSources).where(and89(eq103(trafficSources.projectId, project.id), eq103(trafficSources.id, request.params.id))).get();
75236
+ const sourceRow2 = tx.select().from(trafficSources).where(and89(eq104(trafficSources.projectId, project.id), eq104(trafficSources.id, request.params.id))).get();
75076
75237
  if (!sourceRow2) {
75077
75238
  throw notFound("traffic source", request.params.id);
75078
75239
  }
@@ -75085,7 +75246,7 @@ async function trafficRoutes(app, opts) {
75085
75246
  );
75086
75247
  }
75087
75248
  const now = (/* @__PURE__ */ new Date()).toISOString();
75088
- tx.update(trafficSources).set({ skippedThroughAt: null, updatedAt: now }).where(eq103(trafficSources.id, sourceRow2.id)).run();
75249
+ tx.update(trafficSources).set({ skippedThroughAt: null, updatedAt: now }).where(eq104(trafficSources.id, sourceRow2.id)).run();
75089
75250
  writeAuditLog(tx, auditFromRequest(request, {
75090
75251
  projectId: project.id,
75091
75252
  actor: "api",
@@ -75094,20 +75255,20 @@ async function trafficRoutes(app, opts) {
75094
75255
  entityId: sourceRow2.id,
75095
75256
  diff: { skippedThroughAt: sourceRow2.skippedThroughAt, sourceType: sourceRow2.sourceType }
75096
75257
  }));
75097
- updatedRow = tx.select().from(trafficSources).where(eq103(trafficSources.id, sourceRow2.id)).get();
75258
+ updatedRow = tx.select().from(trafficSources).where(eq104(trafficSources.id, sourceRow2.id)).get();
75098
75259
  });
75099
75260
  return buildSourceDetail(project.id, updatedRow, new Date(Date.now() - 24 * 60 * 6e4).toISOString());
75100
75261
  });
75101
75262
  app.get("/projects/:name/traffic/sources", async (request) => {
75102
75263
  const project = resolveProject(app.db, request.params.name);
75103
- const rows = app.db.select().from(trafficSources).where(eq103(trafficSources.projectId, project.id)).orderBy(desc47(trafficSources.createdAt)).all();
75264
+ const rows = app.db.select().from(trafficSources).where(eq104(trafficSources.projectId, project.id)).orderBy(desc48(trafficSources.createdAt)).all();
75104
75265
  const sources = rows.filter((row) => row.status !== TrafficSourceStatuses.archived).map(rowToDto);
75105
75266
  const response = { sources };
75106
75267
  return response;
75107
75268
  });
75108
75269
  app.get("/projects/:name/traffic/status", async (request) => {
75109
75270
  const project = resolveProject(app.db, request.params.name);
75110
- const rows = app.db.select().from(trafficSources).where(eq103(trafficSources.projectId, project.id)).orderBy(desc47(trafficSources.createdAt)).all();
75271
+ const rows = app.db.select().from(trafficSources).where(eq104(trafficSources.projectId, project.id)).orderBy(desc48(trafficSources.createdAt)).all();
75111
75272
  const since = new Date(Date.now() - 24 * 60 * 6e4).toISOString();
75112
75273
  const sources = rows.filter((row) => row.status !== TrafficSourceStatuses.archived).map((row) => buildSourceDetail(project.id, row, since));
75113
75274
  const response = { sources };
@@ -75117,7 +75278,7 @@ async function trafficRoutes(app, opts) {
75117
75278
  "/projects/:name/traffic/sources/:id",
75118
75279
  async (request) => {
75119
75280
  const project = resolveProject(app.db, request.params.name);
75120
- const row = app.db.select().from(trafficSources).where(eq103(trafficSources.id, request.params.id)).get();
75281
+ const row = app.db.select().from(trafficSources).where(eq104(trafficSources.id, request.params.id)).get();
75121
75282
  if (!row || row.projectId !== project.id) {
75122
75283
  throw notFound("Traffic source", request.params.id);
75123
75284
  }
@@ -75136,8 +75297,10 @@ async function trafficRoutes(app, opts) {
75136
75297
  }
75137
75298
  const sinceParam = request.query?.since;
75138
75299
  const untilParam = request.query?.until;
75139
- const since = sinceParam ? new Date(sinceParam) : defaultSince;
75140
- const until = untilParam ? new Date(untilParam) : now;
75300
+ const cursorParam = optionalQueryString(request.query?.cursor, "cursor");
75301
+ const cursorWindow = cursorParam === null ? null : readTrafficEventCursorWindow(cursorParam);
75302
+ const since = cursorWindow ? new Date(cursorWindow.since) : sinceParam ? new Date(sinceParam) : defaultSince;
75303
+ const until = cursorWindow ? new Date(cursorWindow.until) : untilParam ? new Date(untilParam) : now;
75141
75304
  if (Number.isNaN(since.getTime())) {
75142
75305
  throw validationError('"since" must be an ISO-8601 timestamp');
75143
75306
  }
@@ -75147,12 +75310,25 @@ async function trafficRoutes(app, opts) {
75147
75310
  if (since.getTime() > until.getTime()) {
75148
75311
  throw validationError('"since" must be \u2264 "until"');
75149
75312
  }
75313
+ if (cursorWindow) {
75314
+ const sameBound = (param, bound) => param === void 0 || !Number.isNaN(new Date(param).getTime()) && new Date(param).toISOString() === bound;
75315
+ if (!sameBound(sinceParam, cursorWindow.since) || !sameBound(untilParam, cursorWindow.until)) {
75316
+ throw validationError(`"cursor" keeps the first page's window. Leave "since" and "until" out, or repeat the first page's values.`);
75317
+ }
75318
+ }
75150
75319
  const kindParam = request.query?.kind;
75151
75320
  const kindList = kindParam === void 0 ? parseTrafficEventKindFilter("all") : typeof kindParam === "string" ? parseTrafficEventKindFilter(kindParam) : null;
75152
75321
  if (!kindList) {
75153
75322
  throw validationError(`"kind" must be ${TRAFFIC_EVENT_KIND_FILTER_HINT}`);
75154
75323
  }
75155
75324
  const kinds = new Set(kindList);
75325
+ const pathFilter = optionalQueryString(request.query?.path, "path");
75326
+ const agentFilter = optionalQueryString(request.query?.agent, "agent");
75327
+ const groupByParam = optionalQueryString(request.query?.groupBy, "groupBy");
75328
+ const groupBy = groupByParam === null ? null : parseTrafficEventGroupBy(groupByParam);
75329
+ if (groupByParam !== null && !groupBy) {
75330
+ throw validationError(`"groupBy" must be ${TRAFFIC_EVENT_GROUP_BY_HINT}`);
75331
+ }
75156
75332
  const limitParam = request.query?.limit;
75157
75333
  const requestedLimit = limitParam ? parseInt(limitParam, 10) : 500;
75158
75334
  if (!Number.isFinite(requestedLimit) || requestedLimit <= 0) {
@@ -75171,10 +75347,37 @@ async function trafficRoutes(app, opts) {
75171
75347
  );
75172
75348
  }
75173
75349
  }
75174
- const sourceIdParam = request.query?.sourceId;
75350
+ const sourceIdParam = optionalQueryString(request.query?.sourceId, "sourceId") ?? void 0;
75175
75351
  const sinceIso = since.toISOString();
75176
75352
  const untilIso = until.toISOString();
75177
- const events = [];
75353
+ const readFilters = {
75354
+ kinds: kindList,
75355
+ sourceId: sourceIdParam || null,
75356
+ path: pathFilter,
75357
+ agent: agentFilter
75358
+ };
75359
+ const cursor = cursorParam === null ? null : decodeTrafficEventCursor(cursorParam, readFilters, sinceIso, untilIso);
75360
+ const pageRows = (table, where, read) => read(cursor ? and89(where, trafficEventCursorPredicate(table, cursor)) : where, trafficEventOrder(table), limit + 1).map((row) => ({
75361
+ rank: table.rank,
75362
+ tsHour: row.tsHour,
75363
+ keys: table.keyFields.map((field) => row[field]),
75364
+ row
75365
+ }));
75366
+ const rankedPages = [];
75367
+ const groupEntries = [];
75368
+ const collectGroups = (table, where) => {
75369
+ if (!groupBy) return;
75370
+ const columns = trafficEventGroupColumns(table, groupBy);
75371
+ const groupColumns = Object.values(columns);
75372
+ const rows = app.db.select({
75373
+ ...columns,
75374
+ hits: sql48`COALESCE(SUM(${table.hits}), 0)`,
75375
+ rows: sql48`COUNT(*)`,
75376
+ firstHour: sql48`MIN(${table.tsHour})`,
75377
+ lastHour: sql48`MAX(${table.tsHour})`
75378
+ }).from(table.table).where(where).groupBy(...groupColumns).all();
75379
+ for (const row of rows) groupEntries.push(toTrafficEventGroup(table.kind, row));
75380
+ };
75178
75381
  let crawlerTotal = 0;
75179
75382
  let crawlerSegments = { content: 0, sitemap: 0, robots: 0, asset: 0, other: 0 };
75180
75383
  let aiUserFetchTotal = 0;
@@ -75186,16 +75389,18 @@ async function trafficRoutes(app, opts) {
75186
75389
  const seriesByBucket = /* @__PURE__ */ new Map();
75187
75390
  if (kinds.has(TrafficEventKinds.crawler)) {
75188
75391
  const crawlerFilters = [
75189
- eq103(crawlerEventsHourly.projectId, project.id),
75392
+ eq104(crawlerEventsHourly.projectId, project.id),
75190
75393
  gte27(crawlerEventsHourly.tsHour, sinceIso),
75191
75394
  lte27(crawlerEventsHourly.tsHour, untilIso)
75192
75395
  ];
75193
- if (sourceIdParam) crawlerFilters.push(eq103(crawlerEventsHourly.sourceId, sourceIdParam));
75396
+ if (sourceIdParam) crawlerFilters.push(eq104(crawlerEventsHourly.sourceId, sourceIdParam));
75397
+ crawlerFilters.push(...trafficEventFilterPredicates(TRAFFIC_EVENT_TABLES.crawler, readFilters));
75194
75398
  const crawlerWhere = and89(...crawlerFilters);
75399
+ collectGroups(TRAFFIC_EVENT_TABLES.crawler, crawlerWhere);
75195
75400
  const pathTotals = app.db.select({
75196
75401
  pathNormalized: crawlerEventsHourly.pathNormalized,
75197
- hits: sql47`COALESCE(SUM(${crawlerEventsHourly.hits}), 0)`,
75198
- rows: sql47`COUNT(*)`
75402
+ hits: sql48`COALESCE(SUM(${crawlerEventsHourly.hits}), 0)`,
75403
+ rows: sql48`COUNT(*)`
75199
75404
  }).from(crawlerEventsHourly).where(crawlerWhere).groupBy(crawlerEventsHourly.pathNormalized).all();
75200
75405
  crawlerSegments = segmentCrawlerHits(
75201
75406
  pathTotals.map((r) => ({ pathNormalized: r.pathNormalized, hits: Number(r.hits) }))
@@ -75214,12 +75419,12 @@ async function trafficRoutes(app, opts) {
75214
75419
  const listed = useContentList ? contentPaths : infraPaths;
75215
75420
  const IN_LIST_CAP = 2e4;
75216
75421
  const listFitsInSql = listed.length <= IN_LIST_CAP;
75217
- const contentExpr = listed.length === 0 ? useContentList ? sql47`0` : sql47`${crawlerEventsHourly.hits}` : useContentList ? sql47`CASE WHEN ${inArray48(crawlerEventsHourly.pathNormalized, listed)} THEN ${crawlerEventsHourly.hits} ELSE 0 END` : sql47`CASE WHEN ${inArray48(crawlerEventsHourly.pathNormalized, listed)} THEN 0 ELSE ${crawlerEventsHourly.hits} END`;
75422
+ const contentExpr = listed.length === 0 ? useContentList ? sql48`0` : sql48`${crawlerEventsHourly.hits}` : useContentList ? sql48`CASE WHEN ${inArray48(crawlerEventsHourly.pathNormalized, listed)} THEN ${crawlerEventsHourly.hits} ELSE 0 END` : sql48`CASE WHEN ${inArray48(crawlerEventsHourly.pathNormalized, listed)} THEN 0 ELSE ${crawlerEventsHourly.hits} END`;
75218
75423
  if (listFitsInSql) {
75219
75424
  const crawlerSeries = app.db.select({
75220
75425
  bucket: crawlerSeriesBucket,
75221
- hits: sql47`COALESCE(SUM(${crawlerEventsHourly.hits}), 0)`,
75222
- content: sql47`COALESCE(SUM(${contentExpr}), 0)`
75426
+ hits: sql48`COALESCE(SUM(${crawlerEventsHourly.hits}), 0)`,
75427
+ content: sql48`COALESCE(SUM(${contentExpr}), 0)`
75223
75428
  }).from(crawlerEventsHourly).where(crawlerWhere).groupBy(crawlerSeriesBucket).all();
75224
75429
  for (const row of crawlerSeries) {
75225
75430
  const point = trafficSeriesPoint(seriesByBucket, String(row.bucket));
@@ -75231,7 +75436,7 @@ async function trafficRoutes(app, opts) {
75231
75436
  const grouped = app.db.select({
75232
75437
  bucket: crawlerSeriesBucket,
75233
75438
  pathNormalized: crawlerEventsHourly.pathNormalized,
75234
- hits: sql47`COALESCE(SUM(${crawlerEventsHourly.hits}), 0)`
75439
+ hits: sql48`COALESCE(SUM(${crawlerEventsHourly.hits}), 0)`
75235
75440
  }).from(crawlerEventsHourly).where(crawlerWhere).groupBy(crawlerSeriesBucket, crawlerEventsHourly.pathNormalized).all();
75236
75441
  for (const row of grouped) {
75237
75442
  const point = trafficSeriesPoint(seriesByBucket, String(row.bucket));
@@ -75241,9 +75446,14 @@ async function trafficRoutes(app, opts) {
75241
75446
  if (useContentList ? inList : !inList) point.crawlerContentHits += hits;
75242
75447
  }
75243
75448
  }
75244
- const rows = app.db.select().from(crawlerEventsHourly).where(crawlerWhere).orderBy(desc47(crawlerEventsHourly.tsHour)).limit(limit).all();
75245
- for (const r of rows) {
75246
- events.push({
75449
+ const crawlerPage = pageRows(
75450
+ TRAFFIC_EVENT_TABLES.crawler,
75451
+ crawlerWhere,
75452
+ (where, order, take) => app.db.select().from(crawlerEventsHourly).where(where).orderBy(...order).limit(take).all()
75453
+ );
75454
+ rankedPages.push(crawlerPage.map(({ row: r, ...ranked }) => ({
75455
+ ...ranked,
75456
+ row: {
75247
75457
  kind: TrafficEventKinds.crawler,
75248
75458
  sourceId: r.sourceId,
75249
75459
  tsHour: r.tsHour,
@@ -75256,34 +75466,41 @@ async function trafficRoutes(app, opts) {
75256
75466
  pathClass: classifyTrafficPath(r.pathNormalized),
75257
75467
  status: r.status,
75258
75468
  hits: r.hits
75259
- });
75260
- }
75469
+ }
75470
+ })));
75261
75471
  }
75262
75472
  if (kinds.has(TrafficEventKinds["ai-user-fetch"])) {
75263
75473
  const userFetchFilters = [
75264
- eq103(aiUserFetchEventsHourly.projectId, project.id),
75474
+ eq104(aiUserFetchEventsHourly.projectId, project.id),
75265
75475
  gte27(aiUserFetchEventsHourly.tsHour, sinceIso),
75266
75476
  lte27(aiUserFetchEventsHourly.tsHour, untilIso)
75267
75477
  ];
75268
- if (sourceIdParam) userFetchFilters.push(eq103(aiUserFetchEventsHourly.sourceId, sourceIdParam));
75478
+ if (sourceIdParam) userFetchFilters.push(eq104(aiUserFetchEventsHourly.sourceId, sourceIdParam));
75479
+ userFetchFilters.push(...trafficEventFilterPredicates(TRAFFIC_EVENT_TABLES["ai-user-fetch"], readFilters));
75269
75480
  const userFetchWhere = and89(...userFetchFilters);
75481
+ collectGroups(TRAFFIC_EVENT_TABLES["ai-user-fetch"], userFetchWhere);
75270
75482
  const total = app.db.select({
75271
- total: sql47`COALESCE(SUM(${aiUserFetchEventsHourly.hits}), 0)`,
75272
- rows: sql47`COUNT(*)`
75483
+ total: sql48`COALESCE(SUM(${aiUserFetchEventsHourly.hits}), 0)`,
75484
+ rows: sql48`COUNT(*)`
75273
75485
  }).from(aiUserFetchEventsHourly).where(userFetchWhere).get();
75274
75486
  aiUserFetchTotal = Number(total?.total ?? 0);
75275
75487
  totalEventRows += Number(total?.rows ?? 0);
75276
75488
  const userFetchSeriesBucket = seriesBucketSql(aiUserFetchEventsHourly.tsHour, granularity);
75277
75489
  const userFetchSeries = app.db.select({
75278
75490
  bucket: userFetchSeriesBucket,
75279
- hits: sql47`COALESCE(SUM(${aiUserFetchEventsHourly.hits}), 0)`
75491
+ hits: sql48`COALESCE(SUM(${aiUserFetchEventsHourly.hits}), 0)`
75280
75492
  }).from(aiUserFetchEventsHourly).where(userFetchWhere).groupBy(userFetchSeriesBucket).all();
75281
75493
  for (const row of userFetchSeries) {
75282
75494
  trafficSeriesPoint(seriesByBucket, row.bucket).aiUserFetchHits = Number(row.hits);
75283
75495
  }
75284
- const rows = app.db.select().from(aiUserFetchEventsHourly).where(userFetchWhere).orderBy(desc47(aiUserFetchEventsHourly.tsHour)).limit(limit).all();
75285
- for (const r of rows) {
75286
- events.push({
75496
+ const userFetchPage = pageRows(
75497
+ TRAFFIC_EVENT_TABLES["ai-user-fetch"],
75498
+ userFetchWhere,
75499
+ (where, order, take) => app.db.select().from(aiUserFetchEventsHourly).where(where).orderBy(...order).limit(take).all()
75500
+ );
75501
+ rankedPages.push(userFetchPage.map(({ row: r, ...ranked }) => ({
75502
+ ...ranked,
75503
+ row: {
75287
75504
  kind: TrafficEventKinds["ai-user-fetch"],
75288
75505
  sourceId: r.sourceId,
75289
75506
  tsHour: r.tsHour,
@@ -75295,24 +75512,26 @@ async function trafficRoutes(app, opts) {
75295
75512
  pathNormalized: r.pathNormalized,
75296
75513
  status: r.status,
75297
75514
  hits: r.hits
75298
- });
75299
- }
75515
+ }
75516
+ })));
75300
75517
  }
75301
75518
  if (kinds.has(TrafficEventKinds["ai-referral"])) {
75302
75519
  const aiFilters = [
75303
- eq103(aiReferralEventsHourly.projectId, project.id),
75520
+ eq104(aiReferralEventsHourly.projectId, project.id),
75304
75521
  gte27(aiReferralEventsHourly.tsHour, sinceIso),
75305
75522
  lte27(aiReferralEventsHourly.tsHour, untilIso)
75306
75523
  ];
75307
- if (sourceIdParam) aiFilters.push(eq103(aiReferralEventsHourly.sourceId, sourceIdParam));
75524
+ if (sourceIdParam) aiFilters.push(eq104(aiReferralEventsHourly.sourceId, sourceIdParam));
75525
+ aiFilters.push(...trafficEventFilterPredicates(TRAFFIC_EVENT_TABLES["ai-referral"], readFilters));
75308
75526
  const aiWhere = and89(...aiFilters);
75527
+ collectGroups(TRAFFIC_EVENT_TABLES["ai-referral"], aiWhere);
75309
75528
  const total = app.db.select({
75310
- total: sql47`COALESCE(SUM(${aiReferralEventsHourly.sessionsOrHits}), 0)`,
75311
- nonhop: sql47`COALESCE(SUM(CASE WHEN ${referralLandedCondition()} THEN ${aiReferralEventsHourly.sessionsOrHits} ELSE 0 END), 0)`,
75312
- landed: sql47`COALESCE(SUM(CASE WHEN ${countableReferralCondition()} THEN ${aiReferralEventsHourly.sessionsOrHits} ELSE 0 END), 0)`,
75313
- paid: sql47`COALESCE(SUM(CASE WHEN ${countableReferralCondition()} THEN ${aiReferralEventsHourly.paidSessionsOrHits} ELSE 0 END), 0)`,
75314
- organic: sql47`COALESCE(SUM(CASE WHEN ${countableReferralCondition()} THEN ${aiReferralEventsHourly.organicSessionsOrHits} ELSE 0 END), 0)`,
75315
- rows: sql47`COUNT(*)`
75529
+ total: sql48`COALESCE(SUM(${aiReferralEventsHourly.sessionsOrHits}), 0)`,
75530
+ nonhop: sql48`COALESCE(SUM(CASE WHEN ${referralLandedCondition()} THEN ${aiReferralEventsHourly.sessionsOrHits} ELSE 0 END), 0)`,
75531
+ landed: sql48`COALESCE(SUM(CASE WHEN ${countableReferralCondition()} THEN ${aiReferralEventsHourly.sessionsOrHits} ELSE 0 END), 0)`,
75532
+ paid: sql48`COALESCE(SUM(CASE WHEN ${countableReferralCondition()} THEN ${aiReferralEventsHourly.paidSessionsOrHits} ELSE 0 END), 0)`,
75533
+ organic: sql48`COALESCE(SUM(CASE WHEN ${countableReferralCondition()} THEN ${aiReferralEventsHourly.organicSessionsOrHits} ELSE 0 END), 0)`,
75534
+ rows: sql48`COUNT(*)`
75316
75535
  }).from(aiReferralEventsHourly).where(aiWhere).get();
75317
75536
  aiReferralTotalHits = Number(total?.total ?? 0);
75318
75537
  aiReferralNonHopHits = Number(total?.nonhop ?? 0);
@@ -75326,36 +75545,44 @@ async function trafficRoutes(app, opts) {
75326
75545
  const referralSeriesBucket = seriesBucketSql(aiReferralEventsHourly.tsHour, granularity);
75327
75546
  const referralSeries = app.db.select({
75328
75547
  bucket: referralSeriesBucket,
75329
- hits: sql47`COALESCE(SUM(${aiReferralEventsHourly.sessionsOrHits}), 0)`,
75330
- landed: sql47`COALESCE(SUM(CASE WHEN ${countableReferralCondition()} THEN ${aiReferralEventsHourly.sessionsOrHits} ELSE 0 END), 0)`
75548
+ hits: sql48`COALESCE(SUM(${aiReferralEventsHourly.sessionsOrHits}), 0)`,
75549
+ landed: sql48`COALESCE(SUM(CASE WHEN ${countableReferralCondition()} THEN ${aiReferralEventsHourly.sessionsOrHits} ELSE 0 END), 0)`
75331
75550
  }).from(aiReferralEventsHourly).where(aiWhere).groupBy(referralSeriesBucket).all();
75332
75551
  for (const row of referralSeries) {
75333
75552
  const point = trafficSeriesPoint(seriesByBucket, row.bucket);
75334
75553
  point.aiReferralHits = Number(row.hits);
75335
75554
  point.aiReferralLandedHits = Number(row.landed);
75336
75555
  }
75337
- const rows = app.db.select().from(aiReferralEventsHourly).where(aiWhere).orderBy(desc47(aiReferralEventsHourly.tsHour)).limit(limit).all();
75338
- for (const r of rows) {
75556
+ const referralPage = pageRows(
75557
+ TRAFFIC_EVENT_TABLES["ai-referral"],
75558
+ aiWhere,
75559
+ (where, order, take) => app.db.select().from(aiReferralEventsHourly).where(where).orderBy(...order).limit(take).all()
75560
+ );
75561
+ rankedPages.push(referralPage.map(({ row: r, ...ranked }) => {
75339
75562
  const counts2 = aiReferralClassCounts(r.sessionsOrHits, r.paidSessionsOrHits, r.organicSessionsOrHits);
75340
- events.push({
75341
- kind: TrafficEventKinds["ai-referral"],
75342
- sourceId: r.sourceId,
75343
- tsHour: r.tsHour,
75344
- product: r.product,
75345
- operator: r.operator,
75346
- sourceDomain: r.sourceDomain,
75347
- evidenceType: r.evidenceType,
75348
- landingPathNormalized: r.landingPathNormalized,
75349
- status: r.status,
75350
- hits: counts2.total,
75351
- paidHits: counts2.paid,
75352
- organicHits: counts2.organic,
75353
- unknownHits: counts2.unknown
75354
- });
75355
- }
75563
+ return {
75564
+ ...ranked,
75565
+ row: {
75566
+ kind: TrafficEventKinds["ai-referral"],
75567
+ sourceId: r.sourceId,
75568
+ tsHour: r.tsHour,
75569
+ product: r.product,
75570
+ operator: r.operator,
75571
+ sourceDomain: r.sourceDomain,
75572
+ evidenceType: r.evidenceType,
75573
+ landingPathNormalized: r.landingPathNormalized,
75574
+ status: r.status,
75575
+ hits: counts2.total,
75576
+ paidHits: counts2.paid,
75577
+ organicHits: counts2.organic,
75578
+ unknownHits: counts2.unknown
75579
+ }
75580
+ };
75581
+ }));
75356
75582
  }
75357
- events.sort((a, b) => a.tsHour < b.tsHour ? 1 : a.tsHour > b.tsHour ? -1 : 0);
75358
- const trimmed = events.slice(0, limit);
75583
+ const { page: rankedPage, nextCursor } = mergeTrafficEventPages(rankedPages, limit, readFilters, sinceIso, untilIso);
75584
+ const trimmed = rankedPage.map((ranked) => ranked.row);
75585
+ groupEntries.sort(compareTrafficEventGroups);
75359
75586
  const trimmedCrawlerEvents = trimmed.filter(
75360
75587
  (event) => event.kind === TrafficEventKinds.crawler
75361
75588
  );
@@ -75380,11 +75607,11 @@ async function trafficRoutes(app, opts) {
75380
75607
  windowEnd: untilIso,
75381
75608
  series: (() => {
75382
75609
  const points = completeTrafficSeries(since, until, granularity, seriesByBucket);
75383
- const coverageScope = (col, srcCol) => sourceIdParam ? and89(eq103(col, project.id), eq103(srcCol, sourceIdParam)) : eq103(col, project.id);
75610
+ const coverageScope = (col, srcCol) => sourceIdParam ? and89(eq104(col, project.id), eq104(srcCol, sourceIdParam)) : eq104(col, project.id);
75384
75611
  const firsts = [
75385
- app.db.select({ v: sql47`MIN(${crawlerEventsHourly.tsHour})` }).from(crawlerEventsHourly).where(coverageScope(crawlerEventsHourly.projectId, crawlerEventsHourly.sourceId)).get()?.v,
75386
- app.db.select({ v: sql47`MIN(${aiUserFetchEventsHourly.tsHour})` }).from(aiUserFetchEventsHourly).where(coverageScope(aiUserFetchEventsHourly.projectId, aiUserFetchEventsHourly.sourceId)).get()?.v,
75387
- app.db.select({ v: sql47`MIN(${aiReferralEventsHourly.tsHour})` }).from(aiReferralEventsHourly).where(coverageScope(aiReferralEventsHourly.projectId, aiReferralEventsHourly.sourceId)).get()?.v
75612
+ app.db.select({ v: sql48`MIN(${crawlerEventsHourly.tsHour})` }).from(crawlerEventsHourly).where(coverageScope(crawlerEventsHourly.projectId, crawlerEventsHourly.sourceId)).get()?.v,
75613
+ app.db.select({ v: sql48`MIN(${aiUserFetchEventsHourly.tsHour})` }).from(aiUserFetchEventsHourly).where(coverageScope(aiUserFetchEventsHourly.projectId, aiUserFetchEventsHourly.sourceId)).get()?.v,
75614
+ app.db.select({ v: sql48`MIN(${aiReferralEventsHourly.tsHour})` }).from(aiReferralEventsHourly).where(coverageScope(aiReferralEventsHourly.projectId, aiReferralEventsHourly.sourceId)).get()?.v
75388
75615
  ].filter((v) => typeof v === "string" && v.length > 0);
75389
75616
  const referralCountingChangedAt = aiReferralOlderCountUntil(app.db, { projectId: project.id, sourceId: sourceIdParam });
75390
75617
  const referralCountingChangedMs = referralCountingChangedAt === null ? null : Date.parse(referralCountingChangedAt);
@@ -75462,19 +75689,30 @@ async function trafficRoutes(app, opts) {
75462
75689
  aiReferralOrganicHits: aiReferralCounts.organic,
75463
75690
  aiReferralUnknownHits: aiReferralCounts.unknown
75464
75691
  },
75692
+ filters: readFilters,
75465
75693
  eventRows: {
75466
75694
  total: totalEventRows,
75467
75695
  returned: trimmed.length,
75468
- truncated: trimmed.length < totalEventRows
75696
+ truncated: nextCursor !== null,
75697
+ nextCursor
75469
75698
  },
75470
- events: eventsWithProvenance
75699
+ events: eventsWithProvenance,
75700
+ ...groupBy ? {
75701
+ groups: {
75702
+ by: groupBy,
75703
+ total: groupEntries.length,
75704
+ returned: Math.min(groupEntries.length, limit),
75705
+ truncated: groupEntries.length > limit,
75706
+ entries: groupEntries.slice(0, limit)
75707
+ }
75708
+ } : {}
75471
75709
  };
75472
75710
  return response;
75473
75711
  });
75474
75712
  }
75475
75713
 
75476
75714
  // ../api-routes/src/doctor/checks/report-sweeps.ts
75477
- import { and as and90, asc as asc28, eq as eq104, gte as gte28, lte as lte28 } from "drizzle-orm";
75715
+ import { and as and90, asc as asc28, eq as eq105, gte as gte28, lte as lte28 } from "drizzle-orm";
75478
75716
 
75479
75717
  // ../api-routes/src/visibility-attribution.ts
75480
75718
  function buildQueryAttribution2(projectQueries) {
@@ -75508,11 +75746,11 @@ function inspectSweep(ctx, run) {
75508
75746
  answerMentioned: querySnapshots.answerMentioned,
75509
75747
  answerText: querySnapshots.answerText,
75510
75748
  measurementExecutionId: querySnapshots.measurementExecutionId
75511
- }).from(querySnapshots).where(eq104(querySnapshots.runId, run.id)).all();
75749
+ }).from(querySnapshots).where(eq105(querySnapshots.runId, run.id)).all();
75512
75750
  if (snapshots.length === 0) return { detail: { ...base, complete: false, reason: "no-answers" } };
75513
75751
  try {
75514
75752
  if (run.measurementPlanVersionId) {
75515
- const version = ctx.db.select().from(measurementPlanVersions).where(and90(eq104(measurementPlanVersions.projectId, ctx.project.id), eq104(measurementPlanVersions.id, run.measurementPlanVersionId))).get();
75753
+ const version = ctx.db.select().from(measurementPlanVersions).where(and90(eq105(measurementPlanVersions.projectId, ctx.project.id), eq105(measurementPlanVersions.id, run.measurementPlanVersionId))).get();
75516
75754
  if (!version) return { detail: { ...base, complete: false, reason: "missing-plan" } };
75517
75755
  const plan = parseStoredMeasurementPlanAnyVersion(version.canonicalJson);
75518
75756
  const manifest = measurementRunExpectedSlots(run, plan);
@@ -75544,10 +75782,10 @@ function inspectSweep(ctx, run) {
75544
75782
  };
75545
75783
  return unbound ? { detail } : { detail, coverage: slotCoverage(expected2, answered3) };
75546
75784
  }
75547
- const stored = ctx.db.select().from(simpleMeasurementDefinitions).where(eq104(simpleMeasurementDefinitions.runId, run.id)).get();
75785
+ const stored = ctx.db.select().from(simpleMeasurementDefinitions).where(eq105(simpleMeasurementDefinitions.runId, run.id)).get();
75548
75786
  const frozen = stored ? simpleMeasurementDefinitionSchema.parse(stored.definition) : null;
75549
- const project = ctx.db.select().from(projects).where(eq104(projects.id, ctx.project.id)).get();
75550
- const basket = frozen ? frozen.queries.map((query2) => ({ id: query2.queryId, query: query2.queryText })) : ctx.db.select({ id: queries.id, query: queries.query }).from(queries).where(eq104(queries.projectId, project.id)).all();
75787
+ const project = ctx.db.select().from(projects).where(eq105(projects.id, ctx.project.id)).get();
75788
+ const basket = frozen ? frozen.queries.map((query2) => ({ id: query2.queryId, query: query2.queryText })) : ctx.db.select({ id: queries.id, query: queries.query }).from(queries).where(eq105(queries.projectId, project.id)).all();
75551
75789
  const providers = frozen ? frozen.engines.map((engine) => engine.provider) : project.providers.length > 0 ? project.providers : [...new Set(snapshots.map((snapshot) => snapshot.provider))];
75552
75790
  const attribution = buildQueryAttribution2(basket);
75553
75791
  const expected = new Set(basket.flatMap((query2) => providers.map((provider) => JSON.stringify([query2.id, provider.trim().toLowerCase()]))));
@@ -75596,7 +75834,7 @@ var reportSweepsCheck = {
75596
75834
  const graded = gradedReportMonths(reportMonths, now);
75597
75835
  const months = reportMonths.map((month) => {
75598
75836
  const bounds = calendarMonthBounds(month);
75599
- const monthRuns = ctx.db.select().from(runs).where(and90(eq104(runs.projectId, ctx.project.id), eq104(runs.kind, RunKinds["answer-visibility"]), notProbeRun(), gte28(runs.createdAt, bounds.since), lte28(runs.createdAt, bounds.until))).orderBy(asc28(runs.createdAt), asc28(runs.id)).all();
75837
+ const monthRuns = ctx.db.select().from(runs).where(and90(eq105(runs.projectId, ctx.project.id), eq105(runs.kind, RunKinds["answer-visibility"]), notProbeRun(), gte28(runs.createdAt, bounds.since), lte28(runs.createdAt, bounds.until))).orderBy(asc28(runs.createdAt), asc28(runs.id)).all();
75600
75838
  const evidence = monthRuns.map((run) => inspectSweep(ctx, run));
75601
75839
  return {
75602
75840
  month,
@@ -75619,7 +75857,7 @@ var reportSweepsCheck = {
75619
75857
  };
75620
75858
 
75621
75859
  // ../api-routes/src/doctor/checks/report-models.ts
75622
- import { and as and91, eq as eq105, gte as gte29, inArray as inArray49, lte as lte29 } from "drizzle-orm";
75860
+ import { and as and91, eq as eq106, gte as gte29, inArray as inArray49, lte as lte29 } from "drizzle-orm";
75623
75861
  var reportModelsCheck = {
75624
75862
  id: "report.models",
75625
75863
  category: CheckCategories.providers,
@@ -75634,7 +75872,7 @@ var reportModelsCheck = {
75634
75872
  const months = reportMonths.flatMap((month) => {
75635
75873
  const bounds = calendarMonthBounds(month);
75636
75874
  const previous = new Date(Date.parse(bounds.since) - 1).toISOString().slice(0, 7);
75637
- const observations = ctx.db.select({ provider: querySnapshots.provider, model: querySnapshots.model, at: runs.createdAt }).from(querySnapshots).innerJoin(runs, eq105(runs.id, querySnapshots.runId)).where(and91(eq105(runs.projectId, ctx.project.id), eq105(runs.kind, RunKinds["answer-visibility"]), inArray49(runs.status, [RunStatuses.completed, RunStatuses.partial]), notProbeRun(), gte29(runs.createdAt, bounds.since), lte29(runs.createdAt, bounds.until))).all();
75875
+ const observations = ctx.db.select({ provider: querySnapshots.provider, model: querySnapshots.model, at: runs.createdAt }).from(querySnapshots).innerJoin(runs, eq106(runs.id, querySnapshots.runId)).where(and91(eq106(runs.projectId, ctx.project.id), eq106(runs.kind, RunKinds["answer-visibility"]), inArray49(runs.status, [RunStatuses.completed, RunStatuses.partial]), notProbeRun(), gte29(runs.createdAt, bounds.since), lte29(runs.createdAt, bounds.until))).all();
75638
75876
  return readVisibilityContinuity(ctx.db, ctx.project.name, { from: previous, to: month }).map(({ frame, continuity: continuity2 }) => ({
75639
75877
  month,
75640
75878
  previousMonth: previous,
@@ -75675,7 +75913,7 @@ var reportModelsCheck = {
75675
75913
  };
75676
75914
 
75677
75915
  // ../api-routes/src/doctor/checks/report-daily-data.ts
75678
- import { eq as eq106 } from "drizzle-orm";
75916
+ import { eq as eq107 } from "drizzle-orm";
75679
75917
  var REPORTING_LAG_DAYS = 3;
75680
75918
  function dateSpan(dates) {
75681
75919
  const sorted = [...dates].sort();
@@ -75684,31 +75922,31 @@ function dateSpan(dates) {
75684
75922
  function latestSyncRange(ctx, source) {
75685
75923
  const projectId = ctx.project.id;
75686
75924
  if (source === "ga") {
75687
- const rows2 = ctx.db.select({ date: gaDailyTotals.date, syncedAt: gaDailyTotals.syncedAt }).from(gaDailyTotals).where(eq106(gaDailyTotals.projectId, projectId)).all();
75925
+ const rows2 = ctx.db.select({ date: gaDailyTotals.date, syncedAt: gaDailyTotals.syncedAt }).from(gaDailyTotals).where(eq107(gaDailyTotals.projectId, projectId)).all();
75688
75926
  const latest2 = rows2.reduce((max2, row) => max2 === null || row.syncedAt > max2 ? row.syncedAt : max2, null);
75689
- const summary3 = ctx.db.select({ start: gaTrafficSummaries.periodStart, end: gaTrafficSummaries.periodEnd, syncedAt: gaTrafficSummaries.syncedAt }).from(gaTrafficSummaries).where(eq106(gaTrafficSummaries.projectId, projectId)).get();
75927
+ const summary3 = ctx.db.select({ start: gaTrafficSummaries.periodStart, end: gaTrafficSummaries.periodEnd, syncedAt: gaTrafficSummaries.syncedAt }).from(gaTrafficSummaries).where(eq107(gaTrafficSummaries.projectId, projectId)).get();
75690
75928
  if (summary3 && (latest2 === null || summary3.syncedAt >= latest2)) return { start: summary3.start, end: summary3.end, syncedAt: summary3.syncedAt };
75691
75929
  const span2 = dateSpan(rows2.filter((row) => row.syncedAt === latest2).map((row) => row.date));
75692
75930
  return span2 && latest2 !== null ? { ...span2, syncedAt: latest2 } : null;
75693
75931
  }
75694
- const rows = ctx.db.select({ date: gscDailyTotals.date, createdAt: gscDailyTotals.createdAt }).from(gscDailyTotals).where(eq106(gscDailyTotals.projectId, projectId)).all();
75932
+ const rows = ctx.db.select({ date: gscDailyTotals.date, createdAt: gscDailyTotals.createdAt }).from(gscDailyTotals).where(eq107(gscDailyTotals.projectId, projectId)).all();
75695
75933
  const latest = rows.reduce((max2, row) => max2 === null || row.createdAt > max2 ? row.createdAt : max2, null);
75696
75934
  const span = dateSpan(rows.filter((row) => row.createdAt === latest).map((row) => row.date));
75697
75935
  if (!span || latest === null) return null;
75698
- const watermark = ctx.db.select({ through: gscDataWatermarks.syncedThroughDate, updatedAt: gscDataWatermarks.updatedAt }).from(gscDataWatermarks).where(eq106(gscDataWatermarks.projectId, projectId)).get();
75936
+ const watermark = ctx.db.select({ through: gscDataWatermarks.syncedThroughDate, updatedAt: gscDataWatermarks.updatedAt }).from(gscDataWatermarks).where(eq107(gscDataWatermarks.projectId, projectId)).get();
75699
75937
  return watermark?.through && watermark.updatedAt === latest && watermark.through > span.end ? { start: span.start, end: watermark.through, syncedAt: latest } : { ...span, syncedAt: latest };
75700
75938
  }
75701
75939
  function dailyCoverage(ctx, month, source) {
75702
75940
  const project = ctx.project;
75703
75941
  const connection = source === "ga" ? ctx.ga4CredentialStore?.getConnection(project.name) ?? ctx.googleConnectionStore?.getConnection(project.canonicalDomain, "ga4") : ctx.googleConnectionStore?.getConnection(project.canonicalDomain, "gsc");
75704
- const stored = source === "ga" ? ctx.db.select({ date: gaDailyTotals.date, count: gaDailyTotals.sessions }).from(gaDailyTotals).where(eq106(gaDailyTotals.projectId, project.id)).all() : ctx.db.select({ date: gscDailyTotals.date, count: gscDailyTotals.impressions }).from(gscDailyTotals).where(eq106(gscDailyTotals.projectId, project.id)).all();
75942
+ const stored = source === "ga" ? ctx.db.select({ date: gaDailyTotals.date, count: gaDailyTotals.sessions }).from(gaDailyTotals).where(eq107(gaDailyTotals.projectId, project.id)).all() : ctx.db.select({ date: gscDailyTotals.date, count: gscDailyTotals.impressions }).from(gscDailyTotals).where(eq107(gscDailyTotals.projectId, project.id)).all();
75705
75943
  if (!connection && stored.length === 0) return null;
75706
75944
  const bounds = calendarMonthBounds(month);
75707
75945
  const start = bounds.since.slice(0, 10);
75708
75946
  const end = bounds.until.slice(0, 10);
75709
75947
  const timeZone = source === "gsc" ? "America/Los_Angeles" : "UTC";
75710
75948
  const matureThrough = isoDateDaysBeforeInTimeZone((/* @__PURE__ */ new Date()).toISOString(), REPORTING_LAG_DAYS, timeZone);
75711
- const created = ctx.db.select({ date: projects.createdAt }).from(projects).where(eq106(projects.id, project.id)).get().date.slice(0, 10);
75949
+ const created = ctx.db.select({ date: projects.createdAt }).from(projects).where(eq107(projects.id, project.id)).get().date.slice(0, 10);
75712
75950
  const connectedAt = connection?.createdAt?.slice(0, 10) ?? created;
75713
75951
  const onboardingDate = [connectedAt, ...stored.map((row) => row.date)].sort()[0];
75714
75952
  const byDate = new Map(stored.map((row) => [row.date, row.count]));
@@ -75790,7 +76028,7 @@ var reportDailyDataCheck = {
75790
76028
  };
75791
76029
 
75792
76030
  // ../api-routes/src/doctor/checks/referral-assessment.ts
75793
- import { and as and92, eq as eq107, ne as ne16 } from "drizzle-orm";
76031
+ import { and as and92, eq as eq108, ne as ne16 } from "drizzle-orm";
75794
76032
  var REFERRAL_ASSESSMENT_CHECKS = [{
75795
76033
  id: "report.ai-referral-bursts",
75796
76034
  category: CheckCategories.integrations,
@@ -75799,7 +76037,7 @@ var REFERRAL_ASSESSMENT_CHECKS = [{
75799
76037
  notificationPolicy: CheckNotificationPolicies.silent,
75800
76038
  run: (ctx) => {
75801
76039
  if (!ctx.project) return { status: CheckStatuses.skipped, code: "report.ai-referral-bursts.no-project", summary: "Select a project to inspect referral evidence." };
75802
- const configured = ctx.db.select({ id: trafficSources.id }).from(trafficSources).where(and92(eq107(trafficSources.projectId, ctx.project.id), ne16(trafficSources.status, TrafficSourceStatuses.archived))).get();
76040
+ const configured = ctx.db.select({ id: trafficSources.id }).from(trafficSources).where(and92(eq108(trafficSources.projectId, ctx.project.id), ne16(trafficSources.status, TrafficSourceStatuses.archived))).get();
75803
76041
  if (!configured) {
75804
76042
  return { status: CheckStatuses.skipped, code: "report.ai-referral-bursts.not-configured", summary: "No non-archived server traffic source is configured for this project." };
75805
76043
  }
@@ -75832,7 +76070,7 @@ var REFERRAL_ASSESSMENT_CHECKS = [{
75832
76070
  }];
75833
76071
 
75834
76072
  // ../api-routes/src/doctor/checks/agent.ts
75835
- import crypto61 from "crypto";
76073
+ import crypto62 from "crypto";
75836
76074
  import fs6 from "fs";
75837
76075
  import path7 from "path";
75838
76076
  var REQUIRED_SKILLS = ["canonry", "aero"];
@@ -76066,7 +76304,7 @@ function isInstalled(dir) {
76066
76304
  }
76067
76305
  function hashInstalledFile(filePath) {
76068
76306
  try {
76069
- return crypto61.createHash("sha256").update(fs6.readFileSync(filePath)).digest("hex");
76307
+ return crypto62.createHash("sha256").update(fs6.readFileSync(filePath)).digest("hex");
76070
76308
  } catch {
76071
76309
  return void 0;
76072
76310
  }
@@ -76211,19 +76449,19 @@ var BACKLINKS_CHECKS = [
76211
76449
  ];
76212
76450
 
76213
76451
  // ../api-routes/src/doctor/checks/bing-auth.ts
76214
- import { and as and93, desc as desc48, eq as eq108, inArray as inArray50 } from "drizzle-orm";
76452
+ import { and as and93, desc as desc49, eq as eq109, inArray as inArray50 } from "drizzle-orm";
76215
76453
  var BING_CONNECTION_ENTITY = "bing_connection";
76216
76454
  var BING_CONNECTED_ACTION = "bing.connected";
76217
76455
  var BING_DISCONNECTED_ACTION = "bing.disconnected";
76218
76456
  function lostBingConnection(ctx, project) {
76219
76457
  const hasRow = (row) => row !== void 0;
76220
- const storedData = hasRow(ctx.db.select({ id: bingCoverageSnapshots.id }).from(bingCoverageSnapshots).where(eq108(bingCoverageSnapshots.projectId, project.id)).limit(1).get()) || hasRow(ctx.db.select({ id: bingUrlInspections.id }).from(bingUrlInspections).where(eq108(bingUrlInspections.projectId, project.id)).limit(1).get()) || hasRow(ctx.db.select({ id: bingKeywordStats.id }).from(bingKeywordStats).where(eq108(bingKeywordStats.projectId, project.id)).limit(1).get()) || hasRow(ctx.db.select({ id: bingTrafficDaily.id }).from(bingTrafficDaily).where(eq108(bingTrafficDaily.projectId, project.id)).limit(1).get());
76458
+ const storedData = hasRow(ctx.db.select({ id: bingCoverageSnapshots.id }).from(bingCoverageSnapshots).where(eq109(bingCoverageSnapshots.projectId, project.id)).limit(1).get()) || hasRow(ctx.db.select({ id: bingUrlInspections.id }).from(bingUrlInspections).where(eq109(bingUrlInspections.projectId, project.id)).limit(1).get()) || hasRow(ctx.db.select({ id: bingKeywordStats.id }).from(bingKeywordStats).where(eq109(bingKeywordStats.projectId, project.id)).limit(1).get()) || hasRow(ctx.db.select({ id: bingTrafficDaily.id }).from(bingTrafficDaily).where(eq109(bingTrafficDaily.projectId, project.id)).limit(1).get());
76221
76459
  if (!storedData) return false;
76222
76460
  const lastChange = ctx.db.select({ action: auditLog.action }).from(auditLog).where(and93(
76223
- eq108(auditLog.entityType, BING_CONNECTION_ENTITY),
76224
- eq108(auditLog.entityId, project.canonicalDomain),
76461
+ eq109(auditLog.entityType, BING_CONNECTION_ENTITY),
76462
+ eq109(auditLog.entityId, project.canonicalDomain),
76225
76463
  inArray50(auditLog.action, [BING_CONNECTED_ACTION, BING_DISCONNECTED_ACTION])
76226
- )).orderBy(desc48(auditLog.createdAt)).limit(1).get();
76464
+ )).orderBy(desc49(auditLog.createdAt)).limit(1).get();
76227
76465
  return lastChange?.action !== BING_DISCONNECTED_ACTION;
76228
76466
  }
76229
76467
  var BING_AUTH_CHECKS = [
@@ -76380,7 +76618,7 @@ var BING_AUTH_CHECKS = [
76380
76618
  ];
76381
76619
 
76382
76620
  // ../api-routes/src/doctor/checks/content.ts
76383
- import { eq as eq109 } from "drizzle-orm";
76621
+ import { eq as eq110 } from "drizzle-orm";
76384
76622
  var WINNABILITY_COVERAGE_WARN_THRESHOLD = 0.8;
76385
76623
  var UNCLASSIFIED_DOMAIN_SAMPLE_LIMIT = 10;
76386
76624
  function skippedNoProject2() {
@@ -76393,7 +76631,7 @@ function skippedNoProject2() {
76393
76631
  }
76394
76632
  function loadProject(ctx) {
76395
76633
  if (!ctx.project) return null;
76396
- return ctx.db.select().from(projects).where(eq109(projects.id, ctx.project.id)).get() ?? null;
76634
+ return ctx.db.select().from(projects).where(eq110(projects.id, ctx.project.id)).get() ?? null;
76397
76635
  }
76398
76636
  var winnabilityCoverageCheck = {
76399
76637
  id: "content.winnability.coverage",
@@ -76486,7 +76724,7 @@ var CONTENT_CHECK_BY_ID = Object.fromEntries(
76486
76724
  );
76487
76725
 
76488
76726
  // ../api-routes/src/doctor/checks/ads.ts
76489
- import { eq as eq110 } from "drizzle-orm";
76727
+ import { eq as eq111 } from "drizzle-orm";
76490
76728
  var ADS_RECENT_SYNC_WARN_DAYS = 7;
76491
76729
  var ADS_RECENT_SYNC_FAIL_DAYS = 30;
76492
76730
  var adsConnectionCheck = {
@@ -76503,7 +76741,7 @@ var adsConnectionCheck = {
76503
76741
  remediation: null
76504
76742
  };
76505
76743
  }
76506
- const row = ctx.db.select().from(adsConnections).where(eq110(adsConnections.projectId, ctx.project.id)).get();
76744
+ const row = ctx.db.select().from(adsConnections).where(eq111(adsConnections.projectId, ctx.project.id)).get();
76507
76745
  if (!row) {
76508
76746
  return {
76509
76747
  status: CheckStatuses.skipped,
@@ -76553,7 +76791,7 @@ var adsRecentSyncCheck = {
76553
76791
  remediation: null
76554
76792
  };
76555
76793
  }
76556
- const row = ctx.db.select().from(adsConnections).where(eq110(adsConnections.projectId, ctx.project.id)).get();
76794
+ const row = ctx.db.select().from(adsConnections).where(eq111(adsConnections.projectId, ctx.project.id)).get();
76557
76795
  if (!row) {
76558
76796
  return {
76559
76797
  status: CheckStatuses.skipped,
@@ -76768,7 +77006,7 @@ var ga4ConnectionCheck = {
76768
77006
  var GA_AUTH_CHECKS = [ga4ConnectionCheck];
76769
77007
 
76770
77008
  // ../api-routes/src/doctor/checks/data-freshness.ts
76771
- import { and as and94, desc as desc49, eq as eq111, inArray as inArray51 } from "drizzle-orm";
77009
+ import { and as and94, desc as desc50, eq as eq112, inArray as inArray51 } from "drizzle-orm";
76772
77010
  var GA_DATA_AGING_DAYS = 3;
76773
77011
  var GA_DATA_STALE_DAYS = 5;
76774
77012
  var GSC_DATA_AGING_DAYS = 5;
@@ -76798,7 +77036,7 @@ function skipped(code, summary3) {
76798
77036
  return { status: CheckStatuses.skipped, code, summary: summary3, remediation: null };
76799
77037
  }
76800
77038
  function lastSyncAgeDays(ctx, kinds) {
76801
- const row = ctx.db.select({ createdAt: runs.createdAt }).from(runs).where(and94(eq111(runs.projectId, ctx.project.id), inArray51(runs.kind, kinds), eq111(runs.status, "completed"))).orderBy(desc49(runs.createdAt)).limit(1).get();
77039
+ const row = ctx.db.select({ createdAt: runs.createdAt }).from(runs).where(and94(eq112(runs.projectId, ctx.project.id), inArray51(runs.kind, kinds), eq112(runs.status, "completed"))).orderBy(desc50(runs.createdAt)).limit(1).get();
76802
77040
  if (!row?.createdAt) return null;
76803
77041
  const age = Math.floor((Date.now() - Date.parse(row.createdAt)) / DAY_MS6);
76804
77042
  return Number.isFinite(age) ? age : null;
@@ -76900,7 +77138,7 @@ var gaRecentDataCheck = {
76900
77138
  const connection = gaConnected(ctx);
76901
77139
  if (connection === "store-unavailable") return skipped("ga.data.store-unavailable", "No GA4 credential store configured for this deployment.");
76902
77140
  if (connection === "not-connected") return skipped("ga.data.not-connected", "GA4 is not connected for this project.");
76903
- const newest = ctx.db.select({ date: gaDailyTotals.date }).from(gaDailyTotals).where(eq111(gaDailyTotals.projectId, ctx.project.id)).orderBy(desc49(gaDailyTotals.date)).limit(1).get();
77141
+ const newest = ctx.db.select({ date: gaDailyTotals.date }).from(gaDailyTotals).where(eq112(gaDailyTotals.projectId, ctx.project.id)).orderBy(desc50(gaDailyTotals.date)).limit(1).get();
76904
77142
  return grade(ctx, GA_SPEC, newest?.date);
76905
77143
  }
76906
77144
  };
@@ -76915,16 +77153,16 @@ var gscRecentDataCheck = {
76915
77153
  if (!ctx.googleConnectionStore.getConnection(ctx.project.canonicalDomain, "gsc")) {
76916
77154
  return skipped("gsc.data.not-connected", "Search Console is not connected for this project.");
76917
77155
  }
76918
- const watermark = ctx.db.select({ dataThroughDate: gscDataWatermarks.dataThroughDate }).from(gscDataWatermarks).where(eq111(gscDataWatermarks.projectId, ctx.project.id)).get();
77156
+ const watermark = ctx.db.select({ dataThroughDate: gscDataWatermarks.dataThroughDate }).from(gscDataWatermarks).where(eq112(gscDataWatermarks.projectId, ctx.project.id)).get();
76919
77157
  if (watermark?.dataThroughDate) return grade(ctx, GSC_SPEC, watermark.dataThroughDate);
76920
- const newest = ctx.db.select({ date: gscDailyTotals.date }).from(gscDailyTotals).where(eq111(gscDailyTotals.projectId, ctx.project.id)).orderBy(desc49(gscDailyTotals.date)).limit(1).get();
77158
+ const newest = ctx.db.select({ date: gscDailyTotals.date }).from(gscDailyTotals).where(eq112(gscDailyTotals.projectId, ctx.project.id)).orderBy(desc50(gscDailyTotals.date)).limit(1).get();
76921
77159
  return grade(ctx, GSC_SPEC, newest?.date);
76922
77160
  }
76923
77161
  };
76924
77162
  var DATA_FRESHNESS_CHECKS = [gaRecentDataCheck, gscRecentDataCheck];
76925
77163
 
76926
77164
  // ../api-routes/src/doctor/checks/seo-refresh.ts
76927
- import { and as and95, asc as asc29, desc as desc50, eq as eq112, gt as gt9, inArray as inArray52, sql as sql48 } from "drizzle-orm";
77165
+ import { and as and95, asc as asc29, desc as desc51, eq as eq113, gt as gt9, inArray as inArray52, sql as sql49 } from "drizzle-orm";
76928
77166
  var GRACE_DAYS = 2;
76929
77167
  var DAY_MS7 = 24 * 60 * 60 * 1e3;
76930
77168
  var FIRING_SPAN_MS = 6e4;
@@ -76933,7 +77171,7 @@ function skipped2(code, summary3) {
76933
77171
  return { status: CheckStatuses.skipped, code, summary: summary3, remediation: null };
76934
77172
  }
76935
77173
  function seoSyncRuns(projectId) {
76936
- return and95(eq112(runs.projectId, projectId), eq112(runs.kind, RunKinds["seo-sync"]));
77174
+ return and95(eq113(runs.projectId, projectId), eq113(runs.kind, RunKinds["seo-sync"]));
76937
77175
  }
76938
77176
  function scheduleTiming(schedule) {
76939
77177
  if (!schedule.recurrence) return { cronExpr: schedule.cronExpr, timezone: schedule.timezone, recurrence: null };
@@ -76941,16 +77179,16 @@ function scheduleTiming(schedule) {
76941
77179
  return recurrence ? { cronExpr: schedule.cronExpr, timezone: schedule.timezone, recurrence } : null;
76942
77180
  }
76943
77181
  function latestFiring(ctx, projectId, enabledSince) {
76944
- const scheduled = and95(seoSyncRuns(projectId), eq112(runs.trigger, RunTriggers.scheduled), gt9(runs.createdAt, enabledSince));
76945
- const newest = ctx.db.select({ createdAt: runs.createdAt }).from(runs).where(scheduled).orderBy(desc50(runs.createdAt)).limit(1).get();
77182
+ const scheduled = and95(seoSyncRuns(projectId), eq113(runs.trigger, RunTriggers.scheduled), gt9(runs.createdAt, enabledSince));
77183
+ const newest = ctx.db.select({ createdAt: runs.createdAt }).from(runs).where(scheduled).orderBy(desc51(runs.createdAt)).limit(1).get();
76946
77184
  if (!newest) return [];
76947
77185
  const newestMs = Date.parse(newest.createdAt);
76948
77186
  const after = Number.isFinite(newestMs) ? new Date(newestMs - FIRING_SPAN_MS).toISOString() : newest.createdAt;
76949
77187
  return ctx.db.select({ id: runs.id, status: runs.status, error: runs.error, createdAt: runs.createdAt }).from(runs).where(and95(scheduled, gt9(runs.createdAt, after))).orderBy(asc29(runs.createdAt), asc29(runs.id)).all();
76950
77188
  }
76951
77189
  function lastCompleted(ctx, projectId) {
76952
- const at = sql48`coalesce(${runs.finishedAt}, ${runs.createdAt})`;
76953
- return ctx.db.select({ id: runs.id, at }).from(runs).where(and95(seoSyncRuns(projectId), eq112(runs.status, RunStatuses.completed))).orderBy(desc50(at)).limit(1).get() ?? null;
77190
+ const at = sql49`coalesce(${runs.finishedAt}, ${runs.createdAt})`;
77191
+ return ctx.db.select({ id: runs.id, at }).from(runs).where(and95(seoSyncRuns(projectId), eq113(runs.status, RunStatuses.completed))).orderBy(desc51(at)).limit(1).get() ?? null;
76954
77192
  }
76955
77193
  function isIncomplete(run) {
76956
77194
  return run.status === RunStatuses.failed || run.status === RunStatuses.partial;
@@ -76964,7 +77202,7 @@ function unsettledRuns(ctx, projectId, firing, profiles) {
76964
77202
  const incomplete = firing.filter(isIncomplete);
76965
77203
  const firedAt = firing[firing.length - 1]?.createdAt;
76966
77204
  if (incomplete.length === 0 || !firedAt) return incomplete;
76967
- const refreshed = new Set(ctx.db.select({ profileId: seoJobs.profileId }).from(runs).innerJoin(seoJobs, eq112(seoJobs.runId, runs.id)).where(and95(seoSyncRuns(projectId), eq112(runs.status, RunStatuses.completed), gt9(runs.createdAt, firedAt))).all().map((row) => row.profileId));
77205
+ const refreshed = new Set(ctx.db.select({ profileId: seoJobs.profileId }).from(runs).innerJoin(seoJobs, eq113(seoJobs.runId, runs.id)).where(and95(seoSyncRuns(projectId), eq113(runs.status, RunStatuses.completed), gt9(runs.createdAt, firedAt))).all().map((row) => row.profileId));
76968
77206
  return incomplete.filter((run) => {
76969
77207
  const profile = profiles.get(run.id) ?? null;
76970
77208
  return profile === null ? refreshed.size === 0 : !refreshed.has(profile);
@@ -76974,7 +77212,7 @@ var COUNT_LIST = new Intl.ListFormat("en", { style: "long", type: "conjunction"
76974
77212
  function refreshReason(ctx, run) {
76975
77213
  const stored = parseRunError(run.error);
76976
77214
  if (stored) return formatRunErrorOneLine(stored);
76977
- const tasks = currentSeoTasks(ctx.db.select({ id: seoTasks.id, retryOf: seoTasks.retryOf, status: seoTasks.status, error: seoTasks.error, request: seoTasks.request }).from(seoTasks).innerJoin(seoJobs, eq112(seoTasks.jobId, seoJobs.id)).where(eq112(seoJobs.runId, run.id)).all());
77215
+ const tasks = currentSeoTasks(ctx.db.select({ id: seoTasks.id, retryOf: seoTasks.retryOf, status: seoTasks.status, error: seoTasks.error, request: seoTasks.request }).from(seoTasks).innerJoin(seoJobs, eq113(seoTasks.jobId, seoJobs.id)).where(eq113(seoJobs.runId, run.id)).all());
76978
77216
  const failed = tasks.filter((task) => task.status === SeoRunStatuses.failed || task.status === SeoRunStatuses["reconciliation-required"]);
76979
77217
  const partial = tasks.filter((task) => task.status === SeoRunStatuses.partial).length;
76980
77218
  const cancelled = tasks.filter((task) => task.status === SeoRunStatuses.cancelled).length;
@@ -76994,7 +77232,7 @@ function refreshReason(ctx, run) {
76994
77232
  return `Of ${tasks.length} ${unit}, ${COUNT_LIST.format(counts2)}.${errors ? ` ${errors}` : ""}`;
76995
77233
  }
76996
77234
  function gradeSeoRefresh(ctx, project) {
76997
- const schedule = ctx.db.select().from(schedules).where(and95(eq112(schedules.projectId, project.id), eq112(schedules.kind, SchedulableRunKinds["seo-sync"]))).get();
77235
+ const schedule = ctx.db.select().from(schedules).where(and95(eq113(schedules.projectId, project.id), eq113(schedules.kind, SchedulableRunKinds["seo-sync"]))).get();
76998
77236
  if (!schedule) return skipped2("seo.data.not-scheduled", "No SEO refresh schedule is set for this project.");
76999
77237
  if (!schedule.enabled) return skipped2("seo.data.not-scheduled", "The SEO refresh schedule is disabled.");
77000
77238
  const name = project.name;
@@ -77376,7 +77614,7 @@ var siteReachabilityCheck = {
77376
77614
  var SITE_REACHABILITY_CHECKS = [siteReachabilityCheck];
77377
77615
 
77378
77616
  // ../api-routes/src/doctor/checks/api-hosts.ts
77379
- import { eq as eq114 } from "drizzle-orm";
77617
+ import { eq as eq115 } from "drizzle-orm";
77380
77618
 
77381
77619
  // ../api-routes/src/api-host-probe.ts
77382
77620
  import dns4 from "dns/promises";
@@ -77482,7 +77720,7 @@ async function probeApiHost(host, options = {}) {
77482
77720
  }
77483
77721
 
77484
77722
  // ../api-routes/src/doctor/checks/integration-sync.ts
77485
- import { and as and96, count as count9, desc as desc51, eq as eq113, gte as gte30, gt as gt10, inArray as inArray53, isNull as isNull18, notInArray as notInArray3, or as or20 } from "drizzle-orm";
77723
+ import { and as and96, count as count9, desc as desc52, eq as eq114, gte as gte30, gt as gt10, inArray as inArray53, isNull as isNull18, notInArray as notInArray3, or as or21 } from "drizzle-orm";
77486
77724
  var SYNC_FAILURE_WINDOW = 3;
77487
77725
  var SUMMARY_ERROR_LIMIT = 300;
77488
77726
  var FINISHED_STATUSES = [RunStatuses.completed, RunStatuses.partial, RunStatuses.failed];
@@ -77509,7 +77747,7 @@ function gscConnection(ctx, project) {
77509
77747
  function gbpConnection(ctx, project) {
77510
77748
  if (!ctx.googleConnectionStore) return { state: "store-unavailable" };
77511
77749
  if (!ctx.googleConnectionStore.getConnection(project.canonicalDomain, "gbp")) return { state: "not-connected" };
77512
- const selected = ctx.db.select({ locationName: gbpLocations.locationName }).from(gbpLocations).where(and96(eq113(gbpLocations.projectId, project.id), eq113(gbpLocations.selected, true))).limit(1).get();
77750
+ const selected = ctx.db.select({ locationName: gbpLocations.locationName }).from(gbpLocations).where(and96(eq114(gbpLocations.projectId, project.id), eq114(gbpLocations.selected, true))).limit(1).get();
77513
77751
  return selected ? CONNECTED : { state: "no-selected-locations" };
77514
77752
  }
77515
77753
  function gaConnection(ctx, project) {
@@ -77583,15 +77821,15 @@ function latestErrorText(raw) {
77583
77821
  }
77584
77822
  function readSyncRunState(db, projectId, kind, options = {}) {
77585
77823
  const scope = and96(
77586
- eq113(runs.projectId, projectId),
77587
- eq113(runs.kind, kind),
77588
- ...options.sourceId ? [eq113(runs.sourceId, options.sourceId)] : [],
77589
- ...options.nothingToSyncErrors?.length ? [or20(isNull18(runs.error), notInArray3(runs.error, [...options.nothingToSyncErrors]))] : []
77824
+ eq114(runs.projectId, projectId),
77825
+ eq114(runs.kind, kind),
77826
+ ...options.sourceId ? [eq114(runs.sourceId, options.sourceId)] : [],
77827
+ ...options.nothingToSyncErrors?.length ? [or21(isNull18(runs.error), notInArray3(runs.error, [...options.nothingToSyncErrors]))] : []
77590
77828
  );
77591
77829
  const graded = options.since ? and96(scope, gte30(runs.createdAt, options.since)) : scope;
77592
- const recent = db.select({ id: runs.id, status: runs.status, trigger: runs.trigger, error: runs.error, createdAt: runs.createdAt }).from(runs).where(and96(graded, inArray53(runs.status, FINISHED_STATUSES))).orderBy(desc51(runs.createdAt)).limit(SYNC_FAILURE_WINDOW).all();
77593
- const lastSuccess = db.select({ createdAt: runs.createdAt, finishedAt: runs.finishedAt }).from(runs).where(and96(graded, inArray53(runs.status, SUCCESS_STATUSES))).orderBy(desc51(runs.createdAt)).limit(1).get();
77594
- const failureCount = db.select({ count: count9() }).from(runs).where(and96(lastSuccess ? and96(graded, gt10(runs.createdAt, lastSuccess.createdAt)) : graded, eq113(runs.status, RunStatuses.failed))).get();
77830
+ const recent = db.select({ id: runs.id, status: runs.status, trigger: runs.trigger, error: runs.error, createdAt: runs.createdAt }).from(runs).where(and96(graded, inArray53(runs.status, FINISHED_STATUSES))).orderBy(desc52(runs.createdAt)).limit(SYNC_FAILURE_WINDOW).all();
77831
+ const lastSuccess = db.select({ createdAt: runs.createdAt, finishedAt: runs.finishedAt }).from(runs).where(and96(graded, inArray53(runs.status, SUCCESS_STATUSES))).orderBy(desc52(runs.createdAt)).limit(1).get();
77832
+ const failureCount = db.select({ count: count9() }).from(runs).where(and96(lastSuccess ? and96(graded, gt10(runs.createdAt, lastSuccess.createdAt)) : graded, eq114(runs.status, RunStatuses.failed))).get();
77595
77833
  const failuresSinceSuccess = Number(failureCount?.count ?? 0);
77596
77834
  const latest = recent[0];
77597
77835
  return {
@@ -77688,7 +77926,7 @@ function connectionFor(prefix, ctx, project) {
77688
77926
  if (prefix === "google-ads") return googleMarketingConnection("googleAds")(ctx);
77689
77927
  if (prefix === "gtm") return googleMarketingConnection("gtm")(ctx);
77690
77928
  if (prefix === "bing") return ctx.bingConnectionStore?.getConnection(project.canonicalDomain) ? { state: "connected", since: null } : { state: "not-connected" };
77691
- return ctx.db.select({ id: adsConnections.id }).from(adsConnections).where(eq114(adsConnections.projectId, project.id)).limit(1).get() ? { state: "connected", since: null } : { state: "not-connected" };
77929
+ return ctx.db.select({ id: adsConnections.id }).from(adsConnections).where(eq115(adsConnections.projectId, project.id)).limit(1).get() ? { state: "connected", since: null } : { state: "not-connected" };
77692
77930
  }
77693
77931
  function syncCommand(prefix) {
77694
77932
  if (prefix === "gsc") return "google sync";
@@ -77733,7 +77971,7 @@ function definition(prefix) {
77733
77971
  var API_HOST_CHECKS = Object.keys(API_HOST_TABLE).map(definition);
77734
77972
 
77735
77973
  // ../api-routes/src/doctor/checks/gbp-auth.ts
77736
- import { and as and97, eq as eq115 } from "drizzle-orm";
77974
+ import { and as and97, eq as eq116 } from "drizzle-orm";
77737
77975
  var RECENT_SYNC_WARN_DAYS = 4;
77738
77976
  var RECENT_SYNC_FAIL_DAYS = 30;
77739
77977
  function skippedNoProject3() {
@@ -77753,7 +77991,7 @@ function storeUnavailable() {
77753
77991
  };
77754
77992
  }
77755
77993
  function hasSelectedLocation(ctx, projectId) {
77756
- return !!ctx.db.select({ id: gbpLocations.id }).from(gbpLocations).where(and97(eq115(gbpLocations.projectId, projectId), eq115(gbpLocations.selected, true))).limit(1).get();
77994
+ return !!ctx.db.select({ id: gbpLocations.id }).from(gbpLocations).where(and97(eq116(gbpLocations.projectId, projectId), eq116(gbpLocations.selected, true))).limit(1).get();
77757
77995
  }
77758
77996
  async function resolveGbpToken(ctx) {
77759
77997
  if (!ctx.project) return { ok: false, output: skippedNoProject3() };
@@ -78013,7 +78251,7 @@ var recentSyncCheck = {
78013
78251
  title: "GBP recent sync",
78014
78252
  run: (ctx) => {
78015
78253
  if (!ctx.project) return skippedNoProject3();
78016
- const selected = ctx.db.select({ locationName: gbpLocations.locationName, syncedAt: gbpLocations.syncedAt }).from(gbpLocations).where(and97(eq115(gbpLocations.projectId, ctx.project.id), eq115(gbpLocations.selected, true))).all();
78254
+ const selected = ctx.db.select({ locationName: gbpLocations.locationName, syncedAt: gbpLocations.syncedAt }).from(gbpLocations).where(and97(eq116(gbpLocations.projectId, ctx.project.id), eq116(gbpLocations.selected, true))).all();
78017
78255
  if (selected.length === 0) {
78018
78256
  return {
78019
78257
  status: CheckStatuses.skipped,
@@ -78073,7 +78311,7 @@ var GBP_AUTH_CHECK_BY_ID = Object.fromEntries(
78073
78311
  );
78074
78312
 
78075
78313
  // ../api-routes/src/doctor/checks/places.ts
78076
- import { eq as eq116 } from "drizzle-orm";
78314
+ import { eq as eq117 } from "drizzle-orm";
78077
78315
  var apiKeyCheck = {
78078
78316
  id: "gbp.places.api-key",
78079
78317
  category: CheckCategories.auth,
@@ -78118,7 +78356,7 @@ var apiKeyCheck = {
78118
78356
  details: { tier: cfg.tier }
78119
78357
  };
78120
78358
  }
78121
- const rows = ctx.db.select({ placeId: gbpLocations.placeId, selected: gbpLocations.selected }).from(gbpLocations).where(eq116(gbpLocations.projectId, ctx.project.id)).all();
78359
+ const rows = ctx.db.select({ placeId: gbpLocations.placeId, selected: gbpLocations.selected }).from(gbpLocations).where(eq117(gbpLocations.projectId, ctx.project.id)).all();
78122
78360
  const selected = rows.filter((r) => r.selected);
78123
78361
  const locationsWithPlaceId = selected.filter((r) => Boolean(r.placeId)).length;
78124
78362
  const details = {
@@ -78151,7 +78389,7 @@ var PLACES_CHECK_BY_ID = Object.fromEntries(
78151
78389
  );
78152
78390
 
78153
78391
  // ../api-routes/src/doctor/checks/gbp-reviews.ts
78154
- import { and as and98, desc as desc52, eq as eq117, gte as gte31, inArray as inArray54, sql as sql49 } from "drizzle-orm";
78392
+ import { and as and98, desc as desc53, eq as eq118, gte as gte31, inArray as inArray54, sql as sql50 } from "drizzle-orm";
78155
78393
  var REVIEW_EVENTS = /* @__PURE__ */ new Set(["review.negative", "review.rating-dropped"]);
78156
78394
  var V4_ACCESS_REMEDIATION = "Business Profile reviews use the legacy My Business API (mybusiness.googleapis.com), which Google enables per Cloud project only on request; the API Library and `gcloud services enable` cannot turn it on. Open the enable link in the API access approval email as the approved account, or reply to the access-request thread asking Google to enable mybusiness.googleapis.com for your project number, then run `canonry gbp sync`.";
78157
78395
  var reviewsAccessCheck = {
@@ -78179,7 +78417,7 @@ var reviewsAccessCheck = {
78179
78417
  reviewsAccess: gbpLocations.reviewsAccess,
78180
78418
  reviewsAccessReason: gbpLocations.reviewsAccessReason,
78181
78419
  reviewsCheckedAt: gbpLocations.reviewsCheckedAt
78182
- }).from(gbpLocations).where(and98(eq117(gbpLocations.projectId, project.id), eq117(gbpLocations.selected, true))).all();
78420
+ }).from(gbpLocations).where(and98(eq118(gbpLocations.projectId, project.id), eq118(gbpLocations.selected, true))).all();
78183
78421
  if (locations.length === 0) {
78184
78422
  return {
78185
78423
  status: CheckStatuses.skipped,
@@ -78199,7 +78437,7 @@ var reviewsAccessCheck = {
78199
78437
  const places = ctx.getPlacesConfig?.();
78200
78438
  const placesFallback = places !== void 0 && places.tier === "atmosphere" && Boolean(places.apiKey);
78201
78439
  const v4Worked = new Set(
78202
- ctx.db.select({ locationName: gbpReviewRatings.locationName }).from(gbpReviewRatings).where(and98(eq117(gbpReviewRatings.projectId, project.id), eq117(gbpReviewRatings.origin, "gbp"))).all().map((row) => row.locationName)
78440
+ ctx.db.select({ locationName: gbpReviewRatings.locationName }).from(gbpReviewRatings).where(and98(eq118(gbpReviewRatings.projectId, project.id), eq118(gbpReviewRatings.origin, "gbp"))).all().map((row) => row.locationName)
78203
78441
  );
78204
78442
  const coverageOf = (loc) => {
78205
78443
  if (businessProfileReviewsCover(loc.reviewsAccess ?? null, v4Worked.has(loc.locationName))) return "full";
@@ -78233,7 +78471,7 @@ var reviewsAccessCheck = {
78233
78471
  none > 0 ? `${none} have no review source` : null
78234
78472
  ].filter((part) => part !== null);
78235
78473
  const summary3 = `Business Profile reviews are not available${why}. ${parts.join("; ")}.`;
78236
- const subscribed = ctx.db.select({ config: notifications.config, enabled: notifications.enabled }).from(notifications).where(eq117(notifications.projectId, project.id)).all().some((n) => n.enabled && (n.config.events ?? []).some((event) => REVIEW_EVENTS.has(event)));
78474
+ const subscribed = ctx.db.select({ config: notifications.config, enabled: notifications.enabled }).from(notifications).where(eq118(notifications.projectId, project.id)).all().some((n) => n.enabled && (n.config.events ?? []).some((event) => REVIEW_EVENTS.has(event)));
78237
78475
  const placesHint = placesFallback ? "" : " For partial coverage meanwhile, set a Places API key (`GOOGLE_PLACES_API_KEY` or `places.apiKey`) with `places.tier: atmosphere`.";
78238
78476
  if (none > 0 && subscribed) {
78239
78477
  return {
@@ -78264,7 +78502,7 @@ var reviewDeliveryCheck = {
78264
78502
  return { status: CheckStatuses.skipped, code: "gbp.reviews.delivery.no-project", summary: "Project context required.", remediation: null };
78265
78503
  }
78266
78504
  const since = new Date(Date.now() - UNDELIVERED_ATTENTION_DAYS * 864e5).toISOString();
78267
- const lastTouched = sql49`coalesce(${reviewWebhookDeliveries.attemptedAt}, ${reviewWebhookDeliveries.createdAt})`;
78505
+ const lastTouched = sql50`coalesce(${reviewWebhookDeliveries.attemptedAt}, ${reviewWebhookDeliveries.createdAt})`;
78268
78506
  const rows = ctx.db.select({
78269
78507
  id: reviewWebhookDeliveries.id,
78270
78508
  notificationId: reviewWebhookDeliveries.notificationId,
@@ -78273,10 +78511,10 @@ var reviewDeliveryCheck = {
78273
78511
  lastTouched,
78274
78512
  payload: reviewWebhookDeliveries.payload
78275
78513
  }).from(reviewWebhookDeliveries).where(and98(
78276
- eq117(reviewWebhookDeliveries.projectId, ctx.project.id),
78514
+ eq118(reviewWebhookDeliveries.projectId, ctx.project.id),
78277
78515
  inArray54(reviewWebhookDeliveries.state, [ReviewDeliveryStates.Uncertain, ReviewDeliveryStates.Failed]),
78278
78516
  gte31(lastTouched, since)
78279
- )).orderBy(desc52(lastTouched)).all();
78517
+ )).orderBy(desc53(lastTouched)).all();
78280
78518
  if (rows.length === 0) {
78281
78519
  return {
78282
78520
  status: CheckStatuses.ok,
@@ -78285,7 +78523,7 @@ var reviewDeliveryCheck = {
78285
78523
  remediation: null
78286
78524
  };
78287
78525
  }
78288
- const destinations = new Map(ctx.db.select({ id: notifications.id, config: notifications.config }).from(notifications).where(eq117(notifications.projectId, ctx.project.id)).all().map((row) => [row.id, redactNotificationUrl(row.config.url).urlDisplay]));
78526
+ const destinations = new Map(ctx.db.select({ id: notifications.id, config: notifications.config }).from(notifications).where(eq118(notifications.projectId, ctx.project.id)).all().map((row) => [row.id, redactNotificationUrl(row.config.url).urlDisplay]));
78289
78527
  const deliveries = rows.map((row) => {
78290
78528
  const review = row.payload.reviews[0];
78291
78529
  return {
@@ -78859,7 +79097,7 @@ var RUNTIME_STATE_CHECKS = [
78859
79097
  ];
78860
79098
 
78861
79099
  // ../api-routes/src/doctor/checks/traffic-source.ts
78862
- import { and as and99, desc as desc53, eq as eq118, gte as gte32, inArray as inArray55, isNotNull as isNotNull11, ne as ne17, sql as sql50 } from "drizzle-orm";
79100
+ import { and as and99, desc as desc54, eq as eq119, gte as gte32, inArray as inArray55, isNotNull as isNotNull11, ne as ne17, sql as sql51 } from "drizzle-orm";
78863
79101
  var RECENT_DATA_WARN_DAYS = 7;
78864
79102
  var RECENT_DATA_FAIL_DAYS = 30;
78865
79103
  function isCloudflareDirectPush(source) {
@@ -78899,7 +79137,7 @@ function loadProbes(ctx) {
78899
79137
  if (!ctx.project) return [];
78900
79138
  const rows = ctx.db.select().from(trafficSources).where(
78901
79139
  and99(
78902
- eq118(trafficSources.projectId, ctx.project.id),
79140
+ eq119(trafficSources.projectId, ctx.project.id),
78903
79141
  ne17(trafficSources.status, TrafficSourceStatuses.archived)
78904
79142
  )
78905
79143
  ).all();
@@ -79036,27 +79274,27 @@ var recentDataCheck = {
79036
79274
  const warnCutoff = new Date(now.getTime() - RECENT_DATA_WARN_DAYS * 24 * 60 * 6e4).toISOString();
79037
79275
  const failCutoff = new Date(now.getTime() - RECENT_DATA_FAIL_DAYS * 24 * 60 * 6e4).toISOString();
79038
79276
  const recentCrawlers = Number(
79039
- ctx.db.select({ total: sql50`COALESCE(SUM(${crawlerEventsHourly.hits}), 0)` }).from(crawlerEventsHourly).where(
79277
+ ctx.db.select({ total: sql51`COALESCE(SUM(${crawlerEventsHourly.hits}), 0)` }).from(crawlerEventsHourly).where(
79040
79278
  and99(
79041
- eq118(crawlerEventsHourly.projectId, ctx.project.id),
79279
+ eq119(crawlerEventsHourly.projectId, ctx.project.id),
79042
79280
  inArray55(crawlerEventsHourly.sourceId, activeSourceIds),
79043
79281
  gte32(crawlerEventsHourly.tsHour, warnCutoff)
79044
79282
  )
79045
79283
  ).get()?.total ?? 0
79046
79284
  );
79047
79285
  const recentReferrals = Number(
79048
- ctx.db.select({ total: sql50`COALESCE(SUM(${aiReferralEventsHourly.sessionsOrHits}), 0)` }).from(aiReferralEventsHourly).where(
79286
+ ctx.db.select({ total: sql51`COALESCE(SUM(${aiReferralEventsHourly.sessionsOrHits}), 0)` }).from(aiReferralEventsHourly).where(
79049
79287
  and99(
79050
- eq118(aiReferralEventsHourly.projectId, ctx.project.id),
79288
+ eq119(aiReferralEventsHourly.projectId, ctx.project.id),
79051
79289
  inArray55(aiReferralEventsHourly.sourceId, activeSourceIds),
79052
79290
  gte32(aiReferralEventsHourly.tsHour, warnCutoff)
79053
79291
  )
79054
79292
  ).get()?.total ?? 0
79055
79293
  );
79056
79294
  const recentUserFetches = Number(
79057
- ctx.db.select({ total: sql50`COALESCE(SUM(${aiUserFetchEventsHourly.hits}), 0)` }).from(aiUserFetchEventsHourly).where(
79295
+ ctx.db.select({ total: sql51`COALESCE(SUM(${aiUserFetchEventsHourly.hits}), 0)` }).from(aiUserFetchEventsHourly).where(
79058
79296
  and99(
79059
- eq118(aiUserFetchEventsHourly.projectId, ctx.project.id),
79297
+ eq119(aiUserFetchEventsHourly.projectId, ctx.project.id),
79060
79298
  inArray55(aiUserFetchEventsHourly.sourceId, activeSourceIds),
79061
79299
  gte32(aiUserFetchEventsHourly.tsHour, warnCutoff)
79062
79300
  )
@@ -79080,27 +79318,27 @@ var recentDataCheck = {
79080
79318
  };
79081
79319
  }
79082
79320
  const olderCrawlers = Number(
79083
- ctx.db.select({ total: sql50`COALESCE(SUM(${crawlerEventsHourly.hits}), 0)` }).from(crawlerEventsHourly).where(
79321
+ ctx.db.select({ total: sql51`COALESCE(SUM(${crawlerEventsHourly.hits}), 0)` }).from(crawlerEventsHourly).where(
79084
79322
  and99(
79085
- eq118(crawlerEventsHourly.projectId, ctx.project.id),
79323
+ eq119(crawlerEventsHourly.projectId, ctx.project.id),
79086
79324
  inArray55(crawlerEventsHourly.sourceId, activeSourceIds),
79087
79325
  gte32(crawlerEventsHourly.tsHour, failCutoff)
79088
79326
  )
79089
79327
  ).get()?.total ?? 0
79090
79328
  );
79091
79329
  const olderReferrals = Number(
79092
- ctx.db.select({ total: sql50`COALESCE(SUM(${aiReferralEventsHourly.sessionsOrHits}), 0)` }).from(aiReferralEventsHourly).where(
79330
+ ctx.db.select({ total: sql51`COALESCE(SUM(${aiReferralEventsHourly.sessionsOrHits}), 0)` }).from(aiReferralEventsHourly).where(
79093
79331
  and99(
79094
- eq118(aiReferralEventsHourly.projectId, ctx.project.id),
79332
+ eq119(aiReferralEventsHourly.projectId, ctx.project.id),
79095
79333
  inArray55(aiReferralEventsHourly.sourceId, activeSourceIds),
79096
79334
  gte32(aiReferralEventsHourly.tsHour, failCutoff)
79097
79335
  )
79098
79336
  ).get()?.total ?? 0
79099
79337
  );
79100
79338
  const olderUserFetches = Number(
79101
- ctx.db.select({ total: sql50`COALESCE(SUM(${aiUserFetchEventsHourly.hits}), 0)` }).from(aiUserFetchEventsHourly).where(
79339
+ ctx.db.select({ total: sql51`COALESCE(SUM(${aiUserFetchEventsHourly.hits}), 0)` }).from(aiUserFetchEventsHourly).where(
79102
79340
  and99(
79103
- eq118(aiUserFetchEventsHourly.projectId, ctx.project.id),
79341
+ eq119(aiUserFetchEventsHourly.projectId, ctx.project.id),
79104
79342
  inArray55(aiUserFetchEventsHourly.sourceId, activeSourceIds),
79105
79343
  gte32(aiUserFetchEventsHourly.tsHour, failCutoff)
79106
79344
  )
@@ -79428,11 +79666,11 @@ var syncLagCheck = {
79428
79666
  };
79429
79667
  function lastQueueStopReason(ctx, sourceId) {
79430
79668
  const row = ctx.db.select({ syncSummary: runs.syncSummary }).from(runs).where(and99(
79431
- eq118(runs.projectId, ctx.project.id),
79432
- eq118(runs.kind, RunKinds["traffic-sync"]),
79433
- eq118(runs.sourceId, sourceId),
79669
+ eq119(runs.projectId, ctx.project.id),
79670
+ eq119(runs.kind, RunKinds["traffic-sync"]),
79671
+ eq119(runs.sourceId, sourceId),
79434
79672
  isNotNull11(runs.syncSummary)
79435
- )).orderBy(desc53(runs.createdAt)).limit(1).get();
79673
+ )).orderBy(desc54(runs.createdAt)).limit(1).get();
79436
79674
  return row?.syncSummary?.type === "cloudflare-queue" ? row.syncSummary.stopReason : null;
79437
79675
  }
79438
79676
  var QUEUE_LIMIT_STOPS = [
@@ -80230,7 +80468,7 @@ async function doctorRoutes(app, opts) {
80230
80468
  }
80231
80469
 
80232
80470
  // ../api-routes/src/status.ts
80233
- import { and as and100, desc as desc54, eq as eq119, isNull as isNull19 } from "drizzle-orm";
80471
+ import { and as and100, desc as desc55, eq as eq120, isNull as isNull19 } from "drizzle-orm";
80234
80472
  function ageDays(iso2) {
80235
80473
  if (!iso2) return null;
80236
80474
  const ms = Date.now() - Date.parse(iso2);
@@ -80280,7 +80518,7 @@ function makeRow(integration, label, runKind, state, staleAfterDays, dataThrough
80280
80518
  };
80281
80519
  }
80282
80520
  function latestDate2(db, table, projectId) {
80283
- const row = db.select({ date: table.date }).from(table).where(eq119(table.projectId, projectId)).orderBy(desc54(table.date)).limit(1).get();
80521
+ const row = db.select({ date: table.date }).from(table).where(eq120(table.projectId, projectId)).orderBy(desc55(table.date)).limit(1).get();
80284
80522
  return row?.date ?? null;
80285
80523
  }
80286
80524
  function projectRows(opts, project) {
@@ -80295,7 +80533,7 @@ function projectRows(opts, project) {
80295
80533
  const rows = [];
80296
80534
  const gsc = gscConnection(ctx, info);
80297
80535
  if (connected(gsc)) {
80298
- const watermarkRow = opts.db.select({ dataThroughDate: gscDataWatermarks.dataThroughDate }).from(gscDataWatermarks).where(eq119(gscDataWatermarks.projectId, project.id)).limit(1).get();
80536
+ const watermarkRow = opts.db.select({ dataThroughDate: gscDataWatermarks.dataThroughDate }).from(gscDataWatermarks).where(eq120(gscDataWatermarks.projectId, project.id)).limit(1).get();
80299
80537
  const state = readSyncRunState(opts.db, project.id, RunKinds["gsc-sync"], { since: gsc.since });
80300
80538
  const dataThrough = watermarkRow?.dataThroughDate ?? latestDate2(opts.db, gscDailyTotals, project.id);
80301
80539
  rows.push(makeRow("gsc", "Search Console", RunKinds["gsc-sync"], state, SYNC_IDLE_DAYS, dataThrough, null, ["gsc.sync.recent-failures"], GSC_DATA_AGING_DAYS));
@@ -80311,12 +80549,12 @@ function projectRows(opts, project) {
80311
80549
  rows.push(makeRow("bing", "Bing Webmaster Tools", RunKinds["bing-inspect-sitemap"], readSyncRunState(opts.db, project.id, RunKinds["bing-inspect-sitemap"]), null));
80312
80550
  rows.push(makeRow("bing-search", "Bing search data", RunKinds["bing-sync"], readSyncRunState(opts.db, project.id, RunKinds["bing-sync"]), SYNC_IDLE_DAYS, latestDate2(opts.db, bingTrafficDaily, project.id), null, ["bing.sync.recent-failures"], BING_DATA_AGING_DAYS));
80313
80551
  }
80314
- const ads = opts.db.select({ id: adsConnections.id, lastSyncedAt: adsConnections.lastSyncedAt }).from(adsConnections).where(eq119(adsConnections.projectId, project.id)).limit(1).get();
80552
+ const ads = opts.db.select({ id: adsConnections.id, lastSyncedAt: adsConnections.lastSyncedAt }).from(adsConnections).where(eq120(adsConnections.projectId, project.id)).limit(1).get();
80315
80553
  if (ads) rows.push(makeRow("ads", "OpenAI Ads", RunKinds["ads-sync"], readSyncRunState(opts.db, project.id, RunKinds["ads-sync"]), ADS_RECENT_SYNC_WARN_DAYS, null, null, ["ads.data.recent-sync"], ADS_RECENT_SYNC_WARN_DAYS, ads.lastSyncedAt));
80316
80554
  const marketing = opts.getGoogleMarketingDoctorInput?.(ctx);
80317
80555
  if (marketing?.googleAds) rows.push(makeRow("google-ads", "Google Ads", RunKinds["google-ads-sync"], readSyncRunState(opts.db, project.id, RunKinds["google-ads-sync"]), FRESH_SNAPSHOT_WARN_DAYS, null, null, ["google-ads.sync.recent-failures"], FRESH_SNAPSHOT_WARN_DAYS, marketing.googleAds.latestSnapshotAt));
80318
80556
  if (marketing?.gtm) rows.push(makeRow("gtm", "Google Tag Manager", RunKinds["gtm-sync"], readSyncRunState(opts.db, project.id, RunKinds["gtm-sync"]), FRESH_SNAPSHOT_WARN_DAYS, null, null, ["gtm.sync.recent-failures"], FRESH_SNAPSHOT_WARN_DAYS, marketing.gtm.latestSnapshotAt));
80319
- const sources = opts.db.select().from(trafficSources).where(and100(eq119(trafficSources.projectId, project.id), isNull19(trafficSources.archivedAt))).all();
80557
+ const sources = opts.db.select().from(trafficSources).where(and100(eq120(trafficSources.projectId, project.id), isNull19(trafficSources.archivedAt))).all();
80320
80558
  for (const source of sources) {
80321
80559
  const row = makeRow("traffic", source.displayName, RunKinds["traffic-sync"], readSyncRunState(opts.db, project.id, RunKinds["traffic-sync"], { sourceId: source.id }), null, null, source.id, ["traffic.source.sync-lag", "traffic.source.recent-data"]);
80322
80560
  const lag = source.lastSyncedAt ? Date.now() - Date.parse(source.lastSyncedAt) : Number.POSITIVE_INFINITY;
@@ -80328,7 +80566,7 @@ function projectRows(opts, project) {
80328
80566
  }
80329
80567
  function projectStatus(opts, project) {
80330
80568
  const integrations = projectRows(opts, project);
80331
- const healthRow = opts.db.select().from(doctorHealthState).where(eq119(doctorHealthState.projectId, project.id)).limit(1).get();
80569
+ const healthRow = opts.db.select().from(doctorHealthState).where(eq120(doctorHealthState.projectId, project.id)).limit(1).get();
80332
80570
  const health = healthRow ? { status: healthRow.status, code: healthRow.code, summary: healthRow.summary, checkedAt: healthRow.checkedAt, notifiedAt: healthRow.notifiedAt } : null;
80333
80571
  const rank = { ok: 0, "never-synced": 1, warning: 2, stale: 3, failing: 4 };
80334
80572
  const healthState = health?.status === "fail" ? "failing" : health?.status === "warn" ? "warning" : "ok";
@@ -80348,7 +80586,7 @@ async function statusRoutes(app, opts) {
80348
80586
  if (request.query.problems === "true") result.projects = result.projects.map((item2) => ({ ...item2, integrations: item2.integrations.filter((row) => row.state !== "ok") }));
80349
80587
  return instanceStatusDtoSchema.parse(result);
80350
80588
  }
80351
- const projectsRows = (scopedId ? opts.db.select().from(projects).where(eq119(projects.id, scopedId)) : opts.db.select().from(projects)).all();
80589
+ const projectsRows = (scopedId ? opts.db.select().from(projects).where(eq120(projects.id, scopedId)) : opts.db.select().from(projects)).all();
80352
80590
  const output = { generatedAt: (/* @__PURE__ */ new Date()).toISOString(), ...opts.getMcpHealth ? { mcp: opts.getMcpHealth() } : {}, summary: { projects: projectsRows.length, ok: 0, failing: 0, warning: 0, stale: 0, neverSynced: 0 }, projects: projectsRows.map((project) => projectStatus(opts, project)) };
80353
80591
  for (const project of output.projects) {
80354
80592
  const key = project.state === "never-synced" ? "neverSynced" : project.state;
@@ -80360,8 +80598,8 @@ async function statusRoutes(app, opts) {
80360
80598
  }
80361
80599
 
80362
80600
  // ../api-routes/src/discovery/routes.ts
80363
- import crypto62 from "crypto";
80364
- import { and as and101, desc as desc55, eq as eq120, gte as gte33, inArray as inArray56, isNull as isNull20, or as or21 } from "drizzle-orm";
80601
+ import crypto63 from "crypto";
80602
+ import { and as and101, desc as desc56, eq as eq121, gte as gte33, inArray as inArray56, isNull as isNull20, or as or22 } from "drizzle-orm";
80365
80603
  var MAX_INFLIGHT_DISCOVERY_AGE_MS = 2 * 60 * 60 * 1e3;
80366
80604
  async function discoveryRoutes(app, opts) {
80367
80605
  app.post("/projects/:name/discover/run", async (request, reply) => {
@@ -80396,12 +80634,12 @@ async function discoveryRoutes(app, opts) {
80396
80634
  const ageFloorIso = new Date(Date.now() - MAX_INFLIGHT_DISCOVERY_AGE_MS).toISOString();
80397
80635
  const decision = app.db.transaction((tx) => {
80398
80636
  const existing = tx.select({ id: discoverySessions.id, runId: discoverySessions.runId }).from(discoverySessions).where(and101(
80399
- eq120(discoverySessions.projectId, project.id),
80400
- eq120(discoverySessions.icpDescription, icpDescription),
80637
+ eq121(discoverySessions.projectId, project.id),
80638
+ eq121(discoverySessions.icpDescription, icpDescription),
80401
80639
  // Buyer is part of session identity: it changes the seed prompt's
80402
80640
  // semantics, so a request with a different (or no) buyer must start
80403
80641
  // its own session, never adopt another buyer's probes.
80404
- parsed.data.buyerDescription == null ? isNull20(discoverySessions.buyerDescription) : eq120(discoverySessions.buyerDescription, parsed.data.buyerDescription),
80642
+ parsed.data.buyerDescription == null ? isNull20(discoverySessions.buyerDescription) : eq121(discoverySessions.buyerDescription, parsed.data.buyerDescription),
80405
80643
  // Locations are identity too: a different service-area subset seeds
80406
80644
  // and probes a different geo, so it must never reuse another geo's
80407
80645
  // session. resolveLocations is deterministic (project-config order),
@@ -80411,23 +80649,23 @@ async function discoveryRoutes(app, opts) {
80411
80649
  // locations a NULL row's subset is unknowable, so it conservatively
80412
80650
  // never reuses — a one-time, bounded (2h window) non-reuse after
80413
80651
  // upgrade, never a wrong reuse.
80414
- locations.length === 0 ? or21(isNull20(discoverySessions.locations), eq120(discoverySessions.locations, locations)) : eq120(discoverySessions.locations, locations),
80652
+ locations.length === 0 ? or22(isNull20(discoverySessions.locations), eq121(discoverySessions.locations, locations)) : eq121(discoverySessions.locations, locations),
80415
80653
  // Seed provider set is identity: a different phrasing distribution
80416
80654
  // must never reuse another set's session. Null (= Gemini-only
80417
80655
  // default, including explicit ['gemini']) matches legacy rows.
80418
- seedProviders == null ? isNull20(discoverySessions.seedProviders) : eq120(discoverySessions.seedProviders, seedProviders),
80656
+ seedProviders == null ? isNull20(discoverySessions.seedProviders) : eq121(discoverySessions.seedProviders, seedProviders),
80419
80657
  inArray56(discoverySessions.status, [
80420
80658
  DiscoverySessionStatuses.queued,
80421
80659
  DiscoverySessionStatuses.seeding,
80422
80660
  DiscoverySessionStatuses.probing
80423
80661
  ]),
80424
80662
  gte33(discoverySessions.createdAt, ageFloorIso)
80425
- )).orderBy(desc55(discoverySessions.createdAt)).get();
80663
+ )).orderBy(desc56(discoverySessions.createdAt)).get();
80426
80664
  if (existing && existing.runId) {
80427
80665
  return { reused: true, sessionId: existing.id, runId: existing.runId };
80428
80666
  }
80429
- const sessionId = crypto62.randomUUID();
80430
- const runId = crypto62.randomUUID();
80667
+ const sessionId = crypto63.randomUUID();
80668
+ const runId = crypto63.randomUUID();
80431
80669
  tx.insert(discoverySessions).values({
80432
80670
  id: sessionId,
80433
80671
  projectId: project.id,
@@ -80491,7 +80729,7 @@ async function discoveryRoutes(app, opts) {
80491
80729
  const project = resolveProject(app.db, request.params.name);
80492
80730
  const parsedLimit = parseInt(request.query.limit ?? "", 10);
80493
80731
  const limit = Number.isNaN(parsedLimit) || parsedLimit <= 0 ? 50 : parsedLimit;
80494
- const rows = app.db.select().from(discoverySessions).where(eq120(discoverySessions.projectId, project.id)).orderBy(desc55(discoverySessions.createdAt)).limit(limit).all();
80732
+ const rows = app.db.select().from(discoverySessions).where(eq121(discoverySessions.projectId, project.id)).orderBy(desc56(discoverySessions.createdAt)).limit(limit).all();
80495
80733
  return reply.send(rows.map(serializeSession));
80496
80734
  }
80497
80735
  );
@@ -80499,11 +80737,11 @@ async function discoveryRoutes(app, opts) {
80499
80737
  "/projects/:name/discover/sessions/:id",
80500
80738
  async (request, reply) => {
80501
80739
  const project = resolveProject(app.db, request.params.name);
80502
- const session = app.db.select().from(discoverySessions).where(eq120(discoverySessions.id, request.params.id)).get();
80740
+ const session = app.db.select().from(discoverySessions).where(eq121(discoverySessions.id, request.params.id)).get();
80503
80741
  if (!session || session.projectId !== project.id) {
80504
80742
  throw notFound("Discovery session", request.params.id);
80505
80743
  }
80506
- const probeRows = app.db.select().from(discoveryProbes).where(eq120(discoveryProbes.sessionId, session.id)).all();
80744
+ const probeRows = app.db.select().from(discoveryProbes).where(eq121(discoveryProbes.sessionId, session.id)).all();
80507
80745
  const detail = {
80508
80746
  ...serializeSession(session),
80509
80747
  probes: probeRows.map(serializeProbe)
@@ -80517,7 +80755,7 @@ async function discoveryRoutes(app, opts) {
80517
80755
  requireAdminSession(request);
80518
80756
  requirePaidReadScope(request, [], "Discovery harvest requires wildcard (*) API key scope because it can call the embedding provider.");
80519
80757
  const project = resolveProject(app.db, request.params.name);
80520
- const session = app.db.select().from(discoverySessions).where(eq120(discoverySessions.id, request.params.id)).get();
80758
+ const session = app.db.select().from(discoverySessions).where(eq121(discoverySessions.id, request.params.id)).get();
80521
80759
  if (!session || session.projectId !== project.id) {
80522
80760
  throw notFound("Discovery session", request.params.id);
80523
80761
  }
@@ -80525,7 +80763,7 @@ async function discoveryRoutes(app, opts) {
80525
80763
  const minProbeHits = Number.isNaN(parsedFloor) || parsedFloor < 1 ? 1 : parsedFloor;
80526
80764
  const applyAnchor = request.query.anchor !== "false";
80527
80765
  const provider = session.seedProvider ?? "gemini";
80528
- const probeRows = app.db.select().from(discoveryProbes).where(eq120(discoveryProbes.sessionId, session.id)).all();
80766
+ const probeRows = app.db.select().from(discoveryProbes).where(eq121(discoveryProbes.sessionId, session.id)).all();
80529
80767
  const extract = opts.harvestSearchQueries;
80530
80768
  const probesWithQueries = probeRows.map((row) => {
80531
80769
  if (!extract || !row.rawResponse) return { searchQueries: [] };
@@ -80536,7 +80774,7 @@ async function discoveryRoutes(app, opts) {
80536
80774
  return { searchQueries: [] };
80537
80775
  }
80538
80776
  });
80539
- const trackedQueries = app.db.select({ query: queries.query }).from(queries).where(eq120(queries.projectId, project.id)).all().map((r) => r.query);
80777
+ const trackedQueries = app.db.select({ query: queries.query }).from(queries).where(eq121(queries.projectId, project.id)).all().map((r) => r.query);
80540
80778
  const anchorTerms = buildHarvestAnchorTerms(
80541
80779
  [session.icpDescription ?? "", ...trackedQueries],
80542
80780
  effectiveDomains(project)
@@ -80583,11 +80821,11 @@ async function discoveryRoutes(app, opts) {
80583
80821
  "/projects/:name/discover/sessions/:id/promote",
80584
80822
  async (request, reply) => {
80585
80823
  const project = resolveProject(app.db, request.params.name);
80586
- const session = app.db.select().from(discoverySessions).where(eq120(discoverySessions.id, request.params.id)).get();
80824
+ const session = app.db.select().from(discoverySessions).where(eq121(discoverySessions.id, request.params.id)).get();
80587
80825
  if (!session || session.projectId !== project.id) {
80588
80826
  throw notFound("Discovery session", request.params.id);
80589
80827
  }
80590
- const probeRows = app.db.select().from(discoveryProbes).where(eq120(discoveryProbes.sessionId, session.id)).all();
80828
+ const probeRows = app.db.select().from(discoveryProbes).where(eq121(discoveryProbes.sessionId, session.id)).all();
80591
80829
  const cited = /* @__PURE__ */ new Set();
80592
80830
  const aspirational = /* @__PURE__ */ new Set();
80593
80831
  const wasted = /* @__PURE__ */ new Set();
@@ -80622,7 +80860,7 @@ async function discoveryRoutes(app, opts) {
80622
80860
  );
80623
80861
  app.post("/projects/:name/discover/sessions/:id/promote", async (request, reply) => {
80624
80862
  const project = resolveProject(app.db, request.params.name);
80625
- const session = app.db.select().from(discoverySessions).where(eq120(discoverySessions.id, request.params.id)).get();
80863
+ const session = app.db.select().from(discoverySessions).where(eq121(discoverySessions.id, request.params.id)).get();
80626
80864
  if (!session || session.projectId !== project.id) {
80627
80865
  throw notFound("Discovery session", request.params.id);
80628
80866
  }
@@ -80645,7 +80883,7 @@ async function discoveryRoutes(app, opts) {
80645
80883
  const bucketSet = new Set(buckets);
80646
80884
  const includeCompetitors = parsed.data.includeCompetitors ?? true;
80647
80885
  const competitorTypes = parsed.data.competitorTypes ?? DEFAULT_DISCOVERY_PROMOTE_COMPETITOR_TYPES;
80648
- const probeRows = app.db.select().from(discoveryProbes).where(eq120(discoveryProbes.sessionId, session.id)).all();
80886
+ const probeRows = app.db.select().from(discoveryProbes).where(eq121(discoveryProbes.sessionId, session.id)).all();
80649
80887
  const candidateQueries = /* @__PURE__ */ new Set();
80650
80888
  for (const probe of probeRows) {
80651
80889
  if (!probe.bucket) continue;
@@ -80653,7 +80891,7 @@ async function discoveryRoutes(app, opts) {
80653
80891
  if (bucket.success && bucketSet.has(bucket.data)) candidateQueries.add(probe.query);
80654
80892
  }
80655
80893
  const existingQueries = new Set(
80656
- app.db.select({ query: queries.query }).from(queries).where(eq120(queries.projectId, project.id)).all().map((r) => r.query.toLowerCase())
80894
+ app.db.select({ query: queries.query }).from(queries).where(eq121(queries.projectId, project.id)).all().map((r) => r.query.toLowerCase())
80657
80895
  );
80658
80896
  const promotedQueries = [];
80659
80897
  const skippedQueries = [];
@@ -80684,7 +80922,7 @@ async function discoveryRoutes(app, opts) {
80684
80922
  const marketNames = beginMarketNameWrite(tx, project.id);
80685
80923
  for (const query2 of promotedQueries) {
80686
80924
  tx.insert(queries).values({
80687
- id: crypto62.randomUUID(),
80925
+ id: crypto63.randomUUID(),
80688
80926
  projectId: project.id,
80689
80927
  query: query2,
80690
80928
  provenance,
@@ -80866,8 +81104,8 @@ function planCompetitorPromotion(input) {
80866
81104
  }
80867
81105
 
80868
81106
  // ../api-routes/src/discovery/orchestrate.ts
80869
- import crypto63 from "crypto";
80870
- import { eq as eq121 } from "drizzle-orm";
81107
+ import crypto64 from "crypto";
81108
+ import { eq as eq122 } from "drizzle-orm";
80871
81109
  var DEFAULT_MAX_PROBES = 100;
80872
81110
  var ABSOLUTE_MAX_PROBES = 500;
80873
81111
  function classifyProbeBucket(input) {
@@ -80953,7 +81191,7 @@ async function executeDiscovery(opts) {
80953
81191
  status: DiscoverySessionStatuses.seeding,
80954
81192
  dedupThreshold,
80955
81193
  startedAt
80956
- }).where(eq121(discoverySessions.id, opts.sessionId)).run();
81194
+ }).where(eq122(discoverySessions.id, opts.sessionId)).run();
80957
81195
  const seedResult = await opts.deps.seed({
80958
81196
  project: opts.project,
80959
81197
  icpDescription: opts.icpDescription,
@@ -81014,7 +81252,7 @@ async function executeDiscovery(opts) {
81014
81252
  dedupBandPairFraction: dedupStats.bandPairFraction,
81015
81253
  dedupPairsTotal: dedupStats.pairsTotal,
81016
81254
  warning
81017
- }).where(eq121(discoverySessions.id, opts.sessionId)).run();
81255
+ }).where(eq122(discoverySessions.id, opts.sessionId)).run();
81018
81256
  const probeLocation = opts.locations?.[0];
81019
81257
  const probeResults = await mapWithConcurrency(
81020
81258
  probedCanonicals,
@@ -81033,7 +81271,7 @@ async function executeDiscovery(opts) {
81033
81271
  probeRows.push({ citedDomains: probe.citedDomains, bucket });
81034
81272
  buckets[bucket]++;
81035
81273
  return {
81036
- id: crypto63.randomUUID(),
81274
+ id: crypto64.randomUUID(),
81037
81275
  sessionId: opts.sessionId,
81038
81276
  projectId: opts.project.id,
81039
81277
  query: probedCanonicals[index],
@@ -81068,7 +81306,7 @@ async function executeDiscovery(opts) {
81068
81306
  wastedCount: buckets["wasted-surface"],
81069
81307
  competitorMap,
81070
81308
  finishedAt: (/* @__PURE__ */ new Date()).toISOString()
81071
- }).where(eq121(discoverySessions.id, opts.sessionId)).run();
81309
+ }).where(eq122(discoverySessions.id, opts.sessionId)).run();
81072
81310
  upsertDomainClassifications(opts.db, opts.project.id, opts.sessionId, competitorMap);
81073
81311
  return {
81074
81312
  buckets,
@@ -81085,7 +81323,7 @@ function upsertDomainClassifications(db, projectId, sessionId, competitorMap) {
81085
81323
  const domain = hostOf(entry.domain) ?? "";
81086
81324
  if (!domain) continue;
81087
81325
  db.insert(domainClassifications).values({
81088
- id: crypto63.randomUUID(),
81326
+ id: crypto64.randomUUID(),
81089
81327
  projectId,
81090
81328
  domain,
81091
81329
  competitorType: entry.competitorType,
@@ -81108,7 +81346,7 @@ function markSessionFailed(db, sessionId, error) {
81108
81346
  status: DiscoverySessionStatuses.failed,
81109
81347
  error,
81110
81348
  finishedAt: (/* @__PURE__ */ new Date()).toISOString()
81111
- }).where(eq121(discoverySessions.id, sessionId)).run();
81349
+ }).where(eq122(discoverySessions.id, sessionId)).run();
81112
81350
  }
81113
81351
  function dedupeStrings(input) {
81114
81352
  const seen2 = /* @__PURE__ */ new Set();
@@ -81125,7 +81363,7 @@ function dedupeStrings(input) {
81125
81363
  }
81126
81364
 
81127
81365
  // ../api-routes/src/trends.ts
81128
- import { and as and102, asc as asc30, eq as eq122 } from "drizzle-orm";
81366
+ import { and as and102, asc as asc30, eq as eq123 } from "drizzle-orm";
81129
81367
  function parseSurface(value) {
81130
81368
  const parsed = trendSurfaceSchema.safeParse(value);
81131
81369
  if (!parsed.success) {
@@ -81181,8 +81419,8 @@ async function trendsRoutes(app) {
81181
81419
  function readSurface(app, projectId, surface) {
81182
81420
  switch (surface) {
81183
81421
  case TrendSurfaces["index-coverage"]: {
81184
- const google = app.db.select({ date: gscCoverageSnapshots.date, indexed: gscCoverageSnapshots.indexed, notIndexed: gscCoverageSnapshots.notIndexed }).from(gscCoverageSnapshots).where(eq122(gscCoverageSnapshots.projectId, projectId)).orderBy(asc30(gscCoverageSnapshots.date)).all();
81185
- const bing = app.db.select({ date: bingCoverageSnapshots.date, indexed: bingCoverageSnapshots.indexed, notIndexed: bingCoverageSnapshots.notIndexed }).from(bingCoverageSnapshots).where(eq122(bingCoverageSnapshots.projectId, projectId)).orderBy(asc30(bingCoverageSnapshots.date)).all();
81422
+ const google = app.db.select({ date: gscCoverageSnapshots.date, indexed: gscCoverageSnapshots.indexed, notIndexed: gscCoverageSnapshots.notIndexed }).from(gscCoverageSnapshots).where(eq123(gscCoverageSnapshots.projectId, projectId)).orderBy(asc30(gscCoverageSnapshots.date)).all();
81423
+ const bing = app.db.select({ date: bingCoverageSnapshots.date, indexed: bingCoverageSnapshots.indexed, notIndexed: bingCoverageSnapshots.notIndexed }).from(bingCoverageSnapshots).where(eq123(bingCoverageSnapshots.projectId, projectId)).orderBy(asc30(bingCoverageSnapshots.date)).all();
81186
81424
  const coverage = (key, label, rows) => ({
81187
81425
  key,
81188
81426
  label,
@@ -81194,7 +81432,7 @@ function readSurface(app, projectId, surface) {
81194
81432
  return [coverage("google", "Google", google), coverage("bing", "Bing", bing)];
81195
81433
  }
81196
81434
  case TrendSurfaces["site-health"]: {
81197
- const rows = app.db.select({ auditedAt: siteAuditSnapshots.auditedAt, aggregateScore: siteAuditSnapshots.aggregateScore, pagesAudited: siteAuditSnapshots.pagesAudited }).from(siteAuditSnapshots).innerJoin(runs, eq122(siteAuditSnapshots.runId, runs.id)).where(and102(...surfaceableSiteAuditFilters(projectId))).orderBy(asc30(siteAuditSnapshots.auditedAt)).all();
81435
+ const rows = app.db.select({ auditedAt: siteAuditSnapshots.auditedAt, aggregateScore: siteAuditSnapshots.aggregateScore, pagesAudited: siteAuditSnapshots.pagesAudited }).from(siteAuditSnapshots).innerJoin(runs, eq123(siteAuditSnapshots.runId, runs.id)).where(and102(...surfaceableSiteAuditFilters(projectId))).orderBy(asc30(siteAuditSnapshots.auditedAt)).all();
81198
81436
  return [{
81199
81437
  key: "site-health",
81200
81438
  label: "Agent Readiness",
@@ -81206,7 +81444,7 @@ function readSurface(app, projectId, surface) {
81206
81444
  }
81207
81445
  case TrendSurfaces.backlinks: {
81208
81446
  const totals = computeFilteredReleaseTotals(app.db, projectId, BacklinkSources.commoncrawl);
81209
- const rows = app.db.select({ release: backlinkSummaries.release, totalLinkingDomains: backlinkSummaries.totalLinkingDomains, queriedAt: backlinkSummaries.queriedAt }).from(backlinkSummaries).where(and102(eq122(backlinkSummaries.projectId, projectId), eq122(backlinkSummaries.source, BacklinkSources.commoncrawl))).all().sort((a, b) => compareReleaseIds(a.release, b.release)).map((row) => {
81447
+ const rows = app.db.select({ release: backlinkSummaries.release, totalLinkingDomains: backlinkSummaries.totalLinkingDomains, queriedAt: backlinkSummaries.queriedAt }).from(backlinkSummaries).where(and102(eq123(backlinkSummaries.projectId, projectId), eq123(backlinkSummaries.source, BacklinkSources.commoncrawl))).all().sort((a, b) => compareReleaseIds(a.release, b.release)).map((row) => {
81210
81448
  const filtered = totals.get(row.release);
81211
81449
  const known = (filtered?.domainRows ?? 0) > 0 || row.totalLinkingDomains === 0;
81212
81450
  const windowEnd = releaseWindowEndMonth(row.release);
@@ -81234,9 +81472,9 @@ function readSurface(app, projectId, surface) {
81234
81472
  }
81235
81473
 
81236
81474
  // ../api-routes/src/research.ts
81237
- import crypto64 from "crypto";
81475
+ import crypto65 from "crypto";
81238
81476
  import { z as z7 } from "zod";
81239
- import { and as and103, count as count10, desc as desc56, eq as eq123, gte as gte34, lt as lt21, or as or22, sql as sql51 } from "drizzle-orm";
81477
+ import { and as and103, count as count10, desc as desc57, eq as eq124, gte as gte34, lt as lt21, or as or23, sql as sql52 } from "drizzle-orm";
81240
81478
  var sameLocation = (a, b) => a.label === b.label && a.city === b.city && a.region === b.region && a.country === b.country && a.timezone === b.timezone;
81241
81479
  var BATCH_RECEIPT_PREFIX = "__canonry_research_batch__:";
81242
81480
  async function researchRoutes(app, opts) {
@@ -81255,7 +81493,7 @@ async function researchRoutes(app, opts) {
81255
81493
  const input = parsed.data;
81256
81494
  if (input.idempotencyKey?.startsWith(BATCH_RECEIPT_PREFIX)) throw validationError("This idempotency key prefix is reserved for internal research batch receipts.");
81257
81495
  const requestHash2 = directResearchRequestHash(input);
81258
- const existingReceipt = input.idempotencyKey ? app.db.select().from(researchRuns).where(and103(eq123(researchRuns.projectId, project.id), eq123(researchRuns.idempotencyKey, input.idempotencyKey))).get() : void 0;
81496
+ const existingReceipt = input.idempotencyKey ? app.db.select().from(researchRuns).where(and103(eq124(researchRuns.projectId, project.id), eq124(researchRuns.idempotencyKey, input.idempotencyKey))).get() : void 0;
81259
81497
  if (existingReceipt) {
81260
81498
  assertSameDirectResearchRequest(existingReceipt, input, requestHash2);
81261
81499
  const result2 = getDetail(app, project.id, existingReceipt.id);
@@ -81290,7 +81528,7 @@ async function researchRoutes(app, opts) {
81290
81528
  const initiatedBy = researchPrincipal(request);
81291
81529
  const decision = app.db.transaction((tx) => {
81292
81530
  if (input.idempotencyKey) {
81293
- const existing = tx.select().from(researchRuns).where(and103(eq123(researchRuns.projectId, project.id), eq123(researchRuns.idempotencyKey, input.idempotencyKey))).get();
81531
+ const existing = tx.select().from(researchRuns).where(and103(eq124(researchRuns.projectId, project.id), eq124(researchRuns.idempotencyKey, input.idempotencyKey))).get();
81294
81532
  if (existing) {
81295
81533
  assertSameDirectResearchRequest(existing, input, requestHash2);
81296
81534
  return { reused: true, id: existing.id, shouldDispatch: existing.status === ResearchRunStatuses.queued };
@@ -81299,18 +81537,18 @@ async function researchRoutes(app, opts) {
81299
81537
  if (initiatedBy?.limited) {
81300
81538
  const { start, end, date } = utcDayBounds(now);
81301
81539
  const used = tx.select({ value: count10() }).from(researchRuns).where(and103(
81302
- eq123(researchRuns.projectId, project.id),
81540
+ eq124(researchRuns.projectId, project.id),
81303
81541
  gte34(researchRuns.createdAt, start),
81304
81542
  lt21(researchRuns.createdAt, end),
81305
- sql51`(json_extract(${researchRuns.initiatedBy}, '$.role') = ${UserRoles.viewer} OR json_extract(${researchRuns.initiatedBy}, '$.limited') = 1)`
81543
+ sql52`(json_extract(${researchRuns.initiatedBy}, '$.role') = ${UserRoles.viewer} OR json_extract(${researchRuns.initiatedBy}, '$.limited') = 1)`
81306
81544
  )).get()?.value ?? 0;
81307
81545
  if (used >= viewerDailyRunLimit) {
81308
81546
  throw researchDailyLimitExceeded(project.name, viewerDailyRunLimit, date);
81309
81547
  }
81310
81548
  }
81311
- const id = crypto64.randomUUID();
81549
+ const id = crypto65.randomUUID();
81312
81550
  tx.insert(researchRuns).values({ id, projectId: project.id, status: ResearchRunStatuses.queued, provider: providerName, requestedModel: requestedModel2, resolvedModel, location: location ?? null, totalQueries: input.queries.length, scope, template, idempotencyKey: input.idempotencyKey ?? null, requestHash: input.idempotencyKey ? requestHash2 : null, initiatedBy, createdAt: now }).run();
81313
- for (const [position, query2] of input.queries.entries()) tx.insert(researchRunQueries).values({ id: crypto64.randomUUID(), researchRunId: id, position, queryText: query2, queryClass: queryClasses[position] ?? null, status: ResearchQueryStatuses.queued, requestedModel: requestedModel2, resolvedModel, groundingSources: [], citedDomains: [], searchQueries: [], createdAt: now }).run();
81551
+ for (const [position, query2] of input.queries.entries()) tx.insert(researchRunQueries).values({ id: crypto65.randomUUID(), researchRunId: id, position, queryText: query2, queryClass: queryClasses[position] ?? null, status: ResearchQueryStatuses.queued, requestedModel: requestedModel2, resolvedModel, groundingSources: [], citedDomains: [], searchQueries: [], createdAt: now }).run();
81314
81552
  writeAuditLog(tx, { projectId: project.id, actor: "api", action: "research.created", entityType: "research_run", entityId: id });
81315
81553
  return { reused: false, id, shouldDispatch: true };
81316
81554
  });
@@ -81331,14 +81569,14 @@ async function researchRoutes(app, opts) {
81331
81569
  const requestHash2 = researchBatchRequestHash(input);
81332
81570
  const receiptKeys = input.runs.map((_run, index) => batchChildReceiptKey(input.idempotencyKey, index));
81333
81571
  const firstReceipt = app.db.select().from(researchRuns).where(and103(
81334
- eq123(researchRuns.projectId, project.id),
81335
- eq123(researchRuns.idempotencyKey, receiptKeys[0])
81572
+ eq124(researchRuns.projectId, project.id),
81573
+ eq124(researchRuns.idempotencyKey, receiptKeys[0])
81336
81574
  )).get();
81337
81575
  if (firstReceipt) {
81338
81576
  if (firstReceipt.requestHash !== requestHash2) throw alreadyExists("Research batch idempotency key", input.idempotencyKey);
81339
81577
  const saved = receiptKeys.map((key) => app.db.select().from(researchRuns).where(and103(
81340
- eq123(researchRuns.projectId, project.id),
81341
- eq123(researchRuns.idempotencyKey, key)
81578
+ eq124(researchRuns.projectId, project.id),
81579
+ eq124(researchRuns.idempotencyKey, key)
81342
81580
  )).get());
81343
81581
  if (saved.some((row) => !row || row.requestHash !== requestHash2)) throw alreadyExists("Research batch idempotency key", input.idempotencyKey);
81344
81582
  const runs3 = saved.map((row) => getDetail(app, project.id, row.id));
@@ -81355,16 +81593,16 @@ async function researchRoutes(app, opts) {
81355
81593
  if (initiatedBy?.limited) {
81356
81594
  const { start, end, date } = utcDayBounds(now);
81357
81595
  const used = tx.select({ value: count10() }).from(researchRuns).where(and103(
81358
- eq123(researchRuns.projectId, project.id),
81596
+ eq124(researchRuns.projectId, project.id),
81359
81597
  gte34(researchRuns.createdAt, start),
81360
81598
  lt21(researchRuns.createdAt, end),
81361
- sql51`(json_extract(${researchRuns.initiatedBy}, '$.role') = ${UserRoles.viewer} OR json_extract(${researchRuns.initiatedBy}, '$.limited') = 1)`
81599
+ sql52`(json_extract(${researchRuns.initiatedBy}, '$.role') = ${UserRoles.viewer} OR json_extract(${researchRuns.initiatedBy}, '$.limited') = 1)`
81362
81600
  )).get()?.value ?? 0;
81363
81601
  if (used + prepared.length > viewerDailyRunLimit) throw researchDailyLimitExceeded(project.name, viewerDailyRunLimit, date);
81364
81602
  }
81365
81603
  const ids = [];
81366
81604
  for (const [index, run] of prepared.entries()) {
81367
- const id = crypto64.randomUUID();
81605
+ const id = crypto65.randomUUID();
81368
81606
  ids.push(id);
81369
81607
  tx.insert(researchRuns).values({
81370
81608
  id,
@@ -81383,7 +81621,7 @@ async function researchRoutes(app, opts) {
81383
81621
  createdAt: now
81384
81622
  }).run();
81385
81623
  for (const [position, query2] of run.input.queries.entries()) tx.insert(researchRunQueries).values({
81386
- id: crypto64.randomUUID(),
81624
+ id: crypto65.randomUUID(),
81387
81625
  researchRunId: id,
81388
81626
  position,
81389
81627
  queryText: query2,
@@ -81410,9 +81648,9 @@ async function researchRoutes(app, opts) {
81410
81648
  const limit = Number.isInteger(requested) && requested > 0 ? Math.min(requested, 100) : 20;
81411
81649
  const cursor = request.query.cursor ? parseResearchCursor(request.query.cursor, project.id) : null;
81412
81650
  const rows = app.db.select().from(researchRuns).where(and103(
81413
- eq123(researchRuns.projectId, project.id),
81414
- cursor ? or22(lt21(researchRuns.createdAt, cursor.createdAt), and103(eq123(researchRuns.createdAt, cursor.createdAt), lt21(researchRuns.id, cursor.id))) : void 0
81415
- )).orderBy(desc56(researchRuns.createdAt), desc56(researchRuns.id)).limit(limit + 1).all();
81651
+ eq124(researchRuns.projectId, project.id),
81652
+ cursor ? or23(lt21(researchRuns.createdAt, cursor.createdAt), and103(eq124(researchRuns.createdAt, cursor.createdAt), lt21(researchRuns.id, cursor.id))) : void 0
81653
+ )).orderBy(desc57(researchRuns.createdAt), desc57(researchRuns.id)).limit(limit + 1).all();
81416
81654
  const runs2 = rows.slice(0, limit).map(serializeRun);
81417
81655
  const last = runs2.at(-1);
81418
81656
  const nextCursor = rows.length > limit && last ? Buffer.from(JSON.stringify({ projectId: project.id, createdAt: last.createdAt, id: last.id })).toString("base64url") : null;
@@ -81464,7 +81702,7 @@ function researchProjectProviders(app, projectId, projectProviders) {
81464
81702
  var DIRECT_REQUEST_HASH_VERSION = "direct-v2:";
81465
81703
  function directResearchRequestHash(input) {
81466
81704
  const { idempotencyKey: _key, ...request } = input;
81467
- return DIRECT_REQUEST_HASH_VERSION + crypto64.createHash("sha256").update(JSON.stringify(request)).digest("hex");
81705
+ return DIRECT_REQUEST_HASH_VERSION + crypto65.createHash("sha256").update(JSON.stringify(request)).digest("hex");
81468
81706
  }
81469
81707
  function assertSameDirectResearchRequest(existing, input, hash3) {
81470
81708
  if (existing.requestHash?.startsWith(DIRECT_REQUEST_HASH_VERSION)) {
@@ -81482,7 +81720,7 @@ function assertSameDirectResearchRequest(existing, input, hash3) {
81482
81720
  ...scope ? { scope } : {},
81483
81721
  ...template ? { template } : {}
81484
81722
  };
81485
- if (crypto64.createHash("sha256").update(JSON.stringify(normalized)).digest("hex") !== existing.requestHash) throw alreadyExists("Research idempotency key", input.idempotencyKey);
81723
+ if (crypto65.createHash("sha256").update(JSON.stringify(normalized)).digest("hex") !== existing.requestHash) throw alreadyExists("Research idempotency key", input.idempotencyKey);
81486
81724
  }
81487
81725
  var researchCursorSchema = z7.object({ projectId: z7.string().min(1), createdAt: z7.string().datetime({ offset: true }), id: z7.string().min(1).max(256) }).strict();
81488
81726
  function parseResearchCursor(value, projectId) {
@@ -81502,11 +81740,11 @@ function resolveStoredResearchScope(stored, selection, idempotencyKey) {
81502
81740
  return stored;
81503
81741
  }
81504
81742
  function batchChildReceiptKey(rootKey, index) {
81505
- const derived = crypto64.createHash("sha256").update(`${rootKey}\0${index}`).digest("hex");
81743
+ const derived = crypto65.createHash("sha256").update(`${rootKey}\0${index}`).digest("hex");
81506
81744
  return `${BATCH_RECEIPT_PREFIX}${derived}:${index}`;
81507
81745
  }
81508
81746
  function researchBatchRequestHash(input) {
81509
- return crypto64.createHash("sha256").update(JSON.stringify({ runs: input.runs })).digest("hex");
81747
+ return crypto65.createHash("sha256").update(JSON.stringify({ runs: input.runs })).digest("hex");
81510
81748
  }
81511
81749
  function prepareBatchRun(app, opts, project, active, input) {
81512
81750
  const adapters = opts.providerAdapters ?? [];
@@ -81562,8 +81800,8 @@ function resolveStoredResearchTemplate(stored, selection, idempotencyKey) {
81562
81800
  }
81563
81801
  function resolveResearchTemplate(app, projectId, selection, scope, location) {
81564
81802
  const savedTemplate = app.db.select().from(measurementQueryTemplates).where(and103(
81565
- eq123(measurementQueryTemplates.projectId, projectId),
81566
- eq123(measurementQueryTemplates.id, selection.templateId)
81803
+ eq124(measurementQueryTemplates.projectId, projectId),
81804
+ eq124(measurementQueryTemplates.id, selection.templateId)
81567
81805
  )).get();
81568
81806
  if (!savedTemplate) throw validationError("Unknown or stale research template. Reload the selected template and try again.");
81569
81807
  const templateVersion = savedTemplate.updatedAt;
@@ -81572,7 +81810,7 @@ function resolveResearchTemplate(app, projectId, selection, scope, location) {
81572
81810
  }
81573
81811
  const bindingLocation = selection.bindingLocation === void 0 ? location : selection.bindingLocation;
81574
81812
  if (bindingLocation) {
81575
- const project = app.db.select({ locations: projects.locations }).from(projects).where(eq123(projects.id, projectId)).get();
81813
+ const project = app.db.select({ locations: projects.locations }).from(projects).where(eq124(projects.id, projectId)).get();
81576
81814
  if (!project.locations.some((item2) => sameLocation(item2, bindingLocation))) throw validationError("Research template binding location must match a configured project location.");
81577
81815
  }
81578
81816
  const { bindings, output } = expandResearchTemplate(savedTemplate, scope, bindingLocation);
@@ -81585,9 +81823,9 @@ function classifyResearchQueries(project, plan, queries2) {
81585
81823
  return queries2.map((query2) => classifier?.classify(query2) ?? null);
81586
81824
  }
81587
81825
  function getDetail(app, projectId, id) {
81588
- const row = app.db.select().from(researchRuns).where(and103(eq123(researchRuns.id, id), eq123(researchRuns.projectId, projectId))).get();
81826
+ const row = app.db.select().from(researchRuns).where(and103(eq124(researchRuns.id, id), eq124(researchRuns.projectId, projectId))).get();
81589
81827
  if (!row) throw notFound("Research run", id);
81590
- const queries2 = app.db.select().from(researchRunQueries).where(eq123(researchRunQueries.researchRunId, id)).orderBy(researchRunQueries.position).all().map((query2) => serializeQuery(query2, row.provider));
81828
+ const queries2 = app.db.select().from(researchRunQueries).where(eq124(researchRunQueries.researchRunId, id)).orderBy(researchRunQueries.position).all().map((query2) => serializeQuery(query2, row.provider));
81591
81829
  return { ...serializeRun(row), queries: queries2 };
81592
81830
  }
81593
81831
  function serializeRun(row) {
@@ -81647,8 +81885,8 @@ function utcDayBounds(now) {
81647
81885
  }
81648
81886
 
81649
81887
  // ../api-routes/src/simple-measurement-definitions.ts
81650
- import crypto65 from "crypto";
81651
- import { and as and104, eq as eq124 } from "drizzle-orm";
81888
+ import crypto66 from "crypto";
81889
+ import { and as and104, eq as eq125 } from "drizzle-orm";
81652
81890
  function captureSimpleMeasurementDefinition(db, input) {
81653
81891
  return db.transaction((tx) => {
81654
81892
  const run = tx.select({
@@ -81656,7 +81894,7 @@ function captureSimpleMeasurementDefinition(db, input) {
81656
81894
  trigger: runs.trigger,
81657
81895
  status: runs.status,
81658
81896
  measurementPlanVersionId: runs.measurementPlanVersionId
81659
- }).from(runs).where(and104(eq124(runs.projectId, input.projectId), eq124(runs.id, input.runId))).get();
81897
+ }).from(runs).where(and104(eq125(runs.projectId, input.projectId), eq125(runs.id, input.runId))).get();
81660
81898
  if (!run) throw notFound("Run", input.runId);
81661
81899
  if (run.kind !== RunKinds["answer-visibility"] || run.trigger === RunTriggers.probe || run.measurementPlanVersionId !== null) {
81662
81900
  return null;
@@ -81677,7 +81915,7 @@ function captureSimpleMeasurementDefinition(db, input) {
81677
81915
  throw validationError("Qualified aliases must be a sorted subset of the captured aliases.");
81678
81916
  }
81679
81917
  }
81680
- const existing = tx.select().from(simpleMeasurementDefinitions).where(and104(eq124(simpleMeasurementDefinitions.projectId, input.projectId), eq124(simpleMeasurementDefinitions.runId, input.runId))).get();
81918
+ const existing = tx.select().from(simpleMeasurementDefinitions).where(and104(eq125(simpleMeasurementDefinitions.projectId, input.projectId), eq125(simpleMeasurementDefinitions.runId, input.runId))).get();
81681
81919
  if (existing) {
81682
81920
  const frozen = simpleMeasurementDefinitionSchema.parse(existing.definition);
81683
81921
  const { qualifiedAliases: _liveQualifiedAliases, ...liveIdentity } = definition2.identity;
@@ -81689,11 +81927,11 @@ function captureSimpleMeasurementDefinition(db, input) {
81689
81927
  ...frozen.identity.qualifiedAliases?.length ? { qualifiedAliases: frozen.identity.qualifiedAliases } : {}
81690
81928
  }
81691
81929
  };
81692
- const replayChecksum = crypto65.createHash("sha256").update(canonicalSimpleMeasurementDefinitionJson(replayDefinition)).digest("hex");
81930
+ const replayChecksum = crypto66.createHash("sha256").update(canonicalSimpleMeasurementDefinitionJson(replayDefinition)).digest("hex");
81693
81931
  if (existing.checksum !== replayChecksum) {
81694
81932
  if (frozen.competitors === void 0) {
81695
81933
  const { competitors: _currentCompetitors, ...legacyReplayDefinition } = replayDefinition;
81696
- const legacyReplayChecksum = crypto65.createHash("sha256").update(canonicalSimpleMeasurementDefinitionJson(legacyReplayDefinition)).digest("hex");
81934
+ const legacyReplayChecksum = crypto66.createHash("sha256").update(canonicalSimpleMeasurementDefinitionJson(legacyReplayDefinition)).digest("hex");
81697
81935
  if (existing.checksum === legacyReplayChecksum) return frozen;
81698
81936
  }
81699
81937
  throw validationError("This run already has a captured measurement definition. Start a new run for changed inputs.");
@@ -81703,21 +81941,21 @@ function captureSimpleMeasurementDefinition(db, input) {
81703
81941
  if (run.status !== RunStatuses.running) {
81704
81942
  throw validationError("Only a running run can capture a new measurement definition.");
81705
81943
  }
81706
- if (tx.select({ id: querySnapshots.id }).from(querySnapshots).where(eq124(querySnapshots.runId, input.runId)).limit(1).get()) {
81944
+ if (tx.select({ id: querySnapshots.id }).from(querySnapshots).where(eq125(querySnapshots.runId, input.runId)).limit(1).get()) {
81707
81945
  throw validationError("This run already has stored answers. Its measurement definition cannot be inferred afterward.");
81708
81946
  }
81709
- const projectQueryIds = new Set(tx.select({ id: queries.id }).from(queries).where(eq124(queries.projectId, input.projectId)).all().map((query2) => query2.id));
81947
+ const projectQueryIds = new Set(tx.select({ id: queries.id }).from(queries).where(eq125(queries.projectId, input.projectId)).all().map((query2) => query2.id));
81710
81948
  if (definition2.queries.some((query2) => !projectQueryIds.has(query2.queryId))) {
81711
81949
  throw validationError("Every captured query must belong to the run project.");
81712
81950
  }
81713
81951
  if (definition2.competitors !== void 0) {
81714
- const liveCompetitorDomains = new Set(tx.select({ domain: competitors.domain }).from(competitors).where(eq124(competitors.projectId, input.projectId)).orderBy(competitors.domain).all().map((competitor) => competitor.domain));
81952
+ const liveCompetitorDomains = new Set(tx.select({ domain: competitors.domain }).from(competitors).where(eq125(competitors.projectId, input.projectId)).orderBy(competitors.domain).all().map((competitor) => competitor.domain));
81715
81953
  const capturedDomains = new Set(definition2.competitors.map((competitor) => competitor.domain));
81716
81954
  if (liveCompetitorDomains.size !== capturedDomains.size || [...liveCompetitorDomains].some((domain) => !capturedDomains.has(domain))) {
81717
81955
  throw validationError("Captured competitors must exactly match the project competitors dispatched for this run.");
81718
81956
  }
81719
81957
  }
81720
- const checksum = crypto65.createHash("sha256").update(canonicalSimpleMeasurementDefinitionJson(definition2)).digest("hex");
81958
+ const checksum = crypto66.createHash("sha256").update(canonicalSimpleMeasurementDefinitionJson(definition2)).digest("hex");
81721
81959
  tx.insert(simpleMeasurementDefinitions).values({
81722
81960
  projectId: input.projectId,
81723
81961
  runId: input.runId,
@@ -81971,7 +82209,8 @@ async function apiRoutes(app, opts) {
81971
82209
  providerAdapters: opts.providerAdapters
81972
82210
  });
81973
82211
  await api.register(notificationRoutes, {
81974
- allowLoopbackWebhooks: opts.allowLoopbackWebhooks
82212
+ allowLoopbackWebhooks: opts.allowLoopbackWebhooks,
82213
+ appVersion: opts.appVersion
81975
82214
  });
81976
82215
  await api.register(sentimentRoutes, opts.sentiment ?? { install: () => ({ enabled: false, ready: false, reason: "install-disabled", model: "jev-1.13.0" }), previewSecret: randomUUID4() });
81977
82216
  await api.register(operationalLogsRoutes, { listOperationalLogs: opts.listOperationalLogs });
@@ -82450,6 +82689,7 @@ export {
82450
82689
  nextRunFromCron,
82451
82690
  nextRunFromSchedule,
82452
82691
  resolveWebhookTarget,
82692
+ webhookUserAgent,
82453
82693
  deliverWebhook,
82454
82694
  readAdvancedSignalTransitions,
82455
82695
  readLatestGscDataDate,