@canonry/canonry 7.111.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 (141) hide show
  1. package/README.md +1 -1
  2. package/assets/agent-workspace/skills/aero/references/ai-traffic-tracking.md +5 -3
  3. package/assets/agent-workspace/skills/canonry/references/ai-traffic-tracking.md +5 -3
  4. package/assets/agent-workspace/skills/canonry/references/canonry-cli.md +3 -0
  5. package/assets/agent-workspace/skills/canonry/references/server-side-traffic.md +4 -0
  6. package/assets/assets/{AccessControls-CJMIWtDc.js → AccessControls-BxtFDXYH.js} +1 -1
  7. package/assets/assets/{AgentSetupPage-DR8w0A9t.js → AgentSetupPage-q1Ku1PAd.js} +1 -1
  8. package/assets/assets/{AuditHistoryPanel-BLF2-WSw.js → AuditHistoryPanel-6EnlABwM.js} +1 -1
  9. package/assets/assets/{BacklinksPage-BCuEkphC.js → BacklinksPage-BaHCJEuK.js} +1 -1
  10. package/assets/assets/{ChartPrimitives-Dxr7b1zf.js → ChartPrimitives-C3lJj3eO.js} +1 -1
  11. package/assets/assets/{HistoryPage-C3UcNB4C.js → HistoryPage-B_NVeDCn.js} +1 -1
  12. package/assets/assets/{MeasurementPropertyPage-BKDciQn4.js → MeasurementPropertyPage-DxCRxoIF.js} +1 -1
  13. package/assets/assets/{ProjectPage-BwkFGMs_.js → ProjectPage-BjGsilZJ.js} +3 -3
  14. package/assets/assets/{RunsPage-BqteFByy.js → RunsPage-9T1OrQw3.js} +1 -1
  15. package/assets/assets/{ServerTrafficSection-CqHfSvux.js → ServerTrafficSection-iUdFKWEc.js} +1 -1
  16. package/assets/assets/{SettingsPage-BORbl6fR.js → SettingsPage-BswQYkkB.js} +1 -1
  17. package/assets/assets/{ToneBadge-Cu25HdVj.js → ToneBadge-CWufDJgM.js} +2 -2
  18. package/assets/assets/{TrafficPage-xqJU4CR4.js → TrafficPage-DN9DxoWm.js} +1 -1
  19. package/assets/assets/{TrafficSourceDetailPage-CVHyU3Za.js → TrafficSourceDetailPage-D6TdTyP-.js} +1 -1
  20. package/assets/assets/{account-context-DR0diETl.js → account-context-CyE8qMvH.js} +1 -1
  21. package/assets/assets/{agent-trust-copy-DX06JhNj.js → agent-trust-copy-CinW-f_8.js} +1 -1
  22. package/assets/assets/{card-BG4pD6H7.js → card-CI9gz2Hb.js} +1 -1
  23. package/assets/assets/{index-CggAFvBE.js → index-DshFRkPM.js} +3 -3
  24. package/assets/assets/{query-client-DiID-orC.js → query-client-BlAtm9zS.js} +1 -1
  25. package/assets/assets/{react-query-gPYNMl8L.js → react-query-DE_LaZkX.js} +1 -1
  26. package/assets/assets/{react-sigma_core.esm.min-CaAAyMHy.js → react-sigma_core.esm.min-CZkN6sL0.js} +1 -1
  27. package/assets/assets/{server-traffic-DGkceMij.js → server-traffic-Ci9JbS2U.js} +1 -1
  28. package/assets/assets/{service-DqtXV3A5.js → service-CiYDMju_.js} +1 -1
  29. package/assets/index.html +8 -8
  30. package/dist/{ads-MA5UHDSK.js → ads-WRMNYPJ7.js} +3 -3
  31. package/dist/{agent-QBDESRUX.js → agent-V4PAGAPZ.js} +7 -7
  32. package/dist/{agent-ask-DVUWIY4T.js → agent-ask-3LAAT4WN.js} +3 -3
  33. package/dist/{agent-conversations-Q7SE57ZA.js → agent-conversations-TVNDZY54.js} +3 -3
  34. package/dist/{agent-journeys-OWNSW6GR.js → agent-journeys-UB7ZGAKP.js} +3 -3
  35. package/dist/{agent-memory-YIVRBUPS.js → agent-memory-RWF2WODB.js} +3 -3
  36. package/dist/{agent-providers-UDILAU6B.js → agent-providers-77A45KZD.js} +3 -3
  37. package/dist/{agent-transcript-KU7ELEEC.js → agent-transcript-K5WZJHJX.js} +3 -3
  38. package/dist/{analytics-WFMI7N5Y.js → analytics-RNSYOGUP.js} +3 -3
  39. package/dist/{apply-2WHADGXD.js → apply-UU6GFYIJ.js} +3 -3
  40. package/dist/{backfill-ZNGMPK7N.js → backfill-DOYPYZJL.js} +10 -10
  41. package/dist/{backlinks-LH77XWHZ.js → backlinks-UKRILGDJ.js} +3 -3
  42. package/dist/{bing-5OCPBLYU.js → bing-P6GTLGIP.js} +3 -3
  43. package/dist/{bootstrap-SCTHOCSM.js → bootstrap-BRXDKCNB.js} +10 -10
  44. package/dist/{cdp-6OEBXRAY.js → cdp-CPGVPWTU.js} +7 -7
  45. package/dist/{chunk-PPOHDQ3T.js → chunk-2LXLJXTG.js} +2 -2
  46. package/dist/{chunk-IU26JPKH.js → chunk-4ALKLWSQ.js} +619 -384
  47. package/dist/{chunk-DR4QNC2H.js → chunk-4PMS7CAF.js} +2 -2
  48. package/dist/{chunk-4EWCBHGV.js → chunk-4WXNCSYL.js} +2 -2
  49. package/dist/{chunk-VXOZUCH4.js → chunk-7IF576RC.js} +5 -5
  50. package/dist/{chunk-QKEBSO3T.js → chunk-AZPWF42S.js} +7 -3
  51. package/dist/{chunk-BZMIVLRX.js → chunk-B27F7C6S.js} +5 -5
  52. package/dist/{chunk-S7TL4SCS.js → chunk-C44S7EE7.js} +4 -4
  53. package/dist/{chunk-YQ5NFMQB.js → chunk-DZCJNSBY.js} +1 -1
  54. package/dist/{chunk-LPW2TRLI.js → chunk-F6CYO37C.js} +6 -6
  55. package/dist/{chunk-44JAOWMT.js → chunk-I4YRKF6G.js} +3 -3
  56. package/dist/{chunk-EUARY2OX.js → chunk-JCK5TDIU.js} +71 -4
  57. package/dist/{chunk-A2VDUQB2.js → chunk-JHAG6DEG.js} +3 -3
  58. package/dist/{chunk-XAS6ARPI.js → chunk-KYZ5A7AX.js} +1 -1
  59. package/dist/{chunk-KMES74KU.js → chunk-LGAQXH3L.js} +1 -1
  60. package/dist/{chunk-BNHQ55UD.js → chunk-M2RTTCLC.js} +3 -3
  61. package/dist/{chunk-WK6SPZG4.js → chunk-N5K35MDQ.js} +1 -1
  62. package/dist/{chunk-LGPITEEE.js → chunk-NICTKJ3O.js} +1 -1
  63. package/dist/{chunk-GHNEC23U.js → chunk-NLU2MMFA.js} +1 -1
  64. package/dist/{chunk-MQU5QBUQ.js → chunk-OBDRDAIK.js} +1 -1
  65. package/dist/{chunk-TSQG2PNH.js → chunk-PT3VROG7.js} +376 -368
  66. package/dist/{chunk-H5LL4HMB.js → chunk-Q4XHWZDT.js} +1 -1
  67. package/dist/{chunk-IBTMJA76.js → chunk-R4PQ7D32.js} +7 -7
  68. package/dist/{chunk-5IX4ZOSU.js → chunk-S6ULO6H5.js} +1 -1
  69. package/dist/{chunk-U4YVA2A2.js → chunk-SJD3ZAEH.js} +2 -2
  70. package/dist/{chunk-LGPJMBH2.js → chunk-SNL4C4BV.js} +2 -2
  71. package/dist/{chunk-YOQQUG7C.js → chunk-TDRPVIUB.js} +1 -1
  72. package/dist/{chunk-ORX3X7P5.js → chunk-TDSISMOJ.js} +21 -21
  73. package/dist/{chunk-CJRL5BT3.js → chunk-W3UYVNYQ.js} +1 -1
  74. package/dist/{chunk-46HRC23F.js → chunk-WHBLQJGZ.js} +1 -1
  75. package/dist/{chunk-3SCJOPT5.js → chunk-Y6D7K63F.js} +3 -3
  76. package/dist/{chunk-N5U474SX.js → chunk-YN7OV22K.js} +4 -4
  77. package/dist/{chunk-UKQPA7NT.js → chunk-YWKALX6A.js} +4 -4
  78. package/dist/{chunk-523WBUKU.js → chunk-YXCMVHYJ.js} +3 -3
  79. package/dist/{chunk-ZKYOGC7O.js → chunk-ZMCRVQ6Q.js} +1 -1
  80. package/dist/{chunk-EQ6RZE7U.js → chunk-ZVDUBOE4.js} +16 -6
  81. package/dist/{citations-27ENEGJM.js → citations-GW2ELWME.js} +4 -4
  82. package/dist/{cli-catalog-PAZQB7WG.js → cli-catalog-PDU4Z4IO.js} +3 -3
  83. package/dist/{cli-commands-L6G5AQG2.js → cli-commands-XWIWF4VG.js} +7 -7
  84. package/dist/cli.js +13 -13
  85. package/dist/{competitor-EK5UX6W6.js → competitor-MS4P6GJ4.js} +3 -3
  86. package/dist/{content-3MBCVYMR.js → content-3QQRT3Q4.js} +3 -3
  87. package/dist/{dashboard-5LZMYX52.js → dashboard-FDVY7CMI.js} +6 -6
  88. package/dist/{demo-2NB2BVZO.js → demo-WRF3ZSQ5.js} +1 -1
  89. package/dist/{demo-server-MUJ566YQ.js → demo-server-Q77EUE5A.js} +12 -12
  90. package/dist/{discover-VMPF4CLS.js → discover-BAKAHH5X.js} +4 -4
  91. package/dist/{discover-eval-EK5ZAJKW.js → discover-eval-KMYMVZVX.js} +3 -3
  92. package/dist/{doctor-2KY5SS4O.js → doctor-OAYNGBBT.js} +3 -3
  93. package/dist/{evidence-OXYY666S.js → evidence-FEDSZTLW.js} +3 -3
  94. package/dist/{export-cmd-5Q6TNXN6.js → export-cmd-OYQVBE5C.js} +3 -3
  95. package/dist/{ga-CG3KAWEE.js → ga-MWJQ2S4D.js} +3 -3
  96. package/dist/{gbp-F555XC4I.js → gbp-K4FXHF6N.js} +3 -3
  97. package/dist/{google-44XHCXOZ.js → google-B6VUPLQN.js} +4 -4
  98. package/dist/{google-marketing-MSJVMCMQ.js → google-marketing-3KKTACAA.js} +1 -1
  99. package/dist/{health-cmd-KXCY4527.js → health-cmd-YEHYFXEN.js} +4 -4
  100. package/dist/{history-Y6PMRNUA.js → history-5EYU4PQT.js} +3 -3
  101. package/dist/index.d.ts +32 -32
  102. package/dist/index.js +25 -25
  103. package/dist/{init-CCVUPSZZ.js → init-2HLTEB5Y.js} +12 -12
  104. package/dist/{insights-FGR5AU5D.js → insights-MW5VTF7N.js} +3 -3
  105. package/dist/intelligence-service-PTAA5WJB.js +16 -0
  106. package/dist/{journeys-2V4KIVDF.js → journeys-YW2IWDMN.js} +3 -3
  107. package/dist/{keys-2EOH2M22.js → keys-RRT26LGV.js} +3 -3
  108. package/dist/{keyword-XFHVSN3B.js → keyword-KSN3JTCX.js} +3 -3
  109. package/dist/{logs-WJU66NI5.js → logs-IPAE4F4W.js} +3 -3
  110. package/dist/{mcp-23HANPN3.js → mcp-WJR6RKYK.js} +4 -4
  111. package/dist/mcp.js +9 -9
  112. package/dist/{measurement-plan-VQIG5UCP.js → measurement-plan-DGLUEK7M.js} +5 -5
  113. package/dist/{notify-E33IOGRC.js → notify-3QOG6NWS.js} +3 -3
  114. package/dist/{organic-evidence-3YJ3WTF5.js → organic-evidence-M3VSSLQR.js} +3 -3
  115. package/dist/{overview-66VPXGSA.js → overview-7RRCHUWZ.js} +5 -5
  116. package/dist/{project-SHXJFR3K.js → project-T3JZJPVK.js} +3 -3
  117. package/dist/{project-setup-SMTRU7UG.js → project-setup-Y6DSDF4V.js} +3 -3
  118. package/dist/{query-UNCXNQLZ.js → query-24JZPB3M.js} +3 -3
  119. package/dist/{research-C5JIOYGU.js → research-ERVKTKMV.js} +3 -3
  120. package/dist/{results-export-WZZDWAQB.js → results-export-KSGIWPAM.js} +3 -3
  121. package/dist/{run-NRBLHGT3.js → run-XX6YUJRI.js} +5 -5
  122. package/dist/{schedule-BOBKSQAN.js → schedule-JBZENJ2V.js} +3 -3
  123. package/dist/{search-26B4UX3P.js → search-V67KUYIZ.js} +3 -3
  124. package/dist/{serve-3TN2RDHE.js → serve-HTQ76BFW.js} +26 -26
  125. package/dist/{session-PTB4UBY3.js → session-AJ6R6K4B.js} +13 -13
  126. package/dist/{settings-25JAM5MJ.js → settings-KVKWFTJZ.js} +3 -3
  127. package/dist/{sitemaps-YXJIIT52.js → sitemaps-UDIC4YUU.js} +3 -3
  128. package/dist/{skills-HAYPXHWH.js → skills-35CPSNXM.js} +2 -2
  129. package/dist/{snapshot-V6D4W4MF.js → snapshot-OHGM7JBF.js} +3 -3
  130. package/dist/{src-ENRBRVV2.js → src-GNBUAHT7.js} +2 -2
  131. package/dist/{status-35RGWHEQ.js → status-GKWSTMUV.js} +5 -5
  132. package/dist/{technical-aeo-YG7Q3554.js → technical-aeo-IHQYV4TT.js} +3 -3
  133. package/dist/{telemetry-LUT6F4HJ.js → telemetry-AA2CONG2.js} +4 -4
  134. package/dist/{tools-NPGGINFO.js → tools-CWNRV7PQ.js} +11 -11
  135. package/dist/{traffic-CKYSAD4T.js → traffic-F7WR32VB.js} +55 -13
  136. package/dist/{trends-NQZD7X67.js → trends-YB2GNT75.js} +3 -3
  137. package/dist/{users-6FPNRCXJ.js → users-PXTIUGXI.js} +3 -3
  138. package/dist/{visibility-stats-S2FXH3NH.js → visibility-stats-KSPE4GHQ.js} +4 -4
  139. package/dist/{wordpress-BN62WUII.js → wordpress-YGSH5MSK.js} +3 -3
  140. package/package.json +1 -1
  141. package/dist/intelligence-service-NOZAMR73.js +0 -16
@@ -19,14 +19,14 @@ import {
19
19
  normalizeTrafficPathPattern,
20
20
  sessionizeJourneyRequests,
21
21
  verifyRequestSignature
22
- } from "./chunk-5IX4ZOSU.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-WK6SPZG4.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-MQU5QBUQ.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-EUARY2OX.js";
1377
+ } from "./chunk-JCK5TDIU.js";
1376
1378
 
1377
1379
  // ../api-routes/src/user-session.ts
1378
1380
  import crypto2 from "crypto";
@@ -48791,7 +48793,7 @@ var routeCatalog = [
48791
48793
  method: "get",
48792
48794
  path: "/api/v1/projects/{name}/traffic/events",
48793
48795
  summary: "List rolled-up crawler hits, AI user-fetch hits, and AI-referral sessions within a window",
48794
- 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.",
48795
48797
  tags: ["traffic"],
48796
48798
  parameters: [
48797
48799
  nameParameter,
@@ -48800,7 +48802,11 @@ var routeCatalog = [
48800
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 },
48801
48803
  { name: "limit", in: "query", description: "Max newest combined detail rows in the events array (default 500, max 5000).", schema: stringSchema },
48802
48804
  { name: "sourceId", in: "query", description: "Restrict to a single traffic source.", schema: stringSchema },
48803
- { 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 }
48804
48810
  ],
48805
48811
  responses: {
48806
48812
  200: jsonResponse("Events returned with windowed totals.", "TrafficEventsResponse"),
@@ -69946,7 +69952,7 @@ async function queryBacklinks(opts) {
69946
69952
  const reversed = opts.targets.map(reverseDomain);
69947
69953
  const targetList = reversed.map(quote).join(", ");
69948
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)}` : "";
69949
- const sql52 = `
69955
+ const sql53 = `
69950
69956
  WITH vertices AS (
69951
69957
  SELECT * FROM read_csv(
69952
69958
  ${quote(opts.vertexPath)},
@@ -69982,7 +69988,7 @@ async function queryBacklinks(opts) {
69982
69988
  const conn = await instance.connect();
69983
69989
  let rows;
69984
69990
  try {
69985
- const reader = await conn.runAndReadAll(sql52);
69991
+ const reader = await conn.runAndReadAll(sql53);
69986
69992
  rows = reader.getRowObjects();
69987
69993
  } finally {
69988
69994
  conn.disconnectSync?.();
@@ -70484,10 +70490,10 @@ async function backlinksRoutes(app, opts) {
70484
70490
  }
70485
70491
 
70486
70492
  // ../api-routes/src/traffic.ts
70487
- import crypto60 from "crypto";
70493
+ import crypto61 from "crypto";
70488
70494
  import { isIP as isIP3 } from "net";
70489
70495
  import { isDeepStrictEqual } from "util";
70490
- 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";
70491
70497
 
70492
70498
  // ../api-routes/src/traffic-limits.ts
70493
70499
  var VERCEL_MAX_SYNC_WINDOW_MS = 24 * 60 * 6e4;
@@ -71867,6 +71873,158 @@ function releaseTrafficSyncLease(input) {
71867
71873
  }, { behavior: "immediate" });
71868
71874
  }
71869
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
+
71870
72028
  // ../api-routes/src/traffic.ts
71871
72029
  var DEFAULT_SYNC_WINDOW_MINUTES = 43200;
71872
72030
  var DEFAULT_PAGE_SIZE3 = 1e3;
@@ -71905,7 +72063,7 @@ function logBrowserAgentNonPageHits(log, fields) {
71905
72063
  );
71906
72064
  }
71907
72065
  function sha256Hex3(value) {
71908
- return crypto60.createHash("sha256").update(value).digest("hex");
72066
+ return crypto61.createHash("sha256").update(value).digest("hex");
71909
72067
  }
71910
72068
  function hashCloudflareBearerToken(value) {
71911
72069
  return sha256Hex3(value);
@@ -71915,7 +72073,7 @@ function timingSafeEqualHex(a, b) {
71915
72073
  if (!SHA256_HEX_PATTERN.test(a) || !SHA256_HEX_PATTERN.test(b)) return false;
71916
72074
  const left = Buffer.from(a, "hex");
71917
72075
  const right = Buffer.from(b, "hex");
71918
- return left.length === right.length && crypto60.timingSafeEqual(left, right);
72076
+ return left.length === right.length && crypto61.timingSafeEqual(left, right);
71919
72077
  }
71920
72078
  async function loadQueueReceiptPolicy(db, sourceId, readRetentionSeconds, warn2) {
71921
72079
  let liveTtlMs = null;
@@ -71935,14 +72093,14 @@ async function loadQueueReceiptPolicy(db, sourceId, readRetentionSeconds, warn2)
71935
72093
  if (liveTtlMs === null) return { ttlMsAt: () => CLOUDFLARE_QUEUE_RECEIPT_TTL_MS };
71936
72094
  const ttlMs = liveTtlMs;
71937
72095
  const now = (/* @__PURE__ */ new Date()).toISOString();
71938
- const alive = and89(eq103(trafficEventReceipts.sourceId, sourceId), gt8(trafficEventReceipts.expiresAt, now));
71939
- const lifetimeMs = sql47`(julianday(${trafficEventReceipts.expiresAt}) - julianday(${trafficEventReceipts.receivedAt})) * ${DAY_MS5}`;
71940
- 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;
71941
72099
  if (shortest !== null && shortest < ttlMs - 1e3) {
71942
- 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})`;
71943
72101
  db.update(trafficEventReceipts).set({ expiresAt: extended }).where(and89(alive, lt20(trafficEventReceipts.expiresAt, extended))).run();
71944
72102
  }
71945
- 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;
71946
72104
  const floorMs = floorExpiry ? Date.parse(floorExpiry) : 0;
71947
72105
  return { ttlMsAt: (receivedAt) => Math.max(ttlMs, floorMs - Date.parse(receivedAt)) };
71948
72106
  }
@@ -71997,7 +72155,7 @@ function cloudflareIngestRateLimitKey(request, store, db) {
71997
72155
  const authenticated = authenticateCloudflareIngest(request, store);
71998
72156
  const params = request.params;
71999
72157
  if (authenticated && typeof params.name === "string" && authenticated.credential.projectName === params.name) {
72000
- 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();
72001
72159
  if (source && source.sourceType === TrafficSourceTypes.cloudflare && source.status === TrafficSourceStatuses.connected && parseDirectPushCloudflareSourceConfig(source.configJson) && timingSafeEqualHex(authenticated.bearerHash, source.ingestTokenHash)) {
72002
72160
  return `cloudflare-source:${authenticated.credential.sourceId}`;
72003
72161
  }
@@ -72076,7 +72234,7 @@ var SERIES_BUCKET_LENGTH = {
72076
72234
  };
72077
72235
  function seriesBucketSql(tsHour, granularity) {
72078
72236
  const length = SERIES_BUCKET_LENGTH[granularity];
72079
- 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))})`;
72080
72238
  }
72081
72239
  function seriesBucketOf(iso2, granularity) {
72082
72240
  const length = SERIES_BUCKET_LENGTH[granularity];
@@ -72168,7 +72326,7 @@ function crawlerVerificationProvenance(db, projectId, events) {
72168
72326
  manifestId: crawlerVerificationManifestsHourly.manifestId,
72169
72327
  manifest: crawlerVerificationManifestsHourly.manifestJson,
72170
72328
  hits: crawlerVerificationManifestsHourly.hits
72171
- }).from(crawlerVerificationManifestsHourly).where(sql47`(
72329
+ }).from(crawlerVerificationManifestsHourly).where(sql48`(
72172
72330
  ${crawlerVerificationManifestsHourly.projectId},
72173
72331
  ${crawlerVerificationManifestsHourly.sourceId},
72174
72332
  ${crawlerVerificationManifestsHourly.tsHour},
@@ -72202,7 +72360,7 @@ function aiUserFetchVerificationProvenance(db, projectId, events) {
72202
72360
  manifestId: aiUserFetchVerificationManifestsHourly.manifestId,
72203
72361
  manifest: aiUserFetchVerificationManifestsHourly.manifestJson,
72204
72362
  hits: aiUserFetchVerificationManifestsHourly.hits
72205
- }).from(aiUserFetchVerificationManifestsHourly).where(sql47`(
72363
+ }).from(aiUserFetchVerificationManifestsHourly).where(sql48`(
72206
72364
  ${aiUserFetchVerificationManifestsHourly.projectId},
72207
72365
  ${aiUserFetchVerificationManifestsHourly.sourceId},
72208
72366
  ${aiUserFetchVerificationManifestsHourly.tsHour},
@@ -72257,7 +72415,7 @@ async function defaultResolveAccessToken(record3) {
72257
72415
  );
72258
72416
  }
72259
72417
  function hasConnectedTrafficSourceSibling(db, projectId, sourceId) {
72260
- 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);
72261
72419
  }
72262
72420
  function isAuthoritativeTrafficSource(db, source) {
72263
72421
  return (source.status === TrafficSourceStatuses.connected || source.status === TrafficSourceStatuses.error) && !hasConnectedTrafficSourceSibling(db, source.projectId, source.id);
@@ -72285,17 +72443,17 @@ function wordpressBaseUrlIdentity(value) {
72285
72443
  }
72286
72444
  function bindTrafficSyncSchedule(tx, projectId, sourceId, now, createIfMissing = true) {
72287
72445
  const schedule = tx.select().from(schedules).where(and89(
72288
- eq103(schedules.projectId, projectId),
72289
- eq103(schedules.kind, SchedulableRunKinds["traffic-sync"])
72446
+ eq104(schedules.projectId, projectId),
72447
+ eq104(schedules.kind, SchedulableRunKinds["traffic-sync"])
72290
72448
  )).get();
72291
72449
  if (schedule) {
72292
72450
  if (schedule.sourceId === sourceId) return { changed: false, created: false };
72293
- 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();
72294
72452
  return { changed: true, created: false };
72295
72453
  }
72296
72454
  if (!createIfMissing) return { changed: false, created: false };
72297
72455
  tx.insert(schedules).values({
72298
- id: crypto60.randomUUID(),
72456
+ id: crypto61.randomUUID(),
72299
72457
  projectId,
72300
72458
  kind: SchedulableRunKinds["traffic-sync"],
72301
72459
  cronExpr: DEFAULT_TRAFFIC_SYNC_CRON,
@@ -72332,7 +72490,7 @@ async function runBackfillTask(options) {
72332
72490
  };
72333
72491
  const renewLease2 = setInterval(() => {
72334
72492
  try {
72335
- 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();
72336
72494
  if (!latest || !isAuthoritativeTrafficSource(app.db, latest) || !isSameTrafficSourceGeneration(latest, sourceRow2)) {
72337
72495
  clearInterval(renewLease2);
72338
72496
  stopped.abort();
@@ -72380,10 +72538,10 @@ async function runBackfillTaskHoldingLease(options, signal) {
72380
72538
  const failedAt = (/* @__PURE__ */ new Date()).toISOString();
72381
72539
  try {
72382
72540
  app.db.transaction((tx) => {
72383
- tx.update(runs).set({ status: RunStatuses.failed, error: msg, finishedAt: failedAt }).where(eq103(runs.id, runId)).run();
72384
- 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();
72385
72543
  if (!preserveSourceState && latestSource && isAuthoritativeTrafficSource(tx, latestSource) && isSameBackfillSource(latestSource, sourceRow2, leaseOwner)) {
72386
- 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();
72387
72545
  }
72388
72546
  });
72389
72547
  } catch {
@@ -72415,7 +72573,7 @@ async function runBackfillTaskHoldingLease(options, signal) {
72415
72573
  let emptyOutcome;
72416
72574
  try {
72417
72575
  const completed = app.db.transaction((tx) => {
72418
- 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();
72419
72577
  const stillAuthoritative = latestSource && isAuthoritativeTrafficSource(tx, latestSource) && isSameBackfillSource(latestSource, sourceRow2, leaseOwner);
72420
72578
  if (stillAuthoritative) {
72421
72579
  enforceRawEventSampleRetention(tx, sourceRow2.id, finishedAt2);
@@ -72424,7 +72582,7 @@ async function runBackfillTaskHoldingLease(options, signal) {
72424
72582
  status: RunStatuses.failed,
72425
72583
  error: "Traffic source was deactivated or reconfigured during backfill",
72426
72584
  finishedAt: finishedAt2
72427
- }).where(eq103(runs.id, runId)).run();
72585
+ }).where(eq104(runs.id, runId)).run();
72428
72586
  return Boolean(stillAuthoritative);
72429
72587
  });
72430
72588
  emptyOutcome = completed ? { status: OutcomeStatuses.skipped, reasonCode: OutcomeReasonCodes.NO_DATA } : { status: OutcomeStatuses.failed, reasonCode: OutcomeReasonCodes.NOT_CONNECTED };
@@ -72456,13 +72614,13 @@ async function runBackfillTaskHoldingLease(options, signal) {
72456
72614
  const nextLastSyncedAt = Math.max(currentLastSyncedMs, windowEnd.getTime()) === windowEnd.getTime() ? windowEndIso : sourceRow2.lastSyncedAt;
72457
72615
  try {
72458
72616
  const commitOutcome = app.db.transaction((tx) => {
72459
- 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();
72460
72618
  if (latestSource?.sourceType === TrafficSourceTypes.wordpress) {
72461
72619
  tx.update(runs).set({
72462
72620
  status: RunStatuses.failed,
72463
72621
  error: "Generic WordPress replace backfill is unavailable because retained coverage is unproven.",
72464
72622
  finishedAt
72465
- }).where(eq103(runs.id, runId)).run();
72623
+ }).where(eq104(runs.id, runId)).run();
72466
72624
  return "wordpress-backfill-unsupported";
72467
72625
  }
72468
72626
  if (!latestSource || !isAuthoritativeTrafficSource(tx, latestSource) || !isSameBackfillSource(latestSource, sourceRow2, leaseOwner)) {
@@ -72470,7 +72628,7 @@ async function runBackfillTaskHoldingLease(options, signal) {
72470
72628
  status: RunStatuses.failed,
72471
72629
  error: "Traffic source was deactivated or reconfigured during backfill",
72472
72630
  finishedAt
72473
- }).where(eq103(runs.id, runId)).run();
72631
+ }).where(eq104(runs.id, runId)).run();
72474
72632
  return "source-inactive";
72475
72633
  }
72476
72634
  const rawSampleCutoff = enforceRawEventSampleRetention(
@@ -72480,14 +72638,14 @@ async function runBackfillTaskHoldingLease(options, signal) {
72480
72638
  );
72481
72639
  tx.delete(crawlerEventsHourly).where(
72482
72640
  and89(
72483
- eq103(crawlerEventsHourly.sourceId, sourceRow2.id),
72641
+ eq104(crawlerEventsHourly.sourceId, sourceRow2.id),
72484
72642
  gte27(crawlerEventsHourly.tsHour, windowStartIso),
72485
72643
  lte27(crawlerEventsHourly.tsHour, windowEndIso)
72486
72644
  )
72487
72645
  ).run();
72488
72646
  tx.delete(aiUserFetchEventsHourly).where(
72489
72647
  and89(
72490
- eq103(aiUserFetchEventsHourly.sourceId, sourceRow2.id),
72648
+ eq104(aiUserFetchEventsHourly.sourceId, sourceRow2.id),
72491
72649
  gte27(aiUserFetchEventsHourly.tsHour, windowStartIso),
72492
72650
  lte27(aiUserFetchEventsHourly.tsHour, windowEndIso)
72493
72651
  )
@@ -72495,21 +72653,21 @@ async function runBackfillTaskHoldingLease(options, signal) {
72495
72653
  clearLikelyFakeAgentHits(tx, { sourceId: sourceRow2.id, windowStart: windowStartIso, windowEnd: windowEndIso });
72496
72654
  tx.delete(aiReferralEventsHourly).where(
72497
72655
  and89(
72498
- eq103(aiReferralEventsHourly.sourceId, sourceRow2.id),
72656
+ eq104(aiReferralEventsHourly.sourceId, sourceRow2.id),
72499
72657
  gte27(aiReferralEventsHourly.tsHour, windowStartIso),
72500
72658
  lte27(aiReferralEventsHourly.tsHour, windowEndIso)
72501
72659
  )
72502
72660
  ).run();
72503
72661
  tx.delete(rawEventSamples).where(
72504
72662
  and89(
72505
- eq103(rawEventSamples.sourceId, sourceRow2.id),
72663
+ eq104(rawEventSamples.sourceId, sourceRow2.id),
72506
72664
  gte27(rawEventSamples.ts, windowStartIso),
72507
72665
  lte27(rawEventSamples.ts, windowEndIso)
72508
72666
  )
72509
72667
  ).run();
72510
72668
  tx.delete(unrecognizedAgentEventsHourly).where(
72511
72669
  and89(
72512
- eq103(unrecognizedAgentEventsHourly.sourceId, sourceRow2.id),
72670
+ eq104(unrecognizedAgentEventsHourly.sourceId, sourceRow2.id),
72513
72671
  gte27(unrecognizedAgentEventsHourly.tsHour, windowStartIso),
72514
72672
  lte27(unrecognizedAgentEventsHourly.tsHour, windowEndIso)
72515
72673
  )
@@ -72540,7 +72698,7 @@ async function runBackfillTaskHoldingLease(options, signal) {
72540
72698
  crawlerEventsHourly.status
72541
72699
  ],
72542
72700
  set: {
72543
- hits: sql47`${crawlerEventsHourly.hits} + ${bucket.hits}`,
72701
+ hits: sql48`${crawlerEventsHourly.hits} + ${bucket.hits}`,
72544
72702
  sampledUserAgent: bucket.sampledUserAgent,
72545
72703
  updatedAt: finishedAt
72546
72704
  }
@@ -72571,7 +72729,7 @@ async function runBackfillTaskHoldingLease(options, signal) {
72571
72729
  crawlerVerificationManifestsHourly.manifestId
72572
72730
  ],
72573
72731
  set: {
72574
- hits: sql47`${crawlerVerificationManifestsHourly.hits} + ${bucket.hits}`,
72732
+ hits: sql48`${crawlerVerificationManifestsHourly.hits} + ${bucket.hits}`,
72575
72733
  manifestJson: bucket.verificationManifest,
72576
72734
  updatedAt: finishedAt
72577
72735
  }
@@ -72604,7 +72762,7 @@ async function runBackfillTaskHoldingLease(options, signal) {
72604
72762
  aiUserFetchEventsHourly.status
72605
72763
  ],
72606
72764
  set: {
72607
- hits: sql47`${aiUserFetchEventsHourly.hits} + ${bucket.hits}`,
72765
+ hits: sql48`${aiUserFetchEventsHourly.hits} + ${bucket.hits}`,
72608
72766
  sampledUserAgent: bucket.sampledUserAgent,
72609
72767
  updatedAt: finishedAt
72610
72768
  }
@@ -72635,7 +72793,7 @@ async function runBackfillTaskHoldingLease(options, signal) {
72635
72793
  aiUserFetchVerificationManifestsHourly.manifestId
72636
72794
  ],
72637
72795
  set: {
72638
- hits: sql47`${aiUserFetchVerificationManifestsHourly.hits} + ${bucket.hits}`,
72796
+ hits: sql48`${aiUserFetchVerificationManifestsHourly.hits} + ${bucket.hits}`,
72639
72797
  manifestJson: bucket.verificationManifest,
72640
72798
  updatedAt: finishedAt
72641
72799
  }
@@ -72676,7 +72834,7 @@ async function runBackfillTaskHoldingLease(options, signal) {
72676
72834
  }
72677
72835
  })();
72678
72836
  tx.insert(rawEventSamples).values({
72679
- id: crypto60.randomUUID(),
72837
+ id: crypto61.randomUUID(),
72680
72838
  projectId: project.id,
72681
72839
  sourceId: sourceRow2.id,
72682
72840
  ts: sampleTimestamp,
@@ -72712,13 +72870,13 @@ async function runBackfillTaskHoldingLease(options, signal) {
72712
72870
  const skipRecovered = sourceRow2.sourceType !== TrafficSourceTypes.wordpress && Number.isFinite(recordedSkipMs) && windowStart.getTime() <= recordedSkipMs;
72713
72871
  let olderCountUntil = latestSource.aiReferralOlderCountUntil;
72714
72872
  if (olderCountUntil !== null) {
72715
- const ruleChange = tx.get(sql47`
72873
+ const ruleChange = tx.get(sql48`
72716
72874
  SELECT strftime('%Y-%m-%dT%H:%M:%fZ', applied_at) AS appliedAt
72717
72875
  FROM _migrations WHERE version = 207
72718
72876
  `);
72719
72877
  if (ruleChange?.appliedAt) {
72720
72878
  const olderReferral = tx.select({ sourceId: aiReferralEventsHourly.sourceId }).from(aiReferralEventsHourly).where(and89(
72721
- eq103(aiReferralEventsHourly.sourceId, sourceRow2.id),
72879
+ eq104(aiReferralEventsHourly.sourceId, sourceRow2.id),
72722
72880
  lt20(aiReferralEventsHourly.createdAt, ruleChange.appliedAt)
72723
72881
  )).limit(1).get();
72724
72882
  if (!olderReferral) olderCountUntil = null;
@@ -72739,8 +72897,8 @@ async function runBackfillTaskHoldingLease(options, signal) {
72739
72897
  aiUserFetchOlderCountUntil: userFetchOlderCountUntil,
72740
72898
  ...skipRecovered ? { skippedThroughAt: null } : {},
72741
72899
  updatedAt: finishedAt
72742
- }).where(eq103(trafficSources.id, sourceRow2.id)).run();
72743
- 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();
72744
72902
  return "committed";
72745
72903
  });
72746
72904
  reportBackfill(commitOutcome === "committed" ? {
@@ -72914,8 +73072,8 @@ async function trafficRoutes(app, opts) {
72914
73072
  };
72915
73073
  const fallbackName = displayName ?? `Cloud Run \xB7 ${gcpProjectId}${serviceName ? ` / ${serviceName}` : ""}`;
72916
73074
  const { sourceRow: sourceRow2, scheduleChanged } = app.db.transaction((tx) => {
72917
- const activeSource = tx.select().from(trafficSources).where(eq103(trafficSources.projectId, project.id)).all().find((row) => row.sourceType === TrafficSourceTypes["cloud-run"] && row.status !== TrafficSourceStatuses.archived);
72918
- 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();
72919
73077
  const sourceStatus = trafficConnectStatus(tx, project.id, activeSource);
72920
73078
  if (activeSource) {
72921
73079
  tx.update(trafficSources).set({
@@ -72924,7 +73082,7 @@ async function trafficRoutes(app, opts) {
72924
73082
  lastError: null,
72925
73083
  configJson: config,
72926
73084
  updatedAt: now
72927
- }).where(eq103(trafficSources.id, sourceId)).run();
73085
+ }).where(eq104(trafficSources.id, sourceId)).run();
72928
73086
  } else {
72929
73087
  tx.insert(trafficSources).values({
72930
73088
  id: sourceId,
@@ -72950,7 +73108,7 @@ async function trafficRoutes(app, opts) {
72950
73108
  entityId: sourceId
72951
73109
  });
72952
73110
  return {
72953
- sourceRow: tx.select().from(trafficSources).where(eq103(trafficSources.id, sourceId)).get(),
73111
+ sourceRow: tx.select().from(trafficSources).where(eq104(trafficSources.id, sourceId)).get(),
72954
73112
  scheduleChanged: scheduleBinding.changed
72955
73113
  };
72956
73114
  }, { behavior: "immediate" });
@@ -73005,9 +73163,9 @@ async function trafficRoutes(app, opts) {
73005
73163
  const config = { baseUrl, username };
73006
73164
  const fallbackName = displayName ?? `WordPress \xB7 ${new URL(baseUrl).host}`;
73007
73165
  const { sourceRow: sourceRow2, scheduleChanged } = app.db.transaction((tx) => {
73008
- 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);
73009
73167
  const endpointChanged = activeSource !== void 0 && wordpressBaseUrlIdentity(activeSource.configJson.baseUrl) !== wordpressBaseUrlIdentity(baseUrl);
73010
- const sourceId = endpointChanged ? crypto60.randomUUID() : activeSource?.id ?? crypto60.randomUUID();
73168
+ const sourceId = endpointChanged ? crypto61.randomUUID() : activeSource?.id ?? crypto61.randomUUID();
73011
73169
  const sourceStatus = trafficConnectStatus(tx, project.id, activeSource);
73012
73170
  if (activeSource && !endpointChanged) {
73013
73171
  tx.update(trafficSources).set({
@@ -73016,14 +73174,14 @@ async function trafficRoutes(app, opts) {
73016
73174
  lastError: null,
73017
73175
  configJson: config,
73018
73176
  updatedAt: now
73019
- }).where(eq103(trafficSources.id, sourceId)).run();
73177
+ }).where(eq104(trafficSources.id, sourceId)).run();
73020
73178
  } else {
73021
73179
  if (activeSource) {
73022
73180
  tx.update(trafficSources).set({
73023
73181
  status: TrafficSourceStatuses.archived,
73024
73182
  archivedAt: now,
73025
73183
  updatedAt: now
73026
- }).where(eq103(trafficSources.id, activeSource.id)).run();
73184
+ }).where(eq104(trafficSources.id, activeSource.id)).run();
73027
73185
  }
73028
73186
  tx.insert(trafficSources).values({
73029
73187
  id: sourceId,
@@ -73049,7 +73207,7 @@ async function trafficRoutes(app, opts) {
73049
73207
  entityId: sourceId
73050
73208
  });
73051
73209
  return {
73052
- sourceRow: tx.select().from(trafficSources).where(eq103(trafficSources.id, sourceId)).get(),
73210
+ sourceRow: tx.select().from(trafficSources).where(eq104(trafficSources.id, sourceId)).get(),
73053
73211
  scheduleChanged: scheduleBinding.changed
73054
73212
  };
73055
73213
  }, { behavior: "immediate" });
@@ -73106,7 +73264,7 @@ async function trafficRoutes(app, opts) {
73106
73264
  const config = { projectId, teamId, environment };
73107
73265
  const fallbackName = displayName ?? `Vercel \xB7 ${projectId}`;
73108
73266
  const { sourceRow: sourceRow2, scheduleChanged } = app.db.transaction((tx) => {
73109
- 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);
73110
73268
  const sourceStatus = trafficConnectStatus(tx, project.id, activeSource);
73111
73269
  let row;
73112
73270
  if (activeSource) {
@@ -73116,10 +73274,10 @@ async function trafficRoutes(app, opts) {
73116
73274
  lastError: null,
73117
73275
  configJson: config,
73118
73276
  updatedAt: now
73119
- }).where(eq103(trafficSources.id, activeSource.id)).run();
73120
- 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();
73121
73279
  } else {
73122
- const newId = crypto60.randomUUID();
73280
+ const newId = crypto61.randomUUID();
73123
73281
  tx.insert(trafficSources).values({
73124
73282
  id: newId,
73125
73283
  projectId: project.id,
@@ -73142,7 +73300,7 @@ async function trafficRoutes(app, opts) {
73142
73300
  createdAt: now,
73143
73301
  updatedAt: now
73144
73302
  }).run();
73145
- row = tx.select().from(trafficSources).where(eq103(trafficSources.id, newId)).get();
73303
+ row = tx.select().from(trafficSources).where(eq104(trafficSources.id, newId)).get();
73146
73304
  }
73147
73305
  const scheduleBinding = sourceStatus === TrafficSourceStatuses.connected ? bindTrafficSyncSchedule(tx, project.id, row.id, now) : { changed: false, created: false };
73148
73306
  writeAuditLog(tx, {
@@ -73186,10 +73344,10 @@ async function trafficRoutes(app, opts) {
73186
73344
  const { displayName: displayName2, zoneId: zoneId2, accountId: accountId2, queueId, queueName, retentionSeconds, apiToken } = parsed.data;
73187
73345
  const workerRouteHost2 = resolveCloudflareWorkerRouteHost(project.canonicalDomain);
73188
73346
  const now2 = (/* @__PURE__ */ new Date()).toISOString();
73189
- 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);
73190
73348
  const sameModeSource = cloudflareSources.find((row) => parseQueuePullCloudflareSourceConfig(row.configJson));
73191
73349
  if (sameModeSource) attempt.update({ action: "reauth" });
73192
- const sourceId2 = sameModeSource?.id ?? crypto60.randomUUID();
73350
+ const sourceId2 = sameModeSource?.id ?? crypto61.randomUUID();
73193
73351
  const previousCredential2 = credentialStore.getConnectionBySourceId(sourceId2);
73194
73352
  const forwardPageViews2 = parsed.data.forwardPageViews ?? (sameModeSource ? parseQueuePullCloudflareSourceConfig(sameModeSource.configJson)?.forwardPageViews : void 0) ?? false;
73195
73353
  const workerVersion2 = cloudflareWorkerVersionFor({ forwardPageViews: forwardPageViews2 });
@@ -73240,7 +73398,7 @@ async function trafficRoutes(app, opts) {
73240
73398
  let scheduleChanged = false;
73241
73399
  try {
73242
73400
  const result = app.db.transaction((tx) => {
73243
- 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);
73244
73402
  if ((currentSameModeSource?.id ?? null) !== (sameModeSource?.id ?? null)) {
73245
73403
  throw operationInProgress("Cloudflare Queue source changed during connect; retry");
73246
73404
  }
@@ -73258,7 +73416,7 @@ async function trafficRoutes(app, opts) {
73258
73416
  queueBacklogObservedAt: null
73259
73417
  } : {},
73260
73418
  updatedAt: now2
73261
- }).where(eq103(trafficSources.id, sourceId2)).run();
73419
+ }).where(eq104(trafficSources.id, sourceId2)).run();
73262
73420
  } else {
73263
73421
  tx.insert(trafficSources).values({
73264
73422
  id: sourceId2,
@@ -73278,7 +73436,7 @@ async function trafficRoutes(app, opts) {
73278
73436
  }
73279
73437
  const changed = status === TrafficSourceStatuses.connected ? bindTrafficSyncSchedule(tx, project.id, sourceId2, now2).changed : false;
73280
73438
  return {
73281
- row: tx.select().from(trafficSources).where(eq103(trafficSources.id, sourceId2)).get(),
73439
+ row: tx.select().from(trafficSources).where(eq104(trafficSources.id, sourceId2)).get(),
73282
73440
  scheduleChanged: changed
73283
73441
  };
73284
73442
  }, { behavior: "immediate" });
@@ -73328,9 +73486,9 @@ async function trafficRoutes(app, opts) {
73328
73486
  const { deliveryMode, displayName, zoneId, accountId } = parsed.data;
73329
73487
  const workerRouteHost = resolveCloudflareWorkerRouteHost(project.canonicalDomain);
73330
73488
  const now = (/* @__PURE__ */ new Date()).toISOString();
73331
- 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);
73332
73490
  if (activeSource) attempt.update({ action: "reauth" });
73333
- const sourceId = activeSource?.id ?? crypto60.randomUUID();
73491
+ const sourceId = activeSource?.id ?? crypto61.randomUUID();
73334
73492
  const parsedActiveConfig = activeSource ? parseDirectPushCloudflareSourceConfig(activeSource.configJson) : null;
73335
73493
  if (activeSource && !parsedActiveConfig) {
73336
73494
  throw validationError("Existing Cloudflare source is not configured for direct-push delivery");
@@ -73347,8 +73505,8 @@ async function trafficRoutes(app, opts) {
73347
73505
  const effectiveZoneId = zoneId ?? previousZoneId;
73348
73506
  const effectiveAccountId = accountId ?? previousAccountId;
73349
73507
  const forwardPageViews = parsed.data.forwardPageViews ?? parsedActiveConfig?.forwardPageViews ?? false;
73350
- const bearerToken = reusableCredential?.bearerToken ?? `cnry_cfw_${crypto60.randomBytes(32).toString("hex")}`;
73351
- 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");
73352
73510
  const ingestTokenHash = sha256Hex3(bearerToken);
73353
73511
  const ingestUrl = opts.cloudflareTrafficIngestUrl.replace("{name}", encodeURIComponent(project.name));
73354
73512
  assertCloudflareIngestUrlIsPublicHttps(ingestUrl);
@@ -73396,7 +73554,7 @@ async function trafficRoutes(app, opts) {
73396
73554
  let scheduleRemoved = false;
73397
73555
  try {
73398
73556
  const result = app.db.transaction((tx) => {
73399
- 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);
73400
73558
  if ((currentActiveSource?.id ?? null) !== (activeSource?.id ?? null)) {
73401
73559
  throw operationInProgress("Cloudflare direct-push source changed during connect; retry");
73402
73560
  }
@@ -73410,8 +73568,8 @@ async function trafficRoutes(app, opts) {
73410
73568
  configJson: config,
73411
73569
  ingestTokenHash,
73412
73570
  updatedAt: now
73413
- }).where(eq103(trafficSources.id, currentActiveSource.id)).run();
73414
- 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();
73415
73573
  } else {
73416
73574
  tx.insert(trafficSources).values({
73417
73575
  id: sourceId,
@@ -73431,16 +73589,16 @@ async function trafficRoutes(app, opts) {
73431
73589
  createdAt: now,
73432
73590
  updatedAt: now
73433
73591
  }).run();
73434
- row = tx.select().from(trafficSources).where(eq103(trafficSources.id, sourceId)).get();
73592
+ row = tx.select().from(trafficSources).where(eq104(trafficSources.id, sourceId)).get();
73435
73593
  }
73436
73594
  let removed = false;
73437
73595
  if (row.status === TrafficSourceStatuses.connected) {
73438
73596
  const schedule = tx.select().from(schedules).where(and89(
73439
- eq103(schedules.projectId, project.id),
73440
- eq103(schedules.kind, SchedulableRunKinds["traffic-sync"])
73597
+ eq104(schedules.projectId, project.id),
73598
+ eq104(schedules.kind, SchedulableRunKinds["traffic-sync"])
73441
73599
  )).get();
73442
73600
  if (schedule) {
73443
- tx.delete(schedules).where(eq103(schedules.id, schedule.id)).run();
73601
+ tx.delete(schedules).where(eq104(schedules.id, schedule.id)).run();
73444
73602
  removed = true;
73445
73603
  }
73446
73604
  }
@@ -73496,47 +73654,47 @@ async function trafficRoutes(app, opts) {
73496
73654
  };
73497
73655
  }));
73498
73656
  app.post("/projects/:name/traffic/sources/:id/activate", connectionRoute(app, (request) => {
73499
- 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();
73500
73658
  const integration = source ? TRAFFIC_SOURCE_INTEGRATIONS[source.sourceType] : void 0;
73501
73659
  return integration ? { integration, action: "select" } : void 0;
73502
73660
  }, async (request) => {
73503
73661
  const project = resolveProject(app.db, request.params.name);
73504
73662
  const now = (/* @__PURE__ */ new Date()).toISOString();
73505
73663
  const result = app.db.transaction((tx) => {
73506
- 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();
73507
73665
  if (!target || target.projectId !== project.id || target.status === TrafficSourceStatuses.archived) {
73508
73666
  throw notFound("Traffic source", request.params.id);
73509
73667
  }
73510
73668
  const { usesPullSchedule } = validateTrafficSourceCredential(target, project.name);
73511
- 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();
73512
73670
  for (const sibling of siblings) {
73513
73671
  if (sibling.id === target.id || sibling.status === TrafficSourceStatuses.archived) continue;
73514
73672
  tx.update(trafficSources).set({
73515
73673
  status: TrafficSourceStatuses.paused,
73516
73674
  updatedAt: now
73517
- }).where(eq103(trafficSources.id, sibling.id)).run();
73675
+ }).where(eq104(trafficSources.id, sibling.id)).run();
73518
73676
  }
73519
73677
  tx.update(trafficSources).set({
73520
73678
  status: TrafficSourceStatuses.connected,
73521
73679
  lastError: null,
73522
73680
  archivedAt: null,
73523
73681
  updatedAt: now
73524
- }).where(eq103(trafficSources.id, target.id)).run();
73682
+ }).where(eq104(trafficSources.id, target.id)).run();
73525
73683
  let scheduleAction = null;
73526
73684
  if (usesPullSchedule) {
73527
73685
  bindTrafficSyncSchedule(tx, project.id, target.id, now);
73528
73686
  scheduleAction = "upsert";
73529
73687
  } else {
73530
73688
  const schedule = tx.select().from(schedules).where(and89(
73531
- eq103(schedules.projectId, project.id),
73532
- eq103(schedules.kind, SchedulableRunKinds["traffic-sync"])
73689
+ eq104(schedules.projectId, project.id),
73690
+ eq104(schedules.kind, SchedulableRunKinds["traffic-sync"])
73533
73691
  )).get();
73534
73692
  if (schedule) {
73535
- tx.delete(schedules).where(eq103(schedules.id, schedule.id)).run();
73693
+ tx.delete(schedules).where(eq104(schedules.id, schedule.id)).run();
73536
73694
  scheduleAction = "delete";
73537
73695
  }
73538
73696
  }
73539
- 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();
73540
73698
  writeAuditLog(tx, {
73541
73699
  projectId: project.id,
73542
73700
  actor: "api",
@@ -73604,7 +73762,7 @@ async function trafficRoutes(app, opts) {
73604
73762
  }
73605
73763
  const { bearerHash, credential } = authenticated;
73606
73764
  const sourceId = credential.sourceId;
73607
- 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();
73608
73766
  if (!sourceRow2 || sourceRow2.sourceType !== TrafficSourceTypes.cloudflare || sourceRow2.status !== TrafficSourceStatuses.connected || !parseDirectPushCloudflareSourceConfig(sourceRow2.configJson) || !timingSafeEqualHex(bearerHash, sourceRow2.ingestTokenHash)) {
73609
73767
  throw authRequired();
73610
73768
  }
@@ -73684,7 +73842,7 @@ async function trafficRoutes(app, opts) {
73684
73842
  });
73685
73843
  app.post("/projects/:name/traffic/sources/:id/sync", async (request) => {
73686
73844
  const project = resolveProject(app.db, request.params.name);
73687
- 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();
73688
73846
  if (!initialSourceRow || initialSourceRow.projectId !== project.id) {
73689
73847
  throw notFound("Traffic source", request.params.id);
73690
73848
  }
@@ -73704,7 +73862,7 @@ async function trafficRoutes(app, opts) {
73704
73862
  apiToken: credential.apiToken
73705
73863
  };
73706
73864
  const now = (/* @__PURE__ */ new Date()).toISOString();
73707
- const leaseOwner = crypto60.randomUUID();
73865
+ const leaseOwner = crypto61.randomUUID();
73708
73866
  if (!tryClaimTrafficSyncLease({
73709
73867
  db: app.db,
73710
73868
  sourceId: sourceRow2.id,
@@ -73714,7 +73872,7 @@ async function trafficRoutes(app, opts) {
73714
73872
  })) {
73715
73873
  throw operationInProgress("Cloudflare Queue source sync is already in progress", { sourceId: sourceRow2.id });
73716
73874
  }
73717
- const runId = crypto60.randomUUID();
73875
+ const runId = crypto61.randomUUID();
73718
73876
  const startedAt = (/* @__PURE__ */ new Date()).toISOString();
73719
73877
  const startedMs = Date.now();
73720
73878
  let acceptedEvents = 0;
@@ -73758,7 +73916,7 @@ async function trafficRoutes(app, opts) {
73758
73916
  });
73759
73917
  const finishSync = (status, error, stopReason) => {
73760
73918
  const queueDrain = drainSummary(stopReason);
73761
- 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();
73762
73920
  writeAuditLog(app.db, {
73763
73921
  projectId: project.id,
73764
73922
  actor: "api",
@@ -73935,7 +74093,7 @@ async function trafficRoutes(app, opts) {
73935
74093
  now: (/* @__PURE__ */ new Date()).toISOString(),
73936
74094
  ttlMs: CLOUDFLARE_QUEUE_SYNC_LEASE_TTL_MS
73937
74095
  })) throw new Error("Queue sync lease was lost before acknowledgement");
73938
- 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();
73939
74097
  if (!latestSource || latestSource.projectId !== project.id || latestSource.status !== TrafficSourceStatuses.connected || latestSource.syncLeaseOwner !== leaseOwner || !isDeepStrictEqual(latestSource.configJson, sourceRow2.configJson)) {
73940
74098
  throw validationError("Cloudflare Queue source was reconfigured before acknowledgement");
73941
74099
  }
@@ -74025,13 +74183,13 @@ async function trafficRoutes(app, opts) {
74025
74183
  error: safeError,
74026
74184
  finishedAt: failedAt,
74027
74185
  syncSummary: drainSummary(CloudflareQueueDrainStopReasons.error)
74028
- }).where(eq103(runs.id, runId)).run();
74029
- 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();
74030
74188
  if (latestSource && latestSource.status === TrafficSourceStatuses.connected && latestSource.syncLeaseOwner === leaseOwner && isDeepStrictEqual(latestSource.configJson, sourceRow2.configJson)) {
74031
74189
  tx.update(trafficSources).set({ lastError: safeError, updatedAt: failedAt }).where(and89(
74032
- eq103(trafficSources.id, sourceRow2.id),
74033
- eq103(trafficSources.status, TrafficSourceStatuses.connected),
74034
- eq103(trafficSources.syncLeaseOwner, leaseOwner)
74190
+ eq104(trafficSources.id, sourceRow2.id),
74191
+ eq104(trafficSources.status, TrafficSourceStatuses.connected),
74192
+ eq104(trafficSources.syncLeaseOwner, leaseOwner)
74035
74193
  )).run();
74036
74194
  }
74037
74195
  });
@@ -74050,12 +74208,12 @@ async function trafficRoutes(app, opts) {
74050
74208
  `Sync for source type "${sourceRow2.sourceType}" is not implemented yet \u2014 only cloud-run, wordpress, and vercel are supported in v1.`
74051
74209
  );
74052
74210
  }
74053
- 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);
74054
74212
  if (sourceRow2.status === TrafficSourceStatuses.paused || sourceRow2.status === TrafficSourceStatuses.archived || hasConnectedSibling) {
74055
74213
  throw validationError("Traffic source must be active before it can sync");
74056
74214
  }
74057
74215
  const isWordpressSource = sourceRow2.sourceType === TrafficSourceTypes.wordpress;
74058
- const syncLeaseOwner = crypto60.randomUUID();
74216
+ const syncLeaseOwner = crypto61.randomUUID();
74059
74217
  if (!tryClaimTrafficSyncLease({
74060
74218
  db: app.db,
74061
74219
  sourceId: sourceRow2.id,
@@ -74073,7 +74231,7 @@ async function trafficRoutes(app, opts) {
74073
74231
  let windowEnd = syncWindowEnd;
74074
74232
  const startedAt = syncWindowEnd.toISOString();
74075
74233
  const syncStartedAtMs = syncWindowEnd.getTime();
74076
- const runId = crypto60.randomUUID();
74234
+ const runId = crypto61.randomUUID();
74077
74235
  app.db.insert(runs).values({
74078
74236
  id: runId,
74079
74237
  projectId: project.id,
@@ -74087,10 +74245,10 @@ async function trafficRoutes(app, opts) {
74087
74245
  const markFailed = (msg, errorCode2) => {
74088
74246
  const failedAt = (/* @__PURE__ */ new Date()).toISOString();
74089
74247
  app.db.transaction((tx) => {
74090
- tx.update(runs).set({ status: RunStatuses.failed, error: msg, finishedAt: failedAt }).where(eq103(runs.id, runId)).run();
74091
- 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();
74092
74250
  if (latestSource?.status === TrafficSourceStatuses.connected && isSameTrafficSourceGeneration(latestSource, sourceRow2) && latestSource.syncLeaseOwner === syncLeaseOwner) {
74093
- 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();
74094
74252
  }
74095
74253
  });
74096
74254
  try {
@@ -74184,7 +74342,7 @@ async function trafficRoutes(app, opts) {
74184
74342
  }
74185
74343
  const credential = credentialStore.getConnection(project.name);
74186
74344
  if (!credential) {
74187
- app.db.delete(runs).where(eq103(runs.id, runId)).run();
74345
+ app.db.delete(runs).where(eq104(runs.id, runId)).run();
74188
74346
  throw validationError(
74189
74347
  `No WordPress credential found for project "${project.name}". Run "canonry traffic connect wordpress" first.`
74190
74348
  );
@@ -74218,14 +74376,14 @@ async function trafficRoutes(app, opts) {
74218
74376
  const windowEndIso2 = windowEnd.toISOString();
74219
74377
  const reservedAt = (/* @__PURE__ */ new Date()).toISOString();
74220
74378
  const reservedSource = app.db.transaction((tx) => {
74221
- 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();
74222
74380
  if (!latestSource || !isAuthoritativeTrafficSource(tx, latestSource) || !isSameTrafficSourceGeneration(latestSource, sourceRow2) || latestSource.syncLeaseOwner !== syncLeaseOwner || latestSource.lastCursor || latestSource.wordpressPendingUntil) return void 0;
74223
74381
  tx.update(trafficSources).set({
74224
74382
  lastSyncedAt: windowStartIso2,
74225
74383
  wordpressPendingUntil: windowEndIso2,
74226
74384
  updatedAt: reservedAt
74227
- }).where(eq103(trafficSources.id, sourceRow2.id)).run();
74228
- 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();
74229
74387
  }, { behavior: "immediate" });
74230
74388
  if (!reservedSource) {
74231
74389
  const message = "Traffic source changed while reserving the WordPress sync window; retry the sync.";
@@ -74285,12 +74443,12 @@ async function trafficRoutes(app, opts) {
74285
74443
  auditAction = "traffic.vercel.synced";
74286
74444
  const credentialStore = opts.vercelTrafficCredentialStore;
74287
74445
  if (!credentialStore) {
74288
- app.db.delete(runs).where(eq103(runs.id, runId)).run();
74446
+ app.db.delete(runs).where(eq104(runs.id, runId)).run();
74289
74447
  throw validationError("Vercel traffic credential storage is not configured for this deployment");
74290
74448
  }
74291
74449
  const credential = credentialStore.getConnection(project.name);
74292
74450
  if (!credential) {
74293
- app.db.delete(runs).where(eq103(runs.id, runId)).run();
74451
+ app.db.delete(runs).where(eq104(runs.id, runId)).run();
74294
74452
  throw validationError(
74295
74453
  `No Vercel credential found for project "${project.name}". Run "canonry traffic connect vercel" first.`
74296
74454
  );
@@ -74308,7 +74466,7 @@ async function trafficRoutes(app, opts) {
74308
74466
  if (cappedStartMs > clampedStartMs) {
74309
74467
  const previousSkip = sourceRow2.skippedThroughAt ? Date.parse(sourceRow2.skippedThroughAt) : Number.NaN;
74310
74468
  const skippedThrough = Number.isFinite(previousSkip) ? new Date(Math.max(previousSkip, cappedStartMs)) : new Date(cappedStartMs);
74311
- 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();
74312
74470
  request.log.warn(
74313
74471
  {
74314
74472
  sourceId: sourceRow2.id,
@@ -74403,15 +74561,15 @@ async function trafficRoutes(app, opts) {
74403
74561
  throw providerError(`WordPress sync failed: ${msg}`);
74404
74562
  }
74405
74563
  const commitOutcome = app.db.transaction((tx) => {
74406
- const latestRow = tx.select().from(trafficSources).where(eq103(trafficSources.id, sourceRow2.id)).get();
74407
- 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);
74408
74566
  if (!latestRow || latestRow.status !== TrafficSourceStatuses.connected && latestRow.status !== TrafficSourceStatuses.error || latestHasConnectedSibling || latestRow.syncLeaseOwner !== syncLeaseOwner || !isSameTrafficSourceGeneration(latestRow, sourceRow2)) {
74409
74567
  const abortedAt = (/* @__PURE__ */ new Date()).toISOString();
74410
74568
  tx.update(runs).set({
74411
74569
  status: RunStatuses.failed,
74412
74570
  error: "Traffic source was deactivated or reconfigured during sync",
74413
74571
  finishedAt: abortedAt
74414
- }).where(eq103(runs.id, runId)).run();
74572
+ }).where(eq104(runs.id, runId)).run();
74415
74573
  return "source-inactive";
74416
74574
  }
74417
74575
  const previousIds = latestRow.lastEventIds ?? [];
@@ -74476,7 +74634,7 @@ async function trafficRoutes(app, opts) {
74476
74634
  crawlerEventsHourly.status
74477
74635
  ],
74478
74636
  set: {
74479
- hits: sql47`${crawlerEventsHourly.hits} + ${bucket.hits}`,
74637
+ hits: sql48`${crawlerEventsHourly.hits} + ${bucket.hits}`,
74480
74638
  sampledUserAgent: bucket.sampledUserAgent,
74481
74639
  updatedAt: finishedAt
74482
74640
  }
@@ -74507,7 +74665,7 @@ async function trafficRoutes(app, opts) {
74507
74665
  crawlerVerificationManifestsHourly.manifestId
74508
74666
  ],
74509
74667
  set: {
74510
- hits: sql47`${crawlerVerificationManifestsHourly.hits} + ${bucket.hits}`,
74668
+ hits: sql48`${crawlerVerificationManifestsHourly.hits} + ${bucket.hits}`,
74511
74669
  manifestJson: bucket.verificationManifest,
74512
74670
  updatedAt: finishedAt
74513
74671
  }
@@ -74541,7 +74699,7 @@ async function trafficRoutes(app, opts) {
74541
74699
  aiUserFetchEventsHourly.status
74542
74700
  ],
74543
74701
  set: {
74544
- hits: sql47`${aiUserFetchEventsHourly.hits} + ${bucket.hits}`,
74702
+ hits: sql48`${aiUserFetchEventsHourly.hits} + ${bucket.hits}`,
74545
74703
  sampledUserAgent: bucket.sampledUserAgent,
74546
74704
  updatedAt: finishedAt
74547
74705
  }
@@ -74572,7 +74730,7 @@ async function trafficRoutes(app, opts) {
74572
74730
  aiUserFetchVerificationManifestsHourly.manifestId
74573
74731
  ],
74574
74732
  set: {
74575
- hits: sql47`${aiUserFetchVerificationManifestsHourly.hits} + ${bucket.hits}`,
74733
+ hits: sql48`${aiUserFetchVerificationManifestsHourly.hits} + ${bucket.hits}`,
74576
74734
  manifestJson: bucket.verificationManifest,
74577
74735
  updatedAt: finishedAt
74578
74736
  }
@@ -74614,9 +74772,9 @@ async function trafficRoutes(app, opts) {
74614
74772
  // colliding bucket adds its paid and organic arrivals to the ones
74615
74773
  // already there rather than overwriting a single label.
74616
74774
  set: {
74617
- sessionsOrHits: sql47`${aiReferralEventsHourly.sessionsOrHits} + ${bucket.hits}`,
74618
- paidSessionsOrHits: sql47`${aiReferralEventsHourly.paidSessionsOrHits} + ${bucket.paidHits}`,
74619
- 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}`,
74620
74778
  updatedAt: finishedAt
74621
74779
  }
74622
74780
  }).run();
@@ -74636,7 +74794,7 @@ async function trafficRoutes(app, opts) {
74636
74794
  }
74637
74795
  })();
74638
74796
  tx.insert(rawEventSamples).values({
74639
- id: crypto60.randomUUID(),
74797
+ id: crypto61.randomUUID(),
74640
74798
  projectId: project.id,
74641
74799
  sourceId: sourceRow2.id,
74642
74800
  ts: sampleTimestamp,
@@ -74698,8 +74856,8 @@ async function trafficRoutes(app, opts) {
74698
74856
  sourceUpdate.lastCursor = nextCursor ?? null;
74699
74857
  sourceUpdate.wordpressPendingUntil = nextCursor ? windowEnd.toISOString() : null;
74700
74858
  }
74701
- tx.update(trafficSources).set(sourceUpdate).where(eq103(trafficSources.id, sourceRow2.id)).run();
74702
- 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();
74703
74861
  return "committed";
74704
74862
  }, { behavior: "immediate" });
74705
74863
  if (commitOutcome === "source-inactive") {
@@ -74770,7 +74928,7 @@ async function trafficRoutes(app, opts) {
74770
74928
  });
74771
74929
  app.post("/projects/:name/traffic/sources/:id/backfill", async (request) => withFeatureOutcome(app, { feature: "server_traffic", operation: "backfill" }, async (recordOutcome) => {
74772
74930
  const project = resolveProject(app.db, request.params.name);
74773
- 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();
74774
74932
  if (!sourceRow2 || sourceRow2.projectId !== project.id) {
74775
74933
  throw notFound("Traffic source", request.params.id);
74776
74934
  }
@@ -74882,8 +75040,8 @@ async function trafficRoutes(app, opts) {
74882
75040
  };
74883
75041
  }
74884
75042
  const startedAt = windowEnd.toISOString();
74885
- const runId = crypto60.randomUUID();
74886
- const leaseOwner = crypto60.randomUUID();
75043
+ const runId = crypto61.randomUUID();
75044
+ const leaseOwner = crypto61.randomUUID();
74887
75045
  if (!tryClaimTrafficSyncLease({
74888
75046
  db: app.db,
74889
75047
  sourceId: sourceRow2.id,
@@ -74895,7 +75053,7 @@ async function trafficRoutes(app, opts) {
74895
75053
  }
74896
75054
  try {
74897
75055
  app.db.transaction((tx) => {
74898
- 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();
74899
75057
  if (!latestSource || !isAuthoritativeTrafficSource(tx, latestSource) || !isSameTrafficSourceGeneration(latestSource, sourceRow2)) {
74900
75058
  throw validationError("Traffic source must remain active and unchanged before it can backfill");
74901
75059
  }
@@ -74943,10 +75101,10 @@ async function trafficRoutes(app, opts) {
74943
75101
  function buildSourceDetail(projectId, row, since) {
74944
75102
  const crawlerPathRows = app.db.select({
74945
75103
  pathNormalized: crawlerEventsHourly.pathNormalized,
74946
- hits: sql47`COALESCE(SUM(${crawlerEventsHourly.hits}), 0)`
75104
+ hits: sql48`COALESCE(SUM(${crawlerEventsHourly.hits}), 0)`
74947
75105
  }).from(crawlerEventsHourly).where(
74948
75106
  and89(
74949
- eq103(crawlerEventsHourly.sourceId, row.id),
75107
+ eq104(crawlerEventsHourly.sourceId, row.id),
74950
75108
  gte27(crawlerEventsHourly.tsHour, since)
74951
75109
  )
74952
75110
  ).groupBy(crawlerEventsHourly.pathNormalized).all();
@@ -74954,41 +75112,41 @@ async function trafficRoutes(app, opts) {
74954
75112
  crawlerPathRows.map((r) => ({ pathNormalized: r.pathNormalized, hits: Number(r.hits) }))
74955
75113
  );
74956
75114
  const crawlerTotal = crawlerSegments.content + crawlerSegments.sitemap + crawlerSegments.robots + crawlerSegments.asset + crawlerSegments.other;
74957
- 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(
74958
75116
  and89(
74959
- eq103(aiUserFetchEventsHourly.sourceId, row.id),
75117
+ eq104(aiUserFetchEventsHourly.sourceId, row.id),
74960
75118
  gte27(aiUserFetchEventsHourly.tsHour, since)
74961
75119
  )
74962
75120
  ).get();
74963
- 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(
74964
75122
  and89(
74965
- eq103(aiUserFetchLikelyFakeHourly.sourceId, row.id),
75123
+ eq104(aiUserFetchLikelyFakeHourly.sourceId, row.id),
74966
75124
  gte27(aiUserFetchLikelyFakeHourly.tsHour, since)
74967
75125
  )
74968
75126
  ).get();
74969
75127
  const aiTotals = app.db.select({
74970
- total: sql47`COALESCE(SUM(${aiReferralEventsHourly.sessionsOrHits}), 0)`,
74971
- nonhop: sql47`COALESCE(SUM(CASE WHEN ${referralLandedCondition()} THEN ${aiReferralEventsHourly.sessionsOrHits} ELSE 0 END), 0)`,
74972
- 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)`
74973
75131
  }).from(aiReferralEventsHourly).where(
74974
75132
  and89(
74975
- eq103(aiReferralEventsHourly.sourceId, row.id),
75133
+ eq104(aiReferralEventsHourly.sourceId, row.id),
74976
75134
  gte27(aiReferralEventsHourly.tsHour, since)
74977
75135
  )
74978
75136
  ).get();
74979
- const sampleTotals = app.db.select({ total: sql47`COUNT(*)` }).from(rawEventSamples).where(
75137
+ const sampleTotals = app.db.select({ total: sql48`COUNT(*)` }).from(rawEventSamples).where(
74980
75138
  and89(
74981
- eq103(rawEventSamples.sourceId, row.id),
75139
+ eq104(rawEventSamples.sourceId, row.id),
74982
75140
  gte27(rawEventSamples.ts, since)
74983
75141
  )
74984
75142
  ).get();
74985
75143
  const latestRun2 = app.db.select().from(runs).where(
74986
75144
  and89(
74987
- eq103(runs.projectId, projectId),
74988
- eq103(runs.kind, RunKinds["traffic-sync"]),
74989
- eq103(runs.sourceId, row.id)
75145
+ eq104(runs.projectId, projectId),
75146
+ eq104(runs.kind, RunKinds["traffic-sync"]),
75147
+ eq104(runs.sourceId, row.id)
74990
75148
  )
74991
- ).orderBy(desc47(runs.startedAt)).limit(1).get();
75149
+ ).orderBy(desc48(runs.startedAt)).limit(1).get();
74992
75150
  return {
74993
75151
  ...rowToDto(row),
74994
75152
  totals24h: {
@@ -75024,7 +75182,7 @@ async function trafficRoutes(app, opts) {
75024
75182
  const now = (/* @__PURE__ */ new Date()).toISOString();
75025
75183
  let updatedRow;
75026
75184
  app.db.transaction((tx) => {
75027
- 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();
75028
75186
  if (!sourceRow2) {
75029
75187
  throw notFound("traffic source", request.params.id);
75030
75188
  }
@@ -75038,7 +75196,7 @@ async function trafficRoutes(app, opts) {
75038
75196
  `Traffic source "${sourceRow2.id}" is staged. Activate it explicitly instead of resetting it.`
75039
75197
  );
75040
75198
  }
75041
- 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);
75042
75200
  if (hasConnectedSibling) {
75043
75201
  throw validationError(
75044
75202
  `Traffic source "${sourceRow2.id}" is not authoritative. Activate it explicitly instead of resetting it.`
@@ -75055,7 +75213,7 @@ async function trafficRoutes(app, opts) {
75055
75213
  status: TrafficSourceStatuses.connected,
75056
75214
  lastError: null,
75057
75215
  updatedAt: now
75058
- }).where(eq103(trafficSources.id, sourceRow2.id)).run();
75216
+ }).where(eq104(trafficSources.id, sourceRow2.id)).run();
75059
75217
  writeAuditLog(tx, auditFromRequest(request, {
75060
75218
  projectId: project.id,
75061
75219
  actor: "api",
@@ -75063,7 +75221,7 @@ async function trafficRoutes(app, opts) {
75063
75221
  entityType: "traffic_source",
75064
75222
  entityId: sourceRow2.id
75065
75223
  }));
75066
- 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();
75067
75225
  });
75068
75226
  return buildSourceDetail(project.id, updatedRow, new Date(Date.now() - 24 * 60 * 6e4).toISOString());
75069
75227
  }));
@@ -75075,7 +75233,7 @@ async function trafficRoutes(app, opts) {
75075
75233
  }
75076
75234
  let updatedRow;
75077
75235
  app.db.transaction((tx) => {
75078
- 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();
75079
75237
  if (!sourceRow2) {
75080
75238
  throw notFound("traffic source", request.params.id);
75081
75239
  }
@@ -75088,7 +75246,7 @@ async function trafficRoutes(app, opts) {
75088
75246
  );
75089
75247
  }
75090
75248
  const now = (/* @__PURE__ */ new Date()).toISOString();
75091
- 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();
75092
75250
  writeAuditLog(tx, auditFromRequest(request, {
75093
75251
  projectId: project.id,
75094
75252
  actor: "api",
@@ -75097,20 +75255,20 @@ async function trafficRoutes(app, opts) {
75097
75255
  entityId: sourceRow2.id,
75098
75256
  diff: { skippedThroughAt: sourceRow2.skippedThroughAt, sourceType: sourceRow2.sourceType }
75099
75257
  }));
75100
- 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();
75101
75259
  });
75102
75260
  return buildSourceDetail(project.id, updatedRow, new Date(Date.now() - 24 * 60 * 6e4).toISOString());
75103
75261
  });
75104
75262
  app.get("/projects/:name/traffic/sources", async (request) => {
75105
75263
  const project = resolveProject(app.db, request.params.name);
75106
- 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();
75107
75265
  const sources = rows.filter((row) => row.status !== TrafficSourceStatuses.archived).map(rowToDto);
75108
75266
  const response = { sources };
75109
75267
  return response;
75110
75268
  });
75111
75269
  app.get("/projects/:name/traffic/status", async (request) => {
75112
75270
  const project = resolveProject(app.db, request.params.name);
75113
- 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();
75114
75272
  const since = new Date(Date.now() - 24 * 60 * 6e4).toISOString();
75115
75273
  const sources = rows.filter((row) => row.status !== TrafficSourceStatuses.archived).map((row) => buildSourceDetail(project.id, row, since));
75116
75274
  const response = { sources };
@@ -75120,7 +75278,7 @@ async function trafficRoutes(app, opts) {
75120
75278
  "/projects/:name/traffic/sources/:id",
75121
75279
  async (request) => {
75122
75280
  const project = resolveProject(app.db, request.params.name);
75123
- 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();
75124
75282
  if (!row || row.projectId !== project.id) {
75125
75283
  throw notFound("Traffic source", request.params.id);
75126
75284
  }
@@ -75139,8 +75297,10 @@ async function trafficRoutes(app, opts) {
75139
75297
  }
75140
75298
  const sinceParam = request.query?.since;
75141
75299
  const untilParam = request.query?.until;
75142
- const since = sinceParam ? new Date(sinceParam) : defaultSince;
75143
- 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;
75144
75304
  if (Number.isNaN(since.getTime())) {
75145
75305
  throw validationError('"since" must be an ISO-8601 timestamp');
75146
75306
  }
@@ -75150,12 +75310,25 @@ async function trafficRoutes(app, opts) {
75150
75310
  if (since.getTime() > until.getTime()) {
75151
75311
  throw validationError('"since" must be \u2264 "until"');
75152
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
+ }
75153
75319
  const kindParam = request.query?.kind;
75154
75320
  const kindList = kindParam === void 0 ? parseTrafficEventKindFilter("all") : typeof kindParam === "string" ? parseTrafficEventKindFilter(kindParam) : null;
75155
75321
  if (!kindList) {
75156
75322
  throw validationError(`"kind" must be ${TRAFFIC_EVENT_KIND_FILTER_HINT}`);
75157
75323
  }
75158
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
+ }
75159
75332
  const limitParam = request.query?.limit;
75160
75333
  const requestedLimit = limitParam ? parseInt(limitParam, 10) : 500;
75161
75334
  if (!Number.isFinite(requestedLimit) || requestedLimit <= 0) {
@@ -75174,10 +75347,37 @@ async function trafficRoutes(app, opts) {
75174
75347
  );
75175
75348
  }
75176
75349
  }
75177
- const sourceIdParam = request.query?.sourceId;
75350
+ const sourceIdParam = optionalQueryString(request.query?.sourceId, "sourceId") ?? void 0;
75178
75351
  const sinceIso = since.toISOString();
75179
75352
  const untilIso = until.toISOString();
75180
- 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
+ };
75181
75381
  let crawlerTotal = 0;
75182
75382
  let crawlerSegments = { content: 0, sitemap: 0, robots: 0, asset: 0, other: 0 };
75183
75383
  let aiUserFetchTotal = 0;
@@ -75189,16 +75389,18 @@ async function trafficRoutes(app, opts) {
75189
75389
  const seriesByBucket = /* @__PURE__ */ new Map();
75190
75390
  if (kinds.has(TrafficEventKinds.crawler)) {
75191
75391
  const crawlerFilters = [
75192
- eq103(crawlerEventsHourly.projectId, project.id),
75392
+ eq104(crawlerEventsHourly.projectId, project.id),
75193
75393
  gte27(crawlerEventsHourly.tsHour, sinceIso),
75194
75394
  lte27(crawlerEventsHourly.tsHour, untilIso)
75195
75395
  ];
75196
- 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));
75197
75398
  const crawlerWhere = and89(...crawlerFilters);
75399
+ collectGroups(TRAFFIC_EVENT_TABLES.crawler, crawlerWhere);
75198
75400
  const pathTotals = app.db.select({
75199
75401
  pathNormalized: crawlerEventsHourly.pathNormalized,
75200
- hits: sql47`COALESCE(SUM(${crawlerEventsHourly.hits}), 0)`,
75201
- rows: sql47`COUNT(*)`
75402
+ hits: sql48`COALESCE(SUM(${crawlerEventsHourly.hits}), 0)`,
75403
+ rows: sql48`COUNT(*)`
75202
75404
  }).from(crawlerEventsHourly).where(crawlerWhere).groupBy(crawlerEventsHourly.pathNormalized).all();
75203
75405
  crawlerSegments = segmentCrawlerHits(
75204
75406
  pathTotals.map((r) => ({ pathNormalized: r.pathNormalized, hits: Number(r.hits) }))
@@ -75217,12 +75419,12 @@ async function trafficRoutes(app, opts) {
75217
75419
  const listed = useContentList ? contentPaths : infraPaths;
75218
75420
  const IN_LIST_CAP = 2e4;
75219
75421
  const listFitsInSql = listed.length <= IN_LIST_CAP;
75220
- 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`;
75221
75423
  if (listFitsInSql) {
75222
75424
  const crawlerSeries = app.db.select({
75223
75425
  bucket: crawlerSeriesBucket,
75224
- hits: sql47`COALESCE(SUM(${crawlerEventsHourly.hits}), 0)`,
75225
- content: sql47`COALESCE(SUM(${contentExpr}), 0)`
75426
+ hits: sql48`COALESCE(SUM(${crawlerEventsHourly.hits}), 0)`,
75427
+ content: sql48`COALESCE(SUM(${contentExpr}), 0)`
75226
75428
  }).from(crawlerEventsHourly).where(crawlerWhere).groupBy(crawlerSeriesBucket).all();
75227
75429
  for (const row of crawlerSeries) {
75228
75430
  const point = trafficSeriesPoint(seriesByBucket, String(row.bucket));
@@ -75234,7 +75436,7 @@ async function trafficRoutes(app, opts) {
75234
75436
  const grouped = app.db.select({
75235
75437
  bucket: crawlerSeriesBucket,
75236
75438
  pathNormalized: crawlerEventsHourly.pathNormalized,
75237
- hits: sql47`COALESCE(SUM(${crawlerEventsHourly.hits}), 0)`
75439
+ hits: sql48`COALESCE(SUM(${crawlerEventsHourly.hits}), 0)`
75238
75440
  }).from(crawlerEventsHourly).where(crawlerWhere).groupBy(crawlerSeriesBucket, crawlerEventsHourly.pathNormalized).all();
75239
75441
  for (const row of grouped) {
75240
75442
  const point = trafficSeriesPoint(seriesByBucket, String(row.bucket));
@@ -75244,9 +75446,14 @@ async function trafficRoutes(app, opts) {
75244
75446
  if (useContentList ? inList : !inList) point.crawlerContentHits += hits;
75245
75447
  }
75246
75448
  }
75247
- const rows = app.db.select().from(crawlerEventsHourly).where(crawlerWhere).orderBy(desc47(crawlerEventsHourly.tsHour)).limit(limit).all();
75248
- for (const r of rows) {
75249
- 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: {
75250
75457
  kind: TrafficEventKinds.crawler,
75251
75458
  sourceId: r.sourceId,
75252
75459
  tsHour: r.tsHour,
@@ -75259,34 +75466,41 @@ async function trafficRoutes(app, opts) {
75259
75466
  pathClass: classifyTrafficPath(r.pathNormalized),
75260
75467
  status: r.status,
75261
75468
  hits: r.hits
75262
- });
75263
- }
75469
+ }
75470
+ })));
75264
75471
  }
75265
75472
  if (kinds.has(TrafficEventKinds["ai-user-fetch"])) {
75266
75473
  const userFetchFilters = [
75267
- eq103(aiUserFetchEventsHourly.projectId, project.id),
75474
+ eq104(aiUserFetchEventsHourly.projectId, project.id),
75268
75475
  gte27(aiUserFetchEventsHourly.tsHour, sinceIso),
75269
75476
  lte27(aiUserFetchEventsHourly.tsHour, untilIso)
75270
75477
  ];
75271
- 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));
75272
75480
  const userFetchWhere = and89(...userFetchFilters);
75481
+ collectGroups(TRAFFIC_EVENT_TABLES["ai-user-fetch"], userFetchWhere);
75273
75482
  const total = app.db.select({
75274
- total: sql47`COALESCE(SUM(${aiUserFetchEventsHourly.hits}), 0)`,
75275
- rows: sql47`COUNT(*)`
75483
+ total: sql48`COALESCE(SUM(${aiUserFetchEventsHourly.hits}), 0)`,
75484
+ rows: sql48`COUNT(*)`
75276
75485
  }).from(aiUserFetchEventsHourly).where(userFetchWhere).get();
75277
75486
  aiUserFetchTotal = Number(total?.total ?? 0);
75278
75487
  totalEventRows += Number(total?.rows ?? 0);
75279
75488
  const userFetchSeriesBucket = seriesBucketSql(aiUserFetchEventsHourly.tsHour, granularity);
75280
75489
  const userFetchSeries = app.db.select({
75281
75490
  bucket: userFetchSeriesBucket,
75282
- hits: sql47`COALESCE(SUM(${aiUserFetchEventsHourly.hits}), 0)`
75491
+ hits: sql48`COALESCE(SUM(${aiUserFetchEventsHourly.hits}), 0)`
75283
75492
  }).from(aiUserFetchEventsHourly).where(userFetchWhere).groupBy(userFetchSeriesBucket).all();
75284
75493
  for (const row of userFetchSeries) {
75285
75494
  trafficSeriesPoint(seriesByBucket, row.bucket).aiUserFetchHits = Number(row.hits);
75286
75495
  }
75287
- const rows = app.db.select().from(aiUserFetchEventsHourly).where(userFetchWhere).orderBy(desc47(aiUserFetchEventsHourly.tsHour)).limit(limit).all();
75288
- for (const r of rows) {
75289
- 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: {
75290
75504
  kind: TrafficEventKinds["ai-user-fetch"],
75291
75505
  sourceId: r.sourceId,
75292
75506
  tsHour: r.tsHour,
@@ -75298,24 +75512,26 @@ async function trafficRoutes(app, opts) {
75298
75512
  pathNormalized: r.pathNormalized,
75299
75513
  status: r.status,
75300
75514
  hits: r.hits
75301
- });
75302
- }
75515
+ }
75516
+ })));
75303
75517
  }
75304
75518
  if (kinds.has(TrafficEventKinds["ai-referral"])) {
75305
75519
  const aiFilters = [
75306
- eq103(aiReferralEventsHourly.projectId, project.id),
75520
+ eq104(aiReferralEventsHourly.projectId, project.id),
75307
75521
  gte27(aiReferralEventsHourly.tsHour, sinceIso),
75308
75522
  lte27(aiReferralEventsHourly.tsHour, untilIso)
75309
75523
  ];
75310
- 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));
75311
75526
  const aiWhere = and89(...aiFilters);
75527
+ collectGroups(TRAFFIC_EVENT_TABLES["ai-referral"], aiWhere);
75312
75528
  const total = app.db.select({
75313
- total: sql47`COALESCE(SUM(${aiReferralEventsHourly.sessionsOrHits}), 0)`,
75314
- nonhop: sql47`COALESCE(SUM(CASE WHEN ${referralLandedCondition()} THEN ${aiReferralEventsHourly.sessionsOrHits} ELSE 0 END), 0)`,
75315
- landed: sql47`COALESCE(SUM(CASE WHEN ${countableReferralCondition()} THEN ${aiReferralEventsHourly.sessionsOrHits} ELSE 0 END), 0)`,
75316
- paid: sql47`COALESCE(SUM(CASE WHEN ${countableReferralCondition()} THEN ${aiReferralEventsHourly.paidSessionsOrHits} ELSE 0 END), 0)`,
75317
- organic: sql47`COALESCE(SUM(CASE WHEN ${countableReferralCondition()} THEN ${aiReferralEventsHourly.organicSessionsOrHits} ELSE 0 END), 0)`,
75318
- 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(*)`
75319
75535
  }).from(aiReferralEventsHourly).where(aiWhere).get();
75320
75536
  aiReferralTotalHits = Number(total?.total ?? 0);
75321
75537
  aiReferralNonHopHits = Number(total?.nonhop ?? 0);
@@ -75329,36 +75545,44 @@ async function trafficRoutes(app, opts) {
75329
75545
  const referralSeriesBucket = seriesBucketSql(aiReferralEventsHourly.tsHour, granularity);
75330
75546
  const referralSeries = app.db.select({
75331
75547
  bucket: referralSeriesBucket,
75332
- hits: sql47`COALESCE(SUM(${aiReferralEventsHourly.sessionsOrHits}), 0)`,
75333
- 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)`
75334
75550
  }).from(aiReferralEventsHourly).where(aiWhere).groupBy(referralSeriesBucket).all();
75335
75551
  for (const row of referralSeries) {
75336
75552
  const point = trafficSeriesPoint(seriesByBucket, row.bucket);
75337
75553
  point.aiReferralHits = Number(row.hits);
75338
75554
  point.aiReferralLandedHits = Number(row.landed);
75339
75555
  }
75340
- const rows = app.db.select().from(aiReferralEventsHourly).where(aiWhere).orderBy(desc47(aiReferralEventsHourly.tsHour)).limit(limit).all();
75341
- 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 }) => {
75342
75562
  const counts2 = aiReferralClassCounts(r.sessionsOrHits, r.paidSessionsOrHits, r.organicSessionsOrHits);
75343
- events.push({
75344
- kind: TrafficEventKinds["ai-referral"],
75345
- sourceId: r.sourceId,
75346
- tsHour: r.tsHour,
75347
- product: r.product,
75348
- operator: r.operator,
75349
- sourceDomain: r.sourceDomain,
75350
- evidenceType: r.evidenceType,
75351
- landingPathNormalized: r.landingPathNormalized,
75352
- status: r.status,
75353
- hits: counts2.total,
75354
- paidHits: counts2.paid,
75355
- organicHits: counts2.organic,
75356
- unknownHits: counts2.unknown
75357
- });
75358
- }
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
+ }));
75359
75582
  }
75360
- events.sort((a, b) => a.tsHour < b.tsHour ? 1 : a.tsHour > b.tsHour ? -1 : 0);
75361
- 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);
75362
75586
  const trimmedCrawlerEvents = trimmed.filter(
75363
75587
  (event) => event.kind === TrafficEventKinds.crawler
75364
75588
  );
@@ -75383,11 +75607,11 @@ async function trafficRoutes(app, opts) {
75383
75607
  windowEnd: untilIso,
75384
75608
  series: (() => {
75385
75609
  const points = completeTrafficSeries(since, until, granularity, seriesByBucket);
75386
- 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);
75387
75611
  const firsts = [
75388
- app.db.select({ v: sql47`MIN(${crawlerEventsHourly.tsHour})` }).from(crawlerEventsHourly).where(coverageScope(crawlerEventsHourly.projectId, crawlerEventsHourly.sourceId)).get()?.v,
75389
- app.db.select({ v: sql47`MIN(${aiUserFetchEventsHourly.tsHour})` }).from(aiUserFetchEventsHourly).where(coverageScope(aiUserFetchEventsHourly.projectId, aiUserFetchEventsHourly.sourceId)).get()?.v,
75390
- 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
75391
75615
  ].filter((v) => typeof v === "string" && v.length > 0);
75392
75616
  const referralCountingChangedAt = aiReferralOlderCountUntil(app.db, { projectId: project.id, sourceId: sourceIdParam });
75393
75617
  const referralCountingChangedMs = referralCountingChangedAt === null ? null : Date.parse(referralCountingChangedAt);
@@ -75465,19 +75689,30 @@ async function trafficRoutes(app, opts) {
75465
75689
  aiReferralOrganicHits: aiReferralCounts.organic,
75466
75690
  aiReferralUnknownHits: aiReferralCounts.unknown
75467
75691
  },
75692
+ filters: readFilters,
75468
75693
  eventRows: {
75469
75694
  total: totalEventRows,
75470
75695
  returned: trimmed.length,
75471
- truncated: trimmed.length < totalEventRows
75696
+ truncated: nextCursor !== null,
75697
+ nextCursor
75472
75698
  },
75473
- 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
+ } : {}
75474
75709
  };
75475
75710
  return response;
75476
75711
  });
75477
75712
  }
75478
75713
 
75479
75714
  // ../api-routes/src/doctor/checks/report-sweeps.ts
75480
- 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";
75481
75716
 
75482
75717
  // ../api-routes/src/visibility-attribution.ts
75483
75718
  function buildQueryAttribution2(projectQueries) {
@@ -75511,11 +75746,11 @@ function inspectSweep(ctx, run) {
75511
75746
  answerMentioned: querySnapshots.answerMentioned,
75512
75747
  answerText: querySnapshots.answerText,
75513
75748
  measurementExecutionId: querySnapshots.measurementExecutionId
75514
- }).from(querySnapshots).where(eq104(querySnapshots.runId, run.id)).all();
75749
+ }).from(querySnapshots).where(eq105(querySnapshots.runId, run.id)).all();
75515
75750
  if (snapshots.length === 0) return { detail: { ...base, complete: false, reason: "no-answers" } };
75516
75751
  try {
75517
75752
  if (run.measurementPlanVersionId) {
75518
- 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();
75519
75754
  if (!version) return { detail: { ...base, complete: false, reason: "missing-plan" } };
75520
75755
  const plan = parseStoredMeasurementPlanAnyVersion(version.canonicalJson);
75521
75756
  const manifest = measurementRunExpectedSlots(run, plan);
@@ -75547,10 +75782,10 @@ function inspectSweep(ctx, run) {
75547
75782
  };
75548
75783
  return unbound ? { detail } : { detail, coverage: slotCoverage(expected2, answered3) };
75549
75784
  }
75550
- 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();
75551
75786
  const frozen = stored ? simpleMeasurementDefinitionSchema.parse(stored.definition) : null;
75552
- const project = ctx.db.select().from(projects).where(eq104(projects.id, ctx.project.id)).get();
75553
- 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();
75554
75789
  const providers = frozen ? frozen.engines.map((engine) => engine.provider) : project.providers.length > 0 ? project.providers : [...new Set(snapshots.map((snapshot) => snapshot.provider))];
75555
75790
  const attribution = buildQueryAttribution2(basket);
75556
75791
  const expected = new Set(basket.flatMap((query2) => providers.map((provider) => JSON.stringify([query2.id, provider.trim().toLowerCase()]))));
@@ -75599,7 +75834,7 @@ var reportSweepsCheck = {
75599
75834
  const graded = gradedReportMonths(reportMonths, now);
75600
75835
  const months = reportMonths.map((month) => {
75601
75836
  const bounds = calendarMonthBounds(month);
75602
- 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();
75603
75838
  const evidence = monthRuns.map((run) => inspectSweep(ctx, run));
75604
75839
  return {
75605
75840
  month,
@@ -75622,7 +75857,7 @@ var reportSweepsCheck = {
75622
75857
  };
75623
75858
 
75624
75859
  // ../api-routes/src/doctor/checks/report-models.ts
75625
- 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";
75626
75861
  var reportModelsCheck = {
75627
75862
  id: "report.models",
75628
75863
  category: CheckCategories.providers,
@@ -75637,7 +75872,7 @@ var reportModelsCheck = {
75637
75872
  const months = reportMonths.flatMap((month) => {
75638
75873
  const bounds = calendarMonthBounds(month);
75639
75874
  const previous = new Date(Date.parse(bounds.since) - 1).toISOString().slice(0, 7);
75640
- 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();
75641
75876
  return readVisibilityContinuity(ctx.db, ctx.project.name, { from: previous, to: month }).map(({ frame, continuity: continuity2 }) => ({
75642
75877
  month,
75643
75878
  previousMonth: previous,
@@ -75678,7 +75913,7 @@ var reportModelsCheck = {
75678
75913
  };
75679
75914
 
75680
75915
  // ../api-routes/src/doctor/checks/report-daily-data.ts
75681
- import { eq as eq106 } from "drizzle-orm";
75916
+ import { eq as eq107 } from "drizzle-orm";
75682
75917
  var REPORTING_LAG_DAYS = 3;
75683
75918
  function dateSpan(dates) {
75684
75919
  const sorted = [...dates].sort();
@@ -75687,31 +75922,31 @@ function dateSpan(dates) {
75687
75922
  function latestSyncRange(ctx, source) {
75688
75923
  const projectId = ctx.project.id;
75689
75924
  if (source === "ga") {
75690
- 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();
75691
75926
  const latest2 = rows2.reduce((max2, row) => max2 === null || row.syncedAt > max2 ? row.syncedAt : max2, null);
75692
- 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();
75693
75928
  if (summary3 && (latest2 === null || summary3.syncedAt >= latest2)) return { start: summary3.start, end: summary3.end, syncedAt: summary3.syncedAt };
75694
75929
  const span2 = dateSpan(rows2.filter((row) => row.syncedAt === latest2).map((row) => row.date));
75695
75930
  return span2 && latest2 !== null ? { ...span2, syncedAt: latest2 } : null;
75696
75931
  }
75697
- 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();
75698
75933
  const latest = rows.reduce((max2, row) => max2 === null || row.createdAt > max2 ? row.createdAt : max2, null);
75699
75934
  const span = dateSpan(rows.filter((row) => row.createdAt === latest).map((row) => row.date));
75700
75935
  if (!span || latest === null) return null;
75701
- 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();
75702
75937
  return watermark?.through && watermark.updatedAt === latest && watermark.through > span.end ? { start: span.start, end: watermark.through, syncedAt: latest } : { ...span, syncedAt: latest };
75703
75938
  }
75704
75939
  function dailyCoverage(ctx, month, source) {
75705
75940
  const project = ctx.project;
75706
75941
  const connection = source === "ga" ? ctx.ga4CredentialStore?.getConnection(project.name) ?? ctx.googleConnectionStore?.getConnection(project.canonicalDomain, "ga4") : ctx.googleConnectionStore?.getConnection(project.canonicalDomain, "gsc");
75707
- 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();
75708
75943
  if (!connection && stored.length === 0) return null;
75709
75944
  const bounds = calendarMonthBounds(month);
75710
75945
  const start = bounds.since.slice(0, 10);
75711
75946
  const end = bounds.until.slice(0, 10);
75712
75947
  const timeZone = source === "gsc" ? "America/Los_Angeles" : "UTC";
75713
75948
  const matureThrough = isoDateDaysBeforeInTimeZone((/* @__PURE__ */ new Date()).toISOString(), REPORTING_LAG_DAYS, timeZone);
75714
- 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);
75715
75950
  const connectedAt = connection?.createdAt?.slice(0, 10) ?? created;
75716
75951
  const onboardingDate = [connectedAt, ...stored.map((row) => row.date)].sort()[0];
75717
75952
  const byDate = new Map(stored.map((row) => [row.date, row.count]));
@@ -75793,7 +76028,7 @@ var reportDailyDataCheck = {
75793
76028
  };
75794
76029
 
75795
76030
  // ../api-routes/src/doctor/checks/referral-assessment.ts
75796
- 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";
75797
76032
  var REFERRAL_ASSESSMENT_CHECKS = [{
75798
76033
  id: "report.ai-referral-bursts",
75799
76034
  category: CheckCategories.integrations,
@@ -75802,7 +76037,7 @@ var REFERRAL_ASSESSMENT_CHECKS = [{
75802
76037
  notificationPolicy: CheckNotificationPolicies.silent,
75803
76038
  run: (ctx) => {
75804
76039
  if (!ctx.project) return { status: CheckStatuses.skipped, code: "report.ai-referral-bursts.no-project", summary: "Select a project to inspect referral evidence." };
75805
- 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();
75806
76041
  if (!configured) {
75807
76042
  return { status: CheckStatuses.skipped, code: "report.ai-referral-bursts.not-configured", summary: "No non-archived server traffic source is configured for this project." };
75808
76043
  }
@@ -75835,7 +76070,7 @@ var REFERRAL_ASSESSMENT_CHECKS = [{
75835
76070
  }];
75836
76071
 
75837
76072
  // ../api-routes/src/doctor/checks/agent.ts
75838
- import crypto61 from "crypto";
76073
+ import crypto62 from "crypto";
75839
76074
  import fs6 from "fs";
75840
76075
  import path7 from "path";
75841
76076
  var REQUIRED_SKILLS = ["canonry", "aero"];
@@ -76069,7 +76304,7 @@ function isInstalled(dir) {
76069
76304
  }
76070
76305
  function hashInstalledFile(filePath) {
76071
76306
  try {
76072
- return crypto61.createHash("sha256").update(fs6.readFileSync(filePath)).digest("hex");
76307
+ return crypto62.createHash("sha256").update(fs6.readFileSync(filePath)).digest("hex");
76073
76308
  } catch {
76074
76309
  return void 0;
76075
76310
  }
@@ -76214,19 +76449,19 @@ var BACKLINKS_CHECKS = [
76214
76449
  ];
76215
76450
 
76216
76451
  // ../api-routes/src/doctor/checks/bing-auth.ts
76217
- 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";
76218
76453
  var BING_CONNECTION_ENTITY = "bing_connection";
76219
76454
  var BING_CONNECTED_ACTION = "bing.connected";
76220
76455
  var BING_DISCONNECTED_ACTION = "bing.disconnected";
76221
76456
  function lostBingConnection(ctx, project) {
76222
76457
  const hasRow = (row) => row !== void 0;
76223
- 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());
76224
76459
  if (!storedData) return false;
76225
76460
  const lastChange = ctx.db.select({ action: auditLog.action }).from(auditLog).where(and93(
76226
- eq108(auditLog.entityType, BING_CONNECTION_ENTITY),
76227
- eq108(auditLog.entityId, project.canonicalDomain),
76461
+ eq109(auditLog.entityType, BING_CONNECTION_ENTITY),
76462
+ eq109(auditLog.entityId, project.canonicalDomain),
76228
76463
  inArray50(auditLog.action, [BING_CONNECTED_ACTION, BING_DISCONNECTED_ACTION])
76229
- )).orderBy(desc48(auditLog.createdAt)).limit(1).get();
76464
+ )).orderBy(desc49(auditLog.createdAt)).limit(1).get();
76230
76465
  return lastChange?.action !== BING_DISCONNECTED_ACTION;
76231
76466
  }
76232
76467
  var BING_AUTH_CHECKS = [
@@ -76383,7 +76618,7 @@ var BING_AUTH_CHECKS = [
76383
76618
  ];
76384
76619
 
76385
76620
  // ../api-routes/src/doctor/checks/content.ts
76386
- import { eq as eq109 } from "drizzle-orm";
76621
+ import { eq as eq110 } from "drizzle-orm";
76387
76622
  var WINNABILITY_COVERAGE_WARN_THRESHOLD = 0.8;
76388
76623
  var UNCLASSIFIED_DOMAIN_SAMPLE_LIMIT = 10;
76389
76624
  function skippedNoProject2() {
@@ -76396,7 +76631,7 @@ function skippedNoProject2() {
76396
76631
  }
76397
76632
  function loadProject(ctx) {
76398
76633
  if (!ctx.project) return null;
76399
- 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;
76400
76635
  }
76401
76636
  var winnabilityCoverageCheck = {
76402
76637
  id: "content.winnability.coverage",
@@ -76489,7 +76724,7 @@ var CONTENT_CHECK_BY_ID = Object.fromEntries(
76489
76724
  );
76490
76725
 
76491
76726
  // ../api-routes/src/doctor/checks/ads.ts
76492
- import { eq as eq110 } from "drizzle-orm";
76727
+ import { eq as eq111 } from "drizzle-orm";
76493
76728
  var ADS_RECENT_SYNC_WARN_DAYS = 7;
76494
76729
  var ADS_RECENT_SYNC_FAIL_DAYS = 30;
76495
76730
  var adsConnectionCheck = {
@@ -76506,7 +76741,7 @@ var adsConnectionCheck = {
76506
76741
  remediation: null
76507
76742
  };
76508
76743
  }
76509
- 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();
76510
76745
  if (!row) {
76511
76746
  return {
76512
76747
  status: CheckStatuses.skipped,
@@ -76556,7 +76791,7 @@ var adsRecentSyncCheck = {
76556
76791
  remediation: null
76557
76792
  };
76558
76793
  }
76559
- 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();
76560
76795
  if (!row) {
76561
76796
  return {
76562
76797
  status: CheckStatuses.skipped,
@@ -76771,7 +77006,7 @@ var ga4ConnectionCheck = {
76771
77006
  var GA_AUTH_CHECKS = [ga4ConnectionCheck];
76772
77007
 
76773
77008
  // ../api-routes/src/doctor/checks/data-freshness.ts
76774
- 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";
76775
77010
  var GA_DATA_AGING_DAYS = 3;
76776
77011
  var GA_DATA_STALE_DAYS = 5;
76777
77012
  var GSC_DATA_AGING_DAYS = 5;
@@ -76801,7 +77036,7 @@ function skipped(code, summary3) {
76801
77036
  return { status: CheckStatuses.skipped, code, summary: summary3, remediation: null };
76802
77037
  }
76803
77038
  function lastSyncAgeDays(ctx, kinds) {
76804
- 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();
76805
77040
  if (!row?.createdAt) return null;
76806
77041
  const age = Math.floor((Date.now() - Date.parse(row.createdAt)) / DAY_MS6);
76807
77042
  return Number.isFinite(age) ? age : null;
@@ -76903,7 +77138,7 @@ var gaRecentDataCheck = {
76903
77138
  const connection = gaConnected(ctx);
76904
77139
  if (connection === "store-unavailable") return skipped("ga.data.store-unavailable", "No GA4 credential store configured for this deployment.");
76905
77140
  if (connection === "not-connected") return skipped("ga.data.not-connected", "GA4 is not connected for this project.");
76906
- 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();
76907
77142
  return grade(ctx, GA_SPEC, newest?.date);
76908
77143
  }
76909
77144
  };
@@ -76918,16 +77153,16 @@ var gscRecentDataCheck = {
76918
77153
  if (!ctx.googleConnectionStore.getConnection(ctx.project.canonicalDomain, "gsc")) {
76919
77154
  return skipped("gsc.data.not-connected", "Search Console is not connected for this project.");
76920
77155
  }
76921
- 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();
76922
77157
  if (watermark?.dataThroughDate) return grade(ctx, GSC_SPEC, watermark.dataThroughDate);
76923
- 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();
76924
77159
  return grade(ctx, GSC_SPEC, newest?.date);
76925
77160
  }
76926
77161
  };
76927
77162
  var DATA_FRESHNESS_CHECKS = [gaRecentDataCheck, gscRecentDataCheck];
76928
77163
 
76929
77164
  // ../api-routes/src/doctor/checks/seo-refresh.ts
76930
- 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";
76931
77166
  var GRACE_DAYS = 2;
76932
77167
  var DAY_MS7 = 24 * 60 * 60 * 1e3;
76933
77168
  var FIRING_SPAN_MS = 6e4;
@@ -76936,7 +77171,7 @@ function skipped2(code, summary3) {
76936
77171
  return { status: CheckStatuses.skipped, code, summary: summary3, remediation: null };
76937
77172
  }
76938
77173
  function seoSyncRuns(projectId) {
76939
- 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"]));
76940
77175
  }
76941
77176
  function scheduleTiming(schedule) {
76942
77177
  if (!schedule.recurrence) return { cronExpr: schedule.cronExpr, timezone: schedule.timezone, recurrence: null };
@@ -76944,16 +77179,16 @@ function scheduleTiming(schedule) {
76944
77179
  return recurrence ? { cronExpr: schedule.cronExpr, timezone: schedule.timezone, recurrence } : null;
76945
77180
  }
76946
77181
  function latestFiring(ctx, projectId, enabledSince) {
76947
- const scheduled = and95(seoSyncRuns(projectId), eq112(runs.trigger, RunTriggers.scheduled), gt9(runs.createdAt, enabledSince));
76948
- 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();
76949
77184
  if (!newest) return [];
76950
77185
  const newestMs = Date.parse(newest.createdAt);
76951
77186
  const after = Number.isFinite(newestMs) ? new Date(newestMs - FIRING_SPAN_MS).toISOString() : newest.createdAt;
76952
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();
76953
77188
  }
76954
77189
  function lastCompleted(ctx, projectId) {
76955
- const at = sql48`coalesce(${runs.finishedAt}, ${runs.createdAt})`;
76956
- 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;
76957
77192
  }
76958
77193
  function isIncomplete(run) {
76959
77194
  return run.status === RunStatuses.failed || run.status === RunStatuses.partial;
@@ -76967,7 +77202,7 @@ function unsettledRuns(ctx, projectId, firing, profiles) {
76967
77202
  const incomplete = firing.filter(isIncomplete);
76968
77203
  const firedAt = firing[firing.length - 1]?.createdAt;
76969
77204
  if (incomplete.length === 0 || !firedAt) return incomplete;
76970
- 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));
76971
77206
  return incomplete.filter((run) => {
76972
77207
  const profile = profiles.get(run.id) ?? null;
76973
77208
  return profile === null ? refreshed.size === 0 : !refreshed.has(profile);
@@ -76977,7 +77212,7 @@ var COUNT_LIST = new Intl.ListFormat("en", { style: "long", type: "conjunction"
76977
77212
  function refreshReason(ctx, run) {
76978
77213
  const stored = parseRunError(run.error);
76979
77214
  if (stored) return formatRunErrorOneLine(stored);
76980
- 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());
76981
77216
  const failed = tasks.filter((task) => task.status === SeoRunStatuses.failed || task.status === SeoRunStatuses["reconciliation-required"]);
76982
77217
  const partial = tasks.filter((task) => task.status === SeoRunStatuses.partial).length;
76983
77218
  const cancelled = tasks.filter((task) => task.status === SeoRunStatuses.cancelled).length;
@@ -76997,7 +77232,7 @@ function refreshReason(ctx, run) {
76997
77232
  return `Of ${tasks.length} ${unit}, ${COUNT_LIST.format(counts2)}.${errors ? ` ${errors}` : ""}`;
76998
77233
  }
76999
77234
  function gradeSeoRefresh(ctx, project) {
77000
- 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();
77001
77236
  if (!schedule) return skipped2("seo.data.not-scheduled", "No SEO refresh schedule is set for this project.");
77002
77237
  if (!schedule.enabled) return skipped2("seo.data.not-scheduled", "The SEO refresh schedule is disabled.");
77003
77238
  const name = project.name;
@@ -77379,7 +77614,7 @@ var siteReachabilityCheck = {
77379
77614
  var SITE_REACHABILITY_CHECKS = [siteReachabilityCheck];
77380
77615
 
77381
77616
  // ../api-routes/src/doctor/checks/api-hosts.ts
77382
- import { eq as eq114 } from "drizzle-orm";
77617
+ import { eq as eq115 } from "drizzle-orm";
77383
77618
 
77384
77619
  // ../api-routes/src/api-host-probe.ts
77385
77620
  import dns4 from "dns/promises";
@@ -77485,7 +77720,7 @@ async function probeApiHost(host, options = {}) {
77485
77720
  }
77486
77721
 
77487
77722
  // ../api-routes/src/doctor/checks/integration-sync.ts
77488
- 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";
77489
77724
  var SYNC_FAILURE_WINDOW = 3;
77490
77725
  var SUMMARY_ERROR_LIMIT = 300;
77491
77726
  var FINISHED_STATUSES = [RunStatuses.completed, RunStatuses.partial, RunStatuses.failed];
@@ -77512,7 +77747,7 @@ function gscConnection(ctx, project) {
77512
77747
  function gbpConnection(ctx, project) {
77513
77748
  if (!ctx.googleConnectionStore) return { state: "store-unavailable" };
77514
77749
  if (!ctx.googleConnectionStore.getConnection(project.canonicalDomain, "gbp")) return { state: "not-connected" };
77515
- 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();
77516
77751
  return selected ? CONNECTED : { state: "no-selected-locations" };
77517
77752
  }
77518
77753
  function gaConnection(ctx, project) {
@@ -77586,15 +77821,15 @@ function latestErrorText(raw) {
77586
77821
  }
77587
77822
  function readSyncRunState(db, projectId, kind, options = {}) {
77588
77823
  const scope = and96(
77589
- eq113(runs.projectId, projectId),
77590
- eq113(runs.kind, kind),
77591
- ...options.sourceId ? [eq113(runs.sourceId, options.sourceId)] : [],
77592
- ...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]))] : []
77593
77828
  );
77594
77829
  const graded = options.since ? and96(scope, gte30(runs.createdAt, options.since)) : scope;
77595
- 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();
77596
- 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();
77597
- 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();
77598
77833
  const failuresSinceSuccess = Number(failureCount?.count ?? 0);
77599
77834
  const latest = recent[0];
77600
77835
  return {
@@ -77691,7 +77926,7 @@ function connectionFor(prefix, ctx, project) {
77691
77926
  if (prefix === "google-ads") return googleMarketingConnection("googleAds")(ctx);
77692
77927
  if (prefix === "gtm") return googleMarketingConnection("gtm")(ctx);
77693
77928
  if (prefix === "bing") return ctx.bingConnectionStore?.getConnection(project.canonicalDomain) ? { state: "connected", since: null } : { state: "not-connected" };
77694
- 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" };
77695
77930
  }
77696
77931
  function syncCommand(prefix) {
77697
77932
  if (prefix === "gsc") return "google sync";
@@ -77736,7 +77971,7 @@ function definition(prefix) {
77736
77971
  var API_HOST_CHECKS = Object.keys(API_HOST_TABLE).map(definition);
77737
77972
 
77738
77973
  // ../api-routes/src/doctor/checks/gbp-auth.ts
77739
- import { and as and97, eq as eq115 } from "drizzle-orm";
77974
+ import { and as and97, eq as eq116 } from "drizzle-orm";
77740
77975
  var RECENT_SYNC_WARN_DAYS = 4;
77741
77976
  var RECENT_SYNC_FAIL_DAYS = 30;
77742
77977
  function skippedNoProject3() {
@@ -77756,7 +77991,7 @@ function storeUnavailable() {
77756
77991
  };
77757
77992
  }
77758
77993
  function hasSelectedLocation(ctx, projectId) {
77759
- 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();
77760
77995
  }
77761
77996
  async function resolveGbpToken(ctx) {
77762
77997
  if (!ctx.project) return { ok: false, output: skippedNoProject3() };
@@ -78016,7 +78251,7 @@ var recentSyncCheck = {
78016
78251
  title: "GBP recent sync",
78017
78252
  run: (ctx) => {
78018
78253
  if (!ctx.project) return skippedNoProject3();
78019
- 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();
78020
78255
  if (selected.length === 0) {
78021
78256
  return {
78022
78257
  status: CheckStatuses.skipped,
@@ -78076,7 +78311,7 @@ var GBP_AUTH_CHECK_BY_ID = Object.fromEntries(
78076
78311
  );
78077
78312
 
78078
78313
  // ../api-routes/src/doctor/checks/places.ts
78079
- import { eq as eq116 } from "drizzle-orm";
78314
+ import { eq as eq117 } from "drizzle-orm";
78080
78315
  var apiKeyCheck = {
78081
78316
  id: "gbp.places.api-key",
78082
78317
  category: CheckCategories.auth,
@@ -78121,7 +78356,7 @@ var apiKeyCheck = {
78121
78356
  details: { tier: cfg.tier }
78122
78357
  };
78123
78358
  }
78124
- 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();
78125
78360
  const selected = rows.filter((r) => r.selected);
78126
78361
  const locationsWithPlaceId = selected.filter((r) => Boolean(r.placeId)).length;
78127
78362
  const details = {
@@ -78154,7 +78389,7 @@ var PLACES_CHECK_BY_ID = Object.fromEntries(
78154
78389
  );
78155
78390
 
78156
78391
  // ../api-routes/src/doctor/checks/gbp-reviews.ts
78157
- 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";
78158
78393
  var REVIEW_EVENTS = /* @__PURE__ */ new Set(["review.negative", "review.rating-dropped"]);
78159
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`.";
78160
78395
  var reviewsAccessCheck = {
@@ -78182,7 +78417,7 @@ var reviewsAccessCheck = {
78182
78417
  reviewsAccess: gbpLocations.reviewsAccess,
78183
78418
  reviewsAccessReason: gbpLocations.reviewsAccessReason,
78184
78419
  reviewsCheckedAt: gbpLocations.reviewsCheckedAt
78185
- }).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();
78186
78421
  if (locations.length === 0) {
78187
78422
  return {
78188
78423
  status: CheckStatuses.skipped,
@@ -78202,7 +78437,7 @@ var reviewsAccessCheck = {
78202
78437
  const places = ctx.getPlacesConfig?.();
78203
78438
  const placesFallback = places !== void 0 && places.tier === "atmosphere" && Boolean(places.apiKey);
78204
78439
  const v4Worked = new Set(
78205
- 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)
78206
78441
  );
78207
78442
  const coverageOf = (loc) => {
78208
78443
  if (businessProfileReviewsCover(loc.reviewsAccess ?? null, v4Worked.has(loc.locationName))) return "full";
@@ -78236,7 +78471,7 @@ var reviewsAccessCheck = {
78236
78471
  none > 0 ? `${none} have no review source` : null
78237
78472
  ].filter((part) => part !== null);
78238
78473
  const summary3 = `Business Profile reviews are not available${why}. ${parts.join("; ")}.`;
78239
- 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)));
78240
78475
  const placesHint = placesFallback ? "" : " For partial coverage meanwhile, set a Places API key (`GOOGLE_PLACES_API_KEY` or `places.apiKey`) with `places.tier: atmosphere`.";
78241
78476
  if (none > 0 && subscribed) {
78242
78477
  return {
@@ -78267,7 +78502,7 @@ var reviewDeliveryCheck = {
78267
78502
  return { status: CheckStatuses.skipped, code: "gbp.reviews.delivery.no-project", summary: "Project context required.", remediation: null };
78268
78503
  }
78269
78504
  const since = new Date(Date.now() - UNDELIVERED_ATTENTION_DAYS * 864e5).toISOString();
78270
- const lastTouched = sql49`coalesce(${reviewWebhookDeliveries.attemptedAt}, ${reviewWebhookDeliveries.createdAt})`;
78505
+ const lastTouched = sql50`coalesce(${reviewWebhookDeliveries.attemptedAt}, ${reviewWebhookDeliveries.createdAt})`;
78271
78506
  const rows = ctx.db.select({
78272
78507
  id: reviewWebhookDeliveries.id,
78273
78508
  notificationId: reviewWebhookDeliveries.notificationId,
@@ -78276,10 +78511,10 @@ var reviewDeliveryCheck = {
78276
78511
  lastTouched,
78277
78512
  payload: reviewWebhookDeliveries.payload
78278
78513
  }).from(reviewWebhookDeliveries).where(and98(
78279
- eq117(reviewWebhookDeliveries.projectId, ctx.project.id),
78514
+ eq118(reviewWebhookDeliveries.projectId, ctx.project.id),
78280
78515
  inArray54(reviewWebhookDeliveries.state, [ReviewDeliveryStates.Uncertain, ReviewDeliveryStates.Failed]),
78281
78516
  gte31(lastTouched, since)
78282
- )).orderBy(desc52(lastTouched)).all();
78517
+ )).orderBy(desc53(lastTouched)).all();
78283
78518
  if (rows.length === 0) {
78284
78519
  return {
78285
78520
  status: CheckStatuses.ok,
@@ -78288,7 +78523,7 @@ var reviewDeliveryCheck = {
78288
78523
  remediation: null
78289
78524
  };
78290
78525
  }
78291
- 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]));
78292
78527
  const deliveries = rows.map((row) => {
78293
78528
  const review = row.payload.reviews[0];
78294
78529
  return {
@@ -78862,7 +79097,7 @@ var RUNTIME_STATE_CHECKS = [
78862
79097
  ];
78863
79098
 
78864
79099
  // ../api-routes/src/doctor/checks/traffic-source.ts
78865
- 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";
78866
79101
  var RECENT_DATA_WARN_DAYS = 7;
78867
79102
  var RECENT_DATA_FAIL_DAYS = 30;
78868
79103
  function isCloudflareDirectPush(source) {
@@ -78902,7 +79137,7 @@ function loadProbes(ctx) {
78902
79137
  if (!ctx.project) return [];
78903
79138
  const rows = ctx.db.select().from(trafficSources).where(
78904
79139
  and99(
78905
- eq118(trafficSources.projectId, ctx.project.id),
79140
+ eq119(trafficSources.projectId, ctx.project.id),
78906
79141
  ne17(trafficSources.status, TrafficSourceStatuses.archived)
78907
79142
  )
78908
79143
  ).all();
@@ -79039,27 +79274,27 @@ var recentDataCheck = {
79039
79274
  const warnCutoff = new Date(now.getTime() - RECENT_DATA_WARN_DAYS * 24 * 60 * 6e4).toISOString();
79040
79275
  const failCutoff = new Date(now.getTime() - RECENT_DATA_FAIL_DAYS * 24 * 60 * 6e4).toISOString();
79041
79276
  const recentCrawlers = Number(
79042
- 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(
79043
79278
  and99(
79044
- eq118(crawlerEventsHourly.projectId, ctx.project.id),
79279
+ eq119(crawlerEventsHourly.projectId, ctx.project.id),
79045
79280
  inArray55(crawlerEventsHourly.sourceId, activeSourceIds),
79046
79281
  gte32(crawlerEventsHourly.tsHour, warnCutoff)
79047
79282
  )
79048
79283
  ).get()?.total ?? 0
79049
79284
  );
79050
79285
  const recentReferrals = Number(
79051
- 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(
79052
79287
  and99(
79053
- eq118(aiReferralEventsHourly.projectId, ctx.project.id),
79288
+ eq119(aiReferralEventsHourly.projectId, ctx.project.id),
79054
79289
  inArray55(aiReferralEventsHourly.sourceId, activeSourceIds),
79055
79290
  gte32(aiReferralEventsHourly.tsHour, warnCutoff)
79056
79291
  )
79057
79292
  ).get()?.total ?? 0
79058
79293
  );
79059
79294
  const recentUserFetches = Number(
79060
- 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(
79061
79296
  and99(
79062
- eq118(aiUserFetchEventsHourly.projectId, ctx.project.id),
79297
+ eq119(aiUserFetchEventsHourly.projectId, ctx.project.id),
79063
79298
  inArray55(aiUserFetchEventsHourly.sourceId, activeSourceIds),
79064
79299
  gte32(aiUserFetchEventsHourly.tsHour, warnCutoff)
79065
79300
  )
@@ -79083,27 +79318,27 @@ var recentDataCheck = {
79083
79318
  };
79084
79319
  }
79085
79320
  const olderCrawlers = Number(
79086
- 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(
79087
79322
  and99(
79088
- eq118(crawlerEventsHourly.projectId, ctx.project.id),
79323
+ eq119(crawlerEventsHourly.projectId, ctx.project.id),
79089
79324
  inArray55(crawlerEventsHourly.sourceId, activeSourceIds),
79090
79325
  gte32(crawlerEventsHourly.tsHour, failCutoff)
79091
79326
  )
79092
79327
  ).get()?.total ?? 0
79093
79328
  );
79094
79329
  const olderReferrals = Number(
79095
- 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(
79096
79331
  and99(
79097
- eq118(aiReferralEventsHourly.projectId, ctx.project.id),
79332
+ eq119(aiReferralEventsHourly.projectId, ctx.project.id),
79098
79333
  inArray55(aiReferralEventsHourly.sourceId, activeSourceIds),
79099
79334
  gte32(aiReferralEventsHourly.tsHour, failCutoff)
79100
79335
  )
79101
79336
  ).get()?.total ?? 0
79102
79337
  );
79103
79338
  const olderUserFetches = Number(
79104
- 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(
79105
79340
  and99(
79106
- eq118(aiUserFetchEventsHourly.projectId, ctx.project.id),
79341
+ eq119(aiUserFetchEventsHourly.projectId, ctx.project.id),
79107
79342
  inArray55(aiUserFetchEventsHourly.sourceId, activeSourceIds),
79108
79343
  gte32(aiUserFetchEventsHourly.tsHour, failCutoff)
79109
79344
  )
@@ -79431,11 +79666,11 @@ var syncLagCheck = {
79431
79666
  };
79432
79667
  function lastQueueStopReason(ctx, sourceId) {
79433
79668
  const row = ctx.db.select({ syncSummary: runs.syncSummary }).from(runs).where(and99(
79434
- eq118(runs.projectId, ctx.project.id),
79435
- eq118(runs.kind, RunKinds["traffic-sync"]),
79436
- eq118(runs.sourceId, sourceId),
79669
+ eq119(runs.projectId, ctx.project.id),
79670
+ eq119(runs.kind, RunKinds["traffic-sync"]),
79671
+ eq119(runs.sourceId, sourceId),
79437
79672
  isNotNull11(runs.syncSummary)
79438
- )).orderBy(desc53(runs.createdAt)).limit(1).get();
79673
+ )).orderBy(desc54(runs.createdAt)).limit(1).get();
79439
79674
  return row?.syncSummary?.type === "cloudflare-queue" ? row.syncSummary.stopReason : null;
79440
79675
  }
79441
79676
  var QUEUE_LIMIT_STOPS = [
@@ -80233,7 +80468,7 @@ async function doctorRoutes(app, opts) {
80233
80468
  }
80234
80469
 
80235
80470
  // ../api-routes/src/status.ts
80236
- 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";
80237
80472
  function ageDays(iso2) {
80238
80473
  if (!iso2) return null;
80239
80474
  const ms = Date.now() - Date.parse(iso2);
@@ -80283,7 +80518,7 @@ function makeRow(integration, label, runKind, state, staleAfterDays, dataThrough
80283
80518
  };
80284
80519
  }
80285
80520
  function latestDate2(db, table, projectId) {
80286
- 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();
80287
80522
  return row?.date ?? null;
80288
80523
  }
80289
80524
  function projectRows(opts, project) {
@@ -80298,7 +80533,7 @@ function projectRows(opts, project) {
80298
80533
  const rows = [];
80299
80534
  const gsc = gscConnection(ctx, info);
80300
80535
  if (connected(gsc)) {
80301
- 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();
80302
80537
  const state = readSyncRunState(opts.db, project.id, RunKinds["gsc-sync"], { since: gsc.since });
80303
80538
  const dataThrough = watermarkRow?.dataThroughDate ?? latestDate2(opts.db, gscDailyTotals, project.id);
80304
80539
  rows.push(makeRow("gsc", "Search Console", RunKinds["gsc-sync"], state, SYNC_IDLE_DAYS, dataThrough, null, ["gsc.sync.recent-failures"], GSC_DATA_AGING_DAYS));
@@ -80314,12 +80549,12 @@ function projectRows(opts, project) {
80314
80549
  rows.push(makeRow("bing", "Bing Webmaster Tools", RunKinds["bing-inspect-sitemap"], readSyncRunState(opts.db, project.id, RunKinds["bing-inspect-sitemap"]), null));
80315
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));
80316
80551
  }
80317
- 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();
80318
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));
80319
80554
  const marketing = opts.getGoogleMarketingDoctorInput?.(ctx);
80320
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));
80321
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));
80322
- 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();
80323
80558
  for (const source of sources) {
80324
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"]);
80325
80560
  const lag = source.lastSyncedAt ? Date.now() - Date.parse(source.lastSyncedAt) : Number.POSITIVE_INFINITY;
@@ -80331,7 +80566,7 @@ function projectRows(opts, project) {
80331
80566
  }
80332
80567
  function projectStatus(opts, project) {
80333
80568
  const integrations = projectRows(opts, project);
80334
- 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();
80335
80570
  const health = healthRow ? { status: healthRow.status, code: healthRow.code, summary: healthRow.summary, checkedAt: healthRow.checkedAt, notifiedAt: healthRow.notifiedAt } : null;
80336
80571
  const rank = { ok: 0, "never-synced": 1, warning: 2, stale: 3, failing: 4 };
80337
80572
  const healthState = health?.status === "fail" ? "failing" : health?.status === "warn" ? "warning" : "ok";
@@ -80351,7 +80586,7 @@ async function statusRoutes(app, opts) {
80351
80586
  if (request.query.problems === "true") result.projects = result.projects.map((item2) => ({ ...item2, integrations: item2.integrations.filter((row) => row.state !== "ok") }));
80352
80587
  return instanceStatusDtoSchema.parse(result);
80353
80588
  }
80354
- 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();
80355
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)) };
80356
80591
  for (const project of output.projects) {
80357
80592
  const key = project.state === "never-synced" ? "neverSynced" : project.state;
@@ -80363,8 +80598,8 @@ async function statusRoutes(app, opts) {
80363
80598
  }
80364
80599
 
80365
80600
  // ../api-routes/src/discovery/routes.ts
80366
- import crypto62 from "crypto";
80367
- 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";
80368
80603
  var MAX_INFLIGHT_DISCOVERY_AGE_MS = 2 * 60 * 60 * 1e3;
80369
80604
  async function discoveryRoutes(app, opts) {
80370
80605
  app.post("/projects/:name/discover/run", async (request, reply) => {
@@ -80399,12 +80634,12 @@ async function discoveryRoutes(app, opts) {
80399
80634
  const ageFloorIso = new Date(Date.now() - MAX_INFLIGHT_DISCOVERY_AGE_MS).toISOString();
80400
80635
  const decision = app.db.transaction((tx) => {
80401
80636
  const existing = tx.select({ id: discoverySessions.id, runId: discoverySessions.runId }).from(discoverySessions).where(and101(
80402
- eq120(discoverySessions.projectId, project.id),
80403
- eq120(discoverySessions.icpDescription, icpDescription),
80637
+ eq121(discoverySessions.projectId, project.id),
80638
+ eq121(discoverySessions.icpDescription, icpDescription),
80404
80639
  // Buyer is part of session identity: it changes the seed prompt's
80405
80640
  // semantics, so a request with a different (or no) buyer must start
80406
80641
  // its own session, never adopt another buyer's probes.
80407
- 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),
80408
80643
  // Locations are identity too: a different service-area subset seeds
80409
80644
  // and probes a different geo, so it must never reuse another geo's
80410
80645
  // session. resolveLocations is deterministic (project-config order),
@@ -80414,23 +80649,23 @@ async function discoveryRoutes(app, opts) {
80414
80649
  // locations a NULL row's subset is unknowable, so it conservatively
80415
80650
  // never reuses — a one-time, bounded (2h window) non-reuse after
80416
80651
  // upgrade, never a wrong reuse.
80417
- 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),
80418
80653
  // Seed provider set is identity: a different phrasing distribution
80419
80654
  // must never reuse another set's session. Null (= Gemini-only
80420
80655
  // default, including explicit ['gemini']) matches legacy rows.
80421
- seedProviders == null ? isNull20(discoverySessions.seedProviders) : eq120(discoverySessions.seedProviders, seedProviders),
80656
+ seedProviders == null ? isNull20(discoverySessions.seedProviders) : eq121(discoverySessions.seedProviders, seedProviders),
80422
80657
  inArray56(discoverySessions.status, [
80423
80658
  DiscoverySessionStatuses.queued,
80424
80659
  DiscoverySessionStatuses.seeding,
80425
80660
  DiscoverySessionStatuses.probing
80426
80661
  ]),
80427
80662
  gte33(discoverySessions.createdAt, ageFloorIso)
80428
- )).orderBy(desc55(discoverySessions.createdAt)).get();
80663
+ )).orderBy(desc56(discoverySessions.createdAt)).get();
80429
80664
  if (existing && existing.runId) {
80430
80665
  return { reused: true, sessionId: existing.id, runId: existing.runId };
80431
80666
  }
80432
- const sessionId = crypto62.randomUUID();
80433
- const runId = crypto62.randomUUID();
80667
+ const sessionId = crypto63.randomUUID();
80668
+ const runId = crypto63.randomUUID();
80434
80669
  tx.insert(discoverySessions).values({
80435
80670
  id: sessionId,
80436
80671
  projectId: project.id,
@@ -80494,7 +80729,7 @@ async function discoveryRoutes(app, opts) {
80494
80729
  const project = resolveProject(app.db, request.params.name);
80495
80730
  const parsedLimit = parseInt(request.query.limit ?? "", 10);
80496
80731
  const limit = Number.isNaN(parsedLimit) || parsedLimit <= 0 ? 50 : parsedLimit;
80497
- 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();
80498
80733
  return reply.send(rows.map(serializeSession));
80499
80734
  }
80500
80735
  );
@@ -80502,11 +80737,11 @@ async function discoveryRoutes(app, opts) {
80502
80737
  "/projects/:name/discover/sessions/:id",
80503
80738
  async (request, reply) => {
80504
80739
  const project = resolveProject(app.db, request.params.name);
80505
- 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();
80506
80741
  if (!session || session.projectId !== project.id) {
80507
80742
  throw notFound("Discovery session", request.params.id);
80508
80743
  }
80509
- 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();
80510
80745
  const detail = {
80511
80746
  ...serializeSession(session),
80512
80747
  probes: probeRows.map(serializeProbe)
@@ -80520,7 +80755,7 @@ async function discoveryRoutes(app, opts) {
80520
80755
  requireAdminSession(request);
80521
80756
  requirePaidReadScope(request, [], "Discovery harvest requires wildcard (*) API key scope because it can call the embedding provider.");
80522
80757
  const project = resolveProject(app.db, request.params.name);
80523
- 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();
80524
80759
  if (!session || session.projectId !== project.id) {
80525
80760
  throw notFound("Discovery session", request.params.id);
80526
80761
  }
@@ -80528,7 +80763,7 @@ async function discoveryRoutes(app, opts) {
80528
80763
  const minProbeHits = Number.isNaN(parsedFloor) || parsedFloor < 1 ? 1 : parsedFloor;
80529
80764
  const applyAnchor = request.query.anchor !== "false";
80530
80765
  const provider = session.seedProvider ?? "gemini";
80531
- 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();
80532
80767
  const extract = opts.harvestSearchQueries;
80533
80768
  const probesWithQueries = probeRows.map((row) => {
80534
80769
  if (!extract || !row.rawResponse) return { searchQueries: [] };
@@ -80539,7 +80774,7 @@ async function discoveryRoutes(app, opts) {
80539
80774
  return { searchQueries: [] };
80540
80775
  }
80541
80776
  });
80542
- 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);
80543
80778
  const anchorTerms = buildHarvestAnchorTerms(
80544
80779
  [session.icpDescription ?? "", ...trackedQueries],
80545
80780
  effectiveDomains(project)
@@ -80586,11 +80821,11 @@ async function discoveryRoutes(app, opts) {
80586
80821
  "/projects/:name/discover/sessions/:id/promote",
80587
80822
  async (request, reply) => {
80588
80823
  const project = resolveProject(app.db, request.params.name);
80589
- 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();
80590
80825
  if (!session || session.projectId !== project.id) {
80591
80826
  throw notFound("Discovery session", request.params.id);
80592
80827
  }
80593
- 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();
80594
80829
  const cited = /* @__PURE__ */ new Set();
80595
80830
  const aspirational = /* @__PURE__ */ new Set();
80596
80831
  const wasted = /* @__PURE__ */ new Set();
@@ -80625,7 +80860,7 @@ async function discoveryRoutes(app, opts) {
80625
80860
  );
80626
80861
  app.post("/projects/:name/discover/sessions/:id/promote", async (request, reply) => {
80627
80862
  const project = resolveProject(app.db, request.params.name);
80628
- 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();
80629
80864
  if (!session || session.projectId !== project.id) {
80630
80865
  throw notFound("Discovery session", request.params.id);
80631
80866
  }
@@ -80648,7 +80883,7 @@ async function discoveryRoutes(app, opts) {
80648
80883
  const bucketSet = new Set(buckets);
80649
80884
  const includeCompetitors = parsed.data.includeCompetitors ?? true;
80650
80885
  const competitorTypes = parsed.data.competitorTypes ?? DEFAULT_DISCOVERY_PROMOTE_COMPETITOR_TYPES;
80651
- 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();
80652
80887
  const candidateQueries = /* @__PURE__ */ new Set();
80653
80888
  for (const probe of probeRows) {
80654
80889
  if (!probe.bucket) continue;
@@ -80656,7 +80891,7 @@ async function discoveryRoutes(app, opts) {
80656
80891
  if (bucket.success && bucketSet.has(bucket.data)) candidateQueries.add(probe.query);
80657
80892
  }
80658
80893
  const existingQueries = new Set(
80659
- 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())
80660
80895
  );
80661
80896
  const promotedQueries = [];
80662
80897
  const skippedQueries = [];
@@ -80687,7 +80922,7 @@ async function discoveryRoutes(app, opts) {
80687
80922
  const marketNames = beginMarketNameWrite(tx, project.id);
80688
80923
  for (const query2 of promotedQueries) {
80689
80924
  tx.insert(queries).values({
80690
- id: crypto62.randomUUID(),
80925
+ id: crypto63.randomUUID(),
80691
80926
  projectId: project.id,
80692
80927
  query: query2,
80693
80928
  provenance,
@@ -80869,8 +81104,8 @@ function planCompetitorPromotion(input) {
80869
81104
  }
80870
81105
 
80871
81106
  // ../api-routes/src/discovery/orchestrate.ts
80872
- import crypto63 from "crypto";
80873
- import { eq as eq121 } from "drizzle-orm";
81107
+ import crypto64 from "crypto";
81108
+ import { eq as eq122 } from "drizzle-orm";
80874
81109
  var DEFAULT_MAX_PROBES = 100;
80875
81110
  var ABSOLUTE_MAX_PROBES = 500;
80876
81111
  function classifyProbeBucket(input) {
@@ -80956,7 +81191,7 @@ async function executeDiscovery(opts) {
80956
81191
  status: DiscoverySessionStatuses.seeding,
80957
81192
  dedupThreshold,
80958
81193
  startedAt
80959
- }).where(eq121(discoverySessions.id, opts.sessionId)).run();
81194
+ }).where(eq122(discoverySessions.id, opts.sessionId)).run();
80960
81195
  const seedResult = await opts.deps.seed({
80961
81196
  project: opts.project,
80962
81197
  icpDescription: opts.icpDescription,
@@ -81017,7 +81252,7 @@ async function executeDiscovery(opts) {
81017
81252
  dedupBandPairFraction: dedupStats.bandPairFraction,
81018
81253
  dedupPairsTotal: dedupStats.pairsTotal,
81019
81254
  warning
81020
- }).where(eq121(discoverySessions.id, opts.sessionId)).run();
81255
+ }).where(eq122(discoverySessions.id, opts.sessionId)).run();
81021
81256
  const probeLocation = opts.locations?.[0];
81022
81257
  const probeResults = await mapWithConcurrency(
81023
81258
  probedCanonicals,
@@ -81036,7 +81271,7 @@ async function executeDiscovery(opts) {
81036
81271
  probeRows.push({ citedDomains: probe.citedDomains, bucket });
81037
81272
  buckets[bucket]++;
81038
81273
  return {
81039
- id: crypto63.randomUUID(),
81274
+ id: crypto64.randomUUID(),
81040
81275
  sessionId: opts.sessionId,
81041
81276
  projectId: opts.project.id,
81042
81277
  query: probedCanonicals[index],
@@ -81071,7 +81306,7 @@ async function executeDiscovery(opts) {
81071
81306
  wastedCount: buckets["wasted-surface"],
81072
81307
  competitorMap,
81073
81308
  finishedAt: (/* @__PURE__ */ new Date()).toISOString()
81074
- }).where(eq121(discoverySessions.id, opts.sessionId)).run();
81309
+ }).where(eq122(discoverySessions.id, opts.sessionId)).run();
81075
81310
  upsertDomainClassifications(opts.db, opts.project.id, opts.sessionId, competitorMap);
81076
81311
  return {
81077
81312
  buckets,
@@ -81088,7 +81323,7 @@ function upsertDomainClassifications(db, projectId, sessionId, competitorMap) {
81088
81323
  const domain = hostOf(entry.domain) ?? "";
81089
81324
  if (!domain) continue;
81090
81325
  db.insert(domainClassifications).values({
81091
- id: crypto63.randomUUID(),
81326
+ id: crypto64.randomUUID(),
81092
81327
  projectId,
81093
81328
  domain,
81094
81329
  competitorType: entry.competitorType,
@@ -81111,7 +81346,7 @@ function markSessionFailed(db, sessionId, error) {
81111
81346
  status: DiscoverySessionStatuses.failed,
81112
81347
  error,
81113
81348
  finishedAt: (/* @__PURE__ */ new Date()).toISOString()
81114
- }).where(eq121(discoverySessions.id, sessionId)).run();
81349
+ }).where(eq122(discoverySessions.id, sessionId)).run();
81115
81350
  }
81116
81351
  function dedupeStrings(input) {
81117
81352
  const seen2 = /* @__PURE__ */ new Set();
@@ -81128,7 +81363,7 @@ function dedupeStrings(input) {
81128
81363
  }
81129
81364
 
81130
81365
  // ../api-routes/src/trends.ts
81131
- 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";
81132
81367
  function parseSurface(value) {
81133
81368
  const parsed = trendSurfaceSchema.safeParse(value);
81134
81369
  if (!parsed.success) {
@@ -81184,8 +81419,8 @@ async function trendsRoutes(app) {
81184
81419
  function readSurface(app, projectId, surface) {
81185
81420
  switch (surface) {
81186
81421
  case TrendSurfaces["index-coverage"]: {
81187
- 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();
81188
- 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();
81189
81424
  const coverage = (key, label, rows) => ({
81190
81425
  key,
81191
81426
  label,
@@ -81197,7 +81432,7 @@ function readSurface(app, projectId, surface) {
81197
81432
  return [coverage("google", "Google", google), coverage("bing", "Bing", bing)];
81198
81433
  }
81199
81434
  case TrendSurfaces["site-health"]: {
81200
- 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();
81201
81436
  return [{
81202
81437
  key: "site-health",
81203
81438
  label: "Agent Readiness",
@@ -81209,7 +81444,7 @@ function readSurface(app, projectId, surface) {
81209
81444
  }
81210
81445
  case TrendSurfaces.backlinks: {
81211
81446
  const totals = computeFilteredReleaseTotals(app.db, projectId, BacklinkSources.commoncrawl);
81212
- 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) => {
81213
81448
  const filtered = totals.get(row.release);
81214
81449
  const known = (filtered?.domainRows ?? 0) > 0 || row.totalLinkingDomains === 0;
81215
81450
  const windowEnd = releaseWindowEndMonth(row.release);
@@ -81237,9 +81472,9 @@ function readSurface(app, projectId, surface) {
81237
81472
  }
81238
81473
 
81239
81474
  // ../api-routes/src/research.ts
81240
- import crypto64 from "crypto";
81475
+ import crypto65 from "crypto";
81241
81476
  import { z as z7 } from "zod";
81242
- 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";
81243
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;
81244
81479
  var BATCH_RECEIPT_PREFIX = "__canonry_research_batch__:";
81245
81480
  async function researchRoutes(app, opts) {
@@ -81258,7 +81493,7 @@ async function researchRoutes(app, opts) {
81258
81493
  const input = parsed.data;
81259
81494
  if (input.idempotencyKey?.startsWith(BATCH_RECEIPT_PREFIX)) throw validationError("This idempotency key prefix is reserved for internal research batch receipts.");
81260
81495
  const requestHash2 = directResearchRequestHash(input);
81261
- 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;
81262
81497
  if (existingReceipt) {
81263
81498
  assertSameDirectResearchRequest(existingReceipt, input, requestHash2);
81264
81499
  const result2 = getDetail(app, project.id, existingReceipt.id);
@@ -81293,7 +81528,7 @@ async function researchRoutes(app, opts) {
81293
81528
  const initiatedBy = researchPrincipal(request);
81294
81529
  const decision = app.db.transaction((tx) => {
81295
81530
  if (input.idempotencyKey) {
81296
- 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();
81297
81532
  if (existing) {
81298
81533
  assertSameDirectResearchRequest(existing, input, requestHash2);
81299
81534
  return { reused: true, id: existing.id, shouldDispatch: existing.status === ResearchRunStatuses.queued };
@@ -81302,18 +81537,18 @@ async function researchRoutes(app, opts) {
81302
81537
  if (initiatedBy?.limited) {
81303
81538
  const { start, end, date } = utcDayBounds(now);
81304
81539
  const used = tx.select({ value: count10() }).from(researchRuns).where(and103(
81305
- eq123(researchRuns.projectId, project.id),
81540
+ eq124(researchRuns.projectId, project.id),
81306
81541
  gte34(researchRuns.createdAt, start),
81307
81542
  lt21(researchRuns.createdAt, end),
81308
- 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)`
81309
81544
  )).get()?.value ?? 0;
81310
81545
  if (used >= viewerDailyRunLimit) {
81311
81546
  throw researchDailyLimitExceeded(project.name, viewerDailyRunLimit, date);
81312
81547
  }
81313
81548
  }
81314
- const id = crypto64.randomUUID();
81549
+ const id = crypto65.randomUUID();
81315
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();
81316
- 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();
81317
81552
  writeAuditLog(tx, { projectId: project.id, actor: "api", action: "research.created", entityType: "research_run", entityId: id });
81318
81553
  return { reused: false, id, shouldDispatch: true };
81319
81554
  });
@@ -81334,14 +81569,14 @@ async function researchRoutes(app, opts) {
81334
81569
  const requestHash2 = researchBatchRequestHash(input);
81335
81570
  const receiptKeys = input.runs.map((_run, index) => batchChildReceiptKey(input.idempotencyKey, index));
81336
81571
  const firstReceipt = app.db.select().from(researchRuns).where(and103(
81337
- eq123(researchRuns.projectId, project.id),
81338
- eq123(researchRuns.idempotencyKey, receiptKeys[0])
81572
+ eq124(researchRuns.projectId, project.id),
81573
+ eq124(researchRuns.idempotencyKey, receiptKeys[0])
81339
81574
  )).get();
81340
81575
  if (firstReceipt) {
81341
81576
  if (firstReceipt.requestHash !== requestHash2) throw alreadyExists("Research batch idempotency key", input.idempotencyKey);
81342
81577
  const saved = receiptKeys.map((key) => app.db.select().from(researchRuns).where(and103(
81343
- eq123(researchRuns.projectId, project.id),
81344
- eq123(researchRuns.idempotencyKey, key)
81578
+ eq124(researchRuns.projectId, project.id),
81579
+ eq124(researchRuns.idempotencyKey, key)
81345
81580
  )).get());
81346
81581
  if (saved.some((row) => !row || row.requestHash !== requestHash2)) throw alreadyExists("Research batch idempotency key", input.idempotencyKey);
81347
81582
  const runs3 = saved.map((row) => getDetail(app, project.id, row.id));
@@ -81358,16 +81593,16 @@ async function researchRoutes(app, opts) {
81358
81593
  if (initiatedBy?.limited) {
81359
81594
  const { start, end, date } = utcDayBounds(now);
81360
81595
  const used = tx.select({ value: count10() }).from(researchRuns).where(and103(
81361
- eq123(researchRuns.projectId, project.id),
81596
+ eq124(researchRuns.projectId, project.id),
81362
81597
  gte34(researchRuns.createdAt, start),
81363
81598
  lt21(researchRuns.createdAt, end),
81364
- 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)`
81365
81600
  )).get()?.value ?? 0;
81366
81601
  if (used + prepared.length > viewerDailyRunLimit) throw researchDailyLimitExceeded(project.name, viewerDailyRunLimit, date);
81367
81602
  }
81368
81603
  const ids = [];
81369
81604
  for (const [index, run] of prepared.entries()) {
81370
- const id = crypto64.randomUUID();
81605
+ const id = crypto65.randomUUID();
81371
81606
  ids.push(id);
81372
81607
  tx.insert(researchRuns).values({
81373
81608
  id,
@@ -81386,7 +81621,7 @@ async function researchRoutes(app, opts) {
81386
81621
  createdAt: now
81387
81622
  }).run();
81388
81623
  for (const [position, query2] of run.input.queries.entries()) tx.insert(researchRunQueries).values({
81389
- id: crypto64.randomUUID(),
81624
+ id: crypto65.randomUUID(),
81390
81625
  researchRunId: id,
81391
81626
  position,
81392
81627
  queryText: query2,
@@ -81413,9 +81648,9 @@ async function researchRoutes(app, opts) {
81413
81648
  const limit = Number.isInteger(requested) && requested > 0 ? Math.min(requested, 100) : 20;
81414
81649
  const cursor = request.query.cursor ? parseResearchCursor(request.query.cursor, project.id) : null;
81415
81650
  const rows = app.db.select().from(researchRuns).where(and103(
81416
- eq123(researchRuns.projectId, project.id),
81417
- cursor ? or22(lt21(researchRuns.createdAt, cursor.createdAt), and103(eq123(researchRuns.createdAt, cursor.createdAt), lt21(researchRuns.id, cursor.id))) : void 0
81418
- )).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();
81419
81654
  const runs2 = rows.slice(0, limit).map(serializeRun);
81420
81655
  const last = runs2.at(-1);
81421
81656
  const nextCursor = rows.length > limit && last ? Buffer.from(JSON.stringify({ projectId: project.id, createdAt: last.createdAt, id: last.id })).toString("base64url") : null;
@@ -81467,7 +81702,7 @@ function researchProjectProviders(app, projectId, projectProviders) {
81467
81702
  var DIRECT_REQUEST_HASH_VERSION = "direct-v2:";
81468
81703
  function directResearchRequestHash(input) {
81469
81704
  const { idempotencyKey: _key, ...request } = input;
81470
- 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");
81471
81706
  }
81472
81707
  function assertSameDirectResearchRequest(existing, input, hash3) {
81473
81708
  if (existing.requestHash?.startsWith(DIRECT_REQUEST_HASH_VERSION)) {
@@ -81485,7 +81720,7 @@ function assertSameDirectResearchRequest(existing, input, hash3) {
81485
81720
  ...scope ? { scope } : {},
81486
81721
  ...template ? { template } : {}
81487
81722
  };
81488
- 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);
81489
81724
  }
81490
81725
  var researchCursorSchema = z7.object({ projectId: z7.string().min(1), createdAt: z7.string().datetime({ offset: true }), id: z7.string().min(1).max(256) }).strict();
81491
81726
  function parseResearchCursor(value, projectId) {
@@ -81505,11 +81740,11 @@ function resolveStoredResearchScope(stored, selection, idempotencyKey) {
81505
81740
  return stored;
81506
81741
  }
81507
81742
  function batchChildReceiptKey(rootKey, index) {
81508
- const derived = crypto64.createHash("sha256").update(`${rootKey}\0${index}`).digest("hex");
81743
+ const derived = crypto65.createHash("sha256").update(`${rootKey}\0${index}`).digest("hex");
81509
81744
  return `${BATCH_RECEIPT_PREFIX}${derived}:${index}`;
81510
81745
  }
81511
81746
  function researchBatchRequestHash(input) {
81512
- 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");
81513
81748
  }
81514
81749
  function prepareBatchRun(app, opts, project, active, input) {
81515
81750
  const adapters = opts.providerAdapters ?? [];
@@ -81565,8 +81800,8 @@ function resolveStoredResearchTemplate(stored, selection, idempotencyKey) {
81565
81800
  }
81566
81801
  function resolveResearchTemplate(app, projectId, selection, scope, location) {
81567
81802
  const savedTemplate = app.db.select().from(measurementQueryTemplates).where(and103(
81568
- eq123(measurementQueryTemplates.projectId, projectId),
81569
- eq123(measurementQueryTemplates.id, selection.templateId)
81803
+ eq124(measurementQueryTemplates.projectId, projectId),
81804
+ eq124(measurementQueryTemplates.id, selection.templateId)
81570
81805
  )).get();
81571
81806
  if (!savedTemplate) throw validationError("Unknown or stale research template. Reload the selected template and try again.");
81572
81807
  const templateVersion = savedTemplate.updatedAt;
@@ -81575,7 +81810,7 @@ function resolveResearchTemplate(app, projectId, selection, scope, location) {
81575
81810
  }
81576
81811
  const bindingLocation = selection.bindingLocation === void 0 ? location : selection.bindingLocation;
81577
81812
  if (bindingLocation) {
81578
- 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();
81579
81814
  if (!project.locations.some((item2) => sameLocation(item2, bindingLocation))) throw validationError("Research template binding location must match a configured project location.");
81580
81815
  }
81581
81816
  const { bindings, output } = expandResearchTemplate(savedTemplate, scope, bindingLocation);
@@ -81588,9 +81823,9 @@ function classifyResearchQueries(project, plan, queries2) {
81588
81823
  return queries2.map((query2) => classifier?.classify(query2) ?? null);
81589
81824
  }
81590
81825
  function getDetail(app, projectId, id) {
81591
- 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();
81592
81827
  if (!row) throw notFound("Research run", id);
81593
- 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));
81594
81829
  return { ...serializeRun(row), queries: queries2 };
81595
81830
  }
81596
81831
  function serializeRun(row) {
@@ -81650,8 +81885,8 @@ function utcDayBounds(now) {
81650
81885
  }
81651
81886
 
81652
81887
  // ../api-routes/src/simple-measurement-definitions.ts
81653
- import crypto65 from "crypto";
81654
- 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";
81655
81890
  function captureSimpleMeasurementDefinition(db, input) {
81656
81891
  return db.transaction((tx) => {
81657
81892
  const run = tx.select({
@@ -81659,7 +81894,7 @@ function captureSimpleMeasurementDefinition(db, input) {
81659
81894
  trigger: runs.trigger,
81660
81895
  status: runs.status,
81661
81896
  measurementPlanVersionId: runs.measurementPlanVersionId
81662
- }).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();
81663
81898
  if (!run) throw notFound("Run", input.runId);
81664
81899
  if (run.kind !== RunKinds["answer-visibility"] || run.trigger === RunTriggers.probe || run.measurementPlanVersionId !== null) {
81665
81900
  return null;
@@ -81680,7 +81915,7 @@ function captureSimpleMeasurementDefinition(db, input) {
81680
81915
  throw validationError("Qualified aliases must be a sorted subset of the captured aliases.");
81681
81916
  }
81682
81917
  }
81683
- 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();
81684
81919
  if (existing) {
81685
81920
  const frozen = simpleMeasurementDefinitionSchema.parse(existing.definition);
81686
81921
  const { qualifiedAliases: _liveQualifiedAliases, ...liveIdentity } = definition2.identity;
@@ -81692,11 +81927,11 @@ function captureSimpleMeasurementDefinition(db, input) {
81692
81927
  ...frozen.identity.qualifiedAliases?.length ? { qualifiedAliases: frozen.identity.qualifiedAliases } : {}
81693
81928
  }
81694
81929
  };
81695
- const replayChecksum = crypto65.createHash("sha256").update(canonicalSimpleMeasurementDefinitionJson(replayDefinition)).digest("hex");
81930
+ const replayChecksum = crypto66.createHash("sha256").update(canonicalSimpleMeasurementDefinitionJson(replayDefinition)).digest("hex");
81696
81931
  if (existing.checksum !== replayChecksum) {
81697
81932
  if (frozen.competitors === void 0) {
81698
81933
  const { competitors: _currentCompetitors, ...legacyReplayDefinition } = replayDefinition;
81699
- const legacyReplayChecksum = crypto65.createHash("sha256").update(canonicalSimpleMeasurementDefinitionJson(legacyReplayDefinition)).digest("hex");
81934
+ const legacyReplayChecksum = crypto66.createHash("sha256").update(canonicalSimpleMeasurementDefinitionJson(legacyReplayDefinition)).digest("hex");
81700
81935
  if (existing.checksum === legacyReplayChecksum) return frozen;
81701
81936
  }
81702
81937
  throw validationError("This run already has a captured measurement definition. Start a new run for changed inputs.");
@@ -81706,21 +81941,21 @@ function captureSimpleMeasurementDefinition(db, input) {
81706
81941
  if (run.status !== RunStatuses.running) {
81707
81942
  throw validationError("Only a running run can capture a new measurement definition.");
81708
81943
  }
81709
- 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()) {
81710
81945
  throw validationError("This run already has stored answers. Its measurement definition cannot be inferred afterward.");
81711
81946
  }
81712
- 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));
81713
81948
  if (definition2.queries.some((query2) => !projectQueryIds.has(query2.queryId))) {
81714
81949
  throw validationError("Every captured query must belong to the run project.");
81715
81950
  }
81716
81951
  if (definition2.competitors !== void 0) {
81717
- 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));
81718
81953
  const capturedDomains = new Set(definition2.competitors.map((competitor) => competitor.domain));
81719
81954
  if (liveCompetitorDomains.size !== capturedDomains.size || [...liveCompetitorDomains].some((domain) => !capturedDomains.has(domain))) {
81720
81955
  throw validationError("Captured competitors must exactly match the project competitors dispatched for this run.");
81721
81956
  }
81722
81957
  }
81723
- const checksum = crypto65.createHash("sha256").update(canonicalSimpleMeasurementDefinitionJson(definition2)).digest("hex");
81958
+ const checksum = crypto66.createHash("sha256").update(canonicalSimpleMeasurementDefinitionJson(definition2)).digest("hex");
81724
81959
  tx.insert(simpleMeasurementDefinitions).values({
81725
81960
  projectId: input.projectId,
81726
81961
  runId: input.runId,