@canonry/canonry 7.118.2 → 7.119.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/assets/assets/{AccessControls-Dw14Y8Zb.js → AccessControls-D9u5mHZy.js} +1 -1
  2. package/assets/assets/{AgentSetupPage-QCAFqYqz.js → AgentSetupPage-sxobNnR4.js} +1 -1
  3. package/assets/assets/{AuditHistoryPanel-C06iViSe.js → AuditHistoryPanel-B-br1Rgm.js} +1 -1
  4. package/assets/assets/{BacklinksPage-CJqWfjy1.js → BacklinksPage-DBncT_in.js} +1 -1
  5. package/assets/assets/{ChartPrimitives-DBTchs1y.js → ChartPrimitives-BVl_On4G.js} +1 -1
  6. package/assets/assets/{HistoryPage-Dif-fQuy.js → HistoryPage-DLzXIHGd.js} +1 -1
  7. package/assets/assets/{MeasurementPropertyPage-BJFfATTB.js → MeasurementPropertyPage-C2RXn2iP.js} +1 -1
  8. package/assets/assets/ProjectPage-CUGvozZu.js +15 -0
  9. package/assets/assets/{RunsPage-DUnwiusE.js → RunsPage-CGdstDkz.js} +1 -1
  10. package/assets/assets/{ServerTrafficSection-CBCczz52.js → ServerTrafficSection-DsmN-vR2.js} +3 -3
  11. package/assets/assets/{SettingsPage-BQRQYuJ9.js → SettingsPage-DAnYQBff.js} +1 -1
  12. package/assets/assets/{ToneBadge-CViol5aK.js → ToneBadge-BCQPh7t2.js} +1 -1
  13. package/assets/assets/{TrafficPage-jtQlqa0x.js → TrafficPage-HQMcIXhQ.js} +1 -1
  14. package/assets/assets/{TrafficSourceDetailPage-8p8kPet2.js → TrafficSourceDetailPage-BXQX0fyG.js} +1 -1
  15. package/assets/assets/{account-context-B1G3xhE1.js → account-context-BNo2KFA7.js} +1 -1
  16. package/assets/assets/{agent-trust-copy-CMgWNJn0.js → agent-trust-copy-B3Dw_M_3.js} +1 -1
  17. package/assets/assets/{card-B8kjwkFR.js → card-h-mmYzMc.js} +1 -1
  18. package/assets/assets/{index-DxNmD1SS.js → index-DpBLjU4G.js} +3 -3
  19. package/assets/assets/{preload-helper-DzM601DW.js → preload-helper-D2o-5DDv.js} +1 -1
  20. package/assets/assets/{query-client-3W7wQep0.js → query-client-gk-fhrrc.js} +1 -1
  21. package/assets/assets/{react-query-B0EpSPOn.js → react-query-hUdNgz2a.js} +1 -1
  22. package/assets/assets/{react-sigma_core.esm.min-DWNI6FGP.js → react-sigma_core.esm.min-CbMudrIV.js} +1 -1
  23. package/assets/assets/{server-traffic-D6FWsQIv.js → server-traffic-CL5cYldZ.js} +1 -1
  24. package/assets/assets/{service-Cy2ZA98R.js → service-CxbxBFUX.js} +1 -1
  25. package/assets/index.html +9 -9
  26. package/dist/{ads-BJCFT2N7.js → ads-PMDSTHUC.js} +4 -4
  27. package/dist/{agent-KJ5C5BUZ.js → agent-5EL5AECW.js} +8 -8
  28. package/dist/{agent-ask-RP2FZIWH.js → agent-ask-VAZUSWFA.js} +4 -4
  29. package/dist/{agent-conversations-N6PJOOJG.js → agent-conversations-KOBHBQS6.js} +4 -4
  30. package/dist/{agent-journeys-XK3AXOZZ.js → agent-journeys-Q5J6K76M.js} +4 -4
  31. package/dist/{agent-memory-RKHE5BVJ.js → agent-memory-UTZWNL5K.js} +4 -4
  32. package/dist/{agent-providers-G2WHCA5Y.js → agent-providers-TBMKTIJT.js} +4 -4
  33. package/dist/{agent-transcript-SSRB4KHV.js → agent-transcript-4MIMLCSN.js} +4 -4
  34. package/dist/{analytics-QAKMM34E.js → analytics-VGPQ3P7U.js} +4 -4
  35. package/dist/{apply-6IYX6MC6.js → apply-AL52P3BT.js} +4 -4
  36. package/dist/{backfill-PRLYAK63.js → backfill-XBQYJBCL.js} +11 -11
  37. package/dist/{backlinks-G52LSPEQ.js → backlinks-T5ZWICGA.js} +4 -4
  38. package/dist/{bing-OULTQLAJ.js → bing-DFU4M6P2.js} +4 -4
  39. package/dist/{bootstrap-OATKSLBT.js → bootstrap-VBGDPCJ4.js} +11 -11
  40. package/dist/{cdp-NVM5IFD2.js → cdp-WHDGSGRE.js} +8 -8
  41. package/dist/{chunk-G2IJGOVF.js → chunk-2FNWSHOE.js} +3 -3
  42. package/dist/{chunk-3MGALUWM.js → chunk-3N2MSPPU.js} +2 -2
  43. package/dist/{chunk-552V4T75.js → chunk-3Q2D53KV.js} +1 -1
  44. package/dist/{chunk-U2GFFMHS.js → chunk-3QOFLP4W.js} +5 -5
  45. package/dist/{chunk-3JHLIEOY.js → chunk-47Y5UAYA.js} +2 -2
  46. package/dist/{chunk-PPIXSQNM.js → chunk-5KINLLTJ.js} +4 -4
  47. package/dist/{chunk-3QFIBU25.js → chunk-5QNFX55U.js} +347 -307
  48. package/dist/{chunk-TVU3SGB3.js → chunk-6KH4XZLA.js} +1 -1
  49. package/dist/{chunk-AABZZA7S.js → chunk-7R6I6AIP.js} +8 -8
  50. package/dist/{chunk-T6ILJ2FW.js → chunk-AHVF5OE5.js} +2 -2
  51. package/dist/{chunk-R6SX4KC6.js → chunk-AOD35IKL.js} +1 -1
  52. package/dist/{chunk-ATHSMFDP.js → chunk-AOYSK6D2.js} +2 -2
  53. package/dist/{chunk-H5LYOND2.js → chunk-BD24MSOA.js} +22 -22
  54. package/dist/{chunk-K7BPL2BY.js → chunk-EZOBUXLP.js} +3 -3
  55. package/dist/{chunk-KV5I5RJ3.js → chunk-FTPGW2WX.js} +2 -2
  56. package/dist/{chunk-RJDIAWNE.js → chunk-GDRZPBPF.js} +2 -2
  57. package/dist/{chunk-BTM2WKQL.js → chunk-GVU4QOUA.js} +5 -5
  58. package/dist/{chunk-G4NYHN56.js → chunk-HFNLWW3Z.js} +1 -1
  59. package/dist/{chunk-WHFZQMDU.js → chunk-HODKOOJZ.js} +369 -369
  60. package/dist/{chunk-MUE2JCK7.js → chunk-IPOERWGQ.js} +5 -5
  61. package/dist/{chunk-QP7S34UT.js → chunk-IWQFTZ75.js} +1 -1
  62. package/dist/{chunk-43QG3FYE.js → chunk-J4FMWPEM.js} +3 -3
  63. package/dist/{chunk-KWLCI5HP.js → chunk-N5N4TXBD.js} +4 -4
  64. package/dist/{chunk-UZBV2MFC.js → chunk-NQFBIMS4.js} +2 -2
  65. package/dist/{chunk-QM37PRXI.js → chunk-OO4RE44D.js} +1 -1
  66. package/dist/{chunk-J2JJFHAM.js → chunk-OXYZQJLV.js} +1 -1
  67. package/dist/{chunk-AR2AXWZC.js → chunk-QCXKLTVC.js} +4 -4
  68. package/dist/{chunk-25KN55WQ.js → chunk-RLLYGXNA.js} +4 -4
  69. package/dist/{chunk-7QFB2AI4.js → chunk-TS477DBZ.js} +2 -2
  70. package/dist/{chunk-4O5ZWHZ4.js → chunk-TTQBEFSU.js} +1 -1
  71. package/dist/{chunk-4INTWV22.js → chunk-UA7WWHPW.js} +6 -6
  72. package/dist/{chunk-YB7QBOA6.js → chunk-VCXKSGZF.js} +1 -1
  73. package/dist/{chunk-7CXUZI6H.js → chunk-VOK62VGC.js} +27 -9
  74. package/dist/{chunk-JMYX2YJ3.js → chunk-WVZR3J7X.js} +4 -4
  75. package/dist/{chunk-6WBIJWKO.js → chunk-XTR3KSV2.js} +1 -1
  76. package/dist/{chunk-2M37UZGH.js → chunk-ZCRUXUHU.js} +4 -4
  77. package/dist/{chunk-ZTN2BG4D.js → chunk-ZDYWXTNN.js} +4 -4
  78. package/dist/{citations-7ZI2SULG.js → citations-JOM2DJX3.js} +5 -5
  79. package/dist/{cli-catalog-RO57BEAG.js → cli-catalog-4ZCK2TFK.js} +4 -4
  80. package/dist/cli-commands-SZYTLQU4.js +18 -0
  81. package/dist/cli.js +14 -14
  82. package/dist/{competitor-PAILSWRL.js → competitor-FQH7LNR2.js} +4 -4
  83. package/dist/{content-VNVROYY3.js → content-KEZJJEV2.js} +4 -4
  84. package/dist/{dashboard-5WAAR33F.js → dashboard-IWBIZR3V.js} +7 -7
  85. package/dist/{demo-QD55GHC7.js → demo-2P37KIQK.js} +3 -3
  86. package/dist/{demo-server-KMJC4TWS.js → demo-server-6OQXQ7C3.js} +13 -13
  87. package/dist/{discover-Y4OYY55Y.js → discover-ZB6I2A65.js} +5 -5
  88. package/dist/{discover-eval-DZGZH6ED.js → discover-eval-XXRA3XDQ.js} +4 -4
  89. package/dist/{doctor-7BOKC4J6.js → doctor-KTGY5L57.js} +4 -4
  90. package/dist/{evidence-RIJWDHZR.js → evidence-BEBTLKK4.js} +4 -4
  91. package/dist/{export-cmd-J4LZ5GSD.js → export-cmd-VIQGUL7N.js} +4 -4
  92. package/dist/{ga-IEY3C76P.js → ga-YEQKHEN2.js} +4 -4
  93. package/dist/{gbp-OP7B6R6Z.js → gbp-NFTRCNGZ.js} +4 -4
  94. package/dist/{google-G7MNB3XJ.js → google-MBQW2EGU.js} +5 -5
  95. package/dist/{google-marketing-7562CCEM.js → google-marketing-KIGW7ZGN.js} +2 -2
  96. package/dist/{health-cmd-INJ5FWJ7.js → health-cmd-6B6VSAX3.js} +5 -5
  97. package/dist/{history-34NHNH4B.js → history-DX2QSPL2.js} +4 -4
  98. package/dist/index.d.ts +18 -18
  99. package/dist/index.js +26 -26
  100. package/dist/{init-QKAAFP7Z.js → init-NJAZR6MI.js} +13 -13
  101. package/dist/{insights-TPITCFIE.js → insights-ZJD3KUA7.js} +4 -4
  102. package/dist/intelligence-service-PJAISWKW.js +15 -0
  103. package/dist/{journeys-AGSHRJVG.js → journeys-E4FC7PCM.js} +4 -4
  104. package/dist/{keys-ZGA5ZBFE.js → keys-TD6NBRRY.js} +4 -4
  105. package/dist/{keyword-XQA6K462.js → keyword-FEOQSKMZ.js} +4 -4
  106. package/dist/{logs-D2HPGLMI.js → logs-YV5JPJH3.js} +4 -4
  107. package/dist/{mcp-UKYWUOA6.js → mcp-S3YNKUQQ.js} +5 -5
  108. package/dist/mcp.js +10 -10
  109. package/dist/{measurement-plan-3S2BV34R.js → measurement-plan-VVDLIBQO.js} +6 -6
  110. package/dist/{notify-PKXIBY2X.js → notify-GUJ6PLRU.js} +4 -4
  111. package/dist/{organic-evidence-6WAJC7CC.js → organic-evidence-A66B5BWS.js} +4 -4
  112. package/dist/{overview-YIMXGGQC.js → overview-JKW5LARL.js} +6 -6
  113. package/dist/{project-WNMIV5OV.js → project-XUYBPKWJ.js} +4 -4
  114. package/dist/{project-setup-OSAJFEWF.js → project-setup-YO6R26JG.js} +4 -4
  115. package/dist/{query-GN654GYL.js → query-YOTYGF4K.js} +4 -4
  116. package/dist/{research-HR67DZJE.js → research-QVG5XZDF.js} +4 -4
  117. package/dist/{results-export-CNAAOWQX.js → results-export-4TMA6DJT.js} +4 -4
  118. package/dist/{run-M7F6BMTH.js → run-HGYYDS6S.js} +6 -6
  119. package/dist/{schedule-LKGWXMPF.js → schedule-RR6OUMKT.js} +4 -4
  120. package/dist/{search-MRWOL2M3.js → search-KO7PIUMR.js} +4 -4
  121. package/dist/{serve-YR2A6YGF.js → serve-FQFTGJ2Y.js} +27 -27
  122. package/dist/{session-JSZLON4Q.js → session-GVLHMMVC.js} +14 -14
  123. package/dist/{settings-O2TJKLTN.js → settings-HDENU4PV.js} +4 -4
  124. package/dist/{sitemaps-35MYNHN6.js → sitemaps-GTHH2RP3.js} +4 -4
  125. package/dist/{skills-CNUBIGXM.js → skills-U3MDHCWF.js} +3 -3
  126. package/dist/{snapshot-G67JDGMY.js → snapshot-SWFUS4D2.js} +4 -4
  127. package/dist/{src-T2CVI44I.js → src-R74K2NOZ.js} +2 -2
  128. package/dist/{status-EBOPJY3L.js → status-ACUIXSLV.js} +6 -6
  129. package/dist/{support-Q735EEZ7.js → support-3IFWJF3E.js} +2 -2
  130. package/dist/{technical-aeo-N4WO2GSS.js → technical-aeo-NWE56UCG.js} +4 -4
  131. package/dist/{telemetry-CAZH47YY.js → telemetry-CHW3LG5A.js} +5 -5
  132. package/dist/{tools-FCS5X36N.js → tools-LAIZGKA3.js} +12 -12
  133. package/dist/{traffic-G3UAF52O.js → traffic-MHCGXV2V.js} +6 -6
  134. package/dist/{trends-JEQCIQZU.js → trends-5IEV52XW.js} +4 -4
  135. package/dist/{users-5QFNLFVU.js → users-KRY5MKJ4.js} +4 -4
  136. package/dist/{visibility-stats-MQLGIZEM.js → visibility-stats-JF3SXXKS.js} +5 -5
  137. package/dist/{wordpress-NMLL7F6A.js → wordpress-TV2NSQPK.js} +4 -4
  138. package/package.json +1 -1
  139. package/assets/assets/ProjectPage-CFe_NEmJ.js +0 -15
  140. package/dist/cli-commands-23N5ZW76.js +0 -18
  141. package/dist/intelligence-service-3ZR7CGWF.js +0 -15
@@ -19,14 +19,14 @@ import {
19
19
  normalizeTrafficPathPattern,
20
20
  sessionizeJourneyRequests,
21
21
  verifyRequestSignature
22
- } from "./chunk-552V4T75.js";
22
+ } from "./chunk-3Q2D53KV.js";
23
23
  import {
24
24
  currentOutcomeAttribution,
25
25
  getRequestContext,
26
26
  registerRequestContext,
27
27
  requestAuditIdentity,
28
28
  sanitizeRequestContext
29
- } from "./chunk-4O5ZWHZ4.js";
29
+ } from "./chunk-TTQBEFSU.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-YB7QBOA6.js";
193
+ } from "./chunk-VCXKSGZF.js";
194
194
  import {
195
195
  ADS_ACTIVATE_SCOPE,
196
196
  ADS_ACTIVATION_ABSOLUTE_MAX_ENTITIES,
@@ -1390,7 +1390,7 @@ import {
1390
1390
  wordpressSchemaDeployResultDtoSchema,
1391
1391
  wordpressSchemaStatusResultDtoSchema,
1392
1392
  wordpressStatusDtoSchema
1393
- } from "./chunk-7CXUZI6H.js";
1393
+ } from "./chunk-VOK62VGC.js";
1394
1394
 
1395
1395
  // ../api-routes/src/user-session.ts
1396
1396
  import crypto2 from "crypto";
@@ -70863,7 +70863,40 @@ async function backlinksRoutes(app, opts) {
70863
70863
  import crypto62 from "crypto";
70864
70864
  import { isIP as isIP3 } from "net";
70865
70865
  import { isDeepStrictEqual } from "util";
70866
- import { and as and91, desc as desc49, eq as eq106, gt as gt8, gte as gte27, inArray as inArray50, lt as lt20, lte as lte27, sql as sql48 } from "drizzle-orm";
70866
+ import { and as and92, desc as desc49, eq as eq107, gt as gt8, gte as gte27, inArray as inArray50, lt as lt20, lte as lte27, sql as sql48 } from "drizzle-orm";
70867
+
70868
+ // ../api-routes/src/traffic-recording.ts
70869
+ import { and as and90, eq as eq104, notInArray as notInArray3 } from "drizzle-orm";
70870
+ function isCloudflareDirectPush(source) {
70871
+ if (source.sourceType !== TrafficSourceTypes.cloudflare) return false;
70872
+ const deliveryMode = source.configJson.deliveryMode;
70873
+ return deliveryMode === void 0 || deliveryMode === CloudflareTrafficDeliveryModes["direct-push"];
70874
+ }
70875
+ function trafficRecordedThrough(db, projectId, sourceId) {
70876
+ const rows = db.select({
70877
+ sourceType: trafficSources.sourceType,
70878
+ configJson: trafficSources.configJson,
70879
+ lastSyncedAt: trafficSources.lastSyncedAt
70880
+ }).from(trafficSources).where(sourceId ? and90(eq104(trafficSources.projectId, projectId), eq104(trafficSources.id, sourceId)) : and90(
70881
+ eq104(trafficSources.projectId, projectId),
70882
+ notInArray3(trafficSources.status, [TrafficSourceStatuses.archived, TrafficSourceStatuses.paused])
70883
+ )).all();
70884
+ const watermarks = [];
70885
+ for (const row of rows) {
70886
+ if (isCloudflareDirectPush(row)) {
70887
+ watermarks.push(Number.POSITIVE_INFINITY);
70888
+ continue;
70889
+ }
70890
+ const syncedMs = row.lastSyncedAt ? Date.parse(row.lastSyncedAt) : Number.NaN;
70891
+ if (Number.isFinite(syncedMs)) watermarks.push(syncedMs);
70892
+ }
70893
+ if (watermarks.length === 0) return { anyThroughMs: null, allThroughMs: null };
70894
+ const bounded = (ms) => Number.isFinite(ms) ? ms : null;
70895
+ return {
70896
+ anyThroughMs: bounded(Math.max(...watermarks)),
70897
+ allThroughMs: bounded(Math.min(...watermarks))
70898
+ };
70899
+ }
70867
70900
 
70868
70901
  // ../api-routes/src/traffic-limits.ts
70869
70902
  var VERCEL_MAX_SYNC_WINDOW_MS = 24 * 60 * 6e4;
@@ -72229,7 +72262,7 @@ async function ackCloudflareQueueMessages(client, options) {
72229
72262
  }
72230
72263
 
72231
72264
  // ../api-routes/src/traffic-sync-lease.ts
72232
- import { and as and90, eq as eq104, isNull as isNull17, lte as lte26, or as or19 } from "drizzle-orm";
72265
+ import { and as and91, eq as eq105, isNull as isNull17, lte as lte26, or as or19 } from "drizzle-orm";
72233
72266
  function leaseExpiresAt(now, ttlMs) {
72234
72267
  const nowMs = Date.parse(now);
72235
72268
  if (!Number.isFinite(nowMs)) throw new RangeError("Traffic sync lease now must be an ISO instant");
@@ -72242,12 +72275,12 @@ function tryClaimTrafficSyncLease(input) {
72242
72275
  const changed = tx.update(trafficSources).set({
72243
72276
  syncLeaseOwner: input.owner,
72244
72277
  syncLeaseExpiresAt: expiresAt
72245
- }).where(and90(
72246
- eq104(trafficSources.id, input.sourceId),
72278
+ }).where(and91(
72279
+ eq105(trafficSources.id, input.sourceId),
72247
72280
  or19(
72248
72281
  isNull17(trafficSources.syncLeaseOwner),
72249
72282
  lte26(trafficSources.syncLeaseExpiresAt, input.now),
72250
- eq104(trafficSources.syncLeaseOwner, input.owner)
72283
+ eq105(trafficSources.syncLeaseOwner, input.owner)
72251
72284
  )
72252
72285
  )).run();
72253
72286
  return changed.changes === 1;
@@ -72258,9 +72291,9 @@ function releaseTrafficSyncLease(input) {
72258
72291
  const changed = tx.update(trafficSources).set({
72259
72292
  syncLeaseOwner: null,
72260
72293
  syncLeaseExpiresAt: null
72261
- }).where(and90(
72262
- eq104(trafficSources.id, input.sourceId),
72263
- eq104(trafficSources.syncLeaseOwner, input.owner)
72294
+ }).where(and91(
72295
+ eq105(trafficSources.id, input.sourceId),
72296
+ eq105(trafficSources.syncLeaseOwner, input.owner)
72264
72297
  )).run();
72265
72298
  return changed.changes === 1;
72266
72299
  }, { behavior: "immediate" });
@@ -72268,7 +72301,7 @@ function releaseTrafficSyncLease(input) {
72268
72301
 
72269
72302
  // ../api-routes/src/traffic-events-read.ts
72270
72303
  import crypto61 from "crypto";
72271
- import { desc as desc48, eq as eq105, or as or20, sql as sql47 } from "drizzle-orm";
72304
+ import { desc as desc48, eq as eq106, or as or20, sql as sql47 } from "drizzle-orm";
72272
72305
  function keyColumns(table, fields) {
72273
72306
  return { keyFields: fields, keys: fields.map((field) => table[field]) };
72274
72307
  }
@@ -72319,7 +72352,7 @@ function trafficEventPathPredicate(column, path8) {
72319
72352
  function trafficEventFilterPredicates(table, filters) {
72320
72353
  const predicates = [];
72321
72354
  if (filters.path !== null) predicates.push(trafficEventPathPredicate(table.path, filters.path));
72322
- if (filters.agent !== null) predicates.push(eq105(table.agent, filters.agent));
72355
+ if (filters.agent !== null) predicates.push(eq106(table.agent, filters.agent));
72323
72356
  return predicates;
72324
72357
  }
72325
72358
  function optionalQueryString(value, name) {
@@ -72509,14 +72542,14 @@ async function loadQueueReceiptPolicy(db, sourceId, readRetentionSeconds, warn2)
72509
72542
  if (liveTtlMs === null) return { ttlMsAt: () => CLOUDFLARE_QUEUE_RECEIPT_TTL_MS };
72510
72543
  const ttlMs = liveTtlMs;
72511
72544
  const now = (/* @__PURE__ */ new Date()).toISOString();
72512
- const alive = and91(eq106(trafficEventReceipts.sourceId, sourceId), gt8(trafficEventReceipts.expiresAt, now));
72545
+ const alive = and92(eq107(trafficEventReceipts.sourceId, sourceId), gt8(trafficEventReceipts.expiresAt, now));
72513
72546
  const lifetimeMs = sql48`(julianday(${trafficEventReceipts.expiresAt}) - julianday(${trafficEventReceipts.receivedAt})) * ${DAY_MS5}`;
72514
72547
  const shortest = db.select({ ms: sql48`min(${lifetimeMs})` }).from(trafficEventReceipts).where(alive).get()?.ms ?? null;
72515
72548
  if (shortest !== null && shortest < ttlMs - 1e3) {
72516
72549
  const extended = sql48`strftime('%Y-%m-%dT%H:%M:%fZ', julianday(${trafficEventReceipts.receivedAt}) + ${ttlMs / DAY_MS5})`;
72517
- db.update(trafficEventReceipts).set({ expiresAt: extended }).where(and91(alive, lt20(trafficEventReceipts.expiresAt, extended))).run();
72550
+ db.update(trafficEventReceipts).set({ expiresAt: extended }).where(and92(alive, lt20(trafficEventReceipts.expiresAt, extended))).run();
72518
72551
  }
72519
- const floorExpiry = db.select({ at: sql48`max(${trafficEventReceipts.expiresAt})` }).from(trafficEventReceipts).where(and91(alive, sql48`${lifetimeMs} < ${CLOUDFLARE_QUEUE_RECEIPT_TTL_MS - 1e3}`)).get()?.at ?? null;
72552
+ const floorExpiry = db.select({ at: sql48`max(${trafficEventReceipts.expiresAt})` }).from(trafficEventReceipts).where(and92(alive, sql48`${lifetimeMs} < ${CLOUDFLARE_QUEUE_RECEIPT_TTL_MS - 1e3}`)).get()?.at ?? null;
72520
72553
  const floorMs = floorExpiry ? Date.parse(floorExpiry) : 0;
72521
72554
  return { ttlMsAt: (receivedAt) => Math.max(ttlMs, floorMs - Date.parse(receivedAt)) };
72522
72555
  }
@@ -72571,7 +72604,7 @@ function cloudflareIngestRateLimitKey(request, store, db) {
72571
72604
  const authenticated = authenticateCloudflareIngest(request, store);
72572
72605
  const params = request.params;
72573
72606
  if (authenticated && typeof params.name === "string" && authenticated.credential.projectName === params.name) {
72574
- const source = db.select().from(trafficSources).where(eq106(trafficSources.id, authenticated.credential.sourceId)).get();
72607
+ const source = db.select().from(trafficSources).where(eq107(trafficSources.id, authenticated.credential.sourceId)).get();
72575
72608
  if (source && source.sourceType === TrafficSourceTypes.cloudflare && source.status === TrafficSourceStatuses.connected && parseDirectPushCloudflareSourceConfig(source.configJson) && timingSafeEqualHex(authenticated.bearerHash, source.ingestTokenHash)) {
72576
72609
  return `cloudflare-source:${authenticated.credential.sourceId}`;
72577
72610
  }
@@ -72839,7 +72872,7 @@ async function defaultResolveAccessToken(record3) {
72839
72872
  );
72840
72873
  }
72841
72874
  function hasConnectedTrafficSourceSibling(db, projectId, sourceId) {
72842
- return db.select().from(trafficSources).where(eq106(trafficSources.projectId, projectId)).all().some((row) => row.id !== sourceId && row.status === TrafficSourceStatuses.connected);
72875
+ return db.select().from(trafficSources).where(eq107(trafficSources.projectId, projectId)).all().some((row) => row.id !== sourceId && row.status === TrafficSourceStatuses.connected);
72843
72876
  }
72844
72877
  function isAuthoritativeTrafficSource(db, source) {
72845
72878
  return (source.status === TrafficSourceStatuses.connected || source.status === TrafficSourceStatuses.error) && !hasConnectedTrafficSourceSibling(db, source.projectId, source.id);
@@ -72866,13 +72899,13 @@ function wordpressBaseUrlIdentity(value) {
72866
72899
  }
72867
72900
  }
72868
72901
  function bindTrafficSyncSchedule(tx, projectId, sourceId, now, createIfMissing = true) {
72869
- const schedule = tx.select().from(schedules).where(and91(
72870
- eq106(schedules.projectId, projectId),
72871
- eq106(schedules.kind, SchedulableRunKinds["traffic-sync"])
72902
+ const schedule = tx.select().from(schedules).where(and92(
72903
+ eq107(schedules.projectId, projectId),
72904
+ eq107(schedules.kind, SchedulableRunKinds["traffic-sync"])
72872
72905
  )).get();
72873
72906
  if (schedule) {
72874
72907
  if (schedule.sourceId === sourceId) return { changed: false, created: false };
72875
- tx.update(schedules).set({ sourceId, updatedAt: nextScheduleUpdatedAt(schedule.updatedAt, Date.parse(now)) }).where(eq106(schedules.id, schedule.id)).run();
72908
+ tx.update(schedules).set({ sourceId, updatedAt: nextScheduleUpdatedAt(schedule.updatedAt, Date.parse(now)) }).where(eq107(schedules.id, schedule.id)).run();
72876
72909
  return { changed: true, created: false };
72877
72910
  }
72878
72911
  if (!createIfMissing) return { changed: false, created: false };
@@ -72914,7 +72947,7 @@ async function runBackfillTask(options) {
72914
72947
  };
72915
72948
  const renewLease2 = setInterval(() => {
72916
72949
  try {
72917
- const latest = app.db.select().from(trafficSources).where(eq106(trafficSources.id, sourceRow2.id)).get();
72950
+ const latest = app.db.select().from(trafficSources).where(eq107(trafficSources.id, sourceRow2.id)).get();
72918
72951
  if (!latest || !isAuthoritativeTrafficSource(app.db, latest) || !isSameTrafficSourceGeneration(latest, sourceRow2)) {
72919
72952
  clearInterval(renewLease2);
72920
72953
  stopped.abort();
@@ -72962,10 +72995,10 @@ async function runBackfillTaskHoldingLease(options, signal) {
72962
72995
  const failedAt = (/* @__PURE__ */ new Date()).toISOString();
72963
72996
  try {
72964
72997
  app.db.transaction((tx) => {
72965
- tx.update(runs).set({ status: RunStatuses.failed, error: msg, finishedAt: failedAt }).where(eq106(runs.id, runId)).run();
72966
- const latestSource = tx.select().from(trafficSources).where(eq106(trafficSources.id, sourceRow2.id)).get();
72998
+ tx.update(runs).set({ status: RunStatuses.failed, error: msg, finishedAt: failedAt }).where(eq107(runs.id, runId)).run();
72999
+ const latestSource = tx.select().from(trafficSources).where(eq107(trafficSources.id, sourceRow2.id)).get();
72967
73000
  if (!preserveSourceState && latestSource && isAuthoritativeTrafficSource(tx, latestSource) && isSameBackfillSource(latestSource, sourceRow2, leaseOwner)) {
72968
- tx.update(trafficSources).set({ status: TrafficSourceStatuses.error, lastError: msg, updatedAt: failedAt }).where(eq106(trafficSources.id, sourceRow2.id)).run();
73001
+ tx.update(trafficSources).set({ status: TrafficSourceStatuses.error, lastError: msg, updatedAt: failedAt }).where(eq107(trafficSources.id, sourceRow2.id)).run();
72969
73002
  }
72970
73003
  });
72971
73004
  } catch {
@@ -72997,7 +73030,7 @@ async function runBackfillTaskHoldingLease(options, signal) {
72997
73030
  let emptyOutcome;
72998
73031
  try {
72999
73032
  const completed = app.db.transaction((tx) => {
73000
- const latestSource = tx.select().from(trafficSources).where(eq106(trafficSources.id, sourceRow2.id)).get();
73033
+ const latestSource = tx.select().from(trafficSources).where(eq107(trafficSources.id, sourceRow2.id)).get();
73001
73034
  const stillAuthoritative = latestSource && isAuthoritativeTrafficSource(tx, latestSource) && isSameBackfillSource(latestSource, sourceRow2, leaseOwner);
73002
73035
  if (stillAuthoritative) {
73003
73036
  enforceRawEventSampleRetention(tx, sourceRow2.id, finishedAt2);
@@ -73006,7 +73039,7 @@ async function runBackfillTaskHoldingLease(options, signal) {
73006
73039
  status: RunStatuses.failed,
73007
73040
  error: "Traffic source was deactivated or reconfigured during backfill",
73008
73041
  finishedAt: finishedAt2
73009
- }).where(eq106(runs.id, runId)).run();
73042
+ }).where(eq107(runs.id, runId)).run();
73010
73043
  return Boolean(stillAuthoritative);
73011
73044
  });
73012
73045
  emptyOutcome = completed ? { status: OutcomeStatuses.skipped, reasonCode: OutcomeReasonCodes.NO_DATA } : { status: OutcomeStatuses.failed, reasonCode: OutcomeReasonCodes.NOT_CONNECTED };
@@ -73038,13 +73071,13 @@ async function runBackfillTaskHoldingLease(options, signal) {
73038
73071
  const nextLastSyncedAt = Math.max(currentLastSyncedMs, windowEnd.getTime()) === windowEnd.getTime() ? windowEndIso : sourceRow2.lastSyncedAt;
73039
73072
  try {
73040
73073
  const commitOutcome = app.db.transaction((tx) => {
73041
- const latestSource = tx.select().from(trafficSources).where(eq106(trafficSources.id, sourceRow2.id)).get();
73074
+ const latestSource = tx.select().from(trafficSources).where(eq107(trafficSources.id, sourceRow2.id)).get();
73042
73075
  if (latestSource?.sourceType === TrafficSourceTypes.wordpress) {
73043
73076
  tx.update(runs).set({
73044
73077
  status: RunStatuses.failed,
73045
73078
  error: "Generic WordPress replace backfill is unavailable because retained coverage is unproven.",
73046
73079
  finishedAt
73047
- }).where(eq106(runs.id, runId)).run();
73080
+ }).where(eq107(runs.id, runId)).run();
73048
73081
  return "wordpress-backfill-unsupported";
73049
73082
  }
73050
73083
  if (!latestSource || !isAuthoritativeTrafficSource(tx, latestSource) || !isSameBackfillSource(latestSource, sourceRow2, leaseOwner)) {
@@ -73052,7 +73085,7 @@ async function runBackfillTaskHoldingLease(options, signal) {
73052
73085
  status: RunStatuses.failed,
73053
73086
  error: "Traffic source was deactivated or reconfigured during backfill",
73054
73087
  finishedAt
73055
- }).where(eq106(runs.id, runId)).run();
73088
+ }).where(eq107(runs.id, runId)).run();
73056
73089
  return "source-inactive";
73057
73090
  }
73058
73091
  const rawSampleCutoff = enforceRawEventSampleRetention(
@@ -73061,37 +73094,37 @@ async function runBackfillTaskHoldingLease(options, signal) {
73061
73094
  finishedAt
73062
73095
  );
73063
73096
  tx.delete(crawlerEventsHourly).where(
73064
- and91(
73065
- eq106(crawlerEventsHourly.sourceId, sourceRow2.id),
73097
+ and92(
73098
+ eq107(crawlerEventsHourly.sourceId, sourceRow2.id),
73066
73099
  gte27(crawlerEventsHourly.tsHour, windowStartIso),
73067
73100
  lte27(crawlerEventsHourly.tsHour, windowEndIso)
73068
73101
  )
73069
73102
  ).run();
73070
73103
  tx.delete(aiUserFetchEventsHourly).where(
73071
- and91(
73072
- eq106(aiUserFetchEventsHourly.sourceId, sourceRow2.id),
73104
+ and92(
73105
+ eq107(aiUserFetchEventsHourly.sourceId, sourceRow2.id),
73073
73106
  gte27(aiUserFetchEventsHourly.tsHour, windowStartIso),
73074
73107
  lte27(aiUserFetchEventsHourly.tsHour, windowEndIso)
73075
73108
  )
73076
73109
  ).run();
73077
73110
  clearLikelyFakeAgentHits(tx, { sourceId: sourceRow2.id, windowStart: windowStartIso, windowEnd: windowEndIso });
73078
73111
  tx.delete(aiReferralEventsHourly).where(
73079
- and91(
73080
- eq106(aiReferralEventsHourly.sourceId, sourceRow2.id),
73112
+ and92(
73113
+ eq107(aiReferralEventsHourly.sourceId, sourceRow2.id),
73081
73114
  gte27(aiReferralEventsHourly.tsHour, windowStartIso),
73082
73115
  lte27(aiReferralEventsHourly.tsHour, windowEndIso)
73083
73116
  )
73084
73117
  ).run();
73085
73118
  tx.delete(rawEventSamples).where(
73086
- and91(
73087
- eq106(rawEventSamples.sourceId, sourceRow2.id),
73119
+ and92(
73120
+ eq107(rawEventSamples.sourceId, sourceRow2.id),
73088
73121
  gte27(rawEventSamples.ts, windowStartIso),
73089
73122
  lte27(rawEventSamples.ts, windowEndIso)
73090
73123
  )
73091
73124
  ).run();
73092
73125
  tx.delete(unrecognizedAgentEventsHourly).where(
73093
- and91(
73094
- eq106(unrecognizedAgentEventsHourly.sourceId, sourceRow2.id),
73126
+ and92(
73127
+ eq107(unrecognizedAgentEventsHourly.sourceId, sourceRow2.id),
73095
73128
  gte27(unrecognizedAgentEventsHourly.tsHour, windowStartIso),
73096
73129
  lte27(unrecognizedAgentEventsHourly.tsHour, windowEndIso)
73097
73130
  )
@@ -73299,8 +73332,8 @@ async function runBackfillTaskHoldingLease(options, signal) {
73299
73332
  FROM _migrations WHERE version = 207
73300
73333
  `);
73301
73334
  if (ruleChange?.appliedAt) {
73302
- const olderReferral = tx.select({ sourceId: aiReferralEventsHourly.sourceId }).from(aiReferralEventsHourly).where(and91(
73303
- eq106(aiReferralEventsHourly.sourceId, sourceRow2.id),
73335
+ const olderReferral = tx.select({ sourceId: aiReferralEventsHourly.sourceId }).from(aiReferralEventsHourly).where(and92(
73336
+ eq107(aiReferralEventsHourly.sourceId, sourceRow2.id),
73304
73337
  lt20(aiReferralEventsHourly.createdAt, ruleChange.appliedAt)
73305
73338
  )).limit(1).get();
73306
73339
  if (!olderReferral) olderCountUntil = null;
@@ -73321,8 +73354,8 @@ async function runBackfillTaskHoldingLease(options, signal) {
73321
73354
  aiUserFetchOlderCountUntil: userFetchOlderCountUntil,
73322
73355
  ...skipRecovered ? { skippedThroughAt: null } : {},
73323
73356
  updatedAt: finishedAt
73324
- }).where(eq106(trafficSources.id, sourceRow2.id)).run();
73325
- tx.update(runs).set({ status: RunStatuses.completed, finishedAt }).where(eq106(runs.id, runId)).run();
73357
+ }).where(eq107(trafficSources.id, sourceRow2.id)).run();
73358
+ tx.update(runs).set({ status: RunStatuses.completed, finishedAt }).where(eq107(runs.id, runId)).run();
73326
73359
  return "committed";
73327
73360
  });
73328
73361
  reportBackfill(commitOutcome === "committed" ? {
@@ -73504,7 +73537,7 @@ async function trafficRoutes(app, opts) {
73504
73537
  }
73505
73538
  const fallbackName = displayName ?? `Cloud Run \xB7 ${gcpProjectId}${serviceName ? ` / ${serviceName}` : ""}`;
73506
73539
  const { sourceRow: sourceRow2, scheduleChanged } = app.db.transaction((tx) => {
73507
- const activeSource = tx.select().from(trafficSources).where(eq106(trafficSources.projectId, project.id)).all().find((row) => row.sourceType === TrafficSourceTypes["cloud-run"] && row.status !== TrafficSourceStatuses.archived);
73540
+ const activeSource = tx.select().from(trafficSources).where(eq107(trafficSources.projectId, project.id)).all().find((row) => row.sourceType === TrafficSourceTypes["cloud-run"] && row.status !== TrafficSourceStatuses.archived);
73508
73541
  const matchesExistingSource = activeSource && hasCloudRunCredentialForSource(existing, project.name, activeSource);
73509
73542
  const sameOwner = existing?.projectId === project.id || matchesExistingSource;
73510
73543
  let credentialToSave = uploadedCredential;
@@ -73527,7 +73560,7 @@ async function trafficRoutes(app, opts) {
73527
73560
  const sourceId = sameSource?.id ?? crypto62.randomUUID();
73528
73561
  if (!uploadedCredential && sameSource && matchesExistingSource) {
73529
73562
  if (displayName !== void 0 && displayName !== sameSource.displayName) {
73530
- tx.update(trafficSources).set({ displayName }).where(eq106(trafficSources.id, sourceId)).run();
73563
+ tx.update(trafficSources).set({ displayName }).where(eq107(trafficSources.id, sourceId)).run();
73531
73564
  writeAuditLog(tx, {
73532
73565
  projectId: project.id,
73533
73566
  actor: "api",
@@ -73550,10 +73583,10 @@ async function trafficRoutes(app, opts) {
73550
73583
  lastError: null,
73551
73584
  configJson: config,
73552
73585
  updatedAt: now
73553
- }).where(eq106(trafficSources.id, sourceId)).run();
73586
+ }).where(eq107(trafficSources.id, sourceId)).run();
73554
73587
  } else {
73555
73588
  if (activeSource) {
73556
- tx.update(trafficSources).set({ status: TrafficSourceStatuses.archived, archivedAt: now, updatedAt: now }).where(eq106(trafficSources.id, activeSource.id)).run();
73589
+ tx.update(trafficSources).set({ status: TrafficSourceStatuses.archived, archivedAt: now, updatedAt: now }).where(eq107(trafficSources.id, activeSource.id)).run();
73557
73590
  }
73558
73591
  tx.insert(trafficSources).values({
73559
73592
  id: sourceId,
@@ -73580,7 +73613,7 @@ async function trafficRoutes(app, opts) {
73580
73613
  });
73581
73614
  if (credentialToSave) store.upsertConnection(credentialToSave);
73582
73615
  return {
73583
- sourceRow: tx.select().from(trafficSources).where(eq106(trafficSources.id, sourceId)).get(),
73616
+ sourceRow: tx.select().from(trafficSources).where(eq107(trafficSources.id, sourceId)).get(),
73584
73617
  scheduleChanged: scheduleBinding.changed
73585
73618
  };
73586
73619
  }, { behavior: "immediate" });
@@ -73637,7 +73670,7 @@ async function trafficRoutes(app, opts) {
73637
73670
  const config = { baseUrl, username };
73638
73671
  const fallbackName = displayName ?? `WordPress \xB7 ${new URL(baseUrl).host}`;
73639
73672
  const { sourceRow: sourceRow2, scheduleChanged } = app.db.transaction((tx) => {
73640
- const activeSource = tx.select().from(trafficSources).where(eq106(trafficSources.projectId, project.id)).all().find((row) => row.sourceType === TrafficSourceTypes.wordpress && row.status !== TrafficSourceStatuses.archived);
73673
+ const activeSource = tx.select().from(trafficSources).where(eq107(trafficSources.projectId, project.id)).all().find((row) => row.sourceType === TrafficSourceTypes.wordpress && row.status !== TrafficSourceStatuses.archived);
73641
73674
  const endpointChanged = activeSource !== void 0 && wordpressBaseUrlIdentity(activeSource.configJson.baseUrl) !== wordpressBaseUrlIdentity(baseUrl);
73642
73675
  const sourceId = endpointChanged ? crypto62.randomUUID() : activeSource?.id ?? crypto62.randomUUID();
73643
73676
  const sourceStatus = trafficConnectStatus(tx, project.id, activeSource);
@@ -73648,14 +73681,14 @@ async function trafficRoutes(app, opts) {
73648
73681
  lastError: null,
73649
73682
  configJson: config,
73650
73683
  updatedAt: now
73651
- }).where(eq106(trafficSources.id, sourceId)).run();
73684
+ }).where(eq107(trafficSources.id, sourceId)).run();
73652
73685
  } else {
73653
73686
  if (activeSource) {
73654
73687
  tx.update(trafficSources).set({
73655
73688
  status: TrafficSourceStatuses.archived,
73656
73689
  archivedAt: now,
73657
73690
  updatedAt: now
73658
- }).where(eq106(trafficSources.id, activeSource.id)).run();
73691
+ }).where(eq107(trafficSources.id, activeSource.id)).run();
73659
73692
  }
73660
73693
  tx.insert(trafficSources).values({
73661
73694
  id: sourceId,
@@ -73681,7 +73714,7 @@ async function trafficRoutes(app, opts) {
73681
73714
  entityId: sourceId
73682
73715
  });
73683
73716
  return {
73684
- sourceRow: tx.select().from(trafficSources).where(eq106(trafficSources.id, sourceId)).get(),
73717
+ sourceRow: tx.select().from(trafficSources).where(eq107(trafficSources.id, sourceId)).get(),
73685
73718
  scheduleChanged: scheduleBinding.changed
73686
73719
  };
73687
73720
  }, { behavior: "immediate" });
@@ -73740,7 +73773,7 @@ async function trafficRoutes(app, opts) {
73740
73773
  const config = { projectId, teamId, environment };
73741
73774
  const fallbackName = displayName ?? `Vercel \xB7 ${projectId}`;
73742
73775
  const { sourceRow: sourceRow2, scheduleChanged } = app.db.transaction((tx) => {
73743
- const activeSource = tx.select().from(trafficSources).where(eq106(trafficSources.projectId, project.id)).all().find((row2) => row2.sourceType === TrafficSourceTypes.vercel && row2.status !== TrafficSourceStatuses.archived);
73776
+ const activeSource = tx.select().from(trafficSources).where(eq107(trafficSources.projectId, project.id)).all().find((row2) => row2.sourceType === TrafficSourceTypes.vercel && row2.status !== TrafficSourceStatuses.archived);
73744
73777
  const sourceStatus = trafficConnectStatus(tx, project.id, activeSource);
73745
73778
  let row;
73746
73779
  if (activeSource) {
@@ -73750,8 +73783,8 @@ async function trafficRoutes(app, opts) {
73750
73783
  lastError: null,
73751
73784
  configJson: config,
73752
73785
  updatedAt: now
73753
- }).where(eq106(trafficSources.id, activeSource.id)).run();
73754
- row = tx.select().from(trafficSources).where(eq106(trafficSources.id, activeSource.id)).get();
73786
+ }).where(eq107(trafficSources.id, activeSource.id)).run();
73787
+ row = tx.select().from(trafficSources).where(eq107(trafficSources.id, activeSource.id)).get();
73755
73788
  } else {
73756
73789
  const newId = crypto62.randomUUID();
73757
73790
  tx.insert(trafficSources).values({
@@ -73776,7 +73809,7 @@ async function trafficRoutes(app, opts) {
73776
73809
  createdAt: now,
73777
73810
  updatedAt: now
73778
73811
  }).run();
73779
- row = tx.select().from(trafficSources).where(eq106(trafficSources.id, newId)).get();
73812
+ row = tx.select().from(trafficSources).where(eq107(trafficSources.id, newId)).get();
73780
73813
  }
73781
73814
  const scheduleBinding = sourceStatus === TrafficSourceStatuses.connected ? bindTrafficSyncSchedule(tx, project.id, row.id, now) : { changed: false, created: false };
73782
73815
  writeAuditLog(tx, {
@@ -73820,7 +73853,7 @@ async function trafficRoutes(app, opts) {
73820
73853
  const { displayName: displayName2, zoneId: zoneId2, accountId: accountId2, queueId, queueName, retentionSeconds, apiToken } = parsed.data;
73821
73854
  const workerRouteHost2 = resolveCloudflareWorkerRouteHost(project.canonicalDomain);
73822
73855
  const now2 = (/* @__PURE__ */ new Date()).toISOString();
73823
- const cloudflareSources = app.db.select().from(trafficSources).where(eq106(trafficSources.projectId, project.id)).all().filter((row) => row.sourceType === TrafficSourceTypes.cloudflare && row.status !== TrafficSourceStatuses.archived);
73856
+ const cloudflareSources = app.db.select().from(trafficSources).where(eq107(trafficSources.projectId, project.id)).all().filter((row) => row.sourceType === TrafficSourceTypes.cloudflare && row.status !== TrafficSourceStatuses.archived);
73824
73857
  const sameModeSource = cloudflareSources.find((row) => parseQueuePullCloudflareSourceConfig(row.configJson));
73825
73858
  if (sameModeSource) attempt.update({ action: "reauth" });
73826
73859
  const sourceId2 = sameModeSource?.id ?? crypto62.randomUUID();
@@ -73874,7 +73907,7 @@ async function trafficRoutes(app, opts) {
73874
73907
  let scheduleChanged = false;
73875
73908
  try {
73876
73909
  const result = app.db.transaction((tx) => {
73877
- const currentSameModeSource = tx.select().from(trafficSources).where(eq106(trafficSources.projectId, project.id)).all().find((row) => row.sourceType === TrafficSourceTypes.cloudflare && row.status !== TrafficSourceStatuses.archived && parseQueuePullCloudflareSourceConfig(row.configJson) !== null);
73910
+ const currentSameModeSource = tx.select().from(trafficSources).where(eq107(trafficSources.projectId, project.id)).all().find((row) => row.sourceType === TrafficSourceTypes.cloudflare && row.status !== TrafficSourceStatuses.archived && parseQueuePullCloudflareSourceConfig(row.configJson) !== null);
73878
73911
  if ((currentSameModeSource?.id ?? null) !== (sameModeSource?.id ?? null)) {
73879
73912
  throw operationInProgress("Cloudflare Queue source changed during connect; retry");
73880
73913
  }
@@ -73892,7 +73925,7 @@ async function trafficRoutes(app, opts) {
73892
73925
  queueBacklogObservedAt: null
73893
73926
  } : {},
73894
73927
  updatedAt: now2
73895
- }).where(eq106(trafficSources.id, sourceId2)).run();
73928
+ }).where(eq107(trafficSources.id, sourceId2)).run();
73896
73929
  } else {
73897
73930
  tx.insert(trafficSources).values({
73898
73931
  id: sourceId2,
@@ -73912,7 +73945,7 @@ async function trafficRoutes(app, opts) {
73912
73945
  }
73913
73946
  const changed = status === TrafficSourceStatuses.connected ? bindTrafficSyncSchedule(tx, project.id, sourceId2, now2).changed : false;
73914
73947
  return {
73915
- row: tx.select().from(trafficSources).where(eq106(trafficSources.id, sourceId2)).get(),
73948
+ row: tx.select().from(trafficSources).where(eq107(trafficSources.id, sourceId2)).get(),
73916
73949
  scheduleChanged: changed
73917
73950
  };
73918
73951
  }, { behavior: "immediate" });
@@ -73962,7 +73995,7 @@ async function trafficRoutes(app, opts) {
73962
73995
  const { deliveryMode, displayName, zoneId, accountId } = parsed.data;
73963
73996
  const workerRouteHost = resolveCloudflareWorkerRouteHost(project.canonicalDomain);
73964
73997
  const now = (/* @__PURE__ */ new Date()).toISOString();
73965
- const activeSource = app.db.select().from(trafficSources).where(eq106(trafficSources.projectId, project.id)).all().find((row) => row.sourceType === TrafficSourceTypes.cloudflare && row.status !== TrafficSourceStatuses.archived && parseDirectPushCloudflareSourceConfig(row.configJson) !== null);
73998
+ const activeSource = app.db.select().from(trafficSources).where(eq107(trafficSources.projectId, project.id)).all().find((row) => row.sourceType === TrafficSourceTypes.cloudflare && row.status !== TrafficSourceStatuses.archived && parseDirectPushCloudflareSourceConfig(row.configJson) !== null);
73966
73999
  if (activeSource) attempt.update({ action: "reauth" });
73967
74000
  const sourceId = activeSource?.id ?? crypto62.randomUUID();
73968
74001
  const parsedActiveConfig = activeSource ? parseDirectPushCloudflareSourceConfig(activeSource.configJson) : null;
@@ -74030,7 +74063,7 @@ async function trafficRoutes(app, opts) {
74030
74063
  let scheduleRemoved = false;
74031
74064
  try {
74032
74065
  const result = app.db.transaction((tx) => {
74033
- const currentActiveSource = tx.select().from(trafficSources).where(eq106(trafficSources.projectId, project.id)).all().find((row2) => row2.sourceType === TrafficSourceTypes.cloudflare && row2.status !== TrafficSourceStatuses.archived && parseDirectPushCloudflareSourceConfig(row2.configJson) !== null);
74066
+ const currentActiveSource = tx.select().from(trafficSources).where(eq107(trafficSources.projectId, project.id)).all().find((row2) => row2.sourceType === TrafficSourceTypes.cloudflare && row2.status !== TrafficSourceStatuses.archived && parseDirectPushCloudflareSourceConfig(row2.configJson) !== null);
74034
74067
  if ((currentActiveSource?.id ?? null) !== (activeSource?.id ?? null)) {
74035
74068
  throw operationInProgress("Cloudflare direct-push source changed during connect; retry");
74036
74069
  }
@@ -74044,8 +74077,8 @@ async function trafficRoutes(app, opts) {
74044
74077
  configJson: config,
74045
74078
  ingestTokenHash,
74046
74079
  updatedAt: now
74047
- }).where(eq106(trafficSources.id, currentActiveSource.id)).run();
74048
- row = tx.select().from(trafficSources).where(eq106(trafficSources.id, currentActiveSource.id)).get();
74080
+ }).where(eq107(trafficSources.id, currentActiveSource.id)).run();
74081
+ row = tx.select().from(trafficSources).where(eq107(trafficSources.id, currentActiveSource.id)).get();
74049
74082
  } else {
74050
74083
  tx.insert(trafficSources).values({
74051
74084
  id: sourceId,
@@ -74065,16 +74098,16 @@ async function trafficRoutes(app, opts) {
74065
74098
  createdAt: now,
74066
74099
  updatedAt: now
74067
74100
  }).run();
74068
- row = tx.select().from(trafficSources).where(eq106(trafficSources.id, sourceId)).get();
74101
+ row = tx.select().from(trafficSources).where(eq107(trafficSources.id, sourceId)).get();
74069
74102
  }
74070
74103
  let removed = false;
74071
74104
  if (row.status === TrafficSourceStatuses.connected) {
74072
- const schedule = tx.select().from(schedules).where(and91(
74073
- eq106(schedules.projectId, project.id),
74074
- eq106(schedules.kind, SchedulableRunKinds["traffic-sync"])
74105
+ const schedule = tx.select().from(schedules).where(and92(
74106
+ eq107(schedules.projectId, project.id),
74107
+ eq107(schedules.kind, SchedulableRunKinds["traffic-sync"])
74075
74108
  )).get();
74076
74109
  if (schedule) {
74077
- tx.delete(schedules).where(eq106(schedules.id, schedule.id)).run();
74110
+ tx.delete(schedules).where(eq107(schedules.id, schedule.id)).run();
74078
74111
  removed = true;
74079
74112
  }
74080
74113
  }
@@ -74130,47 +74163,47 @@ async function trafficRoutes(app, opts) {
74130
74163
  };
74131
74164
  }));
74132
74165
  app.post("/projects/:name/traffic/sources/:id/activate", connectionRoute(app, (request) => {
74133
- const source = app.db.select({ sourceType: trafficSources.sourceType }).from(trafficSources).where(eq106(trafficSources.id, request.params.id)).get();
74166
+ const source = app.db.select({ sourceType: trafficSources.sourceType }).from(trafficSources).where(eq107(trafficSources.id, request.params.id)).get();
74134
74167
  const integration = source ? TRAFFIC_SOURCE_INTEGRATIONS[source.sourceType] : void 0;
74135
74168
  return integration ? { integration, action: "select" } : void 0;
74136
74169
  }, async (request) => {
74137
74170
  const project = resolveProject(app.db, request.params.name);
74138
74171
  const now = (/* @__PURE__ */ new Date()).toISOString();
74139
74172
  const result = app.db.transaction((tx) => {
74140
- const target = tx.select().from(trafficSources).where(eq106(trafficSources.id, request.params.id)).get();
74173
+ const target = tx.select().from(trafficSources).where(eq107(trafficSources.id, request.params.id)).get();
74141
74174
  if (!target || target.projectId !== project.id || target.status === TrafficSourceStatuses.archived) {
74142
74175
  throw notFound("Traffic source", request.params.id);
74143
74176
  }
74144
74177
  const { usesPullSchedule } = validateTrafficSourceCredential(target, project.name);
74145
- const siblings = tx.select().from(trafficSources).where(eq106(trafficSources.projectId, project.id)).all();
74178
+ const siblings = tx.select().from(trafficSources).where(eq107(trafficSources.projectId, project.id)).all();
74146
74179
  for (const sibling of siblings) {
74147
74180
  if (sibling.id === target.id || sibling.status === TrafficSourceStatuses.archived) continue;
74148
74181
  tx.update(trafficSources).set({
74149
74182
  status: TrafficSourceStatuses.paused,
74150
74183
  updatedAt: now
74151
- }).where(eq106(trafficSources.id, sibling.id)).run();
74184
+ }).where(eq107(trafficSources.id, sibling.id)).run();
74152
74185
  }
74153
74186
  tx.update(trafficSources).set({
74154
74187
  status: TrafficSourceStatuses.connected,
74155
74188
  lastError: null,
74156
74189
  archivedAt: null,
74157
74190
  updatedAt: now
74158
- }).where(eq106(trafficSources.id, target.id)).run();
74191
+ }).where(eq107(trafficSources.id, target.id)).run();
74159
74192
  let scheduleAction = null;
74160
74193
  if (usesPullSchedule) {
74161
74194
  bindTrafficSyncSchedule(tx, project.id, target.id, now);
74162
74195
  scheduleAction = "upsert";
74163
74196
  } else {
74164
- const schedule = tx.select().from(schedules).where(and91(
74165
- eq106(schedules.projectId, project.id),
74166
- eq106(schedules.kind, SchedulableRunKinds["traffic-sync"])
74197
+ const schedule = tx.select().from(schedules).where(and92(
74198
+ eq107(schedules.projectId, project.id),
74199
+ eq107(schedules.kind, SchedulableRunKinds["traffic-sync"])
74167
74200
  )).get();
74168
74201
  if (schedule) {
74169
- tx.delete(schedules).where(eq106(schedules.id, schedule.id)).run();
74202
+ tx.delete(schedules).where(eq107(schedules.id, schedule.id)).run();
74170
74203
  scheduleAction = "delete";
74171
74204
  }
74172
74205
  }
74173
- const source = tx.select().from(trafficSources).where(eq106(trafficSources.id, target.id)).get();
74206
+ const source = tx.select().from(trafficSources).where(eq107(trafficSources.id, target.id)).get();
74174
74207
  writeAuditLog(tx, {
74175
74208
  projectId: project.id,
74176
74209
  actor: "api",
@@ -74238,7 +74271,7 @@ async function trafficRoutes(app, opts) {
74238
74271
  }
74239
74272
  const { bearerHash, credential } = authenticated;
74240
74273
  const sourceId = credential.sourceId;
74241
- const sourceRow2 = app.db.select().from(trafficSources).where(eq106(trafficSources.id, sourceId)).get();
74274
+ const sourceRow2 = app.db.select().from(trafficSources).where(eq107(trafficSources.id, sourceId)).get();
74242
74275
  if (!sourceRow2 || sourceRow2.sourceType !== TrafficSourceTypes.cloudflare || sourceRow2.status !== TrafficSourceStatuses.connected || !parseDirectPushCloudflareSourceConfig(sourceRow2.configJson) || !timingSafeEqualHex(bearerHash, sourceRow2.ingestTokenHash)) {
74243
74276
  throw authRequired();
74244
74277
  }
@@ -74318,7 +74351,7 @@ async function trafficRoutes(app, opts) {
74318
74351
  });
74319
74352
  app.post("/projects/:name/traffic/sources/:id/sync", async (request) => {
74320
74353
  const project = resolveProject(app.db, request.params.name);
74321
- const initialSourceRow = app.db.select().from(trafficSources).where(eq106(trafficSources.id, request.params.id)).get();
74354
+ const initialSourceRow = app.db.select().from(trafficSources).where(eq107(trafficSources.id, request.params.id)).get();
74322
74355
  if (!initialSourceRow || initialSourceRow.projectId !== project.id) {
74323
74356
  throw notFound("Traffic source", request.params.id);
74324
74357
  }
@@ -74392,7 +74425,7 @@ async function trafficRoutes(app, opts) {
74392
74425
  });
74393
74426
  const finishSync = (status, error, stopReason) => {
74394
74427
  const queueDrain = drainSummary(stopReason);
74395
- app.db.update(runs).set({ status, finishedAt: committedAt, syncSummary: queueDrain, ...error ? { error } : {} }).where(eq106(runs.id, runId)).run();
74428
+ app.db.update(runs).set({ status, finishedAt: committedAt, syncSummary: queueDrain, ...error ? { error } : {} }).where(eq107(runs.id, runId)).run();
74396
74429
  writeAuditLog(app.db, {
74397
74430
  projectId: project.id,
74398
74431
  actor: "api",
@@ -74569,7 +74602,7 @@ async function trafficRoutes(app, opts) {
74569
74602
  now: (/* @__PURE__ */ new Date()).toISOString(),
74570
74603
  ttlMs: CLOUDFLARE_QUEUE_SYNC_LEASE_TTL_MS
74571
74604
  })) throw new Error("Queue sync lease was lost before acknowledgement");
74572
- const latestSource = app.db.select().from(trafficSources).where(eq106(trafficSources.id, sourceRow2.id)).get();
74605
+ const latestSource = app.db.select().from(trafficSources).where(eq107(trafficSources.id, sourceRow2.id)).get();
74573
74606
  if (!latestSource || latestSource.projectId !== project.id || latestSource.status !== TrafficSourceStatuses.connected || latestSource.syncLeaseOwner !== leaseOwner || !isDeepStrictEqual(latestSource.configJson, sourceRow2.configJson)) {
74574
74607
  throw validationError("Cloudflare Queue source was reconfigured before acknowledgement");
74575
74608
  }
@@ -74659,13 +74692,13 @@ async function trafficRoutes(app, opts) {
74659
74692
  error: safeError,
74660
74693
  finishedAt: failedAt,
74661
74694
  syncSummary: drainSummary(CloudflareQueueDrainStopReasons.error)
74662
- }).where(eq106(runs.id, runId)).run();
74663
- const latestSource = tx.select().from(trafficSources).where(eq106(trafficSources.id, sourceRow2.id)).get();
74695
+ }).where(eq107(runs.id, runId)).run();
74696
+ const latestSource = tx.select().from(trafficSources).where(eq107(trafficSources.id, sourceRow2.id)).get();
74664
74697
  if (latestSource && latestSource.status === TrafficSourceStatuses.connected && latestSource.syncLeaseOwner === leaseOwner && isDeepStrictEqual(latestSource.configJson, sourceRow2.configJson)) {
74665
- tx.update(trafficSources).set({ lastError: safeError, updatedAt: failedAt }).where(and91(
74666
- eq106(trafficSources.id, sourceRow2.id),
74667
- eq106(trafficSources.status, TrafficSourceStatuses.connected),
74668
- eq106(trafficSources.syncLeaseOwner, leaseOwner)
74698
+ tx.update(trafficSources).set({ lastError: safeError, updatedAt: failedAt }).where(and92(
74699
+ eq107(trafficSources.id, sourceRow2.id),
74700
+ eq107(trafficSources.status, TrafficSourceStatuses.connected),
74701
+ eq107(trafficSources.syncLeaseOwner, leaseOwner)
74669
74702
  )).run();
74670
74703
  }
74671
74704
  });
@@ -74684,7 +74717,7 @@ async function trafficRoutes(app, opts) {
74684
74717
  `Sync for source type "${sourceRow2.sourceType}" is not implemented yet \u2014 only cloud-run, wordpress, and vercel are supported in v1.`
74685
74718
  );
74686
74719
  }
74687
- const hasConnectedSibling = sourceRow2.status === TrafficSourceStatuses.error && app.db.select().from(trafficSources).where(eq106(trafficSources.projectId, project.id)).all().some((row) => row.id !== sourceRow2.id && row.status === TrafficSourceStatuses.connected);
74720
+ const hasConnectedSibling = sourceRow2.status === TrafficSourceStatuses.error && app.db.select().from(trafficSources).where(eq107(trafficSources.projectId, project.id)).all().some((row) => row.id !== sourceRow2.id && row.status === TrafficSourceStatuses.connected);
74688
74721
  if (sourceRow2.status === TrafficSourceStatuses.paused || sourceRow2.status === TrafficSourceStatuses.archived || hasConnectedSibling) {
74689
74722
  throw validationError("Traffic source must be active before it can sync");
74690
74723
  }
@@ -74722,10 +74755,10 @@ async function trafficRoutes(app, opts) {
74722
74755
  const markFailed = (msg, errorCode2) => {
74723
74756
  const failedAt = (/* @__PURE__ */ new Date()).toISOString();
74724
74757
  app.db.transaction((tx) => {
74725
- tx.update(runs).set({ status: RunStatuses.failed, error: msg, finishedAt: failedAt }).where(eq106(runs.id, runId)).run();
74726
- const latestSource = tx.select().from(trafficSources).where(eq106(trafficSources.id, sourceRow2.id)).get();
74758
+ tx.update(runs).set({ status: RunStatuses.failed, error: msg, finishedAt: failedAt }).where(eq107(runs.id, runId)).run();
74759
+ const latestSource = tx.select().from(trafficSources).where(eq107(trafficSources.id, sourceRow2.id)).get();
74727
74760
  if (latestSource?.status === TrafficSourceStatuses.connected && isSameTrafficSourceGeneration(latestSource, sourceRow2) && latestSource.syncLeaseOwner === syncLeaseOwner) {
74728
- tx.update(trafficSources).set({ status: TrafficSourceStatuses.error, lastError: msg, updatedAt: failedAt }).where(eq106(trafficSources.id, sourceRow2.id)).run();
74761
+ tx.update(trafficSources).set({ status: TrafficSourceStatuses.error, lastError: msg, updatedAt: failedAt }).where(eq107(trafficSources.id, sourceRow2.id)).run();
74729
74762
  }
74730
74763
  });
74731
74764
  try {
@@ -74807,7 +74840,7 @@ async function trafficRoutes(app, opts) {
74807
74840
  }
74808
74841
  const credential = credentialStore.getConnection(project.name);
74809
74842
  if (!credential) {
74810
- app.db.delete(runs).where(eq106(runs.id, runId)).run();
74843
+ app.db.delete(runs).where(eq107(runs.id, runId)).run();
74811
74844
  throw validationError(
74812
74845
  `No WordPress credential found for project "${project.name}". Run "canonry traffic connect wordpress" first.`
74813
74846
  );
@@ -74841,14 +74874,14 @@ async function trafficRoutes(app, opts) {
74841
74874
  const windowEndIso2 = windowEnd.toISOString();
74842
74875
  const reservedAt = (/* @__PURE__ */ new Date()).toISOString();
74843
74876
  const reservedSource = app.db.transaction((tx) => {
74844
- const latestSource = tx.select().from(trafficSources).where(eq106(trafficSources.id, sourceRow2.id)).get();
74877
+ const latestSource = tx.select().from(trafficSources).where(eq107(trafficSources.id, sourceRow2.id)).get();
74845
74878
  if (!latestSource || !isAuthoritativeTrafficSource(tx, latestSource) || !isSameTrafficSourceGeneration(latestSource, sourceRow2) || latestSource.syncLeaseOwner !== syncLeaseOwner || latestSource.lastCursor || latestSource.wordpressPendingUntil) return void 0;
74846
74879
  tx.update(trafficSources).set({
74847
74880
  lastSyncedAt: windowStartIso2,
74848
74881
  wordpressPendingUntil: windowEndIso2,
74849
74882
  updatedAt: reservedAt
74850
- }).where(eq106(trafficSources.id, sourceRow2.id)).run();
74851
- return tx.select().from(trafficSources).where(eq106(trafficSources.id, sourceRow2.id)).get();
74883
+ }).where(eq107(trafficSources.id, sourceRow2.id)).run();
74884
+ return tx.select().from(trafficSources).where(eq107(trafficSources.id, sourceRow2.id)).get();
74852
74885
  }, { behavior: "immediate" });
74853
74886
  if (!reservedSource) {
74854
74887
  const message = "Traffic source changed while reserving the WordPress sync window; retry the sync.";
@@ -74908,12 +74941,12 @@ async function trafficRoutes(app, opts) {
74908
74941
  auditAction = "traffic.vercel.synced";
74909
74942
  const credentialStore = opts.vercelTrafficCredentialStore;
74910
74943
  if (!credentialStore) {
74911
- app.db.delete(runs).where(eq106(runs.id, runId)).run();
74944
+ app.db.delete(runs).where(eq107(runs.id, runId)).run();
74912
74945
  throw validationError("Vercel traffic credential storage is not configured for this deployment");
74913
74946
  }
74914
74947
  const credential = credentialStore.getConnection(project.name);
74915
74948
  if (!credential) {
74916
- app.db.delete(runs).where(eq106(runs.id, runId)).run();
74949
+ app.db.delete(runs).where(eq107(runs.id, runId)).run();
74917
74950
  throw validationError(
74918
74951
  `No Vercel credential found for project "${project.name}". Run "canonry traffic connect vercel" first.`
74919
74952
  );
@@ -74931,7 +74964,7 @@ async function trafficRoutes(app, opts) {
74931
74964
  if (cappedStartMs > clampedStartMs) {
74932
74965
  const previousSkip = sourceRow2.skippedThroughAt ? Date.parse(sourceRow2.skippedThroughAt) : Number.NaN;
74933
74966
  const skippedThrough = Number.isFinite(previousSkip) ? new Date(Math.max(previousSkip, cappedStartMs)) : new Date(cappedStartMs);
74934
- app.db.update(trafficSources).set({ skippedThroughAt: skippedThrough.toISOString() }).where(eq106(trafficSources.id, sourceRow2.id)).run();
74967
+ app.db.update(trafficSources).set({ skippedThroughAt: skippedThrough.toISOString() }).where(eq107(trafficSources.id, sourceRow2.id)).run();
74935
74968
  request.log.warn(
74936
74969
  {
74937
74970
  sourceId: sourceRow2.id,
@@ -75026,15 +75059,15 @@ async function trafficRoutes(app, opts) {
75026
75059
  throw providerError(`WordPress sync failed: ${msg}`);
75027
75060
  }
75028
75061
  const commitOutcome = app.db.transaction((tx) => {
75029
- const latestRow = tx.select().from(trafficSources).where(eq106(trafficSources.id, sourceRow2.id)).get();
75030
- const latestHasConnectedSibling = tx.select().from(trafficSources).where(eq106(trafficSources.projectId, project.id)).all().some((row) => row.id !== sourceRow2.id && row.status === TrafficSourceStatuses.connected);
75062
+ const latestRow = tx.select().from(trafficSources).where(eq107(trafficSources.id, sourceRow2.id)).get();
75063
+ const latestHasConnectedSibling = tx.select().from(trafficSources).where(eq107(trafficSources.projectId, project.id)).all().some((row) => row.id !== sourceRow2.id && row.status === TrafficSourceStatuses.connected);
75031
75064
  if (!latestRow || latestRow.status !== TrafficSourceStatuses.connected && latestRow.status !== TrafficSourceStatuses.error || latestHasConnectedSibling || latestRow.syncLeaseOwner !== syncLeaseOwner || !isSameTrafficSourceGeneration(latestRow, sourceRow2)) {
75032
75065
  const abortedAt = (/* @__PURE__ */ new Date()).toISOString();
75033
75066
  tx.update(runs).set({
75034
75067
  status: RunStatuses.failed,
75035
75068
  error: "Traffic source was deactivated or reconfigured during sync",
75036
75069
  finishedAt: abortedAt
75037
- }).where(eq106(runs.id, runId)).run();
75070
+ }).where(eq107(runs.id, runId)).run();
75038
75071
  return "source-inactive";
75039
75072
  }
75040
75073
  const previousIds = latestRow.lastEventIds ?? [];
@@ -75321,8 +75354,8 @@ async function trafficRoutes(app, opts) {
75321
75354
  sourceUpdate.lastCursor = nextCursor ?? null;
75322
75355
  sourceUpdate.wordpressPendingUntil = nextCursor ? windowEnd.toISOString() : null;
75323
75356
  }
75324
- tx.update(trafficSources).set(sourceUpdate).where(eq106(trafficSources.id, sourceRow2.id)).run();
75325
- tx.update(runs).set({ status: RunStatuses.completed, finishedAt }).where(eq106(runs.id, runId)).run();
75357
+ tx.update(trafficSources).set(sourceUpdate).where(eq107(trafficSources.id, sourceRow2.id)).run();
75358
+ tx.update(runs).set({ status: RunStatuses.completed, finishedAt }).where(eq107(runs.id, runId)).run();
75326
75359
  return "committed";
75327
75360
  }, { behavior: "immediate" });
75328
75361
  if (commitOutcome === "source-inactive") {
@@ -75393,7 +75426,7 @@ async function trafficRoutes(app, opts) {
75393
75426
  });
75394
75427
  app.post("/projects/:name/traffic/sources/:id/backfill", async (request) => withFeatureOutcome(app, { feature: "server_traffic", operation: "backfill" }, async (recordOutcome) => {
75395
75428
  const project = resolveProject(app.db, request.params.name);
75396
- const sourceRow2 = app.db.select().from(trafficSources).where(eq106(trafficSources.id, request.params.id)).get();
75429
+ const sourceRow2 = app.db.select().from(trafficSources).where(eq107(trafficSources.id, request.params.id)).get();
75397
75430
  if (!sourceRow2 || sourceRow2.projectId !== project.id) {
75398
75431
  throw notFound("Traffic source", request.params.id);
75399
75432
  }
@@ -75508,7 +75541,7 @@ async function trafficRoutes(app, opts) {
75508
75541
  }
75509
75542
  try {
75510
75543
  app.db.transaction((tx) => {
75511
- const latestSource = tx.select().from(trafficSources).where(eq106(trafficSources.id, sourceRow2.id)).get();
75544
+ const latestSource = tx.select().from(trafficSources).where(eq107(trafficSources.id, sourceRow2.id)).get();
75512
75545
  if (!latestSource || !isAuthoritativeTrafficSource(tx, latestSource) || !isSameTrafficSourceGeneration(latestSource, sourceRow2)) {
75513
75546
  throw validationError("Traffic source must remain active and unchanged before it can backfill");
75514
75547
  }
@@ -75559,8 +75592,8 @@ async function trafficRoutes(app, opts) {
75559
75592
  pathNormalized: crawlerEventsHourly.pathNormalized,
75560
75593
  hits: sql48`COALESCE(SUM(${crawlerEventsHourly.hits}), 0)`
75561
75594
  }).from(crawlerEventsHourly).where(
75562
- and91(
75563
- eq106(crawlerEventsHourly.sourceId, row.id),
75595
+ and92(
75596
+ eq107(crawlerEventsHourly.sourceId, row.id),
75564
75597
  gte27(crawlerEventsHourly.tsHour, since)
75565
75598
  )
75566
75599
  ).groupBy(crawlerEventsHourly.pathNormalized).all();
@@ -75569,14 +75602,14 @@ async function trafficRoutes(app, opts) {
75569
75602
  );
75570
75603
  const crawlerTotal = crawlerSegments.content + crawlerSegments.sitemap + crawlerSegments.robots + crawlerSegments.asset + crawlerSegments.other;
75571
75604
  const aiUserFetchTotals = app.db.select({ total: sql48`COALESCE(SUM(${aiUserFetchEventsHourly.hits}), 0)` }).from(aiUserFetchEventsHourly).where(
75572
- and91(
75573
- eq106(aiUserFetchEventsHourly.sourceId, row.id),
75605
+ and92(
75606
+ eq107(aiUserFetchEventsHourly.sourceId, row.id),
75574
75607
  gte27(aiUserFetchEventsHourly.tsHour, since)
75575
75608
  )
75576
75609
  ).get();
75577
75610
  const likelyFakeTotals = app.db.select({ total: sql48`COALESCE(SUM(${aiUserFetchLikelyFakeHourly.hits}), 0)` }).from(aiUserFetchLikelyFakeHourly).where(
75578
- and91(
75579
- eq106(aiUserFetchLikelyFakeHourly.sourceId, row.id),
75611
+ and92(
75612
+ eq107(aiUserFetchLikelyFakeHourly.sourceId, row.id),
75580
75613
  gte27(aiUserFetchLikelyFakeHourly.tsHour, since)
75581
75614
  )
75582
75615
  ).get();
@@ -75585,22 +75618,22 @@ async function trafficRoutes(app, opts) {
75585
75618
  nonhop: sql48`COALESCE(SUM(CASE WHEN ${referralLandedCondition()} THEN ${aiReferralEventsHourly.sessionsOrHits} ELSE 0 END), 0)`,
75586
75619
  landed: sql48`COALESCE(SUM(CASE WHEN ${countableReferralCondition()} THEN ${aiReferralEventsHourly.sessionsOrHits} ELSE 0 END), 0)`
75587
75620
  }).from(aiReferralEventsHourly).where(
75588
- and91(
75589
- eq106(aiReferralEventsHourly.sourceId, row.id),
75621
+ and92(
75622
+ eq107(aiReferralEventsHourly.sourceId, row.id),
75590
75623
  gte27(aiReferralEventsHourly.tsHour, since)
75591
75624
  )
75592
75625
  ).get();
75593
75626
  const sampleTotals = app.db.select({ total: sql48`COUNT(*)` }).from(rawEventSamples).where(
75594
- and91(
75595
- eq106(rawEventSamples.sourceId, row.id),
75627
+ and92(
75628
+ eq107(rawEventSamples.sourceId, row.id),
75596
75629
  gte27(rawEventSamples.ts, since)
75597
75630
  )
75598
75631
  ).get();
75599
75632
  const latestRun2 = app.db.select().from(runs).where(
75600
- and91(
75601
- eq106(runs.projectId, projectId),
75602
- eq106(runs.kind, RunKinds["traffic-sync"]),
75603
- eq106(runs.sourceId, row.id)
75633
+ and92(
75634
+ eq107(runs.projectId, projectId),
75635
+ eq107(runs.kind, RunKinds["traffic-sync"]),
75636
+ eq107(runs.sourceId, row.id)
75604
75637
  )
75605
75638
  ).orderBy(desc49(runs.startedAt)).limit(1).get();
75606
75639
  return {
@@ -75638,7 +75671,7 @@ async function trafficRoutes(app, opts) {
75638
75671
  const now = (/* @__PURE__ */ new Date()).toISOString();
75639
75672
  let updatedRow;
75640
75673
  app.db.transaction((tx) => {
75641
- const sourceRow2 = tx.select().from(trafficSources).where(and91(eq106(trafficSources.projectId, project.id), eq106(trafficSources.id, request.params.id))).get();
75674
+ const sourceRow2 = tx.select().from(trafficSources).where(and92(eq107(trafficSources.projectId, project.id), eq107(trafficSources.id, request.params.id))).get();
75642
75675
  if (!sourceRow2) {
75643
75676
  throw notFound("traffic source", request.params.id);
75644
75677
  }
@@ -75652,7 +75685,7 @@ async function trafficRoutes(app, opts) {
75652
75685
  `Traffic source "${sourceRow2.id}" is staged. Activate it explicitly instead of resetting it.`
75653
75686
  );
75654
75687
  }
75655
- const hasConnectedSibling = tx.select().from(trafficSources).where(eq106(trafficSources.projectId, project.id)).all().some((row) => row.id !== sourceRow2.id && row.status === TrafficSourceStatuses.connected);
75688
+ const hasConnectedSibling = tx.select().from(trafficSources).where(eq107(trafficSources.projectId, project.id)).all().some((row) => row.id !== sourceRow2.id && row.status === TrafficSourceStatuses.connected);
75656
75689
  if (hasConnectedSibling) {
75657
75690
  throw validationError(
75658
75691
  `Traffic source "${sourceRow2.id}" is not authoritative. Activate it explicitly instead of resetting it.`
@@ -75669,7 +75702,7 @@ async function trafficRoutes(app, opts) {
75669
75702
  status: TrafficSourceStatuses.connected,
75670
75703
  lastError: null,
75671
75704
  updatedAt: now
75672
- }).where(eq106(trafficSources.id, sourceRow2.id)).run();
75705
+ }).where(eq107(trafficSources.id, sourceRow2.id)).run();
75673
75706
  writeAuditLog(tx, auditFromRequest(request, {
75674
75707
  projectId: project.id,
75675
75708
  actor: "api",
@@ -75677,7 +75710,7 @@ async function trafficRoutes(app, opts) {
75677
75710
  entityType: "traffic_source",
75678
75711
  entityId: sourceRow2.id
75679
75712
  }));
75680
- updatedRow = tx.select().from(trafficSources).where(eq106(trafficSources.id, sourceRow2.id)).get();
75713
+ updatedRow = tx.select().from(trafficSources).where(eq107(trafficSources.id, sourceRow2.id)).get();
75681
75714
  });
75682
75715
  return buildSourceDetail(project.id, updatedRow, new Date(Date.now() - 24 * 60 * 6e4).toISOString());
75683
75716
  }));
@@ -75689,7 +75722,7 @@ async function trafficRoutes(app, opts) {
75689
75722
  }
75690
75723
  let updatedRow;
75691
75724
  app.db.transaction((tx) => {
75692
- const sourceRow2 = tx.select().from(trafficSources).where(and91(eq106(trafficSources.projectId, project.id), eq106(trafficSources.id, request.params.id))).get();
75725
+ const sourceRow2 = tx.select().from(trafficSources).where(and92(eq107(trafficSources.projectId, project.id), eq107(trafficSources.id, request.params.id))).get();
75693
75726
  if (!sourceRow2) {
75694
75727
  throw notFound("traffic source", request.params.id);
75695
75728
  }
@@ -75702,7 +75735,7 @@ async function trafficRoutes(app, opts) {
75702
75735
  );
75703
75736
  }
75704
75737
  const now = (/* @__PURE__ */ new Date()).toISOString();
75705
- tx.update(trafficSources).set({ skippedThroughAt: null, updatedAt: now }).where(eq106(trafficSources.id, sourceRow2.id)).run();
75738
+ tx.update(trafficSources).set({ skippedThroughAt: null, updatedAt: now }).where(eq107(trafficSources.id, sourceRow2.id)).run();
75706
75739
  writeAuditLog(tx, auditFromRequest(request, {
75707
75740
  projectId: project.id,
75708
75741
  actor: "api",
@@ -75711,20 +75744,20 @@ async function trafficRoutes(app, opts) {
75711
75744
  entityId: sourceRow2.id,
75712
75745
  diff: { skippedThroughAt: sourceRow2.skippedThroughAt, sourceType: sourceRow2.sourceType }
75713
75746
  }));
75714
- updatedRow = tx.select().from(trafficSources).where(eq106(trafficSources.id, sourceRow2.id)).get();
75747
+ updatedRow = tx.select().from(trafficSources).where(eq107(trafficSources.id, sourceRow2.id)).get();
75715
75748
  });
75716
75749
  return buildSourceDetail(project.id, updatedRow, new Date(Date.now() - 24 * 60 * 6e4).toISOString());
75717
75750
  });
75718
75751
  app.get("/projects/:name/traffic/sources", async (request) => {
75719
75752
  const project = resolveProject(app.db, request.params.name);
75720
- const rows = app.db.select().from(trafficSources).where(eq106(trafficSources.projectId, project.id)).orderBy(desc49(trafficSources.createdAt)).all();
75753
+ const rows = app.db.select().from(trafficSources).where(eq107(trafficSources.projectId, project.id)).orderBy(desc49(trafficSources.createdAt)).all();
75721
75754
  const sources = rows.filter((row) => row.status !== TrafficSourceStatuses.archived).map(rowToDto);
75722
75755
  const response = { sources };
75723
75756
  return response;
75724
75757
  });
75725
75758
  app.get("/projects/:name/traffic/status", async (request) => {
75726
75759
  const project = resolveProject(app.db, request.params.name);
75727
- const rows = app.db.select().from(trafficSources).where(eq106(trafficSources.projectId, project.id)).orderBy(desc49(trafficSources.createdAt)).all();
75760
+ const rows = app.db.select().from(trafficSources).where(eq107(trafficSources.projectId, project.id)).orderBy(desc49(trafficSources.createdAt)).all();
75728
75761
  const since = new Date(Date.now() - 24 * 60 * 6e4).toISOString();
75729
75762
  const sources = rows.filter((row) => row.status !== TrafficSourceStatuses.archived).map((row) => buildSourceDetail(project.id, row, since));
75730
75763
  const response = { sources };
@@ -75734,7 +75767,7 @@ async function trafficRoutes(app, opts) {
75734
75767
  "/projects/:name/traffic/sources/:id",
75735
75768
  async (request) => {
75736
75769
  const project = resolveProject(app.db, request.params.name);
75737
- const row = app.db.select().from(trafficSources).where(eq106(trafficSources.id, request.params.id)).get();
75770
+ const row = app.db.select().from(trafficSources).where(eq107(trafficSources.id, request.params.id)).get();
75738
75771
  if (!row || row.projectId !== project.id) {
75739
75772
  throw notFound("Traffic source", request.params.id);
75740
75773
  }
@@ -75813,7 +75846,7 @@ async function trafficRoutes(app, opts) {
75813
75846
  agent: agentFilter
75814
75847
  };
75815
75848
  const cursor = cursorParam === null ? null : decodeTrafficEventCursor(cursorParam, readFilters, sinceIso, untilIso);
75816
- const pageRows = (table, where, read) => read(cursor ? and91(where, trafficEventCursorPredicate(table, cursor)) : where, trafficEventOrder(table), limit + 1).map((row) => ({
75849
+ const pageRows = (table, where, read) => read(cursor ? and92(where, trafficEventCursorPredicate(table, cursor)) : where, trafficEventOrder(table), limit + 1).map((row) => ({
75817
75850
  rank: table.rank,
75818
75851
  tsHour: row.tsHour,
75819
75852
  keys: table.keyFields.map((field) => row[field]),
@@ -75845,13 +75878,13 @@ async function trafficRoutes(app, opts) {
75845
75878
  const seriesByBucket = /* @__PURE__ */ new Map();
75846
75879
  if (kinds.has(TrafficEventKinds.crawler)) {
75847
75880
  const crawlerFilters = [
75848
- eq106(crawlerEventsHourly.projectId, project.id),
75881
+ eq107(crawlerEventsHourly.projectId, project.id),
75849
75882
  gte27(crawlerEventsHourly.tsHour, sinceIso),
75850
75883
  lte27(crawlerEventsHourly.tsHour, untilIso)
75851
75884
  ];
75852
- if (sourceIdParam) crawlerFilters.push(eq106(crawlerEventsHourly.sourceId, sourceIdParam));
75885
+ if (sourceIdParam) crawlerFilters.push(eq107(crawlerEventsHourly.sourceId, sourceIdParam));
75853
75886
  crawlerFilters.push(...trafficEventFilterPredicates(TRAFFIC_EVENT_TABLES.crawler, readFilters));
75854
- const crawlerWhere = and91(...crawlerFilters);
75887
+ const crawlerWhere = and92(...crawlerFilters);
75855
75888
  collectGroups(TRAFFIC_EVENT_TABLES.crawler, crawlerWhere);
75856
75889
  const pathTotals = app.db.select({
75857
75890
  pathNormalized: crawlerEventsHourly.pathNormalized,
@@ -75927,13 +75960,13 @@ async function trafficRoutes(app, opts) {
75927
75960
  }
75928
75961
  if (kinds.has(TrafficEventKinds["ai-user-fetch"])) {
75929
75962
  const userFetchFilters = [
75930
- eq106(aiUserFetchEventsHourly.projectId, project.id),
75963
+ eq107(aiUserFetchEventsHourly.projectId, project.id),
75931
75964
  gte27(aiUserFetchEventsHourly.tsHour, sinceIso),
75932
75965
  lte27(aiUserFetchEventsHourly.tsHour, untilIso)
75933
75966
  ];
75934
- if (sourceIdParam) userFetchFilters.push(eq106(aiUserFetchEventsHourly.sourceId, sourceIdParam));
75967
+ if (sourceIdParam) userFetchFilters.push(eq107(aiUserFetchEventsHourly.sourceId, sourceIdParam));
75935
75968
  userFetchFilters.push(...trafficEventFilterPredicates(TRAFFIC_EVENT_TABLES["ai-user-fetch"], readFilters));
75936
- const userFetchWhere = and91(...userFetchFilters);
75969
+ const userFetchWhere = and92(...userFetchFilters);
75937
75970
  collectGroups(TRAFFIC_EVENT_TABLES["ai-user-fetch"], userFetchWhere);
75938
75971
  const total = app.db.select({
75939
75972
  total: sql48`COALESCE(SUM(${aiUserFetchEventsHourly.hits}), 0)`,
@@ -75973,13 +76006,13 @@ async function trafficRoutes(app, opts) {
75973
76006
  }
75974
76007
  if (kinds.has(TrafficEventKinds["ai-referral"])) {
75975
76008
  const aiFilters = [
75976
- eq106(aiReferralEventsHourly.projectId, project.id),
76009
+ eq107(aiReferralEventsHourly.projectId, project.id),
75977
76010
  gte27(aiReferralEventsHourly.tsHour, sinceIso),
75978
76011
  lte27(aiReferralEventsHourly.tsHour, untilIso)
75979
76012
  ];
75980
- if (sourceIdParam) aiFilters.push(eq106(aiReferralEventsHourly.sourceId, sourceIdParam));
76013
+ if (sourceIdParam) aiFilters.push(eq107(aiReferralEventsHourly.sourceId, sourceIdParam));
75981
76014
  aiFilters.push(...trafficEventFilterPredicates(TRAFFIC_EVENT_TABLES["ai-referral"], readFilters));
75982
- const aiWhere = and91(...aiFilters);
76015
+ const aiWhere = and92(...aiFilters);
75983
76016
  collectGroups(TRAFFIC_EVENT_TABLES["ai-referral"], aiWhere);
75984
76017
  const total = app.db.select({
75985
76018
  total: sql48`COALESCE(SUM(${aiReferralEventsHourly.sessionsOrHits}), 0)`,
@@ -76063,7 +76096,7 @@ async function trafficRoutes(app, opts) {
76063
76096
  windowEnd: untilIso,
76064
76097
  series: (() => {
76065
76098
  const points = completeTrafficSeries(since, until, granularity, seriesByBucket);
76066
- const coverageScope = (col, srcCol) => sourceIdParam ? and91(eq106(col, project.id), eq106(srcCol, sourceIdParam)) : eq106(col, project.id);
76099
+ const coverageScope = (col, srcCol) => sourceIdParam ? and92(eq107(col, project.id), eq107(srcCol, sourceIdParam)) : eq107(col, project.id);
76067
76100
  const firsts = [
76068
76101
  app.db.select({ v: sql48`MIN(${crawlerEventsHourly.tsHour})` }).from(crawlerEventsHourly).where(coverageScope(crawlerEventsHourly.projectId, crawlerEventsHourly.sourceId)).get()?.v,
76069
76102
  app.db.select({ v: sql48`MIN(${aiUserFetchEventsHourly.tsHour})` }).from(aiUserFetchEventsHourly).where(coverageScope(aiUserFetchEventsHourly.projectId, aiUserFetchEventsHourly.sourceId)).get()?.v,
@@ -76082,6 +76115,17 @@ async function trafficRoutes(app, opts) {
76082
76115
  for (const pt of points) {
76083
76116
  pt.measured = coverageKey === null ? false : seriesBucketOf(pt.bucket, granularity) >= coverageKey;
76084
76117
  }
76118
+ const recorded = trafficRecordedThrough(app.db, project.id, sourceIdParam);
76119
+ const stoppedBuckets = /* @__PURE__ */ new Set();
76120
+ for (const pt of points) {
76121
+ if (!pt.measured) continue;
76122
+ const startMs = bucketStartMs(pt.bucket);
76123
+ if (recorded.anyThroughMs !== null && startMs >= recorded.anyThroughMs) {
76124
+ pt.measured = false;
76125
+ } else if (recorded.allThroughMs !== null && nextSeriesBucketStartMs(startMs, granularity) > recorded.allThroughMs) {
76126
+ stoppedBuckets.add(pt.bucket);
76127
+ }
76128
+ }
76085
76129
  const firstMeasuredIdx = points.findIndex((pt) => pt.measured);
76086
76130
  const coverageStartMs = coverageStart === null ? null : Date.parse(coverageStart);
76087
76131
  const leadingBucketIsPartial = firstMeasuredIdx >= 0 && coverageStartMs !== null && Number.isFinite(coverageStartMs) && Math.max(coverageStartMs, since.getTime()) > bucketStartMs(points[firstMeasuredIdx].bucket);
@@ -76091,16 +76135,17 @@ async function trafficRoutes(app, opts) {
76091
76135
  coverageStart,
76092
76136
  aiReferralCountingChangedAt: referralCountingChangedAt,
76093
76137
  aiUserFetchCountingChangedAt: userFetchCountingChangedAt,
76094
- // The same two edges the fits leave out, named for a chart to draw as partial.
76095
- partialBuckets: [
76096
- ...firstMeasuredIdx >= 0 && leadingBucketIsPartial ? [points[firstMeasuredIdx].bucket] : [],
76097
- ...trailingBucketIsPartial && lastBucket !== null && !(points.length - 1 === firstMeasuredIdx && leadingBucketIsPartial) ? [lastBucket] : []
76098
- ],
76138
+ recordedThrough: recorded.anyThroughMs === null ? null : new Date(recorded.anyThroughMs).toISOString(),
76139
+ // The buckets the fits leave out as partial, in bucket order, named for
76140
+ // a chart to draw as partial. An unmeasured bucket is never partial.
76141
+ partialBuckets: points.filter((pt, i) => pt.measured && (i === firstMeasuredIdx && leadingBucketIsPartial || stoppedBuckets.has(pt.bucket) || i === points.length - 1 && trailingBucketIsPartial)).map((pt) => pt.bucket),
76099
76142
  // Two edges are excluded from the fit, both for the same reason: a
76100
76143
  // bucket that is not a full reading must not be treated as one.
76101
76144
  //
76102
- // Leading: unmeasured buckets predate recording, so they are the
76103
- // ABSENCE of a reading, not a reading of zero. The first MEASURED
76145
+ // Leading: unmeasured buckets predate recording (or follow every
76146
+ // source's last sync), so they are the ABSENCE of a reading, not a
76147
+ // reading of zero. Buckets a source stopped reporting inside or before
76148
+ // go too, for the same reason. The first MEASURED
76104
76149
  // bucket goes too when recording or the range began inside it, since
76105
76150
  // a fraction of a bucket read as a whole slopes the fit up out of nothing.
76106
76151
  //
@@ -76120,7 +76165,7 @@ async function trafficRoutes(app, opts) {
76120
76165
  // linearTrend skips nulls while surviving points keep their true
76121
76166
  // index, so dropping an edge does not compress the x-axis.
76122
76167
  trends: (() => {
76123
- const usable = (pt, i) => pt.measured && !(i === firstMeasuredIdx && leadingBucketIsPartial) && !(i === points.length - 1 && trailingBucketIsPartial);
76168
+ const usable = (pt, i) => pt.measured && !(i === firstMeasuredIdx && leadingBucketIsPartial) && !stoppedBuckets.has(pt.bucket) && !(i === points.length - 1 && trailingBucketIsPartial);
76124
76169
  const countedByCurrentRule = (pt) => referralCountingChangedMs === null || bucketStartMs(pt.bucket) >= referralCountingChangedMs;
76125
76170
  const countedByPageLoads = (pt) => userFetchCountingChangedMs === null || bucketStartMs(pt.bucket) >= userFetchCountingChangedMs;
76126
76171
  const series = (pick, include = () => true) => linearTrend(points.map((pt, i) => usable(pt, i) && include(pt) ? pick(pt) : null));
@@ -76168,7 +76213,7 @@ async function trafficRoutes(app, opts) {
76168
76213
  }
76169
76214
 
76170
76215
  // ../api-routes/src/doctor/checks/report-sweeps.ts
76171
- import { and as and92, asc as asc28, eq as eq107, gte as gte28, lte as lte28 } from "drizzle-orm";
76216
+ import { and as and93, asc as asc28, eq as eq108, gte as gte28, lte as lte28 } from "drizzle-orm";
76172
76217
 
76173
76218
  // ../api-routes/src/visibility-attribution.ts
76174
76219
  function buildQueryAttribution2(projectQueries) {
@@ -76202,11 +76247,11 @@ function inspectSweep(ctx, run) {
76202
76247
  answerMentioned: querySnapshots.answerMentioned,
76203
76248
  answerText: querySnapshots.answerText,
76204
76249
  measurementExecutionId: querySnapshots.measurementExecutionId
76205
- }).from(querySnapshots).where(eq107(querySnapshots.runId, run.id)).all();
76250
+ }).from(querySnapshots).where(eq108(querySnapshots.runId, run.id)).all();
76206
76251
  if (snapshots.length === 0) return { detail: { ...base, complete: false, reason: "no-answers" } };
76207
76252
  try {
76208
76253
  if (run.measurementPlanVersionId) {
76209
- const version = ctx.db.select().from(measurementPlanVersions).where(and92(eq107(measurementPlanVersions.projectId, ctx.project.id), eq107(measurementPlanVersions.id, run.measurementPlanVersionId))).get();
76254
+ const version = ctx.db.select().from(measurementPlanVersions).where(and93(eq108(measurementPlanVersions.projectId, ctx.project.id), eq108(measurementPlanVersions.id, run.measurementPlanVersionId))).get();
76210
76255
  if (!version) return { detail: { ...base, complete: false, reason: "missing-plan" } };
76211
76256
  const plan = parseStoredMeasurementPlanAnyVersion(version.canonicalJson);
76212
76257
  const manifest = measurementRunExpectedSlots(run, plan);
@@ -76238,10 +76283,10 @@ function inspectSweep(ctx, run) {
76238
76283
  };
76239
76284
  return unbound ? { detail } : { detail, coverage: slotCoverage(expected2, answered3) };
76240
76285
  }
76241
- const stored = ctx.db.select().from(simpleMeasurementDefinitions).where(eq107(simpleMeasurementDefinitions.runId, run.id)).get();
76286
+ const stored = ctx.db.select().from(simpleMeasurementDefinitions).where(eq108(simpleMeasurementDefinitions.runId, run.id)).get();
76242
76287
  const frozen = stored ? simpleMeasurementDefinitionSchema.parse(stored.definition) : null;
76243
- const project = ctx.db.select().from(projects).where(eq107(projects.id, ctx.project.id)).get();
76244
- 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(eq107(queries.projectId, project.id)).all();
76288
+ const project = ctx.db.select().from(projects).where(eq108(projects.id, ctx.project.id)).get();
76289
+ 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(eq108(queries.projectId, project.id)).all();
76245
76290
  const providers = frozen ? frozen.engines.map((engine) => engine.provider) : project.providers.length > 0 ? project.providers : [...new Set(snapshots.map((snapshot) => snapshot.provider))];
76246
76291
  const attribution = buildQueryAttribution2(basket);
76247
76292
  const expected = new Set(basket.flatMap((query2) => providers.map((provider) => JSON.stringify([query2.id, provider.trim().toLowerCase()]))));
@@ -76290,7 +76335,7 @@ var reportSweepsCheck = {
76290
76335
  const graded = gradedReportMonths(reportMonths, now);
76291
76336
  const months = reportMonths.map((month) => {
76292
76337
  const bounds = calendarMonthBounds(month);
76293
- const monthRuns = ctx.db.select().from(runs).where(and92(eq107(runs.projectId, ctx.project.id), eq107(runs.kind, RunKinds["answer-visibility"]), notProbeRun(), gte28(runs.createdAt, bounds.since), lte28(runs.createdAt, bounds.until))).orderBy(asc28(runs.createdAt), asc28(runs.id)).all();
76338
+ const monthRuns = ctx.db.select().from(runs).where(and93(eq108(runs.projectId, ctx.project.id), eq108(runs.kind, RunKinds["answer-visibility"]), notProbeRun(), gte28(runs.createdAt, bounds.since), lte28(runs.createdAt, bounds.until))).orderBy(asc28(runs.createdAt), asc28(runs.id)).all();
76294
76339
  const evidence = monthRuns.map((run) => inspectSweep(ctx, run));
76295
76340
  return {
76296
76341
  month,
@@ -76313,7 +76358,7 @@ var reportSweepsCheck = {
76313
76358
  };
76314
76359
 
76315
76360
  // ../api-routes/src/doctor/checks/report-models.ts
76316
- import { and as and93, eq as eq108, gte as gte29, inArray as inArray51, lte as lte29 } from "drizzle-orm";
76361
+ import { and as and94, eq as eq109, gte as gte29, inArray as inArray51, lte as lte29 } from "drizzle-orm";
76317
76362
  var reportModelsCheck = {
76318
76363
  id: "report.models",
76319
76364
  category: CheckCategories.providers,
@@ -76328,7 +76373,7 @@ var reportModelsCheck = {
76328
76373
  const months = reportMonths.flatMap((month) => {
76329
76374
  const bounds = calendarMonthBounds(month);
76330
76375
  const previous = new Date(Date.parse(bounds.since) - 1).toISOString().slice(0, 7);
76331
- const observations = ctx.db.select({ provider: querySnapshots.provider, model: querySnapshots.model, at: runs.createdAt }).from(querySnapshots).innerJoin(runs, eq108(runs.id, querySnapshots.runId)).where(and93(eq108(runs.projectId, ctx.project.id), eq108(runs.kind, RunKinds["answer-visibility"]), inArray51(runs.status, [RunStatuses.completed, RunStatuses.partial]), notProbeRun(), gte29(runs.createdAt, bounds.since), lte29(runs.createdAt, bounds.until))).all();
76376
+ const observations = ctx.db.select({ provider: querySnapshots.provider, model: querySnapshots.model, at: runs.createdAt }).from(querySnapshots).innerJoin(runs, eq109(runs.id, querySnapshots.runId)).where(and94(eq109(runs.projectId, ctx.project.id), eq109(runs.kind, RunKinds["answer-visibility"]), inArray51(runs.status, [RunStatuses.completed, RunStatuses.partial]), notProbeRun(), gte29(runs.createdAt, bounds.since), lte29(runs.createdAt, bounds.until))).all();
76332
76377
  return readVisibilityContinuity(ctx.db, ctx.project.name, { from: previous, to: month }).map(({ frame, continuity: continuity2 }) => ({
76333
76378
  month,
76334
76379
  previousMonth: previous,
@@ -76369,7 +76414,7 @@ var reportModelsCheck = {
76369
76414
  };
76370
76415
 
76371
76416
  // ../api-routes/src/doctor/checks/report-daily-data.ts
76372
- import { eq as eq109 } from "drizzle-orm";
76417
+ import { eq as eq110 } from "drizzle-orm";
76373
76418
  var REPORTING_LAG_DAYS = 3;
76374
76419
  function dateSpan(dates) {
76375
76420
  const sorted = [...dates].sort();
@@ -76378,31 +76423,31 @@ function dateSpan(dates) {
76378
76423
  function latestSyncRange(ctx, source) {
76379
76424
  const projectId = ctx.project.id;
76380
76425
  if (source === "ga") {
76381
- const rows2 = ctx.db.select({ date: gaDailyTotals.date, syncedAt: gaDailyTotals.syncedAt }).from(gaDailyTotals).where(eq109(gaDailyTotals.projectId, projectId)).all();
76426
+ const rows2 = ctx.db.select({ date: gaDailyTotals.date, syncedAt: gaDailyTotals.syncedAt }).from(gaDailyTotals).where(eq110(gaDailyTotals.projectId, projectId)).all();
76382
76427
  const latest2 = rows2.reduce((max2, row) => max2 === null || row.syncedAt > max2 ? row.syncedAt : max2, null);
76383
- const summary3 = ctx.db.select({ start: gaTrafficSummaries.periodStart, end: gaTrafficSummaries.periodEnd, syncedAt: gaTrafficSummaries.syncedAt }).from(gaTrafficSummaries).where(eq109(gaTrafficSummaries.projectId, projectId)).get();
76428
+ const summary3 = ctx.db.select({ start: gaTrafficSummaries.periodStart, end: gaTrafficSummaries.periodEnd, syncedAt: gaTrafficSummaries.syncedAt }).from(gaTrafficSummaries).where(eq110(gaTrafficSummaries.projectId, projectId)).get();
76384
76429
  if (summary3 && (latest2 === null || summary3.syncedAt >= latest2)) return { start: summary3.start, end: summary3.end, syncedAt: summary3.syncedAt };
76385
76430
  const span2 = dateSpan(rows2.filter((row) => row.syncedAt === latest2).map((row) => row.date));
76386
76431
  return span2 && latest2 !== null ? { ...span2, syncedAt: latest2 } : null;
76387
76432
  }
76388
- const rows = ctx.db.select({ date: gscDailyTotals.date, createdAt: gscDailyTotals.createdAt }).from(gscDailyTotals).where(eq109(gscDailyTotals.projectId, projectId)).all();
76433
+ const rows = ctx.db.select({ date: gscDailyTotals.date, createdAt: gscDailyTotals.createdAt }).from(gscDailyTotals).where(eq110(gscDailyTotals.projectId, projectId)).all();
76389
76434
  const latest = rows.reduce((max2, row) => max2 === null || row.createdAt > max2 ? row.createdAt : max2, null);
76390
76435
  const span = dateSpan(rows.filter((row) => row.createdAt === latest).map((row) => row.date));
76391
76436
  if (!span || latest === null) return null;
76392
- const watermark = ctx.db.select({ through: gscDataWatermarks.syncedThroughDate, updatedAt: gscDataWatermarks.updatedAt }).from(gscDataWatermarks).where(eq109(gscDataWatermarks.projectId, projectId)).get();
76437
+ const watermark = ctx.db.select({ through: gscDataWatermarks.syncedThroughDate, updatedAt: gscDataWatermarks.updatedAt }).from(gscDataWatermarks).where(eq110(gscDataWatermarks.projectId, projectId)).get();
76393
76438
  return watermark?.through && watermark.updatedAt === latest && watermark.through > span.end ? { start: span.start, end: watermark.through, syncedAt: latest } : { ...span, syncedAt: latest };
76394
76439
  }
76395
76440
  function dailyCoverage(ctx, month, source) {
76396
76441
  const project = ctx.project;
76397
76442
  const connection = source === "ga" ? ctx.ga4CredentialStore?.getConnection(project.name) ?? ctx.googleConnectionStore?.getConnection(project.canonicalDomain, "ga4") : ctx.googleConnectionStore?.getConnection(project.canonicalDomain, "gsc");
76398
- const stored = source === "ga" ? ctx.db.select({ date: gaDailyTotals.date, count: gaDailyTotals.sessions }).from(gaDailyTotals).where(eq109(gaDailyTotals.projectId, project.id)).all() : ctx.db.select({ date: gscDailyTotals.date, count: gscDailyTotals.impressions }).from(gscDailyTotals).where(eq109(gscDailyTotals.projectId, project.id)).all();
76443
+ const stored = source === "ga" ? ctx.db.select({ date: gaDailyTotals.date, count: gaDailyTotals.sessions }).from(gaDailyTotals).where(eq110(gaDailyTotals.projectId, project.id)).all() : ctx.db.select({ date: gscDailyTotals.date, count: gscDailyTotals.impressions }).from(gscDailyTotals).where(eq110(gscDailyTotals.projectId, project.id)).all();
76399
76444
  if (!connection && stored.length === 0) return null;
76400
76445
  const bounds = calendarMonthBounds(month);
76401
76446
  const start = bounds.since.slice(0, 10);
76402
76447
  const end = bounds.until.slice(0, 10);
76403
76448
  const timeZone = source === "gsc" ? "America/Los_Angeles" : "UTC";
76404
76449
  const matureThrough = isoDateDaysBeforeInTimeZone((/* @__PURE__ */ new Date()).toISOString(), REPORTING_LAG_DAYS, timeZone);
76405
- const created = ctx.db.select({ date: projects.createdAt }).from(projects).where(eq109(projects.id, project.id)).get().date.slice(0, 10);
76450
+ const created = ctx.db.select({ date: projects.createdAt }).from(projects).where(eq110(projects.id, project.id)).get().date.slice(0, 10);
76406
76451
  const connectedAt = connection?.createdAt?.slice(0, 10) ?? created;
76407
76452
  const onboardingDate = [connectedAt, ...stored.map((row) => row.date)].sort()[0];
76408
76453
  const byDate = new Map(stored.map((row) => [row.date, row.count]));
@@ -76484,7 +76529,7 @@ var reportDailyDataCheck = {
76484
76529
  };
76485
76530
 
76486
76531
  // ../api-routes/src/doctor/checks/referral-assessment.ts
76487
- import { and as and94, eq as eq110, ne as ne17 } from "drizzle-orm";
76532
+ import { and as and95, eq as eq111, ne as ne17 } from "drizzle-orm";
76488
76533
  var REFERRAL_ASSESSMENT_CHECKS = [{
76489
76534
  id: "report.ai-referral-bursts",
76490
76535
  category: CheckCategories.integrations,
@@ -76493,7 +76538,7 @@ var REFERRAL_ASSESSMENT_CHECKS = [{
76493
76538
  notificationPolicy: CheckNotificationPolicies.silent,
76494
76539
  run: (ctx) => {
76495
76540
  if (!ctx.project) return { status: CheckStatuses.skipped, code: "report.ai-referral-bursts.no-project", summary: "Select a project to inspect referral evidence." };
76496
- const configured = ctx.db.select({ id: trafficSources.id }).from(trafficSources).where(and94(eq110(trafficSources.projectId, ctx.project.id), ne17(trafficSources.status, TrafficSourceStatuses.archived))).get();
76541
+ const configured = ctx.db.select({ id: trafficSources.id }).from(trafficSources).where(and95(eq111(trafficSources.projectId, ctx.project.id), ne17(trafficSources.status, TrafficSourceStatuses.archived))).get();
76497
76542
  if (!configured) {
76498
76543
  return { status: CheckStatuses.skipped, code: "report.ai-referral-bursts.not-configured", summary: "No non-archived server traffic source is configured for this project." };
76499
76544
  }
@@ -76905,17 +76950,17 @@ var BACKLINKS_CHECKS = [
76905
76950
  ];
76906
76951
 
76907
76952
  // ../api-routes/src/doctor/checks/bing-auth.ts
76908
- import { and as and95, desc as desc50, eq as eq111, inArray as inArray52 } from "drizzle-orm";
76953
+ import { and as and96, desc as desc50, eq as eq112, inArray as inArray52 } from "drizzle-orm";
76909
76954
  var BING_CONNECTION_ENTITY = "bing_connection";
76910
76955
  var BING_CONNECTED_ACTION = "bing.connected";
76911
76956
  var BING_DISCONNECTED_ACTION = "bing.disconnected";
76912
76957
  function lostBingConnection(ctx, project) {
76913
76958
  const hasRow = (row) => row !== void 0;
76914
- const storedData = hasRow(ctx.db.select({ id: bingCoverageSnapshots.id }).from(bingCoverageSnapshots).where(eq111(bingCoverageSnapshots.projectId, project.id)).limit(1).get()) || hasRow(ctx.db.select({ id: bingUrlInspections.id }).from(bingUrlInspections).where(eq111(bingUrlInspections.projectId, project.id)).limit(1).get()) || hasRow(ctx.db.select({ id: bingKeywordStats.id }).from(bingKeywordStats).where(eq111(bingKeywordStats.projectId, project.id)).limit(1).get()) || hasRow(ctx.db.select({ id: bingTrafficDaily.id }).from(bingTrafficDaily).where(eq111(bingTrafficDaily.projectId, project.id)).limit(1).get());
76959
+ const storedData = hasRow(ctx.db.select({ id: bingCoverageSnapshots.id }).from(bingCoverageSnapshots).where(eq112(bingCoverageSnapshots.projectId, project.id)).limit(1).get()) || hasRow(ctx.db.select({ id: bingUrlInspections.id }).from(bingUrlInspections).where(eq112(bingUrlInspections.projectId, project.id)).limit(1).get()) || hasRow(ctx.db.select({ id: bingKeywordStats.id }).from(bingKeywordStats).where(eq112(bingKeywordStats.projectId, project.id)).limit(1).get()) || hasRow(ctx.db.select({ id: bingTrafficDaily.id }).from(bingTrafficDaily).where(eq112(bingTrafficDaily.projectId, project.id)).limit(1).get());
76915
76960
  if (!storedData) return false;
76916
- const lastChange = ctx.db.select({ action: auditLog.action }).from(auditLog).where(and95(
76917
- eq111(auditLog.entityType, BING_CONNECTION_ENTITY),
76918
- eq111(auditLog.entityId, project.canonicalDomain),
76961
+ const lastChange = ctx.db.select({ action: auditLog.action }).from(auditLog).where(and96(
76962
+ eq112(auditLog.entityType, BING_CONNECTION_ENTITY),
76963
+ eq112(auditLog.entityId, project.canonicalDomain),
76919
76964
  inArray52(auditLog.action, [BING_CONNECTED_ACTION, BING_DISCONNECTED_ACTION])
76920
76965
  )).orderBy(desc50(auditLog.createdAt)).limit(1).get();
76921
76966
  return lastChange?.action !== BING_DISCONNECTED_ACTION;
@@ -77074,7 +77119,7 @@ var BING_AUTH_CHECKS = [
77074
77119
  ];
77075
77120
 
77076
77121
  // ../api-routes/src/doctor/checks/content.ts
77077
- import { eq as eq112 } from "drizzle-orm";
77122
+ import { eq as eq113 } from "drizzle-orm";
77078
77123
  var WINNABILITY_COVERAGE_WARN_THRESHOLD = 0.8;
77079
77124
  var UNCLASSIFIED_DOMAIN_SAMPLE_LIMIT = 10;
77080
77125
  function skippedNoProject2() {
@@ -77087,7 +77132,7 @@ function skippedNoProject2() {
77087
77132
  }
77088
77133
  function loadProject(ctx) {
77089
77134
  if (!ctx.project) return null;
77090
- return ctx.db.select().from(projects).where(eq112(projects.id, ctx.project.id)).get() ?? null;
77135
+ return ctx.db.select().from(projects).where(eq113(projects.id, ctx.project.id)).get() ?? null;
77091
77136
  }
77092
77137
  var winnabilityCoverageCheck = {
77093
77138
  id: "content.winnability.coverage",
@@ -77180,7 +77225,7 @@ var CONTENT_CHECK_BY_ID = Object.fromEntries(
77180
77225
  );
77181
77226
 
77182
77227
  // ../api-routes/src/doctor/checks/ads.ts
77183
- import { eq as eq113 } from "drizzle-orm";
77228
+ import { eq as eq114 } from "drizzle-orm";
77184
77229
  var ADS_RECENT_SYNC_WARN_DAYS = 7;
77185
77230
  var ADS_RECENT_SYNC_FAIL_DAYS = 30;
77186
77231
  var adsConnectionCheck = {
@@ -77197,7 +77242,7 @@ var adsConnectionCheck = {
77197
77242
  remediation: null
77198
77243
  };
77199
77244
  }
77200
- const row = ctx.db.select().from(adsConnections).where(eq113(adsConnections.projectId, ctx.project.id)).get();
77245
+ const row = ctx.db.select().from(adsConnections).where(eq114(adsConnections.projectId, ctx.project.id)).get();
77201
77246
  if (!row) {
77202
77247
  return {
77203
77248
  status: CheckStatuses.skipped,
@@ -77247,7 +77292,7 @@ var adsRecentSyncCheck = {
77247
77292
  remediation: null
77248
77293
  };
77249
77294
  }
77250
- const row = ctx.db.select().from(adsConnections).where(eq113(adsConnections.projectId, ctx.project.id)).get();
77295
+ const row = ctx.db.select().from(adsConnections).where(eq114(adsConnections.projectId, ctx.project.id)).get();
77251
77296
  if (!row) {
77252
77297
  return {
77253
77298
  status: CheckStatuses.skipped,
@@ -77462,7 +77507,7 @@ var ga4ConnectionCheck = {
77462
77507
  var GA_AUTH_CHECKS = [ga4ConnectionCheck];
77463
77508
 
77464
77509
  // ../api-routes/src/doctor/checks/data-freshness.ts
77465
- import { and as and96, desc as desc51, eq as eq114, inArray as inArray53 } from "drizzle-orm";
77510
+ import { and as and97, desc as desc51, eq as eq115, inArray as inArray53 } from "drizzle-orm";
77466
77511
  var GA_DATA_AGING_DAYS = 3;
77467
77512
  var GA_DATA_STALE_DAYS = 5;
77468
77513
  var GSC_DATA_AGING_DAYS = 5;
@@ -77492,7 +77537,7 @@ function skipped(code, summary3) {
77492
77537
  return { status: CheckStatuses.skipped, code, summary: summary3, remediation: null };
77493
77538
  }
77494
77539
  function lastSyncAgeDays(ctx, kinds) {
77495
- const row = ctx.db.select({ createdAt: runs.createdAt }).from(runs).where(and96(eq114(runs.projectId, ctx.project.id), inArray53(runs.kind, kinds), eq114(runs.status, "completed"))).orderBy(desc51(runs.createdAt)).limit(1).get();
77540
+ const row = ctx.db.select({ createdAt: runs.createdAt }).from(runs).where(and97(eq115(runs.projectId, ctx.project.id), inArray53(runs.kind, kinds), eq115(runs.status, "completed"))).orderBy(desc51(runs.createdAt)).limit(1).get();
77496
77541
  if (!row?.createdAt) return null;
77497
77542
  const age = Math.floor((Date.now() - Date.parse(row.createdAt)) / DAY_MS6);
77498
77543
  return Number.isFinite(age) ? age : null;
@@ -77594,7 +77639,7 @@ var gaRecentDataCheck = {
77594
77639
  const connection = gaConnected(ctx);
77595
77640
  if (connection === "store-unavailable") return skipped("ga.data.store-unavailable", "No GA4 credential store configured for this deployment.");
77596
77641
  if (connection === "not-connected") return skipped("ga.data.not-connected", "GA4 is not connected for this project.");
77597
- const newest = ctx.db.select({ date: gaDailyTotals.date }).from(gaDailyTotals).where(eq114(gaDailyTotals.projectId, ctx.project.id)).orderBy(desc51(gaDailyTotals.date)).limit(1).get();
77642
+ const newest = ctx.db.select({ date: gaDailyTotals.date }).from(gaDailyTotals).where(eq115(gaDailyTotals.projectId, ctx.project.id)).orderBy(desc51(gaDailyTotals.date)).limit(1).get();
77598
77643
  return grade(ctx, GA_SPEC, newest?.date);
77599
77644
  }
77600
77645
  };
@@ -77609,16 +77654,16 @@ var gscRecentDataCheck = {
77609
77654
  if (!ctx.googleConnectionStore.getConnection(ctx.project.canonicalDomain, "gsc")) {
77610
77655
  return skipped("gsc.data.not-connected", "Search Console is not connected for this project.");
77611
77656
  }
77612
- const watermark = ctx.db.select({ dataThroughDate: gscDataWatermarks.dataThroughDate }).from(gscDataWatermarks).where(eq114(gscDataWatermarks.projectId, ctx.project.id)).get();
77657
+ const watermark = ctx.db.select({ dataThroughDate: gscDataWatermarks.dataThroughDate }).from(gscDataWatermarks).where(eq115(gscDataWatermarks.projectId, ctx.project.id)).get();
77613
77658
  if (watermark?.dataThroughDate) return grade(ctx, GSC_SPEC, watermark.dataThroughDate);
77614
- const newest = ctx.db.select({ date: gscDailyTotals.date }).from(gscDailyTotals).where(eq114(gscDailyTotals.projectId, ctx.project.id)).orderBy(desc51(gscDailyTotals.date)).limit(1).get();
77659
+ const newest = ctx.db.select({ date: gscDailyTotals.date }).from(gscDailyTotals).where(eq115(gscDailyTotals.projectId, ctx.project.id)).orderBy(desc51(gscDailyTotals.date)).limit(1).get();
77615
77660
  return grade(ctx, GSC_SPEC, newest?.date);
77616
77661
  }
77617
77662
  };
77618
77663
  var DATA_FRESHNESS_CHECKS = [gaRecentDataCheck, gscRecentDataCheck];
77619
77664
 
77620
77665
  // ../api-routes/src/doctor/checks/seo-refresh.ts
77621
- import { and as and97, asc as asc29, desc as desc52, eq as eq115, gt as gt9, inArray as inArray54, sql as sql49 } from "drizzle-orm";
77666
+ import { and as and98, asc as asc29, desc as desc52, eq as eq116, gt as gt9, inArray as inArray54, sql as sql49 } from "drizzle-orm";
77622
77667
  var GRACE_DAYS = 2;
77623
77668
  var DAY_MS7 = 24 * 60 * 60 * 1e3;
77624
77669
  var FIRING_SPAN_MS = 6e4;
@@ -77627,7 +77672,7 @@ function skipped2(code, summary3) {
77627
77672
  return { status: CheckStatuses.skipped, code, summary: summary3, remediation: null };
77628
77673
  }
77629
77674
  function seoSyncRuns(projectId) {
77630
- return and97(eq115(runs.projectId, projectId), eq115(runs.kind, RunKinds["seo-sync"]));
77675
+ return and98(eq116(runs.projectId, projectId), eq116(runs.kind, RunKinds["seo-sync"]));
77631
77676
  }
77632
77677
  function scheduleTiming(schedule) {
77633
77678
  if (!schedule.recurrence) return { cronExpr: schedule.cronExpr, timezone: schedule.timezone, recurrence: null };
@@ -77635,16 +77680,16 @@ function scheduleTiming(schedule) {
77635
77680
  return recurrence ? { cronExpr: schedule.cronExpr, timezone: schedule.timezone, recurrence } : null;
77636
77681
  }
77637
77682
  function latestFiring(ctx, projectId, enabledSince) {
77638
- const scheduled = and97(seoSyncRuns(projectId), eq115(runs.trigger, RunTriggers.scheduled), gt9(runs.createdAt, enabledSince));
77683
+ const scheduled = and98(seoSyncRuns(projectId), eq116(runs.trigger, RunTriggers.scheduled), gt9(runs.createdAt, enabledSince));
77639
77684
  const newest = ctx.db.select({ createdAt: runs.createdAt }).from(runs).where(scheduled).orderBy(desc52(runs.createdAt)).limit(1).get();
77640
77685
  if (!newest) return [];
77641
77686
  const newestMs = Date.parse(newest.createdAt);
77642
77687
  const after = Number.isFinite(newestMs) ? new Date(newestMs - FIRING_SPAN_MS).toISOString() : newest.createdAt;
77643
- return ctx.db.select({ id: runs.id, status: runs.status, error: runs.error, createdAt: runs.createdAt }).from(runs).where(and97(scheduled, gt9(runs.createdAt, after))).orderBy(asc29(runs.createdAt), asc29(runs.id)).all();
77688
+ return ctx.db.select({ id: runs.id, status: runs.status, error: runs.error, createdAt: runs.createdAt }).from(runs).where(and98(scheduled, gt9(runs.createdAt, after))).orderBy(asc29(runs.createdAt), asc29(runs.id)).all();
77644
77689
  }
77645
77690
  function lastCompleted(ctx, projectId) {
77646
77691
  const at = sql49`coalesce(${runs.finishedAt}, ${runs.createdAt})`;
77647
- return ctx.db.select({ id: runs.id, at }).from(runs).where(and97(seoSyncRuns(projectId), eq115(runs.status, RunStatuses.completed))).orderBy(desc52(at)).limit(1).get() ?? null;
77692
+ return ctx.db.select({ id: runs.id, at }).from(runs).where(and98(seoSyncRuns(projectId), eq116(runs.status, RunStatuses.completed))).orderBy(desc52(at)).limit(1).get() ?? null;
77648
77693
  }
77649
77694
  function isIncomplete(run) {
77650
77695
  return run.status === RunStatuses.failed || run.status === RunStatuses.partial;
@@ -77658,7 +77703,7 @@ function unsettledRuns(ctx, projectId, firing, profiles) {
77658
77703
  const incomplete = firing.filter(isIncomplete);
77659
77704
  const firedAt = firing[firing.length - 1]?.createdAt;
77660
77705
  if (incomplete.length === 0 || !firedAt) return incomplete;
77661
- const refreshed = new Set(ctx.db.select({ profileId: seoJobs.profileId }).from(runs).innerJoin(seoJobs, eq115(seoJobs.runId, runs.id)).where(and97(seoSyncRuns(projectId), eq115(runs.status, RunStatuses.completed), gt9(runs.createdAt, firedAt))).all().map((row) => row.profileId));
77706
+ const refreshed = new Set(ctx.db.select({ profileId: seoJobs.profileId }).from(runs).innerJoin(seoJobs, eq116(seoJobs.runId, runs.id)).where(and98(seoSyncRuns(projectId), eq116(runs.status, RunStatuses.completed), gt9(runs.createdAt, firedAt))).all().map((row) => row.profileId));
77662
77707
  return incomplete.filter((run) => {
77663
77708
  const profile = profiles.get(run.id) ?? null;
77664
77709
  return profile === null ? refreshed.size === 0 : !refreshed.has(profile);
@@ -77668,7 +77713,7 @@ var COUNT_LIST = new Intl.ListFormat("en", { style: "long", type: "conjunction"
77668
77713
  function refreshReason(ctx, run) {
77669
77714
  const stored = parseRunError(run.error);
77670
77715
  if (stored) return formatRunErrorOneLine(stored);
77671
- 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, eq115(seoTasks.jobId, seoJobs.id)).where(eq115(seoJobs.runId, run.id)).all());
77716
+ 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, eq116(seoTasks.jobId, seoJobs.id)).where(eq116(seoJobs.runId, run.id)).all());
77672
77717
  const failed = tasks.filter((task) => task.status === SeoRunStatuses.failed || task.status === SeoRunStatuses["reconciliation-required"]);
77673
77718
  const partial = tasks.filter((task) => task.status === SeoRunStatuses.partial).length;
77674
77719
  const cancelled = tasks.filter((task) => task.status === SeoRunStatuses.cancelled).length;
@@ -77688,7 +77733,7 @@ function refreshReason(ctx, run) {
77688
77733
  return `Of ${tasks.length} ${unit}, ${COUNT_LIST.format(counts2)}.${errors ? ` ${errors}` : ""}`;
77689
77734
  }
77690
77735
  function gradeSeoRefresh(ctx, project) {
77691
- const schedule = ctx.db.select().from(schedules).where(and97(eq115(schedules.projectId, project.id), eq115(schedules.kind, SchedulableRunKinds["seo-sync"]))).get();
77736
+ const schedule = ctx.db.select().from(schedules).where(and98(eq116(schedules.projectId, project.id), eq116(schedules.kind, SchedulableRunKinds["seo-sync"]))).get();
77692
77737
  if (!schedule) return skipped2("seo.data.not-scheduled", "No SEO refresh schedule is set for this project.");
77693
77738
  if (!schedule.enabled) return skipped2("seo.data.not-scheduled", "The SEO refresh schedule is disabled.");
77694
77739
  const name = project.name;
@@ -77760,7 +77805,7 @@ function gradeSeoRefresh(ctx, project) {
77760
77805
  };
77761
77806
  }
77762
77807
  if (now >= Date.parse(deadlineAt)) {
77763
- const active = ctx.db.select({ id: runs.id, createdAt: runs.createdAt }).from(runs).where(and97(seoSyncRuns(project.id), inArray54(runs.status, [RunStatuses.queued, RunStatuses.running]))).orderBy(asc29(runs.createdAt)).limit(1).get();
77808
+ const active = ctx.db.select({ id: runs.id, createdAt: runs.createdAt }).from(runs).where(and98(seoSyncRuns(project.id), inArray54(runs.status, [RunStatuses.queued, RunStatuses.running]))).orderBy(asc29(runs.createdAt)).limit(1).get();
77764
77809
  const since = last ? `No SEO refresh has completed since ${day(last.at)}.` : "No SEO refresh has completed since the schedule was enabled.";
77765
77810
  const missed = last ? `The scheduled refresh due ${day(dueAt)} did not complete within ${GRACE_DAYS} days.` : `Its first refresh, due ${day(dueAt)}, did not complete within ${GRACE_DAYS} days.`;
77766
77811
  return {
@@ -78070,7 +78115,7 @@ var siteReachabilityCheck = {
78070
78115
  var SITE_REACHABILITY_CHECKS = [siteReachabilityCheck];
78071
78116
 
78072
78117
  // ../api-routes/src/doctor/checks/api-hosts.ts
78073
- import { eq as eq117 } from "drizzle-orm";
78118
+ import { eq as eq118 } from "drizzle-orm";
78074
78119
 
78075
78120
  // ../api-routes/src/api-host-probe.ts
78076
78121
  import dns4 from "dns/promises";
@@ -78176,7 +78221,7 @@ async function probeApiHost(host, options = {}) {
78176
78221
  }
78177
78222
 
78178
78223
  // ../api-routes/src/doctor/checks/integration-sync.ts
78179
- import { and as and98, count as count9, desc as desc53, eq as eq116, gte as gte30, gt as gt10, inArray as inArray55, isNull as isNull18, notInArray as notInArray3, or as or21 } from "drizzle-orm";
78224
+ import { and as and99, count as count9, desc as desc53, eq as eq117, gte as gte30, gt as gt10, inArray as inArray55, isNull as isNull18, notInArray as notInArray4, or as or21 } from "drizzle-orm";
78180
78225
  var SYNC_FAILURE_WINDOW = 3;
78181
78226
  var SUMMARY_ERROR_LIMIT = 300;
78182
78227
  var FINISHED_STATUSES = [RunStatuses.completed, RunStatuses.partial, RunStatuses.failed];
@@ -78203,7 +78248,7 @@ function gscConnection(ctx, project) {
78203
78248
  function gbpConnection(ctx, project) {
78204
78249
  if (!ctx.googleConnectionStore) return { state: "store-unavailable" };
78205
78250
  if (!ctx.googleConnectionStore.getConnection(project.canonicalDomain, "gbp")) return { state: "not-connected" };
78206
- const selected = ctx.db.select({ locationName: gbpLocations.locationName }).from(gbpLocations).where(and98(eq116(gbpLocations.projectId, project.id), eq116(gbpLocations.selected, true))).limit(1).get();
78251
+ const selected = ctx.db.select({ locationName: gbpLocations.locationName }).from(gbpLocations).where(and99(eq117(gbpLocations.projectId, project.id), eq117(gbpLocations.selected, true))).limit(1).get();
78207
78252
  return selected ? CONNECTED : { state: "no-selected-locations" };
78208
78253
  }
78209
78254
  function gaConnection(ctx, project) {
@@ -78276,16 +78321,16 @@ function latestErrorText(raw) {
78276
78321
  return parsed ? formatRunErrorOneLine(parsed) : "no error was recorded";
78277
78322
  }
78278
78323
  function readSyncRunState(db, projectId, kind, options = {}) {
78279
- const scope = and98(
78280
- eq116(runs.projectId, projectId),
78281
- eq116(runs.kind, kind),
78282
- ...options.sourceId ? [eq116(runs.sourceId, options.sourceId)] : [],
78283
- ...options.nothingToSyncErrors?.length ? [or21(isNull18(runs.error), notInArray3(runs.error, [...options.nothingToSyncErrors]))] : []
78324
+ const scope = and99(
78325
+ eq117(runs.projectId, projectId),
78326
+ eq117(runs.kind, kind),
78327
+ ...options.sourceId ? [eq117(runs.sourceId, options.sourceId)] : [],
78328
+ ...options.nothingToSyncErrors?.length ? [or21(isNull18(runs.error), notInArray4(runs.error, [...options.nothingToSyncErrors]))] : []
78284
78329
  );
78285
- const graded = options.since ? and98(scope, gte30(runs.createdAt, options.since)) : scope;
78286
- const recent = db.select({ id: runs.id, status: runs.status, trigger: runs.trigger, error: runs.error, createdAt: runs.createdAt }).from(runs).where(and98(graded, inArray55(runs.status, FINISHED_STATUSES))).orderBy(desc53(runs.createdAt)).limit(SYNC_FAILURE_WINDOW).all();
78287
- const lastSuccess = db.select({ createdAt: runs.createdAt, finishedAt: runs.finishedAt }).from(runs).where(and98(graded, inArray55(runs.status, SUCCESS_STATUSES))).orderBy(desc53(runs.createdAt)).limit(1).get();
78288
- const failureCount = db.select({ count: count9() }).from(runs).where(and98(lastSuccess ? and98(graded, gt10(runs.createdAt, lastSuccess.createdAt)) : graded, eq116(runs.status, RunStatuses.failed))).get();
78330
+ const graded = options.since ? and99(scope, gte30(runs.createdAt, options.since)) : scope;
78331
+ const recent = db.select({ id: runs.id, status: runs.status, trigger: runs.trigger, error: runs.error, createdAt: runs.createdAt }).from(runs).where(and99(graded, inArray55(runs.status, FINISHED_STATUSES))).orderBy(desc53(runs.createdAt)).limit(SYNC_FAILURE_WINDOW).all();
78332
+ const lastSuccess = db.select({ createdAt: runs.createdAt, finishedAt: runs.finishedAt }).from(runs).where(and99(graded, inArray55(runs.status, SUCCESS_STATUSES))).orderBy(desc53(runs.createdAt)).limit(1).get();
78333
+ const failureCount = db.select({ count: count9() }).from(runs).where(and99(lastSuccess ? and99(graded, gt10(runs.createdAt, lastSuccess.createdAt)) : graded, eq117(runs.status, RunStatuses.failed))).get();
78289
78334
  const failuresSinceSuccess = Number(failureCount?.count ?? 0);
78290
78335
  const latest = recent[0];
78291
78336
  return {
@@ -78382,7 +78427,7 @@ function connectionFor(prefix, ctx, project) {
78382
78427
  if (prefix === "google-ads") return googleMarketingConnection("googleAds")(ctx);
78383
78428
  if (prefix === "gtm") return googleMarketingConnection("gtm")(ctx);
78384
78429
  if (prefix === "bing") return ctx.bingConnectionStore?.getConnection(project.canonicalDomain) ? { state: "connected", since: null } : { state: "not-connected" };
78385
- return ctx.db.select({ id: adsConnections.id }).from(adsConnections).where(eq117(adsConnections.projectId, project.id)).limit(1).get() ? { state: "connected", since: null } : { state: "not-connected" };
78430
+ return ctx.db.select({ id: adsConnections.id }).from(adsConnections).where(eq118(adsConnections.projectId, project.id)).limit(1).get() ? { state: "connected", since: null } : { state: "not-connected" };
78386
78431
  }
78387
78432
  function syncCommand(prefix) {
78388
78433
  if (prefix === "gsc") return "google sync";
@@ -78427,7 +78472,7 @@ function definition(prefix) {
78427
78472
  var API_HOST_CHECKS = Object.keys(API_HOST_TABLE).map(definition);
78428
78473
 
78429
78474
  // ../api-routes/src/doctor/checks/gbp-auth.ts
78430
- import { and as and99, eq as eq118 } from "drizzle-orm";
78475
+ import { and as and100, eq as eq119 } from "drizzle-orm";
78431
78476
  var RECENT_SYNC_WARN_DAYS = 4;
78432
78477
  var RECENT_SYNC_FAIL_DAYS = 30;
78433
78478
  function skippedNoProject3() {
@@ -78447,7 +78492,7 @@ function storeUnavailable() {
78447
78492
  };
78448
78493
  }
78449
78494
  function hasSelectedLocation(ctx, projectId) {
78450
- return !!ctx.db.select({ id: gbpLocations.id }).from(gbpLocations).where(and99(eq118(gbpLocations.projectId, projectId), eq118(gbpLocations.selected, true))).limit(1).get();
78495
+ return !!ctx.db.select({ id: gbpLocations.id }).from(gbpLocations).where(and100(eq119(gbpLocations.projectId, projectId), eq119(gbpLocations.selected, true))).limit(1).get();
78451
78496
  }
78452
78497
  async function resolveGbpToken(ctx) {
78453
78498
  if (!ctx.project) return { ok: false, output: skippedNoProject3() };
@@ -78707,7 +78752,7 @@ var recentSyncCheck = {
78707
78752
  title: "GBP recent sync",
78708
78753
  run: (ctx) => {
78709
78754
  if (!ctx.project) return skippedNoProject3();
78710
- const selected = ctx.db.select({ locationName: gbpLocations.locationName, syncedAt: gbpLocations.syncedAt }).from(gbpLocations).where(and99(eq118(gbpLocations.projectId, ctx.project.id), eq118(gbpLocations.selected, true))).all();
78755
+ const selected = ctx.db.select({ locationName: gbpLocations.locationName, syncedAt: gbpLocations.syncedAt }).from(gbpLocations).where(and100(eq119(gbpLocations.projectId, ctx.project.id), eq119(gbpLocations.selected, true))).all();
78711
78756
  if (selected.length === 0) {
78712
78757
  return {
78713
78758
  status: CheckStatuses.skipped,
@@ -78767,7 +78812,7 @@ var GBP_AUTH_CHECK_BY_ID = Object.fromEntries(
78767
78812
  );
78768
78813
 
78769
78814
  // ../api-routes/src/doctor/checks/places.ts
78770
- import { eq as eq119 } from "drizzle-orm";
78815
+ import { eq as eq120 } from "drizzle-orm";
78771
78816
  var apiKeyCheck = {
78772
78817
  id: "gbp.places.api-key",
78773
78818
  category: CheckCategories.auth,
@@ -78812,7 +78857,7 @@ var apiKeyCheck = {
78812
78857
  details: { tier: cfg.tier }
78813
78858
  };
78814
78859
  }
78815
- const rows = ctx.db.select({ placeId: gbpLocations.placeId, selected: gbpLocations.selected }).from(gbpLocations).where(eq119(gbpLocations.projectId, ctx.project.id)).all();
78860
+ const rows = ctx.db.select({ placeId: gbpLocations.placeId, selected: gbpLocations.selected }).from(gbpLocations).where(eq120(gbpLocations.projectId, ctx.project.id)).all();
78816
78861
  const selected = rows.filter((r) => r.selected);
78817
78862
  const locationsWithPlaceId = selected.filter((r) => Boolean(r.placeId)).length;
78818
78863
  const details = {
@@ -78845,7 +78890,7 @@ var PLACES_CHECK_BY_ID = Object.fromEntries(
78845
78890
  );
78846
78891
 
78847
78892
  // ../api-routes/src/doctor/checks/gbp-reviews.ts
78848
- import { and as and100, desc as desc54, eq as eq120, gte as gte31, inArray as inArray56, sql as sql50 } from "drizzle-orm";
78893
+ import { and as and101, desc as desc54, eq as eq121, gte as gte31, inArray as inArray56, sql as sql50 } from "drizzle-orm";
78849
78894
  var REVIEW_EVENTS = /* @__PURE__ */ new Set(["review.negative", "review.rating-dropped"]);
78850
78895
  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`.";
78851
78896
  var reviewsAccessCheck = {
@@ -78873,7 +78918,7 @@ var reviewsAccessCheck = {
78873
78918
  reviewsAccess: gbpLocations.reviewsAccess,
78874
78919
  reviewsAccessReason: gbpLocations.reviewsAccessReason,
78875
78920
  reviewsCheckedAt: gbpLocations.reviewsCheckedAt
78876
- }).from(gbpLocations).where(and100(eq120(gbpLocations.projectId, project.id), eq120(gbpLocations.selected, true))).all();
78921
+ }).from(gbpLocations).where(and101(eq121(gbpLocations.projectId, project.id), eq121(gbpLocations.selected, true))).all();
78877
78922
  if (locations.length === 0) {
78878
78923
  return {
78879
78924
  status: CheckStatuses.skipped,
@@ -78893,7 +78938,7 @@ var reviewsAccessCheck = {
78893
78938
  const places = ctx.getPlacesConfig?.();
78894
78939
  const placesFallback = places !== void 0 && places.tier === "atmosphere" && Boolean(places.apiKey);
78895
78940
  const v4Worked = new Set(
78896
- ctx.db.select({ locationName: gbpReviewRatings.locationName }).from(gbpReviewRatings).where(and100(eq120(gbpReviewRatings.projectId, project.id), eq120(gbpReviewRatings.origin, "gbp"))).all().map((row) => row.locationName)
78941
+ ctx.db.select({ locationName: gbpReviewRatings.locationName }).from(gbpReviewRatings).where(and101(eq121(gbpReviewRatings.projectId, project.id), eq121(gbpReviewRatings.origin, "gbp"))).all().map((row) => row.locationName)
78897
78942
  );
78898
78943
  const coverageOf = (loc) => {
78899
78944
  if (businessProfileReviewsCover(loc.reviewsAccess ?? null, v4Worked.has(loc.locationName))) return "full";
@@ -78927,7 +78972,7 @@ var reviewsAccessCheck = {
78927
78972
  none > 0 ? `${none} have no review source` : null
78928
78973
  ].filter((part) => part !== null);
78929
78974
  const summary3 = `Business Profile reviews are not available${why}. ${parts.join("; ")}.`;
78930
- const subscribed = ctx.db.select({ config: notifications.config, enabled: notifications.enabled }).from(notifications).where(eq120(notifications.projectId, project.id)).all().some((n) => n.enabled && (n.config.events ?? []).some((event) => REVIEW_EVENTS.has(event)));
78975
+ const subscribed = ctx.db.select({ config: notifications.config, enabled: notifications.enabled }).from(notifications).where(eq121(notifications.projectId, project.id)).all().some((n) => n.enabled && (n.config.events ?? []).some((event) => REVIEW_EVENTS.has(event)));
78931
78976
  const placesHint = placesFallback ? "" : " For partial coverage meanwhile, set a Places API key (`GOOGLE_PLACES_API_KEY` or `places.apiKey`) with `places.tier: atmosphere`.";
78932
78977
  if (none > 0 && subscribed) {
78933
78978
  return {
@@ -78966,8 +79011,8 @@ var reviewDeliveryCheck = {
78966
79011
  attempts: reviewWebhookDeliveries.attempts,
78967
79012
  lastTouched,
78968
79013
  payload: reviewWebhookDeliveries.payload
78969
- }).from(reviewWebhookDeliveries).where(and100(
78970
- eq120(reviewWebhookDeliveries.projectId, ctx.project.id),
79014
+ }).from(reviewWebhookDeliveries).where(and101(
79015
+ eq121(reviewWebhookDeliveries.projectId, ctx.project.id),
78971
79016
  inArray56(reviewWebhookDeliveries.state, [ReviewDeliveryStates.Uncertain, ReviewDeliveryStates.Failed]),
78972
79017
  gte31(lastTouched, since)
78973
79018
  )).orderBy(desc54(lastTouched)).all();
@@ -78979,7 +79024,7 @@ var reviewDeliveryCheck = {
78979
79024
  remediation: null
78980
79025
  };
78981
79026
  }
78982
- const destinations = new Map(ctx.db.select({ id: notifications.id, config: notifications.config }).from(notifications).where(eq120(notifications.projectId, ctx.project.id)).all().map((row) => [row.id, redactNotificationUrl(row.config.url).urlDisplay]));
79027
+ const destinations = new Map(ctx.db.select({ id: notifications.id, config: notifications.config }).from(notifications).where(eq121(notifications.projectId, ctx.project.id)).all().map((row) => [row.id, redactNotificationUrl(row.config.url).urlDisplay]));
78983
79028
  const deliveries = rows.map((row) => {
78984
79029
  const review = row.payload.reviews[0];
78985
79030
  return {
@@ -79553,14 +79598,9 @@ var RUNTIME_STATE_CHECKS = [
79553
79598
  ];
79554
79599
 
79555
79600
  // ../api-routes/src/doctor/checks/traffic-source.ts
79556
- import { and as and101, desc as desc55, eq as eq121, gte as gte32, inArray as inArray57, isNotNull as isNotNull11, ne as ne18, sql as sql51 } from "drizzle-orm";
79601
+ import { and as and102, desc as desc55, eq as eq122, gte as gte32, inArray as inArray57, isNotNull as isNotNull11, ne as ne18, sql as sql51 } from "drizzle-orm";
79557
79602
  var RECENT_DATA_WARN_DAYS = 7;
79558
79603
  var RECENT_DATA_FAIL_DAYS = 30;
79559
- function isCloudflareDirectPush(source) {
79560
- if (source.sourceType !== TrafficSourceTypes.cloudflare) return false;
79561
- const deliveryMode = source.configJson.deliveryMode;
79562
- return deliveryMode === void 0 || deliveryMode === CloudflareTrafficDeliveryModes["direct-push"];
79563
- }
79564
79604
  function isCloudflareQueuePull(source) {
79565
79605
  return source.sourceType === TrafficSourceTypes.cloudflare && source.configJson.deliveryMode === CloudflareTrafficDeliveryModes["queue-pull"];
79566
79606
  }
@@ -79592,8 +79632,8 @@ function skippedNoProject5() {
79592
79632
  function loadProbes(ctx) {
79593
79633
  if (!ctx.project) return [];
79594
79634
  const rows = ctx.db.select().from(trafficSources).where(
79595
- and101(
79596
- eq121(trafficSources.projectId, ctx.project.id),
79635
+ and102(
79636
+ eq122(trafficSources.projectId, ctx.project.id),
79597
79637
  ne18(trafficSources.status, TrafficSourceStatuses.archived)
79598
79638
  )
79599
79639
  ).all();
@@ -79756,8 +79796,8 @@ var recentDataCheck = {
79756
79796
  const failCutoff = new Date(now.getTime() - RECENT_DATA_FAIL_DAYS * 24 * 60 * 6e4).toISOString();
79757
79797
  const recentCrawlers = Number(
79758
79798
  ctx.db.select({ total: sql51`COALESCE(SUM(${crawlerEventsHourly.hits}), 0)` }).from(crawlerEventsHourly).where(
79759
- and101(
79760
- eq121(crawlerEventsHourly.projectId, ctx.project.id),
79799
+ and102(
79800
+ eq122(crawlerEventsHourly.projectId, ctx.project.id),
79761
79801
  inArray57(crawlerEventsHourly.sourceId, activeSourceIds),
79762
79802
  gte32(crawlerEventsHourly.tsHour, warnCutoff)
79763
79803
  )
@@ -79765,8 +79805,8 @@ var recentDataCheck = {
79765
79805
  );
79766
79806
  const recentReferrals = Number(
79767
79807
  ctx.db.select({ total: sql51`COALESCE(SUM(${aiReferralEventsHourly.sessionsOrHits}), 0)` }).from(aiReferralEventsHourly).where(
79768
- and101(
79769
- eq121(aiReferralEventsHourly.projectId, ctx.project.id),
79808
+ and102(
79809
+ eq122(aiReferralEventsHourly.projectId, ctx.project.id),
79770
79810
  inArray57(aiReferralEventsHourly.sourceId, activeSourceIds),
79771
79811
  gte32(aiReferralEventsHourly.tsHour, warnCutoff)
79772
79812
  )
@@ -79774,8 +79814,8 @@ var recentDataCheck = {
79774
79814
  );
79775
79815
  const recentUserFetches = Number(
79776
79816
  ctx.db.select({ total: sql51`COALESCE(SUM(${aiUserFetchEventsHourly.hits}), 0)` }).from(aiUserFetchEventsHourly).where(
79777
- and101(
79778
- eq121(aiUserFetchEventsHourly.projectId, ctx.project.id),
79817
+ and102(
79818
+ eq122(aiUserFetchEventsHourly.projectId, ctx.project.id),
79779
79819
  inArray57(aiUserFetchEventsHourly.sourceId, activeSourceIds),
79780
79820
  gte32(aiUserFetchEventsHourly.tsHour, warnCutoff)
79781
79821
  )
@@ -79800,8 +79840,8 @@ var recentDataCheck = {
79800
79840
  }
79801
79841
  const olderCrawlers = Number(
79802
79842
  ctx.db.select({ total: sql51`COALESCE(SUM(${crawlerEventsHourly.hits}), 0)` }).from(crawlerEventsHourly).where(
79803
- and101(
79804
- eq121(crawlerEventsHourly.projectId, ctx.project.id),
79843
+ and102(
79844
+ eq122(crawlerEventsHourly.projectId, ctx.project.id),
79805
79845
  inArray57(crawlerEventsHourly.sourceId, activeSourceIds),
79806
79846
  gte32(crawlerEventsHourly.tsHour, failCutoff)
79807
79847
  )
@@ -79809,8 +79849,8 @@ var recentDataCheck = {
79809
79849
  );
79810
79850
  const olderReferrals = Number(
79811
79851
  ctx.db.select({ total: sql51`COALESCE(SUM(${aiReferralEventsHourly.sessionsOrHits}), 0)` }).from(aiReferralEventsHourly).where(
79812
- and101(
79813
- eq121(aiReferralEventsHourly.projectId, ctx.project.id),
79852
+ and102(
79853
+ eq122(aiReferralEventsHourly.projectId, ctx.project.id),
79814
79854
  inArray57(aiReferralEventsHourly.sourceId, activeSourceIds),
79815
79855
  gte32(aiReferralEventsHourly.tsHour, failCutoff)
79816
79856
  )
@@ -79818,8 +79858,8 @@ var recentDataCheck = {
79818
79858
  );
79819
79859
  const olderUserFetches = Number(
79820
79860
  ctx.db.select({ total: sql51`COALESCE(SUM(${aiUserFetchEventsHourly.hits}), 0)` }).from(aiUserFetchEventsHourly).where(
79821
- and101(
79822
- eq121(aiUserFetchEventsHourly.projectId, ctx.project.id),
79861
+ and102(
79862
+ eq122(aiUserFetchEventsHourly.projectId, ctx.project.id),
79823
79863
  inArray57(aiUserFetchEventsHourly.sourceId, activeSourceIds),
79824
79864
  gte32(aiUserFetchEventsHourly.tsHour, failCutoff)
79825
79865
  )
@@ -80146,10 +80186,10 @@ var syncLagCheck = {
80146
80186
  }
80147
80187
  };
80148
80188
  function lastQueueStopReason(ctx, sourceId) {
80149
- const row = ctx.db.select({ syncSummary: runs.syncSummary }).from(runs).where(and101(
80150
- eq121(runs.projectId, ctx.project.id),
80151
- eq121(runs.kind, RunKinds["traffic-sync"]),
80152
- eq121(runs.sourceId, sourceId),
80189
+ const row = ctx.db.select({ syncSummary: runs.syncSummary }).from(runs).where(and102(
80190
+ eq122(runs.projectId, ctx.project.id),
80191
+ eq122(runs.kind, RunKinds["traffic-sync"]),
80192
+ eq122(runs.sourceId, sourceId),
80153
80193
  isNotNull11(runs.syncSummary)
80154
80194
  )).orderBy(desc55(runs.createdAt)).limit(1).get();
80155
80195
  return row?.syncSummary?.type === "cloudflare-queue" ? row.syncSummary.stopReason : null;
@@ -80949,7 +80989,7 @@ async function doctorRoutes(app, opts) {
80949
80989
  }
80950
80990
 
80951
80991
  // ../api-routes/src/status.ts
80952
- import { and as and102, desc as desc56, eq as eq122, isNull as isNull19 } from "drizzle-orm";
80992
+ import { and as and103, desc as desc56, eq as eq123, isNull as isNull19 } from "drizzle-orm";
80953
80993
  function ageDays(iso2) {
80954
80994
  if (!iso2) return null;
80955
80995
  const ms = Date.now() - Date.parse(iso2);
@@ -80999,7 +81039,7 @@ function makeRow(integration, label, runKind, state, staleAfterDays, dataThrough
80999
81039
  };
81000
81040
  }
81001
81041
  function latestDate2(db, table, projectId) {
81002
- const row = db.select({ date: table.date }).from(table).where(eq122(table.projectId, projectId)).orderBy(desc56(table.date)).limit(1).get();
81042
+ const row = db.select({ date: table.date }).from(table).where(eq123(table.projectId, projectId)).orderBy(desc56(table.date)).limit(1).get();
81003
81043
  return row?.date ?? null;
81004
81044
  }
81005
81045
  function projectRows(opts, project) {
@@ -81014,7 +81054,7 @@ function projectRows(opts, project) {
81014
81054
  const rows = [];
81015
81055
  const gsc = gscConnection(ctx, info);
81016
81056
  if (connected(gsc)) {
81017
- const watermarkRow = opts.db.select({ dataThroughDate: gscDataWatermarks.dataThroughDate }).from(gscDataWatermarks).where(eq122(gscDataWatermarks.projectId, project.id)).limit(1).get();
81057
+ const watermarkRow = opts.db.select({ dataThroughDate: gscDataWatermarks.dataThroughDate }).from(gscDataWatermarks).where(eq123(gscDataWatermarks.projectId, project.id)).limit(1).get();
81018
81058
  const state = readSyncRunState(opts.db, project.id, RunKinds["gsc-sync"], { since: gsc.since });
81019
81059
  const dataThrough = watermarkRow?.dataThroughDate ?? latestDate2(opts.db, gscDailyTotals, project.id);
81020
81060
  rows.push(makeRow("gsc", "Search Console", RunKinds["gsc-sync"], state, SYNC_IDLE_DAYS, dataThrough, null, ["gsc.sync.recent-failures"], GSC_DATA_AGING_DAYS));
@@ -81030,12 +81070,12 @@ function projectRows(opts, project) {
81030
81070
  rows.push(makeRow("bing", "Bing Webmaster Tools", RunKinds["bing-inspect-sitemap"], readSyncRunState(opts.db, project.id, RunKinds["bing-inspect-sitemap"]), null));
81031
81071
  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));
81032
81072
  }
81033
- const ads = opts.db.select({ id: adsConnections.id, lastSyncedAt: adsConnections.lastSyncedAt }).from(adsConnections).where(eq122(adsConnections.projectId, project.id)).limit(1).get();
81073
+ const ads = opts.db.select({ id: adsConnections.id, lastSyncedAt: adsConnections.lastSyncedAt }).from(adsConnections).where(eq123(adsConnections.projectId, project.id)).limit(1).get();
81034
81074
  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));
81035
81075
  const marketing = opts.getGoogleMarketingDoctorInput?.(ctx);
81036
81076
  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));
81037
81077
  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));
81038
- const sources = opts.db.select().from(trafficSources).where(and102(eq122(trafficSources.projectId, project.id), isNull19(trafficSources.archivedAt))).all();
81078
+ const sources = opts.db.select().from(trafficSources).where(and103(eq123(trafficSources.projectId, project.id), isNull19(trafficSources.archivedAt))).all();
81039
81079
  for (const source of sources) {
81040
81080
  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"]);
81041
81081
  const lag = source.lastSyncedAt ? Date.now() - Date.parse(source.lastSyncedAt) : Number.POSITIVE_INFINITY;
@@ -81047,7 +81087,7 @@ function projectRows(opts, project) {
81047
81087
  }
81048
81088
  function projectStatus(opts, project) {
81049
81089
  const integrations = projectRows(opts, project);
81050
- const healthRow = opts.db.select().from(doctorHealthState).where(eq122(doctorHealthState.projectId, project.id)).limit(1).get();
81090
+ const healthRow = opts.db.select().from(doctorHealthState).where(eq123(doctorHealthState.projectId, project.id)).limit(1).get();
81051
81091
  const health = healthRow ? { status: healthRow.status, code: healthRow.code, summary: healthRow.summary, checkedAt: healthRow.checkedAt, notifiedAt: healthRow.notifiedAt } : null;
81052
81092
  const rank = { ok: 0, "never-synced": 1, warning: 2, stale: 3, failing: 4 };
81053
81093
  const healthState = health?.status === "fail" ? "failing" : health?.status === "warn" ? "warning" : "ok";
@@ -81067,7 +81107,7 @@ async function statusRoutes(app, opts) {
81067
81107
  if (request.query.problems === "true") result.projects = result.projects.map((item2) => ({ ...item2, integrations: item2.integrations.filter((row) => row.state !== "ok") }));
81068
81108
  return instanceStatusDtoSchema.parse(result);
81069
81109
  }
81070
- const projectsRows = (scopedId ? opts.db.select().from(projects).where(eq122(projects.id, scopedId)) : opts.db.select().from(projects)).all();
81110
+ const projectsRows = (scopedId ? opts.db.select().from(projects).where(eq123(projects.id, scopedId)) : opts.db.select().from(projects)).all();
81071
81111
  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)) };
81072
81112
  for (const project of output.projects) {
81073
81113
  const key = project.state === "never-synced" ? "neverSynced" : project.state;
@@ -81080,7 +81120,7 @@ async function statusRoutes(app, opts) {
81080
81120
 
81081
81121
  // ../api-routes/src/discovery/routes.ts
81082
81122
  import crypto64 from "crypto";
81083
- import { and as and103, desc as desc57, eq as eq123, gte as gte33, inArray as inArray58, isNull as isNull20, or as or22 } from "drizzle-orm";
81123
+ import { and as and104, desc as desc57, eq as eq124, gte as gte33, inArray as inArray58, isNull as isNull20, or as or22 } from "drizzle-orm";
81084
81124
  var MAX_INFLIGHT_DISCOVERY_AGE_MS = 2 * 60 * 60 * 1e3;
81085
81125
  async function discoveryRoutes(app, opts) {
81086
81126
  app.post("/projects/:name/discover/run", async (request, reply) => {
@@ -81114,13 +81154,13 @@ async function discoveryRoutes(app, opts) {
81114
81154
  const now = (/* @__PURE__ */ new Date()).toISOString();
81115
81155
  const ageFloorIso = new Date(Date.now() - MAX_INFLIGHT_DISCOVERY_AGE_MS).toISOString();
81116
81156
  const decision = app.db.transaction((tx) => {
81117
- const existing = tx.select({ id: discoverySessions.id, runId: discoverySessions.runId }).from(discoverySessions).where(and103(
81118
- eq123(discoverySessions.projectId, project.id),
81119
- eq123(discoverySessions.icpDescription, icpDescription),
81157
+ const existing = tx.select({ id: discoverySessions.id, runId: discoverySessions.runId }).from(discoverySessions).where(and104(
81158
+ eq124(discoverySessions.projectId, project.id),
81159
+ eq124(discoverySessions.icpDescription, icpDescription),
81120
81160
  // Buyer is part of session identity: it changes the seed prompt's
81121
81161
  // semantics, so a request with a different (or no) buyer must start
81122
81162
  // its own session, never adopt another buyer's probes.
81123
- parsed.data.buyerDescription == null ? isNull20(discoverySessions.buyerDescription) : eq123(discoverySessions.buyerDescription, parsed.data.buyerDescription),
81163
+ parsed.data.buyerDescription == null ? isNull20(discoverySessions.buyerDescription) : eq124(discoverySessions.buyerDescription, parsed.data.buyerDescription),
81124
81164
  // Locations are identity too: a different service-area subset seeds
81125
81165
  // and probes a different geo, so it must never reuse another geo's
81126
81166
  // session. resolveLocations is deterministic (project-config order),
@@ -81130,11 +81170,11 @@ async function discoveryRoutes(app, opts) {
81130
81170
  // locations a NULL row's subset is unknowable, so it conservatively
81131
81171
  // never reuses — a one-time, bounded (2h window) non-reuse after
81132
81172
  // upgrade, never a wrong reuse.
81133
- locations.length === 0 ? or22(isNull20(discoverySessions.locations), eq123(discoverySessions.locations, locations)) : eq123(discoverySessions.locations, locations),
81173
+ locations.length === 0 ? or22(isNull20(discoverySessions.locations), eq124(discoverySessions.locations, locations)) : eq124(discoverySessions.locations, locations),
81134
81174
  // Seed provider set is identity: a different phrasing distribution
81135
81175
  // must never reuse another set's session. Null (= Gemini-only
81136
81176
  // default, including explicit ['gemini']) matches legacy rows.
81137
- seedProviders == null ? isNull20(discoverySessions.seedProviders) : eq123(discoverySessions.seedProviders, seedProviders),
81177
+ seedProviders == null ? isNull20(discoverySessions.seedProviders) : eq124(discoverySessions.seedProviders, seedProviders),
81138
81178
  inArray58(discoverySessions.status, [
81139
81179
  DiscoverySessionStatuses.queued,
81140
81180
  DiscoverySessionStatuses.seeding,
@@ -81210,7 +81250,7 @@ async function discoveryRoutes(app, opts) {
81210
81250
  const project = resolveProject(app.db, request.params.name);
81211
81251
  const parsedLimit = parseInt(request.query.limit ?? "", 10);
81212
81252
  const limit = Number.isNaN(parsedLimit) || parsedLimit <= 0 ? 50 : parsedLimit;
81213
- const rows = app.db.select().from(discoverySessions).where(eq123(discoverySessions.projectId, project.id)).orderBy(desc57(discoverySessions.createdAt)).limit(limit).all();
81253
+ const rows = app.db.select().from(discoverySessions).where(eq124(discoverySessions.projectId, project.id)).orderBy(desc57(discoverySessions.createdAt)).limit(limit).all();
81214
81254
  return reply.send(rows.map(serializeSession));
81215
81255
  }
81216
81256
  );
@@ -81218,11 +81258,11 @@ async function discoveryRoutes(app, opts) {
81218
81258
  "/projects/:name/discover/sessions/:id",
81219
81259
  async (request, reply) => {
81220
81260
  const project = resolveProject(app.db, request.params.name);
81221
- const session = app.db.select().from(discoverySessions).where(eq123(discoverySessions.id, request.params.id)).get();
81261
+ const session = app.db.select().from(discoverySessions).where(eq124(discoverySessions.id, request.params.id)).get();
81222
81262
  if (!session || session.projectId !== project.id) {
81223
81263
  throw notFound("Discovery session", request.params.id);
81224
81264
  }
81225
- const probeRows = app.db.select().from(discoveryProbes).where(eq123(discoveryProbes.sessionId, session.id)).all();
81265
+ const probeRows = app.db.select().from(discoveryProbes).where(eq124(discoveryProbes.sessionId, session.id)).all();
81226
81266
  const detail = {
81227
81267
  ...serializeSession(session),
81228
81268
  probes: probeRows.map(serializeProbe)
@@ -81236,7 +81276,7 @@ async function discoveryRoutes(app, opts) {
81236
81276
  requireAdminSession(request);
81237
81277
  requirePaidReadScope(request, [], "Discovery harvest requires wildcard (*) API key scope because it can call the embedding provider.");
81238
81278
  const project = resolveProject(app.db, request.params.name);
81239
- const session = app.db.select().from(discoverySessions).where(eq123(discoverySessions.id, request.params.id)).get();
81279
+ const session = app.db.select().from(discoverySessions).where(eq124(discoverySessions.id, request.params.id)).get();
81240
81280
  if (!session || session.projectId !== project.id) {
81241
81281
  throw notFound("Discovery session", request.params.id);
81242
81282
  }
@@ -81244,7 +81284,7 @@ async function discoveryRoutes(app, opts) {
81244
81284
  const minProbeHits = Number.isNaN(parsedFloor) || parsedFloor < 1 ? 1 : parsedFloor;
81245
81285
  const applyAnchor = request.query.anchor !== "false";
81246
81286
  const provider = session.seedProvider ?? "gemini";
81247
- const probeRows = app.db.select().from(discoveryProbes).where(eq123(discoveryProbes.sessionId, session.id)).all();
81287
+ const probeRows = app.db.select().from(discoveryProbes).where(eq124(discoveryProbes.sessionId, session.id)).all();
81248
81288
  const extract = opts.harvestSearchQueries;
81249
81289
  const probesWithQueries = probeRows.map((row) => {
81250
81290
  if (!extract || !row.rawResponse) return { searchQueries: [] };
@@ -81255,7 +81295,7 @@ async function discoveryRoutes(app, opts) {
81255
81295
  return { searchQueries: [] };
81256
81296
  }
81257
81297
  });
81258
- const trackedQueries = app.db.select({ query: queries.query }).from(queries).where(eq123(queries.projectId, project.id)).all().map((r) => r.query);
81298
+ const trackedQueries = app.db.select({ query: queries.query }).from(queries).where(eq124(queries.projectId, project.id)).all().map((r) => r.query);
81259
81299
  const anchorTerms = buildHarvestAnchorTerms(
81260
81300
  [session.icpDescription ?? "", ...trackedQueries],
81261
81301
  effectiveDomains(project)
@@ -81302,11 +81342,11 @@ async function discoveryRoutes(app, opts) {
81302
81342
  "/projects/:name/discover/sessions/:id/promote",
81303
81343
  async (request, reply) => {
81304
81344
  const project = resolveProject(app.db, request.params.name);
81305
- const session = app.db.select().from(discoverySessions).where(eq123(discoverySessions.id, request.params.id)).get();
81345
+ const session = app.db.select().from(discoverySessions).where(eq124(discoverySessions.id, request.params.id)).get();
81306
81346
  if (!session || session.projectId !== project.id) {
81307
81347
  throw notFound("Discovery session", request.params.id);
81308
81348
  }
81309
- const probeRows = app.db.select().from(discoveryProbes).where(eq123(discoveryProbes.sessionId, session.id)).all();
81349
+ const probeRows = app.db.select().from(discoveryProbes).where(eq124(discoveryProbes.sessionId, session.id)).all();
81310
81350
  const cited = /* @__PURE__ */ new Set();
81311
81351
  const aspirational = /* @__PURE__ */ new Set();
81312
81352
  const wasted = /* @__PURE__ */ new Set();
@@ -81341,7 +81381,7 @@ async function discoveryRoutes(app, opts) {
81341
81381
  );
81342
81382
  app.post("/projects/:name/discover/sessions/:id/promote", async (request, reply) => {
81343
81383
  const project = resolveProject(app.db, request.params.name);
81344
- const session = app.db.select().from(discoverySessions).where(eq123(discoverySessions.id, request.params.id)).get();
81384
+ const session = app.db.select().from(discoverySessions).where(eq124(discoverySessions.id, request.params.id)).get();
81345
81385
  if (!session || session.projectId !== project.id) {
81346
81386
  throw notFound("Discovery session", request.params.id);
81347
81387
  }
@@ -81364,7 +81404,7 @@ async function discoveryRoutes(app, opts) {
81364
81404
  const bucketSet = new Set(buckets);
81365
81405
  const includeCompetitors = parsed.data.includeCompetitors ?? true;
81366
81406
  const competitorTypes = parsed.data.competitorTypes ?? DEFAULT_DISCOVERY_PROMOTE_COMPETITOR_TYPES;
81367
- const probeRows = app.db.select().from(discoveryProbes).where(eq123(discoveryProbes.sessionId, session.id)).all();
81407
+ const probeRows = app.db.select().from(discoveryProbes).where(eq124(discoveryProbes.sessionId, session.id)).all();
81368
81408
  const candidateQueries = /* @__PURE__ */ new Set();
81369
81409
  for (const probe of probeRows) {
81370
81410
  if (!probe.bucket) continue;
@@ -81372,7 +81412,7 @@ async function discoveryRoutes(app, opts) {
81372
81412
  if (bucket.success && bucketSet.has(bucket.data)) candidateQueries.add(probe.query);
81373
81413
  }
81374
81414
  const existingQueries = new Set(
81375
- app.db.select({ query: queries.query }).from(queries).where(eq123(queries.projectId, project.id)).all().map((r) => r.query.toLowerCase())
81415
+ app.db.select({ query: queries.query }).from(queries).where(eq124(queries.projectId, project.id)).all().map((r) => r.query.toLowerCase())
81376
81416
  );
81377
81417
  const promotedQueries = [];
81378
81418
  const skippedQueries = [];
@@ -81586,7 +81626,7 @@ function planCompetitorPromotion(input) {
81586
81626
 
81587
81627
  // ../api-routes/src/discovery/orchestrate.ts
81588
81628
  import crypto65 from "crypto";
81589
- import { eq as eq124 } from "drizzle-orm";
81629
+ import { eq as eq125 } from "drizzle-orm";
81590
81630
  var DEFAULT_MAX_PROBES = 100;
81591
81631
  var ABSOLUTE_MAX_PROBES = 500;
81592
81632
  function classifyProbeBucket(input) {
@@ -81672,7 +81712,7 @@ async function executeDiscovery(opts) {
81672
81712
  status: DiscoverySessionStatuses.seeding,
81673
81713
  dedupThreshold,
81674
81714
  startedAt
81675
- }).where(eq124(discoverySessions.id, opts.sessionId)).run();
81715
+ }).where(eq125(discoverySessions.id, opts.sessionId)).run();
81676
81716
  const seedResult = await opts.deps.seed({
81677
81717
  project: opts.project,
81678
81718
  icpDescription: opts.icpDescription,
@@ -81733,7 +81773,7 @@ async function executeDiscovery(opts) {
81733
81773
  dedupBandPairFraction: dedupStats.bandPairFraction,
81734
81774
  dedupPairsTotal: dedupStats.pairsTotal,
81735
81775
  warning
81736
- }).where(eq124(discoverySessions.id, opts.sessionId)).run();
81776
+ }).where(eq125(discoverySessions.id, opts.sessionId)).run();
81737
81777
  const probeLocation = opts.locations?.[0];
81738
81778
  const probeResults = await mapWithConcurrency(
81739
81779
  probedCanonicals,
@@ -81787,7 +81827,7 @@ async function executeDiscovery(opts) {
81787
81827
  wastedCount: buckets["wasted-surface"],
81788
81828
  competitorMap,
81789
81829
  finishedAt: (/* @__PURE__ */ new Date()).toISOString()
81790
- }).where(eq124(discoverySessions.id, opts.sessionId)).run();
81830
+ }).where(eq125(discoverySessions.id, opts.sessionId)).run();
81791
81831
  upsertDomainClassifications(opts.db, opts.project.id, opts.sessionId, competitorMap);
81792
81832
  return {
81793
81833
  buckets,
@@ -81827,7 +81867,7 @@ function markSessionFailed(db, sessionId, error) {
81827
81867
  status: DiscoverySessionStatuses.failed,
81828
81868
  error,
81829
81869
  finishedAt: (/* @__PURE__ */ new Date()).toISOString()
81830
- }).where(eq124(discoverySessions.id, sessionId)).run();
81870
+ }).where(eq125(discoverySessions.id, sessionId)).run();
81831
81871
  }
81832
81872
  function dedupeStrings(input) {
81833
81873
  const seen2 = /* @__PURE__ */ new Set();
@@ -81844,7 +81884,7 @@ function dedupeStrings(input) {
81844
81884
  }
81845
81885
 
81846
81886
  // ../api-routes/src/trends.ts
81847
- import { and as and104, asc as asc30, eq as eq125 } from "drizzle-orm";
81887
+ import { and as and105, asc as asc30, eq as eq126 } from "drizzle-orm";
81848
81888
  function parseSurface(value) {
81849
81889
  const parsed = trendSurfaceSchema.safeParse(value);
81850
81890
  if (!parsed.success) {
@@ -81900,8 +81940,8 @@ async function trendsRoutes(app) {
81900
81940
  function readSurface(app, projectId, surface) {
81901
81941
  switch (surface) {
81902
81942
  case TrendSurfaces["index-coverage"]: {
81903
- const google = app.db.select({ date: gscCoverageSnapshots.date, indexed: gscCoverageSnapshots.indexed, notIndexed: gscCoverageSnapshots.notIndexed }).from(gscCoverageSnapshots).where(eq125(gscCoverageSnapshots.projectId, projectId)).orderBy(asc30(gscCoverageSnapshots.date)).all();
81904
- const bing = app.db.select({ date: bingCoverageSnapshots.date, indexed: bingCoverageSnapshots.indexed, notIndexed: bingCoverageSnapshots.notIndexed }).from(bingCoverageSnapshots).where(eq125(bingCoverageSnapshots.projectId, projectId)).orderBy(asc30(bingCoverageSnapshots.date)).all();
81943
+ const google = app.db.select({ date: gscCoverageSnapshots.date, indexed: gscCoverageSnapshots.indexed, notIndexed: gscCoverageSnapshots.notIndexed }).from(gscCoverageSnapshots).where(eq126(gscCoverageSnapshots.projectId, projectId)).orderBy(asc30(gscCoverageSnapshots.date)).all();
81944
+ const bing = app.db.select({ date: bingCoverageSnapshots.date, indexed: bingCoverageSnapshots.indexed, notIndexed: bingCoverageSnapshots.notIndexed }).from(bingCoverageSnapshots).where(eq126(bingCoverageSnapshots.projectId, projectId)).orderBy(asc30(bingCoverageSnapshots.date)).all();
81905
81945
  const coverage = (key, label, rows) => ({
81906
81946
  key,
81907
81947
  label,
@@ -81913,7 +81953,7 @@ function readSurface(app, projectId, surface) {
81913
81953
  return [coverage("google", "Google", google), coverage("bing", "Bing", bing)];
81914
81954
  }
81915
81955
  case TrendSurfaces["site-health"]: {
81916
- const rows = app.db.select({ auditedAt: siteAuditSnapshots.auditedAt, aggregateScore: siteAuditSnapshots.aggregateScore, pagesAudited: siteAuditSnapshots.pagesAudited }).from(siteAuditSnapshots).innerJoin(runs, eq125(siteAuditSnapshots.runId, runs.id)).where(and104(...surfaceableSiteAuditFilters(projectId))).orderBy(asc30(siteAuditSnapshots.auditedAt)).all();
81956
+ const rows = app.db.select({ auditedAt: siteAuditSnapshots.auditedAt, aggregateScore: siteAuditSnapshots.aggregateScore, pagesAudited: siteAuditSnapshots.pagesAudited }).from(siteAuditSnapshots).innerJoin(runs, eq126(siteAuditSnapshots.runId, runs.id)).where(and105(...surfaceableSiteAuditFilters(projectId))).orderBy(asc30(siteAuditSnapshots.auditedAt)).all();
81917
81957
  return [{
81918
81958
  key: "site-health",
81919
81959
  label: "Agent Readiness",
@@ -81925,7 +81965,7 @@ function readSurface(app, projectId, surface) {
81925
81965
  }
81926
81966
  case TrendSurfaces.backlinks: {
81927
81967
  const totals = computeFilteredReleaseTotals(app.db, projectId, BacklinkSources.commoncrawl);
81928
- const rows = app.db.select({ release: backlinkSummaries.release, totalLinkingDomains: backlinkSummaries.totalLinkingDomains, queriedAt: backlinkSummaries.queriedAt }).from(backlinkSummaries).where(and104(eq125(backlinkSummaries.projectId, projectId), eq125(backlinkSummaries.source, BacklinkSources.commoncrawl))).all().sort((a, b) => compareReleaseIds(a.release, b.release)).map((row) => {
81968
+ const rows = app.db.select({ release: backlinkSummaries.release, totalLinkingDomains: backlinkSummaries.totalLinkingDomains, queriedAt: backlinkSummaries.queriedAt }).from(backlinkSummaries).where(and105(eq126(backlinkSummaries.projectId, projectId), eq126(backlinkSummaries.source, BacklinkSources.commoncrawl))).all().sort((a, b) => compareReleaseIds(a.release, b.release)).map((row) => {
81929
81969
  const filtered = totals.get(row.release);
81930
81970
  const known = (filtered?.domainRows ?? 0) > 0 || row.totalLinkingDomains === 0;
81931
81971
  const windowEnd = releaseWindowEndMonth(row.release);
@@ -81955,7 +81995,7 @@ function readSurface(app, projectId, surface) {
81955
81995
  // ../api-routes/src/research.ts
81956
81996
  import crypto66 from "crypto";
81957
81997
  import { z as z7 } from "zod";
81958
- import { and as and105, count as count10, desc as desc58, eq as eq126, gte as gte34, lt as lt21, or as or23, sql as sql52 } from "drizzle-orm";
81998
+ import { and as and106, count as count10, desc as desc58, eq as eq127, gte as gte34, lt as lt21, or as or23, sql as sql52 } from "drizzle-orm";
81959
81999
  var sameLocation = (a, b) => a.label === b.label && a.city === b.city && a.region === b.region && a.country === b.country && a.timezone === b.timezone;
81960
82000
  var BATCH_RECEIPT_PREFIX = "__canonry_research_batch__:";
81961
82001
  async function researchRoutes(app, opts) {
@@ -81974,7 +82014,7 @@ async function researchRoutes(app, opts) {
81974
82014
  const input = parsed.data;
81975
82015
  if (input.idempotencyKey?.startsWith(BATCH_RECEIPT_PREFIX)) throw validationError("This idempotency key prefix is reserved for internal research batch receipts.");
81976
82016
  const requestHash2 = directResearchRequestHash(input);
81977
- const existingReceipt = input.idempotencyKey ? app.db.select().from(researchRuns).where(and105(eq126(researchRuns.projectId, project.id), eq126(researchRuns.idempotencyKey, input.idempotencyKey))).get() : void 0;
82017
+ const existingReceipt = input.idempotencyKey ? app.db.select().from(researchRuns).where(and106(eq127(researchRuns.projectId, project.id), eq127(researchRuns.idempotencyKey, input.idempotencyKey))).get() : void 0;
81978
82018
  if (existingReceipt) {
81979
82019
  assertSameDirectResearchRequest(existingReceipt, input, requestHash2);
81980
82020
  const result2 = getDetail(app, project.id, existingReceipt.id);
@@ -82009,7 +82049,7 @@ async function researchRoutes(app, opts) {
82009
82049
  const initiatedBy = researchPrincipal(request);
82010
82050
  const decision = app.db.transaction((tx) => {
82011
82051
  if (input.idempotencyKey) {
82012
- const existing = tx.select().from(researchRuns).where(and105(eq126(researchRuns.projectId, project.id), eq126(researchRuns.idempotencyKey, input.idempotencyKey))).get();
82052
+ const existing = tx.select().from(researchRuns).where(and106(eq127(researchRuns.projectId, project.id), eq127(researchRuns.idempotencyKey, input.idempotencyKey))).get();
82013
82053
  if (existing) {
82014
82054
  assertSameDirectResearchRequest(existing, input, requestHash2);
82015
82055
  return { reused: true, id: existing.id, shouldDispatch: existing.status === ResearchRunStatuses.queued };
@@ -82017,8 +82057,8 @@ async function researchRoutes(app, opts) {
82017
82057
  }
82018
82058
  if (initiatedBy?.limited) {
82019
82059
  const { start, end, date } = utcDayBounds(now);
82020
- const used = tx.select({ value: count10() }).from(researchRuns).where(and105(
82021
- eq126(researchRuns.projectId, project.id),
82060
+ const used = tx.select({ value: count10() }).from(researchRuns).where(and106(
82061
+ eq127(researchRuns.projectId, project.id),
82022
82062
  gte34(researchRuns.createdAt, start),
82023
82063
  lt21(researchRuns.createdAt, end),
82024
82064
  sql52`(json_extract(${researchRuns.initiatedBy}, '$.role') = ${UserRoles.viewer} OR json_extract(${researchRuns.initiatedBy}, '$.limited') = 1)`
@@ -82049,15 +82089,15 @@ async function researchRoutes(app, opts) {
82049
82089
  if (input.idempotencyKey.startsWith(BATCH_RECEIPT_PREFIX)) throw validationError("This idempotency key prefix is reserved for internal research batch receipts.");
82050
82090
  const requestHash2 = researchBatchRequestHash(input);
82051
82091
  const receiptKeys = input.runs.map((_run, index) => batchChildReceiptKey(input.idempotencyKey, index));
82052
- const firstReceipt = app.db.select().from(researchRuns).where(and105(
82053
- eq126(researchRuns.projectId, project.id),
82054
- eq126(researchRuns.idempotencyKey, receiptKeys[0])
82092
+ const firstReceipt = app.db.select().from(researchRuns).where(and106(
82093
+ eq127(researchRuns.projectId, project.id),
82094
+ eq127(researchRuns.idempotencyKey, receiptKeys[0])
82055
82095
  )).get();
82056
82096
  if (firstReceipt) {
82057
82097
  if (firstReceipt.requestHash !== requestHash2) throw alreadyExists("Research batch idempotency key", input.idempotencyKey);
82058
- const saved = receiptKeys.map((key) => app.db.select().from(researchRuns).where(and105(
82059
- eq126(researchRuns.projectId, project.id),
82060
- eq126(researchRuns.idempotencyKey, key)
82098
+ const saved = receiptKeys.map((key) => app.db.select().from(researchRuns).where(and106(
82099
+ eq127(researchRuns.projectId, project.id),
82100
+ eq127(researchRuns.idempotencyKey, key)
82061
82101
  )).get());
82062
82102
  if (saved.some((row) => !row || row.requestHash !== requestHash2)) throw alreadyExists("Research batch idempotency key", input.idempotencyKey);
82063
82103
  const runs3 = saved.map((row) => getDetail(app, project.id, row.id));
@@ -82073,8 +82113,8 @@ async function researchRoutes(app, opts) {
82073
82113
  const decision = app.db.transaction((tx) => {
82074
82114
  if (initiatedBy?.limited) {
82075
82115
  const { start, end, date } = utcDayBounds(now);
82076
- const used = tx.select({ value: count10() }).from(researchRuns).where(and105(
82077
- eq126(researchRuns.projectId, project.id),
82116
+ const used = tx.select({ value: count10() }).from(researchRuns).where(and106(
82117
+ eq127(researchRuns.projectId, project.id),
82078
82118
  gte34(researchRuns.createdAt, start),
82079
82119
  lt21(researchRuns.createdAt, end),
82080
82120
  sql52`(json_extract(${researchRuns.initiatedBy}, '$.role') = ${UserRoles.viewer} OR json_extract(${researchRuns.initiatedBy}, '$.limited') = 1)`
@@ -82128,9 +82168,9 @@ async function researchRoutes(app, opts) {
82128
82168
  const requested = Number.parseInt(request.query.limit ?? "", 10);
82129
82169
  const limit = Number.isInteger(requested) && requested > 0 ? Math.min(requested, 100) : 20;
82130
82170
  const cursor = request.query.cursor ? parseResearchCursor(request.query.cursor, project.id) : null;
82131
- const rows = app.db.select().from(researchRuns).where(and105(
82132
- eq126(researchRuns.projectId, project.id),
82133
- cursor ? or23(lt21(researchRuns.createdAt, cursor.createdAt), and105(eq126(researchRuns.createdAt, cursor.createdAt), lt21(researchRuns.id, cursor.id))) : void 0
82171
+ const rows = app.db.select().from(researchRuns).where(and106(
82172
+ eq127(researchRuns.projectId, project.id),
82173
+ cursor ? or23(lt21(researchRuns.createdAt, cursor.createdAt), and106(eq127(researchRuns.createdAt, cursor.createdAt), lt21(researchRuns.id, cursor.id))) : void 0
82134
82174
  )).orderBy(desc58(researchRuns.createdAt), desc58(researchRuns.id)).limit(limit + 1).all();
82135
82175
  const runs2 = rows.slice(0, limit).map(serializeRun);
82136
82176
  const last = runs2.at(-1);
@@ -82280,9 +82320,9 @@ function resolveStoredResearchTemplate(stored, selection, idempotencyKey) {
82280
82320
  return stored;
82281
82321
  }
82282
82322
  function resolveResearchTemplate(app, projectId, selection, scope, location) {
82283
- const savedTemplate = app.db.select().from(measurementQueryTemplates).where(and105(
82284
- eq126(measurementQueryTemplates.projectId, projectId),
82285
- eq126(measurementQueryTemplates.id, selection.templateId)
82323
+ const savedTemplate = app.db.select().from(measurementQueryTemplates).where(and106(
82324
+ eq127(measurementQueryTemplates.projectId, projectId),
82325
+ eq127(measurementQueryTemplates.id, selection.templateId)
82286
82326
  )).get();
82287
82327
  if (!savedTemplate) throw validationError("Unknown or stale research template. Reload the selected template and try again.");
82288
82328
  const templateVersion = savedTemplate.updatedAt;
@@ -82291,7 +82331,7 @@ function resolveResearchTemplate(app, projectId, selection, scope, location) {
82291
82331
  }
82292
82332
  const bindingLocation = selection.bindingLocation === void 0 ? location : selection.bindingLocation;
82293
82333
  if (bindingLocation) {
82294
- const project = app.db.select({ locations: projects.locations }).from(projects).where(eq126(projects.id, projectId)).get();
82334
+ const project = app.db.select({ locations: projects.locations }).from(projects).where(eq127(projects.id, projectId)).get();
82295
82335
  if (!project.locations.some((item2) => sameLocation(item2, bindingLocation))) throw validationError("Research template binding location must match a configured project location.");
82296
82336
  }
82297
82337
  const { bindings, output } = expandResearchTemplate(savedTemplate, scope, bindingLocation);
@@ -82304,9 +82344,9 @@ function classifyResearchQueries(project, plan, queries2) {
82304
82344
  return queries2.map((query2) => classifier?.classify(query2) ?? null);
82305
82345
  }
82306
82346
  function getDetail(app, projectId, id) {
82307
- const row = app.db.select().from(researchRuns).where(and105(eq126(researchRuns.id, id), eq126(researchRuns.projectId, projectId))).get();
82347
+ const row = app.db.select().from(researchRuns).where(and106(eq127(researchRuns.id, id), eq127(researchRuns.projectId, projectId))).get();
82308
82348
  if (!row) throw notFound("Research run", id);
82309
- const queries2 = app.db.select().from(researchRunQueries).where(eq126(researchRunQueries.researchRunId, id)).orderBy(researchRunQueries.position).all().map((query2) => serializeQuery(query2, row.provider));
82349
+ const queries2 = app.db.select().from(researchRunQueries).where(eq127(researchRunQueries.researchRunId, id)).orderBy(researchRunQueries.position).all().map((query2) => serializeQuery(query2, row.provider));
82310
82350
  return { ...serializeRun(row), queries: queries2 };
82311
82351
  }
82312
82352
  function serializeRun(row) {
@@ -82367,7 +82407,7 @@ function utcDayBounds(now) {
82367
82407
 
82368
82408
  // ../api-routes/src/simple-measurement-definitions.ts
82369
82409
  import crypto67 from "crypto";
82370
- import { and as and106, eq as eq127 } from "drizzle-orm";
82410
+ import { and as and107, eq as eq128 } from "drizzle-orm";
82371
82411
  function captureSimpleMeasurementDefinition(db, input) {
82372
82412
  return db.transaction((tx) => {
82373
82413
  const run = tx.select({
@@ -82375,7 +82415,7 @@ function captureSimpleMeasurementDefinition(db, input) {
82375
82415
  trigger: runs.trigger,
82376
82416
  status: runs.status,
82377
82417
  measurementPlanVersionId: runs.measurementPlanVersionId
82378
- }).from(runs).where(and106(eq127(runs.projectId, input.projectId), eq127(runs.id, input.runId))).get();
82418
+ }).from(runs).where(and107(eq128(runs.projectId, input.projectId), eq128(runs.id, input.runId))).get();
82379
82419
  if (!run) throw notFound("Run", input.runId);
82380
82420
  if (run.kind !== RunKinds["answer-visibility"] || run.trigger === RunTriggers.probe || run.measurementPlanVersionId !== null) {
82381
82421
  return null;
@@ -82396,7 +82436,7 @@ function captureSimpleMeasurementDefinition(db, input) {
82396
82436
  throw validationError("Qualified aliases must be a sorted subset of the captured aliases.");
82397
82437
  }
82398
82438
  }
82399
- const existing = tx.select().from(simpleMeasurementDefinitions).where(and106(eq127(simpleMeasurementDefinitions.projectId, input.projectId), eq127(simpleMeasurementDefinitions.runId, input.runId))).get();
82439
+ const existing = tx.select().from(simpleMeasurementDefinitions).where(and107(eq128(simpleMeasurementDefinitions.projectId, input.projectId), eq128(simpleMeasurementDefinitions.runId, input.runId))).get();
82400
82440
  if (existing) {
82401
82441
  const frozen = simpleMeasurementDefinitionSchema.parse(existing.definition);
82402
82442
  const { qualifiedAliases: _liveQualifiedAliases, ...liveIdentity } = definition2.identity;
@@ -82422,15 +82462,15 @@ function captureSimpleMeasurementDefinition(db, input) {
82422
82462
  if (run.status !== RunStatuses.running) {
82423
82463
  throw validationError("Only a running run can capture a new measurement definition.");
82424
82464
  }
82425
- if (tx.select({ id: querySnapshots.id }).from(querySnapshots).where(eq127(querySnapshots.runId, input.runId)).limit(1).get()) {
82465
+ if (tx.select({ id: querySnapshots.id }).from(querySnapshots).where(eq128(querySnapshots.runId, input.runId)).limit(1).get()) {
82426
82466
  throw validationError("This run already has stored answers. Its measurement definition cannot be inferred afterward.");
82427
82467
  }
82428
- const projectQueryIds = new Set(tx.select({ id: queries.id }).from(queries).where(eq127(queries.projectId, input.projectId)).all().map((query2) => query2.id));
82468
+ const projectQueryIds = new Set(tx.select({ id: queries.id }).from(queries).where(eq128(queries.projectId, input.projectId)).all().map((query2) => query2.id));
82429
82469
  if (definition2.queries.some((query2) => !projectQueryIds.has(query2.queryId))) {
82430
82470
  throw validationError("Every captured query must belong to the run project.");
82431
82471
  }
82432
82472
  if (definition2.competitors !== void 0) {
82433
- const liveCompetitorDomains = new Set(tx.select({ domain: competitors.domain }).from(competitors).where(eq127(competitors.projectId, input.projectId)).orderBy(competitors.domain).all().map((competitor) => competitor.domain));
82473
+ const liveCompetitorDomains = new Set(tx.select({ domain: competitors.domain }).from(competitors).where(eq128(competitors.projectId, input.projectId)).orderBy(competitors.domain).all().map((competitor) => competitor.domain));
82434
82474
  const capturedDomains = new Set(definition2.competitors.map((competitor) => competitor.domain));
82435
82475
  if (liveCompetitorDomains.size !== capturedDomains.size || [...liveCompetitorDomains].some((domain) => !capturedDomains.has(domain))) {
82436
82476
  throw validationError("Captured competitors must exactly match the project competitors dispatched for this run.");