@canonry/canonry 7.118.1 → 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.
- package/assets/assets/{AccessControls-CCvvzEec.js → AccessControls-D9u5mHZy.js} +1 -1
- package/assets/assets/{AgentSetupPage-B-vXoIII.js → AgentSetupPage-sxobNnR4.js} +1 -1
- package/assets/assets/{AuditHistoryPanel-ClexSdME.js → AuditHistoryPanel-B-br1Rgm.js} +1 -1
- package/assets/assets/{BacklinksPage-QMPUVhzl.js → BacklinksPage-DBncT_in.js} +1 -1
- package/assets/assets/{ChartPrimitives-Dd9VFWrj.js → ChartPrimitives-BVl_On4G.js} +1 -1
- package/assets/assets/{HistoryPage-CzQLFEZG.js → HistoryPage-DLzXIHGd.js} +1 -1
- package/assets/assets/{MeasurementPropertyPage-BTgy_3-R.js → MeasurementPropertyPage-C2RXn2iP.js} +1 -1
- package/assets/assets/ProjectPage-CUGvozZu.js +15 -0
- package/assets/assets/{RunsPage-CnWXQk8q.js → RunsPage-CGdstDkz.js} +1 -1
- package/assets/assets/{ServerTrafficSection-DqVZznpe.js → ServerTrafficSection-DsmN-vR2.js} +3 -3
- package/assets/assets/{SettingsPage-D2j93m5Q.js → SettingsPage-DAnYQBff.js} +1 -1
- package/assets/assets/{ToneBadge-Dym1_0XC.js → ToneBadge-BCQPh7t2.js} +4 -4
- package/assets/assets/{TrafficPage-CzieybRn.js → TrafficPage-HQMcIXhQ.js} +1 -1
- package/assets/assets/{TrafficSourceDetailPage-CtmGPXZc.js → TrafficSourceDetailPage-BXQX0fyG.js} +1 -1
- package/assets/assets/{account-context-ClThq0Zv.js → account-context-BNo2KFA7.js} +1 -1
- package/assets/assets/{agent-trust-copy-C0WnWM9W.js → agent-trust-copy-B3Dw_M_3.js} +1 -1
- package/assets/assets/{card-C-9Q2kJl.js → card-h-mmYzMc.js} +1 -1
- package/assets/assets/{index-CzPXJ0Qs.js → index-DpBLjU4G.js} +3 -3
- package/assets/assets/{preload-helper-DV4nEYWy.js → preload-helper-D2o-5DDv.js} +1 -1
- package/assets/assets/{query-client-plQHRUyr.js → query-client-gk-fhrrc.js} +1 -1
- package/assets/assets/{react-query-Dz0xmEkM.js → react-query-hUdNgz2a.js} +1 -1
- package/assets/assets/{react-sigma_core.esm.min-B-tTeVwc.js → react-sigma_core.esm.min-CbMudrIV.js} +1 -1
- package/assets/assets/{server-traffic-BNdX8qZ4.js → server-traffic-CL5cYldZ.js} +1 -1
- package/assets/assets/{service-CN4HIDuw.js → service-CxbxBFUX.js} +1 -1
- package/assets/index.html +9 -9
- package/dist/{ads-GVOTYDS3.js → ads-PMDSTHUC.js} +4 -4
- package/dist/{agent-RFYMQYMN.js → agent-5EL5AECW.js} +8 -8
- package/dist/{agent-ask-MZRUCCJO.js → agent-ask-VAZUSWFA.js} +4 -4
- package/dist/{agent-conversations-WBP5TI3X.js → agent-conversations-KOBHBQS6.js} +4 -4
- package/dist/{agent-journeys-6CR77XCZ.js → agent-journeys-Q5J6K76M.js} +4 -4
- package/dist/{agent-memory-PH3Y7OKJ.js → agent-memory-UTZWNL5K.js} +4 -4
- package/dist/{agent-providers-3CBKNXSW.js → agent-providers-TBMKTIJT.js} +4 -4
- package/dist/{agent-transcript-BN3DCK33.js → agent-transcript-4MIMLCSN.js} +4 -4
- package/dist/{analytics-43UR5IMY.js → analytics-VGPQ3P7U.js} +4 -4
- package/dist/{apply-POV25FNG.js → apply-AL52P3BT.js} +4 -4
- package/dist/{backfill-UCUWFGCR.js → backfill-XBQYJBCL.js} +11 -11
- package/dist/{backlinks-W3SLOIHP.js → backlinks-T5ZWICGA.js} +4 -4
- package/dist/{bing-HGKOR5GV.js → bing-DFU4M6P2.js} +4 -4
- package/dist/{bootstrap-XAKQKZCC.js → bootstrap-VBGDPCJ4.js} +11 -11
- package/dist/{cdp-WAB5BPGB.js → cdp-WHDGSGRE.js} +8 -8
- package/dist/{chunk-WKYQRF5A.js → chunk-2FNWSHOE.js} +3 -3
- package/dist/{chunk-HQ6GLLVU.js → chunk-3N2MSPPU.js} +2 -2
- package/dist/{chunk-NZZSWCNM.js → chunk-3Q2D53KV.js} +1 -1
- package/dist/{chunk-TO6J7C35.js → chunk-3QOFLP4W.js} +5 -5
- package/dist/{chunk-SZSZSOXP.js → chunk-47Y5UAYA.js} +2 -2
- package/dist/{chunk-GY7YLVMD.js → chunk-5KINLLTJ.js} +4 -4
- package/dist/{chunk-ZFHVEEXB.js → chunk-5QNFX55U.js} +407 -327
- package/dist/{chunk-ILDAN5TW.js → chunk-6KH4XZLA.js} +1 -1
- package/dist/{chunk-ISLMLTSB.js → chunk-7R6I6AIP.js} +8 -8
- package/dist/{chunk-35DM6ZZ2.js → chunk-AHVF5OE5.js} +2 -2
- package/dist/{chunk-Q7LU7GTH.js → chunk-AOD35IKL.js} +1 -1
- package/dist/{chunk-LSNAMUIJ.js → chunk-AOYSK6D2.js} +2 -2
- package/dist/{chunk-YWRXCL3J.js → chunk-BD24MSOA.js} +22 -22
- package/dist/{chunk-HZTKUGQ4.js → chunk-EZOBUXLP.js} +3 -3
- package/dist/{chunk-4A2JURHR.js → chunk-FTPGW2WX.js} +2 -2
- package/dist/{chunk-LBNJVTGN.js → chunk-GDRZPBPF.js} +2 -2
- package/dist/{chunk-A5X7CSVB.js → chunk-GVU4QOUA.js} +5 -5
- package/dist/{chunk-6UNZDUB6.js → chunk-HFNLWW3Z.js} +1 -1
- package/dist/{chunk-OBRB7CN6.js → chunk-HODKOOJZ.js} +369 -369
- package/dist/{chunk-WEZC57IK.js → chunk-IPOERWGQ.js} +5 -5
- package/dist/{chunk-VU3TF5CD.js → chunk-IWQFTZ75.js} +1 -1
- package/dist/{chunk-7ACE6HGU.js → chunk-J4FMWPEM.js} +3 -3
- package/dist/{chunk-DSDNQLJO.js → chunk-N5N4TXBD.js} +4 -4
- package/dist/{chunk-SBLC7FYP.js → chunk-NQFBIMS4.js} +2 -2
- package/dist/{chunk-6ORW2OUQ.js → chunk-OO4RE44D.js} +1 -1
- package/dist/{chunk-IOOJ7DQ6.js → chunk-OXYZQJLV.js} +1 -1
- package/dist/{chunk-U3TO2MFS.js → chunk-QCXKLTVC.js} +4 -4
- package/dist/{chunk-QOFWKOKD.js → chunk-RLLYGXNA.js} +4 -4
- package/dist/{chunk-6AJ4Y3QL.js → chunk-TS477DBZ.js} +2 -2
- package/dist/{chunk-GSQQ6VVV.js → chunk-TTQBEFSU.js} +1 -1
- package/dist/{chunk-EHOA2RFV.js → chunk-UA7WWHPW.js} +6 -6
- package/dist/{chunk-G3HBHMML.js → chunk-VCXKSGZF.js} +1 -1
- package/dist/{chunk-XDOP2ANX.js → chunk-VOK62VGC.js} +3116 -3069
- package/dist/{chunk-G2JP3KNY.js → chunk-WVZR3J7X.js} +4 -4
- package/dist/{chunk-V2VWIGVT.js → chunk-XTR3KSV2.js} +1 -1
- package/dist/{chunk-7JFPGEXQ.js → chunk-ZCRUXUHU.js} +4 -4
- package/dist/{chunk-377K7XSP.js → chunk-ZDYWXTNN.js} +4 -4
- package/dist/{citations-IMPVSN25.js → citations-JOM2DJX3.js} +5 -5
- package/dist/{cli-catalog-OFMWOBCF.js → cli-catalog-4ZCK2TFK.js} +4 -4
- package/dist/cli-commands-SZYTLQU4.js +18 -0
- package/dist/cli.js +14 -14
- package/dist/{competitor-2NFTABZM.js → competitor-FQH7LNR2.js} +4 -4
- package/dist/{content-HYV3JOIS.js → content-KEZJJEV2.js} +4 -4
- package/dist/{dashboard-OY75SNYT.js → dashboard-IWBIZR3V.js} +7 -7
- package/dist/{demo-643NLHIX.js → demo-2P37KIQK.js} +3 -3
- package/dist/{demo-server-W7YKCOQJ.js → demo-server-6OQXQ7C3.js} +13 -13
- package/dist/{discover-VIQMARSR.js → discover-ZB6I2A65.js} +5 -5
- package/dist/{discover-eval-M5RRXWMX.js → discover-eval-XXRA3XDQ.js} +4 -4
- package/dist/{doctor-HATXMESK.js → doctor-KTGY5L57.js} +4 -4
- package/dist/{evidence-C3IBS7TO.js → evidence-BEBTLKK4.js} +4 -4
- package/dist/{export-cmd-F674KINC.js → export-cmd-VIQGUL7N.js} +4 -4
- package/dist/{ga-AWBTXHSN.js → ga-YEQKHEN2.js} +4 -4
- package/dist/{gbp-NAZYXN4S.js → gbp-NFTRCNGZ.js} +4 -4
- package/dist/{google-IYDAWLIV.js → google-MBQW2EGU.js} +5 -5
- package/dist/{google-marketing-NHV7BCQM.js → google-marketing-KIGW7ZGN.js} +2 -2
- package/dist/{health-cmd-ASZUPWDG.js → health-cmd-6B6VSAX3.js} +5 -5
- package/dist/{history-TFLEYUHW.js → history-DX2QSPL2.js} +4 -4
- package/dist/index.d.ts +29 -29
- package/dist/index.js +26 -26
- package/dist/{init-CYZUNXPV.js → init-NJAZR6MI.js} +13 -13
- package/dist/{insights-VMU43BJM.js → insights-ZJD3KUA7.js} +4 -4
- package/dist/intelligence-service-PJAISWKW.js +15 -0
- package/dist/{journeys-DSPUDWGM.js → journeys-E4FC7PCM.js} +4 -4
- package/dist/{keys-K56VXNJX.js → keys-TD6NBRRY.js} +4 -4
- package/dist/{keyword-FCMS45PF.js → keyword-FEOQSKMZ.js} +4 -4
- package/dist/{logs-75HP7UD3.js → logs-YV5JPJH3.js} +4 -4
- package/dist/{mcp-D7P73XVO.js → mcp-S3YNKUQQ.js} +5 -5
- package/dist/mcp.js +10 -10
- package/dist/{measurement-plan-AX6G3RWU.js → measurement-plan-VVDLIBQO.js} +6 -6
- package/dist/{notify-QUOFVHKS.js → notify-GUJ6PLRU.js} +4 -4
- package/dist/{organic-evidence-PPHL7QGS.js → organic-evidence-A66B5BWS.js} +4 -4
- package/dist/{overview-C6SSTCC6.js → overview-JKW5LARL.js} +6 -6
- package/dist/{project-MMQ2H6TH.js → project-XUYBPKWJ.js} +4 -4
- package/dist/{project-setup-6DGYQAG2.js → project-setup-YO6R26JG.js} +4 -4
- package/dist/{query-EJGNRC2F.js → query-YOTYGF4K.js} +4 -4
- package/dist/{research-X43RAY3W.js → research-QVG5XZDF.js} +4 -4
- package/dist/{results-export-FOQXK6NA.js → results-export-4TMA6DJT.js} +4 -4
- package/dist/{run-D4CFXIFR.js → run-HGYYDS6S.js} +6 -6
- package/dist/{schedule-UFOJOPKA.js → schedule-RR6OUMKT.js} +4 -4
- package/dist/{search-6C3ZPK24.js → search-KO7PIUMR.js} +4 -4
- package/dist/{serve-RBBLESEQ.js → serve-FQFTGJ2Y.js} +27 -27
- package/dist/{session-4BIHTXY3.js → session-GVLHMMVC.js} +14 -14
- package/dist/{settings-6AGLHMPI.js → settings-HDENU4PV.js} +4 -4
- package/dist/{sitemaps-FIN5CVTH.js → sitemaps-GTHH2RP3.js} +4 -4
- package/dist/{skills-3ZD3N6S7.js → skills-U3MDHCWF.js} +3 -3
- package/dist/{snapshot-EFW3B6TM.js → snapshot-SWFUS4D2.js} +4 -4
- package/dist/{src-QSFAXHBF.js → src-R74K2NOZ.js} +2 -2
- package/dist/{status-CLWEOZP4.js → status-ACUIXSLV.js} +6 -6
- package/dist/{support-P5H555LC.js → support-3IFWJF3E.js} +2 -2
- package/dist/{technical-aeo-IVNC26PJ.js → technical-aeo-NWE56UCG.js} +4 -4
- package/dist/{telemetry-ZUFUNFST.js → telemetry-CHW3LG5A.js} +5 -5
- package/dist/{tools-V2V7RUTA.js → tools-LAIZGKA3.js} +12 -12
- package/dist/{traffic-CN667DLE.js → traffic-MHCGXV2V.js} +25 -8
- package/dist/{trends-2XLTO3EN.js → trends-5IEV52XW.js} +4 -4
- package/dist/{users-NXZSJ7CM.js → users-KRY5MKJ4.js} +4 -4
- package/dist/{visibility-stats-DTJD4TEN.js → visibility-stats-JF3SXXKS.js} +5 -5
- package/dist/{wordpress-LE6UNQCX.js → wordpress-TV2NSQPK.js} +4 -4
- package/package.json +1 -1
- package/assets/assets/ProjectPage-DLgYLplH.js +0 -15
- package/dist/cli-commands-TJHBC2HQ.js +0 -18
- package/dist/intelligence-service-NGD2KVLQ.js +0 -15
|
@@ -19,14 +19,14 @@ import {
|
|
|
19
19
|
normalizeTrafficPathPattern,
|
|
20
20
|
sessionizeJourneyRequests,
|
|
21
21
|
verifyRequestSignature
|
|
22
|
-
} from "./chunk-
|
|
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-
|
|
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-
|
|
193
|
+
} from "./chunk-VCXKSGZF.js";
|
|
194
194
|
import {
|
|
195
195
|
ADS_ACTIVATE_SCOPE,
|
|
196
196
|
ADS_ACTIVATION_ABSOLUTE_MAX_ENTITIES,
|
|
@@ -712,6 +712,7 @@ import {
|
|
|
712
712
|
createUserInvitationRequestSchema,
|
|
713
713
|
createUserRequestSchema,
|
|
714
714
|
createdApiKeyDtoSchema,
|
|
715
|
+
credentialRedactionValues,
|
|
715
716
|
deduplicateResearchQueries,
|
|
716
717
|
deliveryFailed,
|
|
717
718
|
deltaPercent,
|
|
@@ -1138,6 +1139,7 @@ import {
|
|
|
1138
1139
|
recommendationBriefDtoSchema,
|
|
1139
1140
|
recommendationExplainRequestSchema,
|
|
1140
1141
|
recommendationExplanationDtoSchema,
|
|
1142
|
+
redactKnownSecrets,
|
|
1141
1143
|
redactLogString,
|
|
1142
1144
|
referralAssessmentQuerySchema,
|
|
1143
1145
|
referralAssessmentSchema,
|
|
@@ -1388,7 +1390,7 @@ import {
|
|
|
1388
1390
|
wordpressSchemaDeployResultDtoSchema,
|
|
1389
1391
|
wordpressSchemaStatusResultDtoSchema,
|
|
1390
1392
|
wordpressStatusDtoSchema
|
|
1391
|
-
} from "./chunk-
|
|
1393
|
+
} from "./chunk-VOK62VGC.js";
|
|
1392
1394
|
|
|
1393
1395
|
// ../api-routes/src/user-session.ts
|
|
1394
1396
|
import crypto2 from "crypto";
|
|
@@ -70861,7 +70863,40 @@ async function backlinksRoutes(app, opts) {
|
|
|
70861
70863
|
import crypto62 from "crypto";
|
|
70862
70864
|
import { isIP as isIP3 } from "net";
|
|
70863
70865
|
import { isDeepStrictEqual } from "util";
|
|
70864
|
-
import { and as
|
|
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
|
+
}
|
|
70865
70900
|
|
|
70866
70901
|
// ../api-routes/src/traffic-limits.ts
|
|
70867
70902
|
var VERCEL_MAX_SYNC_WINDOW_MS = 24 * 60 * 6e4;
|
|
@@ -71552,6 +71587,23 @@ function trimRequired2(name, value) {
|
|
|
71552
71587
|
}
|
|
71553
71588
|
return trimmed;
|
|
71554
71589
|
}
|
|
71590
|
+
function assertSingleLineToken(token) {
|
|
71591
|
+
if (/[\s\u0000-\u001F\u007F]/.test(token)) {
|
|
71592
|
+
throw new VercelLogsApiError(
|
|
71593
|
+
"The Vercel token must be a single line with no spaces. Reconnect the source with the token alone.",
|
|
71594
|
+
400
|
|
71595
|
+
);
|
|
71596
|
+
}
|
|
71597
|
+
}
|
|
71598
|
+
function transportFailure(error) {
|
|
71599
|
+
const name = error instanceof Error ? error.name : "";
|
|
71600
|
+
if (name === "TimeoutError" || name === "AbortError") {
|
|
71601
|
+
return new VercelLogsApiError("Vercel request-logs request timed out", 504);
|
|
71602
|
+
}
|
|
71603
|
+
const cause = error instanceof Error ? error.cause : void 0;
|
|
71604
|
+
const code = typeof cause?.code === "string" && /^[A-Z][A-Z0-9_]{1,40}$/.test(cause.code) ? cause.code : null;
|
|
71605
|
+
return new VercelLogsApiError(`Vercel request-logs request failed${code ? ` (${code})` : ""}`, 503);
|
|
71606
|
+
}
|
|
71555
71607
|
function normalizeMaxPages3(maxPages) {
|
|
71556
71608
|
if (maxPages === void 0) return DEFAULT_MAX_PAGES3;
|
|
71557
71609
|
if (!Number.isInteger(maxPages) || maxPages < 1) {
|
|
@@ -71591,6 +71643,7 @@ async function withVercelRetry(attempt, maxRetries, initialDelayMs) {
|
|
|
71591
71643
|
}
|
|
71592
71644
|
async function listVercelTrafficEvents(options) {
|
|
71593
71645
|
const token = trimRequired2("token", options.token);
|
|
71646
|
+
assertSingleLineToken(token);
|
|
71594
71647
|
const projectId = trimRequired2("projectId", options.projectId);
|
|
71595
71648
|
const teamId = trimRequired2("teamId", options.teamId);
|
|
71596
71649
|
const environment = options.environment ?? DEFAULT_ENVIRONMENT;
|
|
@@ -71614,14 +71667,19 @@ async function listVercelTrafficEvents(options) {
|
|
|
71614
71667
|
url.searchParams.set("endDate", endDate);
|
|
71615
71668
|
url.searchParams.set("environment", environment);
|
|
71616
71669
|
const body = await withVercelRetry(async () => {
|
|
71617
|
-
|
|
71618
|
-
|
|
71619
|
-
|
|
71620
|
-
|
|
71621
|
-
|
|
71622
|
-
|
|
71623
|
-
|
|
71624
|
-
|
|
71670
|
+
let response;
|
|
71671
|
+
try {
|
|
71672
|
+
response = await fetch(url, {
|
|
71673
|
+
method: "GET",
|
|
71674
|
+
headers: {
|
|
71675
|
+
Authorization: `Bearer ${token}`,
|
|
71676
|
+
Accept: "application/json"
|
|
71677
|
+
},
|
|
71678
|
+
signal: AbortSignal.timeout(timeoutMs)
|
|
71679
|
+
});
|
|
71680
|
+
} catch (error) {
|
|
71681
|
+
throw transportFailure(error);
|
|
71682
|
+
}
|
|
71625
71683
|
if (!response.ok) {
|
|
71626
71684
|
const errorBody = await readErrorBody3(response);
|
|
71627
71685
|
const retryAfterSeconds2 = parseRetryAfter2(response.headers.get("retry-after"));
|
|
@@ -72204,7 +72262,7 @@ async function ackCloudflareQueueMessages(client, options) {
|
|
|
72204
72262
|
}
|
|
72205
72263
|
|
|
72206
72264
|
// ../api-routes/src/traffic-sync-lease.ts
|
|
72207
|
-
import { and as
|
|
72265
|
+
import { and as and91, eq as eq105, isNull as isNull17, lte as lte26, or as or19 } from "drizzle-orm";
|
|
72208
72266
|
function leaseExpiresAt(now, ttlMs) {
|
|
72209
72267
|
const nowMs = Date.parse(now);
|
|
72210
72268
|
if (!Number.isFinite(nowMs)) throw new RangeError("Traffic sync lease now must be an ISO instant");
|
|
@@ -72217,12 +72275,12 @@ function tryClaimTrafficSyncLease(input) {
|
|
|
72217
72275
|
const changed = tx.update(trafficSources).set({
|
|
72218
72276
|
syncLeaseOwner: input.owner,
|
|
72219
72277
|
syncLeaseExpiresAt: expiresAt
|
|
72220
|
-
}).where(
|
|
72221
|
-
|
|
72278
|
+
}).where(and91(
|
|
72279
|
+
eq105(trafficSources.id, input.sourceId),
|
|
72222
72280
|
or19(
|
|
72223
72281
|
isNull17(trafficSources.syncLeaseOwner),
|
|
72224
72282
|
lte26(trafficSources.syncLeaseExpiresAt, input.now),
|
|
72225
|
-
|
|
72283
|
+
eq105(trafficSources.syncLeaseOwner, input.owner)
|
|
72226
72284
|
)
|
|
72227
72285
|
)).run();
|
|
72228
72286
|
return changed.changes === 1;
|
|
@@ -72233,9 +72291,9 @@ function releaseTrafficSyncLease(input) {
|
|
|
72233
72291
|
const changed = tx.update(trafficSources).set({
|
|
72234
72292
|
syncLeaseOwner: null,
|
|
72235
72293
|
syncLeaseExpiresAt: null
|
|
72236
|
-
}).where(
|
|
72237
|
-
|
|
72238
|
-
|
|
72294
|
+
}).where(and91(
|
|
72295
|
+
eq105(trafficSources.id, input.sourceId),
|
|
72296
|
+
eq105(trafficSources.syncLeaseOwner, input.owner)
|
|
72239
72297
|
)).run();
|
|
72240
72298
|
return changed.changes === 1;
|
|
72241
72299
|
}, { behavior: "immediate" });
|
|
@@ -72243,7 +72301,7 @@ function releaseTrafficSyncLease(input) {
|
|
|
72243
72301
|
|
|
72244
72302
|
// ../api-routes/src/traffic-events-read.ts
|
|
72245
72303
|
import crypto61 from "crypto";
|
|
72246
|
-
import { desc as desc48, eq as
|
|
72304
|
+
import { desc as desc48, eq as eq106, or as or20, sql as sql47 } from "drizzle-orm";
|
|
72247
72305
|
function keyColumns(table, fields) {
|
|
72248
72306
|
return { keyFields: fields, keys: fields.map((field) => table[field]) };
|
|
72249
72307
|
}
|
|
@@ -72294,7 +72352,7 @@ function trafficEventPathPredicate(column, path8) {
|
|
|
72294
72352
|
function trafficEventFilterPredicates(table, filters) {
|
|
72295
72353
|
const predicates = [];
|
|
72296
72354
|
if (filters.path !== null) predicates.push(trafficEventPathPredicate(table.path, filters.path));
|
|
72297
|
-
if (filters.agent !== null) predicates.push(
|
|
72355
|
+
if (filters.agent !== null) predicates.push(eq106(table.agent, filters.agent));
|
|
72298
72356
|
return predicates;
|
|
72299
72357
|
}
|
|
72300
72358
|
function optionalQueryString(value, name) {
|
|
@@ -72484,14 +72542,14 @@ async function loadQueueReceiptPolicy(db, sourceId, readRetentionSeconds, warn2)
|
|
|
72484
72542
|
if (liveTtlMs === null) return { ttlMsAt: () => CLOUDFLARE_QUEUE_RECEIPT_TTL_MS };
|
|
72485
72543
|
const ttlMs = liveTtlMs;
|
|
72486
72544
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
72487
|
-
const alive =
|
|
72545
|
+
const alive = and92(eq107(trafficEventReceipts.sourceId, sourceId), gt8(trafficEventReceipts.expiresAt, now));
|
|
72488
72546
|
const lifetimeMs = sql48`(julianday(${trafficEventReceipts.expiresAt}) - julianday(${trafficEventReceipts.receivedAt})) * ${DAY_MS5}`;
|
|
72489
72547
|
const shortest = db.select({ ms: sql48`min(${lifetimeMs})` }).from(trafficEventReceipts).where(alive).get()?.ms ?? null;
|
|
72490
72548
|
if (shortest !== null && shortest < ttlMs - 1e3) {
|
|
72491
72549
|
const extended = sql48`strftime('%Y-%m-%dT%H:%M:%fZ', julianday(${trafficEventReceipts.receivedAt}) + ${ttlMs / DAY_MS5})`;
|
|
72492
|
-
db.update(trafficEventReceipts).set({ expiresAt: extended }).where(
|
|
72550
|
+
db.update(trafficEventReceipts).set({ expiresAt: extended }).where(and92(alive, lt20(trafficEventReceipts.expiresAt, extended))).run();
|
|
72493
72551
|
}
|
|
72494
|
-
const floorExpiry = db.select({ at: sql48`max(${trafficEventReceipts.expiresAt})` }).from(trafficEventReceipts).where(
|
|
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;
|
|
72495
72553
|
const floorMs = floorExpiry ? Date.parse(floorExpiry) : 0;
|
|
72496
72554
|
return { ttlMsAt: (receivedAt) => Math.max(ttlMs, floorMs - Date.parse(receivedAt)) };
|
|
72497
72555
|
}
|
|
@@ -72546,7 +72604,7 @@ function cloudflareIngestRateLimitKey(request, store, db) {
|
|
|
72546
72604
|
const authenticated = authenticateCloudflareIngest(request, store);
|
|
72547
72605
|
const params = request.params;
|
|
72548
72606
|
if (authenticated && typeof params.name === "string" && authenticated.credential.projectName === params.name) {
|
|
72549
|
-
const source = db.select().from(trafficSources).where(
|
|
72607
|
+
const source = db.select().from(trafficSources).where(eq107(trafficSources.id, authenticated.credential.sourceId)).get();
|
|
72550
72608
|
if (source && source.sourceType === TrafficSourceTypes.cloudflare && source.status === TrafficSourceStatuses.connected && parseDirectPushCloudflareSourceConfig(source.configJson) && timingSafeEqualHex(authenticated.bearerHash, source.ingestTokenHash)) {
|
|
72551
72609
|
return `cloudflare-source:${authenticated.credential.sourceId}`;
|
|
72552
72610
|
}
|
|
@@ -72772,6 +72830,14 @@ function aiUserFetchVerificationProvenance(db, projectId, events) {
|
|
|
72772
72830
|
)`).orderBy(aiUserFetchVerificationManifestsHourly.manifestId).all();
|
|
72773
72831
|
return buildVerificationProvenance(events, rows);
|
|
72774
72832
|
}
|
|
72833
|
+
function wordpressRedactionValues(username, applicationPassword) {
|
|
72834
|
+
return [
|
|
72835
|
+
...credentialRedactionValues(applicationPassword),
|
|
72836
|
+
// WordPress accepts the password with or without its group spaces.
|
|
72837
|
+
applicationPassword.replace(/\s+/g, ""),
|
|
72838
|
+
Buffer.from(`${username.trim()}:${applicationPassword.trim()}`, "utf8").toString("base64")
|
|
72839
|
+
];
|
|
72840
|
+
}
|
|
72775
72841
|
function parseSourceConfig(row) {
|
|
72776
72842
|
return row.configJson;
|
|
72777
72843
|
}
|
|
@@ -72806,7 +72872,7 @@ async function defaultResolveAccessToken(record3) {
|
|
|
72806
72872
|
);
|
|
72807
72873
|
}
|
|
72808
72874
|
function hasConnectedTrafficSourceSibling(db, projectId, sourceId) {
|
|
72809
|
-
return db.select().from(trafficSources).where(
|
|
72875
|
+
return db.select().from(trafficSources).where(eq107(trafficSources.projectId, projectId)).all().some((row) => row.id !== sourceId && row.status === TrafficSourceStatuses.connected);
|
|
72810
72876
|
}
|
|
72811
72877
|
function isAuthoritativeTrafficSource(db, source) {
|
|
72812
72878
|
return (source.status === TrafficSourceStatuses.connected || source.status === TrafficSourceStatuses.error) && !hasConnectedTrafficSourceSibling(db, source.projectId, source.id);
|
|
@@ -72833,13 +72899,13 @@ function wordpressBaseUrlIdentity(value) {
|
|
|
72833
72899
|
}
|
|
72834
72900
|
}
|
|
72835
72901
|
function bindTrafficSyncSchedule(tx, projectId, sourceId, now, createIfMissing = true) {
|
|
72836
|
-
const schedule = tx.select().from(schedules).where(
|
|
72837
|
-
|
|
72838
|
-
|
|
72902
|
+
const schedule = tx.select().from(schedules).where(and92(
|
|
72903
|
+
eq107(schedules.projectId, projectId),
|
|
72904
|
+
eq107(schedules.kind, SchedulableRunKinds["traffic-sync"])
|
|
72839
72905
|
)).get();
|
|
72840
72906
|
if (schedule) {
|
|
72841
72907
|
if (schedule.sourceId === sourceId) return { changed: false, created: false };
|
|
72842
|
-
tx.update(schedules).set({ sourceId, updatedAt: nextScheduleUpdatedAt(schedule.updatedAt, Date.parse(now)) }).where(
|
|
72908
|
+
tx.update(schedules).set({ sourceId, updatedAt: nextScheduleUpdatedAt(schedule.updatedAt, Date.parse(now)) }).where(eq107(schedules.id, schedule.id)).run();
|
|
72843
72909
|
return { changed: true, created: false };
|
|
72844
72910
|
}
|
|
72845
72911
|
if (!createIfMissing) return { changed: false, created: false };
|
|
@@ -72881,7 +72947,7 @@ async function runBackfillTask(options) {
|
|
|
72881
72947
|
};
|
|
72882
72948
|
const renewLease2 = setInterval(() => {
|
|
72883
72949
|
try {
|
|
72884
|
-
const latest = app.db.select().from(trafficSources).where(
|
|
72950
|
+
const latest = app.db.select().from(trafficSources).where(eq107(trafficSources.id, sourceRow2.id)).get();
|
|
72885
72951
|
if (!latest || !isAuthoritativeTrafficSource(app.db, latest) || !isSameTrafficSourceGeneration(latest, sourceRow2)) {
|
|
72886
72952
|
clearInterval(renewLease2);
|
|
72887
72953
|
stopped.abort();
|
|
@@ -72929,10 +72995,10 @@ async function runBackfillTaskHoldingLease(options, signal) {
|
|
|
72929
72995
|
const failedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
72930
72996
|
try {
|
|
72931
72997
|
app.db.transaction((tx) => {
|
|
72932
|
-
tx.update(runs).set({ status: RunStatuses.failed, error: msg, finishedAt: failedAt }).where(
|
|
72933
|
-
const latestSource = tx.select().from(trafficSources).where(
|
|
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();
|
|
72934
73000
|
if (!preserveSourceState && latestSource && isAuthoritativeTrafficSource(tx, latestSource) && isSameBackfillSource(latestSource, sourceRow2, leaseOwner)) {
|
|
72935
|
-
tx.update(trafficSources).set({ status: TrafficSourceStatuses.error, lastError: msg, updatedAt: failedAt }).where(
|
|
73001
|
+
tx.update(trafficSources).set({ status: TrafficSourceStatuses.error, lastError: msg, updatedAt: failedAt }).where(eq107(trafficSources.id, sourceRow2.id)).run();
|
|
72936
73002
|
}
|
|
72937
73003
|
});
|
|
72938
73004
|
} catch {
|
|
@@ -72953,7 +73019,7 @@ async function runBackfillTaskHoldingLease(options, signal) {
|
|
|
72953
73019
|
return;
|
|
72954
73020
|
}
|
|
72955
73021
|
markFailed(
|
|
72956
|
-
`${pullErrorPrefix}: ${describeError(e)}`,
|
|
73022
|
+
`${pullErrorPrefix}: ${redactKnownSecrets(describeError(e), options.pullSecrets ?? [])}`,
|
|
72957
73023
|
e instanceof VercelRetentionClampError
|
|
72958
73024
|
);
|
|
72959
73025
|
reportBackfill(failedOutcome(e, e instanceof VercelRetentionClampError ? OutcomeReasonCodes.NO_DATA : void 0));
|
|
@@ -72964,7 +73030,7 @@ async function runBackfillTaskHoldingLease(options, signal) {
|
|
|
72964
73030
|
let emptyOutcome;
|
|
72965
73031
|
try {
|
|
72966
73032
|
const completed = app.db.transaction((tx) => {
|
|
72967
|
-
const latestSource = tx.select().from(trafficSources).where(
|
|
73033
|
+
const latestSource = tx.select().from(trafficSources).where(eq107(trafficSources.id, sourceRow2.id)).get();
|
|
72968
73034
|
const stillAuthoritative = latestSource && isAuthoritativeTrafficSource(tx, latestSource) && isSameBackfillSource(latestSource, sourceRow2, leaseOwner);
|
|
72969
73035
|
if (stillAuthoritative) {
|
|
72970
73036
|
enforceRawEventSampleRetention(tx, sourceRow2.id, finishedAt2);
|
|
@@ -72973,7 +73039,7 @@ async function runBackfillTaskHoldingLease(options, signal) {
|
|
|
72973
73039
|
status: RunStatuses.failed,
|
|
72974
73040
|
error: "Traffic source was deactivated or reconfigured during backfill",
|
|
72975
73041
|
finishedAt: finishedAt2
|
|
72976
|
-
}).where(
|
|
73042
|
+
}).where(eq107(runs.id, runId)).run();
|
|
72977
73043
|
return Boolean(stillAuthoritative);
|
|
72978
73044
|
});
|
|
72979
73045
|
emptyOutcome = completed ? { status: OutcomeStatuses.skipped, reasonCode: OutcomeReasonCodes.NO_DATA } : { status: OutcomeStatuses.failed, reasonCode: OutcomeReasonCodes.NOT_CONNECTED };
|
|
@@ -73005,13 +73071,13 @@ async function runBackfillTaskHoldingLease(options, signal) {
|
|
|
73005
73071
|
const nextLastSyncedAt = Math.max(currentLastSyncedMs, windowEnd.getTime()) === windowEnd.getTime() ? windowEndIso : sourceRow2.lastSyncedAt;
|
|
73006
73072
|
try {
|
|
73007
73073
|
const commitOutcome = app.db.transaction((tx) => {
|
|
73008
|
-
const latestSource = tx.select().from(trafficSources).where(
|
|
73074
|
+
const latestSource = tx.select().from(trafficSources).where(eq107(trafficSources.id, sourceRow2.id)).get();
|
|
73009
73075
|
if (latestSource?.sourceType === TrafficSourceTypes.wordpress) {
|
|
73010
73076
|
tx.update(runs).set({
|
|
73011
73077
|
status: RunStatuses.failed,
|
|
73012
73078
|
error: "Generic WordPress replace backfill is unavailable because retained coverage is unproven.",
|
|
73013
73079
|
finishedAt
|
|
73014
|
-
}).where(
|
|
73080
|
+
}).where(eq107(runs.id, runId)).run();
|
|
73015
73081
|
return "wordpress-backfill-unsupported";
|
|
73016
73082
|
}
|
|
73017
73083
|
if (!latestSource || !isAuthoritativeTrafficSource(tx, latestSource) || !isSameBackfillSource(latestSource, sourceRow2, leaseOwner)) {
|
|
@@ -73019,7 +73085,7 @@ async function runBackfillTaskHoldingLease(options, signal) {
|
|
|
73019
73085
|
status: RunStatuses.failed,
|
|
73020
73086
|
error: "Traffic source was deactivated or reconfigured during backfill",
|
|
73021
73087
|
finishedAt
|
|
73022
|
-
}).where(
|
|
73088
|
+
}).where(eq107(runs.id, runId)).run();
|
|
73023
73089
|
return "source-inactive";
|
|
73024
73090
|
}
|
|
73025
73091
|
const rawSampleCutoff = enforceRawEventSampleRetention(
|
|
@@ -73028,37 +73094,37 @@ async function runBackfillTaskHoldingLease(options, signal) {
|
|
|
73028
73094
|
finishedAt
|
|
73029
73095
|
);
|
|
73030
73096
|
tx.delete(crawlerEventsHourly).where(
|
|
73031
|
-
|
|
73032
|
-
|
|
73097
|
+
and92(
|
|
73098
|
+
eq107(crawlerEventsHourly.sourceId, sourceRow2.id),
|
|
73033
73099
|
gte27(crawlerEventsHourly.tsHour, windowStartIso),
|
|
73034
73100
|
lte27(crawlerEventsHourly.tsHour, windowEndIso)
|
|
73035
73101
|
)
|
|
73036
73102
|
).run();
|
|
73037
73103
|
tx.delete(aiUserFetchEventsHourly).where(
|
|
73038
|
-
|
|
73039
|
-
|
|
73104
|
+
and92(
|
|
73105
|
+
eq107(aiUserFetchEventsHourly.sourceId, sourceRow2.id),
|
|
73040
73106
|
gte27(aiUserFetchEventsHourly.tsHour, windowStartIso),
|
|
73041
73107
|
lte27(aiUserFetchEventsHourly.tsHour, windowEndIso)
|
|
73042
73108
|
)
|
|
73043
73109
|
).run();
|
|
73044
73110
|
clearLikelyFakeAgentHits(tx, { sourceId: sourceRow2.id, windowStart: windowStartIso, windowEnd: windowEndIso });
|
|
73045
73111
|
tx.delete(aiReferralEventsHourly).where(
|
|
73046
|
-
|
|
73047
|
-
|
|
73112
|
+
and92(
|
|
73113
|
+
eq107(aiReferralEventsHourly.sourceId, sourceRow2.id),
|
|
73048
73114
|
gte27(aiReferralEventsHourly.tsHour, windowStartIso),
|
|
73049
73115
|
lte27(aiReferralEventsHourly.tsHour, windowEndIso)
|
|
73050
73116
|
)
|
|
73051
73117
|
).run();
|
|
73052
73118
|
tx.delete(rawEventSamples).where(
|
|
73053
|
-
|
|
73054
|
-
|
|
73119
|
+
and92(
|
|
73120
|
+
eq107(rawEventSamples.sourceId, sourceRow2.id),
|
|
73055
73121
|
gte27(rawEventSamples.ts, windowStartIso),
|
|
73056
73122
|
lte27(rawEventSamples.ts, windowEndIso)
|
|
73057
73123
|
)
|
|
73058
73124
|
).run();
|
|
73059
73125
|
tx.delete(unrecognizedAgentEventsHourly).where(
|
|
73060
|
-
|
|
73061
|
-
|
|
73126
|
+
and92(
|
|
73127
|
+
eq107(unrecognizedAgentEventsHourly.sourceId, sourceRow2.id),
|
|
73062
73128
|
gte27(unrecognizedAgentEventsHourly.tsHour, windowStartIso),
|
|
73063
73129
|
lte27(unrecognizedAgentEventsHourly.tsHour, windowEndIso)
|
|
73064
73130
|
)
|
|
@@ -73266,8 +73332,8 @@ async function runBackfillTaskHoldingLease(options, signal) {
|
|
|
73266
73332
|
FROM _migrations WHERE version = 207
|
|
73267
73333
|
`);
|
|
73268
73334
|
if (ruleChange?.appliedAt) {
|
|
73269
|
-
const olderReferral = tx.select({ sourceId: aiReferralEventsHourly.sourceId }).from(aiReferralEventsHourly).where(
|
|
73270
|
-
|
|
73335
|
+
const olderReferral = tx.select({ sourceId: aiReferralEventsHourly.sourceId }).from(aiReferralEventsHourly).where(and92(
|
|
73336
|
+
eq107(aiReferralEventsHourly.sourceId, sourceRow2.id),
|
|
73271
73337
|
lt20(aiReferralEventsHourly.createdAt, ruleChange.appliedAt)
|
|
73272
73338
|
)).limit(1).get();
|
|
73273
73339
|
if (!olderReferral) olderCountUntil = null;
|
|
@@ -73288,8 +73354,8 @@ async function runBackfillTaskHoldingLease(options, signal) {
|
|
|
73288
73354
|
aiUserFetchOlderCountUntil: userFetchOlderCountUntil,
|
|
73289
73355
|
...skipRecovered ? { skippedThroughAt: null } : {},
|
|
73290
73356
|
updatedAt: finishedAt
|
|
73291
|
-
}).where(
|
|
73292
|
-
tx.update(runs).set({ status: RunStatuses.completed, finishedAt }).where(
|
|
73357
|
+
}).where(eq107(trafficSources.id, sourceRow2.id)).run();
|
|
73358
|
+
tx.update(runs).set({ status: RunStatuses.completed, finishedAt }).where(eq107(runs.id, runId)).run();
|
|
73293
73359
|
return "committed";
|
|
73294
73360
|
});
|
|
73295
73361
|
reportBackfill(commitOutcome === "committed" ? {
|
|
@@ -73471,7 +73537,7 @@ async function trafficRoutes(app, opts) {
|
|
|
73471
73537
|
}
|
|
73472
73538
|
const fallbackName = displayName ?? `Cloud Run \xB7 ${gcpProjectId}${serviceName ? ` / ${serviceName}` : ""}`;
|
|
73473
73539
|
const { sourceRow: sourceRow2, scheduleChanged } = app.db.transaction((tx) => {
|
|
73474
|
-
const activeSource = tx.select().from(trafficSources).where(
|
|
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);
|
|
73475
73541
|
const matchesExistingSource = activeSource && hasCloudRunCredentialForSource(existing, project.name, activeSource);
|
|
73476
73542
|
const sameOwner = existing?.projectId === project.id || matchesExistingSource;
|
|
73477
73543
|
let credentialToSave = uploadedCredential;
|
|
@@ -73494,7 +73560,7 @@ async function trafficRoutes(app, opts) {
|
|
|
73494
73560
|
const sourceId = sameSource?.id ?? crypto62.randomUUID();
|
|
73495
73561
|
if (!uploadedCredential && sameSource && matchesExistingSource) {
|
|
73496
73562
|
if (displayName !== void 0 && displayName !== sameSource.displayName) {
|
|
73497
|
-
tx.update(trafficSources).set({ displayName }).where(
|
|
73563
|
+
tx.update(trafficSources).set({ displayName }).where(eq107(trafficSources.id, sourceId)).run();
|
|
73498
73564
|
writeAuditLog(tx, {
|
|
73499
73565
|
projectId: project.id,
|
|
73500
73566
|
actor: "api",
|
|
@@ -73517,10 +73583,10 @@ async function trafficRoutes(app, opts) {
|
|
|
73517
73583
|
lastError: null,
|
|
73518
73584
|
configJson: config,
|
|
73519
73585
|
updatedAt: now
|
|
73520
|
-
}).where(
|
|
73586
|
+
}).where(eq107(trafficSources.id, sourceId)).run();
|
|
73521
73587
|
} else {
|
|
73522
73588
|
if (activeSource) {
|
|
73523
|
-
tx.update(trafficSources).set({ status: TrafficSourceStatuses.archived, archivedAt: now, updatedAt: now }).where(
|
|
73589
|
+
tx.update(trafficSources).set({ status: TrafficSourceStatuses.archived, archivedAt: now, updatedAt: now }).where(eq107(trafficSources.id, activeSource.id)).run();
|
|
73524
73590
|
}
|
|
73525
73591
|
tx.insert(trafficSources).values({
|
|
73526
73592
|
id: sourceId,
|
|
@@ -73547,7 +73613,7 @@ async function trafficRoutes(app, opts) {
|
|
|
73547
73613
|
});
|
|
73548
73614
|
if (credentialToSave) store.upsertConnection(credentialToSave);
|
|
73549
73615
|
return {
|
|
73550
|
-
sourceRow: tx.select().from(trafficSources).where(
|
|
73616
|
+
sourceRow: tx.select().from(trafficSources).where(eq107(trafficSources.id, sourceId)).get(),
|
|
73551
73617
|
scheduleChanged: scheduleBinding.changed
|
|
73552
73618
|
};
|
|
73553
73619
|
}, { behavior: "immediate" });
|
|
@@ -73579,13 +73645,15 @@ async function trafficRoutes(app, opts) {
|
|
|
73579
73645
|
});
|
|
73580
73646
|
} catch (e) {
|
|
73581
73647
|
attempt.failed(e, e instanceof EgressRefusedError ? "BLOCKED_UNSAFE_URL" : e instanceof EgressFailedError ? "NETWORK" : void 0);
|
|
73648
|
+
const secrets = wordpressRedactionValues(username, applicationPassword);
|
|
73582
73649
|
if (e instanceof WordpressTrafficApiError) {
|
|
73583
|
-
throw providerError(
|
|
73584
|
-
`WordPress traffic probe failed (HTTP ${e.status}): ${e.message}${e.body ? ` \u2014 ${e.body}` : ""}
|
|
73585
|
-
|
|
73650
|
+
throw providerError(redactKnownSecrets(
|
|
73651
|
+
`WordPress traffic probe failed (HTTP ${e.status}): ${e.message}${e.body ? ` \u2014 ${e.body}` : ""}`,
|
|
73652
|
+
secrets
|
|
73653
|
+
));
|
|
73586
73654
|
}
|
|
73587
73655
|
if (e instanceof EgressRefusedError && !e.redirected) throw validationError(`WordPress baseUrl rejected: ${e.message}`);
|
|
73588
|
-
const msg = describeError(e);
|
|
73656
|
+
const msg = redactKnownSecrets(describeError(e), secrets);
|
|
73589
73657
|
throw providerError(`WordPress traffic probe failed: ${msg}`);
|
|
73590
73658
|
}
|
|
73591
73659
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
@@ -73602,7 +73670,7 @@ async function trafficRoutes(app, opts) {
|
|
|
73602
73670
|
const config = { baseUrl, username };
|
|
73603
73671
|
const fallbackName = displayName ?? `WordPress \xB7 ${new URL(baseUrl).host}`;
|
|
73604
73672
|
const { sourceRow: sourceRow2, scheduleChanged } = app.db.transaction((tx) => {
|
|
73605
|
-
const activeSource = tx.select().from(trafficSources).where(
|
|
73673
|
+
const activeSource = tx.select().from(trafficSources).where(eq107(trafficSources.projectId, project.id)).all().find((row) => row.sourceType === TrafficSourceTypes.wordpress && row.status !== TrafficSourceStatuses.archived);
|
|
73606
73674
|
const endpointChanged = activeSource !== void 0 && wordpressBaseUrlIdentity(activeSource.configJson.baseUrl) !== wordpressBaseUrlIdentity(baseUrl);
|
|
73607
73675
|
const sourceId = endpointChanged ? crypto62.randomUUID() : activeSource?.id ?? crypto62.randomUUID();
|
|
73608
73676
|
const sourceStatus = trafficConnectStatus(tx, project.id, activeSource);
|
|
@@ -73613,14 +73681,14 @@ async function trafficRoutes(app, opts) {
|
|
|
73613
73681
|
lastError: null,
|
|
73614
73682
|
configJson: config,
|
|
73615
73683
|
updatedAt: now
|
|
73616
|
-
}).where(
|
|
73684
|
+
}).where(eq107(trafficSources.id, sourceId)).run();
|
|
73617
73685
|
} else {
|
|
73618
73686
|
if (activeSource) {
|
|
73619
73687
|
tx.update(trafficSources).set({
|
|
73620
73688
|
status: TrafficSourceStatuses.archived,
|
|
73621
73689
|
archivedAt: now,
|
|
73622
73690
|
updatedAt: now
|
|
73623
|
-
}).where(
|
|
73691
|
+
}).where(eq107(trafficSources.id, activeSource.id)).run();
|
|
73624
73692
|
}
|
|
73625
73693
|
tx.insert(trafficSources).values({
|
|
73626
73694
|
id: sourceId,
|
|
@@ -73646,7 +73714,7 @@ async function trafficRoutes(app, opts) {
|
|
|
73646
73714
|
entityId: sourceId
|
|
73647
73715
|
});
|
|
73648
73716
|
return {
|
|
73649
|
-
sourceRow: tx.select().from(trafficSources).where(
|
|
73717
|
+
sourceRow: tx.select().from(trafficSources).where(eq107(trafficSources.id, sourceId)).get(),
|
|
73650
73718
|
scheduleChanged: scheduleBinding.changed
|
|
73651
73719
|
};
|
|
73652
73720
|
}, { behavior: "immediate" });
|
|
@@ -73680,12 +73748,14 @@ async function trafficRoutes(app, opts) {
|
|
|
73680
73748
|
});
|
|
73681
73749
|
} catch (e) {
|
|
73682
73750
|
attempt.failed(e);
|
|
73751
|
+
const secrets = credentialRedactionValues(token);
|
|
73683
73752
|
if (e instanceof VercelLogsApiError) {
|
|
73684
|
-
throw providerError(
|
|
73685
|
-
`Vercel traffic probe failed (HTTP ${e.status}): ${e.message}${e.body ? ` \u2014 ${e.body}` : ""}
|
|
73686
|
-
|
|
73753
|
+
throw providerError(redactKnownSecrets(
|
|
73754
|
+
`Vercel traffic probe failed (HTTP ${e.status}): ${e.message}${e.body ? ` \u2014 ${e.body}` : ""}`,
|
|
73755
|
+
secrets
|
|
73756
|
+
));
|
|
73687
73757
|
}
|
|
73688
|
-
const msg = describeError(e);
|
|
73758
|
+
const msg = redactKnownSecrets(describeError(e), secrets);
|
|
73689
73759
|
throw providerError(`Vercel traffic probe failed: ${msg}`);
|
|
73690
73760
|
}
|
|
73691
73761
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
@@ -73703,7 +73773,7 @@ async function trafficRoutes(app, opts) {
|
|
|
73703
73773
|
const config = { projectId, teamId, environment };
|
|
73704
73774
|
const fallbackName = displayName ?? `Vercel \xB7 ${projectId}`;
|
|
73705
73775
|
const { sourceRow: sourceRow2, scheduleChanged } = app.db.transaction((tx) => {
|
|
73706
|
-
const activeSource = tx.select().from(trafficSources).where(
|
|
73776
|
+
const activeSource = tx.select().from(trafficSources).where(eq107(trafficSources.projectId, project.id)).all().find((row2) => row2.sourceType === TrafficSourceTypes.vercel && row2.status !== TrafficSourceStatuses.archived);
|
|
73707
73777
|
const sourceStatus = trafficConnectStatus(tx, project.id, activeSource);
|
|
73708
73778
|
let row;
|
|
73709
73779
|
if (activeSource) {
|
|
@@ -73713,8 +73783,8 @@ async function trafficRoutes(app, opts) {
|
|
|
73713
73783
|
lastError: null,
|
|
73714
73784
|
configJson: config,
|
|
73715
73785
|
updatedAt: now
|
|
73716
|
-
}).where(
|
|
73717
|
-
row = tx.select().from(trafficSources).where(
|
|
73786
|
+
}).where(eq107(trafficSources.id, activeSource.id)).run();
|
|
73787
|
+
row = tx.select().from(trafficSources).where(eq107(trafficSources.id, activeSource.id)).get();
|
|
73718
73788
|
} else {
|
|
73719
73789
|
const newId = crypto62.randomUUID();
|
|
73720
73790
|
tx.insert(trafficSources).values({
|
|
@@ -73739,7 +73809,7 @@ async function trafficRoutes(app, opts) {
|
|
|
73739
73809
|
createdAt: now,
|
|
73740
73810
|
updatedAt: now
|
|
73741
73811
|
}).run();
|
|
73742
|
-
row = tx.select().from(trafficSources).where(
|
|
73812
|
+
row = tx.select().from(trafficSources).where(eq107(trafficSources.id, newId)).get();
|
|
73743
73813
|
}
|
|
73744
73814
|
const scheduleBinding = sourceStatus === TrafficSourceStatuses.connected ? bindTrafficSyncSchedule(tx, project.id, row.id, now) : { changed: false, created: false };
|
|
73745
73815
|
writeAuditLog(tx, {
|
|
@@ -73783,7 +73853,7 @@ async function trafficRoutes(app, opts) {
|
|
|
73783
73853
|
const { displayName: displayName2, zoneId: zoneId2, accountId: accountId2, queueId, queueName, retentionSeconds, apiToken } = parsed.data;
|
|
73784
73854
|
const workerRouteHost2 = resolveCloudflareWorkerRouteHost(project.canonicalDomain);
|
|
73785
73855
|
const now2 = (/* @__PURE__ */ new Date()).toISOString();
|
|
73786
|
-
const cloudflareSources = app.db.select().from(trafficSources).where(
|
|
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);
|
|
73787
73857
|
const sameModeSource = cloudflareSources.find((row) => parseQueuePullCloudflareSourceConfig(row.configJson));
|
|
73788
73858
|
if (sameModeSource) attempt.update({ action: "reauth" });
|
|
73789
73859
|
const sourceId2 = sameModeSource?.id ?? crypto62.randomUUID();
|
|
@@ -73837,7 +73907,7 @@ async function trafficRoutes(app, opts) {
|
|
|
73837
73907
|
let scheduleChanged = false;
|
|
73838
73908
|
try {
|
|
73839
73909
|
const result = app.db.transaction((tx) => {
|
|
73840
|
-
const currentSameModeSource = tx.select().from(trafficSources).where(
|
|
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);
|
|
73841
73911
|
if ((currentSameModeSource?.id ?? null) !== (sameModeSource?.id ?? null)) {
|
|
73842
73912
|
throw operationInProgress("Cloudflare Queue source changed during connect; retry");
|
|
73843
73913
|
}
|
|
@@ -73855,7 +73925,7 @@ async function trafficRoutes(app, opts) {
|
|
|
73855
73925
|
queueBacklogObservedAt: null
|
|
73856
73926
|
} : {},
|
|
73857
73927
|
updatedAt: now2
|
|
73858
|
-
}).where(
|
|
73928
|
+
}).where(eq107(trafficSources.id, sourceId2)).run();
|
|
73859
73929
|
} else {
|
|
73860
73930
|
tx.insert(trafficSources).values({
|
|
73861
73931
|
id: sourceId2,
|
|
@@ -73875,7 +73945,7 @@ async function trafficRoutes(app, opts) {
|
|
|
73875
73945
|
}
|
|
73876
73946
|
const changed = status === TrafficSourceStatuses.connected ? bindTrafficSyncSchedule(tx, project.id, sourceId2, now2).changed : false;
|
|
73877
73947
|
return {
|
|
73878
|
-
row: tx.select().from(trafficSources).where(
|
|
73948
|
+
row: tx.select().from(trafficSources).where(eq107(trafficSources.id, sourceId2)).get(),
|
|
73879
73949
|
scheduleChanged: changed
|
|
73880
73950
|
};
|
|
73881
73951
|
}, { behavior: "immediate" });
|
|
@@ -73925,7 +73995,7 @@ async function trafficRoutes(app, opts) {
|
|
|
73925
73995
|
const { deliveryMode, displayName, zoneId, accountId } = parsed.data;
|
|
73926
73996
|
const workerRouteHost = resolveCloudflareWorkerRouteHost(project.canonicalDomain);
|
|
73927
73997
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
73928
|
-
const activeSource = app.db.select().from(trafficSources).where(
|
|
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);
|
|
73929
73999
|
if (activeSource) attempt.update({ action: "reauth" });
|
|
73930
74000
|
const sourceId = activeSource?.id ?? crypto62.randomUUID();
|
|
73931
74001
|
const parsedActiveConfig = activeSource ? parseDirectPushCloudflareSourceConfig(activeSource.configJson) : null;
|
|
@@ -73993,7 +74063,7 @@ async function trafficRoutes(app, opts) {
|
|
|
73993
74063
|
let scheduleRemoved = false;
|
|
73994
74064
|
try {
|
|
73995
74065
|
const result = app.db.transaction((tx) => {
|
|
73996
|
-
const currentActiveSource = tx.select().from(trafficSources).where(
|
|
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);
|
|
73997
74067
|
if ((currentActiveSource?.id ?? null) !== (activeSource?.id ?? null)) {
|
|
73998
74068
|
throw operationInProgress("Cloudflare direct-push source changed during connect; retry");
|
|
73999
74069
|
}
|
|
@@ -74007,8 +74077,8 @@ async function trafficRoutes(app, opts) {
|
|
|
74007
74077
|
configJson: config,
|
|
74008
74078
|
ingestTokenHash,
|
|
74009
74079
|
updatedAt: now
|
|
74010
|
-
}).where(
|
|
74011
|
-
row = tx.select().from(trafficSources).where(
|
|
74080
|
+
}).where(eq107(trafficSources.id, currentActiveSource.id)).run();
|
|
74081
|
+
row = tx.select().from(trafficSources).where(eq107(trafficSources.id, currentActiveSource.id)).get();
|
|
74012
74082
|
} else {
|
|
74013
74083
|
tx.insert(trafficSources).values({
|
|
74014
74084
|
id: sourceId,
|
|
@@ -74028,16 +74098,16 @@ async function trafficRoutes(app, opts) {
|
|
|
74028
74098
|
createdAt: now,
|
|
74029
74099
|
updatedAt: now
|
|
74030
74100
|
}).run();
|
|
74031
|
-
row = tx.select().from(trafficSources).where(
|
|
74101
|
+
row = tx.select().from(trafficSources).where(eq107(trafficSources.id, sourceId)).get();
|
|
74032
74102
|
}
|
|
74033
74103
|
let removed = false;
|
|
74034
74104
|
if (row.status === TrafficSourceStatuses.connected) {
|
|
74035
|
-
const schedule = tx.select().from(schedules).where(
|
|
74036
|
-
|
|
74037
|
-
|
|
74105
|
+
const schedule = tx.select().from(schedules).where(and92(
|
|
74106
|
+
eq107(schedules.projectId, project.id),
|
|
74107
|
+
eq107(schedules.kind, SchedulableRunKinds["traffic-sync"])
|
|
74038
74108
|
)).get();
|
|
74039
74109
|
if (schedule) {
|
|
74040
|
-
tx.delete(schedules).where(
|
|
74110
|
+
tx.delete(schedules).where(eq107(schedules.id, schedule.id)).run();
|
|
74041
74111
|
removed = true;
|
|
74042
74112
|
}
|
|
74043
74113
|
}
|
|
@@ -74093,47 +74163,47 @@ async function trafficRoutes(app, opts) {
|
|
|
74093
74163
|
};
|
|
74094
74164
|
}));
|
|
74095
74165
|
app.post("/projects/:name/traffic/sources/:id/activate", connectionRoute(app, (request) => {
|
|
74096
|
-
const source = app.db.select({ sourceType: trafficSources.sourceType }).from(trafficSources).where(
|
|
74166
|
+
const source = app.db.select({ sourceType: trafficSources.sourceType }).from(trafficSources).where(eq107(trafficSources.id, request.params.id)).get();
|
|
74097
74167
|
const integration = source ? TRAFFIC_SOURCE_INTEGRATIONS[source.sourceType] : void 0;
|
|
74098
74168
|
return integration ? { integration, action: "select" } : void 0;
|
|
74099
74169
|
}, async (request) => {
|
|
74100
74170
|
const project = resolveProject(app.db, request.params.name);
|
|
74101
74171
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
74102
74172
|
const result = app.db.transaction((tx) => {
|
|
74103
|
-
const target = tx.select().from(trafficSources).where(
|
|
74173
|
+
const target = tx.select().from(trafficSources).where(eq107(trafficSources.id, request.params.id)).get();
|
|
74104
74174
|
if (!target || target.projectId !== project.id || target.status === TrafficSourceStatuses.archived) {
|
|
74105
74175
|
throw notFound("Traffic source", request.params.id);
|
|
74106
74176
|
}
|
|
74107
74177
|
const { usesPullSchedule } = validateTrafficSourceCredential(target, project.name);
|
|
74108
|
-
const siblings = tx.select().from(trafficSources).where(
|
|
74178
|
+
const siblings = tx.select().from(trafficSources).where(eq107(trafficSources.projectId, project.id)).all();
|
|
74109
74179
|
for (const sibling of siblings) {
|
|
74110
74180
|
if (sibling.id === target.id || sibling.status === TrafficSourceStatuses.archived) continue;
|
|
74111
74181
|
tx.update(trafficSources).set({
|
|
74112
74182
|
status: TrafficSourceStatuses.paused,
|
|
74113
74183
|
updatedAt: now
|
|
74114
|
-
}).where(
|
|
74184
|
+
}).where(eq107(trafficSources.id, sibling.id)).run();
|
|
74115
74185
|
}
|
|
74116
74186
|
tx.update(trafficSources).set({
|
|
74117
74187
|
status: TrafficSourceStatuses.connected,
|
|
74118
74188
|
lastError: null,
|
|
74119
74189
|
archivedAt: null,
|
|
74120
74190
|
updatedAt: now
|
|
74121
|
-
}).where(
|
|
74191
|
+
}).where(eq107(trafficSources.id, target.id)).run();
|
|
74122
74192
|
let scheduleAction = null;
|
|
74123
74193
|
if (usesPullSchedule) {
|
|
74124
74194
|
bindTrafficSyncSchedule(tx, project.id, target.id, now);
|
|
74125
74195
|
scheduleAction = "upsert";
|
|
74126
74196
|
} else {
|
|
74127
|
-
const schedule = tx.select().from(schedules).where(
|
|
74128
|
-
|
|
74129
|
-
|
|
74197
|
+
const schedule = tx.select().from(schedules).where(and92(
|
|
74198
|
+
eq107(schedules.projectId, project.id),
|
|
74199
|
+
eq107(schedules.kind, SchedulableRunKinds["traffic-sync"])
|
|
74130
74200
|
)).get();
|
|
74131
74201
|
if (schedule) {
|
|
74132
|
-
tx.delete(schedules).where(
|
|
74202
|
+
tx.delete(schedules).where(eq107(schedules.id, schedule.id)).run();
|
|
74133
74203
|
scheduleAction = "delete";
|
|
74134
74204
|
}
|
|
74135
74205
|
}
|
|
74136
|
-
const source = tx.select().from(trafficSources).where(
|
|
74206
|
+
const source = tx.select().from(trafficSources).where(eq107(trafficSources.id, target.id)).get();
|
|
74137
74207
|
writeAuditLog(tx, {
|
|
74138
74208
|
projectId: project.id,
|
|
74139
74209
|
actor: "api",
|
|
@@ -74201,7 +74271,7 @@ async function trafficRoutes(app, opts) {
|
|
|
74201
74271
|
}
|
|
74202
74272
|
const { bearerHash, credential } = authenticated;
|
|
74203
74273
|
const sourceId = credential.sourceId;
|
|
74204
|
-
const sourceRow2 = app.db.select().from(trafficSources).where(
|
|
74274
|
+
const sourceRow2 = app.db.select().from(trafficSources).where(eq107(trafficSources.id, sourceId)).get();
|
|
74205
74275
|
if (!sourceRow2 || sourceRow2.sourceType !== TrafficSourceTypes.cloudflare || sourceRow2.status !== TrafficSourceStatuses.connected || !parseDirectPushCloudflareSourceConfig(sourceRow2.configJson) || !timingSafeEqualHex(bearerHash, sourceRow2.ingestTokenHash)) {
|
|
74206
74276
|
throw authRequired();
|
|
74207
74277
|
}
|
|
@@ -74281,7 +74351,7 @@ async function trafficRoutes(app, opts) {
|
|
|
74281
74351
|
});
|
|
74282
74352
|
app.post("/projects/:name/traffic/sources/:id/sync", async (request) => {
|
|
74283
74353
|
const project = resolveProject(app.db, request.params.name);
|
|
74284
|
-
const initialSourceRow = app.db.select().from(trafficSources).where(
|
|
74354
|
+
const initialSourceRow = app.db.select().from(trafficSources).where(eq107(trafficSources.id, request.params.id)).get();
|
|
74285
74355
|
if (!initialSourceRow || initialSourceRow.projectId !== project.id) {
|
|
74286
74356
|
throw notFound("Traffic source", request.params.id);
|
|
74287
74357
|
}
|
|
@@ -74355,7 +74425,7 @@ async function trafficRoutes(app, opts) {
|
|
|
74355
74425
|
});
|
|
74356
74426
|
const finishSync = (status, error, stopReason) => {
|
|
74357
74427
|
const queueDrain = drainSummary(stopReason);
|
|
74358
|
-
app.db.update(runs).set({ status, finishedAt: committedAt, syncSummary: queueDrain, ...error ? { error } : {} }).where(
|
|
74428
|
+
app.db.update(runs).set({ status, finishedAt: committedAt, syncSummary: queueDrain, ...error ? { error } : {} }).where(eq107(runs.id, runId)).run();
|
|
74359
74429
|
writeAuditLog(app.db, {
|
|
74360
74430
|
projectId: project.id,
|
|
74361
74431
|
actor: "api",
|
|
@@ -74532,7 +74602,7 @@ async function trafficRoutes(app, opts) {
|
|
|
74532
74602
|
now: (/* @__PURE__ */ new Date()).toISOString(),
|
|
74533
74603
|
ttlMs: CLOUDFLARE_QUEUE_SYNC_LEASE_TTL_MS
|
|
74534
74604
|
})) throw new Error("Queue sync lease was lost before acknowledgement");
|
|
74535
|
-
const latestSource = app.db.select().from(trafficSources).where(
|
|
74605
|
+
const latestSource = app.db.select().from(trafficSources).where(eq107(trafficSources.id, sourceRow2.id)).get();
|
|
74536
74606
|
if (!latestSource || latestSource.projectId !== project.id || latestSource.status !== TrafficSourceStatuses.connected || latestSource.syncLeaseOwner !== leaseOwner || !isDeepStrictEqual(latestSource.configJson, sourceRow2.configJson)) {
|
|
74537
74607
|
throw validationError("Cloudflare Queue source was reconfigured before acknowledgement");
|
|
74538
74608
|
}
|
|
@@ -74622,13 +74692,13 @@ async function trafficRoutes(app, opts) {
|
|
|
74622
74692
|
error: safeError,
|
|
74623
74693
|
finishedAt: failedAt,
|
|
74624
74694
|
syncSummary: drainSummary(CloudflareQueueDrainStopReasons.error)
|
|
74625
|
-
}).where(
|
|
74626
|
-
const latestSource = tx.select().from(trafficSources).where(
|
|
74695
|
+
}).where(eq107(runs.id, runId)).run();
|
|
74696
|
+
const latestSource = tx.select().from(trafficSources).where(eq107(trafficSources.id, sourceRow2.id)).get();
|
|
74627
74697
|
if (latestSource && latestSource.status === TrafficSourceStatuses.connected && latestSource.syncLeaseOwner === leaseOwner && isDeepStrictEqual(latestSource.configJson, sourceRow2.configJson)) {
|
|
74628
|
-
tx.update(trafficSources).set({ lastError: safeError, updatedAt: failedAt }).where(
|
|
74629
|
-
|
|
74630
|
-
|
|
74631
|
-
|
|
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)
|
|
74632
74702
|
)).run();
|
|
74633
74703
|
}
|
|
74634
74704
|
});
|
|
@@ -74647,7 +74717,7 @@ async function trafficRoutes(app, opts) {
|
|
|
74647
74717
|
`Sync for source type "${sourceRow2.sourceType}" is not implemented yet \u2014 only cloud-run, wordpress, and vercel are supported in v1.`
|
|
74648
74718
|
);
|
|
74649
74719
|
}
|
|
74650
|
-
const hasConnectedSibling = sourceRow2.status === TrafficSourceStatuses.error && app.db.select().from(trafficSources).where(
|
|
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);
|
|
74651
74721
|
if (sourceRow2.status === TrafficSourceStatuses.paused || sourceRow2.status === TrafficSourceStatuses.archived || hasConnectedSibling) {
|
|
74652
74722
|
throw validationError("Traffic source must be active before it can sync");
|
|
74653
74723
|
}
|
|
@@ -74685,10 +74755,10 @@ async function trafficRoutes(app, opts) {
|
|
|
74685
74755
|
const markFailed = (msg, errorCode2) => {
|
|
74686
74756
|
const failedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
74687
74757
|
app.db.transaction((tx) => {
|
|
74688
|
-
tx.update(runs).set({ status: RunStatuses.failed, error: msg, finishedAt: failedAt }).where(
|
|
74689
|
-
const latestSource = tx.select().from(trafficSources).where(
|
|
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();
|
|
74690
74760
|
if (latestSource?.status === TrafficSourceStatuses.connected && isSameTrafficSourceGeneration(latestSource, sourceRow2) && latestSource.syncLeaseOwner === syncLeaseOwner) {
|
|
74691
|
-
tx.update(trafficSources).set({ status: TrafficSourceStatuses.error, lastError: msg, updatedAt: failedAt }).where(
|
|
74761
|
+
tx.update(trafficSources).set({ status: TrafficSourceStatuses.error, lastError: msg, updatedAt: failedAt }).where(eq107(trafficSources.id, sourceRow2.id)).run();
|
|
74692
74762
|
}
|
|
74693
74763
|
});
|
|
74694
74764
|
try {
|
|
@@ -74770,7 +74840,7 @@ async function trafficRoutes(app, opts) {
|
|
|
74770
74840
|
}
|
|
74771
74841
|
const credential = credentialStore.getConnection(project.name);
|
|
74772
74842
|
if (!credential) {
|
|
74773
|
-
app.db.delete(runs).where(
|
|
74843
|
+
app.db.delete(runs).where(eq107(runs.id, runId)).run();
|
|
74774
74844
|
throw validationError(
|
|
74775
74845
|
`No WordPress credential found for project "${project.name}". Run "canonry traffic connect wordpress" first.`
|
|
74776
74846
|
);
|
|
@@ -74804,14 +74874,14 @@ async function trafficRoutes(app, opts) {
|
|
|
74804
74874
|
const windowEndIso2 = windowEnd.toISOString();
|
|
74805
74875
|
const reservedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
74806
74876
|
const reservedSource = app.db.transaction((tx) => {
|
|
74807
|
-
const latestSource = tx.select().from(trafficSources).where(
|
|
74877
|
+
const latestSource = tx.select().from(trafficSources).where(eq107(trafficSources.id, sourceRow2.id)).get();
|
|
74808
74878
|
if (!latestSource || !isAuthoritativeTrafficSource(tx, latestSource) || !isSameTrafficSourceGeneration(latestSource, sourceRow2) || latestSource.syncLeaseOwner !== syncLeaseOwner || latestSource.lastCursor || latestSource.wordpressPendingUntil) return void 0;
|
|
74809
74879
|
tx.update(trafficSources).set({
|
|
74810
74880
|
lastSyncedAt: windowStartIso2,
|
|
74811
74881
|
wordpressPendingUntil: windowEndIso2,
|
|
74812
74882
|
updatedAt: reservedAt
|
|
74813
|
-
}).where(
|
|
74814
|
-
return tx.select().from(trafficSources).where(
|
|
74883
|
+
}).where(eq107(trafficSources.id, sourceRow2.id)).run();
|
|
74884
|
+
return tx.select().from(trafficSources).where(eq107(trafficSources.id, sourceRow2.id)).get();
|
|
74815
74885
|
}, { behavior: "immediate" });
|
|
74816
74886
|
if (!reservedSource) {
|
|
74817
74887
|
const message = "Traffic source changed while reserving the WordPress sync window; retry the sync.";
|
|
@@ -74862,7 +74932,7 @@ async function trafficRoutes(app, opts) {
|
|
|
74862
74932
|
allEvents = collected;
|
|
74863
74933
|
nextCursor = cursor;
|
|
74864
74934
|
} catch (e) {
|
|
74865
|
-
const msg = describeError(e);
|
|
74935
|
+
const msg = redactKnownSecrets(describeError(e), wordpressRedactionValues(credential.username, credential.applicationPassword));
|
|
74866
74936
|
markFailed(msg, "PROVIDER_PULL");
|
|
74867
74937
|
if (e instanceof EgressRefusedError && !e.redirected) throw validationError(`WordPress baseUrl rejected: ${msg}`);
|
|
74868
74938
|
throw providerError(`WordPress pull failed: ${msg}`);
|
|
@@ -74871,12 +74941,12 @@ async function trafficRoutes(app, opts) {
|
|
|
74871
74941
|
auditAction = "traffic.vercel.synced";
|
|
74872
74942
|
const credentialStore = opts.vercelTrafficCredentialStore;
|
|
74873
74943
|
if (!credentialStore) {
|
|
74874
|
-
app.db.delete(runs).where(
|
|
74944
|
+
app.db.delete(runs).where(eq107(runs.id, runId)).run();
|
|
74875
74945
|
throw validationError("Vercel traffic credential storage is not configured for this deployment");
|
|
74876
74946
|
}
|
|
74877
74947
|
const credential = credentialStore.getConnection(project.name);
|
|
74878
74948
|
if (!credential) {
|
|
74879
|
-
app.db.delete(runs).where(
|
|
74949
|
+
app.db.delete(runs).where(eq107(runs.id, runId)).run();
|
|
74880
74950
|
throw validationError(
|
|
74881
74951
|
`No Vercel credential found for project "${project.name}". Run "canonry traffic connect vercel" first.`
|
|
74882
74952
|
);
|
|
@@ -74894,7 +74964,7 @@ async function trafficRoutes(app, opts) {
|
|
|
74894
74964
|
if (cappedStartMs > clampedStartMs) {
|
|
74895
74965
|
const previousSkip = sourceRow2.skippedThroughAt ? Date.parse(sourceRow2.skippedThroughAt) : Number.NaN;
|
|
74896
74966
|
const skippedThrough = Number.isFinite(previousSkip) ? new Date(Math.max(previousSkip, cappedStartMs)) : new Date(cappedStartMs);
|
|
74897
|
-
app.db.update(trafficSources).set({ skippedThroughAt: skippedThrough.toISOString() }).where(
|
|
74967
|
+
app.db.update(trafficSources).set({ skippedThroughAt: skippedThrough.toISOString() }).where(eq107(trafficSources.id, sourceRow2.id)).run();
|
|
74898
74968
|
request.log.warn(
|
|
74899
74969
|
{
|
|
74900
74970
|
sourceId: sourceRow2.id,
|
|
@@ -74962,7 +75032,7 @@ async function trafficRoutes(app, opts) {
|
|
|
74962
75032
|
}
|
|
74963
75033
|
allEvents = drained.events;
|
|
74964
75034
|
} catch (e) {
|
|
74965
|
-
const msg = describeError(e);
|
|
75035
|
+
const msg = redactKnownSecrets(describeError(e), credentialRedactionValues(credential.token));
|
|
74966
75036
|
const credentialRefused = e instanceof VercelLogsApiError && (e.status === 401 || e.status === 403);
|
|
74967
75037
|
markFailed(msg, credentialRefused ? "PROVIDER_AUTH" : "PROVIDER_PULL");
|
|
74968
75038
|
throw providerError(`Vercel pull failed: ${msg}`);
|
|
@@ -74989,15 +75059,15 @@ async function trafficRoutes(app, opts) {
|
|
|
74989
75059
|
throw providerError(`WordPress sync failed: ${msg}`);
|
|
74990
75060
|
}
|
|
74991
75061
|
const commitOutcome = app.db.transaction((tx) => {
|
|
74992
|
-
const latestRow = tx.select().from(trafficSources).where(
|
|
74993
|
-
const latestHasConnectedSibling = tx.select().from(trafficSources).where(
|
|
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);
|
|
74994
75064
|
if (!latestRow || latestRow.status !== TrafficSourceStatuses.connected && latestRow.status !== TrafficSourceStatuses.error || latestHasConnectedSibling || latestRow.syncLeaseOwner !== syncLeaseOwner || !isSameTrafficSourceGeneration(latestRow, sourceRow2)) {
|
|
74995
75065
|
const abortedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
74996
75066
|
tx.update(runs).set({
|
|
74997
75067
|
status: RunStatuses.failed,
|
|
74998
75068
|
error: "Traffic source was deactivated or reconfigured during sync",
|
|
74999
75069
|
finishedAt: abortedAt
|
|
75000
|
-
}).where(
|
|
75070
|
+
}).where(eq107(runs.id, runId)).run();
|
|
75001
75071
|
return "source-inactive";
|
|
75002
75072
|
}
|
|
75003
75073
|
const previousIds = latestRow.lastEventIds ?? [];
|
|
@@ -75284,8 +75354,8 @@ async function trafficRoutes(app, opts) {
|
|
|
75284
75354
|
sourceUpdate.lastCursor = nextCursor ?? null;
|
|
75285
75355
|
sourceUpdate.wordpressPendingUntil = nextCursor ? windowEnd.toISOString() : null;
|
|
75286
75356
|
}
|
|
75287
|
-
tx.update(trafficSources).set(sourceUpdate).where(
|
|
75288
|
-
tx.update(runs).set({ status: RunStatuses.completed, finishedAt }).where(
|
|
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();
|
|
75289
75359
|
return "committed";
|
|
75290
75360
|
}, { behavior: "immediate" });
|
|
75291
75361
|
if (commitOutcome === "source-inactive") {
|
|
@@ -75356,7 +75426,7 @@ async function trafficRoutes(app, opts) {
|
|
|
75356
75426
|
});
|
|
75357
75427
|
app.post("/projects/:name/traffic/sources/:id/backfill", async (request) => withFeatureOutcome(app, { feature: "server_traffic", operation: "backfill" }, async (recordOutcome) => {
|
|
75358
75428
|
const project = resolveProject(app.db, request.params.name);
|
|
75359
|
-
const sourceRow2 = app.db.select().from(trafficSources).where(
|
|
75429
|
+
const sourceRow2 = app.db.select().from(trafficSources).where(eq107(trafficSources.id, request.params.id)).get();
|
|
75360
75430
|
if (!sourceRow2 || sourceRow2.projectId !== project.id) {
|
|
75361
75431
|
throw notFound("Traffic source", request.params.id);
|
|
75362
75432
|
}
|
|
@@ -75384,6 +75454,7 @@ async function trafficRoutes(app, opts) {
|
|
|
75384
75454
|
windowStart.setUTCMinutes(0, 0, 0);
|
|
75385
75455
|
let pullForBackfill;
|
|
75386
75456
|
let pullErrorPrefix;
|
|
75457
|
+
let pullSecrets = [];
|
|
75387
75458
|
if (sourceRow2.sourceType === TrafficSourceTypes["cloud-run"]) {
|
|
75388
75459
|
const credential = requireCloudRunSourceCredential(sourceRow2, project.name);
|
|
75389
75460
|
const { gcpProjectId, serviceName, location } = credential;
|
|
@@ -75424,6 +75495,7 @@ async function trafficRoutes(app, opts) {
|
|
|
75424
75495
|
const vercelTeamId = config.teamId ?? credential.teamId;
|
|
75425
75496
|
const vercelEnvironment = config.environment ?? credential.environment;
|
|
75426
75497
|
pullErrorPrefix = "Vercel pull failed";
|
|
75498
|
+
pullSecrets = credentialRedactionValues(credential.token);
|
|
75427
75499
|
pullForBackfill = async (signal) => {
|
|
75428
75500
|
const collected = [];
|
|
75429
75501
|
const seenEventIds = /* @__PURE__ */ new Set();
|
|
@@ -75469,7 +75541,7 @@ async function trafficRoutes(app, opts) {
|
|
|
75469
75541
|
}
|
|
75470
75542
|
try {
|
|
75471
75543
|
app.db.transaction((tx) => {
|
|
75472
|
-
const latestSource = tx.select().from(trafficSources).where(
|
|
75544
|
+
const latestSource = tx.select().from(trafficSources).where(eq107(trafficSources.id, sourceRow2.id)).get();
|
|
75473
75545
|
if (!latestSource || !isAuthoritativeTrafficSource(tx, latestSource) || !isSameTrafficSourceGeneration(latestSource, sourceRow2)) {
|
|
75474
75546
|
throw validationError("Traffic source must remain active and unchanged before it can backfill");
|
|
75475
75547
|
}
|
|
@@ -75499,7 +75571,8 @@ async function trafficRoutes(app, opts) {
|
|
|
75499
75571
|
windowStart,
|
|
75500
75572
|
windowEnd,
|
|
75501
75573
|
pullForBackfill,
|
|
75502
|
-
pullErrorPrefix
|
|
75574
|
+
pullErrorPrefix,
|
|
75575
|
+
pullSecrets
|
|
75503
75576
|
}).catch(() => {
|
|
75504
75577
|
});
|
|
75505
75578
|
recordOutcome(null);
|
|
@@ -75519,8 +75592,8 @@ async function trafficRoutes(app, opts) {
|
|
|
75519
75592
|
pathNormalized: crawlerEventsHourly.pathNormalized,
|
|
75520
75593
|
hits: sql48`COALESCE(SUM(${crawlerEventsHourly.hits}), 0)`
|
|
75521
75594
|
}).from(crawlerEventsHourly).where(
|
|
75522
|
-
|
|
75523
|
-
|
|
75595
|
+
and92(
|
|
75596
|
+
eq107(crawlerEventsHourly.sourceId, row.id),
|
|
75524
75597
|
gte27(crawlerEventsHourly.tsHour, since)
|
|
75525
75598
|
)
|
|
75526
75599
|
).groupBy(crawlerEventsHourly.pathNormalized).all();
|
|
@@ -75529,14 +75602,14 @@ async function trafficRoutes(app, opts) {
|
|
|
75529
75602
|
);
|
|
75530
75603
|
const crawlerTotal = crawlerSegments.content + crawlerSegments.sitemap + crawlerSegments.robots + crawlerSegments.asset + crawlerSegments.other;
|
|
75531
75604
|
const aiUserFetchTotals = app.db.select({ total: sql48`COALESCE(SUM(${aiUserFetchEventsHourly.hits}), 0)` }).from(aiUserFetchEventsHourly).where(
|
|
75532
|
-
|
|
75533
|
-
|
|
75605
|
+
and92(
|
|
75606
|
+
eq107(aiUserFetchEventsHourly.sourceId, row.id),
|
|
75534
75607
|
gte27(aiUserFetchEventsHourly.tsHour, since)
|
|
75535
75608
|
)
|
|
75536
75609
|
).get();
|
|
75537
75610
|
const likelyFakeTotals = app.db.select({ total: sql48`COALESCE(SUM(${aiUserFetchLikelyFakeHourly.hits}), 0)` }).from(aiUserFetchLikelyFakeHourly).where(
|
|
75538
|
-
|
|
75539
|
-
|
|
75611
|
+
and92(
|
|
75612
|
+
eq107(aiUserFetchLikelyFakeHourly.sourceId, row.id),
|
|
75540
75613
|
gte27(aiUserFetchLikelyFakeHourly.tsHour, since)
|
|
75541
75614
|
)
|
|
75542
75615
|
).get();
|
|
@@ -75545,22 +75618,22 @@ async function trafficRoutes(app, opts) {
|
|
|
75545
75618
|
nonhop: sql48`COALESCE(SUM(CASE WHEN ${referralLandedCondition()} THEN ${aiReferralEventsHourly.sessionsOrHits} ELSE 0 END), 0)`,
|
|
75546
75619
|
landed: sql48`COALESCE(SUM(CASE WHEN ${countableReferralCondition()} THEN ${aiReferralEventsHourly.sessionsOrHits} ELSE 0 END), 0)`
|
|
75547
75620
|
}).from(aiReferralEventsHourly).where(
|
|
75548
|
-
|
|
75549
|
-
|
|
75621
|
+
and92(
|
|
75622
|
+
eq107(aiReferralEventsHourly.sourceId, row.id),
|
|
75550
75623
|
gte27(aiReferralEventsHourly.tsHour, since)
|
|
75551
75624
|
)
|
|
75552
75625
|
).get();
|
|
75553
75626
|
const sampleTotals = app.db.select({ total: sql48`COUNT(*)` }).from(rawEventSamples).where(
|
|
75554
|
-
|
|
75555
|
-
|
|
75627
|
+
and92(
|
|
75628
|
+
eq107(rawEventSamples.sourceId, row.id),
|
|
75556
75629
|
gte27(rawEventSamples.ts, since)
|
|
75557
75630
|
)
|
|
75558
75631
|
).get();
|
|
75559
75632
|
const latestRun2 = app.db.select().from(runs).where(
|
|
75560
|
-
|
|
75561
|
-
|
|
75562
|
-
|
|
75563
|
-
|
|
75633
|
+
and92(
|
|
75634
|
+
eq107(runs.projectId, projectId),
|
|
75635
|
+
eq107(runs.kind, RunKinds["traffic-sync"]),
|
|
75636
|
+
eq107(runs.sourceId, row.id)
|
|
75564
75637
|
)
|
|
75565
75638
|
).orderBy(desc49(runs.startedAt)).limit(1).get();
|
|
75566
75639
|
return {
|
|
@@ -75598,7 +75671,7 @@ async function trafficRoutes(app, opts) {
|
|
|
75598
75671
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
75599
75672
|
let updatedRow;
|
|
75600
75673
|
app.db.transaction((tx) => {
|
|
75601
|
-
const sourceRow2 = tx.select().from(trafficSources).where(
|
|
75674
|
+
const sourceRow2 = tx.select().from(trafficSources).where(and92(eq107(trafficSources.projectId, project.id), eq107(trafficSources.id, request.params.id))).get();
|
|
75602
75675
|
if (!sourceRow2) {
|
|
75603
75676
|
throw notFound("traffic source", request.params.id);
|
|
75604
75677
|
}
|
|
@@ -75612,7 +75685,7 @@ async function trafficRoutes(app, opts) {
|
|
|
75612
75685
|
`Traffic source "${sourceRow2.id}" is staged. Activate it explicitly instead of resetting it.`
|
|
75613
75686
|
);
|
|
75614
75687
|
}
|
|
75615
|
-
const hasConnectedSibling = tx.select().from(trafficSources).where(
|
|
75688
|
+
const hasConnectedSibling = tx.select().from(trafficSources).where(eq107(trafficSources.projectId, project.id)).all().some((row) => row.id !== sourceRow2.id && row.status === TrafficSourceStatuses.connected);
|
|
75616
75689
|
if (hasConnectedSibling) {
|
|
75617
75690
|
throw validationError(
|
|
75618
75691
|
`Traffic source "${sourceRow2.id}" is not authoritative. Activate it explicitly instead of resetting it.`
|
|
@@ -75629,7 +75702,7 @@ async function trafficRoutes(app, opts) {
|
|
|
75629
75702
|
status: TrafficSourceStatuses.connected,
|
|
75630
75703
|
lastError: null,
|
|
75631
75704
|
updatedAt: now
|
|
75632
|
-
}).where(
|
|
75705
|
+
}).where(eq107(trafficSources.id, sourceRow2.id)).run();
|
|
75633
75706
|
writeAuditLog(tx, auditFromRequest(request, {
|
|
75634
75707
|
projectId: project.id,
|
|
75635
75708
|
actor: "api",
|
|
@@ -75637,7 +75710,7 @@ async function trafficRoutes(app, opts) {
|
|
|
75637
75710
|
entityType: "traffic_source",
|
|
75638
75711
|
entityId: sourceRow2.id
|
|
75639
75712
|
}));
|
|
75640
|
-
updatedRow = tx.select().from(trafficSources).where(
|
|
75713
|
+
updatedRow = tx.select().from(trafficSources).where(eq107(trafficSources.id, sourceRow2.id)).get();
|
|
75641
75714
|
});
|
|
75642
75715
|
return buildSourceDetail(project.id, updatedRow, new Date(Date.now() - 24 * 60 * 6e4).toISOString());
|
|
75643
75716
|
}));
|
|
@@ -75649,7 +75722,7 @@ async function trafficRoutes(app, opts) {
|
|
|
75649
75722
|
}
|
|
75650
75723
|
let updatedRow;
|
|
75651
75724
|
app.db.transaction((tx) => {
|
|
75652
|
-
const sourceRow2 = tx.select().from(trafficSources).where(
|
|
75725
|
+
const sourceRow2 = tx.select().from(trafficSources).where(and92(eq107(trafficSources.projectId, project.id), eq107(trafficSources.id, request.params.id))).get();
|
|
75653
75726
|
if (!sourceRow2) {
|
|
75654
75727
|
throw notFound("traffic source", request.params.id);
|
|
75655
75728
|
}
|
|
@@ -75662,7 +75735,7 @@ async function trafficRoutes(app, opts) {
|
|
|
75662
75735
|
);
|
|
75663
75736
|
}
|
|
75664
75737
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
75665
|
-
tx.update(trafficSources).set({ skippedThroughAt: null, updatedAt: now }).where(
|
|
75738
|
+
tx.update(trafficSources).set({ skippedThroughAt: null, updatedAt: now }).where(eq107(trafficSources.id, sourceRow2.id)).run();
|
|
75666
75739
|
writeAuditLog(tx, auditFromRequest(request, {
|
|
75667
75740
|
projectId: project.id,
|
|
75668
75741
|
actor: "api",
|
|
@@ -75671,20 +75744,20 @@ async function trafficRoutes(app, opts) {
|
|
|
75671
75744
|
entityId: sourceRow2.id,
|
|
75672
75745
|
diff: { skippedThroughAt: sourceRow2.skippedThroughAt, sourceType: sourceRow2.sourceType }
|
|
75673
75746
|
}));
|
|
75674
|
-
updatedRow = tx.select().from(trafficSources).where(
|
|
75747
|
+
updatedRow = tx.select().from(trafficSources).where(eq107(trafficSources.id, sourceRow2.id)).get();
|
|
75675
75748
|
});
|
|
75676
75749
|
return buildSourceDetail(project.id, updatedRow, new Date(Date.now() - 24 * 60 * 6e4).toISOString());
|
|
75677
75750
|
});
|
|
75678
75751
|
app.get("/projects/:name/traffic/sources", async (request) => {
|
|
75679
75752
|
const project = resolveProject(app.db, request.params.name);
|
|
75680
|
-
const rows = app.db.select().from(trafficSources).where(
|
|
75753
|
+
const rows = app.db.select().from(trafficSources).where(eq107(trafficSources.projectId, project.id)).orderBy(desc49(trafficSources.createdAt)).all();
|
|
75681
75754
|
const sources = rows.filter((row) => row.status !== TrafficSourceStatuses.archived).map(rowToDto);
|
|
75682
75755
|
const response = { sources };
|
|
75683
75756
|
return response;
|
|
75684
75757
|
});
|
|
75685
75758
|
app.get("/projects/:name/traffic/status", async (request) => {
|
|
75686
75759
|
const project = resolveProject(app.db, request.params.name);
|
|
75687
|
-
const rows = app.db.select().from(trafficSources).where(
|
|
75760
|
+
const rows = app.db.select().from(trafficSources).where(eq107(trafficSources.projectId, project.id)).orderBy(desc49(trafficSources.createdAt)).all();
|
|
75688
75761
|
const since = new Date(Date.now() - 24 * 60 * 6e4).toISOString();
|
|
75689
75762
|
const sources = rows.filter((row) => row.status !== TrafficSourceStatuses.archived).map((row) => buildSourceDetail(project.id, row, since));
|
|
75690
75763
|
const response = { sources };
|
|
@@ -75694,7 +75767,7 @@ async function trafficRoutes(app, opts) {
|
|
|
75694
75767
|
"/projects/:name/traffic/sources/:id",
|
|
75695
75768
|
async (request) => {
|
|
75696
75769
|
const project = resolveProject(app.db, request.params.name);
|
|
75697
|
-
const row = app.db.select().from(trafficSources).where(
|
|
75770
|
+
const row = app.db.select().from(trafficSources).where(eq107(trafficSources.id, request.params.id)).get();
|
|
75698
75771
|
if (!row || row.projectId !== project.id) {
|
|
75699
75772
|
throw notFound("Traffic source", request.params.id);
|
|
75700
75773
|
}
|
|
@@ -75773,7 +75846,7 @@ async function trafficRoutes(app, opts) {
|
|
|
75773
75846
|
agent: agentFilter
|
|
75774
75847
|
};
|
|
75775
75848
|
const cursor = cursorParam === null ? null : decodeTrafficEventCursor(cursorParam, readFilters, sinceIso, untilIso);
|
|
75776
|
-
const pageRows = (table, where, read) => read(cursor ?
|
|
75849
|
+
const pageRows = (table, where, read) => read(cursor ? and92(where, trafficEventCursorPredicate(table, cursor)) : where, trafficEventOrder(table), limit + 1).map((row) => ({
|
|
75777
75850
|
rank: table.rank,
|
|
75778
75851
|
tsHour: row.tsHour,
|
|
75779
75852
|
keys: table.keyFields.map((field) => row[field]),
|
|
@@ -75805,13 +75878,13 @@ async function trafficRoutes(app, opts) {
|
|
|
75805
75878
|
const seriesByBucket = /* @__PURE__ */ new Map();
|
|
75806
75879
|
if (kinds.has(TrafficEventKinds.crawler)) {
|
|
75807
75880
|
const crawlerFilters = [
|
|
75808
|
-
|
|
75881
|
+
eq107(crawlerEventsHourly.projectId, project.id),
|
|
75809
75882
|
gte27(crawlerEventsHourly.tsHour, sinceIso),
|
|
75810
75883
|
lte27(crawlerEventsHourly.tsHour, untilIso)
|
|
75811
75884
|
];
|
|
75812
|
-
if (sourceIdParam) crawlerFilters.push(
|
|
75885
|
+
if (sourceIdParam) crawlerFilters.push(eq107(crawlerEventsHourly.sourceId, sourceIdParam));
|
|
75813
75886
|
crawlerFilters.push(...trafficEventFilterPredicates(TRAFFIC_EVENT_TABLES.crawler, readFilters));
|
|
75814
|
-
const crawlerWhere =
|
|
75887
|
+
const crawlerWhere = and92(...crawlerFilters);
|
|
75815
75888
|
collectGroups(TRAFFIC_EVENT_TABLES.crawler, crawlerWhere);
|
|
75816
75889
|
const pathTotals = app.db.select({
|
|
75817
75890
|
pathNormalized: crawlerEventsHourly.pathNormalized,
|
|
@@ -75887,13 +75960,13 @@ async function trafficRoutes(app, opts) {
|
|
|
75887
75960
|
}
|
|
75888
75961
|
if (kinds.has(TrafficEventKinds["ai-user-fetch"])) {
|
|
75889
75962
|
const userFetchFilters = [
|
|
75890
|
-
|
|
75963
|
+
eq107(aiUserFetchEventsHourly.projectId, project.id),
|
|
75891
75964
|
gte27(aiUserFetchEventsHourly.tsHour, sinceIso),
|
|
75892
75965
|
lte27(aiUserFetchEventsHourly.tsHour, untilIso)
|
|
75893
75966
|
];
|
|
75894
|
-
if (sourceIdParam) userFetchFilters.push(
|
|
75967
|
+
if (sourceIdParam) userFetchFilters.push(eq107(aiUserFetchEventsHourly.sourceId, sourceIdParam));
|
|
75895
75968
|
userFetchFilters.push(...trafficEventFilterPredicates(TRAFFIC_EVENT_TABLES["ai-user-fetch"], readFilters));
|
|
75896
|
-
const userFetchWhere =
|
|
75969
|
+
const userFetchWhere = and92(...userFetchFilters);
|
|
75897
75970
|
collectGroups(TRAFFIC_EVENT_TABLES["ai-user-fetch"], userFetchWhere);
|
|
75898
75971
|
const total = app.db.select({
|
|
75899
75972
|
total: sql48`COALESCE(SUM(${aiUserFetchEventsHourly.hits}), 0)`,
|
|
@@ -75933,13 +76006,13 @@ async function trafficRoutes(app, opts) {
|
|
|
75933
76006
|
}
|
|
75934
76007
|
if (kinds.has(TrafficEventKinds["ai-referral"])) {
|
|
75935
76008
|
const aiFilters = [
|
|
75936
|
-
|
|
76009
|
+
eq107(aiReferralEventsHourly.projectId, project.id),
|
|
75937
76010
|
gte27(aiReferralEventsHourly.tsHour, sinceIso),
|
|
75938
76011
|
lte27(aiReferralEventsHourly.tsHour, untilIso)
|
|
75939
76012
|
];
|
|
75940
|
-
if (sourceIdParam) aiFilters.push(
|
|
76013
|
+
if (sourceIdParam) aiFilters.push(eq107(aiReferralEventsHourly.sourceId, sourceIdParam));
|
|
75941
76014
|
aiFilters.push(...trafficEventFilterPredicates(TRAFFIC_EVENT_TABLES["ai-referral"], readFilters));
|
|
75942
|
-
const aiWhere =
|
|
76015
|
+
const aiWhere = and92(...aiFilters);
|
|
75943
76016
|
collectGroups(TRAFFIC_EVENT_TABLES["ai-referral"], aiWhere);
|
|
75944
76017
|
const total = app.db.select({
|
|
75945
76018
|
total: sql48`COALESCE(SUM(${aiReferralEventsHourly.sessionsOrHits}), 0)`,
|
|
@@ -76023,7 +76096,7 @@ async function trafficRoutes(app, opts) {
|
|
|
76023
76096
|
windowEnd: untilIso,
|
|
76024
76097
|
series: (() => {
|
|
76025
76098
|
const points = completeTrafficSeries(since, until, granularity, seriesByBucket);
|
|
76026
|
-
const coverageScope = (col, srcCol) => sourceIdParam ?
|
|
76099
|
+
const coverageScope = (col, srcCol) => sourceIdParam ? and92(eq107(col, project.id), eq107(srcCol, sourceIdParam)) : eq107(col, project.id);
|
|
76027
76100
|
const firsts = [
|
|
76028
76101
|
app.db.select({ v: sql48`MIN(${crawlerEventsHourly.tsHour})` }).from(crawlerEventsHourly).where(coverageScope(crawlerEventsHourly.projectId, crawlerEventsHourly.sourceId)).get()?.v,
|
|
76029
76102
|
app.db.select({ v: sql48`MIN(${aiUserFetchEventsHourly.tsHour})` }).from(aiUserFetchEventsHourly).where(coverageScope(aiUserFetchEventsHourly.projectId, aiUserFetchEventsHourly.sourceId)).get()?.v,
|
|
@@ -76042,6 +76115,17 @@ async function trafficRoutes(app, opts) {
|
|
|
76042
76115
|
for (const pt of points) {
|
|
76043
76116
|
pt.measured = coverageKey === null ? false : seriesBucketOf(pt.bucket, granularity) >= coverageKey;
|
|
76044
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
|
+
}
|
|
76045
76129
|
const firstMeasuredIdx = points.findIndex((pt) => pt.measured);
|
|
76046
76130
|
const coverageStartMs = coverageStart === null ? null : Date.parse(coverageStart);
|
|
76047
76131
|
const leadingBucketIsPartial = firstMeasuredIdx >= 0 && coverageStartMs !== null && Number.isFinite(coverageStartMs) && Math.max(coverageStartMs, since.getTime()) > bucketStartMs(points[firstMeasuredIdx].bucket);
|
|
@@ -76051,16 +76135,17 @@ async function trafficRoutes(app, opts) {
|
|
|
76051
76135
|
coverageStart,
|
|
76052
76136
|
aiReferralCountingChangedAt: referralCountingChangedAt,
|
|
76053
76137
|
aiUserFetchCountingChangedAt: userFetchCountingChangedAt,
|
|
76054
|
-
|
|
76055
|
-
|
|
76056
|
-
|
|
76057
|
-
|
|
76058
|
-
],
|
|
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),
|
|
76059
76142
|
// Two edges are excluded from the fit, both for the same reason: a
|
|
76060
76143
|
// bucket that is not a full reading must not be treated as one.
|
|
76061
76144
|
//
|
|
76062
|
-
// Leading: unmeasured buckets predate recording
|
|
76063
|
-
// ABSENCE of a reading, not a
|
|
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
|
|
76064
76149
|
// bucket goes too when recording or the range began inside it, since
|
|
76065
76150
|
// a fraction of a bucket read as a whole slopes the fit up out of nothing.
|
|
76066
76151
|
//
|
|
@@ -76080,7 +76165,7 @@ async function trafficRoutes(app, opts) {
|
|
|
76080
76165
|
// linearTrend skips nulls while surviving points keep their true
|
|
76081
76166
|
// index, so dropping an edge does not compress the x-axis.
|
|
76082
76167
|
trends: (() => {
|
|
76083
|
-
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);
|
|
76084
76169
|
const countedByCurrentRule = (pt) => referralCountingChangedMs === null || bucketStartMs(pt.bucket) >= referralCountingChangedMs;
|
|
76085
76170
|
const countedByPageLoads = (pt) => userFetchCountingChangedMs === null || bucketStartMs(pt.bucket) >= userFetchCountingChangedMs;
|
|
76086
76171
|
const series = (pick, include = () => true) => linearTrend(points.map((pt, i) => usable(pt, i) && include(pt) ? pick(pt) : null));
|
|
@@ -76128,7 +76213,7 @@ async function trafficRoutes(app, opts) {
|
|
|
76128
76213
|
}
|
|
76129
76214
|
|
|
76130
76215
|
// ../api-routes/src/doctor/checks/report-sweeps.ts
|
|
76131
|
-
import { and as
|
|
76216
|
+
import { and as and93, asc as asc28, eq as eq108, gte as gte28, lte as lte28 } from "drizzle-orm";
|
|
76132
76217
|
|
|
76133
76218
|
// ../api-routes/src/visibility-attribution.ts
|
|
76134
76219
|
function buildQueryAttribution2(projectQueries) {
|
|
@@ -76162,11 +76247,11 @@ function inspectSweep(ctx, run) {
|
|
|
76162
76247
|
answerMentioned: querySnapshots.answerMentioned,
|
|
76163
76248
|
answerText: querySnapshots.answerText,
|
|
76164
76249
|
measurementExecutionId: querySnapshots.measurementExecutionId
|
|
76165
|
-
}).from(querySnapshots).where(
|
|
76250
|
+
}).from(querySnapshots).where(eq108(querySnapshots.runId, run.id)).all();
|
|
76166
76251
|
if (snapshots.length === 0) return { detail: { ...base, complete: false, reason: "no-answers" } };
|
|
76167
76252
|
try {
|
|
76168
76253
|
if (run.measurementPlanVersionId) {
|
|
76169
|
-
const version = ctx.db.select().from(measurementPlanVersions).where(
|
|
76254
|
+
const version = ctx.db.select().from(measurementPlanVersions).where(and93(eq108(measurementPlanVersions.projectId, ctx.project.id), eq108(measurementPlanVersions.id, run.measurementPlanVersionId))).get();
|
|
76170
76255
|
if (!version) return { detail: { ...base, complete: false, reason: "missing-plan" } };
|
|
76171
76256
|
const plan = parseStoredMeasurementPlanAnyVersion(version.canonicalJson);
|
|
76172
76257
|
const manifest = measurementRunExpectedSlots(run, plan);
|
|
@@ -76198,10 +76283,10 @@ function inspectSweep(ctx, run) {
|
|
|
76198
76283
|
};
|
|
76199
76284
|
return unbound ? { detail } : { detail, coverage: slotCoverage(expected2, answered3) };
|
|
76200
76285
|
}
|
|
76201
|
-
const stored = ctx.db.select().from(simpleMeasurementDefinitions).where(
|
|
76286
|
+
const stored = ctx.db.select().from(simpleMeasurementDefinitions).where(eq108(simpleMeasurementDefinitions.runId, run.id)).get();
|
|
76202
76287
|
const frozen = stored ? simpleMeasurementDefinitionSchema.parse(stored.definition) : null;
|
|
76203
|
-
const project = ctx.db.select().from(projects).where(
|
|
76204
|
-
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(
|
|
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();
|
|
76205
76290
|
const providers = frozen ? frozen.engines.map((engine) => engine.provider) : project.providers.length > 0 ? project.providers : [...new Set(snapshots.map((snapshot) => snapshot.provider))];
|
|
76206
76291
|
const attribution = buildQueryAttribution2(basket);
|
|
76207
76292
|
const expected = new Set(basket.flatMap((query2) => providers.map((provider) => JSON.stringify([query2.id, provider.trim().toLowerCase()]))));
|
|
@@ -76250,7 +76335,7 @@ var reportSweepsCheck = {
|
|
|
76250
76335
|
const graded = gradedReportMonths(reportMonths, now);
|
|
76251
76336
|
const months = reportMonths.map((month) => {
|
|
76252
76337
|
const bounds = calendarMonthBounds(month);
|
|
76253
|
-
const monthRuns = ctx.db.select().from(runs).where(
|
|
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();
|
|
76254
76339
|
const evidence = monthRuns.map((run) => inspectSweep(ctx, run));
|
|
76255
76340
|
return {
|
|
76256
76341
|
month,
|
|
@@ -76273,7 +76358,7 @@ var reportSweepsCheck = {
|
|
|
76273
76358
|
};
|
|
76274
76359
|
|
|
76275
76360
|
// ../api-routes/src/doctor/checks/report-models.ts
|
|
76276
|
-
import { and as
|
|
76361
|
+
import { and as and94, eq as eq109, gte as gte29, inArray as inArray51, lte as lte29 } from "drizzle-orm";
|
|
76277
76362
|
var reportModelsCheck = {
|
|
76278
76363
|
id: "report.models",
|
|
76279
76364
|
category: CheckCategories.providers,
|
|
@@ -76288,7 +76373,7 @@ var reportModelsCheck = {
|
|
|
76288
76373
|
const months = reportMonths.flatMap((month) => {
|
|
76289
76374
|
const bounds = calendarMonthBounds(month);
|
|
76290
76375
|
const previous = new Date(Date.parse(bounds.since) - 1).toISOString().slice(0, 7);
|
|
76291
|
-
const observations = ctx.db.select({ provider: querySnapshots.provider, model: querySnapshots.model, at: runs.createdAt }).from(querySnapshots).innerJoin(runs,
|
|
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();
|
|
76292
76377
|
return readVisibilityContinuity(ctx.db, ctx.project.name, { from: previous, to: month }).map(({ frame, continuity: continuity2 }) => ({
|
|
76293
76378
|
month,
|
|
76294
76379
|
previousMonth: previous,
|
|
@@ -76329,7 +76414,7 @@ var reportModelsCheck = {
|
|
|
76329
76414
|
};
|
|
76330
76415
|
|
|
76331
76416
|
// ../api-routes/src/doctor/checks/report-daily-data.ts
|
|
76332
|
-
import { eq as
|
|
76417
|
+
import { eq as eq110 } from "drizzle-orm";
|
|
76333
76418
|
var REPORTING_LAG_DAYS = 3;
|
|
76334
76419
|
function dateSpan(dates) {
|
|
76335
76420
|
const sorted = [...dates].sort();
|
|
@@ -76338,31 +76423,31 @@ function dateSpan(dates) {
|
|
|
76338
76423
|
function latestSyncRange(ctx, source) {
|
|
76339
76424
|
const projectId = ctx.project.id;
|
|
76340
76425
|
if (source === "ga") {
|
|
76341
|
-
const rows2 = ctx.db.select({ date: gaDailyTotals.date, syncedAt: gaDailyTotals.syncedAt }).from(gaDailyTotals).where(
|
|
76426
|
+
const rows2 = ctx.db.select({ date: gaDailyTotals.date, syncedAt: gaDailyTotals.syncedAt }).from(gaDailyTotals).where(eq110(gaDailyTotals.projectId, projectId)).all();
|
|
76342
76427
|
const latest2 = rows2.reduce((max2, row) => max2 === null || row.syncedAt > max2 ? row.syncedAt : max2, null);
|
|
76343
|
-
const summary3 = ctx.db.select({ start: gaTrafficSummaries.periodStart, end: gaTrafficSummaries.periodEnd, syncedAt: gaTrafficSummaries.syncedAt }).from(gaTrafficSummaries).where(
|
|
76428
|
+
const summary3 = ctx.db.select({ start: gaTrafficSummaries.periodStart, end: gaTrafficSummaries.periodEnd, syncedAt: gaTrafficSummaries.syncedAt }).from(gaTrafficSummaries).where(eq110(gaTrafficSummaries.projectId, projectId)).get();
|
|
76344
76429
|
if (summary3 && (latest2 === null || summary3.syncedAt >= latest2)) return { start: summary3.start, end: summary3.end, syncedAt: summary3.syncedAt };
|
|
76345
76430
|
const span2 = dateSpan(rows2.filter((row) => row.syncedAt === latest2).map((row) => row.date));
|
|
76346
76431
|
return span2 && latest2 !== null ? { ...span2, syncedAt: latest2 } : null;
|
|
76347
76432
|
}
|
|
76348
|
-
const rows = ctx.db.select({ date: gscDailyTotals.date, createdAt: gscDailyTotals.createdAt }).from(gscDailyTotals).where(
|
|
76433
|
+
const rows = ctx.db.select({ date: gscDailyTotals.date, createdAt: gscDailyTotals.createdAt }).from(gscDailyTotals).where(eq110(gscDailyTotals.projectId, projectId)).all();
|
|
76349
76434
|
const latest = rows.reduce((max2, row) => max2 === null || row.createdAt > max2 ? row.createdAt : max2, null);
|
|
76350
76435
|
const span = dateSpan(rows.filter((row) => row.createdAt === latest).map((row) => row.date));
|
|
76351
76436
|
if (!span || latest === null) return null;
|
|
76352
|
-
const watermark = ctx.db.select({ through: gscDataWatermarks.syncedThroughDate, updatedAt: gscDataWatermarks.updatedAt }).from(gscDataWatermarks).where(
|
|
76437
|
+
const watermark = ctx.db.select({ through: gscDataWatermarks.syncedThroughDate, updatedAt: gscDataWatermarks.updatedAt }).from(gscDataWatermarks).where(eq110(gscDataWatermarks.projectId, projectId)).get();
|
|
76353
76438
|
return watermark?.through && watermark.updatedAt === latest && watermark.through > span.end ? { start: span.start, end: watermark.through, syncedAt: latest } : { ...span, syncedAt: latest };
|
|
76354
76439
|
}
|
|
76355
76440
|
function dailyCoverage(ctx, month, source) {
|
|
76356
76441
|
const project = ctx.project;
|
|
76357
76442
|
const connection = source === "ga" ? ctx.ga4CredentialStore?.getConnection(project.name) ?? ctx.googleConnectionStore?.getConnection(project.canonicalDomain, "ga4") : ctx.googleConnectionStore?.getConnection(project.canonicalDomain, "gsc");
|
|
76358
|
-
const stored = source === "ga" ? ctx.db.select({ date: gaDailyTotals.date, count: gaDailyTotals.sessions }).from(gaDailyTotals).where(
|
|
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();
|
|
76359
76444
|
if (!connection && stored.length === 0) return null;
|
|
76360
76445
|
const bounds = calendarMonthBounds(month);
|
|
76361
76446
|
const start = bounds.since.slice(0, 10);
|
|
76362
76447
|
const end = bounds.until.slice(0, 10);
|
|
76363
76448
|
const timeZone = source === "gsc" ? "America/Los_Angeles" : "UTC";
|
|
76364
76449
|
const matureThrough = isoDateDaysBeforeInTimeZone((/* @__PURE__ */ new Date()).toISOString(), REPORTING_LAG_DAYS, timeZone);
|
|
76365
|
-
const created = ctx.db.select({ date: projects.createdAt }).from(projects).where(
|
|
76450
|
+
const created = ctx.db.select({ date: projects.createdAt }).from(projects).where(eq110(projects.id, project.id)).get().date.slice(0, 10);
|
|
76366
76451
|
const connectedAt = connection?.createdAt?.slice(0, 10) ?? created;
|
|
76367
76452
|
const onboardingDate = [connectedAt, ...stored.map((row) => row.date)].sort()[0];
|
|
76368
76453
|
const byDate = new Map(stored.map((row) => [row.date, row.count]));
|
|
@@ -76444,7 +76529,7 @@ var reportDailyDataCheck = {
|
|
|
76444
76529
|
};
|
|
76445
76530
|
|
|
76446
76531
|
// ../api-routes/src/doctor/checks/referral-assessment.ts
|
|
76447
|
-
import { and as
|
|
76532
|
+
import { and as and95, eq as eq111, ne as ne17 } from "drizzle-orm";
|
|
76448
76533
|
var REFERRAL_ASSESSMENT_CHECKS = [{
|
|
76449
76534
|
id: "report.ai-referral-bursts",
|
|
76450
76535
|
category: CheckCategories.integrations,
|
|
@@ -76453,7 +76538,7 @@ var REFERRAL_ASSESSMENT_CHECKS = [{
|
|
|
76453
76538
|
notificationPolicy: CheckNotificationPolicies.silent,
|
|
76454
76539
|
run: (ctx) => {
|
|
76455
76540
|
if (!ctx.project) return { status: CheckStatuses.skipped, code: "report.ai-referral-bursts.no-project", summary: "Select a project to inspect referral evidence." };
|
|
76456
|
-
const configured = ctx.db.select({ id: trafficSources.id }).from(trafficSources).where(
|
|
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();
|
|
76457
76542
|
if (!configured) {
|
|
76458
76543
|
return { status: CheckStatuses.skipped, code: "report.ai-referral-bursts.not-configured", summary: "No non-archived server traffic source is configured for this project." };
|
|
76459
76544
|
}
|
|
@@ -76865,17 +76950,17 @@ var BACKLINKS_CHECKS = [
|
|
|
76865
76950
|
];
|
|
76866
76951
|
|
|
76867
76952
|
// ../api-routes/src/doctor/checks/bing-auth.ts
|
|
76868
|
-
import { and as
|
|
76953
|
+
import { and as and96, desc as desc50, eq as eq112, inArray as inArray52 } from "drizzle-orm";
|
|
76869
76954
|
var BING_CONNECTION_ENTITY = "bing_connection";
|
|
76870
76955
|
var BING_CONNECTED_ACTION = "bing.connected";
|
|
76871
76956
|
var BING_DISCONNECTED_ACTION = "bing.disconnected";
|
|
76872
76957
|
function lostBingConnection(ctx, project) {
|
|
76873
76958
|
const hasRow = (row) => row !== void 0;
|
|
76874
|
-
const storedData = hasRow(ctx.db.select({ id: bingCoverageSnapshots.id }).from(bingCoverageSnapshots).where(
|
|
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());
|
|
76875
76960
|
if (!storedData) return false;
|
|
76876
|
-
const lastChange = ctx.db.select({ action: auditLog.action }).from(auditLog).where(
|
|
76877
|
-
|
|
76878
|
-
|
|
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),
|
|
76879
76964
|
inArray52(auditLog.action, [BING_CONNECTED_ACTION, BING_DISCONNECTED_ACTION])
|
|
76880
76965
|
)).orderBy(desc50(auditLog.createdAt)).limit(1).get();
|
|
76881
76966
|
return lastChange?.action !== BING_DISCONNECTED_ACTION;
|
|
@@ -77034,7 +77119,7 @@ var BING_AUTH_CHECKS = [
|
|
|
77034
77119
|
];
|
|
77035
77120
|
|
|
77036
77121
|
// ../api-routes/src/doctor/checks/content.ts
|
|
77037
|
-
import { eq as
|
|
77122
|
+
import { eq as eq113 } from "drizzle-orm";
|
|
77038
77123
|
var WINNABILITY_COVERAGE_WARN_THRESHOLD = 0.8;
|
|
77039
77124
|
var UNCLASSIFIED_DOMAIN_SAMPLE_LIMIT = 10;
|
|
77040
77125
|
function skippedNoProject2() {
|
|
@@ -77047,7 +77132,7 @@ function skippedNoProject2() {
|
|
|
77047
77132
|
}
|
|
77048
77133
|
function loadProject(ctx) {
|
|
77049
77134
|
if (!ctx.project) return null;
|
|
77050
|
-
return ctx.db.select().from(projects).where(
|
|
77135
|
+
return ctx.db.select().from(projects).where(eq113(projects.id, ctx.project.id)).get() ?? null;
|
|
77051
77136
|
}
|
|
77052
77137
|
var winnabilityCoverageCheck = {
|
|
77053
77138
|
id: "content.winnability.coverage",
|
|
@@ -77140,7 +77225,7 @@ var CONTENT_CHECK_BY_ID = Object.fromEntries(
|
|
|
77140
77225
|
);
|
|
77141
77226
|
|
|
77142
77227
|
// ../api-routes/src/doctor/checks/ads.ts
|
|
77143
|
-
import { eq as
|
|
77228
|
+
import { eq as eq114 } from "drizzle-orm";
|
|
77144
77229
|
var ADS_RECENT_SYNC_WARN_DAYS = 7;
|
|
77145
77230
|
var ADS_RECENT_SYNC_FAIL_DAYS = 30;
|
|
77146
77231
|
var adsConnectionCheck = {
|
|
@@ -77157,7 +77242,7 @@ var adsConnectionCheck = {
|
|
|
77157
77242
|
remediation: null
|
|
77158
77243
|
};
|
|
77159
77244
|
}
|
|
77160
|
-
const row = ctx.db.select().from(adsConnections).where(
|
|
77245
|
+
const row = ctx.db.select().from(adsConnections).where(eq114(adsConnections.projectId, ctx.project.id)).get();
|
|
77161
77246
|
if (!row) {
|
|
77162
77247
|
return {
|
|
77163
77248
|
status: CheckStatuses.skipped,
|
|
@@ -77207,7 +77292,7 @@ var adsRecentSyncCheck = {
|
|
|
77207
77292
|
remediation: null
|
|
77208
77293
|
};
|
|
77209
77294
|
}
|
|
77210
|
-
const row = ctx.db.select().from(adsConnections).where(
|
|
77295
|
+
const row = ctx.db.select().from(adsConnections).where(eq114(adsConnections.projectId, ctx.project.id)).get();
|
|
77211
77296
|
if (!row) {
|
|
77212
77297
|
return {
|
|
77213
77298
|
status: CheckStatuses.skipped,
|
|
@@ -77422,7 +77507,7 @@ var ga4ConnectionCheck = {
|
|
|
77422
77507
|
var GA_AUTH_CHECKS = [ga4ConnectionCheck];
|
|
77423
77508
|
|
|
77424
77509
|
// ../api-routes/src/doctor/checks/data-freshness.ts
|
|
77425
|
-
import { and as
|
|
77510
|
+
import { and as and97, desc as desc51, eq as eq115, inArray as inArray53 } from "drizzle-orm";
|
|
77426
77511
|
var GA_DATA_AGING_DAYS = 3;
|
|
77427
77512
|
var GA_DATA_STALE_DAYS = 5;
|
|
77428
77513
|
var GSC_DATA_AGING_DAYS = 5;
|
|
@@ -77452,7 +77537,7 @@ function skipped(code, summary3) {
|
|
|
77452
77537
|
return { status: CheckStatuses.skipped, code, summary: summary3, remediation: null };
|
|
77453
77538
|
}
|
|
77454
77539
|
function lastSyncAgeDays(ctx, kinds) {
|
|
77455
|
-
const row = ctx.db.select({ createdAt: runs.createdAt }).from(runs).where(
|
|
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();
|
|
77456
77541
|
if (!row?.createdAt) return null;
|
|
77457
77542
|
const age = Math.floor((Date.now() - Date.parse(row.createdAt)) / DAY_MS6);
|
|
77458
77543
|
return Number.isFinite(age) ? age : null;
|
|
@@ -77554,7 +77639,7 @@ var gaRecentDataCheck = {
|
|
|
77554
77639
|
const connection = gaConnected(ctx);
|
|
77555
77640
|
if (connection === "store-unavailable") return skipped("ga.data.store-unavailable", "No GA4 credential store configured for this deployment.");
|
|
77556
77641
|
if (connection === "not-connected") return skipped("ga.data.not-connected", "GA4 is not connected for this project.");
|
|
77557
|
-
const newest = ctx.db.select({ date: gaDailyTotals.date }).from(gaDailyTotals).where(
|
|
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();
|
|
77558
77643
|
return grade(ctx, GA_SPEC, newest?.date);
|
|
77559
77644
|
}
|
|
77560
77645
|
};
|
|
@@ -77569,16 +77654,16 @@ var gscRecentDataCheck = {
|
|
|
77569
77654
|
if (!ctx.googleConnectionStore.getConnection(ctx.project.canonicalDomain, "gsc")) {
|
|
77570
77655
|
return skipped("gsc.data.not-connected", "Search Console is not connected for this project.");
|
|
77571
77656
|
}
|
|
77572
|
-
const watermark = ctx.db.select({ dataThroughDate: gscDataWatermarks.dataThroughDate }).from(gscDataWatermarks).where(
|
|
77657
|
+
const watermark = ctx.db.select({ dataThroughDate: gscDataWatermarks.dataThroughDate }).from(gscDataWatermarks).where(eq115(gscDataWatermarks.projectId, ctx.project.id)).get();
|
|
77573
77658
|
if (watermark?.dataThroughDate) return grade(ctx, GSC_SPEC, watermark.dataThroughDate);
|
|
77574
|
-
const newest = ctx.db.select({ date: gscDailyTotals.date }).from(gscDailyTotals).where(
|
|
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();
|
|
77575
77660
|
return grade(ctx, GSC_SPEC, newest?.date);
|
|
77576
77661
|
}
|
|
77577
77662
|
};
|
|
77578
77663
|
var DATA_FRESHNESS_CHECKS = [gaRecentDataCheck, gscRecentDataCheck];
|
|
77579
77664
|
|
|
77580
77665
|
// ../api-routes/src/doctor/checks/seo-refresh.ts
|
|
77581
|
-
import { and as
|
|
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";
|
|
77582
77667
|
var GRACE_DAYS = 2;
|
|
77583
77668
|
var DAY_MS7 = 24 * 60 * 60 * 1e3;
|
|
77584
77669
|
var FIRING_SPAN_MS = 6e4;
|
|
@@ -77587,7 +77672,7 @@ function skipped2(code, summary3) {
|
|
|
77587
77672
|
return { status: CheckStatuses.skipped, code, summary: summary3, remediation: null };
|
|
77588
77673
|
}
|
|
77589
77674
|
function seoSyncRuns(projectId) {
|
|
77590
|
-
return
|
|
77675
|
+
return and98(eq116(runs.projectId, projectId), eq116(runs.kind, RunKinds["seo-sync"]));
|
|
77591
77676
|
}
|
|
77592
77677
|
function scheduleTiming(schedule) {
|
|
77593
77678
|
if (!schedule.recurrence) return { cronExpr: schedule.cronExpr, timezone: schedule.timezone, recurrence: null };
|
|
@@ -77595,16 +77680,16 @@ function scheduleTiming(schedule) {
|
|
|
77595
77680
|
return recurrence ? { cronExpr: schedule.cronExpr, timezone: schedule.timezone, recurrence } : null;
|
|
77596
77681
|
}
|
|
77597
77682
|
function latestFiring(ctx, projectId, enabledSince) {
|
|
77598
|
-
const scheduled =
|
|
77683
|
+
const scheduled = and98(seoSyncRuns(projectId), eq116(runs.trigger, RunTriggers.scheduled), gt9(runs.createdAt, enabledSince));
|
|
77599
77684
|
const newest = ctx.db.select({ createdAt: runs.createdAt }).from(runs).where(scheduled).orderBy(desc52(runs.createdAt)).limit(1).get();
|
|
77600
77685
|
if (!newest) return [];
|
|
77601
77686
|
const newestMs = Date.parse(newest.createdAt);
|
|
77602
77687
|
const after = Number.isFinite(newestMs) ? new Date(newestMs - FIRING_SPAN_MS).toISOString() : newest.createdAt;
|
|
77603
|
-
return ctx.db.select({ id: runs.id, status: runs.status, error: runs.error, createdAt: runs.createdAt }).from(runs).where(
|
|
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();
|
|
77604
77689
|
}
|
|
77605
77690
|
function lastCompleted(ctx, projectId) {
|
|
77606
77691
|
const at = sql49`coalesce(${runs.finishedAt}, ${runs.createdAt})`;
|
|
77607
|
-
return ctx.db.select({ id: runs.id, at }).from(runs).where(
|
|
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;
|
|
77608
77693
|
}
|
|
77609
77694
|
function isIncomplete(run) {
|
|
77610
77695
|
return run.status === RunStatuses.failed || run.status === RunStatuses.partial;
|
|
@@ -77618,7 +77703,7 @@ function unsettledRuns(ctx, projectId, firing, profiles) {
|
|
|
77618
77703
|
const incomplete = firing.filter(isIncomplete);
|
|
77619
77704
|
const firedAt = firing[firing.length - 1]?.createdAt;
|
|
77620
77705
|
if (incomplete.length === 0 || !firedAt) return incomplete;
|
|
77621
|
-
const refreshed = new Set(ctx.db.select({ profileId: seoJobs.profileId }).from(runs).innerJoin(seoJobs,
|
|
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));
|
|
77622
77707
|
return incomplete.filter((run) => {
|
|
77623
77708
|
const profile = profiles.get(run.id) ?? null;
|
|
77624
77709
|
return profile === null ? refreshed.size === 0 : !refreshed.has(profile);
|
|
@@ -77628,7 +77713,7 @@ var COUNT_LIST = new Intl.ListFormat("en", { style: "long", type: "conjunction"
|
|
|
77628
77713
|
function refreshReason(ctx, run) {
|
|
77629
77714
|
const stored = parseRunError(run.error);
|
|
77630
77715
|
if (stored) return formatRunErrorOneLine(stored);
|
|
77631
|
-
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,
|
|
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());
|
|
77632
77717
|
const failed = tasks.filter((task) => task.status === SeoRunStatuses.failed || task.status === SeoRunStatuses["reconciliation-required"]);
|
|
77633
77718
|
const partial = tasks.filter((task) => task.status === SeoRunStatuses.partial).length;
|
|
77634
77719
|
const cancelled = tasks.filter((task) => task.status === SeoRunStatuses.cancelled).length;
|
|
@@ -77648,7 +77733,7 @@ function refreshReason(ctx, run) {
|
|
|
77648
77733
|
return `Of ${tasks.length} ${unit}, ${COUNT_LIST.format(counts2)}.${errors ? ` ${errors}` : ""}`;
|
|
77649
77734
|
}
|
|
77650
77735
|
function gradeSeoRefresh(ctx, project) {
|
|
77651
|
-
const schedule = ctx.db.select().from(schedules).where(
|
|
77736
|
+
const schedule = ctx.db.select().from(schedules).where(and98(eq116(schedules.projectId, project.id), eq116(schedules.kind, SchedulableRunKinds["seo-sync"]))).get();
|
|
77652
77737
|
if (!schedule) return skipped2("seo.data.not-scheduled", "No SEO refresh schedule is set for this project.");
|
|
77653
77738
|
if (!schedule.enabled) return skipped2("seo.data.not-scheduled", "The SEO refresh schedule is disabled.");
|
|
77654
77739
|
const name = project.name;
|
|
@@ -77720,7 +77805,7 @@ function gradeSeoRefresh(ctx, project) {
|
|
|
77720
77805
|
};
|
|
77721
77806
|
}
|
|
77722
77807
|
if (now >= Date.parse(deadlineAt)) {
|
|
77723
|
-
const active = ctx.db.select({ id: runs.id, createdAt: runs.createdAt }).from(runs).where(
|
|
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();
|
|
77724
77809
|
const since = last ? `No SEO refresh has completed since ${day(last.at)}.` : "No SEO refresh has completed since the schedule was enabled.";
|
|
77725
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.`;
|
|
77726
77811
|
return {
|
|
@@ -78030,7 +78115,7 @@ var siteReachabilityCheck = {
|
|
|
78030
78115
|
var SITE_REACHABILITY_CHECKS = [siteReachabilityCheck];
|
|
78031
78116
|
|
|
78032
78117
|
// ../api-routes/src/doctor/checks/api-hosts.ts
|
|
78033
|
-
import { eq as
|
|
78118
|
+
import { eq as eq118 } from "drizzle-orm";
|
|
78034
78119
|
|
|
78035
78120
|
// ../api-routes/src/api-host-probe.ts
|
|
78036
78121
|
import dns4 from "dns/promises";
|
|
@@ -78136,7 +78221,7 @@ async function probeApiHost(host, options = {}) {
|
|
|
78136
78221
|
}
|
|
78137
78222
|
|
|
78138
78223
|
// ../api-routes/src/doctor/checks/integration-sync.ts
|
|
78139
|
-
import { and as
|
|
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";
|
|
78140
78225
|
var SYNC_FAILURE_WINDOW = 3;
|
|
78141
78226
|
var SUMMARY_ERROR_LIMIT = 300;
|
|
78142
78227
|
var FINISHED_STATUSES = [RunStatuses.completed, RunStatuses.partial, RunStatuses.failed];
|
|
@@ -78163,7 +78248,7 @@ function gscConnection(ctx, project) {
|
|
|
78163
78248
|
function gbpConnection(ctx, project) {
|
|
78164
78249
|
if (!ctx.googleConnectionStore) return { state: "store-unavailable" };
|
|
78165
78250
|
if (!ctx.googleConnectionStore.getConnection(project.canonicalDomain, "gbp")) return { state: "not-connected" };
|
|
78166
|
-
const selected = ctx.db.select({ locationName: gbpLocations.locationName }).from(gbpLocations).where(
|
|
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();
|
|
78167
78252
|
return selected ? CONNECTED : { state: "no-selected-locations" };
|
|
78168
78253
|
}
|
|
78169
78254
|
function gaConnection(ctx, project) {
|
|
@@ -78236,16 +78321,16 @@ function latestErrorText(raw) {
|
|
|
78236
78321
|
return parsed ? formatRunErrorOneLine(parsed) : "no error was recorded";
|
|
78237
78322
|
}
|
|
78238
78323
|
function readSyncRunState(db, projectId, kind, options = {}) {
|
|
78239
|
-
const scope =
|
|
78240
|
-
|
|
78241
|
-
|
|
78242
|
-
...options.sourceId ? [
|
|
78243
|
-
...options.nothingToSyncErrors?.length ? [or21(isNull18(runs.error),
|
|
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]))] : []
|
|
78244
78329
|
);
|
|
78245
|
-
const graded = options.since ?
|
|
78246
|
-
const recent = db.select({ id: runs.id, status: runs.status, trigger: runs.trigger, error: runs.error, createdAt: runs.createdAt }).from(runs).where(
|
|
78247
|
-
const lastSuccess = db.select({ createdAt: runs.createdAt, finishedAt: runs.finishedAt }).from(runs).where(
|
|
78248
|
-
const failureCount = db.select({ count: count9() }).from(runs).where(
|
|
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();
|
|
78249
78334
|
const failuresSinceSuccess = Number(failureCount?.count ?? 0);
|
|
78250
78335
|
const latest = recent[0];
|
|
78251
78336
|
return {
|
|
@@ -78342,7 +78427,7 @@ function connectionFor(prefix, ctx, project) {
|
|
|
78342
78427
|
if (prefix === "google-ads") return googleMarketingConnection("googleAds")(ctx);
|
|
78343
78428
|
if (prefix === "gtm") return googleMarketingConnection("gtm")(ctx);
|
|
78344
78429
|
if (prefix === "bing") return ctx.bingConnectionStore?.getConnection(project.canonicalDomain) ? { state: "connected", since: null } : { state: "not-connected" };
|
|
78345
|
-
return ctx.db.select({ id: adsConnections.id }).from(adsConnections).where(
|
|
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" };
|
|
78346
78431
|
}
|
|
78347
78432
|
function syncCommand(prefix) {
|
|
78348
78433
|
if (prefix === "gsc") return "google sync";
|
|
@@ -78387,7 +78472,7 @@ function definition(prefix) {
|
|
|
78387
78472
|
var API_HOST_CHECKS = Object.keys(API_HOST_TABLE).map(definition);
|
|
78388
78473
|
|
|
78389
78474
|
// ../api-routes/src/doctor/checks/gbp-auth.ts
|
|
78390
|
-
import { and as
|
|
78475
|
+
import { and as and100, eq as eq119 } from "drizzle-orm";
|
|
78391
78476
|
var RECENT_SYNC_WARN_DAYS = 4;
|
|
78392
78477
|
var RECENT_SYNC_FAIL_DAYS = 30;
|
|
78393
78478
|
function skippedNoProject3() {
|
|
@@ -78407,7 +78492,7 @@ function storeUnavailable() {
|
|
|
78407
78492
|
};
|
|
78408
78493
|
}
|
|
78409
78494
|
function hasSelectedLocation(ctx, projectId) {
|
|
78410
|
-
return !!ctx.db.select({ id: gbpLocations.id }).from(gbpLocations).where(
|
|
78495
|
+
return !!ctx.db.select({ id: gbpLocations.id }).from(gbpLocations).where(and100(eq119(gbpLocations.projectId, projectId), eq119(gbpLocations.selected, true))).limit(1).get();
|
|
78411
78496
|
}
|
|
78412
78497
|
async function resolveGbpToken(ctx) {
|
|
78413
78498
|
if (!ctx.project) return { ok: false, output: skippedNoProject3() };
|
|
@@ -78667,7 +78752,7 @@ var recentSyncCheck = {
|
|
|
78667
78752
|
title: "GBP recent sync",
|
|
78668
78753
|
run: (ctx) => {
|
|
78669
78754
|
if (!ctx.project) return skippedNoProject3();
|
|
78670
|
-
const selected = ctx.db.select({ locationName: gbpLocations.locationName, syncedAt: gbpLocations.syncedAt }).from(gbpLocations).where(
|
|
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();
|
|
78671
78756
|
if (selected.length === 0) {
|
|
78672
78757
|
return {
|
|
78673
78758
|
status: CheckStatuses.skipped,
|
|
@@ -78727,7 +78812,7 @@ var GBP_AUTH_CHECK_BY_ID = Object.fromEntries(
|
|
|
78727
78812
|
);
|
|
78728
78813
|
|
|
78729
78814
|
// ../api-routes/src/doctor/checks/places.ts
|
|
78730
|
-
import { eq as
|
|
78815
|
+
import { eq as eq120 } from "drizzle-orm";
|
|
78731
78816
|
var apiKeyCheck = {
|
|
78732
78817
|
id: "gbp.places.api-key",
|
|
78733
78818
|
category: CheckCategories.auth,
|
|
@@ -78772,7 +78857,7 @@ var apiKeyCheck = {
|
|
|
78772
78857
|
details: { tier: cfg.tier }
|
|
78773
78858
|
};
|
|
78774
78859
|
}
|
|
78775
|
-
const rows = ctx.db.select({ placeId: gbpLocations.placeId, selected: gbpLocations.selected }).from(gbpLocations).where(
|
|
78860
|
+
const rows = ctx.db.select({ placeId: gbpLocations.placeId, selected: gbpLocations.selected }).from(gbpLocations).where(eq120(gbpLocations.projectId, ctx.project.id)).all();
|
|
78776
78861
|
const selected = rows.filter((r) => r.selected);
|
|
78777
78862
|
const locationsWithPlaceId = selected.filter((r) => Boolean(r.placeId)).length;
|
|
78778
78863
|
const details = {
|
|
@@ -78805,7 +78890,7 @@ var PLACES_CHECK_BY_ID = Object.fromEntries(
|
|
|
78805
78890
|
);
|
|
78806
78891
|
|
|
78807
78892
|
// ../api-routes/src/doctor/checks/gbp-reviews.ts
|
|
78808
|
-
import { and as
|
|
78893
|
+
import { and as and101, desc as desc54, eq as eq121, gte as gte31, inArray as inArray56, sql as sql50 } from "drizzle-orm";
|
|
78809
78894
|
var REVIEW_EVENTS = /* @__PURE__ */ new Set(["review.negative", "review.rating-dropped"]);
|
|
78810
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`.";
|
|
78811
78896
|
var reviewsAccessCheck = {
|
|
@@ -78833,7 +78918,7 @@ var reviewsAccessCheck = {
|
|
|
78833
78918
|
reviewsAccess: gbpLocations.reviewsAccess,
|
|
78834
78919
|
reviewsAccessReason: gbpLocations.reviewsAccessReason,
|
|
78835
78920
|
reviewsCheckedAt: gbpLocations.reviewsCheckedAt
|
|
78836
|
-
}).from(gbpLocations).where(
|
|
78921
|
+
}).from(gbpLocations).where(and101(eq121(gbpLocations.projectId, project.id), eq121(gbpLocations.selected, true))).all();
|
|
78837
78922
|
if (locations.length === 0) {
|
|
78838
78923
|
return {
|
|
78839
78924
|
status: CheckStatuses.skipped,
|
|
@@ -78853,7 +78938,7 @@ var reviewsAccessCheck = {
|
|
|
78853
78938
|
const places = ctx.getPlacesConfig?.();
|
|
78854
78939
|
const placesFallback = places !== void 0 && places.tier === "atmosphere" && Boolean(places.apiKey);
|
|
78855
78940
|
const v4Worked = new Set(
|
|
78856
|
-
ctx.db.select({ locationName: gbpReviewRatings.locationName }).from(gbpReviewRatings).where(
|
|
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)
|
|
78857
78942
|
);
|
|
78858
78943
|
const coverageOf = (loc) => {
|
|
78859
78944
|
if (businessProfileReviewsCover(loc.reviewsAccess ?? null, v4Worked.has(loc.locationName))) return "full";
|
|
@@ -78887,7 +78972,7 @@ var reviewsAccessCheck = {
|
|
|
78887
78972
|
none > 0 ? `${none} have no review source` : null
|
|
78888
78973
|
].filter((part) => part !== null);
|
|
78889
78974
|
const summary3 = `Business Profile reviews are not available${why}. ${parts.join("; ")}.`;
|
|
78890
|
-
const subscribed = ctx.db.select({ config: notifications.config, enabled: notifications.enabled }).from(notifications).where(
|
|
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)));
|
|
78891
78976
|
const placesHint = placesFallback ? "" : " For partial coverage meanwhile, set a Places API key (`GOOGLE_PLACES_API_KEY` or `places.apiKey`) with `places.tier: atmosphere`.";
|
|
78892
78977
|
if (none > 0 && subscribed) {
|
|
78893
78978
|
return {
|
|
@@ -78926,8 +79011,8 @@ var reviewDeliveryCheck = {
|
|
|
78926
79011
|
attempts: reviewWebhookDeliveries.attempts,
|
|
78927
79012
|
lastTouched,
|
|
78928
79013
|
payload: reviewWebhookDeliveries.payload
|
|
78929
|
-
}).from(reviewWebhookDeliveries).where(
|
|
78930
|
-
|
|
79014
|
+
}).from(reviewWebhookDeliveries).where(and101(
|
|
79015
|
+
eq121(reviewWebhookDeliveries.projectId, ctx.project.id),
|
|
78931
79016
|
inArray56(reviewWebhookDeliveries.state, [ReviewDeliveryStates.Uncertain, ReviewDeliveryStates.Failed]),
|
|
78932
79017
|
gte31(lastTouched, since)
|
|
78933
79018
|
)).orderBy(desc54(lastTouched)).all();
|
|
@@ -78939,7 +79024,7 @@ var reviewDeliveryCheck = {
|
|
|
78939
79024
|
remediation: null
|
|
78940
79025
|
};
|
|
78941
79026
|
}
|
|
78942
|
-
const destinations = new Map(ctx.db.select({ id: notifications.id, config: notifications.config }).from(notifications).where(
|
|
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]));
|
|
78943
79028
|
const deliveries = rows.map((row) => {
|
|
78944
79029
|
const review = row.payload.reviews[0];
|
|
78945
79030
|
return {
|
|
@@ -79513,14 +79598,9 @@ var RUNTIME_STATE_CHECKS = [
|
|
|
79513
79598
|
];
|
|
79514
79599
|
|
|
79515
79600
|
// ../api-routes/src/doctor/checks/traffic-source.ts
|
|
79516
|
-
import { and as
|
|
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";
|
|
79517
79602
|
var RECENT_DATA_WARN_DAYS = 7;
|
|
79518
79603
|
var RECENT_DATA_FAIL_DAYS = 30;
|
|
79519
|
-
function isCloudflareDirectPush(source) {
|
|
79520
|
-
if (source.sourceType !== TrafficSourceTypes.cloudflare) return false;
|
|
79521
|
-
const deliveryMode = source.configJson.deliveryMode;
|
|
79522
|
-
return deliveryMode === void 0 || deliveryMode === CloudflareTrafficDeliveryModes["direct-push"];
|
|
79523
|
-
}
|
|
79524
79604
|
function isCloudflareQueuePull(source) {
|
|
79525
79605
|
return source.sourceType === TrafficSourceTypes.cloudflare && source.configJson.deliveryMode === CloudflareTrafficDeliveryModes["queue-pull"];
|
|
79526
79606
|
}
|
|
@@ -79552,8 +79632,8 @@ function skippedNoProject5() {
|
|
|
79552
79632
|
function loadProbes(ctx) {
|
|
79553
79633
|
if (!ctx.project) return [];
|
|
79554
79634
|
const rows = ctx.db.select().from(trafficSources).where(
|
|
79555
|
-
|
|
79556
|
-
|
|
79635
|
+
and102(
|
|
79636
|
+
eq122(trafficSources.projectId, ctx.project.id),
|
|
79557
79637
|
ne18(trafficSources.status, TrafficSourceStatuses.archived)
|
|
79558
79638
|
)
|
|
79559
79639
|
).all();
|
|
@@ -79716,8 +79796,8 @@ var recentDataCheck = {
|
|
|
79716
79796
|
const failCutoff = new Date(now.getTime() - RECENT_DATA_FAIL_DAYS * 24 * 60 * 6e4).toISOString();
|
|
79717
79797
|
const recentCrawlers = Number(
|
|
79718
79798
|
ctx.db.select({ total: sql51`COALESCE(SUM(${crawlerEventsHourly.hits}), 0)` }).from(crawlerEventsHourly).where(
|
|
79719
|
-
|
|
79720
|
-
|
|
79799
|
+
and102(
|
|
79800
|
+
eq122(crawlerEventsHourly.projectId, ctx.project.id),
|
|
79721
79801
|
inArray57(crawlerEventsHourly.sourceId, activeSourceIds),
|
|
79722
79802
|
gte32(crawlerEventsHourly.tsHour, warnCutoff)
|
|
79723
79803
|
)
|
|
@@ -79725,8 +79805,8 @@ var recentDataCheck = {
|
|
|
79725
79805
|
);
|
|
79726
79806
|
const recentReferrals = Number(
|
|
79727
79807
|
ctx.db.select({ total: sql51`COALESCE(SUM(${aiReferralEventsHourly.sessionsOrHits}), 0)` }).from(aiReferralEventsHourly).where(
|
|
79728
|
-
|
|
79729
|
-
|
|
79808
|
+
and102(
|
|
79809
|
+
eq122(aiReferralEventsHourly.projectId, ctx.project.id),
|
|
79730
79810
|
inArray57(aiReferralEventsHourly.sourceId, activeSourceIds),
|
|
79731
79811
|
gte32(aiReferralEventsHourly.tsHour, warnCutoff)
|
|
79732
79812
|
)
|
|
@@ -79734,8 +79814,8 @@ var recentDataCheck = {
|
|
|
79734
79814
|
);
|
|
79735
79815
|
const recentUserFetches = Number(
|
|
79736
79816
|
ctx.db.select({ total: sql51`COALESCE(SUM(${aiUserFetchEventsHourly.hits}), 0)` }).from(aiUserFetchEventsHourly).where(
|
|
79737
|
-
|
|
79738
|
-
|
|
79817
|
+
and102(
|
|
79818
|
+
eq122(aiUserFetchEventsHourly.projectId, ctx.project.id),
|
|
79739
79819
|
inArray57(aiUserFetchEventsHourly.sourceId, activeSourceIds),
|
|
79740
79820
|
gte32(aiUserFetchEventsHourly.tsHour, warnCutoff)
|
|
79741
79821
|
)
|
|
@@ -79760,8 +79840,8 @@ var recentDataCheck = {
|
|
|
79760
79840
|
}
|
|
79761
79841
|
const olderCrawlers = Number(
|
|
79762
79842
|
ctx.db.select({ total: sql51`COALESCE(SUM(${crawlerEventsHourly.hits}), 0)` }).from(crawlerEventsHourly).where(
|
|
79763
|
-
|
|
79764
|
-
|
|
79843
|
+
and102(
|
|
79844
|
+
eq122(crawlerEventsHourly.projectId, ctx.project.id),
|
|
79765
79845
|
inArray57(crawlerEventsHourly.sourceId, activeSourceIds),
|
|
79766
79846
|
gte32(crawlerEventsHourly.tsHour, failCutoff)
|
|
79767
79847
|
)
|
|
@@ -79769,8 +79849,8 @@ var recentDataCheck = {
|
|
|
79769
79849
|
);
|
|
79770
79850
|
const olderReferrals = Number(
|
|
79771
79851
|
ctx.db.select({ total: sql51`COALESCE(SUM(${aiReferralEventsHourly.sessionsOrHits}), 0)` }).from(aiReferralEventsHourly).where(
|
|
79772
|
-
|
|
79773
|
-
|
|
79852
|
+
and102(
|
|
79853
|
+
eq122(aiReferralEventsHourly.projectId, ctx.project.id),
|
|
79774
79854
|
inArray57(aiReferralEventsHourly.sourceId, activeSourceIds),
|
|
79775
79855
|
gte32(aiReferralEventsHourly.tsHour, failCutoff)
|
|
79776
79856
|
)
|
|
@@ -79778,8 +79858,8 @@ var recentDataCheck = {
|
|
|
79778
79858
|
);
|
|
79779
79859
|
const olderUserFetches = Number(
|
|
79780
79860
|
ctx.db.select({ total: sql51`COALESCE(SUM(${aiUserFetchEventsHourly.hits}), 0)` }).from(aiUserFetchEventsHourly).where(
|
|
79781
|
-
|
|
79782
|
-
|
|
79861
|
+
and102(
|
|
79862
|
+
eq122(aiUserFetchEventsHourly.projectId, ctx.project.id),
|
|
79783
79863
|
inArray57(aiUserFetchEventsHourly.sourceId, activeSourceIds),
|
|
79784
79864
|
gte32(aiUserFetchEventsHourly.tsHour, failCutoff)
|
|
79785
79865
|
)
|
|
@@ -80106,10 +80186,10 @@ var syncLagCheck = {
|
|
|
80106
80186
|
}
|
|
80107
80187
|
};
|
|
80108
80188
|
function lastQueueStopReason(ctx, sourceId) {
|
|
80109
|
-
const row = ctx.db.select({ syncSummary: runs.syncSummary }).from(runs).where(
|
|
80110
|
-
|
|
80111
|
-
|
|
80112
|
-
|
|
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),
|
|
80113
80193
|
isNotNull11(runs.syncSummary)
|
|
80114
80194
|
)).orderBy(desc55(runs.createdAt)).limit(1).get();
|
|
80115
80195
|
return row?.syncSummary?.type === "cloudflare-queue" ? row.syncSummary.stopReason : null;
|
|
@@ -80909,7 +80989,7 @@ async function doctorRoutes(app, opts) {
|
|
|
80909
80989
|
}
|
|
80910
80990
|
|
|
80911
80991
|
// ../api-routes/src/status.ts
|
|
80912
|
-
import { and as
|
|
80992
|
+
import { and as and103, desc as desc56, eq as eq123, isNull as isNull19 } from "drizzle-orm";
|
|
80913
80993
|
function ageDays(iso2) {
|
|
80914
80994
|
if (!iso2) return null;
|
|
80915
80995
|
const ms = Date.now() - Date.parse(iso2);
|
|
@@ -80959,7 +81039,7 @@ function makeRow(integration, label, runKind, state, staleAfterDays, dataThrough
|
|
|
80959
81039
|
};
|
|
80960
81040
|
}
|
|
80961
81041
|
function latestDate2(db, table, projectId) {
|
|
80962
|
-
const row = db.select({ date: table.date }).from(table).where(
|
|
81042
|
+
const row = db.select({ date: table.date }).from(table).where(eq123(table.projectId, projectId)).orderBy(desc56(table.date)).limit(1).get();
|
|
80963
81043
|
return row?.date ?? null;
|
|
80964
81044
|
}
|
|
80965
81045
|
function projectRows(opts, project) {
|
|
@@ -80974,7 +81054,7 @@ function projectRows(opts, project) {
|
|
|
80974
81054
|
const rows = [];
|
|
80975
81055
|
const gsc = gscConnection(ctx, info);
|
|
80976
81056
|
if (connected(gsc)) {
|
|
80977
|
-
const watermarkRow = opts.db.select({ dataThroughDate: gscDataWatermarks.dataThroughDate }).from(gscDataWatermarks).where(
|
|
81057
|
+
const watermarkRow = opts.db.select({ dataThroughDate: gscDataWatermarks.dataThroughDate }).from(gscDataWatermarks).where(eq123(gscDataWatermarks.projectId, project.id)).limit(1).get();
|
|
80978
81058
|
const state = readSyncRunState(opts.db, project.id, RunKinds["gsc-sync"], { since: gsc.since });
|
|
80979
81059
|
const dataThrough = watermarkRow?.dataThroughDate ?? latestDate2(opts.db, gscDailyTotals, project.id);
|
|
80980
81060
|
rows.push(makeRow("gsc", "Search Console", RunKinds["gsc-sync"], state, SYNC_IDLE_DAYS, dataThrough, null, ["gsc.sync.recent-failures"], GSC_DATA_AGING_DAYS));
|
|
@@ -80990,12 +81070,12 @@ function projectRows(opts, project) {
|
|
|
80990
81070
|
rows.push(makeRow("bing", "Bing Webmaster Tools", RunKinds["bing-inspect-sitemap"], readSyncRunState(opts.db, project.id, RunKinds["bing-inspect-sitemap"]), null));
|
|
80991
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));
|
|
80992
81072
|
}
|
|
80993
|
-
const ads = opts.db.select({ id: adsConnections.id, lastSyncedAt: adsConnections.lastSyncedAt }).from(adsConnections).where(
|
|
81073
|
+
const ads = opts.db.select({ id: adsConnections.id, lastSyncedAt: adsConnections.lastSyncedAt }).from(adsConnections).where(eq123(adsConnections.projectId, project.id)).limit(1).get();
|
|
80994
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));
|
|
80995
81075
|
const marketing = opts.getGoogleMarketingDoctorInput?.(ctx);
|
|
80996
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));
|
|
80997
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));
|
|
80998
|
-
const sources = opts.db.select().from(trafficSources).where(
|
|
81078
|
+
const sources = opts.db.select().from(trafficSources).where(and103(eq123(trafficSources.projectId, project.id), isNull19(trafficSources.archivedAt))).all();
|
|
80999
81079
|
for (const source of sources) {
|
|
81000
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"]);
|
|
81001
81081
|
const lag = source.lastSyncedAt ? Date.now() - Date.parse(source.lastSyncedAt) : Number.POSITIVE_INFINITY;
|
|
@@ -81007,7 +81087,7 @@ function projectRows(opts, project) {
|
|
|
81007
81087
|
}
|
|
81008
81088
|
function projectStatus(opts, project) {
|
|
81009
81089
|
const integrations = projectRows(opts, project);
|
|
81010
|
-
const healthRow = opts.db.select().from(doctorHealthState).where(
|
|
81090
|
+
const healthRow = opts.db.select().from(doctorHealthState).where(eq123(doctorHealthState.projectId, project.id)).limit(1).get();
|
|
81011
81091
|
const health = healthRow ? { status: healthRow.status, code: healthRow.code, summary: healthRow.summary, checkedAt: healthRow.checkedAt, notifiedAt: healthRow.notifiedAt } : null;
|
|
81012
81092
|
const rank = { ok: 0, "never-synced": 1, warning: 2, stale: 3, failing: 4 };
|
|
81013
81093
|
const healthState = health?.status === "fail" ? "failing" : health?.status === "warn" ? "warning" : "ok";
|
|
@@ -81027,7 +81107,7 @@ async function statusRoutes(app, opts) {
|
|
|
81027
81107
|
if (request.query.problems === "true") result.projects = result.projects.map((item2) => ({ ...item2, integrations: item2.integrations.filter((row) => row.state !== "ok") }));
|
|
81028
81108
|
return instanceStatusDtoSchema.parse(result);
|
|
81029
81109
|
}
|
|
81030
|
-
const projectsRows = (scopedId ? opts.db.select().from(projects).where(
|
|
81110
|
+
const projectsRows = (scopedId ? opts.db.select().from(projects).where(eq123(projects.id, scopedId)) : opts.db.select().from(projects)).all();
|
|
81031
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)) };
|
|
81032
81112
|
for (const project of output.projects) {
|
|
81033
81113
|
const key = project.state === "never-synced" ? "neverSynced" : project.state;
|
|
@@ -81040,7 +81120,7 @@ async function statusRoutes(app, opts) {
|
|
|
81040
81120
|
|
|
81041
81121
|
// ../api-routes/src/discovery/routes.ts
|
|
81042
81122
|
import crypto64 from "crypto";
|
|
81043
|
-
import { and as
|
|
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";
|
|
81044
81124
|
var MAX_INFLIGHT_DISCOVERY_AGE_MS = 2 * 60 * 60 * 1e3;
|
|
81045
81125
|
async function discoveryRoutes(app, opts) {
|
|
81046
81126
|
app.post("/projects/:name/discover/run", async (request, reply) => {
|
|
@@ -81074,13 +81154,13 @@ async function discoveryRoutes(app, opts) {
|
|
|
81074
81154
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
81075
81155
|
const ageFloorIso = new Date(Date.now() - MAX_INFLIGHT_DISCOVERY_AGE_MS).toISOString();
|
|
81076
81156
|
const decision = app.db.transaction((tx) => {
|
|
81077
|
-
const existing = tx.select({ id: discoverySessions.id, runId: discoverySessions.runId }).from(discoverySessions).where(
|
|
81078
|
-
|
|
81079
|
-
|
|
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),
|
|
81080
81160
|
// Buyer is part of session identity: it changes the seed prompt's
|
|
81081
81161
|
// semantics, so a request with a different (or no) buyer must start
|
|
81082
81162
|
// its own session, never adopt another buyer's probes.
|
|
81083
|
-
parsed.data.buyerDescription == null ? isNull20(discoverySessions.buyerDescription) :
|
|
81163
|
+
parsed.data.buyerDescription == null ? isNull20(discoverySessions.buyerDescription) : eq124(discoverySessions.buyerDescription, parsed.data.buyerDescription),
|
|
81084
81164
|
// Locations are identity too: a different service-area subset seeds
|
|
81085
81165
|
// and probes a different geo, so it must never reuse another geo's
|
|
81086
81166
|
// session. resolveLocations is deterministic (project-config order),
|
|
@@ -81090,11 +81170,11 @@ async function discoveryRoutes(app, opts) {
|
|
|
81090
81170
|
// locations a NULL row's subset is unknowable, so it conservatively
|
|
81091
81171
|
// never reuses — a one-time, bounded (2h window) non-reuse after
|
|
81092
81172
|
// upgrade, never a wrong reuse.
|
|
81093
|
-
locations.length === 0 ? or22(isNull20(discoverySessions.locations),
|
|
81173
|
+
locations.length === 0 ? or22(isNull20(discoverySessions.locations), eq124(discoverySessions.locations, locations)) : eq124(discoverySessions.locations, locations),
|
|
81094
81174
|
// Seed provider set is identity: a different phrasing distribution
|
|
81095
81175
|
// must never reuse another set's session. Null (= Gemini-only
|
|
81096
81176
|
// default, including explicit ['gemini']) matches legacy rows.
|
|
81097
|
-
seedProviders == null ? isNull20(discoverySessions.seedProviders) :
|
|
81177
|
+
seedProviders == null ? isNull20(discoverySessions.seedProviders) : eq124(discoverySessions.seedProviders, seedProviders),
|
|
81098
81178
|
inArray58(discoverySessions.status, [
|
|
81099
81179
|
DiscoverySessionStatuses.queued,
|
|
81100
81180
|
DiscoverySessionStatuses.seeding,
|
|
@@ -81170,7 +81250,7 @@ async function discoveryRoutes(app, opts) {
|
|
|
81170
81250
|
const project = resolveProject(app.db, request.params.name);
|
|
81171
81251
|
const parsedLimit = parseInt(request.query.limit ?? "", 10);
|
|
81172
81252
|
const limit = Number.isNaN(parsedLimit) || parsedLimit <= 0 ? 50 : parsedLimit;
|
|
81173
|
-
const rows = app.db.select().from(discoverySessions).where(
|
|
81253
|
+
const rows = app.db.select().from(discoverySessions).where(eq124(discoverySessions.projectId, project.id)).orderBy(desc57(discoverySessions.createdAt)).limit(limit).all();
|
|
81174
81254
|
return reply.send(rows.map(serializeSession));
|
|
81175
81255
|
}
|
|
81176
81256
|
);
|
|
@@ -81178,11 +81258,11 @@ async function discoveryRoutes(app, opts) {
|
|
|
81178
81258
|
"/projects/:name/discover/sessions/:id",
|
|
81179
81259
|
async (request, reply) => {
|
|
81180
81260
|
const project = resolveProject(app.db, request.params.name);
|
|
81181
|
-
const session = app.db.select().from(discoverySessions).where(
|
|
81261
|
+
const session = app.db.select().from(discoverySessions).where(eq124(discoverySessions.id, request.params.id)).get();
|
|
81182
81262
|
if (!session || session.projectId !== project.id) {
|
|
81183
81263
|
throw notFound("Discovery session", request.params.id);
|
|
81184
81264
|
}
|
|
81185
|
-
const probeRows = app.db.select().from(discoveryProbes).where(
|
|
81265
|
+
const probeRows = app.db.select().from(discoveryProbes).where(eq124(discoveryProbes.sessionId, session.id)).all();
|
|
81186
81266
|
const detail = {
|
|
81187
81267
|
...serializeSession(session),
|
|
81188
81268
|
probes: probeRows.map(serializeProbe)
|
|
@@ -81196,7 +81276,7 @@ async function discoveryRoutes(app, opts) {
|
|
|
81196
81276
|
requireAdminSession(request);
|
|
81197
81277
|
requirePaidReadScope(request, [], "Discovery harvest requires wildcard (*) API key scope because it can call the embedding provider.");
|
|
81198
81278
|
const project = resolveProject(app.db, request.params.name);
|
|
81199
|
-
const session = app.db.select().from(discoverySessions).where(
|
|
81279
|
+
const session = app.db.select().from(discoverySessions).where(eq124(discoverySessions.id, request.params.id)).get();
|
|
81200
81280
|
if (!session || session.projectId !== project.id) {
|
|
81201
81281
|
throw notFound("Discovery session", request.params.id);
|
|
81202
81282
|
}
|
|
@@ -81204,7 +81284,7 @@ async function discoveryRoutes(app, opts) {
|
|
|
81204
81284
|
const minProbeHits = Number.isNaN(parsedFloor) || parsedFloor < 1 ? 1 : parsedFloor;
|
|
81205
81285
|
const applyAnchor = request.query.anchor !== "false";
|
|
81206
81286
|
const provider = session.seedProvider ?? "gemini";
|
|
81207
|
-
const probeRows = app.db.select().from(discoveryProbes).where(
|
|
81287
|
+
const probeRows = app.db.select().from(discoveryProbes).where(eq124(discoveryProbes.sessionId, session.id)).all();
|
|
81208
81288
|
const extract = opts.harvestSearchQueries;
|
|
81209
81289
|
const probesWithQueries = probeRows.map((row) => {
|
|
81210
81290
|
if (!extract || !row.rawResponse) return { searchQueries: [] };
|
|
@@ -81215,7 +81295,7 @@ async function discoveryRoutes(app, opts) {
|
|
|
81215
81295
|
return { searchQueries: [] };
|
|
81216
81296
|
}
|
|
81217
81297
|
});
|
|
81218
|
-
const trackedQueries = app.db.select({ query: queries.query }).from(queries).where(
|
|
81298
|
+
const trackedQueries = app.db.select({ query: queries.query }).from(queries).where(eq124(queries.projectId, project.id)).all().map((r) => r.query);
|
|
81219
81299
|
const anchorTerms = buildHarvestAnchorTerms(
|
|
81220
81300
|
[session.icpDescription ?? "", ...trackedQueries],
|
|
81221
81301
|
effectiveDomains(project)
|
|
@@ -81262,11 +81342,11 @@ async function discoveryRoutes(app, opts) {
|
|
|
81262
81342
|
"/projects/:name/discover/sessions/:id/promote",
|
|
81263
81343
|
async (request, reply) => {
|
|
81264
81344
|
const project = resolveProject(app.db, request.params.name);
|
|
81265
|
-
const session = app.db.select().from(discoverySessions).where(
|
|
81345
|
+
const session = app.db.select().from(discoverySessions).where(eq124(discoverySessions.id, request.params.id)).get();
|
|
81266
81346
|
if (!session || session.projectId !== project.id) {
|
|
81267
81347
|
throw notFound("Discovery session", request.params.id);
|
|
81268
81348
|
}
|
|
81269
|
-
const probeRows = app.db.select().from(discoveryProbes).where(
|
|
81349
|
+
const probeRows = app.db.select().from(discoveryProbes).where(eq124(discoveryProbes.sessionId, session.id)).all();
|
|
81270
81350
|
const cited = /* @__PURE__ */ new Set();
|
|
81271
81351
|
const aspirational = /* @__PURE__ */ new Set();
|
|
81272
81352
|
const wasted = /* @__PURE__ */ new Set();
|
|
@@ -81301,7 +81381,7 @@ async function discoveryRoutes(app, opts) {
|
|
|
81301
81381
|
);
|
|
81302
81382
|
app.post("/projects/:name/discover/sessions/:id/promote", async (request, reply) => {
|
|
81303
81383
|
const project = resolveProject(app.db, request.params.name);
|
|
81304
|
-
const session = app.db.select().from(discoverySessions).where(
|
|
81384
|
+
const session = app.db.select().from(discoverySessions).where(eq124(discoverySessions.id, request.params.id)).get();
|
|
81305
81385
|
if (!session || session.projectId !== project.id) {
|
|
81306
81386
|
throw notFound("Discovery session", request.params.id);
|
|
81307
81387
|
}
|
|
@@ -81324,7 +81404,7 @@ async function discoveryRoutes(app, opts) {
|
|
|
81324
81404
|
const bucketSet = new Set(buckets);
|
|
81325
81405
|
const includeCompetitors = parsed.data.includeCompetitors ?? true;
|
|
81326
81406
|
const competitorTypes = parsed.data.competitorTypes ?? DEFAULT_DISCOVERY_PROMOTE_COMPETITOR_TYPES;
|
|
81327
|
-
const probeRows = app.db.select().from(discoveryProbes).where(
|
|
81407
|
+
const probeRows = app.db.select().from(discoveryProbes).where(eq124(discoveryProbes.sessionId, session.id)).all();
|
|
81328
81408
|
const candidateQueries = /* @__PURE__ */ new Set();
|
|
81329
81409
|
for (const probe of probeRows) {
|
|
81330
81410
|
if (!probe.bucket) continue;
|
|
@@ -81332,7 +81412,7 @@ async function discoveryRoutes(app, opts) {
|
|
|
81332
81412
|
if (bucket.success && bucketSet.has(bucket.data)) candidateQueries.add(probe.query);
|
|
81333
81413
|
}
|
|
81334
81414
|
const existingQueries = new Set(
|
|
81335
|
-
app.db.select({ query: queries.query }).from(queries).where(
|
|
81415
|
+
app.db.select({ query: queries.query }).from(queries).where(eq124(queries.projectId, project.id)).all().map((r) => r.query.toLowerCase())
|
|
81336
81416
|
);
|
|
81337
81417
|
const promotedQueries = [];
|
|
81338
81418
|
const skippedQueries = [];
|
|
@@ -81546,7 +81626,7 @@ function planCompetitorPromotion(input) {
|
|
|
81546
81626
|
|
|
81547
81627
|
// ../api-routes/src/discovery/orchestrate.ts
|
|
81548
81628
|
import crypto65 from "crypto";
|
|
81549
|
-
import { eq as
|
|
81629
|
+
import { eq as eq125 } from "drizzle-orm";
|
|
81550
81630
|
var DEFAULT_MAX_PROBES = 100;
|
|
81551
81631
|
var ABSOLUTE_MAX_PROBES = 500;
|
|
81552
81632
|
function classifyProbeBucket(input) {
|
|
@@ -81632,7 +81712,7 @@ async function executeDiscovery(opts) {
|
|
|
81632
81712
|
status: DiscoverySessionStatuses.seeding,
|
|
81633
81713
|
dedupThreshold,
|
|
81634
81714
|
startedAt
|
|
81635
|
-
}).where(
|
|
81715
|
+
}).where(eq125(discoverySessions.id, opts.sessionId)).run();
|
|
81636
81716
|
const seedResult = await opts.deps.seed({
|
|
81637
81717
|
project: opts.project,
|
|
81638
81718
|
icpDescription: opts.icpDescription,
|
|
@@ -81693,7 +81773,7 @@ async function executeDiscovery(opts) {
|
|
|
81693
81773
|
dedupBandPairFraction: dedupStats.bandPairFraction,
|
|
81694
81774
|
dedupPairsTotal: dedupStats.pairsTotal,
|
|
81695
81775
|
warning
|
|
81696
|
-
}).where(
|
|
81776
|
+
}).where(eq125(discoverySessions.id, opts.sessionId)).run();
|
|
81697
81777
|
const probeLocation = opts.locations?.[0];
|
|
81698
81778
|
const probeResults = await mapWithConcurrency(
|
|
81699
81779
|
probedCanonicals,
|
|
@@ -81747,7 +81827,7 @@ async function executeDiscovery(opts) {
|
|
|
81747
81827
|
wastedCount: buckets["wasted-surface"],
|
|
81748
81828
|
competitorMap,
|
|
81749
81829
|
finishedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
81750
|
-
}).where(
|
|
81830
|
+
}).where(eq125(discoverySessions.id, opts.sessionId)).run();
|
|
81751
81831
|
upsertDomainClassifications(opts.db, opts.project.id, opts.sessionId, competitorMap);
|
|
81752
81832
|
return {
|
|
81753
81833
|
buckets,
|
|
@@ -81787,7 +81867,7 @@ function markSessionFailed(db, sessionId, error) {
|
|
|
81787
81867
|
status: DiscoverySessionStatuses.failed,
|
|
81788
81868
|
error,
|
|
81789
81869
|
finishedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
81790
|
-
}).where(
|
|
81870
|
+
}).where(eq125(discoverySessions.id, sessionId)).run();
|
|
81791
81871
|
}
|
|
81792
81872
|
function dedupeStrings(input) {
|
|
81793
81873
|
const seen2 = /* @__PURE__ */ new Set();
|
|
@@ -81804,7 +81884,7 @@ function dedupeStrings(input) {
|
|
|
81804
81884
|
}
|
|
81805
81885
|
|
|
81806
81886
|
// ../api-routes/src/trends.ts
|
|
81807
|
-
import { and as
|
|
81887
|
+
import { and as and105, asc as asc30, eq as eq126 } from "drizzle-orm";
|
|
81808
81888
|
function parseSurface(value) {
|
|
81809
81889
|
const parsed = trendSurfaceSchema.safeParse(value);
|
|
81810
81890
|
if (!parsed.success) {
|
|
@@ -81860,8 +81940,8 @@ async function trendsRoutes(app) {
|
|
|
81860
81940
|
function readSurface(app, projectId, surface) {
|
|
81861
81941
|
switch (surface) {
|
|
81862
81942
|
case TrendSurfaces["index-coverage"]: {
|
|
81863
|
-
const google = app.db.select({ date: gscCoverageSnapshots.date, indexed: gscCoverageSnapshots.indexed, notIndexed: gscCoverageSnapshots.notIndexed }).from(gscCoverageSnapshots).where(
|
|
81864
|
-
const bing = app.db.select({ date: bingCoverageSnapshots.date, indexed: bingCoverageSnapshots.indexed, notIndexed: bingCoverageSnapshots.notIndexed }).from(bingCoverageSnapshots).where(
|
|
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();
|
|
81865
81945
|
const coverage = (key, label, rows) => ({
|
|
81866
81946
|
key,
|
|
81867
81947
|
label,
|
|
@@ -81873,7 +81953,7 @@ function readSurface(app, projectId, surface) {
|
|
|
81873
81953
|
return [coverage("google", "Google", google), coverage("bing", "Bing", bing)];
|
|
81874
81954
|
}
|
|
81875
81955
|
case TrendSurfaces["site-health"]: {
|
|
81876
|
-
const rows = app.db.select({ auditedAt: siteAuditSnapshots.auditedAt, aggregateScore: siteAuditSnapshots.aggregateScore, pagesAudited: siteAuditSnapshots.pagesAudited }).from(siteAuditSnapshots).innerJoin(runs,
|
|
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();
|
|
81877
81957
|
return [{
|
|
81878
81958
|
key: "site-health",
|
|
81879
81959
|
label: "Agent Readiness",
|
|
@@ -81885,7 +81965,7 @@ function readSurface(app, projectId, surface) {
|
|
|
81885
81965
|
}
|
|
81886
81966
|
case TrendSurfaces.backlinks: {
|
|
81887
81967
|
const totals = computeFilteredReleaseTotals(app.db, projectId, BacklinkSources.commoncrawl);
|
|
81888
|
-
const rows = app.db.select({ release: backlinkSummaries.release, totalLinkingDomains: backlinkSummaries.totalLinkingDomains, queriedAt: backlinkSummaries.queriedAt }).from(backlinkSummaries).where(
|
|
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) => {
|
|
81889
81969
|
const filtered = totals.get(row.release);
|
|
81890
81970
|
const known = (filtered?.domainRows ?? 0) > 0 || row.totalLinkingDomains === 0;
|
|
81891
81971
|
const windowEnd = releaseWindowEndMonth(row.release);
|
|
@@ -81915,7 +81995,7 @@ function readSurface(app, projectId, surface) {
|
|
|
81915
81995
|
// ../api-routes/src/research.ts
|
|
81916
81996
|
import crypto66 from "crypto";
|
|
81917
81997
|
import { z as z7 } from "zod";
|
|
81918
|
-
import { and as
|
|
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";
|
|
81919
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;
|
|
81920
82000
|
var BATCH_RECEIPT_PREFIX = "__canonry_research_batch__:";
|
|
81921
82001
|
async function researchRoutes(app, opts) {
|
|
@@ -81934,7 +82014,7 @@ async function researchRoutes(app, opts) {
|
|
|
81934
82014
|
const input = parsed.data;
|
|
81935
82015
|
if (input.idempotencyKey?.startsWith(BATCH_RECEIPT_PREFIX)) throw validationError("This idempotency key prefix is reserved for internal research batch receipts.");
|
|
81936
82016
|
const requestHash2 = directResearchRequestHash(input);
|
|
81937
|
-
const existingReceipt = input.idempotencyKey ? app.db.select().from(researchRuns).where(
|
|
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;
|
|
81938
82018
|
if (existingReceipt) {
|
|
81939
82019
|
assertSameDirectResearchRequest(existingReceipt, input, requestHash2);
|
|
81940
82020
|
const result2 = getDetail(app, project.id, existingReceipt.id);
|
|
@@ -81969,7 +82049,7 @@ async function researchRoutes(app, opts) {
|
|
|
81969
82049
|
const initiatedBy = researchPrincipal(request);
|
|
81970
82050
|
const decision = app.db.transaction((tx) => {
|
|
81971
82051
|
if (input.idempotencyKey) {
|
|
81972
|
-
const existing = tx.select().from(researchRuns).where(
|
|
82052
|
+
const existing = tx.select().from(researchRuns).where(and106(eq127(researchRuns.projectId, project.id), eq127(researchRuns.idempotencyKey, input.idempotencyKey))).get();
|
|
81973
82053
|
if (existing) {
|
|
81974
82054
|
assertSameDirectResearchRequest(existing, input, requestHash2);
|
|
81975
82055
|
return { reused: true, id: existing.id, shouldDispatch: existing.status === ResearchRunStatuses.queued };
|
|
@@ -81977,8 +82057,8 @@ async function researchRoutes(app, opts) {
|
|
|
81977
82057
|
}
|
|
81978
82058
|
if (initiatedBy?.limited) {
|
|
81979
82059
|
const { start, end, date } = utcDayBounds(now);
|
|
81980
|
-
const used = tx.select({ value: count10() }).from(researchRuns).where(
|
|
81981
|
-
|
|
82060
|
+
const used = tx.select({ value: count10() }).from(researchRuns).where(and106(
|
|
82061
|
+
eq127(researchRuns.projectId, project.id),
|
|
81982
82062
|
gte34(researchRuns.createdAt, start),
|
|
81983
82063
|
lt21(researchRuns.createdAt, end),
|
|
81984
82064
|
sql52`(json_extract(${researchRuns.initiatedBy}, '$.role') = ${UserRoles.viewer} OR json_extract(${researchRuns.initiatedBy}, '$.limited') = 1)`
|
|
@@ -82009,15 +82089,15 @@ async function researchRoutes(app, opts) {
|
|
|
82009
82089
|
if (input.idempotencyKey.startsWith(BATCH_RECEIPT_PREFIX)) throw validationError("This idempotency key prefix is reserved for internal research batch receipts.");
|
|
82010
82090
|
const requestHash2 = researchBatchRequestHash(input);
|
|
82011
82091
|
const receiptKeys = input.runs.map((_run, index) => batchChildReceiptKey(input.idempotencyKey, index));
|
|
82012
|
-
const firstReceipt = app.db.select().from(researchRuns).where(
|
|
82013
|
-
|
|
82014
|
-
|
|
82092
|
+
const firstReceipt = app.db.select().from(researchRuns).where(and106(
|
|
82093
|
+
eq127(researchRuns.projectId, project.id),
|
|
82094
|
+
eq127(researchRuns.idempotencyKey, receiptKeys[0])
|
|
82015
82095
|
)).get();
|
|
82016
82096
|
if (firstReceipt) {
|
|
82017
82097
|
if (firstReceipt.requestHash !== requestHash2) throw alreadyExists("Research batch idempotency key", input.idempotencyKey);
|
|
82018
|
-
const saved = receiptKeys.map((key) => app.db.select().from(researchRuns).where(
|
|
82019
|
-
|
|
82020
|
-
|
|
82098
|
+
const saved = receiptKeys.map((key) => app.db.select().from(researchRuns).where(and106(
|
|
82099
|
+
eq127(researchRuns.projectId, project.id),
|
|
82100
|
+
eq127(researchRuns.idempotencyKey, key)
|
|
82021
82101
|
)).get());
|
|
82022
82102
|
if (saved.some((row) => !row || row.requestHash !== requestHash2)) throw alreadyExists("Research batch idempotency key", input.idempotencyKey);
|
|
82023
82103
|
const runs3 = saved.map((row) => getDetail(app, project.id, row.id));
|
|
@@ -82033,8 +82113,8 @@ async function researchRoutes(app, opts) {
|
|
|
82033
82113
|
const decision = app.db.transaction((tx) => {
|
|
82034
82114
|
if (initiatedBy?.limited) {
|
|
82035
82115
|
const { start, end, date } = utcDayBounds(now);
|
|
82036
|
-
const used = tx.select({ value: count10() }).from(researchRuns).where(
|
|
82037
|
-
|
|
82116
|
+
const used = tx.select({ value: count10() }).from(researchRuns).where(and106(
|
|
82117
|
+
eq127(researchRuns.projectId, project.id),
|
|
82038
82118
|
gte34(researchRuns.createdAt, start),
|
|
82039
82119
|
lt21(researchRuns.createdAt, end),
|
|
82040
82120
|
sql52`(json_extract(${researchRuns.initiatedBy}, '$.role') = ${UserRoles.viewer} OR json_extract(${researchRuns.initiatedBy}, '$.limited') = 1)`
|
|
@@ -82088,9 +82168,9 @@ async function researchRoutes(app, opts) {
|
|
|
82088
82168
|
const requested = Number.parseInt(request.query.limit ?? "", 10);
|
|
82089
82169
|
const limit = Number.isInteger(requested) && requested > 0 ? Math.min(requested, 100) : 20;
|
|
82090
82170
|
const cursor = request.query.cursor ? parseResearchCursor(request.query.cursor, project.id) : null;
|
|
82091
|
-
const rows = app.db.select().from(researchRuns).where(
|
|
82092
|
-
|
|
82093
|
-
cursor ? or23(lt21(researchRuns.createdAt, cursor.createdAt),
|
|
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
|
|
82094
82174
|
)).orderBy(desc58(researchRuns.createdAt), desc58(researchRuns.id)).limit(limit + 1).all();
|
|
82095
82175
|
const runs2 = rows.slice(0, limit).map(serializeRun);
|
|
82096
82176
|
const last = runs2.at(-1);
|
|
@@ -82240,9 +82320,9 @@ function resolveStoredResearchTemplate(stored, selection, idempotencyKey) {
|
|
|
82240
82320
|
return stored;
|
|
82241
82321
|
}
|
|
82242
82322
|
function resolveResearchTemplate(app, projectId, selection, scope, location) {
|
|
82243
|
-
const savedTemplate = app.db.select().from(measurementQueryTemplates).where(
|
|
82244
|
-
|
|
82245
|
-
|
|
82323
|
+
const savedTemplate = app.db.select().from(measurementQueryTemplates).where(and106(
|
|
82324
|
+
eq127(measurementQueryTemplates.projectId, projectId),
|
|
82325
|
+
eq127(measurementQueryTemplates.id, selection.templateId)
|
|
82246
82326
|
)).get();
|
|
82247
82327
|
if (!savedTemplate) throw validationError("Unknown or stale research template. Reload the selected template and try again.");
|
|
82248
82328
|
const templateVersion = savedTemplate.updatedAt;
|
|
@@ -82251,7 +82331,7 @@ function resolveResearchTemplate(app, projectId, selection, scope, location) {
|
|
|
82251
82331
|
}
|
|
82252
82332
|
const bindingLocation = selection.bindingLocation === void 0 ? location : selection.bindingLocation;
|
|
82253
82333
|
if (bindingLocation) {
|
|
82254
|
-
const project = app.db.select({ locations: projects.locations }).from(projects).where(
|
|
82334
|
+
const project = app.db.select({ locations: projects.locations }).from(projects).where(eq127(projects.id, projectId)).get();
|
|
82255
82335
|
if (!project.locations.some((item2) => sameLocation(item2, bindingLocation))) throw validationError("Research template binding location must match a configured project location.");
|
|
82256
82336
|
}
|
|
82257
82337
|
const { bindings, output } = expandResearchTemplate(savedTemplate, scope, bindingLocation);
|
|
@@ -82264,9 +82344,9 @@ function classifyResearchQueries(project, plan, queries2) {
|
|
|
82264
82344
|
return queries2.map((query2) => classifier?.classify(query2) ?? null);
|
|
82265
82345
|
}
|
|
82266
82346
|
function getDetail(app, projectId, id) {
|
|
82267
|
-
const row = app.db.select().from(researchRuns).where(
|
|
82347
|
+
const row = app.db.select().from(researchRuns).where(and106(eq127(researchRuns.id, id), eq127(researchRuns.projectId, projectId))).get();
|
|
82268
82348
|
if (!row) throw notFound("Research run", id);
|
|
82269
|
-
const queries2 = app.db.select().from(researchRunQueries).where(
|
|
82349
|
+
const queries2 = app.db.select().from(researchRunQueries).where(eq127(researchRunQueries.researchRunId, id)).orderBy(researchRunQueries.position).all().map((query2) => serializeQuery(query2, row.provider));
|
|
82270
82350
|
return { ...serializeRun(row), queries: queries2 };
|
|
82271
82351
|
}
|
|
82272
82352
|
function serializeRun(row) {
|
|
@@ -82327,7 +82407,7 @@ function utcDayBounds(now) {
|
|
|
82327
82407
|
|
|
82328
82408
|
// ../api-routes/src/simple-measurement-definitions.ts
|
|
82329
82409
|
import crypto67 from "crypto";
|
|
82330
|
-
import { and as
|
|
82410
|
+
import { and as and107, eq as eq128 } from "drizzle-orm";
|
|
82331
82411
|
function captureSimpleMeasurementDefinition(db, input) {
|
|
82332
82412
|
return db.transaction((tx) => {
|
|
82333
82413
|
const run = tx.select({
|
|
@@ -82335,7 +82415,7 @@ function captureSimpleMeasurementDefinition(db, input) {
|
|
|
82335
82415
|
trigger: runs.trigger,
|
|
82336
82416
|
status: runs.status,
|
|
82337
82417
|
measurementPlanVersionId: runs.measurementPlanVersionId
|
|
82338
|
-
}).from(runs).where(
|
|
82418
|
+
}).from(runs).where(and107(eq128(runs.projectId, input.projectId), eq128(runs.id, input.runId))).get();
|
|
82339
82419
|
if (!run) throw notFound("Run", input.runId);
|
|
82340
82420
|
if (run.kind !== RunKinds["answer-visibility"] || run.trigger === RunTriggers.probe || run.measurementPlanVersionId !== null) {
|
|
82341
82421
|
return null;
|
|
@@ -82356,7 +82436,7 @@ function captureSimpleMeasurementDefinition(db, input) {
|
|
|
82356
82436
|
throw validationError("Qualified aliases must be a sorted subset of the captured aliases.");
|
|
82357
82437
|
}
|
|
82358
82438
|
}
|
|
82359
|
-
const existing = tx.select().from(simpleMeasurementDefinitions).where(
|
|
82439
|
+
const existing = tx.select().from(simpleMeasurementDefinitions).where(and107(eq128(simpleMeasurementDefinitions.projectId, input.projectId), eq128(simpleMeasurementDefinitions.runId, input.runId))).get();
|
|
82360
82440
|
if (existing) {
|
|
82361
82441
|
const frozen = simpleMeasurementDefinitionSchema.parse(existing.definition);
|
|
82362
82442
|
const { qualifiedAliases: _liveQualifiedAliases, ...liveIdentity } = definition2.identity;
|
|
@@ -82382,15 +82462,15 @@ function captureSimpleMeasurementDefinition(db, input) {
|
|
|
82382
82462
|
if (run.status !== RunStatuses.running) {
|
|
82383
82463
|
throw validationError("Only a running run can capture a new measurement definition.");
|
|
82384
82464
|
}
|
|
82385
|
-
if (tx.select({ id: querySnapshots.id }).from(querySnapshots).where(
|
|
82465
|
+
if (tx.select({ id: querySnapshots.id }).from(querySnapshots).where(eq128(querySnapshots.runId, input.runId)).limit(1).get()) {
|
|
82386
82466
|
throw validationError("This run already has stored answers. Its measurement definition cannot be inferred afterward.");
|
|
82387
82467
|
}
|
|
82388
|
-
const projectQueryIds = new Set(tx.select({ id: queries.id }).from(queries).where(
|
|
82468
|
+
const projectQueryIds = new Set(tx.select({ id: queries.id }).from(queries).where(eq128(queries.projectId, input.projectId)).all().map((query2) => query2.id));
|
|
82389
82469
|
if (definition2.queries.some((query2) => !projectQueryIds.has(query2.queryId))) {
|
|
82390
82470
|
throw validationError("Every captured query must belong to the run project.");
|
|
82391
82471
|
}
|
|
82392
82472
|
if (definition2.competitors !== void 0) {
|
|
82393
|
-
const liveCompetitorDomains = new Set(tx.select({ domain: competitors.domain }).from(competitors).where(
|
|
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));
|
|
82394
82474
|
const capturedDomains = new Set(definition2.competitors.map((competitor) => competitor.domain));
|
|
82395
82475
|
if (liveCompetitorDomains.size !== capturedDomains.size || [...liveCompetitorDomains].some((domain) => !capturedDomains.has(domain))) {
|
|
82396
82476
|
throw validationError("Captured competitors must exactly match the project competitors dispatched for this run.");
|