@canonry/canonry 7.123.0 → 7.123.2
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/agent-workspace/skills/canonry/references/canonry-cli.md +4 -2
- package/assets/assets/{AccessControls-qKt0MIwz.js → AccessControls-Dta-SizF.js} +1 -1
- package/assets/assets/{AgentSetupPage-CS6TAG_q.js → AgentSetupPage-BCZb2JPd.js} +1 -1
- package/assets/assets/{AuditHistoryPanel-C9muxa5U.js → AuditHistoryPanel-CKfjkLV9.js} +1 -1
- package/assets/assets/{BacklinksPage-YSi04rze.js → BacklinksPage-DqonUKGQ.js} +1 -1
- package/assets/assets/{ChartPrimitives-DA5ldw5q.js → ChartPrimitives-QqkNW1z_.js} +1 -1
- package/assets/assets/{HistoryPage-tTCABHZr.js → HistoryPage-5GKX_eTg.js} +1 -1
- package/assets/assets/{MeasurementPropertyPage-B-eHRFSF.js → MeasurementPropertyPage-DX2Y334y.js} +1 -1
- package/assets/assets/{ProjectPage-DK7y3uMN.js → ProjectPage-CVjtoNwY.js} +3 -3
- package/assets/assets/{RunsPage-B6HxjqFp.js → RunsPage-DvNIMEBR.js} +1 -1
- package/assets/assets/{ServerTrafficSection-BCPF6Rxk.js → ServerTrafficSection-CTXgnGFO.js} +3 -3
- package/assets/assets/{SettingsPage-Dlsqc0Xk.js → SettingsPage-DNRMlgyi.js} +1 -1
- package/assets/assets/{ToneBadge-BekCDc9B.js → ToneBadge-BT5eyW7T.js} +1 -1
- package/assets/assets/{TrafficPage-CcZ2VKWS.js → TrafficPage-By1Ha68i.js} +1 -1
- package/assets/assets/{TrafficSourceDetailPage-BUWRBlEj.js → TrafficSourceDetailPage-Dd1suSAW.js} +1 -1
- package/assets/assets/{account-context-CTgTl_U3.js → account-context-DXPWWIHe.js} +1 -1
- package/assets/assets/{agent-trust-copy-C3Su6oTh.js → agent-trust-copy-Co71D_rr.js} +1 -1
- package/assets/assets/{card-fF4DLMtN.js → card-FKB7Bzi_.js} +1 -1
- package/assets/assets/{index-CZK8ELxf.js → index--sAfSMDD.js} +4 -4
- package/assets/assets/{preload-helper-D6vLhNAZ.js → preload-helper-DPpAnfor.js} +1 -1
- package/assets/assets/{query-client-bLCsQvmN.js → query-client-CfqIBFn5.js} +1 -1
- package/assets/assets/{react-query-DPn84_Mu.js → react-query-DPm_HpW7.js} +1 -1
- package/assets/assets/{react-sigma_core.esm.min-Dkaqqban.js → react-sigma_core.esm.min-6VFVUIDW.js} +1 -1
- package/assets/assets/{server-traffic-CCdnHKbu.js → server-traffic-nohNgNs2.js} +1 -1
- package/assets/assets/{service-CUnyHRGl.js → service-DvysKXv7.js} +1 -1
- package/assets/index.html +9 -9
- package/dist/activity-IHLM2J7H.js +13 -0
- package/dist/{ads-OXZFLKFO.js → ads-DDVAI7ZZ.js} +4 -4
- package/dist/{agent-VMLMGUVU.js → agent-OEFMVVYC.js} +8 -8
- package/dist/{agent-ask-IGL7KSBW.js → agent-ask-4HETA3Z7.js} +4 -4
- package/dist/{agent-conversations-ZQQJTVLM.js → agent-conversations-CCMZJIWB.js} +4 -4
- package/dist/{agent-journeys-Z3ZILTRB.js → agent-journeys-VXHMJ3SE.js} +4 -4
- package/dist/{agent-memory-MEFTNQWG.js → agent-memory-MOTZGQY6.js} +4 -4
- package/dist/{agent-providers-ZZ6RN4TB.js → agent-providers-QIPWDCAJ.js} +4 -4
- package/dist/{agent-transcript-QK3OTZ7B.js → agent-transcript-YIMZZF7M.js} +4 -4
- package/dist/{analytics-VAJT24GQ.js → analytics-46CHCOBG.js} +4 -4
- package/dist/{apply-IWCME5ZF.js → apply-6YQMLMGS.js} +4 -4
- package/dist/{backfill-5E2D3HFJ.js → backfill-YL2FNUFE.js} +11 -11
- package/dist/{backlinks-QVFDZZCI.js → backlinks-5GE5HVBE.js} +4 -4
- package/dist/{bing-JUCW5FTY.js → bing-YUVHQVCO.js} +4 -4
- package/dist/{bootstrap-R2O2TPAR.js → bootstrap-MT3QPFXR.js} +11 -11
- package/dist/{cdp-VTQYZVW5.js → cdp-JMYRL3XN.js} +8 -8
- package/dist/{chunk-TCHIEN67.js → chunk-2FZM66FH.js} +6 -6
- package/dist/{chunk-AUMR4UXI.js → chunk-2YRIEAVO.js} +4 -4
- package/dist/{chunk-SLHX5HBD.js → chunk-3MYRQB3W.js} +4 -4
- package/dist/{chunk-QXUNANMR.js → chunk-3SKGFNCD.js} +2 -2
- package/dist/{chunk-RBUT6DJG.js → chunk-54X76NGL.js} +5 -5
- package/dist/{chunk-DMFFERXC.js → chunk-B7YR57FO.js} +1 -1
- package/dist/{chunk-2DT55UKG.js → chunk-CBORUOY3.js} +3 -3
- package/dist/{chunk-73AQQAPC.js → chunk-CBYBYL7A.js} +11 -1
- package/dist/{chunk-Z6ZH7N6U.js → chunk-FB7ZRPBD.js} +3 -3
- package/dist/{chunk-OCL6NZGL.js → chunk-IA7U7XXS.js} +2 -2
- package/dist/{chunk-LGD3K4G5.js → chunk-JMBAYBFO.js} +4 -4
- package/dist/{chunk-BSUAO3RJ.js → chunk-JPRWAASQ.js} +1 -1
- package/dist/{chunk-BNL3BKXK.js → chunk-K77OPDGD.js} +1 -1
- package/dist/{chunk-CCBFBQFR.js → chunk-LBVLZWLF.js} +3 -3
- package/dist/{chunk-F3PBATIZ.js → chunk-LJKOYEYH.js} +1 -1
- package/dist/{chunk-7E2TDSUH.js → chunk-LN7L45WN.js} +371 -371
- package/dist/{chunk-F3UXTYXA.js → chunk-MFZIEBHI.js} +4 -4
- package/dist/{chunk-ITX7ELLK.js → chunk-MKCI6M2G.js} +5 -5
- package/dist/{chunk-AMVQA6NC.js → chunk-MMCYPRRQ.js} +619 -561
- package/dist/{chunk-7D735WS6.js → chunk-N2BYOBOL.js} +1 -1
- package/dist/{chunk-R2P6XGND.js → chunk-NGD7TX3R.js} +5 -5
- package/dist/{chunk-6URM26ZP.js → chunk-NLW6XEUI.js} +2 -2
- package/dist/{chunk-BVJUYSOB.js → chunk-QNO2KO66.js} +2 -2
- package/dist/{chunk-DPUAVYEG.js → chunk-RII4R3ZZ.js} +4 -4
- package/dist/{chunk-2RG6CSZB.js → chunk-RXDYCDE6.js} +1 -1
- package/dist/{chunk-HSYZCNXY.js → chunk-SGLMEEQ5.js} +2 -2
- package/dist/{chunk-YWLJQ2FY.js → chunk-UEIMKBG6.js} +1 -1
- package/dist/{chunk-YXM6FPGD.js → chunk-UF5MG47X.js} +1 -1
- package/dist/{chunk-ZP6PZZAW.js → chunk-UH3M7XSQ.js} +2 -2
- package/dist/{chunk-7G4YTMZE.js → chunk-UUKO5OCN.js} +8 -8
- package/dist/{chunk-FLUYAMPP.js → chunk-V7OJEOEQ.js} +269 -178
- package/dist/{chunk-LQGTGSA5.js → chunk-VSPGQLEH.js} +3 -3
- package/dist/{chunk-NZOLX55S.js → chunk-W7KF43JV.js} +1 -1
- package/dist/{chunk-XXSDKDKU.js → chunk-WAAESDBG.js} +4 -4
- package/dist/{chunk-TTK6ZZHK.js → chunk-WHJA4QYX.js} +2 -2
- package/dist/{chunk-RHH2K4BZ.js → chunk-WQYYCJGN.js} +4 -4
- package/dist/{chunk-LWGO6ETW.js → chunk-XAF22QBW.js} +2 -2
- package/dist/{chunk-2J6LXZPK.js → chunk-YA54KGF3.js} +1 -1
- package/dist/{citations-HQQQM73E.js → citations-XDBO5C6Y.js} +5 -5
- package/dist/{cli-catalog-STHVOXXT.js → cli-catalog-I4EVHBN3.js} +4 -4
- package/dist/cli-commands-RQQ2IA24.js +18 -0
- package/dist/cli.js +14 -14
- package/dist/{competitor-VP52MSQM.js → competitor-4AIJ4XJF.js} +4 -4
- package/dist/{content-IHFS2BRF.js → content-T3RJQQZB.js} +4 -4
- package/dist/{dashboard-S4KT2J34.js → dashboard-TCT2OZFG.js} +7 -7
- package/dist/{demo-E4Q6WQ5R.js → demo-JQNKAWZI.js} +3 -3
- package/dist/{demo-server-GYJZICT7.js → demo-server-7SFA77LN.js} +13 -13
- package/dist/{discover-X2RATQCF.js → discover-XW7THOUJ.js} +5 -5
- package/dist/{discover-eval-FEQ3HAM2.js → discover-eval-B2VMAP7A.js} +4 -4
- package/dist/{doctor-2CM5FVMJ.js → doctor-GWFLDP6E.js} +4 -4
- package/dist/{evidence-5IAVY6JN.js → evidence-3E56FTV3.js} +4 -4
- package/dist/{export-cmd-LGXY4GIT.js → export-cmd-EM7KBF7D.js} +4 -4
- package/dist/{ga-KVFZSSFH.js → ga-H67UEL5Z.js} +7 -4
- package/dist/{gbp-PLSX7QBV.js → gbp-ZIPJARZX.js} +4 -4
- package/dist/{google-R7HNCZNY.js → google-L3GPQYBY.js} +5 -5
- package/dist/{google-marketing-ZEU6ZNTS.js → google-marketing-STFWTVH2.js} +2 -2
- package/dist/{health-cmd-UNYQIHHZ.js → health-cmd-WGTE6GDP.js} +5 -5
- package/dist/{history-IR234HUF.js → history-X4REKZI7.js} +4 -4
- package/dist/index.d.ts +41 -41
- package/dist/index.js +26 -26
- package/dist/{init-ZRVCNBSL.js → init-KSAQEVOI.js} +13 -13
- package/dist/{insights-OQ4TYD7O.js → insights-DKIQVLF7.js} +4 -4
- package/dist/intelligence-service-XOQWGWUQ.js +15 -0
- package/dist/{journeys-G72GTTDS.js → journeys-IBX6DVER.js} +4 -4
- package/dist/{keys-A2NSFAJR.js → keys-HC56635P.js} +4 -4
- package/dist/{keyword-4ECZAEFL.js → keyword-XCFZ6XYF.js} +4 -4
- package/dist/{logs-OMBVVMGA.js → logs-DOBMYWEL.js} +4 -4
- package/dist/{mcp-OALO7GAG.js → mcp-7URS3Y35.js} +5 -5
- package/dist/mcp.js +10 -10
- package/dist/{measurement-plan-3KJSVBMM.js → measurement-plan-A5XD6GTX.js} +6 -6
- package/dist/{notify-AYBCSPXF.js → notify-WB4D7YSN.js} +4 -4
- package/dist/{organic-evidence-XMS6WPCR.js → organic-evidence-WNHMO6EJ.js} +4 -4
- package/dist/{overview-K4RBEW7T.js → overview-V6VDXKGL.js} +7 -7
- package/dist/{project-KGIYKLEE.js → project-FK454CW2.js} +4 -4
- package/dist/{project-setup-OBS4PSB4.js → project-setup-DU3QZQIH.js} +4 -4
- package/dist/{query-TJAMHSAJ.js → query-XN753RNY.js} +4 -4
- package/dist/{research-REDM6KKM.js → research-SQRXT62J.js} +4 -4
- package/dist/{results-export-E7P2G3FV.js → results-export-V2SWKZ4S.js} +4 -4
- package/dist/{run-43C6BWTO.js → run-V6JJFAQX.js} +6 -6
- package/dist/{schedule-B4TSMTC4.js → schedule-THBN6G7B.js} +4 -4
- package/dist/{search-VE7DGSD7.js → search-DGNFW3LV.js} +4 -4
- package/dist/{serve-LWXCQAA2.js → serve-MCHKKOOS.js} +27 -27
- package/dist/{session-4FP4QJTN.js → session-7DJVNGNI.js} +14 -14
- package/dist/{settings-W3SCNC25.js → settings-J2IGFFTN.js} +4 -4
- package/dist/{sitemaps-YPD7U2ZP.js → sitemaps-OZBTUP7H.js} +4 -4
- package/dist/{skills-K6BM2BQV.js → skills-HDFOPJA4.js} +3 -3
- package/dist/{snapshot-GK6G72YF.js → snapshot-GZDMZHRT.js} +4 -4
- package/dist/{src-RUWMU4ZS.js → src-Y2JHYSZX.js} +2 -2
- package/dist/{status-I23DTMWM.js → status-3DBBZVSJ.js} +6 -6
- package/dist/{support-PEI7R4MY.js → support-MAV3J2JF.js} +2 -2
- package/dist/{technical-aeo-W5ZF2TPH.js → technical-aeo-OYXGISRF.js} +4 -4
- package/dist/{telemetry-YV6IHYS7.js → telemetry-CZEUM2S6.js} +5 -5
- package/dist/{tools-46YC2R4V.js → tools-DPR6GTYF.js} +12 -12
- package/dist/{traffic-SQ4O6QW6.js → traffic-NORJ3VPC.js} +6 -6
- package/dist/{trends-MCDIYFQB.js → trends-DWJIK23M.js} +4 -4
- package/dist/{users-R66ASOSH.js → users-IUPRSMBK.js} +4 -4
- package/dist/{visibility-stats-7XTGKFPE.js → visibility-stats-A7CXPJAL.js} +5 -5
- package/dist/{wordpress-ZMNF2C2H.js → wordpress-SEFAVNRT.js} +4 -4
- package/package.json +1 -1
- package/dist/activity-NEHRLN66.js +0 -13
- package/dist/cli-commands-AHQK2WVB.js +0 -18
- package/dist/intelligence-service-G3EHHS35.js +0 -15
|
@@ -19,14 +19,14 @@ import {
|
|
|
19
19
|
normalizeTrafficPathPattern,
|
|
20
20
|
sessionizeJourneyRequests,
|
|
21
21
|
verifyRequestSignature
|
|
22
|
-
} from "./chunk-
|
|
22
|
+
} from "./chunk-YA54KGF3.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-UEIMKBG6.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-W7KF43JV.js";
|
|
194
194
|
import {
|
|
195
195
|
ADS_ACTIVATE_SCOPE,
|
|
196
196
|
ADS_ACTIVATION_ABSOLUTE_MAX_ENTITIES,
|
|
@@ -1395,7 +1395,7 @@ import {
|
|
|
1395
1395
|
wordpressSchemaDeployResultDtoSchema,
|
|
1396
1396
|
wordpressSchemaStatusResultDtoSchema,
|
|
1397
1397
|
wordpressStatusDtoSchema
|
|
1398
|
-
} from "./chunk-
|
|
1398
|
+
} from "./chunk-CBYBYL7A.js";
|
|
1399
1399
|
|
|
1400
1400
|
// ../api-routes/src/user-session.ts
|
|
1401
1401
|
import crypto2 from "crypto";
|
|
@@ -54316,6 +54316,8 @@ function resolveGa4SyncDays(days) {
|
|
|
54316
54316
|
return { requestedDays, effectiveDays, clamped: effectiveDays !== requestedDays };
|
|
54317
54317
|
}
|
|
54318
54318
|
var GA4_REQUEST_TIMEOUT_MS = 3e4;
|
|
54319
|
+
var GA4_REPORT_TIMEOUT_MS = 6e4;
|
|
54320
|
+
var GA4_MAX_TIMEOUT_RETRIES = 1;
|
|
54319
54321
|
var GA4_MAX_PAGES = 50;
|
|
54320
54322
|
var GA4_MAX_CONCURRENT_REQUESTS = 4;
|
|
54321
54323
|
var GA4_MAX_RETRIES = 3;
|
|
@@ -54538,16 +54540,17 @@ function parseRetryAfter(headerValue3) {
|
|
|
54538
54540
|
}
|
|
54539
54541
|
return void 0;
|
|
54540
54542
|
}
|
|
54543
|
+
function isGa4Timeout(err) {
|
|
54544
|
+
return err instanceof Error && (err.name === "TimeoutError" || err.name === "AbortError");
|
|
54545
|
+
}
|
|
54541
54546
|
function isRetryableGa4Error(err) {
|
|
54542
54547
|
if (err instanceof GA4ApiError) {
|
|
54543
54548
|
return err.status === 429 || err.status >= 500;
|
|
54544
54549
|
}
|
|
54545
|
-
|
|
54546
|
-
return true;
|
|
54547
|
-
}
|
|
54548
|
-
return false;
|
|
54550
|
+
return isGa4Timeout(err);
|
|
54549
54551
|
}
|
|
54550
54552
|
async function withGa4Retry(fn, errLabel) {
|
|
54553
|
+
let timeoutRetries = 0;
|
|
54551
54554
|
return withRetry(fn, {
|
|
54552
54555
|
maxRetries: GA4_MAX_RETRIES,
|
|
54553
54556
|
baseDelayMs: GA4_INITIAL_RETRY_DELAY_MS,
|
|
@@ -54555,7 +54558,12 @@ async function withGa4Retry(fn, errLabel) {
|
|
|
54555
54558
|
// schedule operators have been seeing in production until we have a
|
|
54556
54559
|
// reason to introduce variance.
|
|
54557
54560
|
jitter: false,
|
|
54558
|
-
isRetryable:
|
|
54561
|
+
isRetryable: (err) => {
|
|
54562
|
+
if (!isRetryableGa4Error(err)) return false;
|
|
54563
|
+
if (!isGa4Timeout(err)) return true;
|
|
54564
|
+
timeoutRetries++;
|
|
54565
|
+
return timeoutRetries <= GA4_MAX_TIMEOUT_RETRIES;
|
|
54566
|
+
},
|
|
54559
54567
|
// Honor `Retry-After` when the server supplies it; fall back to the
|
|
54560
54568
|
// computed exponential delay otherwise.
|
|
54561
54569
|
computeDelayMs: (_attempt, err, defaultMs) => {
|
|
@@ -54571,6 +54579,7 @@ async function withGa4Retry(fn, errLabel) {
|
|
|
54571
54579
|
attempt: attempt + 1,
|
|
54572
54580
|
maxAttempts: GA4_MAX_RETRIES + 1,
|
|
54573
54581
|
status: ga4Err?.status,
|
|
54582
|
+
timedOut: isGa4Timeout(err),
|
|
54574
54583
|
delayMs,
|
|
54575
54584
|
usedRetryAfter: ga4Err?.retryAfterSeconds !== void 0
|
|
54576
54585
|
});
|
|
@@ -54589,7 +54598,7 @@ async function runReport(accessToken, propertyId, request) {
|
|
|
54589
54598
|
"Content-Type": "application/json"
|
|
54590
54599
|
},
|
|
54591
54600
|
body: JSON.stringify(request),
|
|
54592
|
-
signal: AbortSignal.timeout(
|
|
54601
|
+
signal: AbortSignal.timeout(GA4_REPORT_TIMEOUT_MS)
|
|
54593
54602
|
});
|
|
54594
54603
|
if (res.status === 401 || res.status === 403) {
|
|
54595
54604
|
const body = await res.text().catch(() => "");
|
|
@@ -54643,7 +54652,7 @@ async function batchRunReports(accessToken, propertyId, requests) {
|
|
|
54643
54652
|
"Content-Type": "application/json"
|
|
54644
54653
|
},
|
|
54645
54654
|
body: JSON.stringify({ requests }),
|
|
54646
|
-
signal: AbortSignal.timeout(
|
|
54655
|
+
signal: AbortSignal.timeout(GA4_REPORT_TIMEOUT_MS)
|
|
54647
54656
|
});
|
|
54648
54657
|
if (res.status === 401 || res.status === 403) {
|
|
54649
54658
|
const body = await res.text().catch(() => "");
|
|
@@ -64449,6 +64458,9 @@ function openThrottleCooldown(apiKey, err) {
|
|
|
64449
64458
|
throttleCooldownUntil.set(key, retryAt);
|
|
64450
64459
|
bingClientLog("error", "http.cooldown-open", { cooldownMs: retryAt - now });
|
|
64451
64460
|
}
|
|
64461
|
+
function bingThrottleCooldownRemainingMs(apiKey) {
|
|
64462
|
+
return throttleCooldownRemainingMs(apiKey);
|
|
64463
|
+
}
|
|
64452
64464
|
async function bingFetch(apiKey, endpoint, opts) {
|
|
64453
64465
|
const isIdempotent = opts?.idempotent ?? (opts?.method ?? "GET") === "GET";
|
|
64454
64466
|
const cooling = throttleCooldownRemainingMs(apiKey);
|
|
@@ -66657,6 +66669,23 @@ async function fetchGaSyncRanges(plan, fetchRange) {
|
|
|
66657
66669
|
return results;
|
|
66658
66670
|
}
|
|
66659
66671
|
|
|
66672
|
+
// ../api-routes/src/ga-sync-windows.ts
|
|
66673
|
+
function settleGaWindows(windows, results) {
|
|
66674
|
+
const read = [];
|
|
66675
|
+
const failed = [];
|
|
66676
|
+
results.forEach((result, index) => {
|
|
66677
|
+
if (result.status === "fulfilled") read.push(result.value);
|
|
66678
|
+
else failed.push({ window: windows[index], error: result.reason });
|
|
66679
|
+
});
|
|
66680
|
+
return { read, failed };
|
|
66681
|
+
}
|
|
66682
|
+
function keptGaWindows(windows, failures) {
|
|
66683
|
+
return windows.flatMap((window2) => {
|
|
66684
|
+
const failure = failures.find((entry) => entry.window === window2);
|
|
66685
|
+
return failure ? [{ window: window2, error: describeError(failure.error) }] : [];
|
|
66686
|
+
});
|
|
66687
|
+
}
|
|
66688
|
+
|
|
66660
66689
|
// ../api-routes/src/ga-search-landing-pages.ts
|
|
66661
66690
|
import crypto56 from "crypto";
|
|
66662
66691
|
import { and as and85, asc as asc25, count as count7, desc as desc44, eq as eq99, gte as gte25, lte as lte24, sql as sql43 } from "drizzle-orm";
|
|
@@ -67480,18 +67509,40 @@ async function ga4Routes(app, opts) {
|
|
|
67480
67509
|
let aiReferrals = [];
|
|
67481
67510
|
let socialReferrals = [];
|
|
67482
67511
|
const WINDOW_KEYS = GA_OVERVIEW_WINDOWS;
|
|
67483
|
-
const
|
|
67512
|
+
const windowsRequestedAt = /* @__PURE__ */ new Date();
|
|
67513
|
+
const [summary3, windowSummaryResults, windowMetricResults] = await Promise.all([
|
|
67484
67514
|
fetchAggregateSummary(accessToken, propertyId, days),
|
|
67485
|
-
Promise.
|
|
67486
|
-
Promise.
|
|
67515
|
+
Promise.allSettled(WINDOW_KEYS.map((w) => fetchWindowSummary(accessToken, propertyId, w))),
|
|
67516
|
+
Promise.allSettled(WINDOW_KEYS.map((w) => fetchWindowMetrics(accessToken, propertyId, w)))
|
|
67487
67517
|
]);
|
|
67518
|
+
const { read: windowSummaries, failed: failedSummaryWindows } = settleGaWindows(WINDOW_KEYS, windowSummaryResults);
|
|
67519
|
+
const { read: windowMetrics, failed: failedMetricWindows } = settleGaWindows(WINDOW_KEYS, windowMetricResults);
|
|
67520
|
+
const zoneReport = windowMetrics[0];
|
|
67521
|
+
if (!zoneReport) {
|
|
67522
|
+
const firstError = failedMetricWindows[0].error;
|
|
67523
|
+
throw firstError instanceof Error ? firstError : new Error(describeError(firstError));
|
|
67524
|
+
}
|
|
67525
|
+
const reportTimeZone2 = zoneReport.timeZone;
|
|
67526
|
+
const failedWindows = [...failedMetricWindows, ...failedSummaryWindows];
|
|
67527
|
+
for (const failure of failedWindows) {
|
|
67528
|
+
componentFailure ??= { error: failure.error };
|
|
67529
|
+
gaLog("warn", "window.kept", {
|
|
67530
|
+
projectId: project.id,
|
|
67531
|
+
runId,
|
|
67532
|
+
window: failure.window,
|
|
67533
|
+
report: failedMetricWindows.includes(failure) ? "totals" : "summary",
|
|
67534
|
+
error: describeError(failure.error)
|
|
67535
|
+
});
|
|
67536
|
+
}
|
|
67537
|
+
const keptWindows = keptGaWindows(WINDOW_KEYS, failedWindows);
|
|
67488
67538
|
const requested = { startDate: summary3.periodStart, endDate: summary3.periodEnd };
|
|
67489
|
-
const definition2 = JSON.stringify(["v1",
|
|
67539
|
+
const definition2 = JSON.stringify(["v1", reportTimeZone2 ?? "UTC"]);
|
|
67490
67540
|
const planInput = { projectId: project.id, propertyId, requested, definition: definition2 };
|
|
67491
67541
|
const trafficPlan = planGaSyncCoverage(app.db, { ...planInput, component: "traffic" }, startedAt);
|
|
67492
67542
|
const aiPlan = planGaSyncCoverage(app.db, { ...planInput, component: "ai" }, startedAt);
|
|
67493
67543
|
const socialPlan = planGaSyncCoverage(app.db, { ...planInput, component: "social" }, startedAt);
|
|
67494
|
-
const
|
|
67544
|
+
const longestWindowKey = WINDOW_KEYS.at(-1);
|
|
67545
|
+
const longestWindow = windowMetrics.find((metric2) => metric2.windowKey === longestWindowKey) ?? gaOverviewComparisonRanges(longestWindowKey, windowsRequestedAt, reportTimeZone2 ?? "UTC");
|
|
67495
67546
|
const dailyPlan = planGaSyncCoverage(app.db, {
|
|
67496
67547
|
...planInput,
|
|
67497
67548
|
component: "daily",
|
|
@@ -67509,7 +67560,7 @@ async function ga4Routes(app, opts) {
|
|
|
67509
67560
|
requested: { startDate: shiftIsoCalendarDate(requested.endDate, -leadDays), endDate: requested.endDate }
|
|
67510
67561
|
}, startedAt);
|
|
67511
67562
|
const searchRequestedAt = /* @__PURE__ */ new Date();
|
|
67512
|
-
const searchTimeZone =
|
|
67563
|
+
const searchTimeZone = reportTimeZone2 ?? null;
|
|
67513
67564
|
const searchWindows = syncSearchLanding ? searchLandingWindowsToFetch(app.db, project.id, propertyId, searchTimeZone, searchRequestedAt.toISOString()) : [];
|
|
67514
67565
|
const measurementFetch = Promise.allSettled([
|
|
67515
67566
|
fetchGaSyncRanges(acquisitionPlan, (range) => fetchAcquisitionByChannel(accessToken, propertyId, acquisitionDays, { dateRange: range })),
|
|
@@ -67594,7 +67645,12 @@ async function ga4Routes(app, opts) {
|
|
|
67594
67645
|
createdAt: now
|
|
67595
67646
|
}).run();
|
|
67596
67647
|
}
|
|
67597
|
-
|
|
67648
|
+
if (windowMetrics.length > 0) {
|
|
67649
|
+
tx.delete(gaWindowMetrics).where(and86(
|
|
67650
|
+
eq100(gaWindowMetrics.projectId, project.id),
|
|
67651
|
+
inArray49(gaWindowMetrics.windowKey, windowMetrics.map((metric2) => metric2.windowKey))
|
|
67652
|
+
)).run();
|
|
67653
|
+
}
|
|
67598
67654
|
for (const windowMetric of windowMetrics) {
|
|
67599
67655
|
for (const [period2, totals] of [
|
|
67600
67656
|
[GaOverviewPeriods.current, windowMetric.current],
|
|
@@ -67695,7 +67751,12 @@ async function ga4Routes(app, opts) {
|
|
|
67695
67751
|
syncedAt: now,
|
|
67696
67752
|
syncRunId: runId
|
|
67697
67753
|
}).run();
|
|
67698
|
-
|
|
67754
|
+
if (windowSummaries.length > 0) {
|
|
67755
|
+
tx.delete(gaTrafficWindowSummaries).where(and86(
|
|
67756
|
+
eq100(gaTrafficWindowSummaries.projectId, project.id),
|
|
67757
|
+
inArray49(gaTrafficWindowSummaries.windowKey, windowSummaries.map((ws) => ws.windowKey))
|
|
67758
|
+
)).run();
|
|
67759
|
+
}
|
|
67699
67760
|
for (const ws of windowSummaries) {
|
|
67700
67761
|
tx.insert(gaTrafficWindowSummaries).values({
|
|
67701
67762
|
id: crypto57.randomUUID(),
|
|
@@ -67864,7 +67925,8 @@ async function ga4Routes(app, opts) {
|
|
|
67864
67925
|
days,
|
|
67865
67926
|
...clamped ? { requestedDays, clamped } : {},
|
|
67866
67927
|
totalUsers: summary3.totalUsers,
|
|
67867
|
-
...only ? { only } : {}
|
|
67928
|
+
...only ? { only } : {},
|
|
67929
|
+
...keptWindows.length > 0 ? { keptWindows: keptWindows.map((kept) => kept.window) } : {}
|
|
67868
67930
|
});
|
|
67869
67931
|
const counts2 = { rows: rows.length + dailyTotals.rows.length + aiReferrals.length + socialReferrals.length };
|
|
67870
67932
|
if (componentFailure) {
|
|
@@ -67888,6 +67950,7 @@ async function ga4Routes(app, opts) {
|
|
|
67888
67950
|
leads: leadResult,
|
|
67889
67951
|
...searchLandingResult ? { searchLandingPages: searchLandingResult } : {}
|
|
67890
67952
|
},
|
|
67953
|
+
...keptWindows.length > 0 ? { keptWindows } : {},
|
|
67891
67954
|
...syncedComponents ? { syncedComponents } : {}
|
|
67892
67955
|
};
|
|
67893
67956
|
} catch (e) {
|
|
@@ -77681,7 +77744,43 @@ var ga4ConnectionCheck = {
|
|
|
77681
77744
|
var GA_AUTH_CHECKS = [ga4ConnectionCheck];
|
|
77682
77745
|
|
|
77683
77746
|
// ../api-routes/src/doctor/checks/data-freshness.ts
|
|
77684
|
-
import { and as
|
|
77747
|
+
import { and as and99, desc as desc52, eq as eq116 } from "drizzle-orm";
|
|
77748
|
+
|
|
77749
|
+
// ../api-routes/src/doctor/checks/sync-run-state.ts
|
|
77750
|
+
import { and as and98, count as count9, desc as desc51, eq as eq115, gte as gte30, gt as gt9, inArray as inArray53, isNull as isNull18, notInArray as notInArray4, or as or21 } from "drizzle-orm";
|
|
77751
|
+
var SYNC_FAILURE_WINDOW = 3;
|
|
77752
|
+
var FINISHED_STATUSES = [RunStatuses.completed, RunStatuses.partial, RunStatuses.failed];
|
|
77753
|
+
var SUCCESS_STATUSES = [RunStatuses.completed, RunStatuses.partial];
|
|
77754
|
+
function latestErrorText(raw) {
|
|
77755
|
+
const parsed = parseRunError(raw);
|
|
77756
|
+
return parsed ? formatRunErrorOneLine(parsed) : "no error was recorded";
|
|
77757
|
+
}
|
|
77758
|
+
function readSyncRunState(db, projectId, kind, options = {}) {
|
|
77759
|
+
const scope = and98(
|
|
77760
|
+
eq115(runs.projectId, projectId),
|
|
77761
|
+
eq115(runs.kind, kind),
|
|
77762
|
+
...options.sourceId ? [eq115(runs.sourceId, options.sourceId)] : [],
|
|
77763
|
+
...options.nothingToSyncErrors?.length ? [or21(isNull18(runs.error), notInArray4(runs.error, [...options.nothingToSyncErrors]))] : []
|
|
77764
|
+
);
|
|
77765
|
+
const graded = options.since ? and98(scope, gte30(runs.createdAt, options.since)) : scope;
|
|
77766
|
+
const recent = db.select({ id: runs.id, status: runs.status, trigger: runs.trigger, error: runs.error, createdAt: runs.createdAt }).from(runs).where(and98(graded, inArray53(runs.status, FINISHED_STATUSES))).orderBy(desc51(runs.createdAt)).limit(SYNC_FAILURE_WINDOW).all();
|
|
77767
|
+
const lastSuccess = db.select({ createdAt: runs.createdAt, finishedAt: runs.finishedAt }).from(runs).where(and98(graded, inArray53(runs.status, SUCCESS_STATUSES))).orderBy(desc51(runs.createdAt)).limit(1).get();
|
|
77768
|
+
const failureCount = db.select({ count: count9() }).from(runs).where(and98(lastSuccess ? and98(graded, gt9(runs.createdAt, lastSuccess.createdAt)) : graded, eq115(runs.status, RunStatuses.failed))).get();
|
|
77769
|
+
const failuresSinceSuccess = Number(failureCount?.count ?? 0);
|
|
77770
|
+
const latest = recent[0];
|
|
77771
|
+
return {
|
|
77772
|
+
latestStatus: latest?.status ?? null,
|
|
77773
|
+
latestRunAt: latest?.createdAt ?? null,
|
|
77774
|
+
latestRunId: latest?.id ?? null,
|
|
77775
|
+
latestTrigger: latest?.trigger ?? null,
|
|
77776
|
+
latestError: latest?.status === RunStatuses.failed ? latestErrorText(latest.error) : null,
|
|
77777
|
+
lastSuccessAt: lastSuccess ? lastSuccess.finishedAt ?? lastSuccess.createdAt : null,
|
|
77778
|
+
consecutiveFailures: failuresSinceSuccess,
|
|
77779
|
+
repeatedFailure: recent.length >= SYNC_FAILURE_WINDOW && recent.every((run) => run.status === RunStatuses.failed)
|
|
77780
|
+
};
|
|
77781
|
+
}
|
|
77782
|
+
|
|
77783
|
+
// ../api-routes/src/doctor/checks/data-freshness.ts
|
|
77685
77784
|
var GA_DATA_AGING_DAYS = 3;
|
|
77686
77785
|
var GA_DATA_STALE_DAYS = 5;
|
|
77687
77786
|
var GSC_DATA_AGING_DAYS = 5;
|
|
@@ -77690,6 +77789,7 @@ var BING_DATA_AGING_DAYS = 7;
|
|
|
77690
77789
|
var SYNC_IDLE_DAYS = 3;
|
|
77691
77790
|
var NOT_SYNCING_URGENT_DAYS = 8;
|
|
77692
77791
|
var GSC_REPORTING_TIME_ZONE2 = "America/Los_Angeles";
|
|
77792
|
+
var SUMMARY_ERROR_LIMIT = 300;
|
|
77693
77793
|
var DAY_MS6 = 24 * 60 * 60 * 1e3;
|
|
77694
77794
|
var ISO_DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
|
|
77695
77795
|
function utcFromIsoDate(date) {
|
|
@@ -77710,8 +77810,8 @@ function daysSinceDate(date, now = /* @__PURE__ */ new Date(), timeZone) {
|
|
|
77710
77810
|
function skipped(code, summary3) {
|
|
77711
77811
|
return { status: CheckStatuses.skipped, code, summary: summary3, remediation: null };
|
|
77712
77812
|
}
|
|
77713
|
-
function lastSyncAgeDays(ctx,
|
|
77714
|
-
const row = ctx.db.select({ createdAt: runs.createdAt }).from(runs).where(
|
|
77813
|
+
function lastSyncAgeDays(ctx, kind) {
|
|
77814
|
+
const row = ctx.db.select({ createdAt: runs.createdAt }).from(runs).where(and99(eq116(runs.projectId, ctx.project.id), eq116(runs.kind, kind), eq116(runs.status, RunStatuses.completed))).orderBy(desc52(runs.createdAt)).limit(1).get();
|
|
77715
77815
|
if (!row?.createdAt) return null;
|
|
77716
77816
|
const age = Math.floor((Date.now() - Date.parse(row.createdAt)) / DAY_MS6);
|
|
77717
77817
|
return Number.isFinite(age) ? age : null;
|
|
@@ -77720,7 +77820,7 @@ function grade(ctx, spec, newestDate) {
|
|
|
77720
77820
|
const projectName = ctx.project.name;
|
|
77721
77821
|
const code = (suffix) => `${spec.source}.data.${suffix}`;
|
|
77722
77822
|
const sync = spec.syncCommand(projectName);
|
|
77723
|
-
const syncAge = lastSyncAgeDays(ctx, spec.
|
|
77823
|
+
const syncAge = lastSyncAgeDays(ctx, spec.syncKind);
|
|
77724
77824
|
const syncIdle = syncAge === null || syncAge >= SYNC_IDLE_DAYS;
|
|
77725
77825
|
if (!newestDate) {
|
|
77726
77826
|
return {
|
|
@@ -77751,6 +77851,26 @@ function grade(ctx, spec, newestDate) {
|
|
|
77751
77851
|
details
|
|
77752
77852
|
};
|
|
77753
77853
|
}
|
|
77854
|
+
const syncState = readSyncRunState(ctx.db, ctx.project.id, spec.syncKind);
|
|
77855
|
+
if (syncState.latestStatus === RunStatuses.failed) {
|
|
77856
|
+
const errorText = syncState.latestError ?? "no error was recorded";
|
|
77857
|
+
const shownError = errorText.length > SUMMARY_ERROR_LIMIT ? `${truncateUtf16(errorText, SUMMARY_ERROR_LIMIT)}...` : errorText;
|
|
77858
|
+
const failures = syncState.consecutiveFailures;
|
|
77859
|
+
return {
|
|
77860
|
+
status: CheckStatuses.warn,
|
|
77861
|
+
code: code("sync-failing"),
|
|
77862
|
+
...age >= spec.staleDays ? { urgent: true } : {},
|
|
77863
|
+
summary: `${failures <= 1 ? `The latest ${spec.label} sync` : `The last ${failures} ${spec.label} syncs`} failed, and stored data ends ${newestDate} (${age} days). Latest error: ${shownError}`,
|
|
77864
|
+
remediation: `Fix the cause the error names, then run \`${sync}\`.`,
|
|
77865
|
+
details: {
|
|
77866
|
+
...details,
|
|
77867
|
+
consecutiveFailures: failures,
|
|
77868
|
+
latestRunAt: syncState.latestRunAt,
|
|
77869
|
+
latestError: syncState.latestError,
|
|
77870
|
+
lastSuccessAt: syncState.lastSuccessAt
|
|
77871
|
+
}
|
|
77872
|
+
};
|
|
77873
|
+
}
|
|
77754
77874
|
if (syncIdle) {
|
|
77755
77875
|
return {
|
|
77756
77876
|
status: CheckStatuses.warn,
|
|
@@ -77780,7 +77900,7 @@ var GA_SPEC = {
|
|
|
77780
77900
|
label: "GA4",
|
|
77781
77901
|
agingDays: GA_DATA_AGING_DAYS,
|
|
77782
77902
|
staleDays: GA_DATA_STALE_DAYS,
|
|
77783
|
-
|
|
77903
|
+
syncKind: RunKinds["ga-sync"],
|
|
77784
77904
|
syncCommand: (name) => `canonry ga sync ${name}`,
|
|
77785
77905
|
quietExplanation: "GA4 omits days with no sessions, so a genuinely quiet period clears itself on the next visit.",
|
|
77786
77906
|
brokenExplanation: "If the site did have visitors, check that the GA4 tag or its Tag Manager container is still on the live site."
|
|
@@ -77791,7 +77911,7 @@ var GSC_SPEC = {
|
|
|
77791
77911
|
agingDays: GSC_DATA_AGING_DAYS,
|
|
77792
77912
|
staleDays: GSC_DATA_STALE_DAYS,
|
|
77793
77913
|
timeZone: GSC_REPORTING_TIME_ZONE2,
|
|
77794
|
-
|
|
77914
|
+
syncKind: RunKinds["gsc-sync"],
|
|
77795
77915
|
syncCommand: (name) => `canonry google sync ${name}`,
|
|
77796
77916
|
quietExplanation: "Search Console omits days with no impressions and reports two to three days behind, so a quiet period clears itself.",
|
|
77797
77917
|
brokenExplanation: "If the site did have impressions, check that the property still lists this site and the connected account still has access."
|
|
@@ -77813,7 +77933,7 @@ var gaRecentDataCheck = {
|
|
|
77813
77933
|
const connection = gaConnected(ctx);
|
|
77814
77934
|
if (connection === "store-unavailable") return skipped("ga.data.store-unavailable", "No GA4 credential store configured for this deployment.");
|
|
77815
77935
|
if (connection === "not-connected") return skipped("ga.data.not-connected", "GA4 is not connected for this project.");
|
|
77816
|
-
const newest = ctx.db.select({ date: gaDailyTotals.date }).from(gaDailyTotals).where(
|
|
77936
|
+
const newest = ctx.db.select({ date: gaDailyTotals.date }).from(gaDailyTotals).where(eq116(gaDailyTotals.projectId, ctx.project.id)).orderBy(desc52(gaDailyTotals.date)).limit(1).get();
|
|
77817
77937
|
return grade(ctx, GA_SPEC, newest?.date);
|
|
77818
77938
|
}
|
|
77819
77939
|
};
|
|
@@ -77828,16 +77948,16 @@ var gscRecentDataCheck = {
|
|
|
77828
77948
|
if (!ctx.googleConnectionStore.getConnection(ctx.project.canonicalDomain, "gsc")) {
|
|
77829
77949
|
return skipped("gsc.data.not-connected", "Search Console is not connected for this project.");
|
|
77830
77950
|
}
|
|
77831
|
-
const watermark = ctx.db.select({ dataThroughDate: gscDataWatermarks.dataThroughDate }).from(gscDataWatermarks).where(
|
|
77951
|
+
const watermark = ctx.db.select({ dataThroughDate: gscDataWatermarks.dataThroughDate }).from(gscDataWatermarks).where(eq116(gscDataWatermarks.projectId, ctx.project.id)).get();
|
|
77832
77952
|
if (watermark?.dataThroughDate) return grade(ctx, GSC_SPEC, watermark.dataThroughDate);
|
|
77833
|
-
const newest = ctx.db.select({ date: gscDailyTotals.date }).from(gscDailyTotals).where(
|
|
77953
|
+
const newest = ctx.db.select({ date: gscDailyTotals.date }).from(gscDailyTotals).where(eq116(gscDailyTotals.projectId, ctx.project.id)).orderBy(desc52(gscDailyTotals.date)).limit(1).get();
|
|
77834
77954
|
return grade(ctx, GSC_SPEC, newest?.date);
|
|
77835
77955
|
}
|
|
77836
77956
|
};
|
|
77837
77957
|
var DATA_FRESHNESS_CHECKS = [gaRecentDataCheck, gscRecentDataCheck];
|
|
77838
77958
|
|
|
77839
77959
|
// ../api-routes/src/doctor/checks/seo-refresh.ts
|
|
77840
|
-
import { and as
|
|
77960
|
+
import { and as and100, asc as asc29, desc as desc53, eq as eq117, gt as gt10, inArray as inArray54, sql as sql49 } from "drizzle-orm";
|
|
77841
77961
|
var GRACE_DAYS = 2;
|
|
77842
77962
|
var DAY_MS7 = 24 * 60 * 60 * 1e3;
|
|
77843
77963
|
var FIRING_SPAN_MS = 6e4;
|
|
@@ -77846,7 +77966,7 @@ function skipped2(code, summary3) {
|
|
|
77846
77966
|
return { status: CheckStatuses.skipped, code, summary: summary3, remediation: null };
|
|
77847
77967
|
}
|
|
77848
77968
|
function seoSyncRuns(projectId) {
|
|
77849
|
-
return
|
|
77969
|
+
return and100(eq117(runs.projectId, projectId), eq117(runs.kind, RunKinds["seo-sync"]));
|
|
77850
77970
|
}
|
|
77851
77971
|
function scheduleTiming(schedule) {
|
|
77852
77972
|
if (!schedule.recurrence) return { cronExpr: schedule.cronExpr, timezone: schedule.timezone, recurrence: null };
|
|
@@ -77854,16 +77974,16 @@ function scheduleTiming(schedule) {
|
|
|
77854
77974
|
return recurrence ? { cronExpr: schedule.cronExpr, timezone: schedule.timezone, recurrence } : null;
|
|
77855
77975
|
}
|
|
77856
77976
|
function latestFiring(ctx, projectId, enabledSince) {
|
|
77857
|
-
const scheduled =
|
|
77858
|
-
const newest = ctx.db.select({ createdAt: runs.createdAt }).from(runs).where(scheduled).orderBy(
|
|
77977
|
+
const scheduled = and100(seoSyncRuns(projectId), eq117(runs.trigger, RunTriggers.scheduled), gt10(runs.createdAt, enabledSince));
|
|
77978
|
+
const newest = ctx.db.select({ createdAt: runs.createdAt }).from(runs).where(scheduled).orderBy(desc53(runs.createdAt)).limit(1).get();
|
|
77859
77979
|
if (!newest) return [];
|
|
77860
77980
|
const newestMs = Date.parse(newest.createdAt);
|
|
77861
77981
|
const after = Number.isFinite(newestMs) ? new Date(newestMs - FIRING_SPAN_MS).toISOString() : newest.createdAt;
|
|
77862
|
-
return ctx.db.select({ id: runs.id, status: runs.status, error: runs.error, createdAt: runs.createdAt }).from(runs).where(
|
|
77982
|
+
return ctx.db.select({ id: runs.id, status: runs.status, error: runs.error, createdAt: runs.createdAt }).from(runs).where(and100(scheduled, gt10(runs.createdAt, after))).orderBy(asc29(runs.createdAt), asc29(runs.id)).all();
|
|
77863
77983
|
}
|
|
77864
77984
|
function lastCompleted(ctx, projectId) {
|
|
77865
77985
|
const at = sql49`coalesce(${runs.finishedAt}, ${runs.createdAt})`;
|
|
77866
|
-
return ctx.db.select({ id: runs.id, at }).from(runs).where(
|
|
77986
|
+
return ctx.db.select({ id: runs.id, at }).from(runs).where(and100(seoSyncRuns(projectId), eq117(runs.status, RunStatuses.completed))).orderBy(desc53(at)).limit(1).get() ?? null;
|
|
77867
77987
|
}
|
|
77868
77988
|
function isIncomplete(run) {
|
|
77869
77989
|
return run.status === RunStatuses.failed || run.status === RunStatuses.partial;
|
|
@@ -77877,7 +77997,7 @@ function unsettledRuns(ctx, projectId, firing, profiles) {
|
|
|
77877
77997
|
const incomplete = firing.filter(isIncomplete);
|
|
77878
77998
|
const firedAt = firing[firing.length - 1]?.createdAt;
|
|
77879
77999
|
if (incomplete.length === 0 || !firedAt) return incomplete;
|
|
77880
|
-
const refreshed = new Set(ctx.db.select({ profileId: seoJobs.profileId }).from(runs).innerJoin(seoJobs,
|
|
78000
|
+
const refreshed = new Set(ctx.db.select({ profileId: seoJobs.profileId }).from(runs).innerJoin(seoJobs, eq117(seoJobs.runId, runs.id)).where(and100(seoSyncRuns(projectId), eq117(runs.status, RunStatuses.completed), gt10(runs.createdAt, firedAt))).all().map((row) => row.profileId));
|
|
77881
78001
|
return incomplete.filter((run) => {
|
|
77882
78002
|
const profile = profiles.get(run.id) ?? null;
|
|
77883
78003
|
return profile === null ? refreshed.size === 0 : !refreshed.has(profile);
|
|
@@ -77887,7 +78007,7 @@ var COUNT_LIST = new Intl.ListFormat("en", { style: "long", type: "conjunction"
|
|
|
77887
78007
|
function refreshReason(ctx, run) {
|
|
77888
78008
|
const stored = parseRunError(run.error);
|
|
77889
78009
|
if (stored) return formatRunErrorOneLine(stored);
|
|
77890
|
-
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,
|
|
78010
|
+
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, eq117(seoTasks.jobId, seoJobs.id)).where(eq117(seoJobs.runId, run.id)).all());
|
|
77891
78011
|
const failed = tasks.filter((task) => task.status === SeoRunStatuses.failed || task.status === SeoRunStatuses["reconciliation-required"]);
|
|
77892
78012
|
const partial = tasks.filter((task) => task.status === SeoRunStatuses.partial).length;
|
|
77893
78013
|
const cancelled = tasks.filter((task) => task.status === SeoRunStatuses.cancelled).length;
|
|
@@ -77907,7 +78027,7 @@ function refreshReason(ctx, run) {
|
|
|
77907
78027
|
return `Of ${tasks.length} ${unit}, ${COUNT_LIST.format(counts2)}.${errors ? ` ${errors}` : ""}`;
|
|
77908
78028
|
}
|
|
77909
78029
|
function gradeSeoRefresh(ctx, project) {
|
|
77910
|
-
const schedule = ctx.db.select().from(schedules).where(
|
|
78030
|
+
const schedule = ctx.db.select().from(schedules).where(and100(eq117(schedules.projectId, project.id), eq117(schedules.kind, SchedulableRunKinds["seo-sync"]))).get();
|
|
77911
78031
|
if (!schedule) return skipped2("seo.data.not-scheduled", "No SEO refresh schedule is set for this project.");
|
|
77912
78032
|
if (!schedule.enabled) return skipped2("seo.data.not-scheduled", "The SEO refresh schedule is disabled.");
|
|
77913
78033
|
const name = project.name;
|
|
@@ -77979,7 +78099,7 @@ function gradeSeoRefresh(ctx, project) {
|
|
|
77979
78099
|
};
|
|
77980
78100
|
}
|
|
77981
78101
|
if (now >= Date.parse(deadlineAt)) {
|
|
77982
|
-
const active = ctx.db.select({ id: runs.id, createdAt: runs.createdAt }).from(runs).where(
|
|
78102
|
+
const active = ctx.db.select({ id: runs.id, createdAt: runs.createdAt }).from(runs).where(and100(seoSyncRuns(project.id), inArray54(runs.status, [RunStatuses.queued, RunStatuses.running]))).orderBy(asc29(runs.createdAt)).limit(1).get();
|
|
77983
78103
|
const since = last ? `No SEO refresh has completed since ${day(last.at)}.` : "No SEO refresh has completed since the schedule was enabled.";
|
|
77984
78104
|
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.`;
|
|
77985
78105
|
return {
|
|
@@ -78289,7 +78409,7 @@ var siteReachabilityCheck = {
|
|
|
78289
78409
|
var SITE_REACHABILITY_CHECKS = [siteReachabilityCheck];
|
|
78290
78410
|
|
|
78291
78411
|
// ../api-routes/src/doctor/checks/api-hosts.ts
|
|
78292
|
-
import { eq as
|
|
78412
|
+
import { eq as eq119 } from "drizzle-orm";
|
|
78293
78413
|
|
|
78294
78414
|
// ../api-routes/src/api-host-probe.ts
|
|
78295
78415
|
import dns4 from "dns/promises";
|
|
@@ -78395,11 +78515,8 @@ async function probeApiHost(host, options = {}) {
|
|
|
78395
78515
|
}
|
|
78396
78516
|
|
|
78397
78517
|
// ../api-routes/src/doctor/checks/integration-sync.ts
|
|
78398
|
-
import { and as
|
|
78399
|
-
var
|
|
78400
|
-
var SUMMARY_ERROR_LIMIT = 300;
|
|
78401
|
-
var FINISHED_STATUSES = [RunStatuses.completed, RunStatuses.partial, RunStatuses.failed];
|
|
78402
|
-
var SUCCESS_STATUSES = [RunStatuses.completed, RunStatuses.partial];
|
|
78518
|
+
import { and as and101, eq as eq118 } from "drizzle-orm";
|
|
78519
|
+
var SUMMARY_ERROR_LIMIT2 = 300;
|
|
78403
78520
|
var GBP_NOTHING_TO_SYNC_ERRORS = [serializeRunError({ message: GBP_NO_SELECTED_LOCATIONS_ERROR })];
|
|
78404
78521
|
var CONNECTED = { state: "connected", since: null };
|
|
78405
78522
|
function googleMarketingConnection(provider) {
|
|
@@ -78422,7 +78539,7 @@ function gscConnection(ctx, project) {
|
|
|
78422
78539
|
function gbpConnection(ctx, project) {
|
|
78423
78540
|
if (!ctx.googleConnectionStore) return { state: "store-unavailable" };
|
|
78424
78541
|
if (!ctx.googleConnectionStore.getConnection(project.canonicalDomain, "gbp")) return { state: "not-connected" };
|
|
78425
|
-
const selected = ctx.db.select({ locationName: gbpLocations.locationName }).from(gbpLocations).where(
|
|
78542
|
+
const selected = ctx.db.select({ locationName: gbpLocations.locationName }).from(gbpLocations).where(and101(eq118(gbpLocations.projectId, project.id), eq118(gbpLocations.selected, true))).limit(1).get();
|
|
78426
78543
|
return selected ? CONNECTED : { state: "no-selected-locations" };
|
|
78427
78544
|
}
|
|
78428
78545
|
function gaConnection(ctx, project) {
|
|
@@ -78490,34 +78607,6 @@ var SPECS = [
|
|
|
78490
78607
|
function skipped4(code, summary3) {
|
|
78491
78608
|
return { status: CheckStatuses.skipped, code, summary: summary3, remediation: null };
|
|
78492
78609
|
}
|
|
78493
|
-
function latestErrorText(raw) {
|
|
78494
|
-
const parsed = parseRunError(raw);
|
|
78495
|
-
return parsed ? formatRunErrorOneLine(parsed) : "no error was recorded";
|
|
78496
|
-
}
|
|
78497
|
-
function readSyncRunState(db, projectId, kind, options = {}) {
|
|
78498
|
-
const scope = and100(
|
|
78499
|
-
eq117(runs.projectId, projectId),
|
|
78500
|
-
eq117(runs.kind, kind),
|
|
78501
|
-
...options.sourceId ? [eq117(runs.sourceId, options.sourceId)] : [],
|
|
78502
|
-
...options.nothingToSyncErrors?.length ? [or21(isNull18(runs.error), notInArray4(runs.error, [...options.nothingToSyncErrors]))] : []
|
|
78503
|
-
);
|
|
78504
|
-
const graded = options.since ? and100(scope, gte30(runs.createdAt, options.since)) : scope;
|
|
78505
|
-
const recent = db.select({ id: runs.id, status: runs.status, trigger: runs.trigger, error: runs.error, createdAt: runs.createdAt }).from(runs).where(and100(graded, inArray55(runs.status, FINISHED_STATUSES))).orderBy(desc53(runs.createdAt)).limit(SYNC_FAILURE_WINDOW).all();
|
|
78506
|
-
const lastSuccess = db.select({ createdAt: runs.createdAt, finishedAt: runs.finishedAt }).from(runs).where(and100(graded, inArray55(runs.status, SUCCESS_STATUSES))).orderBy(desc53(runs.createdAt)).limit(1).get();
|
|
78507
|
-
const failureCount = db.select({ count: count9() }).from(runs).where(and100(lastSuccess ? and100(graded, gt10(runs.createdAt, lastSuccess.createdAt)) : graded, eq117(runs.status, RunStatuses.failed))).get();
|
|
78508
|
-
const failuresSinceSuccess = Number(failureCount?.count ?? 0);
|
|
78509
|
-
const latest = recent[0];
|
|
78510
|
-
return {
|
|
78511
|
-
latestStatus: latest?.status ?? null,
|
|
78512
|
-
latestRunAt: latest?.createdAt ?? null,
|
|
78513
|
-
latestRunId: latest?.id ?? null,
|
|
78514
|
-
latestTrigger: latest?.trigger ?? null,
|
|
78515
|
-
latestError: latest?.status === RunStatuses.failed ? latestErrorText(latest.error) : null,
|
|
78516
|
-
lastSuccessAt: lastSuccess ? lastSuccess.finishedAt ?? lastSuccess.createdAt : null,
|
|
78517
|
-
consecutiveFailures: failuresSinceSuccess,
|
|
78518
|
-
repeatedFailure: recent.length >= SYNC_FAILURE_WINDOW && recent.every((run) => run.status === RunStatuses.failed)
|
|
78519
|
-
};
|
|
78520
|
-
}
|
|
78521
78610
|
function gradeSyncFailures(ctx, spec) {
|
|
78522
78611
|
const code = (suffix) => `${spec.prefix}.sync.${suffix}`;
|
|
78523
78612
|
const project = ctx.project;
|
|
@@ -78551,7 +78640,7 @@ function gradeSyncFailures(ctx, spec) {
|
|
|
78551
78640
|
};
|
|
78552
78641
|
if (state.repeatedFailure) {
|
|
78553
78642
|
const errorText = state.latestError ?? "no error was recorded";
|
|
78554
|
-
const shownError = errorText.length >
|
|
78643
|
+
const shownError = errorText.length > SUMMARY_ERROR_LIMIT2 ? `${truncateUtf16(errorText, SUMMARY_ERROR_LIMIT2)}...` : errorText;
|
|
78555
78644
|
const lastSuccessText = state.lastSuccessAt ?? (connection.since ? `none since connecting at ${connection.since}` : "never");
|
|
78556
78645
|
const notFound2 = spec.notFoundRemediation && /\bwas not found\b/i.test(errorText);
|
|
78557
78646
|
return {
|
|
@@ -78601,7 +78690,7 @@ function connectionFor(prefix, ctx, project) {
|
|
|
78601
78690
|
if (prefix === "google-ads") return googleMarketingConnection("googleAds")(ctx);
|
|
78602
78691
|
if (prefix === "gtm") return googleMarketingConnection("gtm")(ctx);
|
|
78603
78692
|
if (prefix === "bing") return ctx.bingConnectionStore?.getConnection(project.canonicalDomain) ? { state: "connected", since: null } : { state: "not-connected" };
|
|
78604
|
-
return ctx.db.select({ id: adsConnections.id }).from(adsConnections).where(
|
|
78693
|
+
return ctx.db.select({ id: adsConnections.id }).from(adsConnections).where(eq119(adsConnections.projectId, project.id)).limit(1).get() ? { state: "connected", since: null } : { state: "not-connected" };
|
|
78605
78694
|
}
|
|
78606
78695
|
function syncCommand(prefix) {
|
|
78607
78696
|
if (prefix === "gsc") return "google sync";
|
|
@@ -78646,7 +78735,7 @@ function definition(prefix) {
|
|
|
78646
78735
|
var API_HOST_CHECKS = Object.keys(API_HOST_TABLE).map(definition);
|
|
78647
78736
|
|
|
78648
78737
|
// ../api-routes/src/doctor/checks/gbp-auth.ts
|
|
78649
|
-
import { and as
|
|
78738
|
+
import { and as and102, eq as eq120 } from "drizzle-orm";
|
|
78650
78739
|
var RECENT_SYNC_WARN_DAYS = 4;
|
|
78651
78740
|
var RECENT_SYNC_FAIL_DAYS = 30;
|
|
78652
78741
|
function skippedNoProject3() {
|
|
@@ -78666,7 +78755,7 @@ function storeUnavailable() {
|
|
|
78666
78755
|
};
|
|
78667
78756
|
}
|
|
78668
78757
|
function hasSelectedLocation(ctx, projectId) {
|
|
78669
|
-
return !!ctx.db.select({ id: gbpLocations.id }).from(gbpLocations).where(
|
|
78758
|
+
return !!ctx.db.select({ id: gbpLocations.id }).from(gbpLocations).where(and102(eq120(gbpLocations.projectId, projectId), eq120(gbpLocations.selected, true))).limit(1).get();
|
|
78670
78759
|
}
|
|
78671
78760
|
async function resolveGbpToken(ctx) {
|
|
78672
78761
|
if (!ctx.project) return { ok: false, output: skippedNoProject3() };
|
|
@@ -78926,7 +79015,7 @@ var recentSyncCheck = {
|
|
|
78926
79015
|
title: "GBP recent sync",
|
|
78927
79016
|
run: (ctx) => {
|
|
78928
79017
|
if (!ctx.project) return skippedNoProject3();
|
|
78929
|
-
const selected = ctx.db.select({ locationName: gbpLocations.locationName, syncedAt: gbpLocations.syncedAt }).from(gbpLocations).where(
|
|
79018
|
+
const selected = ctx.db.select({ locationName: gbpLocations.locationName, syncedAt: gbpLocations.syncedAt }).from(gbpLocations).where(and102(eq120(gbpLocations.projectId, ctx.project.id), eq120(gbpLocations.selected, true))).all();
|
|
78930
79019
|
if (selected.length === 0) {
|
|
78931
79020
|
return {
|
|
78932
79021
|
status: CheckStatuses.skipped,
|
|
@@ -78986,7 +79075,7 @@ var GBP_AUTH_CHECK_BY_ID = Object.fromEntries(
|
|
|
78986
79075
|
);
|
|
78987
79076
|
|
|
78988
79077
|
// ../api-routes/src/doctor/checks/places.ts
|
|
78989
|
-
import { eq as
|
|
79078
|
+
import { eq as eq121 } from "drizzle-orm";
|
|
78990
79079
|
var apiKeyCheck = {
|
|
78991
79080
|
id: "gbp.places.api-key",
|
|
78992
79081
|
category: CheckCategories.auth,
|
|
@@ -79031,7 +79120,7 @@ var apiKeyCheck = {
|
|
|
79031
79120
|
details: { tier: cfg.tier }
|
|
79032
79121
|
};
|
|
79033
79122
|
}
|
|
79034
|
-
const rows = ctx.db.select({ placeId: gbpLocations.placeId, selected: gbpLocations.selected }).from(gbpLocations).where(
|
|
79123
|
+
const rows = ctx.db.select({ placeId: gbpLocations.placeId, selected: gbpLocations.selected }).from(gbpLocations).where(eq121(gbpLocations.projectId, ctx.project.id)).all();
|
|
79035
79124
|
const selected = rows.filter((r) => r.selected);
|
|
79036
79125
|
const locationsWithPlaceId = selected.filter((r) => Boolean(r.placeId)).length;
|
|
79037
79126
|
const details = {
|
|
@@ -79064,7 +79153,7 @@ var PLACES_CHECK_BY_ID = Object.fromEntries(
|
|
|
79064
79153
|
);
|
|
79065
79154
|
|
|
79066
79155
|
// ../api-routes/src/doctor/checks/gbp-reviews.ts
|
|
79067
|
-
import { and as
|
|
79156
|
+
import { and as and103, desc as desc54, eq as eq122, gte as gte31, inArray as inArray55, sql as sql50 } from "drizzle-orm";
|
|
79068
79157
|
var REVIEW_EVENTS = /* @__PURE__ */ new Set(["review.negative", "review.rating-dropped"]);
|
|
79069
79158
|
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`.";
|
|
79070
79159
|
var reviewsAccessCheck = {
|
|
@@ -79092,7 +79181,7 @@ var reviewsAccessCheck = {
|
|
|
79092
79181
|
reviewsAccess: gbpLocations.reviewsAccess,
|
|
79093
79182
|
reviewsAccessReason: gbpLocations.reviewsAccessReason,
|
|
79094
79183
|
reviewsCheckedAt: gbpLocations.reviewsCheckedAt
|
|
79095
|
-
}).from(gbpLocations).where(
|
|
79184
|
+
}).from(gbpLocations).where(and103(eq122(gbpLocations.projectId, project.id), eq122(gbpLocations.selected, true))).all();
|
|
79096
79185
|
if (locations.length === 0) {
|
|
79097
79186
|
return {
|
|
79098
79187
|
status: CheckStatuses.skipped,
|
|
@@ -79112,7 +79201,7 @@ var reviewsAccessCheck = {
|
|
|
79112
79201
|
const places = ctx.getPlacesConfig?.();
|
|
79113
79202
|
const placesFallback = places !== void 0 && places.tier === "atmosphere" && Boolean(places.apiKey);
|
|
79114
79203
|
const v4Worked = new Set(
|
|
79115
|
-
ctx.db.select({ locationName: gbpReviewRatings.locationName }).from(gbpReviewRatings).where(
|
|
79204
|
+
ctx.db.select({ locationName: gbpReviewRatings.locationName }).from(gbpReviewRatings).where(and103(eq122(gbpReviewRatings.projectId, project.id), eq122(gbpReviewRatings.origin, "gbp"))).all().map((row) => row.locationName)
|
|
79116
79205
|
);
|
|
79117
79206
|
const coverageOf = (loc) => {
|
|
79118
79207
|
if (businessProfileReviewsCover(loc.reviewsAccess ?? null, v4Worked.has(loc.locationName))) return "full";
|
|
@@ -79146,7 +79235,7 @@ var reviewsAccessCheck = {
|
|
|
79146
79235
|
none > 0 ? `${none} have no review source` : null
|
|
79147
79236
|
].filter((part) => part !== null);
|
|
79148
79237
|
const summary3 = `Business Profile reviews are not available${why}. ${parts.join("; ")}.`;
|
|
79149
|
-
const subscribed = ctx.db.select({ config: notifications.config, enabled: notifications.enabled }).from(notifications).where(
|
|
79238
|
+
const subscribed = ctx.db.select({ config: notifications.config, enabled: notifications.enabled }).from(notifications).where(eq122(notifications.projectId, project.id)).all().some((n) => n.enabled && (n.config.events ?? []).some((event) => REVIEW_EVENTS.has(event)));
|
|
79150
79239
|
const placesHint = placesFallback ? "" : " For partial coverage meanwhile, set a Places API key (`GOOGLE_PLACES_API_KEY` or `places.apiKey`) with `places.tier: atmosphere`.";
|
|
79151
79240
|
if (none > 0 && subscribed) {
|
|
79152
79241
|
return {
|
|
@@ -79185,9 +79274,9 @@ var reviewDeliveryCheck = {
|
|
|
79185
79274
|
attempts: reviewWebhookDeliveries.attempts,
|
|
79186
79275
|
lastTouched,
|
|
79187
79276
|
payload: reviewWebhookDeliveries.payload
|
|
79188
|
-
}).from(reviewWebhookDeliveries).where(
|
|
79189
|
-
|
|
79190
|
-
|
|
79277
|
+
}).from(reviewWebhookDeliveries).where(and103(
|
|
79278
|
+
eq122(reviewWebhookDeliveries.projectId, ctx.project.id),
|
|
79279
|
+
inArray55(reviewWebhookDeliveries.state, [ReviewDeliveryStates.Uncertain, ReviewDeliveryStates.Failed]),
|
|
79191
79280
|
gte31(lastTouched, since)
|
|
79192
79281
|
)).orderBy(desc54(lastTouched)).all();
|
|
79193
79282
|
if (rows.length === 0) {
|
|
@@ -79198,7 +79287,7 @@ var reviewDeliveryCheck = {
|
|
|
79198
79287
|
remediation: null
|
|
79199
79288
|
};
|
|
79200
79289
|
}
|
|
79201
|
-
const destinations = new Map(ctx.db.select({ id: notifications.id, config: notifications.config }).from(notifications).where(
|
|
79290
|
+
const destinations = new Map(ctx.db.select({ id: notifications.id, config: notifications.config }).from(notifications).where(eq122(notifications.projectId, ctx.project.id)).all().map((row) => [row.id, redactNotificationUrl(row.config.url).urlDisplay]));
|
|
79202
79291
|
const deliveries = rows.map((row) => {
|
|
79203
79292
|
const review = row.payload.reviews[0];
|
|
79204
79293
|
return {
|
|
@@ -79772,7 +79861,7 @@ var RUNTIME_STATE_CHECKS = [
|
|
|
79772
79861
|
];
|
|
79773
79862
|
|
|
79774
79863
|
// ../api-routes/src/doctor/checks/traffic-source.ts
|
|
79775
|
-
import { and as
|
|
79864
|
+
import { and as and104, desc as desc55, eq as eq123, gte as gte32, inArray as inArray56, isNotNull as isNotNull11, ne as ne18, sql as sql51 } from "drizzle-orm";
|
|
79776
79865
|
var RECENT_DATA_WARN_DAYS = 7;
|
|
79777
79866
|
var RECENT_DATA_FAIL_DAYS = 30;
|
|
79778
79867
|
function isCloudflareQueuePull(source) {
|
|
@@ -79806,8 +79895,8 @@ function skippedNoProject5() {
|
|
|
79806
79895
|
function loadProbes(ctx) {
|
|
79807
79896
|
if (!ctx.project) return [];
|
|
79808
79897
|
const rows = ctx.db.select().from(trafficSources).where(
|
|
79809
|
-
|
|
79810
|
-
|
|
79898
|
+
and104(
|
|
79899
|
+
eq123(trafficSources.projectId, ctx.project.id),
|
|
79811
79900
|
ne18(trafficSources.status, TrafficSourceStatuses.archived)
|
|
79812
79901
|
)
|
|
79813
79902
|
).all();
|
|
@@ -79970,27 +80059,27 @@ var recentDataCheck = {
|
|
|
79970
80059
|
const failCutoff = new Date(now.getTime() - RECENT_DATA_FAIL_DAYS * 24 * 60 * 6e4).toISOString();
|
|
79971
80060
|
const recentCrawlers = Number(
|
|
79972
80061
|
ctx.db.select({ total: sql51`COALESCE(SUM(${crawlerEventsHourly.hits}), 0)` }).from(crawlerEventsHourly).where(
|
|
79973
|
-
|
|
79974
|
-
|
|
79975
|
-
|
|
80062
|
+
and104(
|
|
80063
|
+
eq123(crawlerEventsHourly.projectId, ctx.project.id),
|
|
80064
|
+
inArray56(crawlerEventsHourly.sourceId, activeSourceIds),
|
|
79976
80065
|
gte32(crawlerEventsHourly.tsHour, warnCutoff)
|
|
79977
80066
|
)
|
|
79978
80067
|
).get()?.total ?? 0
|
|
79979
80068
|
);
|
|
79980
80069
|
const recentReferrals = Number(
|
|
79981
80070
|
ctx.db.select({ total: sql51`COALESCE(SUM(${aiReferralEventsHourly.sessionsOrHits}), 0)` }).from(aiReferralEventsHourly).where(
|
|
79982
|
-
|
|
79983
|
-
|
|
79984
|
-
|
|
80071
|
+
and104(
|
|
80072
|
+
eq123(aiReferralEventsHourly.projectId, ctx.project.id),
|
|
80073
|
+
inArray56(aiReferralEventsHourly.sourceId, activeSourceIds),
|
|
79985
80074
|
gte32(aiReferralEventsHourly.tsHour, warnCutoff)
|
|
79986
80075
|
)
|
|
79987
80076
|
).get()?.total ?? 0
|
|
79988
80077
|
);
|
|
79989
80078
|
const recentUserFetches = Number(
|
|
79990
80079
|
ctx.db.select({ total: sql51`COALESCE(SUM(${aiUserFetchEventsHourly.hits}), 0)` }).from(aiUserFetchEventsHourly).where(
|
|
79991
|
-
|
|
79992
|
-
|
|
79993
|
-
|
|
80080
|
+
and104(
|
|
80081
|
+
eq123(aiUserFetchEventsHourly.projectId, ctx.project.id),
|
|
80082
|
+
inArray56(aiUserFetchEventsHourly.sourceId, activeSourceIds),
|
|
79994
80083
|
gte32(aiUserFetchEventsHourly.tsHour, warnCutoff)
|
|
79995
80084
|
)
|
|
79996
80085
|
).get()?.total ?? 0
|
|
@@ -80014,27 +80103,27 @@ var recentDataCheck = {
|
|
|
80014
80103
|
}
|
|
80015
80104
|
const olderCrawlers = Number(
|
|
80016
80105
|
ctx.db.select({ total: sql51`COALESCE(SUM(${crawlerEventsHourly.hits}), 0)` }).from(crawlerEventsHourly).where(
|
|
80017
|
-
|
|
80018
|
-
|
|
80019
|
-
|
|
80106
|
+
and104(
|
|
80107
|
+
eq123(crawlerEventsHourly.projectId, ctx.project.id),
|
|
80108
|
+
inArray56(crawlerEventsHourly.sourceId, activeSourceIds),
|
|
80020
80109
|
gte32(crawlerEventsHourly.tsHour, failCutoff)
|
|
80021
80110
|
)
|
|
80022
80111
|
).get()?.total ?? 0
|
|
80023
80112
|
);
|
|
80024
80113
|
const olderReferrals = Number(
|
|
80025
80114
|
ctx.db.select({ total: sql51`COALESCE(SUM(${aiReferralEventsHourly.sessionsOrHits}), 0)` }).from(aiReferralEventsHourly).where(
|
|
80026
|
-
|
|
80027
|
-
|
|
80028
|
-
|
|
80115
|
+
and104(
|
|
80116
|
+
eq123(aiReferralEventsHourly.projectId, ctx.project.id),
|
|
80117
|
+
inArray56(aiReferralEventsHourly.sourceId, activeSourceIds),
|
|
80029
80118
|
gte32(aiReferralEventsHourly.tsHour, failCutoff)
|
|
80030
80119
|
)
|
|
80031
80120
|
).get()?.total ?? 0
|
|
80032
80121
|
);
|
|
80033
80122
|
const olderUserFetches = Number(
|
|
80034
80123
|
ctx.db.select({ total: sql51`COALESCE(SUM(${aiUserFetchEventsHourly.hits}), 0)` }).from(aiUserFetchEventsHourly).where(
|
|
80035
|
-
|
|
80036
|
-
|
|
80037
|
-
|
|
80124
|
+
and104(
|
|
80125
|
+
eq123(aiUserFetchEventsHourly.projectId, ctx.project.id),
|
|
80126
|
+
inArray56(aiUserFetchEventsHourly.sourceId, activeSourceIds),
|
|
80038
80127
|
gte32(aiUserFetchEventsHourly.tsHour, failCutoff)
|
|
80039
80128
|
)
|
|
80040
80129
|
).get()?.total ?? 0
|
|
@@ -80360,10 +80449,10 @@ var syncLagCheck = {
|
|
|
80360
80449
|
}
|
|
80361
80450
|
};
|
|
80362
80451
|
function lastQueueStopReason(ctx, sourceId) {
|
|
80363
|
-
const row = ctx.db.select({ syncSummary: runs.syncSummary }).from(runs).where(
|
|
80364
|
-
|
|
80365
|
-
|
|
80366
|
-
|
|
80452
|
+
const row = ctx.db.select({ syncSummary: runs.syncSummary }).from(runs).where(and104(
|
|
80453
|
+
eq123(runs.projectId, ctx.project.id),
|
|
80454
|
+
eq123(runs.kind, RunKinds["traffic-sync"]),
|
|
80455
|
+
eq123(runs.sourceId, sourceId),
|
|
80367
80456
|
isNotNull11(runs.syncSummary)
|
|
80368
80457
|
)).orderBy(desc55(runs.createdAt)).limit(1).get();
|
|
80369
80458
|
return row?.syncSummary?.type === "cloudflare-queue" ? row.syncSummary.stopReason : null;
|
|
@@ -81163,7 +81252,7 @@ async function doctorRoutes(app, opts) {
|
|
|
81163
81252
|
}
|
|
81164
81253
|
|
|
81165
81254
|
// ../api-routes/src/status.ts
|
|
81166
|
-
import { and as
|
|
81255
|
+
import { and as and105, desc as desc56, eq as eq124, isNull as isNull19 } from "drizzle-orm";
|
|
81167
81256
|
function ageDays(iso2) {
|
|
81168
81257
|
if (!iso2) return null;
|
|
81169
81258
|
const ms = Date.now() - Date.parse(iso2);
|
|
@@ -81213,7 +81302,7 @@ function makeRow(integration, label, runKind, state, staleAfterDays, dataThrough
|
|
|
81213
81302
|
};
|
|
81214
81303
|
}
|
|
81215
81304
|
function latestDate2(db, table, projectId) {
|
|
81216
|
-
const row = db.select({ date: table.date }).from(table).where(
|
|
81305
|
+
const row = db.select({ date: table.date }).from(table).where(eq124(table.projectId, projectId)).orderBy(desc56(table.date)).limit(1).get();
|
|
81217
81306
|
return row?.date ?? null;
|
|
81218
81307
|
}
|
|
81219
81308
|
function projectRows(opts, project) {
|
|
@@ -81228,7 +81317,7 @@ function projectRows(opts, project) {
|
|
|
81228
81317
|
const rows = [];
|
|
81229
81318
|
const gsc = gscConnection(ctx, info);
|
|
81230
81319
|
if (connected(gsc)) {
|
|
81231
|
-
const watermarkRow = opts.db.select({ dataThroughDate: gscDataWatermarks.dataThroughDate }).from(gscDataWatermarks).where(
|
|
81320
|
+
const watermarkRow = opts.db.select({ dataThroughDate: gscDataWatermarks.dataThroughDate }).from(gscDataWatermarks).where(eq124(gscDataWatermarks.projectId, project.id)).limit(1).get();
|
|
81232
81321
|
const state = readSyncRunState(opts.db, project.id, RunKinds["gsc-sync"], { since: gsc.since });
|
|
81233
81322
|
const dataThrough = watermarkRow?.dataThroughDate ?? latestDate2(opts.db, gscDailyTotals, project.id);
|
|
81234
81323
|
rows.push(makeRow("gsc", "Search Console", RunKinds["gsc-sync"], state, SYNC_IDLE_DAYS, dataThrough, null, ["gsc.sync.recent-failures"], GSC_DATA_AGING_DAYS));
|
|
@@ -81244,12 +81333,12 @@ function projectRows(opts, project) {
|
|
|
81244
81333
|
rows.push(makeRow("bing", "Bing Webmaster Tools", RunKinds["bing-inspect-sitemap"], readSyncRunState(opts.db, project.id, RunKinds["bing-inspect-sitemap"]), null));
|
|
81245
81334
|
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));
|
|
81246
81335
|
}
|
|
81247
|
-
const ads = opts.db.select({ id: adsConnections.id, lastSyncedAt: adsConnections.lastSyncedAt }).from(adsConnections).where(
|
|
81336
|
+
const ads = opts.db.select({ id: adsConnections.id, lastSyncedAt: adsConnections.lastSyncedAt }).from(adsConnections).where(eq124(adsConnections.projectId, project.id)).limit(1).get();
|
|
81248
81337
|
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));
|
|
81249
81338
|
const marketing = opts.getGoogleMarketingDoctorInput?.(ctx);
|
|
81250
81339
|
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));
|
|
81251
81340
|
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));
|
|
81252
|
-
const sources = opts.db.select().from(trafficSources).where(
|
|
81341
|
+
const sources = opts.db.select().from(trafficSources).where(and105(eq124(trafficSources.projectId, project.id), isNull19(trafficSources.archivedAt))).all();
|
|
81253
81342
|
for (const source of sources) {
|
|
81254
81343
|
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"]);
|
|
81255
81344
|
const lag = source.lastSyncedAt ? Date.now() - Date.parse(source.lastSyncedAt) : Number.POSITIVE_INFINITY;
|
|
@@ -81261,7 +81350,7 @@ function projectRows(opts, project) {
|
|
|
81261
81350
|
}
|
|
81262
81351
|
function projectStatus(opts, project) {
|
|
81263
81352
|
const integrations = projectRows(opts, project);
|
|
81264
|
-
const healthRow = opts.db.select().from(doctorHealthState).where(
|
|
81353
|
+
const healthRow = opts.db.select().from(doctorHealthState).where(eq124(doctorHealthState.projectId, project.id)).limit(1).get();
|
|
81265
81354
|
const health = healthRow ? { status: healthRow.status, code: healthRow.code, summary: healthRow.summary, checkedAt: healthRow.checkedAt, notifiedAt: healthRow.notifiedAt } : null;
|
|
81266
81355
|
const rank = { ok: 0, "never-synced": 1, warning: 2, stale: 3, failing: 4 };
|
|
81267
81356
|
const healthState = health?.status === "fail" ? "failing" : health?.status === "warn" ? "warning" : "ok";
|
|
@@ -81281,7 +81370,7 @@ async function statusRoutes(app, opts) {
|
|
|
81281
81370
|
if (request.query.problems === "true") result.projects = result.projects.map((item2) => ({ ...item2, integrations: item2.integrations.filter((row) => row.state !== "ok") }));
|
|
81282
81371
|
return instanceStatusDtoSchema.parse(result);
|
|
81283
81372
|
}
|
|
81284
|
-
const projectsRows = (scopedId ? opts.db.select().from(projects).where(
|
|
81373
|
+
const projectsRows = (scopedId ? opts.db.select().from(projects).where(eq124(projects.id, scopedId)) : opts.db.select().from(projects)).all();
|
|
81285
81374
|
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)) };
|
|
81286
81375
|
for (const project of output.projects) {
|
|
81287
81376
|
const key = project.state === "never-synced" ? "neverSynced" : project.state;
|
|
@@ -81294,7 +81383,7 @@ async function statusRoutes(app, opts) {
|
|
|
81294
81383
|
|
|
81295
81384
|
// ../api-routes/src/discovery/routes.ts
|
|
81296
81385
|
import crypto64 from "crypto";
|
|
81297
|
-
import { and as
|
|
81386
|
+
import { and as and106, desc as desc57, eq as eq125, gte as gte33, inArray as inArray57, isNull as isNull20, or as or22 } from "drizzle-orm";
|
|
81298
81387
|
var MAX_INFLIGHT_DISCOVERY_AGE_MS = 2 * 60 * 60 * 1e3;
|
|
81299
81388
|
async function discoveryRoutes(app, opts) {
|
|
81300
81389
|
app.post("/projects/:name/discover/run", async (request, reply) => {
|
|
@@ -81328,13 +81417,13 @@ async function discoveryRoutes(app, opts) {
|
|
|
81328
81417
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
81329
81418
|
const ageFloorIso = new Date(Date.now() - MAX_INFLIGHT_DISCOVERY_AGE_MS).toISOString();
|
|
81330
81419
|
const decision = app.db.transaction((tx) => {
|
|
81331
|
-
const existing = tx.select({ id: discoverySessions.id, runId: discoverySessions.runId }).from(discoverySessions).where(
|
|
81332
|
-
|
|
81333
|
-
|
|
81420
|
+
const existing = tx.select({ id: discoverySessions.id, runId: discoverySessions.runId }).from(discoverySessions).where(and106(
|
|
81421
|
+
eq125(discoverySessions.projectId, project.id),
|
|
81422
|
+
eq125(discoverySessions.icpDescription, icpDescription),
|
|
81334
81423
|
// Buyer is part of session identity: it changes the seed prompt's
|
|
81335
81424
|
// semantics, so a request with a different (or no) buyer must start
|
|
81336
81425
|
// its own session, never adopt another buyer's probes.
|
|
81337
|
-
parsed.data.buyerDescription == null ? isNull20(discoverySessions.buyerDescription) :
|
|
81426
|
+
parsed.data.buyerDescription == null ? isNull20(discoverySessions.buyerDescription) : eq125(discoverySessions.buyerDescription, parsed.data.buyerDescription),
|
|
81338
81427
|
// Locations are identity too: a different service-area subset seeds
|
|
81339
81428
|
// and probes a different geo, so it must never reuse another geo's
|
|
81340
81429
|
// session. resolveLocations is deterministic (project-config order),
|
|
@@ -81344,12 +81433,12 @@ async function discoveryRoutes(app, opts) {
|
|
|
81344
81433
|
// locations a NULL row's subset is unknowable, so it conservatively
|
|
81345
81434
|
// never reuses — a one-time, bounded (2h window) non-reuse after
|
|
81346
81435
|
// upgrade, never a wrong reuse.
|
|
81347
|
-
locations.length === 0 ? or22(isNull20(discoverySessions.locations),
|
|
81436
|
+
locations.length === 0 ? or22(isNull20(discoverySessions.locations), eq125(discoverySessions.locations, locations)) : eq125(discoverySessions.locations, locations),
|
|
81348
81437
|
// Seed provider set is identity: a different phrasing distribution
|
|
81349
81438
|
// must never reuse another set's session. Null (= Gemini-only
|
|
81350
81439
|
// default, including explicit ['gemini']) matches legacy rows.
|
|
81351
|
-
seedProviders == null ? isNull20(discoverySessions.seedProviders) :
|
|
81352
|
-
|
|
81440
|
+
seedProviders == null ? isNull20(discoverySessions.seedProviders) : eq125(discoverySessions.seedProviders, seedProviders),
|
|
81441
|
+
inArray57(discoverySessions.status, [
|
|
81353
81442
|
DiscoverySessionStatuses.queued,
|
|
81354
81443
|
DiscoverySessionStatuses.seeding,
|
|
81355
81444
|
DiscoverySessionStatuses.probing
|
|
@@ -81424,7 +81513,7 @@ async function discoveryRoutes(app, opts) {
|
|
|
81424
81513
|
const project = resolveProject(app.db, request.params.name);
|
|
81425
81514
|
const parsedLimit = parseInt(request.query.limit ?? "", 10);
|
|
81426
81515
|
const limit = Number.isNaN(parsedLimit) || parsedLimit <= 0 ? 50 : parsedLimit;
|
|
81427
|
-
const rows = app.db.select().from(discoverySessions).where(
|
|
81516
|
+
const rows = app.db.select().from(discoverySessions).where(eq125(discoverySessions.projectId, project.id)).orderBy(desc57(discoverySessions.createdAt)).limit(limit).all();
|
|
81428
81517
|
return reply.send(rows.map(serializeSession));
|
|
81429
81518
|
}
|
|
81430
81519
|
);
|
|
@@ -81432,11 +81521,11 @@ async function discoveryRoutes(app, opts) {
|
|
|
81432
81521
|
"/projects/:name/discover/sessions/:id",
|
|
81433
81522
|
async (request, reply) => {
|
|
81434
81523
|
const project = resolveProject(app.db, request.params.name);
|
|
81435
|
-
const session = app.db.select().from(discoverySessions).where(
|
|
81524
|
+
const session = app.db.select().from(discoverySessions).where(eq125(discoverySessions.id, request.params.id)).get();
|
|
81436
81525
|
if (!session || session.projectId !== project.id) {
|
|
81437
81526
|
throw notFound("Discovery session", request.params.id);
|
|
81438
81527
|
}
|
|
81439
|
-
const probeRows = app.db.select().from(discoveryProbes).where(
|
|
81528
|
+
const probeRows = app.db.select().from(discoveryProbes).where(eq125(discoveryProbes.sessionId, session.id)).all();
|
|
81440
81529
|
const detail = {
|
|
81441
81530
|
...serializeSession(session),
|
|
81442
81531
|
probes: probeRows.map(serializeProbe)
|
|
@@ -81450,7 +81539,7 @@ async function discoveryRoutes(app, opts) {
|
|
|
81450
81539
|
requireAdminSession(request);
|
|
81451
81540
|
requirePaidReadScope(request, [], "Discovery harvest requires wildcard (*) API key scope because it can call the embedding provider.");
|
|
81452
81541
|
const project = resolveProject(app.db, request.params.name);
|
|
81453
|
-
const session = app.db.select().from(discoverySessions).where(
|
|
81542
|
+
const session = app.db.select().from(discoverySessions).where(eq125(discoverySessions.id, request.params.id)).get();
|
|
81454
81543
|
if (!session || session.projectId !== project.id) {
|
|
81455
81544
|
throw notFound("Discovery session", request.params.id);
|
|
81456
81545
|
}
|
|
@@ -81458,7 +81547,7 @@ async function discoveryRoutes(app, opts) {
|
|
|
81458
81547
|
const minProbeHits = Number.isNaN(parsedFloor) || parsedFloor < 1 ? 1 : parsedFloor;
|
|
81459
81548
|
const applyAnchor = request.query.anchor !== "false";
|
|
81460
81549
|
const provider = session.seedProvider ?? "gemini";
|
|
81461
|
-
const probeRows = app.db.select().from(discoveryProbes).where(
|
|
81550
|
+
const probeRows = app.db.select().from(discoveryProbes).where(eq125(discoveryProbes.sessionId, session.id)).all();
|
|
81462
81551
|
const extract = opts.harvestSearchQueries;
|
|
81463
81552
|
const probesWithQueries = probeRows.map((row) => {
|
|
81464
81553
|
if (!extract || !row.rawResponse) return { searchQueries: [] };
|
|
@@ -81469,7 +81558,7 @@ async function discoveryRoutes(app, opts) {
|
|
|
81469
81558
|
return { searchQueries: [] };
|
|
81470
81559
|
}
|
|
81471
81560
|
});
|
|
81472
|
-
const trackedQueries = app.db.select({ query: queries.query }).from(queries).where(
|
|
81561
|
+
const trackedQueries = app.db.select({ query: queries.query }).from(queries).where(eq125(queries.projectId, project.id)).all().map((r) => r.query);
|
|
81473
81562
|
const anchorTerms = buildHarvestAnchorTerms(
|
|
81474
81563
|
[session.icpDescription ?? "", ...trackedQueries],
|
|
81475
81564
|
effectiveDomains(project)
|
|
@@ -81516,11 +81605,11 @@ async function discoveryRoutes(app, opts) {
|
|
|
81516
81605
|
"/projects/:name/discover/sessions/:id/promote",
|
|
81517
81606
|
async (request, reply) => {
|
|
81518
81607
|
const project = resolveProject(app.db, request.params.name);
|
|
81519
|
-
const session = app.db.select().from(discoverySessions).where(
|
|
81608
|
+
const session = app.db.select().from(discoverySessions).where(eq125(discoverySessions.id, request.params.id)).get();
|
|
81520
81609
|
if (!session || session.projectId !== project.id) {
|
|
81521
81610
|
throw notFound("Discovery session", request.params.id);
|
|
81522
81611
|
}
|
|
81523
|
-
const probeRows = app.db.select().from(discoveryProbes).where(
|
|
81612
|
+
const probeRows = app.db.select().from(discoveryProbes).where(eq125(discoveryProbes.sessionId, session.id)).all();
|
|
81524
81613
|
const cited = /* @__PURE__ */ new Set();
|
|
81525
81614
|
const aspirational = /* @__PURE__ */ new Set();
|
|
81526
81615
|
const wasted = /* @__PURE__ */ new Set();
|
|
@@ -81555,7 +81644,7 @@ async function discoveryRoutes(app, opts) {
|
|
|
81555
81644
|
);
|
|
81556
81645
|
app.post("/projects/:name/discover/sessions/:id/promote", async (request, reply) => {
|
|
81557
81646
|
const project = resolveProject(app.db, request.params.name);
|
|
81558
|
-
const session = app.db.select().from(discoverySessions).where(
|
|
81647
|
+
const session = app.db.select().from(discoverySessions).where(eq125(discoverySessions.id, request.params.id)).get();
|
|
81559
81648
|
if (!session || session.projectId !== project.id) {
|
|
81560
81649
|
throw notFound("Discovery session", request.params.id);
|
|
81561
81650
|
}
|
|
@@ -81578,7 +81667,7 @@ async function discoveryRoutes(app, opts) {
|
|
|
81578
81667
|
const bucketSet = new Set(buckets);
|
|
81579
81668
|
const includeCompetitors = parsed.data.includeCompetitors ?? true;
|
|
81580
81669
|
const competitorTypes = parsed.data.competitorTypes ?? DEFAULT_DISCOVERY_PROMOTE_COMPETITOR_TYPES;
|
|
81581
|
-
const probeRows = app.db.select().from(discoveryProbes).where(
|
|
81670
|
+
const probeRows = app.db.select().from(discoveryProbes).where(eq125(discoveryProbes.sessionId, session.id)).all();
|
|
81582
81671
|
const candidateQueries = /* @__PURE__ */ new Set();
|
|
81583
81672
|
for (const probe of probeRows) {
|
|
81584
81673
|
if (!probe.bucket) continue;
|
|
@@ -81586,7 +81675,7 @@ async function discoveryRoutes(app, opts) {
|
|
|
81586
81675
|
if (bucket.success && bucketSet.has(bucket.data)) candidateQueries.add(probe.query);
|
|
81587
81676
|
}
|
|
81588
81677
|
const existingQueries = new Set(
|
|
81589
|
-
app.db.select({ query: queries.query }).from(queries).where(
|
|
81678
|
+
app.db.select({ query: queries.query }).from(queries).where(eq125(queries.projectId, project.id)).all().map((r) => r.query.toLowerCase())
|
|
81590
81679
|
);
|
|
81591
81680
|
const promotedQueries = [];
|
|
81592
81681
|
const skippedQueries = [];
|
|
@@ -81800,7 +81889,7 @@ function planCompetitorPromotion(input) {
|
|
|
81800
81889
|
|
|
81801
81890
|
// ../api-routes/src/discovery/orchestrate.ts
|
|
81802
81891
|
import crypto65 from "crypto";
|
|
81803
|
-
import { eq as
|
|
81892
|
+
import { eq as eq126 } from "drizzle-orm";
|
|
81804
81893
|
var DEFAULT_MAX_PROBES = 100;
|
|
81805
81894
|
var ABSOLUTE_MAX_PROBES = 500;
|
|
81806
81895
|
function classifyProbeBucket(input) {
|
|
@@ -81886,7 +81975,7 @@ async function executeDiscovery(opts) {
|
|
|
81886
81975
|
status: DiscoverySessionStatuses.seeding,
|
|
81887
81976
|
dedupThreshold,
|
|
81888
81977
|
startedAt
|
|
81889
|
-
}).where(
|
|
81978
|
+
}).where(eq126(discoverySessions.id, opts.sessionId)).run();
|
|
81890
81979
|
const seedResult = await opts.deps.seed({
|
|
81891
81980
|
project: opts.project,
|
|
81892
81981
|
icpDescription: opts.icpDescription,
|
|
@@ -81947,7 +82036,7 @@ async function executeDiscovery(opts) {
|
|
|
81947
82036
|
dedupBandPairFraction: dedupStats.bandPairFraction,
|
|
81948
82037
|
dedupPairsTotal: dedupStats.pairsTotal,
|
|
81949
82038
|
warning
|
|
81950
|
-
}).where(
|
|
82039
|
+
}).where(eq126(discoverySessions.id, opts.sessionId)).run();
|
|
81951
82040
|
const probeLocation = opts.locations?.[0];
|
|
81952
82041
|
const probeResults = await mapWithConcurrency(
|
|
81953
82042
|
probedCanonicals,
|
|
@@ -82001,7 +82090,7 @@ async function executeDiscovery(opts) {
|
|
|
82001
82090
|
wastedCount: buckets["wasted-surface"],
|
|
82002
82091
|
competitorMap,
|
|
82003
82092
|
finishedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
82004
|
-
}).where(
|
|
82093
|
+
}).where(eq126(discoverySessions.id, opts.sessionId)).run();
|
|
82005
82094
|
upsertDomainClassifications(opts.db, opts.project.id, opts.sessionId, competitorMap);
|
|
82006
82095
|
return {
|
|
82007
82096
|
buckets,
|
|
@@ -82041,7 +82130,7 @@ function markSessionFailed(db, sessionId, error) {
|
|
|
82041
82130
|
status: DiscoverySessionStatuses.failed,
|
|
82042
82131
|
error,
|
|
82043
82132
|
finishedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
82044
|
-
}).where(
|
|
82133
|
+
}).where(eq126(discoverySessions.id, sessionId)).run();
|
|
82045
82134
|
}
|
|
82046
82135
|
function dedupeStrings(input) {
|
|
82047
82136
|
const seen2 = /* @__PURE__ */ new Set();
|
|
@@ -82058,7 +82147,7 @@ function dedupeStrings(input) {
|
|
|
82058
82147
|
}
|
|
82059
82148
|
|
|
82060
82149
|
// ../api-routes/src/trends.ts
|
|
82061
|
-
import { and as
|
|
82150
|
+
import { and as and107, asc as asc30, eq as eq127 } from "drizzle-orm";
|
|
82062
82151
|
function parseSurface(value) {
|
|
82063
82152
|
const parsed = trendSurfaceSchema.safeParse(value);
|
|
82064
82153
|
if (!parsed.success) {
|
|
@@ -82114,8 +82203,8 @@ async function trendsRoutes(app) {
|
|
|
82114
82203
|
function readSurface(app, projectId, surface) {
|
|
82115
82204
|
switch (surface) {
|
|
82116
82205
|
case TrendSurfaces["index-coverage"]: {
|
|
82117
|
-
const google = app.db.select({ date: gscCoverageSnapshots.date, indexed: gscCoverageSnapshots.indexed, notIndexed: gscCoverageSnapshots.notIndexed }).from(gscCoverageSnapshots).where(
|
|
82118
|
-
const bing = app.db.select({ date: bingCoverageSnapshots.date, indexed: bingCoverageSnapshots.indexed, notIndexed: bingCoverageSnapshots.notIndexed }).from(bingCoverageSnapshots).where(
|
|
82206
|
+
const google = app.db.select({ date: gscCoverageSnapshots.date, indexed: gscCoverageSnapshots.indexed, notIndexed: gscCoverageSnapshots.notIndexed }).from(gscCoverageSnapshots).where(eq127(gscCoverageSnapshots.projectId, projectId)).orderBy(asc30(gscCoverageSnapshots.date)).all();
|
|
82207
|
+
const bing = app.db.select({ date: bingCoverageSnapshots.date, indexed: bingCoverageSnapshots.indexed, notIndexed: bingCoverageSnapshots.notIndexed }).from(bingCoverageSnapshots).where(eq127(bingCoverageSnapshots.projectId, projectId)).orderBy(asc30(bingCoverageSnapshots.date)).all();
|
|
82119
82208
|
const coverage = (key, label, rows) => ({
|
|
82120
82209
|
key,
|
|
82121
82210
|
label,
|
|
@@ -82127,7 +82216,7 @@ function readSurface(app, projectId, surface) {
|
|
|
82127
82216
|
return [coverage("google", "Google", google), coverage("bing", "Bing", bing)];
|
|
82128
82217
|
}
|
|
82129
82218
|
case TrendSurfaces["site-health"]: {
|
|
82130
|
-
const rows = app.db.select({ auditedAt: siteAuditSnapshots.auditedAt, aggregateScore: siteAuditSnapshots.aggregateScore, pagesAudited: siteAuditSnapshots.pagesAudited }).from(siteAuditSnapshots).innerJoin(runs,
|
|
82219
|
+
const rows = app.db.select({ auditedAt: siteAuditSnapshots.auditedAt, aggregateScore: siteAuditSnapshots.aggregateScore, pagesAudited: siteAuditSnapshots.pagesAudited }).from(siteAuditSnapshots).innerJoin(runs, eq127(siteAuditSnapshots.runId, runs.id)).where(and107(...surfaceableSiteAuditFilters(projectId))).orderBy(asc30(siteAuditSnapshots.auditedAt)).all();
|
|
82131
82220
|
return [{
|
|
82132
82221
|
key: "site-health",
|
|
82133
82222
|
label: "Agent Readiness",
|
|
@@ -82139,7 +82228,7 @@ function readSurface(app, projectId, surface) {
|
|
|
82139
82228
|
}
|
|
82140
82229
|
case TrendSurfaces.backlinks: {
|
|
82141
82230
|
const totals = computeFilteredReleaseTotals(app.db, projectId, BacklinkSources.commoncrawl);
|
|
82142
|
-
const rows = app.db.select({ release: backlinkSummaries.release, totalLinkingDomains: backlinkSummaries.totalLinkingDomains, queriedAt: backlinkSummaries.queriedAt }).from(backlinkSummaries).where(
|
|
82231
|
+
const rows = app.db.select({ release: backlinkSummaries.release, totalLinkingDomains: backlinkSummaries.totalLinkingDomains, queriedAt: backlinkSummaries.queriedAt }).from(backlinkSummaries).where(and107(eq127(backlinkSummaries.projectId, projectId), eq127(backlinkSummaries.source, BacklinkSources.commoncrawl))).all().sort((a, b) => compareReleaseIds(a.release, b.release)).map((row) => {
|
|
82143
82232
|
const filtered = totals.get(row.release);
|
|
82144
82233
|
const known = (filtered?.domainRows ?? 0) > 0 || row.totalLinkingDomains === 0;
|
|
82145
82234
|
const windowEnd = releaseWindowEndMonth(row.release);
|
|
@@ -82169,7 +82258,7 @@ function readSurface(app, projectId, surface) {
|
|
|
82169
82258
|
// ../api-routes/src/research.ts
|
|
82170
82259
|
import crypto66 from "crypto";
|
|
82171
82260
|
import { z as z7 } from "zod";
|
|
82172
|
-
import { and as
|
|
82261
|
+
import { and as and108, count as count10, desc as desc58, eq as eq128, gte as gte34, lt as lt21, or as or23, sql as sql52 } from "drizzle-orm";
|
|
82173
82262
|
var sameLocation = (a, b) => a.label === b.label && a.city === b.city && a.region === b.region && a.country === b.country && a.timezone === b.timezone;
|
|
82174
82263
|
var BATCH_RECEIPT_PREFIX = "__canonry_research_batch__:";
|
|
82175
82264
|
async function researchRoutes(app, opts) {
|
|
@@ -82188,7 +82277,7 @@ async function researchRoutes(app, opts) {
|
|
|
82188
82277
|
const input = parsed.data;
|
|
82189
82278
|
if (input.idempotencyKey?.startsWith(BATCH_RECEIPT_PREFIX)) throw validationError("This idempotency key prefix is reserved for internal research batch receipts.");
|
|
82190
82279
|
const requestHash2 = directResearchRequestHash(input);
|
|
82191
|
-
const existingReceipt = input.idempotencyKey ? app.db.select().from(researchRuns).where(
|
|
82280
|
+
const existingReceipt = input.idempotencyKey ? app.db.select().from(researchRuns).where(and108(eq128(researchRuns.projectId, project.id), eq128(researchRuns.idempotencyKey, input.idempotencyKey))).get() : void 0;
|
|
82192
82281
|
if (existingReceipt) {
|
|
82193
82282
|
assertSameDirectResearchRequest(existingReceipt, input, requestHash2);
|
|
82194
82283
|
const result2 = getDetail(app, project.id, existingReceipt.id);
|
|
@@ -82223,7 +82312,7 @@ async function researchRoutes(app, opts) {
|
|
|
82223
82312
|
const initiatedBy = researchPrincipal(request);
|
|
82224
82313
|
const decision = app.db.transaction((tx) => {
|
|
82225
82314
|
if (input.idempotencyKey) {
|
|
82226
|
-
const existing = tx.select().from(researchRuns).where(
|
|
82315
|
+
const existing = tx.select().from(researchRuns).where(and108(eq128(researchRuns.projectId, project.id), eq128(researchRuns.idempotencyKey, input.idempotencyKey))).get();
|
|
82227
82316
|
if (existing) {
|
|
82228
82317
|
assertSameDirectResearchRequest(existing, input, requestHash2);
|
|
82229
82318
|
return { reused: true, id: existing.id, shouldDispatch: existing.status === ResearchRunStatuses.queued };
|
|
@@ -82231,8 +82320,8 @@ async function researchRoutes(app, opts) {
|
|
|
82231
82320
|
}
|
|
82232
82321
|
if (initiatedBy?.limited) {
|
|
82233
82322
|
const { start, end, date } = utcDayBounds(now);
|
|
82234
|
-
const used = tx.select({ value: count10() }).from(researchRuns).where(
|
|
82235
|
-
|
|
82323
|
+
const used = tx.select({ value: count10() }).from(researchRuns).where(and108(
|
|
82324
|
+
eq128(researchRuns.projectId, project.id),
|
|
82236
82325
|
gte34(researchRuns.createdAt, start),
|
|
82237
82326
|
lt21(researchRuns.createdAt, end),
|
|
82238
82327
|
sql52`(json_extract(${researchRuns.initiatedBy}, '$.role') = ${UserRoles.viewer} OR json_extract(${researchRuns.initiatedBy}, '$.limited') = 1)`
|
|
@@ -82263,15 +82352,15 @@ async function researchRoutes(app, opts) {
|
|
|
82263
82352
|
if (input.idempotencyKey.startsWith(BATCH_RECEIPT_PREFIX)) throw validationError("This idempotency key prefix is reserved for internal research batch receipts.");
|
|
82264
82353
|
const requestHash2 = researchBatchRequestHash(input);
|
|
82265
82354
|
const receiptKeys = input.runs.map((_run, index) => batchChildReceiptKey(input.idempotencyKey, index));
|
|
82266
|
-
const firstReceipt = app.db.select().from(researchRuns).where(
|
|
82267
|
-
|
|
82268
|
-
|
|
82355
|
+
const firstReceipt = app.db.select().from(researchRuns).where(and108(
|
|
82356
|
+
eq128(researchRuns.projectId, project.id),
|
|
82357
|
+
eq128(researchRuns.idempotencyKey, receiptKeys[0])
|
|
82269
82358
|
)).get();
|
|
82270
82359
|
if (firstReceipt) {
|
|
82271
82360
|
if (firstReceipt.requestHash !== requestHash2) throw alreadyExists("Research batch idempotency key", input.idempotencyKey);
|
|
82272
|
-
const saved = receiptKeys.map((key) => app.db.select().from(researchRuns).where(
|
|
82273
|
-
|
|
82274
|
-
|
|
82361
|
+
const saved = receiptKeys.map((key) => app.db.select().from(researchRuns).where(and108(
|
|
82362
|
+
eq128(researchRuns.projectId, project.id),
|
|
82363
|
+
eq128(researchRuns.idempotencyKey, key)
|
|
82275
82364
|
)).get());
|
|
82276
82365
|
if (saved.some((row) => !row || row.requestHash !== requestHash2)) throw alreadyExists("Research batch idempotency key", input.idempotencyKey);
|
|
82277
82366
|
const runs3 = saved.map((row) => getDetail(app, project.id, row.id));
|
|
@@ -82287,8 +82376,8 @@ async function researchRoutes(app, opts) {
|
|
|
82287
82376
|
const decision = app.db.transaction((tx) => {
|
|
82288
82377
|
if (initiatedBy?.limited) {
|
|
82289
82378
|
const { start, end, date } = utcDayBounds(now);
|
|
82290
|
-
const used = tx.select({ value: count10() }).from(researchRuns).where(
|
|
82291
|
-
|
|
82379
|
+
const used = tx.select({ value: count10() }).from(researchRuns).where(and108(
|
|
82380
|
+
eq128(researchRuns.projectId, project.id),
|
|
82292
82381
|
gte34(researchRuns.createdAt, start),
|
|
82293
82382
|
lt21(researchRuns.createdAt, end),
|
|
82294
82383
|
sql52`(json_extract(${researchRuns.initiatedBy}, '$.role') = ${UserRoles.viewer} OR json_extract(${researchRuns.initiatedBy}, '$.limited') = 1)`
|
|
@@ -82342,9 +82431,9 @@ async function researchRoutes(app, opts) {
|
|
|
82342
82431
|
const requested = Number.parseInt(request.query.limit ?? "", 10);
|
|
82343
82432
|
const limit = Number.isInteger(requested) && requested > 0 ? Math.min(requested, 100) : 20;
|
|
82344
82433
|
const cursor = request.query.cursor ? parseResearchCursor(request.query.cursor, project.id) : null;
|
|
82345
|
-
const rows = app.db.select().from(researchRuns).where(
|
|
82346
|
-
|
|
82347
|
-
cursor ? or23(lt21(researchRuns.createdAt, cursor.createdAt),
|
|
82434
|
+
const rows = app.db.select().from(researchRuns).where(and108(
|
|
82435
|
+
eq128(researchRuns.projectId, project.id),
|
|
82436
|
+
cursor ? or23(lt21(researchRuns.createdAt, cursor.createdAt), and108(eq128(researchRuns.createdAt, cursor.createdAt), lt21(researchRuns.id, cursor.id))) : void 0
|
|
82348
82437
|
)).orderBy(desc58(researchRuns.createdAt), desc58(researchRuns.id)).limit(limit + 1).all();
|
|
82349
82438
|
const runs2 = rows.slice(0, limit).map(serializeRun);
|
|
82350
82439
|
const last = runs2.at(-1);
|
|
@@ -82494,9 +82583,9 @@ function resolveStoredResearchTemplate(stored, selection, idempotencyKey) {
|
|
|
82494
82583
|
return stored;
|
|
82495
82584
|
}
|
|
82496
82585
|
function resolveResearchTemplate(app, projectId, selection, scope, location) {
|
|
82497
|
-
const savedTemplate = app.db.select().from(measurementQueryTemplates).where(
|
|
82498
|
-
|
|
82499
|
-
|
|
82586
|
+
const savedTemplate = app.db.select().from(measurementQueryTemplates).where(and108(
|
|
82587
|
+
eq128(measurementQueryTemplates.projectId, projectId),
|
|
82588
|
+
eq128(measurementQueryTemplates.id, selection.templateId)
|
|
82500
82589
|
)).get();
|
|
82501
82590
|
if (!savedTemplate) throw validationError("Unknown or stale research template. Reload the selected template and try again.");
|
|
82502
82591
|
const templateVersion = savedTemplate.updatedAt;
|
|
@@ -82505,7 +82594,7 @@ function resolveResearchTemplate(app, projectId, selection, scope, location) {
|
|
|
82505
82594
|
}
|
|
82506
82595
|
const bindingLocation = selection.bindingLocation === void 0 ? location : selection.bindingLocation;
|
|
82507
82596
|
if (bindingLocation) {
|
|
82508
|
-
const project = app.db.select({ locations: projects.locations }).from(projects).where(
|
|
82597
|
+
const project = app.db.select({ locations: projects.locations }).from(projects).where(eq128(projects.id, projectId)).get();
|
|
82509
82598
|
if (!project.locations.some((item2) => sameLocation(item2, bindingLocation))) throw validationError("Research template binding location must match a configured project location.");
|
|
82510
82599
|
}
|
|
82511
82600
|
const { bindings, output } = expandResearchTemplate(savedTemplate, scope, bindingLocation);
|
|
@@ -82518,9 +82607,9 @@ function classifyResearchQueries(project, plan, queries2) {
|
|
|
82518
82607
|
return queries2.map((query2) => classifier?.classify(query2) ?? null);
|
|
82519
82608
|
}
|
|
82520
82609
|
function getDetail(app, projectId, id) {
|
|
82521
|
-
const row = app.db.select().from(researchRuns).where(
|
|
82610
|
+
const row = app.db.select().from(researchRuns).where(and108(eq128(researchRuns.id, id), eq128(researchRuns.projectId, projectId))).get();
|
|
82522
82611
|
if (!row) throw notFound("Research run", id);
|
|
82523
|
-
const queries2 = app.db.select().from(researchRunQueries).where(
|
|
82612
|
+
const queries2 = app.db.select().from(researchRunQueries).where(eq128(researchRunQueries.researchRunId, id)).orderBy(researchRunQueries.position).all().map((query2) => serializeQuery(query2, row.provider));
|
|
82524
82613
|
return { ...serializeRun(row), queries: queries2 };
|
|
82525
82614
|
}
|
|
82526
82615
|
function serializeRun(row) {
|
|
@@ -82581,7 +82670,7 @@ function utcDayBounds(now) {
|
|
|
82581
82670
|
|
|
82582
82671
|
// ../api-routes/src/simple-measurement-definitions.ts
|
|
82583
82672
|
import crypto67 from "crypto";
|
|
82584
|
-
import { and as
|
|
82673
|
+
import { and as and109, eq as eq129 } from "drizzle-orm";
|
|
82585
82674
|
function captureSimpleMeasurementDefinition(db, input) {
|
|
82586
82675
|
return db.transaction((tx) => {
|
|
82587
82676
|
const run = tx.select({
|
|
@@ -82589,7 +82678,7 @@ function captureSimpleMeasurementDefinition(db, input) {
|
|
|
82589
82678
|
trigger: runs.trigger,
|
|
82590
82679
|
status: runs.status,
|
|
82591
82680
|
measurementPlanVersionId: runs.measurementPlanVersionId
|
|
82592
|
-
}).from(runs).where(
|
|
82681
|
+
}).from(runs).where(and109(eq129(runs.projectId, input.projectId), eq129(runs.id, input.runId))).get();
|
|
82593
82682
|
if (!run) throw notFound("Run", input.runId);
|
|
82594
82683
|
if (run.kind !== RunKinds["answer-visibility"] || run.trigger === RunTriggers.probe || run.measurementPlanVersionId !== null) {
|
|
82595
82684
|
return null;
|
|
@@ -82610,7 +82699,7 @@ function captureSimpleMeasurementDefinition(db, input) {
|
|
|
82610
82699
|
throw validationError("Qualified aliases must be a sorted subset of the captured aliases.");
|
|
82611
82700
|
}
|
|
82612
82701
|
}
|
|
82613
|
-
const existing = tx.select().from(simpleMeasurementDefinitions).where(
|
|
82702
|
+
const existing = tx.select().from(simpleMeasurementDefinitions).where(and109(eq129(simpleMeasurementDefinitions.projectId, input.projectId), eq129(simpleMeasurementDefinitions.runId, input.runId))).get();
|
|
82614
82703
|
if (existing) {
|
|
82615
82704
|
const frozen = simpleMeasurementDefinitionSchema.parse(existing.definition);
|
|
82616
82705
|
const { qualifiedAliases: _liveQualifiedAliases, ...liveIdentity } = definition2.identity;
|
|
@@ -82636,15 +82725,15 @@ function captureSimpleMeasurementDefinition(db, input) {
|
|
|
82636
82725
|
if (run.status !== RunStatuses.running) {
|
|
82637
82726
|
throw validationError("Only a running run can capture a new measurement definition.");
|
|
82638
82727
|
}
|
|
82639
|
-
if (tx.select({ id: querySnapshots.id }).from(querySnapshots).where(
|
|
82728
|
+
if (tx.select({ id: querySnapshots.id }).from(querySnapshots).where(eq129(querySnapshots.runId, input.runId)).limit(1).get()) {
|
|
82640
82729
|
throw validationError("This run already has stored answers. Its measurement definition cannot be inferred afterward.");
|
|
82641
82730
|
}
|
|
82642
|
-
const projectQueryIds = new Set(tx.select({ id: queries.id }).from(queries).where(
|
|
82731
|
+
const projectQueryIds = new Set(tx.select({ id: queries.id }).from(queries).where(eq129(queries.projectId, input.projectId)).all().map((query2) => query2.id));
|
|
82643
82732
|
if (definition2.queries.some((query2) => !projectQueryIds.has(query2.queryId))) {
|
|
82644
82733
|
throw validationError("Every captured query must belong to the run project.");
|
|
82645
82734
|
}
|
|
82646
82735
|
if (definition2.competitors !== void 0) {
|
|
82647
|
-
const liveCompetitorDomains = new Set(tx.select({ domain: competitors.domain }).from(competitors).where(
|
|
82736
|
+
const liveCompetitorDomains = new Set(tx.select({ domain: competitors.domain }).from(competitors).where(eq129(competitors.projectId, input.projectId)).orderBy(competitors.domain).all().map((competitor) => competitor.domain));
|
|
82648
82737
|
const capturedDomains = new Set(definition2.competitors.map((competitor) => competitor.domain));
|
|
82649
82738
|
if (liveCompetitorDomains.size !== capturedDomains.size || [...liveCompetitorDomains].some((domain) => !capturedDomains.has(domain))) {
|
|
82650
82739
|
throw validationError("Captured competitors must exactly match the project competitors dispatched for this run.");
|
|
@@ -83433,7 +83522,9 @@ export {
|
|
|
83433
83522
|
extractPlaceAmenities,
|
|
83434
83523
|
getPlaceReviewSignals,
|
|
83435
83524
|
buildGbpSummary,
|
|
83525
|
+
BING_THROTTLE_COOLDOWN_MS,
|
|
83436
83526
|
BingApiError,
|
|
83527
|
+
bingThrottleCooldownRemainingMs,
|
|
83437
83528
|
getUrlInfo,
|
|
83438
83529
|
getCrawlStats,
|
|
83439
83530
|
getCrawlIssues,
|