@canonry/canonry 7.123.1 → 7.123.3
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 +3 -1
- 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-WGEXXMFQ.js → backfill-UDC4DTJJ.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-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-TSCCU54X.js → chunk-7ELQ3IH4.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-7KQESJWH.js → chunk-EHCH77U4.js} +283 -208
- 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-F3UXTYXA.js → chunk-MFZIEBHI.js} +4 -4
- package/dist/{chunk-7D735WS6.js → chunk-N2BYOBOL.js} +1 -1
- package/dist/{chunk-6URM26ZP.js → chunk-NLW6XEUI.js} +2 -2
- package/dist/{chunk-WRWTDHSO.js → chunk-NUYGUUZZ.js} +22 -22
- package/dist/{chunk-BVJUYSOB.js → chunk-QNO2KO66.js} +2 -2
- package/dist/{chunk-NNJ6PD64.js → chunk-QZMAW2K7.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-LQGTGSA5.js → chunk-VSPGQLEH.js} +3 -3
- package/dist/{chunk-7OYOUVZS.js → chunk-VY3SUJWI.js} +371 -371
- package/dist/{chunk-NI5THOYW.js → chunk-VZLBOKGW.js} +6 -6
- 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-NDVKLJXW.js → chunk-WQT37J7C.js} +5 -5
- package/dist/{chunk-RHH2K4BZ.js → chunk-WQYYCJGN.js} +4 -4
- package/dist/{chunk-DLJAUCAU.js → chunk-X6O6Q72D.js} +5 -5
- package/dist/{chunk-LWGO6ETW.js → chunk-XAF22QBW.js} +2 -2
- package/dist/{chunk-CQSLBPR2.js → chunk-XS5OT4FV.js} +8 -8
- 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-Q2OPF77S.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-2DBFBHAU.js → dashboard-FRSMK5KF.js} +7 -7
- package/dist/{demo-UFZBEKZC.js → demo-2EBAMJXS.js} +3 -3
- package/dist/{demo-server-3YTYVGJU.js → demo-server-BLE5KA5J.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 +25 -25
- package/dist/index.js +26 -26
- package/dist/{init-IZ3ANN2I.js → init-ZE6F37WY.js} +13 -13
- package/dist/{insights-OQ4TYD7O.js → insights-DKIQVLF7.js} +4 -4
- package/dist/intelligence-service-WWG4RBK3.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-365C4I42.js → serve-O4I7EIU4.js} +27 -27
- package/dist/{session-ZB2BI6VG.js → session-VPC2DFWP.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-57J55S4A.js → tools-2TVT5ECW.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-KWRHN6M5.js +0 -18
- package/dist/intelligence-service-A6B7TKOX.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";
|
|
@@ -1714,7 +1714,7 @@ async function userSessionRoutes(app, opts = {}) {
|
|
|
1714
1714
|
}));
|
|
1715
1715
|
};
|
|
1716
1716
|
const cookieSessionId = (request) => parseCookieHeader(request.headers.cookie)[USER_SESSION_COOKIE_NAME];
|
|
1717
|
-
app.get("/auth/session", async (request, reply) => {
|
|
1717
|
+
app.get("/auth/session", { config: { skipInstanceAuth: true } }, async (request, reply) => {
|
|
1718
1718
|
if (!anyUsersExist(app.db)) return { authRequired: false, user: null };
|
|
1719
1719
|
const signInMethods = opts.chatgptSignIn?.() ? { signInMethods: { chatgpt: true } } : {};
|
|
1720
1720
|
const token = cookieSessionId(request);
|
|
@@ -1726,7 +1726,7 @@ async function userSessionRoutes(app, opts = {}) {
|
|
|
1726
1726
|
...signInMethods
|
|
1727
1727
|
};
|
|
1728
1728
|
});
|
|
1729
|
-
app.post("/auth/login", async (request, reply) => {
|
|
1729
|
+
app.post("/auth/login", { config: { skipInstanceAuth: true } }, async (request, reply) => {
|
|
1730
1730
|
const parsed = loginRequestSchema.safeParse(request.body);
|
|
1731
1731
|
if (!parsed.success) {
|
|
1732
1732
|
throw validationError("Enter a name and a password.", { issues: parsed.error.issues });
|
|
@@ -1749,7 +1749,7 @@ async function userSessionRoutes(app, opts = {}) {
|
|
|
1749
1749
|
user: { name: account.name, role: account.role }
|
|
1750
1750
|
});
|
|
1751
1751
|
});
|
|
1752
|
-
app.get("/auth/sessions", async (request, reply) => {
|
|
1752
|
+
app.get("/auth/sessions", { config: { skipInstanceAuth: true } }, async (request, reply) => {
|
|
1753
1753
|
const token = cookieSessionId(request);
|
|
1754
1754
|
const resolved = token ? resolveUserSession(app.db, token) : null;
|
|
1755
1755
|
if (!token || !resolved) {
|
|
@@ -1769,7 +1769,7 @@ async function userSessionRoutes(app, opts = {}) {
|
|
|
1769
1769
|
}))
|
|
1770
1770
|
});
|
|
1771
1771
|
});
|
|
1772
|
-
app.delete("/auth/sessions", async (request, reply) => {
|
|
1772
|
+
app.delete("/auth/sessions", { config: { skipInstanceAuth: true } }, async (request, reply) => {
|
|
1773
1773
|
const token = cookieSessionId(request);
|
|
1774
1774
|
const resolved = token ? resolveUserSession(app.db, token) : null;
|
|
1775
1775
|
if (!token || !resolved) {
|
|
@@ -1781,7 +1781,7 @@ async function userSessionRoutes(app, opts = {}) {
|
|
|
1781
1781
|
clearSessionCookie(request, reply);
|
|
1782
1782
|
return reply.status(204).send();
|
|
1783
1783
|
});
|
|
1784
|
-
app.post("/auth/logout", async (request, reply) => {
|
|
1784
|
+
app.post("/auth/logout", { config: { skipInstanceAuth: true } }, async (request, reply) => {
|
|
1785
1785
|
assertCookieWriteOrigin(request);
|
|
1786
1786
|
const sessionId = cookieSessionId(request);
|
|
1787
1787
|
if (sessionId) deleteUserSession(app.db, sessionId);
|
|
@@ -6469,19 +6469,6 @@ function requireGooglePropertyDiscovery(request) {
|
|
|
6469
6469
|
function hashApiKey(key) {
|
|
6470
6470
|
return crypto8.createHash("sha256").update(key).digest("hex");
|
|
6471
6471
|
}
|
|
6472
|
-
var SKIP_PATHS = ["/health"];
|
|
6473
|
-
function shouldSkipAuth(url) {
|
|
6474
|
-
if (SKIP_PATHS.includes(url)) return true;
|
|
6475
|
-
if (url.endsWith("/openapi.json")) return true;
|
|
6476
|
-
if (url.endsWith("/google/callback")) return true;
|
|
6477
|
-
if (url.endsWith("/google-marketing/callback")) return true;
|
|
6478
|
-
if (url.endsWith("/session") || url.endsWith("/session/setup")) return true;
|
|
6479
|
-
if (url.endsWith("/auth/session") || url.endsWith("/auth/login") || url.endsWith("/auth/logout")) return true;
|
|
6480
|
-
if (url.endsWith("/auth/sessions")) return true;
|
|
6481
|
-
if (url.endsWith("/auth/chatgpt/status") || url.endsWith("/auth/chatgpt/start") || url.endsWith("/auth/chatgpt/callback") || url.endsWith("/auth/chatgpt/disconnect") || url.endsWith("/auth/chatgpt/models") || url.endsWith("/auth/chatgpt/model")) return true;
|
|
6482
|
-
if (url.endsWith("/traffic/cloudflare/ingest")) return true;
|
|
6483
|
-
return false;
|
|
6484
|
-
}
|
|
6485
6472
|
var MCP_DELEGATED_KEY_MAX_AGE_MS = 60 * 60 * 1e3;
|
|
6486
6473
|
var USERS_READ_SCOPE = "users.read";
|
|
6487
6474
|
var USERS_WRITE_SCOPE = "users.write";
|
|
@@ -6633,8 +6620,8 @@ function applyScopedWriteGates(request) {
|
|
|
6633
6620
|
}
|
|
6634
6621
|
async function authPlugin(app, opts = {}) {
|
|
6635
6622
|
app.addHook("onRequest", async (request, reply) => {
|
|
6623
|
+
if (request.routeOptions.config?.skipInstanceAuth === true) return;
|
|
6636
6624
|
const url = request.url.split("?")[0];
|
|
6637
|
-
if (shouldSkipAuth(url)) return;
|
|
6638
6625
|
const header2 = request.headers.authorization;
|
|
6639
6626
|
let key;
|
|
6640
6627
|
let keyArrivedInCookie = false;
|
|
@@ -50008,7 +49995,7 @@ function withLegacyAgentReadinessOperations(catalog) {
|
|
|
50008
49995
|
});
|
|
50009
49996
|
}
|
|
50010
49997
|
async function openApiRoutes(app, opts = {}) {
|
|
50011
|
-
app.get("/openapi.json", async (_request, reply) => {
|
|
49998
|
+
app.get("/openapi.json", { config: { skipInstanceAuth: true } }, async (_request, reply) => {
|
|
50012
49999
|
return reply.type("application/json").send(buildOpenApiDocument(opts));
|
|
50013
50000
|
});
|
|
50014
50001
|
}
|
|
@@ -51268,7 +51255,8 @@ function appendCookie(reply, cookie) {
|
|
|
51268
51255
|
}
|
|
51269
51256
|
async function chatGptRoutes(app, opts) {
|
|
51270
51257
|
const dashboardPath = opts.dashboardPath ?? "/";
|
|
51271
|
-
const
|
|
51258
|
+
const signInRouteConfig = (max2) => ({
|
|
51259
|
+
skipInstanceAuth: true,
|
|
51272
51260
|
rateLimit: {
|
|
51273
51261
|
timeWindow: "1 minute",
|
|
51274
51262
|
keyGenerator: (request) => {
|
|
@@ -51320,7 +51308,7 @@ async function chatGptRoutes(app, opts) {
|
|
|
51320
51308
|
reply.header("cache-control", "no-store");
|
|
51321
51309
|
return reply.redirect(withParam(returnTo ?? dashboardPath, "chatgpt_error", error), 302);
|
|
51322
51310
|
};
|
|
51323
|
-
app.get("/auth/chatgpt/status", { config:
|
|
51311
|
+
app.get("/auth/chatgpt/status", { config: signInRouteConfig(120) }, async (request, reply) => {
|
|
51324
51312
|
reply.header("cache-control", "no-store");
|
|
51325
51313
|
const userId = signedInUserId(request, reply);
|
|
51326
51314
|
if (!opts.accounts) {
|
|
@@ -51328,7 +51316,7 @@ async function chatGptRoutes(app, opts) {
|
|
|
51328
51316
|
}
|
|
51329
51317
|
return opts.accounts.status(userId);
|
|
51330
51318
|
});
|
|
51331
|
-
app.get("/auth/chatgpt/start", { config:
|
|
51319
|
+
app.get("/auth/chatgpt/start", { config: signInRouteConfig(20) }, async (request, reply) => {
|
|
51332
51320
|
const parsedIntent = chatGptSignInIntentSchema.safeParse(request.query.intent ?? ChatGptSignInIntents.login);
|
|
51333
51321
|
const returnTo = safeReturnTo(request.query.returnTo, dashboardPath);
|
|
51334
51322
|
if (!parsedIntent.success) return redirectWithError(reply, ChatGptSignInErrors.failed, returnTo);
|
|
@@ -51351,7 +51339,7 @@ async function chatGptRoutes(app, opts) {
|
|
|
51351
51339
|
reply.header("referrer-policy", "no-referrer");
|
|
51352
51340
|
return reply.redirect(started.url, 302);
|
|
51353
51341
|
});
|
|
51354
|
-
app.get("/auth/chatgpt/callback", { config:
|
|
51342
|
+
app.get("/auth/chatgpt/callback", { config: signInRouteConfig(30) }, async (request, reply) => {
|
|
51355
51343
|
appendCookie(reply, bindingCookie(request, null));
|
|
51356
51344
|
reply.header("cache-control", "no-store");
|
|
51357
51345
|
reply.header("referrer-policy", "no-referrer");
|
|
@@ -51400,7 +51388,7 @@ async function chatGptRoutes(app, opts) {
|
|
|
51400
51388
|
}
|
|
51401
51389
|
return reply.redirect(withParam(returnTo ?? dashboardPath, "chatgpt", result.plan === "connected" ? "connected" : "linked"), 302);
|
|
51402
51390
|
});
|
|
51403
|
-
app.post("/auth/chatgpt/disconnect", { config:
|
|
51391
|
+
app.post("/auth/chatgpt/disconnect", { config: signInRouteConfig(10) }, async (request, reply) => {
|
|
51404
51392
|
assertCookieWriteOrigin(request);
|
|
51405
51393
|
const userId = requireSignedIn(request, reply);
|
|
51406
51394
|
if (!opts.accounts) return { disconnected: false, revoked: false };
|
|
@@ -51416,7 +51404,7 @@ async function chatGptRoutes(app, opts) {
|
|
|
51416
51404
|
}
|
|
51417
51405
|
return result;
|
|
51418
51406
|
});
|
|
51419
|
-
app.get("/auth/chatgpt/models", { config:
|
|
51407
|
+
app.get("/auth/chatgpt/models", { config: signInRouteConfig(30) }, async (request, reply) => {
|
|
51420
51408
|
reply.header("cache-control", "no-store");
|
|
51421
51409
|
const userId = requireSignedIn(request, reply);
|
|
51422
51410
|
if (!opts.accounts?.planUsageEnabled()) throw validationError("ChatGPT plan usage is not turned on for this dashboard.");
|
|
@@ -51427,7 +51415,7 @@ async function chatGptRoutes(app, opts) {
|
|
|
51427
51415
|
throw toAppError2(error);
|
|
51428
51416
|
}
|
|
51429
51417
|
});
|
|
51430
|
-
app.put("/auth/chatgpt/model", { config:
|
|
51418
|
+
app.put("/auth/chatgpt/model", { config: signInRouteConfig(30) }, async (request, reply) => {
|
|
51431
51419
|
assertCookieWriteOrigin(request);
|
|
51432
51420
|
const userId = requireSignedIn(request, reply);
|
|
51433
51421
|
if (!opts.accounts?.planUsageEnabled()) throw validationError("ChatGPT plan usage is not turned on for this dashboard.");
|
|
@@ -54316,6 +54304,8 @@ function resolveGa4SyncDays(days) {
|
|
|
54316
54304
|
return { requestedDays, effectiveDays, clamped: effectiveDays !== requestedDays };
|
|
54317
54305
|
}
|
|
54318
54306
|
var GA4_REQUEST_TIMEOUT_MS = 3e4;
|
|
54307
|
+
var GA4_REPORT_TIMEOUT_MS = 6e4;
|
|
54308
|
+
var GA4_MAX_TIMEOUT_RETRIES = 1;
|
|
54319
54309
|
var GA4_MAX_PAGES = 50;
|
|
54320
54310
|
var GA4_MAX_CONCURRENT_REQUESTS = 4;
|
|
54321
54311
|
var GA4_MAX_RETRIES = 3;
|
|
@@ -54538,16 +54528,17 @@ function parseRetryAfter(headerValue3) {
|
|
|
54538
54528
|
}
|
|
54539
54529
|
return void 0;
|
|
54540
54530
|
}
|
|
54531
|
+
function isGa4Timeout(err) {
|
|
54532
|
+
return err instanceof Error && (err.name === "TimeoutError" || err.name === "AbortError");
|
|
54533
|
+
}
|
|
54541
54534
|
function isRetryableGa4Error(err) {
|
|
54542
54535
|
if (err instanceof GA4ApiError) {
|
|
54543
54536
|
return err.status === 429 || err.status >= 500;
|
|
54544
54537
|
}
|
|
54545
|
-
|
|
54546
|
-
return true;
|
|
54547
|
-
}
|
|
54548
|
-
return false;
|
|
54538
|
+
return isGa4Timeout(err);
|
|
54549
54539
|
}
|
|
54550
54540
|
async function withGa4Retry(fn, errLabel) {
|
|
54541
|
+
let timeoutRetries = 0;
|
|
54551
54542
|
return withRetry(fn, {
|
|
54552
54543
|
maxRetries: GA4_MAX_RETRIES,
|
|
54553
54544
|
baseDelayMs: GA4_INITIAL_RETRY_DELAY_MS,
|
|
@@ -54555,7 +54546,12 @@ async function withGa4Retry(fn, errLabel) {
|
|
|
54555
54546
|
// schedule operators have been seeing in production until we have a
|
|
54556
54547
|
// reason to introduce variance.
|
|
54557
54548
|
jitter: false,
|
|
54558
|
-
isRetryable:
|
|
54549
|
+
isRetryable: (err) => {
|
|
54550
|
+
if (!isRetryableGa4Error(err)) return false;
|
|
54551
|
+
if (!isGa4Timeout(err)) return true;
|
|
54552
|
+
timeoutRetries++;
|
|
54553
|
+
return timeoutRetries <= GA4_MAX_TIMEOUT_RETRIES;
|
|
54554
|
+
},
|
|
54559
54555
|
// Honor `Retry-After` when the server supplies it; fall back to the
|
|
54560
54556
|
// computed exponential delay otherwise.
|
|
54561
54557
|
computeDelayMs: (_attempt, err, defaultMs) => {
|
|
@@ -54571,6 +54567,7 @@ async function withGa4Retry(fn, errLabel) {
|
|
|
54571
54567
|
attempt: attempt + 1,
|
|
54572
54568
|
maxAttempts: GA4_MAX_RETRIES + 1,
|
|
54573
54569
|
status: ga4Err?.status,
|
|
54570
|
+
timedOut: isGa4Timeout(err),
|
|
54574
54571
|
delayMs,
|
|
54575
54572
|
usedRetryAfter: ga4Err?.retryAfterSeconds !== void 0
|
|
54576
54573
|
});
|
|
@@ -54589,7 +54586,7 @@ async function runReport(accessToken, propertyId, request) {
|
|
|
54589
54586
|
"Content-Type": "application/json"
|
|
54590
54587
|
},
|
|
54591
54588
|
body: JSON.stringify(request),
|
|
54592
|
-
signal: AbortSignal.timeout(
|
|
54589
|
+
signal: AbortSignal.timeout(GA4_REPORT_TIMEOUT_MS)
|
|
54593
54590
|
});
|
|
54594
54591
|
if (res.status === 401 || res.status === 403) {
|
|
54595
54592
|
const body = await res.text().catch(() => "");
|
|
@@ -54643,7 +54640,7 @@ async function batchRunReports(accessToken, propertyId, requests) {
|
|
|
54643
54640
|
"Content-Type": "application/json"
|
|
54644
54641
|
},
|
|
54645
54642
|
body: JSON.stringify({ requests }),
|
|
54646
|
-
signal: AbortSignal.timeout(
|
|
54643
|
+
signal: AbortSignal.timeout(GA4_REPORT_TIMEOUT_MS)
|
|
54647
54644
|
});
|
|
54648
54645
|
if (res.status === 401 || res.status === 403) {
|
|
54649
54646
|
const body = await res.text().catch(() => "");
|
|
@@ -55985,10 +55982,10 @@ async function googleRoutes(app, opts) {
|
|
|
55985
55982
|
attempt.succeeded();
|
|
55986
55983
|
return reply.type("text/html").send(googleOAuthSuccessHtml(type));
|
|
55987
55984
|
}
|
|
55988
|
-
app.get("/google/callback", async (request, reply) => {
|
|
55985
|
+
app.get("/google/callback", { config: { skipInstanceAuth: true } }, async (request, reply) => {
|
|
55989
55986
|
return handleOAuthCallback(request, reply);
|
|
55990
55987
|
});
|
|
55991
|
-
app.get("/projects/:name/google/callback", async (request, reply) => {
|
|
55988
|
+
app.get("/projects/:name/google/callback", { config: { skipInstanceAuth: true } }, async (request, reply) => {
|
|
55992
55989
|
return handleOAuthCallback(request, reply);
|
|
55993
55990
|
});
|
|
55994
55991
|
app.delete("/projects/:name/google/connections/:type", connectionRoute(app, (request) => {
|
|
@@ -58257,7 +58254,7 @@ async function googleMarketingRoutes(app, opts) {
|
|
|
58257
58254
|
};
|
|
58258
58255
|
registerOAuthConnect("/projects/:name/google-ads/oauth/connect", GoogleMarketingProviders["google-ads"]);
|
|
58259
58256
|
registerOAuthConnect("/projects/:name/gtm/oauth/connect", GoogleMarketingProviders.gtm);
|
|
58260
|
-
app.get("/google-marketing/callback", connectionRoute(app, (request) => {
|
|
58257
|
+
app.get("/google-marketing/callback", { config: { skipInstanceAuth: true } }, connectionRoute(app, (request) => {
|
|
58261
58258
|
const verified = oauthStateSchema.safeParse(verifySignedGoogleOAuthState(request.query.state ?? "", stateSecret));
|
|
58262
58259
|
return marketingConnection(verified.success ? verified.data.provider : unverifiedOAuthStateField(request.query.state, "provider"));
|
|
58263
58260
|
}, async (request, reply, attempt) => {
|
|
@@ -66660,6 +66657,23 @@ async function fetchGaSyncRanges(plan, fetchRange) {
|
|
|
66660
66657
|
return results;
|
|
66661
66658
|
}
|
|
66662
66659
|
|
|
66660
|
+
// ../api-routes/src/ga-sync-windows.ts
|
|
66661
|
+
function settleGaWindows(windows, results) {
|
|
66662
|
+
const read = [];
|
|
66663
|
+
const failed = [];
|
|
66664
|
+
results.forEach((result, index) => {
|
|
66665
|
+
if (result.status === "fulfilled") read.push(result.value);
|
|
66666
|
+
else failed.push({ window: windows[index], error: result.reason });
|
|
66667
|
+
});
|
|
66668
|
+
return { read, failed };
|
|
66669
|
+
}
|
|
66670
|
+
function keptGaWindows(windows, failures) {
|
|
66671
|
+
return windows.flatMap((window2) => {
|
|
66672
|
+
const failure = failures.find((entry) => entry.window === window2);
|
|
66673
|
+
return failure ? [{ window: window2, error: describeError(failure.error) }] : [];
|
|
66674
|
+
});
|
|
66675
|
+
}
|
|
66676
|
+
|
|
66663
66677
|
// ../api-routes/src/ga-search-landing-pages.ts
|
|
66664
66678
|
import crypto56 from "crypto";
|
|
66665
66679
|
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";
|
|
@@ -67483,18 +67497,40 @@ async function ga4Routes(app, opts) {
|
|
|
67483
67497
|
let aiReferrals = [];
|
|
67484
67498
|
let socialReferrals = [];
|
|
67485
67499
|
const WINDOW_KEYS = GA_OVERVIEW_WINDOWS;
|
|
67486
|
-
const
|
|
67500
|
+
const windowsRequestedAt = /* @__PURE__ */ new Date();
|
|
67501
|
+
const [summary3, windowSummaryResults, windowMetricResults] = await Promise.all([
|
|
67487
67502
|
fetchAggregateSummary(accessToken, propertyId, days),
|
|
67488
|
-
Promise.
|
|
67489
|
-
Promise.
|
|
67503
|
+
Promise.allSettled(WINDOW_KEYS.map((w) => fetchWindowSummary(accessToken, propertyId, w))),
|
|
67504
|
+
Promise.allSettled(WINDOW_KEYS.map((w) => fetchWindowMetrics(accessToken, propertyId, w)))
|
|
67490
67505
|
]);
|
|
67506
|
+
const { read: windowSummaries, failed: failedSummaryWindows } = settleGaWindows(WINDOW_KEYS, windowSummaryResults);
|
|
67507
|
+
const { read: windowMetrics, failed: failedMetricWindows } = settleGaWindows(WINDOW_KEYS, windowMetricResults);
|
|
67508
|
+
const zoneReport = windowMetrics[0];
|
|
67509
|
+
if (!zoneReport) {
|
|
67510
|
+
const firstError = failedMetricWindows[0].error;
|
|
67511
|
+
throw firstError instanceof Error ? firstError : new Error(describeError(firstError));
|
|
67512
|
+
}
|
|
67513
|
+
const reportTimeZone2 = zoneReport.timeZone;
|
|
67514
|
+
const failedWindows = [...failedMetricWindows, ...failedSummaryWindows];
|
|
67515
|
+
for (const failure of failedWindows) {
|
|
67516
|
+
componentFailure ??= { error: failure.error };
|
|
67517
|
+
gaLog("warn", "window.kept", {
|
|
67518
|
+
projectId: project.id,
|
|
67519
|
+
runId,
|
|
67520
|
+
window: failure.window,
|
|
67521
|
+
report: failedMetricWindows.includes(failure) ? "totals" : "summary",
|
|
67522
|
+
error: describeError(failure.error)
|
|
67523
|
+
});
|
|
67524
|
+
}
|
|
67525
|
+
const keptWindows = keptGaWindows(WINDOW_KEYS, failedWindows);
|
|
67491
67526
|
const requested = { startDate: summary3.periodStart, endDate: summary3.periodEnd };
|
|
67492
|
-
const definition2 = JSON.stringify(["v1",
|
|
67527
|
+
const definition2 = JSON.stringify(["v1", reportTimeZone2 ?? "UTC"]);
|
|
67493
67528
|
const planInput = { projectId: project.id, propertyId, requested, definition: definition2 };
|
|
67494
67529
|
const trafficPlan = planGaSyncCoverage(app.db, { ...planInput, component: "traffic" }, startedAt);
|
|
67495
67530
|
const aiPlan = planGaSyncCoverage(app.db, { ...planInput, component: "ai" }, startedAt);
|
|
67496
67531
|
const socialPlan = planGaSyncCoverage(app.db, { ...planInput, component: "social" }, startedAt);
|
|
67497
|
-
const
|
|
67532
|
+
const longestWindowKey = WINDOW_KEYS.at(-1);
|
|
67533
|
+
const longestWindow = windowMetrics.find((metric2) => metric2.windowKey === longestWindowKey) ?? gaOverviewComparisonRanges(longestWindowKey, windowsRequestedAt, reportTimeZone2 ?? "UTC");
|
|
67498
67534
|
const dailyPlan = planGaSyncCoverage(app.db, {
|
|
67499
67535
|
...planInput,
|
|
67500
67536
|
component: "daily",
|
|
@@ -67512,7 +67548,7 @@ async function ga4Routes(app, opts) {
|
|
|
67512
67548
|
requested: { startDate: shiftIsoCalendarDate(requested.endDate, -leadDays), endDate: requested.endDate }
|
|
67513
67549
|
}, startedAt);
|
|
67514
67550
|
const searchRequestedAt = /* @__PURE__ */ new Date();
|
|
67515
|
-
const searchTimeZone =
|
|
67551
|
+
const searchTimeZone = reportTimeZone2 ?? null;
|
|
67516
67552
|
const searchWindows = syncSearchLanding ? searchLandingWindowsToFetch(app.db, project.id, propertyId, searchTimeZone, searchRequestedAt.toISOString()) : [];
|
|
67517
67553
|
const measurementFetch = Promise.allSettled([
|
|
67518
67554
|
fetchGaSyncRanges(acquisitionPlan, (range) => fetchAcquisitionByChannel(accessToken, propertyId, acquisitionDays, { dateRange: range })),
|
|
@@ -67597,7 +67633,12 @@ async function ga4Routes(app, opts) {
|
|
|
67597
67633
|
createdAt: now
|
|
67598
67634
|
}).run();
|
|
67599
67635
|
}
|
|
67600
|
-
|
|
67636
|
+
if (windowMetrics.length > 0) {
|
|
67637
|
+
tx.delete(gaWindowMetrics).where(and86(
|
|
67638
|
+
eq100(gaWindowMetrics.projectId, project.id),
|
|
67639
|
+
inArray49(gaWindowMetrics.windowKey, windowMetrics.map((metric2) => metric2.windowKey))
|
|
67640
|
+
)).run();
|
|
67641
|
+
}
|
|
67601
67642
|
for (const windowMetric of windowMetrics) {
|
|
67602
67643
|
for (const [period2, totals] of [
|
|
67603
67644
|
[GaOverviewPeriods.current, windowMetric.current],
|
|
@@ -67698,7 +67739,12 @@ async function ga4Routes(app, opts) {
|
|
|
67698
67739
|
syncedAt: now,
|
|
67699
67740
|
syncRunId: runId
|
|
67700
67741
|
}).run();
|
|
67701
|
-
|
|
67742
|
+
if (windowSummaries.length > 0) {
|
|
67743
|
+
tx.delete(gaTrafficWindowSummaries).where(and86(
|
|
67744
|
+
eq100(gaTrafficWindowSummaries.projectId, project.id),
|
|
67745
|
+
inArray49(gaTrafficWindowSummaries.windowKey, windowSummaries.map((ws) => ws.windowKey))
|
|
67746
|
+
)).run();
|
|
67747
|
+
}
|
|
67702
67748
|
for (const ws of windowSummaries) {
|
|
67703
67749
|
tx.insert(gaTrafficWindowSummaries).values({
|
|
67704
67750
|
id: crypto57.randomUUID(),
|
|
@@ -67867,7 +67913,8 @@ async function ga4Routes(app, opts) {
|
|
|
67867
67913
|
days,
|
|
67868
67914
|
...clamped ? { requestedDays, clamped } : {},
|
|
67869
67915
|
totalUsers: summary3.totalUsers,
|
|
67870
|
-
...only ? { only } : {}
|
|
67916
|
+
...only ? { only } : {},
|
|
67917
|
+
...keptWindows.length > 0 ? { keptWindows: keptWindows.map((kept) => kept.window) } : {}
|
|
67871
67918
|
});
|
|
67872
67919
|
const counts2 = { rows: rows.length + dailyTotals.rows.length + aiReferrals.length + socialReferrals.length };
|
|
67873
67920
|
if (componentFailure) {
|
|
@@ -67891,6 +67938,7 @@ async function ga4Routes(app, opts) {
|
|
|
67891
67938
|
leads: leadResult,
|
|
67892
67939
|
...searchLandingResult ? { searchLandingPages: searchLandingResult } : {}
|
|
67893
67940
|
},
|
|
67941
|
+
...keptWindows.length > 0 ? { keptWindows } : {},
|
|
67894
67942
|
...syncedComponents ? { syncedComponents } : {}
|
|
67895
67943
|
};
|
|
67896
67944
|
} catch (e) {
|
|
@@ -74414,6 +74462,7 @@ async function trafficRoutes(app, opts) {
|
|
|
74414
74462
|
});
|
|
74415
74463
|
},
|
|
74416
74464
|
config: {
|
|
74465
|
+
skipInstanceAuth: true,
|
|
74417
74466
|
rateLimit: {
|
|
74418
74467
|
hook: "onRequest",
|
|
74419
74468
|
max: opts.cloudflareIngestIpRateLimitMax ?? DEFAULT_CLOUDFLARE_INGEST_RATE_LIMIT_MAX,
|
|
@@ -77684,7 +77733,43 @@ var ga4ConnectionCheck = {
|
|
|
77684
77733
|
var GA_AUTH_CHECKS = [ga4ConnectionCheck];
|
|
77685
77734
|
|
|
77686
77735
|
// ../api-routes/src/doctor/checks/data-freshness.ts
|
|
77687
|
-
import { and as
|
|
77736
|
+
import { and as and99, desc as desc52, eq as eq116 } from "drizzle-orm";
|
|
77737
|
+
|
|
77738
|
+
// ../api-routes/src/doctor/checks/sync-run-state.ts
|
|
77739
|
+
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";
|
|
77740
|
+
var SYNC_FAILURE_WINDOW = 3;
|
|
77741
|
+
var FINISHED_STATUSES = [RunStatuses.completed, RunStatuses.partial, RunStatuses.failed];
|
|
77742
|
+
var SUCCESS_STATUSES = [RunStatuses.completed, RunStatuses.partial];
|
|
77743
|
+
function latestErrorText(raw) {
|
|
77744
|
+
const parsed = parseRunError(raw);
|
|
77745
|
+
return parsed ? formatRunErrorOneLine(parsed) : "no error was recorded";
|
|
77746
|
+
}
|
|
77747
|
+
function readSyncRunState(db, projectId, kind, options = {}) {
|
|
77748
|
+
const scope = and98(
|
|
77749
|
+
eq115(runs.projectId, projectId),
|
|
77750
|
+
eq115(runs.kind, kind),
|
|
77751
|
+
...options.sourceId ? [eq115(runs.sourceId, options.sourceId)] : [],
|
|
77752
|
+
...options.nothingToSyncErrors?.length ? [or21(isNull18(runs.error), notInArray4(runs.error, [...options.nothingToSyncErrors]))] : []
|
|
77753
|
+
);
|
|
77754
|
+
const graded = options.since ? and98(scope, gte30(runs.createdAt, options.since)) : scope;
|
|
77755
|
+
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();
|
|
77756
|
+
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();
|
|
77757
|
+
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();
|
|
77758
|
+
const failuresSinceSuccess = Number(failureCount?.count ?? 0);
|
|
77759
|
+
const latest = recent[0];
|
|
77760
|
+
return {
|
|
77761
|
+
latestStatus: latest?.status ?? null,
|
|
77762
|
+
latestRunAt: latest?.createdAt ?? null,
|
|
77763
|
+
latestRunId: latest?.id ?? null,
|
|
77764
|
+
latestTrigger: latest?.trigger ?? null,
|
|
77765
|
+
latestError: latest?.status === RunStatuses.failed ? latestErrorText(latest.error) : null,
|
|
77766
|
+
lastSuccessAt: lastSuccess ? lastSuccess.finishedAt ?? lastSuccess.createdAt : null,
|
|
77767
|
+
consecutiveFailures: failuresSinceSuccess,
|
|
77768
|
+
repeatedFailure: recent.length >= SYNC_FAILURE_WINDOW && recent.every((run) => run.status === RunStatuses.failed)
|
|
77769
|
+
};
|
|
77770
|
+
}
|
|
77771
|
+
|
|
77772
|
+
// ../api-routes/src/doctor/checks/data-freshness.ts
|
|
77688
77773
|
var GA_DATA_AGING_DAYS = 3;
|
|
77689
77774
|
var GA_DATA_STALE_DAYS = 5;
|
|
77690
77775
|
var GSC_DATA_AGING_DAYS = 5;
|
|
@@ -77693,6 +77778,7 @@ var BING_DATA_AGING_DAYS = 7;
|
|
|
77693
77778
|
var SYNC_IDLE_DAYS = 3;
|
|
77694
77779
|
var NOT_SYNCING_URGENT_DAYS = 8;
|
|
77695
77780
|
var GSC_REPORTING_TIME_ZONE2 = "America/Los_Angeles";
|
|
77781
|
+
var SUMMARY_ERROR_LIMIT = 300;
|
|
77696
77782
|
var DAY_MS6 = 24 * 60 * 60 * 1e3;
|
|
77697
77783
|
var ISO_DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
|
|
77698
77784
|
function utcFromIsoDate(date) {
|
|
@@ -77713,8 +77799,8 @@ function daysSinceDate(date, now = /* @__PURE__ */ new Date(), timeZone) {
|
|
|
77713
77799
|
function skipped(code, summary3) {
|
|
77714
77800
|
return { status: CheckStatuses.skipped, code, summary: summary3, remediation: null };
|
|
77715
77801
|
}
|
|
77716
|
-
function lastSyncAgeDays(ctx,
|
|
77717
|
-
const row = ctx.db.select({ createdAt: runs.createdAt }).from(runs).where(
|
|
77802
|
+
function lastSyncAgeDays(ctx, kind) {
|
|
77803
|
+
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();
|
|
77718
77804
|
if (!row?.createdAt) return null;
|
|
77719
77805
|
const age = Math.floor((Date.now() - Date.parse(row.createdAt)) / DAY_MS6);
|
|
77720
77806
|
return Number.isFinite(age) ? age : null;
|
|
@@ -77723,7 +77809,7 @@ function grade(ctx, spec, newestDate) {
|
|
|
77723
77809
|
const projectName = ctx.project.name;
|
|
77724
77810
|
const code = (suffix) => `${spec.source}.data.${suffix}`;
|
|
77725
77811
|
const sync = spec.syncCommand(projectName);
|
|
77726
|
-
const syncAge = lastSyncAgeDays(ctx, spec.
|
|
77812
|
+
const syncAge = lastSyncAgeDays(ctx, spec.syncKind);
|
|
77727
77813
|
const syncIdle = syncAge === null || syncAge >= SYNC_IDLE_DAYS;
|
|
77728
77814
|
if (!newestDate) {
|
|
77729
77815
|
return {
|
|
@@ -77754,6 +77840,26 @@ function grade(ctx, spec, newestDate) {
|
|
|
77754
77840
|
details
|
|
77755
77841
|
};
|
|
77756
77842
|
}
|
|
77843
|
+
const syncState = readSyncRunState(ctx.db, ctx.project.id, spec.syncKind);
|
|
77844
|
+
if (syncState.latestStatus === RunStatuses.failed) {
|
|
77845
|
+
const errorText = syncState.latestError ?? "no error was recorded";
|
|
77846
|
+
const shownError = errorText.length > SUMMARY_ERROR_LIMIT ? `${truncateUtf16(errorText, SUMMARY_ERROR_LIMIT)}...` : errorText;
|
|
77847
|
+
const failures = syncState.consecutiveFailures;
|
|
77848
|
+
return {
|
|
77849
|
+
status: CheckStatuses.warn,
|
|
77850
|
+
code: code("sync-failing"),
|
|
77851
|
+
...age >= spec.staleDays ? { urgent: true } : {},
|
|
77852
|
+
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}`,
|
|
77853
|
+
remediation: `Fix the cause the error names, then run \`${sync}\`.`,
|
|
77854
|
+
details: {
|
|
77855
|
+
...details,
|
|
77856
|
+
consecutiveFailures: failures,
|
|
77857
|
+
latestRunAt: syncState.latestRunAt,
|
|
77858
|
+
latestError: syncState.latestError,
|
|
77859
|
+
lastSuccessAt: syncState.lastSuccessAt
|
|
77860
|
+
}
|
|
77861
|
+
};
|
|
77862
|
+
}
|
|
77757
77863
|
if (syncIdle) {
|
|
77758
77864
|
return {
|
|
77759
77865
|
status: CheckStatuses.warn,
|
|
@@ -77783,7 +77889,7 @@ var GA_SPEC = {
|
|
|
77783
77889
|
label: "GA4",
|
|
77784
77890
|
agingDays: GA_DATA_AGING_DAYS,
|
|
77785
77891
|
staleDays: GA_DATA_STALE_DAYS,
|
|
77786
|
-
|
|
77892
|
+
syncKind: RunKinds["ga-sync"],
|
|
77787
77893
|
syncCommand: (name) => `canonry ga sync ${name}`,
|
|
77788
77894
|
quietExplanation: "GA4 omits days with no sessions, so a genuinely quiet period clears itself on the next visit.",
|
|
77789
77895
|
brokenExplanation: "If the site did have visitors, check that the GA4 tag or its Tag Manager container is still on the live site."
|
|
@@ -77794,7 +77900,7 @@ var GSC_SPEC = {
|
|
|
77794
77900
|
agingDays: GSC_DATA_AGING_DAYS,
|
|
77795
77901
|
staleDays: GSC_DATA_STALE_DAYS,
|
|
77796
77902
|
timeZone: GSC_REPORTING_TIME_ZONE2,
|
|
77797
|
-
|
|
77903
|
+
syncKind: RunKinds["gsc-sync"],
|
|
77798
77904
|
syncCommand: (name) => `canonry google sync ${name}`,
|
|
77799
77905
|
quietExplanation: "Search Console omits days with no impressions and reports two to three days behind, so a quiet period clears itself.",
|
|
77800
77906
|
brokenExplanation: "If the site did have impressions, check that the property still lists this site and the connected account still has access."
|
|
@@ -77816,7 +77922,7 @@ var gaRecentDataCheck = {
|
|
|
77816
77922
|
const connection = gaConnected(ctx);
|
|
77817
77923
|
if (connection === "store-unavailable") return skipped("ga.data.store-unavailable", "No GA4 credential store configured for this deployment.");
|
|
77818
77924
|
if (connection === "not-connected") return skipped("ga.data.not-connected", "GA4 is not connected for this project.");
|
|
77819
|
-
const newest = ctx.db.select({ date: gaDailyTotals.date }).from(gaDailyTotals).where(
|
|
77925
|
+
const newest = ctx.db.select({ date: gaDailyTotals.date }).from(gaDailyTotals).where(eq116(gaDailyTotals.projectId, ctx.project.id)).orderBy(desc52(gaDailyTotals.date)).limit(1).get();
|
|
77820
77926
|
return grade(ctx, GA_SPEC, newest?.date);
|
|
77821
77927
|
}
|
|
77822
77928
|
};
|
|
@@ -77831,16 +77937,16 @@ var gscRecentDataCheck = {
|
|
|
77831
77937
|
if (!ctx.googleConnectionStore.getConnection(ctx.project.canonicalDomain, "gsc")) {
|
|
77832
77938
|
return skipped("gsc.data.not-connected", "Search Console is not connected for this project.");
|
|
77833
77939
|
}
|
|
77834
|
-
const watermark = ctx.db.select({ dataThroughDate: gscDataWatermarks.dataThroughDate }).from(gscDataWatermarks).where(
|
|
77940
|
+
const watermark = ctx.db.select({ dataThroughDate: gscDataWatermarks.dataThroughDate }).from(gscDataWatermarks).where(eq116(gscDataWatermarks.projectId, ctx.project.id)).get();
|
|
77835
77941
|
if (watermark?.dataThroughDate) return grade(ctx, GSC_SPEC, watermark.dataThroughDate);
|
|
77836
|
-
const newest = ctx.db.select({ date: gscDailyTotals.date }).from(gscDailyTotals).where(
|
|
77942
|
+
const newest = ctx.db.select({ date: gscDailyTotals.date }).from(gscDailyTotals).where(eq116(gscDailyTotals.projectId, ctx.project.id)).orderBy(desc52(gscDailyTotals.date)).limit(1).get();
|
|
77837
77943
|
return grade(ctx, GSC_SPEC, newest?.date);
|
|
77838
77944
|
}
|
|
77839
77945
|
};
|
|
77840
77946
|
var DATA_FRESHNESS_CHECKS = [gaRecentDataCheck, gscRecentDataCheck];
|
|
77841
77947
|
|
|
77842
77948
|
// ../api-routes/src/doctor/checks/seo-refresh.ts
|
|
77843
|
-
import { and as
|
|
77949
|
+
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";
|
|
77844
77950
|
var GRACE_DAYS = 2;
|
|
77845
77951
|
var DAY_MS7 = 24 * 60 * 60 * 1e3;
|
|
77846
77952
|
var FIRING_SPAN_MS = 6e4;
|
|
@@ -77849,7 +77955,7 @@ function skipped2(code, summary3) {
|
|
|
77849
77955
|
return { status: CheckStatuses.skipped, code, summary: summary3, remediation: null };
|
|
77850
77956
|
}
|
|
77851
77957
|
function seoSyncRuns(projectId) {
|
|
77852
|
-
return
|
|
77958
|
+
return and100(eq117(runs.projectId, projectId), eq117(runs.kind, RunKinds["seo-sync"]));
|
|
77853
77959
|
}
|
|
77854
77960
|
function scheduleTiming(schedule) {
|
|
77855
77961
|
if (!schedule.recurrence) return { cronExpr: schedule.cronExpr, timezone: schedule.timezone, recurrence: null };
|
|
@@ -77857,16 +77963,16 @@ function scheduleTiming(schedule) {
|
|
|
77857
77963
|
return recurrence ? { cronExpr: schedule.cronExpr, timezone: schedule.timezone, recurrence } : null;
|
|
77858
77964
|
}
|
|
77859
77965
|
function latestFiring(ctx, projectId, enabledSince) {
|
|
77860
|
-
const scheduled =
|
|
77861
|
-
const newest = ctx.db.select({ createdAt: runs.createdAt }).from(runs).where(scheduled).orderBy(
|
|
77966
|
+
const scheduled = and100(seoSyncRuns(projectId), eq117(runs.trigger, RunTriggers.scheduled), gt10(runs.createdAt, enabledSince));
|
|
77967
|
+
const newest = ctx.db.select({ createdAt: runs.createdAt }).from(runs).where(scheduled).orderBy(desc53(runs.createdAt)).limit(1).get();
|
|
77862
77968
|
if (!newest) return [];
|
|
77863
77969
|
const newestMs = Date.parse(newest.createdAt);
|
|
77864
77970
|
const after = Number.isFinite(newestMs) ? new Date(newestMs - FIRING_SPAN_MS).toISOString() : newest.createdAt;
|
|
77865
|
-
return ctx.db.select({ id: runs.id, status: runs.status, error: runs.error, createdAt: runs.createdAt }).from(runs).where(
|
|
77971
|
+
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();
|
|
77866
77972
|
}
|
|
77867
77973
|
function lastCompleted(ctx, projectId) {
|
|
77868
77974
|
const at = sql49`coalesce(${runs.finishedAt}, ${runs.createdAt})`;
|
|
77869
|
-
return ctx.db.select({ id: runs.id, at }).from(runs).where(
|
|
77975
|
+
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;
|
|
77870
77976
|
}
|
|
77871
77977
|
function isIncomplete(run) {
|
|
77872
77978
|
return run.status === RunStatuses.failed || run.status === RunStatuses.partial;
|
|
@@ -77880,7 +77986,7 @@ function unsettledRuns(ctx, projectId, firing, profiles) {
|
|
|
77880
77986
|
const incomplete = firing.filter(isIncomplete);
|
|
77881
77987
|
const firedAt = firing[firing.length - 1]?.createdAt;
|
|
77882
77988
|
if (incomplete.length === 0 || !firedAt) return incomplete;
|
|
77883
|
-
const refreshed = new Set(ctx.db.select({ profileId: seoJobs.profileId }).from(runs).innerJoin(seoJobs,
|
|
77989
|
+
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));
|
|
77884
77990
|
return incomplete.filter((run) => {
|
|
77885
77991
|
const profile = profiles.get(run.id) ?? null;
|
|
77886
77992
|
return profile === null ? refreshed.size === 0 : !refreshed.has(profile);
|
|
@@ -77890,7 +77996,7 @@ var COUNT_LIST = new Intl.ListFormat("en", { style: "long", type: "conjunction"
|
|
|
77890
77996
|
function refreshReason(ctx, run) {
|
|
77891
77997
|
const stored = parseRunError(run.error);
|
|
77892
77998
|
if (stored) return formatRunErrorOneLine(stored);
|
|
77893
|
-
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,
|
|
77999
|
+
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());
|
|
77894
78000
|
const failed = tasks.filter((task) => task.status === SeoRunStatuses.failed || task.status === SeoRunStatuses["reconciliation-required"]);
|
|
77895
78001
|
const partial = tasks.filter((task) => task.status === SeoRunStatuses.partial).length;
|
|
77896
78002
|
const cancelled = tasks.filter((task) => task.status === SeoRunStatuses.cancelled).length;
|
|
@@ -77910,7 +78016,7 @@ function refreshReason(ctx, run) {
|
|
|
77910
78016
|
return `Of ${tasks.length} ${unit}, ${COUNT_LIST.format(counts2)}.${errors ? ` ${errors}` : ""}`;
|
|
77911
78017
|
}
|
|
77912
78018
|
function gradeSeoRefresh(ctx, project) {
|
|
77913
|
-
const schedule = ctx.db.select().from(schedules).where(
|
|
78019
|
+
const schedule = ctx.db.select().from(schedules).where(and100(eq117(schedules.projectId, project.id), eq117(schedules.kind, SchedulableRunKinds["seo-sync"]))).get();
|
|
77914
78020
|
if (!schedule) return skipped2("seo.data.not-scheduled", "No SEO refresh schedule is set for this project.");
|
|
77915
78021
|
if (!schedule.enabled) return skipped2("seo.data.not-scheduled", "The SEO refresh schedule is disabled.");
|
|
77916
78022
|
const name = project.name;
|
|
@@ -77982,7 +78088,7 @@ function gradeSeoRefresh(ctx, project) {
|
|
|
77982
78088
|
};
|
|
77983
78089
|
}
|
|
77984
78090
|
if (now >= Date.parse(deadlineAt)) {
|
|
77985
|
-
const active = ctx.db.select({ id: runs.id, createdAt: runs.createdAt }).from(runs).where(
|
|
78091
|
+
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();
|
|
77986
78092
|
const since = last ? `No SEO refresh has completed since ${day(last.at)}.` : "No SEO refresh has completed since the schedule was enabled.";
|
|
77987
78093
|
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.`;
|
|
77988
78094
|
return {
|
|
@@ -78292,7 +78398,7 @@ var siteReachabilityCheck = {
|
|
|
78292
78398
|
var SITE_REACHABILITY_CHECKS = [siteReachabilityCheck];
|
|
78293
78399
|
|
|
78294
78400
|
// ../api-routes/src/doctor/checks/api-hosts.ts
|
|
78295
|
-
import { eq as
|
|
78401
|
+
import { eq as eq119 } from "drizzle-orm";
|
|
78296
78402
|
|
|
78297
78403
|
// ../api-routes/src/api-host-probe.ts
|
|
78298
78404
|
import dns4 from "dns/promises";
|
|
@@ -78398,11 +78504,8 @@ async function probeApiHost(host, options = {}) {
|
|
|
78398
78504
|
}
|
|
78399
78505
|
|
|
78400
78506
|
// ../api-routes/src/doctor/checks/integration-sync.ts
|
|
78401
|
-
import { and as
|
|
78402
|
-
var
|
|
78403
|
-
var SUMMARY_ERROR_LIMIT = 300;
|
|
78404
|
-
var FINISHED_STATUSES = [RunStatuses.completed, RunStatuses.partial, RunStatuses.failed];
|
|
78405
|
-
var SUCCESS_STATUSES = [RunStatuses.completed, RunStatuses.partial];
|
|
78507
|
+
import { and as and101, eq as eq118 } from "drizzle-orm";
|
|
78508
|
+
var SUMMARY_ERROR_LIMIT2 = 300;
|
|
78406
78509
|
var GBP_NOTHING_TO_SYNC_ERRORS = [serializeRunError({ message: GBP_NO_SELECTED_LOCATIONS_ERROR })];
|
|
78407
78510
|
var CONNECTED = { state: "connected", since: null };
|
|
78408
78511
|
function googleMarketingConnection(provider) {
|
|
@@ -78425,7 +78528,7 @@ function gscConnection(ctx, project) {
|
|
|
78425
78528
|
function gbpConnection(ctx, project) {
|
|
78426
78529
|
if (!ctx.googleConnectionStore) return { state: "store-unavailable" };
|
|
78427
78530
|
if (!ctx.googleConnectionStore.getConnection(project.canonicalDomain, "gbp")) return { state: "not-connected" };
|
|
78428
|
-
const selected = ctx.db.select({ locationName: gbpLocations.locationName }).from(gbpLocations).where(
|
|
78531
|
+
const selected = ctx.db.select({ locationName: gbpLocations.locationName }).from(gbpLocations).where(and101(eq118(gbpLocations.projectId, project.id), eq118(gbpLocations.selected, true))).limit(1).get();
|
|
78429
78532
|
return selected ? CONNECTED : { state: "no-selected-locations" };
|
|
78430
78533
|
}
|
|
78431
78534
|
function gaConnection(ctx, project) {
|
|
@@ -78493,34 +78596,6 @@ var SPECS = [
|
|
|
78493
78596
|
function skipped4(code, summary3) {
|
|
78494
78597
|
return { status: CheckStatuses.skipped, code, summary: summary3, remediation: null };
|
|
78495
78598
|
}
|
|
78496
|
-
function latestErrorText(raw) {
|
|
78497
|
-
const parsed = parseRunError(raw);
|
|
78498
|
-
return parsed ? formatRunErrorOneLine(parsed) : "no error was recorded";
|
|
78499
|
-
}
|
|
78500
|
-
function readSyncRunState(db, projectId, kind, options = {}) {
|
|
78501
|
-
const scope = and100(
|
|
78502
|
-
eq117(runs.projectId, projectId),
|
|
78503
|
-
eq117(runs.kind, kind),
|
|
78504
|
-
...options.sourceId ? [eq117(runs.sourceId, options.sourceId)] : [],
|
|
78505
|
-
...options.nothingToSyncErrors?.length ? [or21(isNull18(runs.error), notInArray4(runs.error, [...options.nothingToSyncErrors]))] : []
|
|
78506
|
-
);
|
|
78507
|
-
const graded = options.since ? and100(scope, gte30(runs.createdAt, options.since)) : scope;
|
|
78508
|
-
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();
|
|
78509
|
-
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();
|
|
78510
|
-
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();
|
|
78511
|
-
const failuresSinceSuccess = Number(failureCount?.count ?? 0);
|
|
78512
|
-
const latest = recent[0];
|
|
78513
|
-
return {
|
|
78514
|
-
latestStatus: latest?.status ?? null,
|
|
78515
|
-
latestRunAt: latest?.createdAt ?? null,
|
|
78516
|
-
latestRunId: latest?.id ?? null,
|
|
78517
|
-
latestTrigger: latest?.trigger ?? null,
|
|
78518
|
-
latestError: latest?.status === RunStatuses.failed ? latestErrorText(latest.error) : null,
|
|
78519
|
-
lastSuccessAt: lastSuccess ? lastSuccess.finishedAt ?? lastSuccess.createdAt : null,
|
|
78520
|
-
consecutiveFailures: failuresSinceSuccess,
|
|
78521
|
-
repeatedFailure: recent.length >= SYNC_FAILURE_WINDOW && recent.every((run) => run.status === RunStatuses.failed)
|
|
78522
|
-
};
|
|
78523
|
-
}
|
|
78524
78599
|
function gradeSyncFailures(ctx, spec) {
|
|
78525
78600
|
const code = (suffix) => `${spec.prefix}.sync.${suffix}`;
|
|
78526
78601
|
const project = ctx.project;
|
|
@@ -78554,7 +78629,7 @@ function gradeSyncFailures(ctx, spec) {
|
|
|
78554
78629
|
};
|
|
78555
78630
|
if (state.repeatedFailure) {
|
|
78556
78631
|
const errorText = state.latestError ?? "no error was recorded";
|
|
78557
|
-
const shownError = errorText.length >
|
|
78632
|
+
const shownError = errorText.length > SUMMARY_ERROR_LIMIT2 ? `${truncateUtf16(errorText, SUMMARY_ERROR_LIMIT2)}...` : errorText;
|
|
78558
78633
|
const lastSuccessText = state.lastSuccessAt ?? (connection.since ? `none since connecting at ${connection.since}` : "never");
|
|
78559
78634
|
const notFound2 = spec.notFoundRemediation && /\bwas not found\b/i.test(errorText);
|
|
78560
78635
|
return {
|
|
@@ -78604,7 +78679,7 @@ function connectionFor(prefix, ctx, project) {
|
|
|
78604
78679
|
if (prefix === "google-ads") return googleMarketingConnection("googleAds")(ctx);
|
|
78605
78680
|
if (prefix === "gtm") return googleMarketingConnection("gtm")(ctx);
|
|
78606
78681
|
if (prefix === "bing") return ctx.bingConnectionStore?.getConnection(project.canonicalDomain) ? { state: "connected", since: null } : { state: "not-connected" };
|
|
78607
|
-
return ctx.db.select({ id: adsConnections.id }).from(adsConnections).where(
|
|
78682
|
+
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" };
|
|
78608
78683
|
}
|
|
78609
78684
|
function syncCommand(prefix) {
|
|
78610
78685
|
if (prefix === "gsc") return "google sync";
|
|
@@ -78649,7 +78724,7 @@ function definition(prefix) {
|
|
|
78649
78724
|
var API_HOST_CHECKS = Object.keys(API_HOST_TABLE).map(definition);
|
|
78650
78725
|
|
|
78651
78726
|
// ../api-routes/src/doctor/checks/gbp-auth.ts
|
|
78652
|
-
import { and as
|
|
78727
|
+
import { and as and102, eq as eq120 } from "drizzle-orm";
|
|
78653
78728
|
var RECENT_SYNC_WARN_DAYS = 4;
|
|
78654
78729
|
var RECENT_SYNC_FAIL_DAYS = 30;
|
|
78655
78730
|
function skippedNoProject3() {
|
|
@@ -78669,7 +78744,7 @@ function storeUnavailable() {
|
|
|
78669
78744
|
};
|
|
78670
78745
|
}
|
|
78671
78746
|
function hasSelectedLocation(ctx, projectId) {
|
|
78672
|
-
return !!ctx.db.select({ id: gbpLocations.id }).from(gbpLocations).where(
|
|
78747
|
+
return !!ctx.db.select({ id: gbpLocations.id }).from(gbpLocations).where(and102(eq120(gbpLocations.projectId, projectId), eq120(gbpLocations.selected, true))).limit(1).get();
|
|
78673
78748
|
}
|
|
78674
78749
|
async function resolveGbpToken(ctx) {
|
|
78675
78750
|
if (!ctx.project) return { ok: false, output: skippedNoProject3() };
|
|
@@ -78929,7 +79004,7 @@ var recentSyncCheck = {
|
|
|
78929
79004
|
title: "GBP recent sync",
|
|
78930
79005
|
run: (ctx) => {
|
|
78931
79006
|
if (!ctx.project) return skippedNoProject3();
|
|
78932
|
-
const selected = ctx.db.select({ locationName: gbpLocations.locationName, syncedAt: gbpLocations.syncedAt }).from(gbpLocations).where(
|
|
79007
|
+
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();
|
|
78933
79008
|
if (selected.length === 0) {
|
|
78934
79009
|
return {
|
|
78935
79010
|
status: CheckStatuses.skipped,
|
|
@@ -78989,7 +79064,7 @@ var GBP_AUTH_CHECK_BY_ID = Object.fromEntries(
|
|
|
78989
79064
|
);
|
|
78990
79065
|
|
|
78991
79066
|
// ../api-routes/src/doctor/checks/places.ts
|
|
78992
|
-
import { eq as
|
|
79067
|
+
import { eq as eq121 } from "drizzle-orm";
|
|
78993
79068
|
var apiKeyCheck = {
|
|
78994
79069
|
id: "gbp.places.api-key",
|
|
78995
79070
|
category: CheckCategories.auth,
|
|
@@ -79034,7 +79109,7 @@ var apiKeyCheck = {
|
|
|
79034
79109
|
details: { tier: cfg.tier }
|
|
79035
79110
|
};
|
|
79036
79111
|
}
|
|
79037
|
-
const rows = ctx.db.select({ placeId: gbpLocations.placeId, selected: gbpLocations.selected }).from(gbpLocations).where(
|
|
79112
|
+
const rows = ctx.db.select({ placeId: gbpLocations.placeId, selected: gbpLocations.selected }).from(gbpLocations).where(eq121(gbpLocations.projectId, ctx.project.id)).all();
|
|
79038
79113
|
const selected = rows.filter((r) => r.selected);
|
|
79039
79114
|
const locationsWithPlaceId = selected.filter((r) => Boolean(r.placeId)).length;
|
|
79040
79115
|
const details = {
|
|
@@ -79067,7 +79142,7 @@ var PLACES_CHECK_BY_ID = Object.fromEntries(
|
|
|
79067
79142
|
);
|
|
79068
79143
|
|
|
79069
79144
|
// ../api-routes/src/doctor/checks/gbp-reviews.ts
|
|
79070
|
-
import { and as
|
|
79145
|
+
import { and as and103, desc as desc54, eq as eq122, gte as gte31, inArray as inArray55, sql as sql50 } from "drizzle-orm";
|
|
79071
79146
|
var REVIEW_EVENTS = /* @__PURE__ */ new Set(["review.negative", "review.rating-dropped"]);
|
|
79072
79147
|
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`.";
|
|
79073
79148
|
var reviewsAccessCheck = {
|
|
@@ -79095,7 +79170,7 @@ var reviewsAccessCheck = {
|
|
|
79095
79170
|
reviewsAccess: gbpLocations.reviewsAccess,
|
|
79096
79171
|
reviewsAccessReason: gbpLocations.reviewsAccessReason,
|
|
79097
79172
|
reviewsCheckedAt: gbpLocations.reviewsCheckedAt
|
|
79098
|
-
}).from(gbpLocations).where(
|
|
79173
|
+
}).from(gbpLocations).where(and103(eq122(gbpLocations.projectId, project.id), eq122(gbpLocations.selected, true))).all();
|
|
79099
79174
|
if (locations.length === 0) {
|
|
79100
79175
|
return {
|
|
79101
79176
|
status: CheckStatuses.skipped,
|
|
@@ -79115,7 +79190,7 @@ var reviewsAccessCheck = {
|
|
|
79115
79190
|
const places = ctx.getPlacesConfig?.();
|
|
79116
79191
|
const placesFallback = places !== void 0 && places.tier === "atmosphere" && Boolean(places.apiKey);
|
|
79117
79192
|
const v4Worked = new Set(
|
|
79118
|
-
ctx.db.select({ locationName: gbpReviewRatings.locationName }).from(gbpReviewRatings).where(
|
|
79193
|
+
ctx.db.select({ locationName: gbpReviewRatings.locationName }).from(gbpReviewRatings).where(and103(eq122(gbpReviewRatings.projectId, project.id), eq122(gbpReviewRatings.origin, "gbp"))).all().map((row) => row.locationName)
|
|
79119
79194
|
);
|
|
79120
79195
|
const coverageOf = (loc) => {
|
|
79121
79196
|
if (businessProfileReviewsCover(loc.reviewsAccess ?? null, v4Worked.has(loc.locationName))) return "full";
|
|
@@ -79149,7 +79224,7 @@ var reviewsAccessCheck = {
|
|
|
79149
79224
|
none > 0 ? `${none} have no review source` : null
|
|
79150
79225
|
].filter((part) => part !== null);
|
|
79151
79226
|
const summary3 = `Business Profile reviews are not available${why}. ${parts.join("; ")}.`;
|
|
79152
|
-
const subscribed = ctx.db.select({ config: notifications.config, enabled: notifications.enabled }).from(notifications).where(
|
|
79227
|
+
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)));
|
|
79153
79228
|
const placesHint = placesFallback ? "" : " For partial coverage meanwhile, set a Places API key (`GOOGLE_PLACES_API_KEY` or `places.apiKey`) with `places.tier: atmosphere`.";
|
|
79154
79229
|
if (none > 0 && subscribed) {
|
|
79155
79230
|
return {
|
|
@@ -79188,9 +79263,9 @@ var reviewDeliveryCheck = {
|
|
|
79188
79263
|
attempts: reviewWebhookDeliveries.attempts,
|
|
79189
79264
|
lastTouched,
|
|
79190
79265
|
payload: reviewWebhookDeliveries.payload
|
|
79191
|
-
}).from(reviewWebhookDeliveries).where(
|
|
79192
|
-
|
|
79193
|
-
|
|
79266
|
+
}).from(reviewWebhookDeliveries).where(and103(
|
|
79267
|
+
eq122(reviewWebhookDeliveries.projectId, ctx.project.id),
|
|
79268
|
+
inArray55(reviewWebhookDeliveries.state, [ReviewDeliveryStates.Uncertain, ReviewDeliveryStates.Failed]),
|
|
79194
79269
|
gte31(lastTouched, since)
|
|
79195
79270
|
)).orderBy(desc54(lastTouched)).all();
|
|
79196
79271
|
if (rows.length === 0) {
|
|
@@ -79201,7 +79276,7 @@ var reviewDeliveryCheck = {
|
|
|
79201
79276
|
remediation: null
|
|
79202
79277
|
};
|
|
79203
79278
|
}
|
|
79204
|
-
const destinations = new Map(ctx.db.select({ id: notifications.id, config: notifications.config }).from(notifications).where(
|
|
79279
|
+
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]));
|
|
79205
79280
|
const deliveries = rows.map((row) => {
|
|
79206
79281
|
const review = row.payload.reviews[0];
|
|
79207
79282
|
return {
|
|
@@ -79775,7 +79850,7 @@ var RUNTIME_STATE_CHECKS = [
|
|
|
79775
79850
|
];
|
|
79776
79851
|
|
|
79777
79852
|
// ../api-routes/src/doctor/checks/traffic-source.ts
|
|
79778
|
-
import { and as
|
|
79853
|
+
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";
|
|
79779
79854
|
var RECENT_DATA_WARN_DAYS = 7;
|
|
79780
79855
|
var RECENT_DATA_FAIL_DAYS = 30;
|
|
79781
79856
|
function isCloudflareQueuePull(source) {
|
|
@@ -79809,8 +79884,8 @@ function skippedNoProject5() {
|
|
|
79809
79884
|
function loadProbes(ctx) {
|
|
79810
79885
|
if (!ctx.project) return [];
|
|
79811
79886
|
const rows = ctx.db.select().from(trafficSources).where(
|
|
79812
|
-
|
|
79813
|
-
|
|
79887
|
+
and104(
|
|
79888
|
+
eq123(trafficSources.projectId, ctx.project.id),
|
|
79814
79889
|
ne18(trafficSources.status, TrafficSourceStatuses.archived)
|
|
79815
79890
|
)
|
|
79816
79891
|
).all();
|
|
@@ -79973,27 +80048,27 @@ var recentDataCheck = {
|
|
|
79973
80048
|
const failCutoff = new Date(now.getTime() - RECENT_DATA_FAIL_DAYS * 24 * 60 * 6e4).toISOString();
|
|
79974
80049
|
const recentCrawlers = Number(
|
|
79975
80050
|
ctx.db.select({ total: sql51`COALESCE(SUM(${crawlerEventsHourly.hits}), 0)` }).from(crawlerEventsHourly).where(
|
|
79976
|
-
|
|
79977
|
-
|
|
79978
|
-
|
|
80051
|
+
and104(
|
|
80052
|
+
eq123(crawlerEventsHourly.projectId, ctx.project.id),
|
|
80053
|
+
inArray56(crawlerEventsHourly.sourceId, activeSourceIds),
|
|
79979
80054
|
gte32(crawlerEventsHourly.tsHour, warnCutoff)
|
|
79980
80055
|
)
|
|
79981
80056
|
).get()?.total ?? 0
|
|
79982
80057
|
);
|
|
79983
80058
|
const recentReferrals = Number(
|
|
79984
80059
|
ctx.db.select({ total: sql51`COALESCE(SUM(${aiReferralEventsHourly.sessionsOrHits}), 0)` }).from(aiReferralEventsHourly).where(
|
|
79985
|
-
|
|
79986
|
-
|
|
79987
|
-
|
|
80060
|
+
and104(
|
|
80061
|
+
eq123(aiReferralEventsHourly.projectId, ctx.project.id),
|
|
80062
|
+
inArray56(aiReferralEventsHourly.sourceId, activeSourceIds),
|
|
79988
80063
|
gte32(aiReferralEventsHourly.tsHour, warnCutoff)
|
|
79989
80064
|
)
|
|
79990
80065
|
).get()?.total ?? 0
|
|
79991
80066
|
);
|
|
79992
80067
|
const recentUserFetches = Number(
|
|
79993
80068
|
ctx.db.select({ total: sql51`COALESCE(SUM(${aiUserFetchEventsHourly.hits}), 0)` }).from(aiUserFetchEventsHourly).where(
|
|
79994
|
-
|
|
79995
|
-
|
|
79996
|
-
|
|
80069
|
+
and104(
|
|
80070
|
+
eq123(aiUserFetchEventsHourly.projectId, ctx.project.id),
|
|
80071
|
+
inArray56(aiUserFetchEventsHourly.sourceId, activeSourceIds),
|
|
79997
80072
|
gte32(aiUserFetchEventsHourly.tsHour, warnCutoff)
|
|
79998
80073
|
)
|
|
79999
80074
|
).get()?.total ?? 0
|
|
@@ -80017,27 +80092,27 @@ var recentDataCheck = {
|
|
|
80017
80092
|
}
|
|
80018
80093
|
const olderCrawlers = Number(
|
|
80019
80094
|
ctx.db.select({ total: sql51`COALESCE(SUM(${crawlerEventsHourly.hits}), 0)` }).from(crawlerEventsHourly).where(
|
|
80020
|
-
|
|
80021
|
-
|
|
80022
|
-
|
|
80095
|
+
and104(
|
|
80096
|
+
eq123(crawlerEventsHourly.projectId, ctx.project.id),
|
|
80097
|
+
inArray56(crawlerEventsHourly.sourceId, activeSourceIds),
|
|
80023
80098
|
gte32(crawlerEventsHourly.tsHour, failCutoff)
|
|
80024
80099
|
)
|
|
80025
80100
|
).get()?.total ?? 0
|
|
80026
80101
|
);
|
|
80027
80102
|
const olderReferrals = Number(
|
|
80028
80103
|
ctx.db.select({ total: sql51`COALESCE(SUM(${aiReferralEventsHourly.sessionsOrHits}), 0)` }).from(aiReferralEventsHourly).where(
|
|
80029
|
-
|
|
80030
|
-
|
|
80031
|
-
|
|
80104
|
+
and104(
|
|
80105
|
+
eq123(aiReferralEventsHourly.projectId, ctx.project.id),
|
|
80106
|
+
inArray56(aiReferralEventsHourly.sourceId, activeSourceIds),
|
|
80032
80107
|
gte32(aiReferralEventsHourly.tsHour, failCutoff)
|
|
80033
80108
|
)
|
|
80034
80109
|
).get()?.total ?? 0
|
|
80035
80110
|
);
|
|
80036
80111
|
const olderUserFetches = Number(
|
|
80037
80112
|
ctx.db.select({ total: sql51`COALESCE(SUM(${aiUserFetchEventsHourly.hits}), 0)` }).from(aiUserFetchEventsHourly).where(
|
|
80038
|
-
|
|
80039
|
-
|
|
80040
|
-
|
|
80113
|
+
and104(
|
|
80114
|
+
eq123(aiUserFetchEventsHourly.projectId, ctx.project.id),
|
|
80115
|
+
inArray56(aiUserFetchEventsHourly.sourceId, activeSourceIds),
|
|
80041
80116
|
gte32(aiUserFetchEventsHourly.tsHour, failCutoff)
|
|
80042
80117
|
)
|
|
80043
80118
|
).get()?.total ?? 0
|
|
@@ -80363,10 +80438,10 @@ var syncLagCheck = {
|
|
|
80363
80438
|
}
|
|
80364
80439
|
};
|
|
80365
80440
|
function lastQueueStopReason(ctx, sourceId) {
|
|
80366
|
-
const row = ctx.db.select({ syncSummary: runs.syncSummary }).from(runs).where(
|
|
80367
|
-
|
|
80368
|
-
|
|
80369
|
-
|
|
80441
|
+
const row = ctx.db.select({ syncSummary: runs.syncSummary }).from(runs).where(and104(
|
|
80442
|
+
eq123(runs.projectId, ctx.project.id),
|
|
80443
|
+
eq123(runs.kind, RunKinds["traffic-sync"]),
|
|
80444
|
+
eq123(runs.sourceId, sourceId),
|
|
80370
80445
|
isNotNull11(runs.syncSummary)
|
|
80371
80446
|
)).orderBy(desc55(runs.createdAt)).limit(1).get();
|
|
80372
80447
|
return row?.syncSummary?.type === "cloudflare-queue" ? row.syncSummary.stopReason : null;
|
|
@@ -81166,7 +81241,7 @@ async function doctorRoutes(app, opts) {
|
|
|
81166
81241
|
}
|
|
81167
81242
|
|
|
81168
81243
|
// ../api-routes/src/status.ts
|
|
81169
|
-
import { and as
|
|
81244
|
+
import { and as and105, desc as desc56, eq as eq124, isNull as isNull19 } from "drizzle-orm";
|
|
81170
81245
|
function ageDays(iso2) {
|
|
81171
81246
|
if (!iso2) return null;
|
|
81172
81247
|
const ms = Date.now() - Date.parse(iso2);
|
|
@@ -81216,7 +81291,7 @@ function makeRow(integration, label, runKind, state, staleAfterDays, dataThrough
|
|
|
81216
81291
|
};
|
|
81217
81292
|
}
|
|
81218
81293
|
function latestDate2(db, table, projectId) {
|
|
81219
|
-
const row = db.select({ date: table.date }).from(table).where(
|
|
81294
|
+
const row = db.select({ date: table.date }).from(table).where(eq124(table.projectId, projectId)).orderBy(desc56(table.date)).limit(1).get();
|
|
81220
81295
|
return row?.date ?? null;
|
|
81221
81296
|
}
|
|
81222
81297
|
function projectRows(opts, project) {
|
|
@@ -81231,7 +81306,7 @@ function projectRows(opts, project) {
|
|
|
81231
81306
|
const rows = [];
|
|
81232
81307
|
const gsc = gscConnection(ctx, info);
|
|
81233
81308
|
if (connected(gsc)) {
|
|
81234
|
-
const watermarkRow = opts.db.select({ dataThroughDate: gscDataWatermarks.dataThroughDate }).from(gscDataWatermarks).where(
|
|
81309
|
+
const watermarkRow = opts.db.select({ dataThroughDate: gscDataWatermarks.dataThroughDate }).from(gscDataWatermarks).where(eq124(gscDataWatermarks.projectId, project.id)).limit(1).get();
|
|
81235
81310
|
const state = readSyncRunState(opts.db, project.id, RunKinds["gsc-sync"], { since: gsc.since });
|
|
81236
81311
|
const dataThrough = watermarkRow?.dataThroughDate ?? latestDate2(opts.db, gscDailyTotals, project.id);
|
|
81237
81312
|
rows.push(makeRow("gsc", "Search Console", RunKinds["gsc-sync"], state, SYNC_IDLE_DAYS, dataThrough, null, ["gsc.sync.recent-failures"], GSC_DATA_AGING_DAYS));
|
|
@@ -81247,12 +81322,12 @@ function projectRows(opts, project) {
|
|
|
81247
81322
|
rows.push(makeRow("bing", "Bing Webmaster Tools", RunKinds["bing-inspect-sitemap"], readSyncRunState(opts.db, project.id, RunKinds["bing-inspect-sitemap"]), null));
|
|
81248
81323
|
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));
|
|
81249
81324
|
}
|
|
81250
|
-
const ads = opts.db.select({ id: adsConnections.id, lastSyncedAt: adsConnections.lastSyncedAt }).from(adsConnections).where(
|
|
81325
|
+
const ads = opts.db.select({ id: adsConnections.id, lastSyncedAt: adsConnections.lastSyncedAt }).from(adsConnections).where(eq124(adsConnections.projectId, project.id)).limit(1).get();
|
|
81251
81326
|
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));
|
|
81252
81327
|
const marketing = opts.getGoogleMarketingDoctorInput?.(ctx);
|
|
81253
81328
|
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));
|
|
81254
81329
|
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));
|
|
81255
|
-
const sources = opts.db.select().from(trafficSources).where(
|
|
81330
|
+
const sources = opts.db.select().from(trafficSources).where(and105(eq124(trafficSources.projectId, project.id), isNull19(trafficSources.archivedAt))).all();
|
|
81256
81331
|
for (const source of sources) {
|
|
81257
81332
|
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"]);
|
|
81258
81333
|
const lag = source.lastSyncedAt ? Date.now() - Date.parse(source.lastSyncedAt) : Number.POSITIVE_INFINITY;
|
|
@@ -81264,7 +81339,7 @@ function projectRows(opts, project) {
|
|
|
81264
81339
|
}
|
|
81265
81340
|
function projectStatus(opts, project) {
|
|
81266
81341
|
const integrations = projectRows(opts, project);
|
|
81267
|
-
const healthRow = opts.db.select().from(doctorHealthState).where(
|
|
81342
|
+
const healthRow = opts.db.select().from(doctorHealthState).where(eq124(doctorHealthState.projectId, project.id)).limit(1).get();
|
|
81268
81343
|
const health = healthRow ? { status: healthRow.status, code: healthRow.code, summary: healthRow.summary, checkedAt: healthRow.checkedAt, notifiedAt: healthRow.notifiedAt } : null;
|
|
81269
81344
|
const rank = { ok: 0, "never-synced": 1, warning: 2, stale: 3, failing: 4 };
|
|
81270
81345
|
const healthState = health?.status === "fail" ? "failing" : health?.status === "warn" ? "warning" : "ok";
|
|
@@ -81284,7 +81359,7 @@ async function statusRoutes(app, opts) {
|
|
|
81284
81359
|
if (request.query.problems === "true") result.projects = result.projects.map((item2) => ({ ...item2, integrations: item2.integrations.filter((row) => row.state !== "ok") }));
|
|
81285
81360
|
return instanceStatusDtoSchema.parse(result);
|
|
81286
81361
|
}
|
|
81287
|
-
const projectsRows = (scopedId ? opts.db.select().from(projects).where(
|
|
81362
|
+
const projectsRows = (scopedId ? opts.db.select().from(projects).where(eq124(projects.id, scopedId)) : opts.db.select().from(projects)).all();
|
|
81288
81363
|
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)) };
|
|
81289
81364
|
for (const project of output.projects) {
|
|
81290
81365
|
const key = project.state === "never-synced" ? "neverSynced" : project.state;
|
|
@@ -81297,7 +81372,7 @@ async function statusRoutes(app, opts) {
|
|
|
81297
81372
|
|
|
81298
81373
|
// ../api-routes/src/discovery/routes.ts
|
|
81299
81374
|
import crypto64 from "crypto";
|
|
81300
|
-
import { and as
|
|
81375
|
+
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";
|
|
81301
81376
|
var MAX_INFLIGHT_DISCOVERY_AGE_MS = 2 * 60 * 60 * 1e3;
|
|
81302
81377
|
async function discoveryRoutes(app, opts) {
|
|
81303
81378
|
app.post("/projects/:name/discover/run", async (request, reply) => {
|
|
@@ -81331,13 +81406,13 @@ async function discoveryRoutes(app, opts) {
|
|
|
81331
81406
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
81332
81407
|
const ageFloorIso = new Date(Date.now() - MAX_INFLIGHT_DISCOVERY_AGE_MS).toISOString();
|
|
81333
81408
|
const decision = app.db.transaction((tx) => {
|
|
81334
|
-
const existing = tx.select({ id: discoverySessions.id, runId: discoverySessions.runId }).from(discoverySessions).where(
|
|
81335
|
-
|
|
81336
|
-
|
|
81409
|
+
const existing = tx.select({ id: discoverySessions.id, runId: discoverySessions.runId }).from(discoverySessions).where(and106(
|
|
81410
|
+
eq125(discoverySessions.projectId, project.id),
|
|
81411
|
+
eq125(discoverySessions.icpDescription, icpDescription),
|
|
81337
81412
|
// Buyer is part of session identity: it changes the seed prompt's
|
|
81338
81413
|
// semantics, so a request with a different (or no) buyer must start
|
|
81339
81414
|
// its own session, never adopt another buyer's probes.
|
|
81340
|
-
parsed.data.buyerDescription == null ? isNull20(discoverySessions.buyerDescription) :
|
|
81415
|
+
parsed.data.buyerDescription == null ? isNull20(discoverySessions.buyerDescription) : eq125(discoverySessions.buyerDescription, parsed.data.buyerDescription),
|
|
81341
81416
|
// Locations are identity too: a different service-area subset seeds
|
|
81342
81417
|
// and probes a different geo, so it must never reuse another geo's
|
|
81343
81418
|
// session. resolveLocations is deterministic (project-config order),
|
|
@@ -81347,12 +81422,12 @@ async function discoveryRoutes(app, opts) {
|
|
|
81347
81422
|
// locations a NULL row's subset is unknowable, so it conservatively
|
|
81348
81423
|
// never reuses — a one-time, bounded (2h window) non-reuse after
|
|
81349
81424
|
// upgrade, never a wrong reuse.
|
|
81350
|
-
locations.length === 0 ? or22(isNull20(discoverySessions.locations),
|
|
81425
|
+
locations.length === 0 ? or22(isNull20(discoverySessions.locations), eq125(discoverySessions.locations, locations)) : eq125(discoverySessions.locations, locations),
|
|
81351
81426
|
// Seed provider set is identity: a different phrasing distribution
|
|
81352
81427
|
// must never reuse another set's session. Null (= Gemini-only
|
|
81353
81428
|
// default, including explicit ['gemini']) matches legacy rows.
|
|
81354
|
-
seedProviders == null ? isNull20(discoverySessions.seedProviders) :
|
|
81355
|
-
|
|
81429
|
+
seedProviders == null ? isNull20(discoverySessions.seedProviders) : eq125(discoverySessions.seedProviders, seedProviders),
|
|
81430
|
+
inArray57(discoverySessions.status, [
|
|
81356
81431
|
DiscoverySessionStatuses.queued,
|
|
81357
81432
|
DiscoverySessionStatuses.seeding,
|
|
81358
81433
|
DiscoverySessionStatuses.probing
|
|
@@ -81427,7 +81502,7 @@ async function discoveryRoutes(app, opts) {
|
|
|
81427
81502
|
const project = resolveProject(app.db, request.params.name);
|
|
81428
81503
|
const parsedLimit = parseInt(request.query.limit ?? "", 10);
|
|
81429
81504
|
const limit = Number.isNaN(parsedLimit) || parsedLimit <= 0 ? 50 : parsedLimit;
|
|
81430
|
-
const rows = app.db.select().from(discoverySessions).where(
|
|
81505
|
+
const rows = app.db.select().from(discoverySessions).where(eq125(discoverySessions.projectId, project.id)).orderBy(desc57(discoverySessions.createdAt)).limit(limit).all();
|
|
81431
81506
|
return reply.send(rows.map(serializeSession));
|
|
81432
81507
|
}
|
|
81433
81508
|
);
|
|
@@ -81435,11 +81510,11 @@ async function discoveryRoutes(app, opts) {
|
|
|
81435
81510
|
"/projects/:name/discover/sessions/:id",
|
|
81436
81511
|
async (request, reply) => {
|
|
81437
81512
|
const project = resolveProject(app.db, request.params.name);
|
|
81438
|
-
const session = app.db.select().from(discoverySessions).where(
|
|
81513
|
+
const session = app.db.select().from(discoverySessions).where(eq125(discoverySessions.id, request.params.id)).get();
|
|
81439
81514
|
if (!session || session.projectId !== project.id) {
|
|
81440
81515
|
throw notFound("Discovery session", request.params.id);
|
|
81441
81516
|
}
|
|
81442
|
-
const probeRows = app.db.select().from(discoveryProbes).where(
|
|
81517
|
+
const probeRows = app.db.select().from(discoveryProbes).where(eq125(discoveryProbes.sessionId, session.id)).all();
|
|
81443
81518
|
const detail = {
|
|
81444
81519
|
...serializeSession(session),
|
|
81445
81520
|
probes: probeRows.map(serializeProbe)
|
|
@@ -81453,7 +81528,7 @@ async function discoveryRoutes(app, opts) {
|
|
|
81453
81528
|
requireAdminSession(request);
|
|
81454
81529
|
requirePaidReadScope(request, [], "Discovery harvest requires wildcard (*) API key scope because it can call the embedding provider.");
|
|
81455
81530
|
const project = resolveProject(app.db, request.params.name);
|
|
81456
|
-
const session = app.db.select().from(discoverySessions).where(
|
|
81531
|
+
const session = app.db.select().from(discoverySessions).where(eq125(discoverySessions.id, request.params.id)).get();
|
|
81457
81532
|
if (!session || session.projectId !== project.id) {
|
|
81458
81533
|
throw notFound("Discovery session", request.params.id);
|
|
81459
81534
|
}
|
|
@@ -81461,7 +81536,7 @@ async function discoveryRoutes(app, opts) {
|
|
|
81461
81536
|
const minProbeHits = Number.isNaN(parsedFloor) || parsedFloor < 1 ? 1 : parsedFloor;
|
|
81462
81537
|
const applyAnchor = request.query.anchor !== "false";
|
|
81463
81538
|
const provider = session.seedProvider ?? "gemini";
|
|
81464
|
-
const probeRows = app.db.select().from(discoveryProbes).where(
|
|
81539
|
+
const probeRows = app.db.select().from(discoveryProbes).where(eq125(discoveryProbes.sessionId, session.id)).all();
|
|
81465
81540
|
const extract = opts.harvestSearchQueries;
|
|
81466
81541
|
const probesWithQueries = probeRows.map((row) => {
|
|
81467
81542
|
if (!extract || !row.rawResponse) return { searchQueries: [] };
|
|
@@ -81472,7 +81547,7 @@ async function discoveryRoutes(app, opts) {
|
|
|
81472
81547
|
return { searchQueries: [] };
|
|
81473
81548
|
}
|
|
81474
81549
|
});
|
|
81475
|
-
const trackedQueries = app.db.select({ query: queries.query }).from(queries).where(
|
|
81550
|
+
const trackedQueries = app.db.select({ query: queries.query }).from(queries).where(eq125(queries.projectId, project.id)).all().map((r) => r.query);
|
|
81476
81551
|
const anchorTerms = buildHarvestAnchorTerms(
|
|
81477
81552
|
[session.icpDescription ?? "", ...trackedQueries],
|
|
81478
81553
|
effectiveDomains(project)
|
|
@@ -81519,11 +81594,11 @@ async function discoveryRoutes(app, opts) {
|
|
|
81519
81594
|
"/projects/:name/discover/sessions/:id/promote",
|
|
81520
81595
|
async (request, reply) => {
|
|
81521
81596
|
const project = resolveProject(app.db, request.params.name);
|
|
81522
|
-
const session = app.db.select().from(discoverySessions).where(
|
|
81597
|
+
const session = app.db.select().from(discoverySessions).where(eq125(discoverySessions.id, request.params.id)).get();
|
|
81523
81598
|
if (!session || session.projectId !== project.id) {
|
|
81524
81599
|
throw notFound("Discovery session", request.params.id);
|
|
81525
81600
|
}
|
|
81526
|
-
const probeRows = app.db.select().from(discoveryProbes).where(
|
|
81601
|
+
const probeRows = app.db.select().from(discoveryProbes).where(eq125(discoveryProbes.sessionId, session.id)).all();
|
|
81527
81602
|
const cited = /* @__PURE__ */ new Set();
|
|
81528
81603
|
const aspirational = /* @__PURE__ */ new Set();
|
|
81529
81604
|
const wasted = /* @__PURE__ */ new Set();
|
|
@@ -81558,7 +81633,7 @@ async function discoveryRoutes(app, opts) {
|
|
|
81558
81633
|
);
|
|
81559
81634
|
app.post("/projects/:name/discover/sessions/:id/promote", async (request, reply) => {
|
|
81560
81635
|
const project = resolveProject(app.db, request.params.name);
|
|
81561
|
-
const session = app.db.select().from(discoverySessions).where(
|
|
81636
|
+
const session = app.db.select().from(discoverySessions).where(eq125(discoverySessions.id, request.params.id)).get();
|
|
81562
81637
|
if (!session || session.projectId !== project.id) {
|
|
81563
81638
|
throw notFound("Discovery session", request.params.id);
|
|
81564
81639
|
}
|
|
@@ -81581,7 +81656,7 @@ async function discoveryRoutes(app, opts) {
|
|
|
81581
81656
|
const bucketSet = new Set(buckets);
|
|
81582
81657
|
const includeCompetitors = parsed.data.includeCompetitors ?? true;
|
|
81583
81658
|
const competitorTypes = parsed.data.competitorTypes ?? DEFAULT_DISCOVERY_PROMOTE_COMPETITOR_TYPES;
|
|
81584
|
-
const probeRows = app.db.select().from(discoveryProbes).where(
|
|
81659
|
+
const probeRows = app.db.select().from(discoveryProbes).where(eq125(discoveryProbes.sessionId, session.id)).all();
|
|
81585
81660
|
const candidateQueries = /* @__PURE__ */ new Set();
|
|
81586
81661
|
for (const probe of probeRows) {
|
|
81587
81662
|
if (!probe.bucket) continue;
|
|
@@ -81589,7 +81664,7 @@ async function discoveryRoutes(app, opts) {
|
|
|
81589
81664
|
if (bucket.success && bucketSet.has(bucket.data)) candidateQueries.add(probe.query);
|
|
81590
81665
|
}
|
|
81591
81666
|
const existingQueries = new Set(
|
|
81592
|
-
app.db.select({ query: queries.query }).from(queries).where(
|
|
81667
|
+
app.db.select({ query: queries.query }).from(queries).where(eq125(queries.projectId, project.id)).all().map((r) => r.query.toLowerCase())
|
|
81593
81668
|
);
|
|
81594
81669
|
const promotedQueries = [];
|
|
81595
81670
|
const skippedQueries = [];
|
|
@@ -81803,7 +81878,7 @@ function planCompetitorPromotion(input) {
|
|
|
81803
81878
|
|
|
81804
81879
|
// ../api-routes/src/discovery/orchestrate.ts
|
|
81805
81880
|
import crypto65 from "crypto";
|
|
81806
|
-
import { eq as
|
|
81881
|
+
import { eq as eq126 } from "drizzle-orm";
|
|
81807
81882
|
var DEFAULT_MAX_PROBES = 100;
|
|
81808
81883
|
var ABSOLUTE_MAX_PROBES = 500;
|
|
81809
81884
|
function classifyProbeBucket(input) {
|
|
@@ -81889,7 +81964,7 @@ async function executeDiscovery(opts) {
|
|
|
81889
81964
|
status: DiscoverySessionStatuses.seeding,
|
|
81890
81965
|
dedupThreshold,
|
|
81891
81966
|
startedAt
|
|
81892
|
-
}).where(
|
|
81967
|
+
}).where(eq126(discoverySessions.id, opts.sessionId)).run();
|
|
81893
81968
|
const seedResult = await opts.deps.seed({
|
|
81894
81969
|
project: opts.project,
|
|
81895
81970
|
icpDescription: opts.icpDescription,
|
|
@@ -81950,7 +82025,7 @@ async function executeDiscovery(opts) {
|
|
|
81950
82025
|
dedupBandPairFraction: dedupStats.bandPairFraction,
|
|
81951
82026
|
dedupPairsTotal: dedupStats.pairsTotal,
|
|
81952
82027
|
warning
|
|
81953
|
-
}).where(
|
|
82028
|
+
}).where(eq126(discoverySessions.id, opts.sessionId)).run();
|
|
81954
82029
|
const probeLocation = opts.locations?.[0];
|
|
81955
82030
|
const probeResults = await mapWithConcurrency(
|
|
81956
82031
|
probedCanonicals,
|
|
@@ -82004,7 +82079,7 @@ async function executeDiscovery(opts) {
|
|
|
82004
82079
|
wastedCount: buckets["wasted-surface"],
|
|
82005
82080
|
competitorMap,
|
|
82006
82081
|
finishedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
82007
|
-
}).where(
|
|
82082
|
+
}).where(eq126(discoverySessions.id, opts.sessionId)).run();
|
|
82008
82083
|
upsertDomainClassifications(opts.db, opts.project.id, opts.sessionId, competitorMap);
|
|
82009
82084
|
return {
|
|
82010
82085
|
buckets,
|
|
@@ -82044,7 +82119,7 @@ function markSessionFailed(db, sessionId, error) {
|
|
|
82044
82119
|
status: DiscoverySessionStatuses.failed,
|
|
82045
82120
|
error,
|
|
82046
82121
|
finishedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
82047
|
-
}).where(
|
|
82122
|
+
}).where(eq126(discoverySessions.id, sessionId)).run();
|
|
82048
82123
|
}
|
|
82049
82124
|
function dedupeStrings(input) {
|
|
82050
82125
|
const seen2 = /* @__PURE__ */ new Set();
|
|
@@ -82061,7 +82136,7 @@ function dedupeStrings(input) {
|
|
|
82061
82136
|
}
|
|
82062
82137
|
|
|
82063
82138
|
// ../api-routes/src/trends.ts
|
|
82064
|
-
import { and as
|
|
82139
|
+
import { and as and107, asc as asc30, eq as eq127 } from "drizzle-orm";
|
|
82065
82140
|
function parseSurface(value) {
|
|
82066
82141
|
const parsed = trendSurfaceSchema.safeParse(value);
|
|
82067
82142
|
if (!parsed.success) {
|
|
@@ -82117,8 +82192,8 @@ async function trendsRoutes(app) {
|
|
|
82117
82192
|
function readSurface(app, projectId, surface) {
|
|
82118
82193
|
switch (surface) {
|
|
82119
82194
|
case TrendSurfaces["index-coverage"]: {
|
|
82120
|
-
const google = app.db.select({ date: gscCoverageSnapshots.date, indexed: gscCoverageSnapshots.indexed, notIndexed: gscCoverageSnapshots.notIndexed }).from(gscCoverageSnapshots).where(
|
|
82121
|
-
const bing = app.db.select({ date: bingCoverageSnapshots.date, indexed: bingCoverageSnapshots.indexed, notIndexed: bingCoverageSnapshots.notIndexed }).from(bingCoverageSnapshots).where(
|
|
82195
|
+
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();
|
|
82196
|
+
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();
|
|
82122
82197
|
const coverage = (key, label, rows) => ({
|
|
82123
82198
|
key,
|
|
82124
82199
|
label,
|
|
@@ -82130,7 +82205,7 @@ function readSurface(app, projectId, surface) {
|
|
|
82130
82205
|
return [coverage("google", "Google", google), coverage("bing", "Bing", bing)];
|
|
82131
82206
|
}
|
|
82132
82207
|
case TrendSurfaces["site-health"]: {
|
|
82133
|
-
const rows = app.db.select({ auditedAt: siteAuditSnapshots.auditedAt, aggregateScore: siteAuditSnapshots.aggregateScore, pagesAudited: siteAuditSnapshots.pagesAudited }).from(siteAuditSnapshots).innerJoin(runs,
|
|
82208
|
+
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();
|
|
82134
82209
|
return [{
|
|
82135
82210
|
key: "site-health",
|
|
82136
82211
|
label: "Agent Readiness",
|
|
@@ -82142,7 +82217,7 @@ function readSurface(app, projectId, surface) {
|
|
|
82142
82217
|
}
|
|
82143
82218
|
case TrendSurfaces.backlinks: {
|
|
82144
82219
|
const totals = computeFilteredReleaseTotals(app.db, projectId, BacklinkSources.commoncrawl);
|
|
82145
|
-
const rows = app.db.select({ release: backlinkSummaries.release, totalLinkingDomains: backlinkSummaries.totalLinkingDomains, queriedAt: backlinkSummaries.queriedAt }).from(backlinkSummaries).where(
|
|
82220
|
+
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) => {
|
|
82146
82221
|
const filtered = totals.get(row.release);
|
|
82147
82222
|
const known = (filtered?.domainRows ?? 0) > 0 || row.totalLinkingDomains === 0;
|
|
82148
82223
|
const windowEnd = releaseWindowEndMonth(row.release);
|
|
@@ -82172,7 +82247,7 @@ function readSurface(app, projectId, surface) {
|
|
|
82172
82247
|
// ../api-routes/src/research.ts
|
|
82173
82248
|
import crypto66 from "crypto";
|
|
82174
82249
|
import { z as z7 } from "zod";
|
|
82175
|
-
import { and as
|
|
82250
|
+
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";
|
|
82176
82251
|
var sameLocation = (a, b) => a.label === b.label && a.city === b.city && a.region === b.region && a.country === b.country && a.timezone === b.timezone;
|
|
82177
82252
|
var BATCH_RECEIPT_PREFIX = "__canonry_research_batch__:";
|
|
82178
82253
|
async function researchRoutes(app, opts) {
|
|
@@ -82191,7 +82266,7 @@ async function researchRoutes(app, opts) {
|
|
|
82191
82266
|
const input = parsed.data;
|
|
82192
82267
|
if (input.idempotencyKey?.startsWith(BATCH_RECEIPT_PREFIX)) throw validationError("This idempotency key prefix is reserved for internal research batch receipts.");
|
|
82193
82268
|
const requestHash2 = directResearchRequestHash(input);
|
|
82194
|
-
const existingReceipt = input.idempotencyKey ? app.db.select().from(researchRuns).where(
|
|
82269
|
+
const existingReceipt = input.idempotencyKey ? app.db.select().from(researchRuns).where(and108(eq128(researchRuns.projectId, project.id), eq128(researchRuns.idempotencyKey, input.idempotencyKey))).get() : void 0;
|
|
82195
82270
|
if (existingReceipt) {
|
|
82196
82271
|
assertSameDirectResearchRequest(existingReceipt, input, requestHash2);
|
|
82197
82272
|
const result2 = getDetail(app, project.id, existingReceipt.id);
|
|
@@ -82226,7 +82301,7 @@ async function researchRoutes(app, opts) {
|
|
|
82226
82301
|
const initiatedBy = researchPrincipal(request);
|
|
82227
82302
|
const decision = app.db.transaction((tx) => {
|
|
82228
82303
|
if (input.idempotencyKey) {
|
|
82229
|
-
const existing = tx.select().from(researchRuns).where(
|
|
82304
|
+
const existing = tx.select().from(researchRuns).where(and108(eq128(researchRuns.projectId, project.id), eq128(researchRuns.idempotencyKey, input.idempotencyKey))).get();
|
|
82230
82305
|
if (existing) {
|
|
82231
82306
|
assertSameDirectResearchRequest(existing, input, requestHash2);
|
|
82232
82307
|
return { reused: true, id: existing.id, shouldDispatch: existing.status === ResearchRunStatuses.queued };
|
|
@@ -82234,8 +82309,8 @@ async function researchRoutes(app, opts) {
|
|
|
82234
82309
|
}
|
|
82235
82310
|
if (initiatedBy?.limited) {
|
|
82236
82311
|
const { start, end, date } = utcDayBounds(now);
|
|
82237
|
-
const used = tx.select({ value: count10() }).from(researchRuns).where(
|
|
82238
|
-
|
|
82312
|
+
const used = tx.select({ value: count10() }).from(researchRuns).where(and108(
|
|
82313
|
+
eq128(researchRuns.projectId, project.id),
|
|
82239
82314
|
gte34(researchRuns.createdAt, start),
|
|
82240
82315
|
lt21(researchRuns.createdAt, end),
|
|
82241
82316
|
sql52`(json_extract(${researchRuns.initiatedBy}, '$.role') = ${UserRoles.viewer} OR json_extract(${researchRuns.initiatedBy}, '$.limited') = 1)`
|
|
@@ -82266,15 +82341,15 @@ async function researchRoutes(app, opts) {
|
|
|
82266
82341
|
if (input.idempotencyKey.startsWith(BATCH_RECEIPT_PREFIX)) throw validationError("This idempotency key prefix is reserved for internal research batch receipts.");
|
|
82267
82342
|
const requestHash2 = researchBatchRequestHash(input);
|
|
82268
82343
|
const receiptKeys = input.runs.map((_run, index) => batchChildReceiptKey(input.idempotencyKey, index));
|
|
82269
|
-
const firstReceipt = app.db.select().from(researchRuns).where(
|
|
82270
|
-
|
|
82271
|
-
|
|
82344
|
+
const firstReceipt = app.db.select().from(researchRuns).where(and108(
|
|
82345
|
+
eq128(researchRuns.projectId, project.id),
|
|
82346
|
+
eq128(researchRuns.idempotencyKey, receiptKeys[0])
|
|
82272
82347
|
)).get();
|
|
82273
82348
|
if (firstReceipt) {
|
|
82274
82349
|
if (firstReceipt.requestHash !== requestHash2) throw alreadyExists("Research batch idempotency key", input.idempotencyKey);
|
|
82275
|
-
const saved = receiptKeys.map((key) => app.db.select().from(researchRuns).where(
|
|
82276
|
-
|
|
82277
|
-
|
|
82350
|
+
const saved = receiptKeys.map((key) => app.db.select().from(researchRuns).where(and108(
|
|
82351
|
+
eq128(researchRuns.projectId, project.id),
|
|
82352
|
+
eq128(researchRuns.idempotencyKey, key)
|
|
82278
82353
|
)).get());
|
|
82279
82354
|
if (saved.some((row) => !row || row.requestHash !== requestHash2)) throw alreadyExists("Research batch idempotency key", input.idempotencyKey);
|
|
82280
82355
|
const runs3 = saved.map((row) => getDetail(app, project.id, row.id));
|
|
@@ -82290,8 +82365,8 @@ async function researchRoutes(app, opts) {
|
|
|
82290
82365
|
const decision = app.db.transaction((tx) => {
|
|
82291
82366
|
if (initiatedBy?.limited) {
|
|
82292
82367
|
const { start, end, date } = utcDayBounds(now);
|
|
82293
|
-
const used = tx.select({ value: count10() }).from(researchRuns).where(
|
|
82294
|
-
|
|
82368
|
+
const used = tx.select({ value: count10() }).from(researchRuns).where(and108(
|
|
82369
|
+
eq128(researchRuns.projectId, project.id),
|
|
82295
82370
|
gte34(researchRuns.createdAt, start),
|
|
82296
82371
|
lt21(researchRuns.createdAt, end),
|
|
82297
82372
|
sql52`(json_extract(${researchRuns.initiatedBy}, '$.role') = ${UserRoles.viewer} OR json_extract(${researchRuns.initiatedBy}, '$.limited') = 1)`
|
|
@@ -82345,9 +82420,9 @@ async function researchRoutes(app, opts) {
|
|
|
82345
82420
|
const requested = Number.parseInt(request.query.limit ?? "", 10);
|
|
82346
82421
|
const limit = Number.isInteger(requested) && requested > 0 ? Math.min(requested, 100) : 20;
|
|
82347
82422
|
const cursor = request.query.cursor ? parseResearchCursor(request.query.cursor, project.id) : null;
|
|
82348
|
-
const rows = app.db.select().from(researchRuns).where(
|
|
82349
|
-
|
|
82350
|
-
cursor ? or23(lt21(researchRuns.createdAt, cursor.createdAt),
|
|
82423
|
+
const rows = app.db.select().from(researchRuns).where(and108(
|
|
82424
|
+
eq128(researchRuns.projectId, project.id),
|
|
82425
|
+
cursor ? or23(lt21(researchRuns.createdAt, cursor.createdAt), and108(eq128(researchRuns.createdAt, cursor.createdAt), lt21(researchRuns.id, cursor.id))) : void 0
|
|
82351
82426
|
)).orderBy(desc58(researchRuns.createdAt), desc58(researchRuns.id)).limit(limit + 1).all();
|
|
82352
82427
|
const runs2 = rows.slice(0, limit).map(serializeRun);
|
|
82353
82428
|
const last = runs2.at(-1);
|
|
@@ -82497,9 +82572,9 @@ function resolveStoredResearchTemplate(stored, selection, idempotencyKey) {
|
|
|
82497
82572
|
return stored;
|
|
82498
82573
|
}
|
|
82499
82574
|
function resolveResearchTemplate(app, projectId, selection, scope, location) {
|
|
82500
|
-
const savedTemplate = app.db.select().from(measurementQueryTemplates).where(
|
|
82501
|
-
|
|
82502
|
-
|
|
82575
|
+
const savedTemplate = app.db.select().from(measurementQueryTemplates).where(and108(
|
|
82576
|
+
eq128(measurementQueryTemplates.projectId, projectId),
|
|
82577
|
+
eq128(measurementQueryTemplates.id, selection.templateId)
|
|
82503
82578
|
)).get();
|
|
82504
82579
|
if (!savedTemplate) throw validationError("Unknown or stale research template. Reload the selected template and try again.");
|
|
82505
82580
|
const templateVersion = savedTemplate.updatedAt;
|
|
@@ -82508,7 +82583,7 @@ function resolveResearchTemplate(app, projectId, selection, scope, location) {
|
|
|
82508
82583
|
}
|
|
82509
82584
|
const bindingLocation = selection.bindingLocation === void 0 ? location : selection.bindingLocation;
|
|
82510
82585
|
if (bindingLocation) {
|
|
82511
|
-
const project = app.db.select({ locations: projects.locations }).from(projects).where(
|
|
82586
|
+
const project = app.db.select({ locations: projects.locations }).from(projects).where(eq128(projects.id, projectId)).get();
|
|
82512
82587
|
if (!project.locations.some((item2) => sameLocation(item2, bindingLocation))) throw validationError("Research template binding location must match a configured project location.");
|
|
82513
82588
|
}
|
|
82514
82589
|
const { bindings, output } = expandResearchTemplate(savedTemplate, scope, bindingLocation);
|
|
@@ -82521,9 +82596,9 @@ function classifyResearchQueries(project, plan, queries2) {
|
|
|
82521
82596
|
return queries2.map((query2) => classifier?.classify(query2) ?? null);
|
|
82522
82597
|
}
|
|
82523
82598
|
function getDetail(app, projectId, id) {
|
|
82524
|
-
const row = app.db.select().from(researchRuns).where(
|
|
82599
|
+
const row = app.db.select().from(researchRuns).where(and108(eq128(researchRuns.id, id), eq128(researchRuns.projectId, projectId))).get();
|
|
82525
82600
|
if (!row) throw notFound("Research run", id);
|
|
82526
|
-
const queries2 = app.db.select().from(researchRunQueries).where(
|
|
82601
|
+
const queries2 = app.db.select().from(researchRunQueries).where(eq128(researchRunQueries.researchRunId, id)).orderBy(researchRunQueries.position).all().map((query2) => serializeQuery(query2, row.provider));
|
|
82527
82602
|
return { ...serializeRun(row), queries: queries2 };
|
|
82528
82603
|
}
|
|
82529
82604
|
function serializeRun(row) {
|
|
@@ -82584,7 +82659,7 @@ function utcDayBounds(now) {
|
|
|
82584
82659
|
|
|
82585
82660
|
// ../api-routes/src/simple-measurement-definitions.ts
|
|
82586
82661
|
import crypto67 from "crypto";
|
|
82587
|
-
import { and as
|
|
82662
|
+
import { and as and109, eq as eq129 } from "drizzle-orm";
|
|
82588
82663
|
function captureSimpleMeasurementDefinition(db, input) {
|
|
82589
82664
|
return db.transaction((tx) => {
|
|
82590
82665
|
const run = tx.select({
|
|
@@ -82592,7 +82667,7 @@ function captureSimpleMeasurementDefinition(db, input) {
|
|
|
82592
82667
|
trigger: runs.trigger,
|
|
82593
82668
|
status: runs.status,
|
|
82594
82669
|
measurementPlanVersionId: runs.measurementPlanVersionId
|
|
82595
|
-
}).from(runs).where(
|
|
82670
|
+
}).from(runs).where(and109(eq129(runs.projectId, input.projectId), eq129(runs.id, input.runId))).get();
|
|
82596
82671
|
if (!run) throw notFound("Run", input.runId);
|
|
82597
82672
|
if (run.kind !== RunKinds["answer-visibility"] || run.trigger === RunTriggers.probe || run.measurementPlanVersionId !== null) {
|
|
82598
82673
|
return null;
|
|
@@ -82613,7 +82688,7 @@ function captureSimpleMeasurementDefinition(db, input) {
|
|
|
82613
82688
|
throw validationError("Qualified aliases must be a sorted subset of the captured aliases.");
|
|
82614
82689
|
}
|
|
82615
82690
|
}
|
|
82616
|
-
const existing = tx.select().from(simpleMeasurementDefinitions).where(
|
|
82691
|
+
const existing = tx.select().from(simpleMeasurementDefinitions).where(and109(eq129(simpleMeasurementDefinitions.projectId, input.projectId), eq129(simpleMeasurementDefinitions.runId, input.runId))).get();
|
|
82617
82692
|
if (existing) {
|
|
82618
82693
|
const frozen = simpleMeasurementDefinitionSchema.parse(existing.definition);
|
|
82619
82694
|
const { qualifiedAliases: _liveQualifiedAliases, ...liveIdentity } = definition2.identity;
|
|
@@ -82639,15 +82714,15 @@ function captureSimpleMeasurementDefinition(db, input) {
|
|
|
82639
82714
|
if (run.status !== RunStatuses.running) {
|
|
82640
82715
|
throw validationError("Only a running run can capture a new measurement definition.");
|
|
82641
82716
|
}
|
|
82642
|
-
if (tx.select({ id: querySnapshots.id }).from(querySnapshots).where(
|
|
82717
|
+
if (tx.select({ id: querySnapshots.id }).from(querySnapshots).where(eq129(querySnapshots.runId, input.runId)).limit(1).get()) {
|
|
82643
82718
|
throw validationError("This run already has stored answers. Its measurement definition cannot be inferred afterward.");
|
|
82644
82719
|
}
|
|
82645
|
-
const projectQueryIds = new Set(tx.select({ id: queries.id }).from(queries).where(
|
|
82720
|
+
const projectQueryIds = new Set(tx.select({ id: queries.id }).from(queries).where(eq129(queries.projectId, input.projectId)).all().map((query2) => query2.id));
|
|
82646
82721
|
if (definition2.queries.some((query2) => !projectQueryIds.has(query2.queryId))) {
|
|
82647
82722
|
throw validationError("Every captured query must belong to the run project.");
|
|
82648
82723
|
}
|
|
82649
82724
|
if (definition2.competitors !== void 0) {
|
|
82650
|
-
const liveCompetitorDomains = new Set(tx.select({ domain: competitors.domain }).from(competitors).where(
|
|
82725
|
+
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));
|
|
82651
82726
|
const capturedDomains = new Set(definition2.competitors.map((competitor) => competitor.domain));
|
|
82652
82727
|
if (liveCompetitorDomains.size !== capturedDomains.size || [...liveCompetitorDomains].some((domain) => !capturedDomains.has(domain))) {
|
|
82653
82728
|
throw validationError("Captured competitors must exactly match the project competitors dispatched for this run.");
|