Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

ralph(M11-004): DELETE packages/trpc and packages/queue; v1-compat.ts stays as the MCP seam

ralph51f15c0c66af
diff --git a/.dependency-cruiser.cjs b/.dependency-cruiser.cjs
index 781ac7cbf..a409ad10b 100644
--- a/.dependency-cruiser.cjs
+++ b/.dependency-cruiser.cjs
@@ -111,8 +111,11 @@ module.exports = {
'real value imports. (2) packages/core/src/v1-compat.ts — THE declared composition ' +
"seam (ADR-007; that file's own header). It is where the boot scope registers the " +
'deps it already built, and the only thing behind it is the lazy fallback for a ' +
- "process that never built AppDeps (packages/trpc's own suites). Nothing holding a " +
- 'Ctx comes through it. It is deleted whole with packages/trpc at P10. ' +
+ "caller with no Ctx to thread through — MCP's tool handlers have a fixed " +
+ "@modelcontextprotocol/sdk signature (modules/mcp/src/auth.ts lazy-imports it; the gsc " +
+ 'tools reach getGsc* through it), and the assistant tool runtime is the same shape. ' +
+ 'Nothing holding a Ctx comes through it. M11-004 corrects an earlier claim here: this ' +
+ 'file is NOT deleted with packages/trpc — it stays as that seam. ' +
'(3) packages/core/src/code-migrations/** — one-shot CLI scripts run by ' +
'`migrate.ts` (`pnpm migrate:deploy:code`), outside the app, with no request and no ' +
'Ctx to lose; ADR-007 puts code-migrations/ in core and keeps clickhouse/migration.ts ' +
diff --git a/apps/api/Dockerfile b/apps/api/Dockerfile
index b6be11d20..9c717a83c 100644
--- a/apps/api/Dockerfile
+++ b/apps/api/Dockerfile
@@ -50,7 +50,7 @@ COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
COPY apps/api/package.json ./apps/api/
# Packages — @openpanel/api's workspace closure, exactly as pnpm computes it
# (verified against `pnpm --filter "@openpanel/api..." list --depth -1`: these
-# 11, plus the private tooling/typescript devDependency, which --prod below
+# 9, plus the private tooling/typescript devDependency, which --prod below
# never installs, so its manifest is deliberately not copied here). This list
# is still hand-maintained: Docker's COPY only accepts a glob for the *last*
# path segment, so `packages/*/package.json` flattens every match into one
@@ -64,10 +64,8 @@ COPY apps/api/package.json ./apps/api/
# graph changes.
COPY packages/core/package.json packages/core/
COPY packages/db/package.json packages/db/
-COPY packages/trpc/package.json packages/trpc/
COPY packages/json/package.json packages/json/
COPY packages/email/package.json packages/email/
-COPY packages/queue/package.json packages/queue/
COPY packages/redis/package.json packages/redis/
COPY packages/common/package.json packages/common/
COPY packages/payments/package.json packages/payments/
diff --git a/apps/api/package.json b/apps/api/package.json
index 4a7ea4ed3..b7832462b 100644
--- a/apps/api/package.json
+++ b/apps/api/package.json
@@ -19,9 +19,7 @@
"@openpanel/common": "workspace:*",
"@openpanel/core": "workspace:*",
"@openpanel/db": "workspace:*",
- "@openpanel/queue": "workspace:*",
"@openpanel/redis": "workspace:*",
- "@openpanel/trpc": "workspace:*",
"elysia": "1.4.30",
"pino": "catalog:",
"pino-pretty": "catalog:",
diff --git a/apps/start/Dockerfile b/apps/start/Dockerfile
index ee139ae8f..c1357a98b 100644
--- a/apps/start/Dockerfile
+++ b/apps/start/Dockerfile
@@ -26,7 +26,6 @@ COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
# Apps
COPY apps/start/package.json ./apps/start/
# Packages - Only copy what start app needs
-COPY packages/trpc/package.json packages/trpc/
COPY packages/json/package.json packages/json/
COPY packages/common/package.json packages/common/
COPY packages/payments/package.json packages/payments/
@@ -81,7 +80,6 @@ COPY --from=build /app/pnpm-workspace.yaml ./
# Copy package.json files for production install
COPY --from=build /app/apps/start/package.json ./apps/start/
COPY --from=build /app/packages/db/package.json ./packages/db/
-COPY --from=build /app/packages/trpc/package.json ./packages/trpc/
COPY --from=build /app/packages/auth/package.json ./packages/auth/
COPY --from=build /app/packages/json/package.json ./packages/json/
COPY --from=build /app/packages/common/package.json ./packages/common/
@@ -139,7 +137,6 @@ RUN set -eux; \
# Copy necessary packages
COPY --from=build /app/packages/db ./packages/db
-COPY --from=build /app/packages/trpc ./packages/trpc
COPY --from=build /app/packages/auth ./packages/auth
COPY --from=build /app/packages/json ./packages/json
COPY --from=build /app/packages/common ./packages/common
diff --git a/packages/core/package.json b/packages/core/package.json
index c44823651..39387f0ca 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -38,7 +38,6 @@
"@openpanel/db": "workspace:*",
"@openpanel/email": "workspace:*",
"@openpanel/payments": "workspace:*",
- "@openpanel/queue": "workspace:*",
"@openpanel/redis": "workspace:*",
"@openpanel/validation": "workspace:*",
"@oslojs/crypto": "^1.0.1",
diff --git a/packages/core/src/buffers/base-buffer.ts b/packages/core/src/buffers/base-buffer.ts
index 35e686aae..c607cf0bc 100644
--- a/packages/core/src/buffers/base-buffer.ts
+++ b/packages/core/src/buffers/base-buffer.ts
@@ -32,12 +32,13 @@ export interface BufferDeps {
* a second client (and a second pino transport) outside any scope.
*
* OPTIONAL, deliberately: `@openpanel/queue`'s process-wide buffer
- * singleton (packages/queue/src/buffers.ts) is a pre-`AppDeps` caller that
- * has no client to hand in and lives outside this wave's scope. When it is
- * absent, `resolveCh()` reaches the boot scope through the declared
- * v1-compat seam — which, once `main.ts` has registered, is the very same
- * client, not a second one. Both the field and the fallback die with
- * `packages/queue` at P10.
+ * singleton used to be the pre-`AppDeps` caller with no client to hand
+ * in; that caller was deleted with the package (M11-004), but
+ * `apps/api/e2e/legacy-job-proof.ts` — a BullMQ-keys-only proof that never
+ * flushes to ClickHouse — builds `BufferDeps` the same way, so the field
+ * and the fallback stay. When it is absent, `resolveCh()` reaches the boot
+ * scope through the declared v1-compat seam — which, once `main.ts` has
+ * registered, is the very same client, not a second one.
*/
ch?: ServiceDeps['ch'];
/**
diff --git a/packages/core/src/clients/logger.ts b/packages/core/src/clients/logger.ts
index e5dcbea4b..e9d2d1ad4 100644
--- a/packages/core/src/clients/logger.ts
+++ b/packages/core/src/clients/logger.ts
@@ -100,7 +100,7 @@ export function getServiceName(name: string): string {
// pino-pretty's transport runs in a worker thread that pino locates via
// require.resolve at the CALLING module's location. Under Bun that
// resolution is broken for a transitive dependency (a caller outside
-// @openpanel/core, e.g. @openpanel/queue's module-scope `createLogger` call)
+// @openpanel/core, e.g. apps/api/src/main.ts's own `createLogger` call)
// and crashes the process instead of the log line — deterministic on this
// box, not a flake. Node has no such issue, so this only turns pretty
// printing off for the Bun-booted V2 API; every Node-booted process
diff --git a/packages/core/src/index.test.ts b/packages/core/src/index.test.ts
index ad4e227d5..bc73fffb1 100644
--- a/packages/core/src/index.test.ts
+++ b/packages/core/src/index.test.ts
@@ -19,9 +19,10 @@ test('the mount surface is curated', () => {
});
// ONE tRPC instance (ADR-009): `initTRPC` is called in rpc/base.ts and
-// nowhere else, so `@openpanel/trpc` has to reach the builder, the router
-// factory and the two injected middleware factories through the barrel.
-// This block shrinks as the 28 routers move into core's modules (P5-P8).
+// nowhere else. All 28 routers now build on this barrel's builder, router
+// factory and the two injected middleware factories (M11-001); V1's
+// `@openpanel/trpc` used to reach them the same way before it was deleted
+// (M11-004).
test('the rpc base is on the barrel, so there is one tRPC instance', () => {
expect(core.procedure).toBeDefined();
expect(core.middleware).toBeTypeOf('function');
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 610009416..ad180db3e 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -228,16 +228,16 @@ export {
getChatRunContext,
runFilterCommand,
} from './modules/assistant/assistant.service';
-// Dissolved from @openpanel/auth (M4-007) — apps/api's OAuth callbacks and
-// @openpanel/trpc's auth/share/user/gsc routers call these directly, the same
-// way they reach the other dissolved leaf packages here. `hashPassword` is
-// renamed on the way out: `./shared/crypto` already owns that name for the
-// (unrelated) scrypt hash client secrets use.
+// Dissolved from @openpanel/auth (M4-007) — apps/api's OAuth callbacks call
+// these directly; V1's now-deleted @openpanel/trpc auth/share/user/gsc
+// routers did too, the same way they reached the other dissolved leaf
+// packages here. `hashPassword` is renamed on the way out: `./shared/crypto`
+// already owns that name for the (unrelated) scrypt hash client secrets use.
//
// The sign-up/sign-in/TOTP/reset-password/share/OAuth-callback half (M6-003)
-// joined it here — packages/trpc's auth router and
-// apps/api/src/controllers/oauth-callback.controller.tsx call these
-// directly, the same way V1 reaches every other dissolved service here.
+// joined it here — V1's now-deleted packages/trpc auth router and
+// apps/api/src/controllers/oauth-callback.controller.tsx called these
+// directly, the same way V1 reached every other dissolved service here.
export type {
AuthProvider,
AuthService,
@@ -562,9 +562,9 @@ export {
export { checkNotificationRulesForEvent } from './modules/notification/src/notification-dispatch';
// New module (M6-003) — the onboarding-project mutation and the onboarding
// email drip, neither of which had a packages/db/src/services/* home to move
-// from. packages/trpc's onboarding router and apps/worker's onboarding cron
-// job call these directly, the same way V1 reaches every other dissolved
-// service here.
+// from. V1's now-deleted packages/trpc onboarding router and apps/worker's
+// onboarding cron job called these directly, the same way V1 reached every
+// other dissolved service here.
export type {
CreateOnboardingProjectResult,
OnboardingCronSummary,
@@ -1014,11 +1014,12 @@ export type {
} from './modules/tools/src/site-checker';
export { runSiteCheck } from './modules/tools/src/site-checker';
export { dashboardRoutes, opsRoutes, publicApiRoutes } from './rest.routes';
-// The RPC base is on the barrel because it is the seam `@openpanel/trpc`
-// builds its 28 routers on: ONE tRPC instance, mounted by V1's Fastify
-// adapter and by V2's `createTrpcFetchHandler` alike (ADR-009). Those routers
-// move into `modules/<name>/<name>.rpc.ts` with their waves (P5-P8), and this
-// block shrinks back to what apps/api needs when the last one has moved.
+// The RPC base is on the barrel because it is the seam every module's own
+// `<name>.rpc.ts` builds its router on: ONE tRPC instance (ADR-009), mounted
+// by V2's `createTrpcFetchHandler`. V1's now-deleted `@openpanel/trpc`
+// reached the same builder the same way, before all 28 routers moved into
+// `modules/<name>/<name>.rpc.ts` (M11-001) and the package itself was
+// deleted (M11-004).
export type {
CacheMiddlewareDeps,
EnforceRateLimit,
diff --git a/packages/core/src/modules/assistant/src/report-runner.ts b/packages/core/src/modules/assistant/src/report-runner.ts
index d66b24d9e..572fc16f1 100644
--- a/packages/core/src/modules/assistant/src/report-runner.ts
+++ b/packages/core/src/modules/assistant/src/report-runner.ts
@@ -6,9 +6,9 @@
// core cannot inherit: `@openpanel/mcp` already depends on `@openpanel/core`
// (its auth + session-manager modules), so core importing `@openpanel/mcp`
// back would be a real package cycle (the same shape cohort.service.ts's
-// header documents for `@openpanel/queue`). ADR-007 also explicitly defers
-// unifying MCP's tool definitions with assistant's, so reaching into mcp is
-// not the fix either.
+// header documents for the now-deleted `@openpanel/queue`). ADR-007 also
+// explicitly defers unifying MCP's tool definitions with assistant's, so
+// reaching into mcp is not the fix either.
//
// The result is a second copy of this dispatch logic, which is exactly the
// "four independent wrapper layers over the same 34 *Core functions"
diff --git a/packages/core/src/modules/cohort/cohort.service.ts b/packages/core/src/modules/cohort/cohort.service.ts
index 7d7165e88..1c1c05aea 100644
--- a/packages/core/src/modules/cohort/cohort.service.ts
+++ b/packages/core/src/modules/cohort/cohort.service.ts
@@ -2,9 +2,10 @@
// producer wrapper (`enqueueCohortCompute`) moves here too — db cannot hold
// producers (ADR-007's discovery: "packages/db/src/services/cohort.service.ts:12
// imports cohortComputeQueue from @openpanel/queue" was flagged as reaching
-// back into infrastructure it should not know about). packages/db loses this
-// file entirely: nothing outside trpc/worker/this module's own tests reached
-// it through @openpanel/db's barrel.
+// back into infrastructure it should not know about; @openpanel/queue itself
+// was deleted at M11-004). packages/db lost this file entirely: nothing
+// outside the now-deleted trpc/worker and this module's own tests reached it
+// through @openpanel/db's barrel.
//
// db/ch access is LAZY (`load*` below), not a static top-level import — see
// insight.service.ts's header for the full reasoning (jobs.registry.ts and
@@ -23,14 +24,15 @@
// connection at all.
//
// V1's trpc router (packages/trpc/src/routers/cohort.ts) and worker cron job
-// (apps/worker/src/jobs/cron.cohort-refresh.ts) stay live (DELEGATE PATTERN)
-// and enqueue by calling @openpanel/queue's cohortComputeQueue directly,
-// same as gsc's V1 router/worker do for gscQueue (M5-002) — @openpanel/queue
-// itself imports @openpanel/core for its logger (packages/queue/src/queues.ts),
-// so core cannot import @openpanel/queue back without a real package cycle.
-// `CohortService.enqueueCompute` (below) is the canonical, ctx.queues-based
-// wrapper for callers that already have a Ctx (this module's own rpc
-// mutations and its cron fragment).
+// (apps/worker/src/jobs/cron.cohort-refresh.ts) used to stay live (DELEGATE
+// PATTERN) and enqueue by calling @openpanel/queue's cohortComputeQueue
+// directly, same as gsc's V1 router/worker did for gscQueue (M5-002) —
+// @openpanel/queue itself imported @openpanel/core for its logger, so core
+// could not import @openpanel/queue back without a real package cycle. Both
+// delegates are gone now (apps/worker at P9, packages/trpc/packages/queue at
+// M11-004). `CohortService.enqueueCompute` (below) is the canonical,
+// ctx.queues-based wrapper for callers that already have a Ctx (this
+// module's own rpc mutations and its cron fragment).
import type { ClickHouseSettings } from '@clickhouse/client';
import type { IChartEventFilter } from '@openpanel/validation';
diff --git a/packages/core/src/modules/overview/overview.rpc.ts b/packages/core/src/modules/overview/overview.rpc.ts
index cc82be92a..abc5d6f6d 100644
--- a/packages/core/src/modules/overview/overview.rpc.ts
+++ b/packages/core/src/modules/overview/overview.rpc.ts
@@ -49,10 +49,10 @@ import {
} from './overview.service';
// Lazy, not a static import: the assistant module's chatApp chain reaches
-// deep into @openpanel/db and @openpanel/queue (see index.ts's own
-// `loadAssistant()` for the full story) — a static import here would pull
-// that chain into this module's evaluation, and this module is itself a
-// static import of rpc.router.ts/index.ts's own barrel.
+// deep into @openpanel/db (see index.ts's own `loadAssistant()` for the full
+// story) — a static import here would pull that chain into this module's
+// evaluation, and this module is itself a static import of
+// rpc.router.ts/index.ts's own barrel.
function loadFilterCommand() {
return import('../assistant/src/filter-command');
}
diff --git a/packages/core/src/modules/session/session.service.ts b/packages/core/src/modules/session/session.service.ts
index de85e88ac..c6a608a7d 100644
--- a/packages/core/src/modules/session/session.service.ts
+++ b/packages/core/src/modules/session/session.service.ts
@@ -503,9 +503,9 @@ export interface SessionService {
): Promise<IServiceSession & { hasReplay: boolean }>;
/**
* Enqueue one `session_end` job, idempotent on the closed session's id.
- * The ctx.queues-based producer; V1's apps/worker keeps its own
- * @openpanel/queue producer (utils/session-handler.ts) because core cannot
- * import @openpanel/queue back (see cohort.service.ts's header).
+ * The ctx.queues-based producer; V1's now-deleted apps/worker kept its own
+ * @openpanel/queue producer (utils/session-handler.ts) because core could
+ * not import @openpanel/queue back (see cohort.service.ts's header).
*/
enqueueSessionEnd(input: EnqueueSessionEndInput): Promise<void>;
}
diff --git a/packages/core/src/shared/access.ts b/packages/core/src/shared/access.ts
index d58fa99a0..9fc37d7b0 100644
--- a/packages/core/src/shared/access.ts
+++ b/packages/core/src/shared/access.ts
@@ -8,8 +8,10 @@
// That injection is not decoration. Core must stay importable without a
// database — `bun test` loads this package with no DATABASE_URL and no Prisma
// client — and it is the same seam `createCacheMiddleware` and
-// `createRateLimitMiddleware` already use in rpc/base.ts. `@openpanel/trpc`
-// binds it to the real services; a test binds it to two functions.
+// `createRateLimitMiddleware` already use in rpc/base.ts. `auth.service.ts`'s
+// `createAccessChecks` call binds it to the real services (M10-002); V1's
+// now-deleted `@openpanel/trpc` used to bind it the same way; a test binds
+// it to two functions.
import { TRPCForbiddenError } from '../rpc/errors';
diff --git a/packages/core/src/v1-compat.ts b/packages/core/src/v1-compat.ts
index bf9b27157..15c3693c6 100644
--- a/packages/core/src/v1-compat.ts
+++ b/packages/core/src/v1-compat.ts
@@ -1,16 +1,16 @@
-// V1 COMPAT SEAM — one file, deleted whole when `packages/trpc` dies at P10.
-//
-// `apps/api/src/main.ts` still mounts `@openpanel/trpc`'s `appRouter`, not
-// this package's `rpc.router.ts`, so V1's 28 routers are the live `/trpc`
-// surface; the mcp and assistant tool runtimes call this package the same
-// way. All of them reach a module through a BARE barrel export and have no
-// `ServiceDeps` to hand it — `packages/trpc` is outside this wave's scope,
-// so its call sites cannot change here.
+// V1 COMPAT SEAM — stays after `packages/trpc` and `packages/queue` are
+// deleted (M11-004); it is not part of that deletion. `apps/api/src/main.ts`
+// has mounted this package's own `rpc.router.ts` `appRouter` since M11-001,
+// but the mcp and assistant tool runtimes still reach a module through a
+// BARE barrel export and have no `ServiceDeps` to hand it — MCP tool
+// handlers have a fixed `@modelcontextprotocol/sdk` signature
+// (modules/mcp/src/auth.ts lazy-imports this file; the gsc tools call
+// getGsc* through it) and the assistant tool runtime is the same shape.
//
// The alternative was to leave every module its own
// `import('@openpanel/db/...')` loader, which is exactly the drift
// docs/TECH_DEBT.md §4 exists to remove. Instead the boot scope registers
-// the deps it has ALREADY built, once, here, and the barrel's V1 wrappers
+// the deps it has ALREADY built, once, here, and the barrel's bare wrappers
// read them from this one place.
//
// Nothing that has a `Ctx` comes through here. HTTP routes, core's own
@@ -19,9 +19,9 @@
// query (ADR-018). What comes through this file gets the boot logger —
// exactly what those callers got before this wave, no worse.
//
-// A process that never builds `AppDeps` — `packages/trpc`'s own vitest
-// suites, which exercise a router directly — falls back to the singletons
-// the deleted module-level `loadDb()` / `loadChClient()` loaders reached, so
+// A process that never builds `AppDeps` — this package's own unit suites,
+// which exercise a service directly — falls back to the singletons the
+// deleted module-level `loadDb()` / `loadChClient()` loaders reached, so
// those callers behave exactly as they did before this wave. The fallback is
// LAZY: importing `@openpanel/core` still constructs no database, which is
// what keeps `bun test` runnable offline.
@@ -1001,8 +1001,10 @@ export const deleteConversation: Services['conversation']['deleteConversation']
// M10-005: the runtime path's bare spellings. `event`, `profile`, `group`,
// `misc`, `overview`/`pages` and `realtime` all gained a `ServiceDeps` first
-// parameter; `packages/trpc`'s routers and `@openpanel/queue`'s notification
-// dispatch still call them bare, and reach them through here.
+// parameter; V1's `@openpanel/trpc` routers and `@openpanel/queue`'s
+// notification dispatch called them bare through here before both were
+// deleted (M11-003 moved notification dispatch into this module's own
+// src/notification-dispatch.ts; M11-004 deleted packages/trpc).
// --- event -------------------------------------------------------------------
@@ -1467,11 +1469,12 @@ export const runPingCron: (
) => ReturnType<typeof misc_runPingCron> = (...args) =>
compatServiceDeps().then((deps) => misc_runPingCron(deps, ...args));
-// `packages/trpc`'s overview and event routers call these as OBJECTS
-// (`overviewService.getMetrics(...)`, `pagesService.getTopPages(...)`), and
-// one of them still does `.bind(overviewService)`. Both were module-singleton
-// class instances before M10-005; here they are plain objects of bare
-// wrappers, so the call sites read identically and `bind` stays a no-op.
+// V1's (now-deleted) `@openpanel/trpc` overview and event routers called
+// these as OBJECTS (`overviewService.getMetrics(...)`,
+// `pagesService.getTopPages(...)`), and one of them still did
+// `.bind(overviewService)`. Both were module-singleton class instances
+// before M10-005; here they are plain objects of bare wrappers, so those
+// call sites read identically and `bind` stayed a no-op.
export const overviewService = {
isPageFilter: (...args: Parameters<Services['overview']['isPageFilter']>) =>
isPageFilter(...args),
diff --git a/packages/db/package.json b/packages/db/package.json
index 5ff088d1d..320496fac 100644
--- a/packages/db/package.json
+++ b/packages/db/package.json
@@ -20,7 +20,6 @@
"@openpanel/core": "workspace:*",
"@openpanel/json": "workspace:*",
"@openpanel/payments": "workspace:*",
- "@openpanel/queue": "workspace:^",
"@openpanel/redis": "workspace:*",
"@openpanel/validation": "workspace:*",
"@prisma/client": "^6.14.0",
diff --git a/packages/queue/index.ts b/packages/queue/index.ts
deleted file mode 100644
index 197f47f0a..000000000
--- a/packages/queue/index.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-// The Kafka transport and the notification dispatch left this package at
-// M11-003 for @openpanel/core (modules/ingest/src/kafka.ts and
-// modules/notification/src/notification-dispatch.ts). What stays is V1's
-// BullMQ queue definitions and the buffer singleton built on `cronQueue`,
-// both still imported by packages/trpc's routers — a package this task's
-// scope does not cover, so their deletion waits for the follow-up that may
-// touch those call sites (see docs/TECH_DEBT.md).
-
-export type { JobsOptions } from 'bullmq';
-export type * from './src/queues';
-export * from './src/queues';
diff --git a/packages/queue/package.json b/packages/queue/package.json
deleted file mode 100644
index 88a5ca367..000000000
--- a/packages/queue/package.json
+++ /dev/null
@@ -1,21 +0,0 @@
-{
- "name": "@openpanel/queue",
- "version": "0.0.1",
- "type": "module",
- "main": "index.ts",
- "scripts": {
- "typecheck": "tsc --noEmit"
- },
- "dependencies": {
- "@openpanel/core": "workspace:*",
- "@openpanel/db": "workspace:*",
- "@openpanel/redis": "workspace:*",
- "bullmq": "^5.63.0",
- "kafkajs": "^2.2.4"
- },
- "devDependencies": {
- "@openpanel/tsconfig": "workspace:*",
- "@types/node": "catalog:",
- "typescript": "catalog:"
- }
-}
\ No newline at end of file
diff --git a/packages/queue/src/buffers.ts b/packages/queue/src/buffers.ts
deleted file mode 100644
index a313cca3e..000000000
--- a/packages/queue/src/buffers.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-// Moved from packages/db/src/buffers/index.ts (M9-CLEANUP-001, packages/db's
-// final-surface shrink). The seven buffers live in @openpanel/core
-// (M8-001): `createBuffers(deps)` builds them once and V2's main.ts hangs the
-// result on `AppDeps.buffers` (ADR-007). This file is the ONE process-wide
-// singleton instance every call site that predates that ctx wiring still
-// reaches. Since M11-003 that is packages/trpc's overview/widget routers
-// alone — core's last lazy importer (widget.rpc.ts, via `loadDbBuffers`)
-// now reads `ctx.buffers`. Repointing the two remaining trpc call sites is
-// the larger, separately-scoped follow-up docs/TECH_DEBT.md tracks (the 93
-// lazy db imports bypassing ctx/requestId) — not this task, whose scope
-// stops at packages/queue.
-//
-// Lives in @openpanel/queue rather than @openpanel/core because it needs
-// `cronQueue` (ADR-005's BullMQ escape hatch: pausing `cron` from bull-board
-// halts all buffer flushing, preserved deliberately — docs/ANSWERS.md §3:
-// "known!"), and core must not import `@openpanel/queue` back without a real
-// package cycle (see queues.ts, which imports core for its logger).
-// `@openpanel/queue` already depends on `@openpanel/core`, so this is the one
-// side of that boundary free of a cycle. Also keeps core's own rule intact:
-// buffers are boot singletons on AppDeps, never a module-level singleton in
-// core itself (M8-005).
-import { createBuffers, createLogger } from '@openpanel/core';
-import { cronQueue } from './queues';
-
-const buffers = createBuffers({
- createLogger: (name) => createLogger({ name }),
- isCronPaused: () => cronQueue.isPaused(),
-});
-
-export const eventBuffer = buffers.event;
-export const profileBuffer = buffers.profile;
-export const botBuffer = buffers.bot;
-export const sessionBuffer = buffers.session;
-export const profileBackfillBuffer = buffers.profileBackfill;
-export const replayBuffer = buffers.replay;
-export const groupBuffer = buffers.group;
-
-export type {
- IClickhouseSessionReplayChunk,
- ProfileBackfillEntry,
- SessionIngestResult,
-} from '@openpanel/core';
-export { SESSION_TIMEOUT_MS } from '@openpanel/core';
diff --git a/packages/queue/src/queues.ts b/packages/queue/src/queues.ts
deleted file mode 100644
index 864045ea9..000000000
--- a/packages/queue/src/queues.ts
+++ /dev/null
@@ -1,316 +0,0 @@
-import {
- createLogger,
- type IClickhouseSession,
- type IServiceCreateEventPayload,
- type IServiceEvent,
-} from '@openpanel/core';
-import type { Prisma } from '@openpanel/db';
-import { getRedisQueue } from '@openpanel/redis';
-import { Queue } from 'bullmq';
-import type { ITrackPayload } from '../../validation';
-
-export const getQueueName = (name: string) =>
- process.env.QUEUE_CLUSTER ? `{${name}}` : name;
-
-export const queueLogger = createLogger({ name: 'queue' });
-
-// BullMQ re-emits ioredis connection errors on every Queue instance; with no
-// 'error' listener Node throws them as uncaughtException and kills the
-// process (the api died ~daily from idle-socket ECONNRESETs, see
-// api-crash-econnreset-plan.md). ioredis reconnects on its own — log and
-// continue.
-const guardQueue = <
- T extends { on(event: 'error', listener: (error: Error) => void): unknown },
->(
- queue: T,
- name: string
-): T => {
- queue.on('error', (error) => {
- queueLogger.error({ err: error, queue: name }, 'queue connection error');
- });
- return queue;
-};
-
-export interface EventsQueuePayloadIncomingEvent {
- type: 'incomingEvent';
- payload: {
- // Minted by the producer (/track, /event) so a Kafka redelivery becomes an
- // identical-id row instead of a new one. Optional on the wire: a V1
- // producer omits it and a V1 consumer ignores it, so the topic payload
- // stays readable across a rolling deploy.
- id?: string;
- projectId: string;
- event: ITrackPayload & {
- timestamp: string | number;
- isTimestampFromThePast: boolean;
- };
- uaInfo:
- | {
- readonly isServer: true;
- readonly device: 'server';
- readonly os: '';
- readonly osVersion: '';
- readonly browser: '';
- readonly browserVersion: '';
- readonly brand: '';
- readonly model: '';
- }
- | {
- readonly os: string | undefined;
- readonly osVersion: string | undefined;
- readonly browser: string | undefined;
- readonly browserVersion: string | undefined;
- readonly device: string;
- readonly brand: string | undefined;
- readonly model: string | undefined;
- readonly isServer: false;
- };
- geo: {
- country: string | undefined;
- city: string | undefined;
- region: string | undefined;
- longitude: number | undefined;
- latitude: number | undefined;
- };
- headers: Record<string, string | undefined>;
- deviceId: string;
- sessionId: string;
- };
-}
-export interface EventsQueuePayloadCreateEvent {
- type: 'createEvent';
- payload: Omit<IServiceEvent, 'id'>;
-}
-
-export interface EventsQueuePayloadCreateSessionEnd {
- type: 'createSessionEnd';
- payload: IServiceCreateEventPayload;
- // Snapshot of the session at the moment the close was decided. Used as a
- // fallback when the live Redis blob has expired by the time the job runs,
- // and to detect post-enqueue extensions (so we don't close a session that
- // received more events in the meantime).
- snapshot: IClickhouseSession;
-}
-
-// TODO: Rename `EventsQueuePayloadCreateSessionEnd`
-export type SessionsQueuePayload = EventsQueuePayloadCreateSessionEnd;
-
-export type EventsQueuePayload =
- | EventsQueuePayloadCreateEvent
- | EventsQueuePayloadCreateSessionEnd
- | EventsQueuePayloadIncomingEvent;
-
-export type CronQueuePayloadSalt = {
- type: 'salt';
- payload: undefined;
-};
-export type CronQueuePayloadFlushEvents = {
- type: 'flushEvents';
- payload: undefined;
-};
-export type CronQueuePayloadFlushProfiles = {
- type: 'flushProfiles';
- payload: undefined;
-};
-export type CronQueuePayloadFlushSessions = {
- type: 'flushSessions';
- payload: undefined;
-};
-export type CronQueuePayloadPing = {
- type: 'ping';
- payload: undefined;
-};
-export type CronQueuePayloadDelete = {
- type: 'delete';
- payload: undefined;
-};
-export type CronQueuePayloadInsightsDaily = {
- type: 'insightsDaily';
- payload: undefined;
-};
-export type CronQueuePayloadOnboarding = {
- type: 'onboarding';
- payload: undefined;
-};
-export type CronQueuePayloadFlushProfileBackfill = {
- type: 'flushProfileBackfill';
- payload: undefined;
-};
-export type CronQueuePayloadFlushReplay = {
- type: 'flushReplay';
- payload: undefined;
-};
-export type CronQueuePayloadGscSync = {
- type: 'gscSync';
- payload: undefined;
-};
-export type CronQueuePayloadFlushGroups = {
- type: 'flushGroups';
- payload: undefined;
-};
-export type CronQueuePayloadCohortRefresh = {
- type: 'cohortRefresh';
- payload: undefined;
-};
-export type CronQueuePayloadSessionReaper = {
- type: 'sessionReaper';
- payload: undefined;
-};
-export type CronQueuePayloadSessionVacuum = {
- type: 'sessionVacuum';
- payload: undefined;
-};
-export type CronQueuePayloadInsightCleanup = {
- type: 'insightCleanup';
- payload: undefined;
-};
-export type CronQueuePayloadWeeklyDigest = {
- type: 'weeklyDigest';
- payload: undefined;
-};
-export type CronQueuePayloadDataHealth = {
- type: 'dataHealth';
- payload: undefined;
-};
-export type CronQueuePayloadWindDown = {
- type: 'windDown';
- payload: undefined;
-};
-export type CronQueuePayloadFlushExports = {
- type: 'flushExports';
- payload: undefined;
-};
-export type CronQueuePayload =
- | CronQueuePayloadSalt
- | CronQueuePayloadFlushEvents
- | CronQueuePayloadFlushSessions
- | CronQueuePayloadFlushProfiles
- | CronQueuePayloadFlushProfileBackfill
- | CronQueuePayloadFlushReplay
- | CronQueuePayloadFlushGroups
- | CronQueuePayloadFlushExports
- | CronQueuePayloadPing
- | CronQueuePayloadDelete
- | CronQueuePayloadInsightsDaily
- | CronQueuePayloadOnboarding
- | CronQueuePayloadGscSync
- | CronQueuePayloadCohortRefresh
- | CronQueuePayloadSessionReaper
- | CronQueuePayloadSessionVacuum
- | CronQueuePayloadInsightCleanup
- | CronQueuePayloadWeeklyDigest
- | CronQueuePayloadDataHealth
- | CronQueuePayloadWindDown;
-
-export type CronQueueType = CronQueuePayload['type'];
-
-export const sessionsQueue = guardQueue(
- new Queue<SessionsQueuePayload>(getQueueName('sessions'), {
- connection: getRedisQueue(),
- defaultJobOptions: {
- removeOnComplete: true,
- },
- }),
- 'sessions'
-);
-
-export const cronQueue = guardQueue(
- new Queue<CronQueuePayload>(getQueueName('cron'), {
- connection: getRedisQueue(),
- defaultJobOptions: {
- removeOnComplete: 10,
- },
- }),
- 'cron'
-);
-
-export type NotificationQueuePayload = {
- type: 'sendNotification';
- payload: {
- notification: Prisma.NotificationUncheckedCreateInput;
- };
-};
-
-export const notificationQueue = guardQueue(
- new Queue<NotificationQueuePayload>(getQueueName('notification'), {
- connection: getRedisQueue(),
- defaultJobOptions: {
- removeOnComplete: 10,
- },
- }),
- 'notification'
-);
-
-export type ImportQueuePayload = {
- type: 'import';
- payload: {
- importId: string;
- };
-};
-
-export const importQueue = guardQueue(
- new Queue<ImportQueuePayload>(getQueueName('import'), {
- connection: getRedisQueue(),
- defaultJobOptions: {
- removeOnComplete: 10,
- removeOnFail: 50,
- },
- }),
- 'import'
-);
-
-export type InsightsQueuePayloadProject = {
- type: 'insightsProject';
- payload: { projectId: string; date: string };
-};
-
-export const insightsQueue = guardQueue(
- new Queue<InsightsQueuePayloadProject>(getQueueName('insights'), {
- connection: getRedisQueue(),
- defaultJobOptions: {
- removeOnComplete: 100,
- },
- }),
- 'insights'
-);
-
-export type GscQueuePayloadSync = {
- type: 'gscProjectSync';
- payload: { projectId: string };
-};
-export type GscQueuePayloadBackfill = {
- type: 'gscProjectBackfill';
- payload: { projectId: string };
-};
-export type GscQueuePayload = GscQueuePayloadSync | GscQueuePayloadBackfill;
-
-export const gscQueue = guardQueue(
- new Queue<GscQueuePayload>(getQueueName('gsc'), {
- connection: getRedisQueue(),
- defaultJobOptions: {
- removeOnComplete: 50,
- removeOnFail: 100,
- },
- }),
- 'gsc'
-);
-
-export type CohortComputePayload = {
- cohortId: string;
-};
-
-export const cohortComputeQueue = guardQueue(
- new Queue<CohortComputePayload>(getQueueName('cohortCompute'), {
- connection: getRedisQueue(),
- defaultJobOptions: {
- attempts: 3,
- backoff: { type: 'exponential', delay: 5000 },
- // `age` alone only trims when another job in this queue finishes, so pair
- // it with a count bound to keep the completed/failed sets from growing
- // unbounded during quiet periods.
- removeOnComplete: { age: 3600, count: 100 },
- removeOnFail: { age: 86_400, count: 100 },
- },
- }),
- 'cohortCompute'
-);
diff --git a/packages/queue/tsconfig.json b/packages/queue/tsconfig.json
deleted file mode 100644
index a4a54fb86..000000000
--- a/packages/queue/tsconfig.json
+++ /dev/null
@@ -1,13 +0,0 @@
-{
- "extends": "@openpanel/tsconfig/base.json",
- "compilerOptions": {
- "baseUrl": ".",
- "paths": {
- "@/*": ["./src/*"]
- },
- "tsBuildInfoFile": "node_modules/.cache/tsbuildinfo.json",
- "strictNullChecks": true
- },
- "include": ["."],
- "exclude": ["node_modules"]
-}
diff --git a/packages/trpc/index.ts b/packages/trpc/index.ts
deleted file mode 100644
index 2c70a8203..000000000
--- a/packages/trpc/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-export * from './src/root';
-export * from './src/trpc';
-export { getProjectAccess } from './src/access';
diff --git a/packages/trpc/package.json b/packages/trpc/package.json
deleted file mode 100644
index 3b95b2671..000000000
--- a/packages/trpc/package.json
+++ /dev/null
@@ -1,41 +0,0 @@
-{
- "name": "@openpanel/trpc",
- "version": "0.0.1",
- "type": "module",
- "main": "index.ts",
- "scripts": {
- "test": "vitest",
- "typecheck": "tsc --noEmit"
- },
- "dependencies": {
- "@better-agent/core": "^0.1.0-beta.3",
- "@openpanel/common": "workspace:*",
- "@openpanel/constants": "workspace:*",
- "@openpanel/core": "workspace:*",
- "@openpanel/db": "workspace:*",
- "@openpanel/email": "workspace:*",
- "@openpanel/payments": "workspace:^",
- "@openpanel/queue": "workspace:*",
- "@openpanel/redis": "workspace:*",
- "@openpanel/validation": "workspace:*",
- "@trpc/client": "^11.17.0",
- "@trpc/server": "^11.17.0",
- "date-fns": "^3.3.1",
- "mathjs": "^12.3.2",
- "prisma-error-enum": "^0.1.3",
- "ramda": "^0.29.1",
- "short-unique-id": "^5.0.3",
- "sqlstring": "^2.3.3",
- "superjson": "^1.13.3",
- "uuid": "^9.0.1",
- "zod": "catalog:"
- },
- "devDependencies": {
- "@openpanel/tsconfig": "workspace:*",
- "@types/node": "catalog:",
- "@types/ramda": "^0.29.6",
- "@types/sqlstring": "^2.3.2",
- "prisma": "^5.1.1",
- "typescript": "catalog:"
- }
-}
diff --git a/packages/trpc/src/access.test.ts b/packages/trpc/src/access.test.ts
deleted file mode 100644
index 31586b590..000000000
--- a/packages/trpc/src/access.test.ts
+++ /dev/null
@@ -1,136 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-const { getProjectAccess, getOrganizationAccess, getProjectById } = vi.hoisted(
- () => ({
- getProjectAccess: vi.fn(),
- getOrganizationAccess: vi.fn(),
- getProjectById: vi.fn(),
- }),
-);
-
-vi.mock('@openpanel/core', async () => ({
- // `createAccessChecks` (the permission ladder itself, GHSA-f9rx-pxgw-c6rg's
- // fix) stays real — only the lookups it's built from are stubbed.
- ...(await vi.importActual<typeof import('@openpanel/core')>(
- '@openpanel/core',
- )),
- getProjectAccess,
- getOrganizationAccess,
- getProjectById,
- getClientAccess: vi.fn(),
- // The real implementation - `admin` is a superset of `write`.
- canWriteProject: (access: { level: string } | null) =>
- !!access && (access.level === 'write' || access.level === 'admin'),
-}));
-
-import {
- requireOrganizationAdmin,
- requireProjectAccess,
- requireProjectAdmin,
-} from './access';
-
-beforeEach(() => {
- vi.clearAllMocks();
-});
-
-/**
- * GHSA-f9rx-pxgw-c6rg: 26 of 29 mutating procedures tested `if (!access)`,
- * and a `{ level: 'read' }` row is a truthy object, so read-only members could
- * delete projects and publish private analytics.
- */
-describe('requireProjectAccess', () => {
- it('rejects a non-member at every level', async () => {
- getProjectAccess.mockResolvedValue(null);
-
- await expect(
- requireProjectAccess({ userId: 'u', projectId: 'p', level: 'read' }),
- ).rejects.toThrow('You do not have access to this project');
- });
-
- it('rejects a read-level member from writing', async () => {
- getProjectAccess.mockResolvedValue({ level: 'read' });
-
- await expect(
- requireProjectAccess({ userId: 'u', projectId: 'p', level: 'write' }),
- ).rejects.toThrow('read-only');
- });
-
- it('lets a read-level member read', async () => {
- getProjectAccess.mockResolvedValue({ level: 'read' });
-
- await expect(
- requireProjectAccess({ userId: 'u', projectId: 'p', level: 'read' }),
- ).resolves.toEqual({ level: 'read' });
- });
-
- it.each(['write', 'admin'])('lets a %s-level member write', async (level) => {
- getProjectAccess.mockResolvedValue({ level });
-
- await expect(
- requireProjectAccess({ userId: 'u', projectId: 'p', level: 'write' }),
- ).resolves.toEqual({ level });
- });
-});
-
-describe('requireOrganizationAdmin', () => {
- it('rejects a plain member', async () => {
- getOrganizationAccess.mockResolvedValue({ role: 'org:member' });
-
- await expect(
- requireOrganizationAdmin({ userId: 'u', organizationId: 'o' }),
- ).rejects.toThrow('Only organization admins');
- });
-
- it('rejects a non-member', async () => {
- getOrganizationAccess.mockResolvedValue(null);
-
- await expect(
- requireOrganizationAdmin({ userId: 'u', organizationId: 'o' }),
- ).rejects.toThrow('Only organization admins');
- });
-
- it('allows an org admin', async () => {
- getOrganizationAccess.mockResolvedValue({ role: 'org:admin' });
-
- await expect(
- requireOrganizationAdmin({ userId: 'u', organizationId: 'o' }),
- ).resolves.toEqual({ role: 'org:admin' });
- });
-});
-
-describe('requireProjectAdmin', () => {
- it('resolves the org from the project, then requires admin', async () => {
- getProjectById.mockResolvedValue({ organizationId: 'o' });
- getOrganizationAccess.mockResolvedValue({ role: 'org:member' });
-
- await expect(
- requireProjectAdmin({ userId: 'u', projectId: 'p' }),
- ).rejects.toThrow('Only organization admins');
-
- expect(getOrganizationAccess).toHaveBeenCalledWith({
- userId: 'u',
- organizationId: 'o',
- });
- });
-
- it('rejects when the project has no organization', async () => {
- getProjectById.mockResolvedValue(null);
-
- await expect(
- requireProjectAdmin({ userId: 'u', projectId: 'p' }),
- ).rejects.toThrow('You do not have access to this project');
-
- expect(getOrganizationAccess).not.toHaveBeenCalled();
- });
-
- // A write-level member must not be able to schedule a project for deletion
- // just because they can edit reports in it.
- it('allows an org admin', async () => {
- getProjectById.mockResolvedValue({ organizationId: 'o' });
- getOrganizationAccess.mockResolvedValue({ role: 'org:admin' });
-
- await expect(
- requireProjectAdmin({ userId: 'u', projectId: 'p' }),
- ).resolves.toEqual({ role: 'org:admin' });
- });
-});
diff --git a/packages/trpc/src/access.ts b/packages/trpc/src/access.ts
deleted file mode 100644
index ae8e1ebc4..000000000
--- a/packages/trpc/src/access.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-// The permission ladder now lives in @openpanel/core (`shared/access`); this
-// file binds it to the real lookups (also core, since M9-CLEANUP-001) and
-// keeps the specifier V1's routers and `apps/api` already import.
-//
-// The ladder itself — the rules, the messages, GHSA-f9rx-pxgw-c6rg's fix — is
-// core's and single-sourced there.
-
-import {
- canWriteProject,
- createAccessChecks,
- getOrganizationAccess,
- getProjectAccess,
- getProjectById,
-} from '@openpanel/core';
-
-export {
- getClientAccess,
- getOrganizationAccess,
- getProjectAccess,
-} from '@openpanel/core';
-
-const checks = createAccessChecks({
- getProjectAccess,
- canWriteProject,
- getOrganizationAccess,
- getProjectById,
-});
-
-export const requireProjectAccess = checks.requireProjectAccess;
-export const requireOrganizationAdmin = checks.requireOrganizationAdmin;
-export const requireProjectAdmin = checks.requireProjectAdmin;
diff --git a/packages/trpc/src/errors.ts b/packages/trpc/src/errors.ts
deleted file mode 100644
index 3217bbd29..000000000
--- a/packages/trpc/src/errors.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-// One definition, in @openpanel/core (`rpc/errors`). Re-exported here so V1's
-// routers keep their specifier until they move into core's modules (P5-P8).
-
-export {
- TRPCAccessError,
- TRPCBadRequestError,
- TRPCForbiddenError,
- TRPCInternalServerError,
- TRPCNotFoundError,
-} from '@openpanel/core';
diff --git a/packages/trpc/src/rate-limit.test.ts b/packages/trpc/src/rate-limit.test.ts
deleted file mode 100644
index 9ccb085df..000000000
--- a/packages/trpc/src/rate-limit.test.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import { describe, expect, it } from 'vitest';
-import { __testing } from './rate-limit';
-
-const { getBlockDurationMs, BLOCK_BASE_MS, BLOCK_MAX_MS, MAX_STRIKES } =
- __testing;
-
-describe('rate limit escalation', () => {
- it('doubles the lockout on every strike', () => {
- expect(getBlockDurationMs(1)).toBe(BLOCK_BASE_MS);
- expect(getBlockDurationMs(2)).toBe(BLOCK_BASE_MS * 2);
- expect(getBlockDurationMs(3)).toBe(BLOCK_BASE_MS * 4);
- expect(getBlockDurationMs(4)).toBe(BLOCK_BASE_MS * 8);
- });
-
- it('caps the lockout instead of overflowing into absurd durations', () => {
- expect(getBlockDurationMs(MAX_STRIKES)).toBe(BLOCK_MAX_MS);
- expect(getBlockDurationMs(1000)).toBe(BLOCK_MAX_MS);
- });
-
- it('reaches the cap at MAX_STRIKES and not before', () => {
- expect(getBlockDurationMs(MAX_STRIKES - 1)).toBeLessThan(BLOCK_MAX_MS);
- });
-
- it('formats the wait as something a human can act on', () => {
- expect(__testing.formatDuration(30_000)).toBe('30 seconds');
- expect(__testing.formatDuration(5 * 60_000)).toBe('5 minutes');
- expect(__testing.formatDuration(24 * 60 * 60_000)).toBe('24 hours');
- });
-});
diff --git a/packages/trpc/src/rate-limit.ts b/packages/trpc/src/rate-limit.ts
deleted file mode 100644
index bf9048285..000000000
--- a/packages/trpc/src/rate-limit.ts
+++ /dev/null
@@ -1,260 +0,0 @@
-import type { EnforceRateLimit } from '@openpanel/core';
-import { getTrustedIpFromHeaders } from '@openpanel/core';
-import { getRedisCache, LRUCache } from '@openpanel/redis';
-import { TRPCError } from '@trpc/server';
-
-const SECOND = 1000;
-const MINUTE = 60 * SECOND;
-const HOUR = 60 * MINUTE;
-
-/**
- * The block handed out the first time a fingerprint blows through its window.
- * It doubles on every further strike, so a client that keeps knocking walks
- * 5m -> 10m -> 20m -> ... -> BLOCK_MAX_MS.
- */
-const BLOCK_BASE_MS = 5 * MINUTE;
-const BLOCK_MAX_MS = 24 * HOUR;
-
-/**
- * Strikes only decay after a full quiet day, and every new strike pushes the
- * expiry out again. Sustained abuse therefore stays at the 24h block forever -
- * the attacker has to actually stop to climb back down.
- */
-const STRIKE_TTL_MS = 24 * HOUR;
-
-/** Past this the duration is capped anyway, so stop counting. */
-const MAX_STRIKES = Math.ceil(Math.log2(BLOCK_MAX_MS / BLOCK_BASE_MS)) + 1;
-
-/**
- * A blocked client that keeps hammering earns further strikes, but at most one
- * per cooldown. A human clicking "sign in" three more times in frustration adds
- * one strike; a bot at 5 req/s reaches the 24h cap in under ten minutes.
- */
-const ESCALATION_COOLDOWN_MS = MINUTE;
-
-/**
- * Per-process fallback used only while Redis is unreachable. Without it a Redis
- * blip would leave the sign-in endpoint completely unthrottled.
- */
-const fallbackCounters = new LRUCache<string, number>({
- max: 10_000,
- ttl: 5 * MINUTE,
-});
-
-const key = (kind: string, path: string, fingerprint: string) =>
- `rl:${kind}:${path}:${fingerprint}`;
-
-function getBlockDurationMs(strikes: number): number {
- return Math.min(BLOCK_BASE_MS * 2 ** (strikes - 1), BLOCK_MAX_MS);
-}
-
-function formatDuration(ms: number): string {
- const seconds = Math.ceil(ms / SECOND);
- if (seconds < 90) {
- return `${seconds} seconds`;
- }
- const minutes = Math.ceil(seconds / 60);
- if (minutes < 90) {
- return `${minutes} minutes`;
- }
- return `${Math.ceil(minutes / 60)} hours`;
-}
-
-/**
- * The identity we rate limit on. Deliberately ignores the client-forwarded IP
- * headers that `getClientIpFromHeaders` prefers - those are attacker-controlled
- * and would make every request its own bucket. `ctx.ip` is exactly those
- * headers, which is why this takes the raw `Headers` and the connection's peer
- * address instead of anything the context already resolved.
- */
-export function getRateLimitIdentity(
- headers: Headers,
- remoteAddress: string | undefined
-) {
- const { ip, header } = getTrustedIpFromHeaders(headers, remoteAddress);
-
- return {
- // Everything we cannot identify shares one bucket. Fail closed: an edge
- // that stops forwarding IPs should throttle, not open the gates.
- fingerprint: ip || 'unknown',
- ipHeader: header,
- };
-}
-
-function tooManyRequests(blockMs: number): TRPCError {
- return new TRPCError({
- code: 'TOO_MANY_REQUESTS',
- message: `Too many requests. Try again in ${formatDuration(blockMs)}.`,
- });
-}
-
-/**
- * Record a strike and (re)arm the block. Returns the new strike count and how
- * long the client is locked out for.
- */
-async function escalate(
- strikeKey: string,
- blockKey: string,
- cooldownKey: string
-) {
- const redis = getRedisCache();
-
- // Counter and its expiry go out together: a strike key that lost its TTL
- // would keep an IP at the maximum lockout forever.
- const results = await redis
- .pipeline()
- .incr(strikeKey)
- .pexpire(strikeKey, STRIKE_TTL_MS)
- .exec();
-
- const strikes = Math.min(Number(results?.[0]?.[1] ?? 1), MAX_STRIKES);
- const blockMs = getBlockDurationMs(strikes);
-
- await redis
- .pipeline()
- .set(blockKey, String(strikes), 'PX', blockMs)
- .set(cooldownKey, '1', 'PX', ESCALATION_COOLDOWN_MS)
- .exec();
-
- return { strikes, blockMs };
-}
-
-/**
- * IP rate limiting with exponential lockout.
- *
- * Blocks are keyed per procedure, so an office NAT that trips the sign-in limit
- * does not lose the rest of the dashboard.
- *
- * Every block is logged as `rate limit blocked` with the resolved IP so
- * repeat offenders can be pulled out of the logs and blackholed at the edge:
- *
- * SELECT LogAttributes['ip'], count() FROM otel_logs
- * WHERE Body = 'rate limit blocked' GROUP BY 1 ORDER BY 2 DESC
- */
-export const enforceRateLimit: EnforceRateLimit = async ({
- headers,
- remoteAddress,
- logger,
- path,
- max,
- windowMs,
-}) => {
- const { fingerprint, ipHeader } = getRateLimitIdentity(
- headers,
- remoteAddress
- );
-
- const counterKey = key('count', path, fingerprint);
- const strikeKey = key('strike', path, fingerprint);
- const blockKey = key('block', path, fingerprint);
- const cooldownKey = key('cooldown', path, fingerprint);
-
- const log = (
- message: string,
- payload: { strikes: number; blockMs: number; hits?: number }
- ) =>
- logger.warn(
- {
- ip: fingerprint,
- ipHeader,
- path,
- userAgent: headers.get('user-agent') ?? undefined,
- strikes: payload.strikes,
- blockedForSeconds: Math.ceil(payload.blockMs / SECOND),
- blockedUntil: new Date(Date.now() + payload.blockMs).toISOString(),
- hits: payload.hits,
- max,
- windowMs,
- },
- message
- );
-
- let blockTtlMs: number;
- let hits: number;
-
- try {
- const redis = getRedisCache();
- const results = await redis
- .pipeline()
- .pttl(blockKey)
- .pttl(counterKey)
- .incr(counterKey)
- .exec();
-
- // `pttl` returns -2 when the key is gone and -1 when it has no expiry.
- blockTtlMs = Number(results?.[0]?.[1] ?? -2);
- const counterTtlMs = Number(results?.[1]?.[1] ?? -2);
- hits = Number(results?.[2]?.[1] ?? 1);
-
- // The window opens on the first hit. Re-arming a counter that somehow lost
- // its expiry matters too: without a TTL it would count up forever and lock
- // the IP out permanently after `max` requests.
- if (hits === 1 || counterTtlMs === -1) {
- await redis.pexpire(counterKey, windowMs);
- }
- } catch (error) {
- logger.error({ err: error, path }, 'rate limit store unavailable');
- const fallbackHits = (fallbackCounters.get(counterKey) ?? 0) + 1;
- fallbackCounters.set(counterKey, fallbackHits, { ttl: windowMs });
- if (fallbackHits > max) {
- throw tooManyRequests(windowMs);
- }
- return;
- }
-
- if (blockTtlMs > 0) {
- // Still locked out. Knocking during a block is itself abusive, so it
- // extends the lockout instead of letting it run down - but at most once per
- // cooldown, so a frustrated human cannot punish themselves the way a bot
- // hammering at full speed does.
- let escalated: { strikes: number; blockMs: number } | null = null;
-
- try {
- const acquired = await getRedisCache().set(
- cooldownKey,
- '1',
- 'PX',
- ESCALATION_COOLDOWN_MS,
- 'NX'
- );
-
- if (acquired) {
- escalated = await escalate(strikeKey, blockKey, cooldownKey);
- }
- } catch (error) {
- logger.error({ err: error, path }, 'rate limit store unavailable');
- }
-
- if (!escalated) {
- throw tooManyRequests(blockTtlMs);
- }
-
- log('rate limit blocked', escalated);
- throw tooManyRequests(escalated.blockMs);
- }
-
- if (hits > max) {
- let escalated: { strikes: number; blockMs: number };
-
- try {
- escalated = await escalate(strikeKey, blockKey, cooldownKey);
- // Start the next window clean so the block, not a stale counter, decides.
- await getRedisCache().del(counterKey);
- } catch (error) {
- logger.error({ err: error, path }, 'rate limit store unavailable');
- throw tooManyRequests(windowMs);
- }
-
- log('rate limit blocked', { ...escalated, hits });
- throw tooManyRequests(escalated.blockMs);
- }
-};
-
-export const __testing = {
- BLOCK_BASE_MS,
- BLOCK_MAX_MS,
- MAX_STRIKES,
- ESCALATION_COOLDOWN_MS,
- getBlockDurationMs,
- formatDuration,
-};
diff --git a/packages/trpc/src/root.ts b/packages/trpc/src/root.ts
deleted file mode 100644
index 0c461beec..000000000
--- a/packages/trpc/src/root.ts
+++ /dev/null
@@ -1,67 +0,0 @@
-import { authRouter } from './routers/auth';
-import { chartRouter } from './routers/chart';
-import { chatRouter } from './routers/chat';
-import { clientRouter } from './routers/client';
-import { cohortRouter } from './routers/cohort';
-import { conversationRouter } from './routers/conversation';
-import { dashboardRouter } from './routers/dashboard';
-import { emailRouter } from './routers/email';
-import { eventRouter } from './routers/event';
-import { groupRouter } from './routers/group';
-import { gscRouter } from './routers/gsc';
-import { importRouter } from './routers/import';
-import { insightRouter } from './routers/insight';
-import { integrationRouter } from './routers/integration';
-import { notificationRouter } from './routers/notification';
-import { onboardingRouter } from './routers/onboarding';
-import { organizationRouter } from './routers/organization';
-import { overviewRouter } from './routers/overview';
-import { profileRouter } from './routers/profile';
-import { projectRouter } from './routers/project';
-import { realtimeRouter } from './routers/realtime';
-import { referenceRouter } from './routers/reference';
-import { reportRouter } from './routers/report';
-import { sessionRouter } from './routers/session';
-import { shareRouter } from './routers/share';
-import { subscriptionRouter } from './routers/subscription';
-import { userRouter } from './routers/user';
-import { widgetRouter } from './routers/widget';
-import { createTRPCRouter } from './trpc';
-/**
- * This is the primary router for your server.
- *
- * All routers added in /api/routers should be manually added here.
- */
-export const appRouter = createTRPCRouter({
- chart: chartRouter,
- report: reportRouter,
- dashboard: dashboardRouter,
- organization: organizationRouter,
- user: userRouter,
- project: projectRouter,
- client: clientRouter,
- event: eventRouter,
- profile: profileRouter,
- session: sessionRouter,
- share: shareRouter,
- onboarding: onboardingRouter,
- reference: referenceRouter,
- notification: notificationRouter,
- integration: integrationRouter,
- import: importRouter,
- auth: authRouter,
- subscription: subscriptionRouter,
- overview: overviewRouter,
- realtime: realtimeRouter,
- chat: chatRouter,
- conversation: conversationRouter,
- insight: insightRouter,
- widget: widgetRouter,
- email: emailRouter,
- gsc: gscRouter,
- group: groupRouter,
- cohort: cohortRouter,
-});
-
-// export type definition of API
-export type AppRouter = typeof appRouter;
diff --git a/packages/trpc/src/routers/auth.ts b/packages/trpc/src/routers/auth.ts
deleted file mode 100644
index c8cce9ed7..000000000
--- a/packages/trpc/src/routers/auth.ts
+++ /dev/null
@@ -1,115 +0,0 @@
-// Dissolved into @openpanel/core's auth module (M6-003): sign-up/sign-in,
-// TOTP challenges, password reset and share unlock moved to
-// packages/core/src/modules/auth/auth.service.ts. This router stays
-// (DELEGATE PATTERN) — it keeps V1's rate-limiting/protectedProcedure stack
-// and delegates every handler body to core's auth functions, same as
-// organization's router does (M6-001).
-
-import {
- disableTotp,
- enableTotp,
- extendSessionCookie,
- getTotpStatus,
- regenerateTotpRecoveryCodes,
- requestPasswordReset,
- resetPasswordWithToken,
- setupTotp,
- signInToShare,
- signInWithEmail,
- signInWithTotp,
- signOutUser,
- signUpWithEmail,
- startOAuthSignIn,
-} from '@openpanel/core';
-import {
- zProvider,
- zRequestResetPassword,
- zResetPassword,
- zSignInEmail,
- zSignInShare,
- zSignUpEmail,
- zTotpCode,
- zTotpOrRecoveryCode,
-} from '@openpanel/validation';
-import { z } from 'zod';
-import {
- createTRPCRouter,
- protectedProcedure,
- publicProcedure,
- rateLimitMiddleware,
-} from '../trpc';
-
-export const authRouter = createTRPCRouter({
- signOut: publicProcedure.mutation(async ({ ctx }) => {
- await signOutUser(ctx.setCookie, ctx.session?.session?.id);
- }),
- signInOAuth: publicProcedure
- .input(z.object({ provider: zProvider, inviteId: z.string().nullish() }))
- .mutation(({ input, ctx }) => startOAuthSignIn(input, ctx.setCookie)),
- signUpEmail: publicProcedure
- .use(rateLimitMiddleware({ max: 5, windowMs: 60_000 }))
- .input(zSignUpEmail)
- .mutation(({ input, ctx }) => signUpWithEmail(input, ctx.setCookie)),
- signInEmail: publicProcedure
- .use(rateLimitMiddleware({ max: 3, windowMs: 30_000 }))
- .input(zSignInEmail)
- .mutation(({ input, ctx }) =>
- signInWithEmail(input, ctx.setCookie, ctx.logger)
- ),
- signInTotp: publicProcedure
- .use(rateLimitMiddleware({ max: 5, windowMs: 60_000 }))
- .input(z.object({ code: zTotpOrRecoveryCode }))
- .mutation(({ input, ctx }) =>
- signInWithTotp(input, ctx.cookies, ctx.setCookie, ctx.logger)
- ),
-
- totpStatus: protectedProcedure.query(({ ctx }) =>
- getTotpStatus(ctx.session.userId!)
- ),
-
- totpSetup: protectedProcedure.mutation(({ ctx }) =>
- setupTotp(ctx.session.userId!)
- ),
-
- totpEnable: protectedProcedure
- .use(rateLimitMiddleware({ max: 5, windowMs: 60_000 }))
- .input(z.object({ code: zTotpCode }))
- .mutation(({ ctx, input }) => enableTotp(ctx.session.userId!, input.code)),
-
- totpDisable: protectedProcedure
- .use(rateLimitMiddleware({ max: 5, windowMs: 60_000 }))
- .input(z.object({ code: zTotpOrRecoveryCode }))
- .mutation(({ ctx, input }) => disableTotp(ctx.session.userId!, input.code)),
-
- totpRegenerateRecoveryCodes: protectedProcedure
- .use(rateLimitMiddleware({ max: 3, windowMs: 60_000 }))
- .input(z.object({ code: zTotpCode }))
- .mutation(({ ctx, input }) =>
- regenerateTotpRecoveryCodes(ctx.session.userId!, input.code)
- ),
-
- resetPassword: publicProcedure
- .input(zResetPassword)
- .use(rateLimitMiddleware({ max: 3, windowMs: 60_000 }))
- .mutation(({ input }) => resetPasswordWithToken(input)),
-
- requestResetPassword: publicProcedure
- .use(rateLimitMiddleware({ max: 3, windowMs: 60_000 }))
- .input(zRequestResetPassword)
- .mutation(({ input }) => requestPasswordReset(input)),
-
- session: publicProcedure.query(({ ctx }) => ctx.session),
-
- extendSession: publicProcedure.mutation(({ ctx }) =>
- extendSessionCookie(
- ctx.cookies,
- Boolean(ctx.session.session),
- ctx.setCookie
- )
- ),
-
- signInShare: publicProcedure
- .use(rateLimitMiddleware({ max: 3, windowMs: 30_000 }))
- .input(zSignInShare)
- .mutation(({ input, ctx }) => signInToShare(input, ctx.setCookie)),
-});
diff --git a/packages/trpc/src/routers/chart.ts b/packages/trpc/src/routers/chart.ts
deleted file mode 100644
index eda4b3131..000000000
--- a/packages/trpc/src/routers/chart.ts
+++ /dev/null
@@ -1,237 +0,0 @@
-// Dissolved into @openpanel/core's chart module (M7-003): the ClickHouse
-// queries moved to packages/core/src/modules/chart/src/chart.sql.ts, the
-// engine to src/engine/ and the handler bodies to chart.service.ts. This
-// router stays (DELEGATE PATTERN) — it keeps V1's protectedProcedure /
-// chartProcedure (share) / cacheMiddleware stacks and delegates every handler
-// body to core's chart functions, same as event.ts.
-
-import {
- executeAggregateChart,
- executeChart,
- getChartBucketProfiles,
- getChartPropertyValues,
- getConversionChart,
- getFunnelChart,
- getFunnelStepProfiles,
- getProjectCard,
- getReportById,
- getRetentionChart,
- getSankeyChart,
- listChartEvents,
- listChartProperties,
- resolveReportInput,
- validateShareAccess,
-} from '@openpanel/core';
-import {
- zChartEventFilter,
- zChartSeries,
- zCriteria,
- zRange,
- zReportInput,
- zTimeInterval,
-} from '@openpanel/validation';
-import { z } from 'zod';
-import { getProjectAccess } from '../access';
-import { TRPCAccessError, TRPCForbiddenError } from '../errors';
-import {
- cacheMiddleware,
- createTRPCRouter,
- protectedProcedure,
- publicProcedure,
-} from '../trpc';
-
-const cacher = cacheMiddleware(60);
-
-const zShareable = z.object({
- shareId: z.string().optional(),
- id: z.string().optional(),
-});
-
-const zShareableReportInput = zReportInput.and(zShareable);
-
-const chartProcedure = publicProcedure.use(
- async ({ ctx, next, getRawInput }) => {
- const rawInput = (await getRawInput()) as {
- projectId: string;
- shareId?: string;
- id?: string;
- };
-
- if (rawInput.shareId) {
- // Require reportId when shareId provided
- if (!rawInput.id) {
- throw new Error('reportId required with shareId');
- }
-
- // Validate share access
- const shareValidation = await validateShareAccess(
- rawInput.shareId,
- rawInput.id,
- {
- cookies: ctx.cookies,
- session: ctx.session?.userId
- ? { userId: ctx.session.userId }
- : undefined,
- }
- );
- if (!shareValidation.isValid) {
- throw new TRPCForbiddenError('You do not have access to this share');
- }
-
- // Fetch report
- const report = await getReportById(rawInput.id);
- if (!report) {
- throw new TRPCAccessError('Report not found');
- }
-
- return next({
- ctx: {
- report,
- },
- });
- }
-
- // Regular member access check
- if (!ctx.session?.userId) {
- throw new TRPCAccessError('Authentication required');
- }
- const access = await getProjectAccess({
- projectId: rawInput.projectId,
- userId: ctx.session.userId,
- });
- if (!access) {
- throw new TRPCForbiddenError('You do not have access to this project');
- }
-
- return next({
- ctx: {
- report: null,
- },
- });
- }
-);
-
-export const chartRouter = createTRPCRouter({
- projectCard: protectedProcedure
- .use(cacheMiddleware(60 * 5))
- .input(
- z.object({
- projectId: z.string(),
- })
- )
- .query(({ input: { projectId } }) => getProjectCard(projectId)),
-
- events: protectedProcedure
- .input(
- z.object({
- projectId: z.string(),
- })
- )
- .query(({ input: { projectId } }) => listChartEvents(projectId)),
-
- properties: protectedProcedure
- .input(
- z.object({
- event: z.string().optional(),
- projectId: z.string(),
- })
- )
- .query(({ input }) => listChartProperties(input)),
-
- values: protectedProcedure
- .input(
- z.object({
- event: z.string(),
- property: z.string(),
- projectId: z.string(),
- })
- )
- .query(({ input }) => getChartPropertyValues(input)),
-
- funnel: chartProcedure
- .use(cacher)
- .input(zShareableReportInput)
- .query(({ input, ctx }) =>
- getFunnelChart(resolveReportInput(ctx.report, input))
- ),
-
- conversion: chartProcedure
- .use(cacher)
- .input(zShareableReportInput)
- .query(({ input, ctx }) =>
- getConversionChart(resolveReportInput(ctx.report, input))
- ),
-
- sankey: protectedProcedure
- .input(zReportInput)
- .query(({ input }) => getSankeyChart(input)),
-
- chart: chartProcedure
- .use(cacher)
- .input(zShareableReportInput)
- .query(({ input, ctx }) =>
- executeChart(resolveReportInput(ctx.report, input))
- ),
-
- aggregate: chartProcedure
- .use(cacher)
- .input(zShareableReportInput)
- .query(({ input, ctx }) =>
- executeAggregateChart(resolveReportInput(ctx.report, input))
- ),
-
- cohort: chartProcedure
- .use(cacher)
- .input(
- z.object({
- projectId: z.string(),
- firstEvent: z.array(z.string()).min(1),
- secondEvent: z.array(z.string()).min(1),
- criteria: zCriteria.default('on_or_after'),
- startDate: z.string().nullish(),
- endDate: z.string().nullish(),
- interval: zTimeInterval.default('day'),
- range: zRange,
- filters: z.array(zChartEventFilter).optional(),
- shareId: z.string().optional(),
- id: z.string().optional(),
- })
- )
- .query(({ input, ctx }) => getRetentionChart(ctx.report, input)),
-
- getProfiles: protectedProcedure
- .input(
- z.object({
- projectId: z.string(),
- date: z.string().describe('The date for the data point (ISO string)'),
- interval: zTimeInterval.default('day'),
- series: zChartSeries,
- breakdowns: z.record(z.string(), z.string()).optional(),
- })
- )
- .query(({ input }) => getChartBucketProfiles(input)),
-
- getFunnelProfiles: protectedProcedure
- .input(
- z.object({
- projectId: z.string(),
- startDate: z.string().nullish(),
- endDate: z.string().nullish(),
- series: zChartSeries,
- stepIndex: z.number().describe('0-based index of the funnel step'),
- showDropoffs: z
- .boolean()
- .optional()
- .default(false)
- .describe(
- 'If true, show users who dropped off at this step. If false, show users who completed at least this step.'
- ),
- funnelWindow: z.number().optional(),
- funnelGroup: z.string().optional(),
- breakdowns: z.array(z.object({ name: z.string() })).optional(),
- breakdownValues: z.array(z.string()).optional(),
- range: zRange,
- })
- )
- .query(({ input }) => getFunnelStepProfiles(input)),
-});
diff --git a/packages/trpc/src/routers/chat.ts b/packages/trpc/src/routers/chat.ts
deleted file mode 100644
index 55459e29a..000000000
--- a/packages/trpc/src/routers/chat.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-// Dissolved into @openpanel/core's assistant module (M5-005): the model
-// whitelist and provider-availability helper moved to
-// packages/core/src/modules/assistant/assistant.constants.ts.
-// @openpanel/validation's chat.ts is now a re-export shim of that file (same
-// shape as @openpanel/validation's import.validation.ts since M5-004), so
-// this router keeps resolving the same symbols unchanged.
-import {
- getAvailableChatModels,
- PREFERRED_DEFAULT_MODEL_ID,
-} from '@openpanel/validation';
-import { createTRPCRouter, protectedProcedure } from '../trpc';
-
-/**
- * Chat config — provider availability is derived from the API process's env
- * vars and returned to the client so the model picker only shows models the
- * server can actually serve.
- *
- * The Better Agent app still registers every model in the whitelist (it's
- * built eagerly at import time); this filter only governs what the UI offers.
- */
-export const chatRouter = createTRPCRouter({
- models: protectedProcedure.query(() => {
- const providers = {
- openai: Boolean(process.env.OPENAI_API_KEY),
- anthropic: Boolean(process.env.ANTHROPIC_API_KEY),
- };
- const models = getAvailableChatModels(providers);
- const preferred = models.find((m) => m.id === PREFERRED_DEFAULT_MODEL_ID);
- const defaultModelId = preferred?.id ?? models[0]?.id ?? null;
- return {
- providers,
- models,
- defaultModelId,
- };
- }),
-});
diff --git a/packages/trpc/src/routers/client.ts b/packages/trpc/src/routers/client.ts
deleted file mode 100644
index ed7312410..000000000
--- a/packages/trpc/src/routers/client.ts
+++ /dev/null
@@ -1,110 +0,0 @@
-// Dissolved into @openpanel/core's client module (M6-002): the CRUD and
-// mutation bodies moved to
-// packages/core/src/modules/client/client.service.ts. This router stays
-// (DELEGATE PATTERN) — it keeps V1's protectedProcedure stack (session/
-// access/logger/rate-limit middleware) and delegates every handler body to
-// core's client functions, same as organization's router does (M6-001).
-import {
- createClientForOrganization,
- deleteClientForOrganization,
- getClientById,
- getClientsByProjectId,
- updateClientForOrganization,
-} from '@openpanel/core';
-import { z } from 'zod';
-import { getClientAccess, requireOrganizationAdmin } from '../access';
-import { TRPCForbiddenError } from '../errors';
-import { createTRPCRouter, protectedProcedure } from '../trpc';
-
-export const clientRouter = createTRPCRouter({
- list: protectedProcedure
- .input(
- z.object({
- projectId: z.string(),
- })
- )
- .query(async ({ input }) => {
- return getClientsByProjectId(input.projectId);
- }),
- update: protectedProcedure
- .input(
- z.object({
- id: z.string(),
- name: z.string(),
- })
- )
- .mutation(async ({ input, ctx }) => {
- const access = await getClientAccess({
- userId: ctx.session.userId,
- clientId: input.id,
- });
-
- if (!access) {
- throw new TRPCForbiddenError('You do not have access to this client');
- }
-
- const client = await getClientById(input.id);
- if (!client) {
- throw new TRPCForbiddenError('Client not found');
- }
-
- return updateClientForOrganization(input.id, client.organizationId, {
- name: input.name,
- });
- }),
- create: protectedProcedure
- .input(
- z.object({
- name: z.string(),
- projectId: z.string(),
- organizationId: z.string(),
- type: z.enum(['read', 'write', 'root']).optional(),
- })
- )
- .mutation(async ({ input, ctx }) => {
- // Minting an ingestion credential - a `root` one at the caller's choosing
- // - is admin-tier, not something any org member should be able to do.
- await requireOrganizationAdmin({
- userId: ctx.session.userId,
- organizationId: input.organizationId,
- message: 'Only organization admins can create API clients',
- });
-
- const created = await createClientForOrganization(input.organizationId, {
- name: input.name,
- projectId: input.projectId,
- type: input.type,
- });
-
- if (!created) {
- throw new TRPCForbiddenError(
- 'Project not found or does not belong to your organization'
- );
- }
-
- return { ...created.client, secret: created.secret };
- }),
- remove: protectedProcedure
- .input(
- z.object({
- id: z.string(),
- })
- )
- .mutation(async ({ input, ctx }) => {
- const client = await getClientById(input.id);
-
- if (!client?.organizationId) {
- throw new TRPCForbiddenError('You do not have access to this client');
- }
-
- // Revoking a credential breaks ingestion for whoever is using it.
- await requireOrganizationAdmin({
- userId: ctx.session.userId,
- organizationId: client.organizationId,
- message: 'Only organization admins can delete API clients',
- });
-
- await deleteClientForOrganization(input.id, client.organizationId);
- return true;
- }),
-});
diff --git a/packages/trpc/src/routers/cohort.ts b/packages/trpc/src/routers/cohort.ts
deleted file mode 100644
index 8a7f69464..000000000
--- a/packages/trpc/src/routers/cohort.ts
+++ /dev/null
@@ -1,318 +0,0 @@
-// Dissolved into @openpanel/core's cohort module (M5-003): the compute
-// functions, the ClickHouse read path and the producer wrapper
-// (`enqueueCohortCompute`) moved to packages/core/src/modules/cohort/cohort.service.ts
-// — db cannot hold producers (ADR-007). This router stays (DELEGATE
-// PATTERN): it keeps V1's protectedProcedure stack (session/access/logger/
-// rate-limit middleware) and its own Prisma cohort CRUD untouched, and
-// delegates every compute/ClickHouse call to the core service.
-//
-// The enqueue itself stays inline here, against @openpanel/queue's
-// cohortComputeQueue directly — same as gsc's router does for
-// `gscProjectBackfill` (M5-002). @openpanel/queue imports @openpanel/core for
-// its logger, so core cannot import @openpanel/queue back; the canonical,
-// ctx.queues-based wrapper is `CohortService.enqueueCompute`, used once this
-// router's core twin (cohort.rpc.ts) goes live.
-import {
- computeCohort,
- countCohort,
- deleteCohortMembership,
- getCohortCount,
- getCohortEventsPerDay,
- getCohortMemberEvents,
- getCohortMemberRoutes,
- getCohortMembers,
- listCohortMemberProfiles,
-} from '@openpanel/core';
-import { db } from '@openpanel/db';
-import { cohortComputeQueue } from '@openpanel/queue';
-import {
- type CohortDefinition,
- zChartEventFilter,
- zCohortDefinition,
- zCohortInput,
- zCohortUpdate,
-} from '@openpanel/validation';
-import { z } from 'zod';
-import { getProjectAccess, requireProjectAccess } from '../access';
-import { TRPCForbiddenError, TRPCNotFoundError } from '../errors';
-import { createTRPCRouter, protectedProcedure } from '../trpc';
-
-// Same dedup scheme as core's CohortService.enqueueCompute
-// (packages/core/src/modules/cohort/cohort.service.ts) — deduplication, not
-// jobId, to avoid the retention-vs-dedup deadlock that file documents.
-async function enqueueCohortCompute(cohortId: string): Promise<void> {
- await cohortComputeQueue.add(
- 'cohortCompute',
- { cohortId },
- { deduplication: { id: `cohort-${cohortId}` } }
- );
-}
-
-export const cohortRouter = createTRPCRouter({
- list: protectedProcedure
- .input(
- z.object({
- projectId: z.string(),
- includeCount: z.boolean().optional().default(false),
- })
- )
- .query(async ({ input }) => {
- const cohorts = await db.cohort.findMany({
- where: { projectId: input.projectId },
- orderBy: { createdAt: 'desc' },
- });
-
- if (input.includeCount) {
- return cohorts.map((cohort) => ({
- ...cohort,
- currentCount: cohort.profileCount ?? 0,
- }));
- }
-
- return cohorts;
- }),
-
- get: protectedProcedure
- .input(z.object({ id: z.string() }))
- .query(async ({ input, ctx }) => {
- const cohort = await db.cohort.findUnique({
- where: { id: input.id },
- });
-
- if (!cohort) {
- throw new TRPCNotFoundError('Cohort not found');
- }
-
- const access = await getProjectAccess({
- projectId: cohort.projectId,
- userId: ctx.session.userId!,
- });
-
- if (!access) {
- throw new TRPCForbiddenError('You do not have access to this cohort');
- }
-
- return cohort;
- }),
-
- create: protectedProcedure.input(zCohortInput).mutation(async ({ input }) => {
- const cohort = await db.cohort.create({
- data: {
- name: input.name,
- description: input.description,
- projectId: input.projectId,
- definition: input.definition,
- isStatic: input.isStatic,
- },
- });
-
- await enqueueCohortCompute(cohort.id);
-
- return cohort;
- }),
-
- update: protectedProcedure
- .input(zCohortUpdate)
- .mutation(async ({ input, ctx }) => {
- const { id, ...data } = input;
-
- const existingCohort = await db.cohort.findUnique({ where: { id } });
-
- if (!existingCohort) {
- throw new TRPCNotFoundError('Cohort not found');
- }
-
- await requireProjectAccess({
- userId: ctx.session.userId!,
- projectId: existingCohort.projectId,
- level: 'write',
- });
-
- const cohort = await db.cohort.update({
- where: { id },
- data: {
- ...(data.name && { name: data.name }),
- ...(data.description !== undefined && {
- description: data.description,
- }),
- ...(data.definition && { definition: data.definition }),
- ...(data.isStatic !== undefined && { isStatic: data.isStatic }),
- },
- });
-
- if (data.definition) {
- await enqueueCohortCompute(cohort.id);
- }
-
- return cohort;
- }),
-
- delete: protectedProcedure
- .input(z.object({ id: z.string() }))
- .mutation(async ({ input, ctx }) => {
- const cohort = await db.cohort.findUnique({ where: { id: input.id } });
-
- if (!cohort) {
- throw new TRPCNotFoundError('Cohort not found');
- }
-
- await requireProjectAccess({
- userId: ctx.session.userId!,
- projectId: cohort.projectId,
- level: 'write',
- });
-
- await db.cohort.delete({ where: { id: input.id } });
-
- deleteCohortMembership(input.id, cohort.projectId).catch((err) => {
- console.error('Failed to cleanup cohort CH data:', err);
- });
-
- return { success: true };
- }),
-
- listProfiles: protectedProcedure
- .input(
- z.object({
- projectId: z.string(),
- cohortId: z.string(),
- cursor: z.number().optional(),
- take: z.number().default(50),
- search: z.string().optional(),
- filters: z.array(zChartEventFilter).default([]),
- })
- )
- .query(async ({ input }) => {
- const { data, count } = await listCohortMemberProfiles(input);
- return {
- data,
- meta: { count, pageCount: input.take },
- };
- }),
-
- mostEvents: protectedProcedure
- .input(z.object({ projectId: z.string(), cohortId: z.string() }))
- .query(({ input }) =>
- getCohortMemberEvents(input.projectId, input.cohortId)
- ),
-
- eventsPerDay: protectedProcedure
- .input(z.object({ projectId: z.string(), cohortId: z.string() }))
- .query(({ input }) =>
- getCohortEventsPerDay(input.projectId, input.cohortId)
- ),
-
- popularRoutes: protectedProcedure
- .input(z.object({ projectId: z.string(), cohortId: z.string() }))
- .query(({ input }) =>
- getCohortMemberRoutes(input.projectId, input.cohortId)
- ),
-
- getCount: protectedProcedure
- .input(z.object({ cohortId: z.string() }))
- .query(async ({ input, ctx }) => {
- const cohort = await db.cohort.findUnique({
- where: { id: input.cohortId },
- });
-
- if (!cohort) {
- throw new TRPCNotFoundError('Cohort not found');
- }
-
- const access = await getProjectAccess({
- projectId: cohort.projectId,
- userId: ctx.session.userId!,
- });
-
- if (!access) {
- throw new TRPCForbiddenError('You do not have access to this cohort');
- }
-
- const count = await getCohortCount(input.cohortId, cohort.projectId);
- return { count };
- }),
-
- preview: protectedProcedure
- .input(
- z.object({
- projectId: z.string(),
- definition: zCohortDefinition,
- })
- )
- .query(async ({ input }) => {
- const definition = input.definition as CohortDefinition;
- const count = await countCohort(input.projectId, definition);
- const sampleProfiles = await computeCohort(
- input.projectId,
- definition,
- 10
- );
- return { count, sampleProfiles };
- }),
-
- exportProfiles: protectedProcedure
- .input(
- z.object({
- cohortId: z.string(),
- limit: z.number().int().min(1).max(10_000).default(10_000),
- offset: z.number().int().min(0).default(0),
- })
- )
- .query(async ({ input, ctx }) => {
- const cohort = await db.cohort.findUnique({
- where: { id: input.cohortId },
- });
-
- if (!cohort) {
- throw new TRPCNotFoundError('Cohort not found');
- }
-
- const access = await getProjectAccess({
- projectId: cohort.projectId,
- userId: ctx.session.userId!,
- });
-
- if (!access) {
- throw new TRPCForbiddenError('You do not have access to this cohort');
- }
-
- const result = await getCohortMembers(input.cohortId, cohort.projectId, {
- limit: input.limit,
- offset: input.offset,
- });
-
- return {
- profileIds: result.profileIds,
- total: result.total,
- cohortName: cohort.name,
- };
- }),
-
- refresh: protectedProcedure
- .input(z.object({ cohortId: z.string() }))
- .mutation(async ({ input, ctx }) => {
- const cohort = await db.cohort.findUnique({
- where: { id: input.cohortId },
- });
-
- if (!cohort) {
- throw new TRPCNotFoundError('Cohort not found');
- }
-
- await requireProjectAccess({
- userId: ctx.session.userId!,
- projectId: cohort.projectId,
- level: 'write',
- });
-
- if (cohort.isStatic) {
- throw new Error(
- 'Cannot refresh static cohorts — they are one-time snapshots'
- );
- }
-
- await enqueueCohortCompute(input.cohortId);
-
- return { success: true };
- }),
-});
diff --git a/packages/trpc/src/routers/conversation.ts b/packages/trpc/src/routers/conversation.ts
deleted file mode 100644
index 05fe669cd..000000000
--- a/packages/trpc/src/routers/conversation.ts
+++ /dev/null
@@ -1,136 +0,0 @@
-// Dissolved into @openpanel/core's conversation module (M5-006): the CRUD
-// itself moved to packages/core/src/modules/conversation/conversation.service.ts.
-// This router stays (DELEGATE PATTERN) — it keeps V1's protectedProcedure
-// stack (session/access/logger/rate-limit middleware) and delegates every
-// handler body to core's conversation functions, same as cohort's router
-// does for its compute functions (M5-003).
-import {
- deleteConversation,
- getConversationById,
- listConversations,
- upsertConversationTitle,
-} from '@openpanel/core';
-import { getOrganizationByProjectIdCached } from '@openpanel/core';
-import { TRPCError } from '@trpc/server';
-import { z } from 'zod';
-import { getProjectAccess, requireProjectAccess } from '../access';
-import { TRPCForbiddenError } from '../errors';
-import { createTRPCRouter, protectedProcedure } from '../trpc';
-
-/**
- * Conversation management — listing, fetching, renaming, deleting.
- * Conversation creation is implicit (lazy) on the first message via the
- * /ai/chat controller, so there's no `create` here.
- *
- * All procedures enforce ownership via `userId === session.userId` so a
- * user can never read or mutate another user's conversations.
- */
-export const conversationRouter = createTRPCRouter({
- list: protectedProcedure
- .input(
- z.object({
- projectId: z.string(),
- limit: z.number().min(1).max(200).default(50),
- })
- )
- .query(async ({ input, ctx }) => {
- const access = await getProjectAccess({
- projectId: input.projectId,
- userId: ctx.session.userId,
- });
- if (!access) {
- throw new TRPCForbiddenError('You do not have access to this project');
- }
- return listConversations({
- projectId: input.projectId,
- userId: ctx.session.userId,
- limit: input.limit,
- });
- }),
-
- get: protectedProcedure
- .input(z.object({ id: z.string() }))
- .query(async ({ input, ctx }) => {
- const conv = await getConversationById(input.id, { withMessages: true });
- if (!conv || conv.userId !== ctx.session.userId) {
- throw new TRPCError({
- code: 'NOT_FOUND',
- message: 'Conversation not found',
- });
- }
- return conv;
- }),
-
- rename: protectedProcedure
- // A conversation belongs to the caller, not to the project - titling your
- // own chat is not a project mutation. Ownership is enforced below.
- .meta({ readOnlyMutation: true })
- .input(
- z.object({
- id: z.string(),
- title: z.string().min(1).max(80),
- /**
- * Required so we can create the row if the titler finishes
- * before the agent's first persistence save. When the row
- * already exists this is ignored — the ownership check
- * below still applies. `organizationId` is derived from the
- * project, not trusted from the client.
- */
- projectId: z.string(),
- })
- )
- .mutation(async ({ input, ctx }) => {
- // If the conversation already exists, enforce ownership. If it
- // doesn't, verify the caller has access to the project being
- // created under before letting the upsert create a fresh row.
- const conv = await getConversationById(input.id);
- if (conv) {
- if (conv.userId !== ctx.session.userId) {
- throw new TRPCError({
- code: 'NOT_FOUND',
- message: 'Conversation not found',
- });
- }
- } else {
- await requireProjectAccess({
- userId: ctx.session.userId,
- projectId: input.projectId,
- level: 'read',
- });
- }
- // Derive organizationId from the project — we never trust a
- // client-supplied value here, even if the caller has access to
- // the project (they'd still be able to tag the conversation with
- // an unrelated org id).
- const organization = await getOrganizationByProjectIdCached(
- input.projectId
- );
- if (!organization) {
- throw new TRPCError({
- code: 'NOT_FOUND',
- message: 'Project not found',
- });
- }
- return upsertConversationTitle({
- id: input.id,
- title: input.title,
- projectId: input.projectId,
- organizationId: organization.id,
- userId: ctx.session.userId,
- });
- }),
-
- delete: protectedProcedure
- .input(z.object({ id: z.string() }))
- .mutation(async ({ input, ctx }) => {
- const conv = await getConversationById(input.id);
- if (!conv || conv.userId !== ctx.session.userId) {
- throw new TRPCError({
- code: 'NOT_FOUND',
- message: 'Conversation not found',
- });
- }
- await deleteConversation(input.id);
- return { success: true };
- }),
-});
diff --git a/packages/trpc/src/routers/dashboard.ts b/packages/trpc/src/routers/dashboard.ts
deleted file mode 100644
index e3e4516d9..000000000
--- a/packages/trpc/src/routers/dashboard.ts
+++ /dev/null
@@ -1,108 +0,0 @@
-// Dissolved into @openpanel/core's dashboard module (M7-006): the reads plus
-// the create/update/delete mutation bodies moved to
-// packages/core/src/modules/dashboard/dashboard.service.ts. This router
-// stays (DELEGATE PATTERN) — it keeps V1's `protectedProcedure` stack and
-// delegates every handler body to core's dashboard functions, same as
-// overview.ts/chart.ts.
-
-import {
- createDashboard,
- deleteDashboard,
- getDashboardById,
- getDashboardByIdOrThrow,
- getDashboardsByProjectId,
- updateDashboard,
-} from '@openpanel/core';
-import { z } from 'zod';
-import { getProjectAccess, requireProjectAccess } from '../access';
-import { TRPCForbiddenError, TRPCNotFoundError } from '../errors';
-import { createTRPCRouter, protectedProcedure } from '../trpc';
-
-export const dashboardRouter = createTRPCRouter({
- list: protectedProcedure
- .input(
- z.object({
- projectId: z.string(),
- })
- )
- .query(({ input }) => {
- return getDashboardsByProjectId(input.projectId);
- }),
- byId: protectedProcedure
- .input(
- z.object({
- id: z.string(),
- projectId: z.string(),
- })
- )
- .query(async ({ input, ctx }) => {
- const access = await getProjectAccess({
- projectId: input.projectId,
- userId: ctx.session.userId,
- });
-
- if (!access) {
- throw new TRPCForbiddenError('You do not have access to this project');
- }
-
- const dashboard = await getDashboardById(input.id, input.projectId);
-
- if (!dashboard) {
- throw new TRPCNotFoundError('Dashboard not found');
- }
-
- return dashboard;
- }),
- create: protectedProcedure
- .input(
- z.object({
- name: z.string(),
- projectId: z.string(),
- })
- )
- .mutation(async ({ input, ctx }) => {
- await requireProjectAccess({
- userId: ctx.session.userId,
- projectId: input.projectId,
- level: 'write',
- });
-
- return createDashboard(input);
- }),
- update: protectedProcedure
- .input(
- z.object({
- id: z.string(),
- name: z.string(),
- })
- )
- .mutation(async ({ input, ctx }) => {
- const dashboard = await getDashboardByIdOrThrow(input.id);
-
- await requireProjectAccess({
- userId: ctx.session.userId,
- projectId: dashboard.projectId,
- level: 'write',
- });
-
- return updateDashboard(input);
- }),
- delete: protectedProcedure
- .input(
- z.object({
- id: z.string(),
- forceDelete: z.boolean().optional(),
- })
- )
- .mutation(async ({ input, ctx }) => {
- const dashboard = await getDashboardByIdOrThrow(input.id);
-
- await requireProjectAccess({
- userId: ctx.session.userId,
- projectId: dashboard.projectId,
- level: 'write',
- });
-
- return deleteDashboard(input);
- }),
-});
diff --git a/packages/trpc/src/routers/email.ts b/packages/trpc/src/routers/email.ts
deleted file mode 100644
index aeef07d6a..000000000
--- a/packages/trpc/src/routers/email.ts
+++ /dev/null
@@ -1,121 +0,0 @@
-// Dissolved into @openpanel/core's email module (M6-004): `emailCategories`
-// moved to packages/core/src/modules/email/email.constants.ts. This router
-// stays (DELEGATE PATTERN) — it keeps V1's protectedProcedure stack and its
-// own db calls (core's email module is R + C only, no service — see
-// core's email.rpc.ts header), reading the same `emailCategories` core now
-// owns instead of @openpanel/constants' copy.
-
-import { emailCategories } from '@openpanel/core';
-import { db } from '@openpanel/db';
-import { verifyUnsubscribeToken } from '@openpanel/email';
-import { z } from 'zod';
-import { TRPCBadRequestError } from '../errors';
-import { createTRPCRouter, protectedProcedure, publicProcedure } from '../trpc';
-
-export const emailRouter = createTRPCRouter({
- unsubscribe: publicProcedure
- .input(
- z.object({
- email: z.string().email(),
- category: z.string(),
- token: z.string(),
- }),
- )
- .mutation(async ({ input }) => {
- const { email, category, token } = input;
-
- // Verify token
- if (!verifyUnsubscribeToken(email, category, token)) {
- throw new TRPCBadRequestError('Invalid unsubscribe link');
- }
-
- // Upsert the unsubscribe record
- await db.emailUnsubscribe.upsert({
- where: {
- email_category: {
- email,
- category,
- },
- },
- create: {
- email,
- category,
- },
- update: {},
- });
-
- return { success: true };
- }),
-
- getPreferences: protectedProcedure.query(async ({ ctx }) => {
- if (!ctx.session.userId || !ctx.session.user?.email) {
- throw new Error('User not authenticated');
- }
-
- const email = ctx.session.user.email;
-
- // Get all unsubscribe records for this user
- const unsubscribes = await db.emailUnsubscribe.findMany({
- where: {
- email,
- },
- select: {
- category: true,
- },
- });
-
- const unsubscribedCategories = new Set(unsubscribes.map((u) => u.category));
-
- // Return object with all categories, true = subscribed (not unsubscribed)
- const preferences: Record<string, boolean> = {};
- for (const [category] of Object.entries(emailCategories)) {
- preferences[category] = !unsubscribedCategories.has(category);
- }
-
- return preferences;
- }),
-
- updatePreferences: protectedProcedure
- .input(
- z.object({
- categories: z.record(z.string(), z.boolean()),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- if (!ctx.session.userId || !ctx.session.user?.email) {
- throw new Error('User not authenticated');
- }
-
- const email = ctx.session.user.email;
-
- // Process each category
- for (const [category, subscribed] of Object.entries(input.categories)) {
- if (subscribed) {
- // User wants to subscribe - delete unsubscribe record if exists
- await db.emailUnsubscribe.deleteMany({
- where: {
- email,
- category,
- },
- });
- } else {
- // User wants to unsubscribe - upsert unsubscribe record
- await db.emailUnsubscribe.upsert({
- where: {
- email_category: {
- email,
- category,
- },
- },
- create: {
- email,
- category,
- },
- update: {},
- });
- }
- }
-
- return { success: true };
- }),
-});
diff --git a/packages/trpc/src/routers/event.ts b/packages/trpc/src/routers/event.ts
deleted file mode 100644
index c63d48255..000000000
--- a/packages/trpc/src/routers/event.ts
+++ /dev/null
@@ -1,217 +0,0 @@
-// Dissolved into @openpanel/core's event module (M7-002): the ClickHouse
-// queries moved to packages/core/src/modules/event/event.service.ts and
-// src/event.sql.ts. This router stays (DELEGATE PATTERN) — it keeps V1's
-// protectedProcedure stack and delegates every handler body to core's event
-// functions, same as session.ts.
-//
-// `bots` was a `publicProcedure` that let anonymous callers in on the mere
-// existence of a ShareOverview row; ADR-011 (§9, P6 row) makes it
-// `protectedProcedure`. The pages* procedures still read `pagesService`,
-// which the overview module owns (its own task).
-
-import {
- getBotEventsPage,
- getChartStartEndDate,
- getConversionEventNames,
- getConversionListPage,
- getEventById,
- getEventDetails,
- getEventListPage,
- getSettingsForProject,
- getTopOrigins,
- pagesService,
- updateEventMeta,
-} from '@openpanel/core';
-import {
- zChartEventFilter,
- zRange,
- zTimeInterval,
-} from '@openpanel/validation';
-import { TRPCError } from '@trpc/server';
-import { z } from 'zod';
-import { createTRPCRouter, protectedProcedure } from '../trpc';
-
-const zEventRef = z.object({
- id: z.string(),
- projectId: z.string(),
- createdAt: z.date().optional(),
-});
-
-function eventNotFound() {
- return new TRPCError({ code: 'NOT_FOUND', message: 'Event not found' });
-}
-
-export const eventRouter = createTRPCRouter({
- updateEventMeta: protectedProcedure
- .input(
- z.object({
- projectId: z.string(),
- name: z.string(),
- icon: z.string().optional(),
- color: z.string().optional(),
- conversion: z.boolean().optional(),
- })
- )
- .mutation(({ input }) => updateEventMeta(input)),
-
- byId: protectedProcedure.input(zEventRef).query(async ({ input }) => {
- const res = await getEventById(input);
- if (!res) {
- throw eventNotFound();
- }
- return res;
- }),
-
- details: protectedProcedure.input(zEventRef).query(async ({ input }) => {
- const res = await getEventDetails(input);
- if (!res) {
- throw eventNotFound();
- }
- return res;
- }),
-
- events: protectedProcedure
- .input(
- z.object({
- projectId: z.string(),
- profileId: z.string().nullish(),
- sessionId: z.string().nullish(),
- groupId: z.string().nullish(),
- cohortId: z.string().nullish(),
- cursor: z.string().nullish(),
- filters: z.array(zChartEventFilter).default([]),
- startDate: z.date().nullish(),
- endDate: z.date().nullish(),
- events: z.array(z.string()).nullish(),
- columnVisibility: z.record(z.string(), z.boolean()).nullish(),
- })
- )
- .query(({ input }) => getEventListPage(input)),
-
- conversionNames: protectedProcedure
- .input(z.object({ projectId: z.string() }))
- .query(({ input: { projectId } }) => getConversionEventNames(projectId)),
-
- conversions: protectedProcedure
- .input(
- z.object({
- projectId: z.string(),
- cursor: z.string().nullish(),
- startDate: z.date().nullish(),
- endDate: z.date().nullish(),
- events: z.array(z.string()).nullish(),
- columnVisibility: z.record(z.string(), z.boolean()).nullish(),
- })
- )
- .query(({ input }) => getConversionListPage(input)),
-
- bots: protectedProcedure
- .input(
- z.object({
- projectId: z.string(),
- cursor: z.number().optional(),
- limit: z.number().default(8),
- })
- )
- .query(({ input }) => getBotEventsPage(input)),
-
- pages: protectedProcedure
- .input(
- z.object({
- projectId: z.string(),
- cursor: z.number().optional(),
- take: z.number().min(1).optional(),
- search: z.string().optional(),
- range: zRange,
- interval: zTimeInterval,
- })
- )
- .query(async ({ input }) => {
- const { timezone } = await getSettingsForProject(input.projectId);
- const { startDate, endDate } = getChartStartEndDate(input, timezone);
- return pagesService.getTopPages({
- projectId: input.projectId,
- startDate,
- endDate,
- timezone,
- search: input.search,
- limit: input.take,
- });
- }),
-
- pagesTimeseries: protectedProcedure
- .input(
- z.object({
- projectId: z.string(),
- range: zRange,
- interval: zTimeInterval,
- })
- )
- .query(async ({ input }) => {
- const { timezone } = await getSettingsForProject(input.projectId);
- const { startDate, endDate } = getChartStartEndDate(input, timezone);
- return pagesService.getPageTimeseries({
- projectId: input.projectId,
- startDate,
- endDate,
- timezone,
- interval: input.interval,
- });
- }),
-
- previousPages: protectedProcedure
- .input(
- z.object({
- projectId: z.string(),
- range: zRange,
- interval: zTimeInterval,
- })
- )
- .query(async ({ input }) => {
- const { timezone } = await getSettingsForProject(input.projectId);
- const { startDate, endDate } = getChartStartEndDate(input, timezone);
-
- const startMs = new Date(startDate).getTime();
- const endMs = new Date(endDate).getTime();
- const duration = endMs - startMs;
-
- const prevEnd = new Date(startMs - 1);
- const prevStart = new Date(prevEnd.getTime() - duration);
- const fmt = (d: Date) => d.toISOString().slice(0, 19).replace('T', ' ');
-
- return pagesService.getTopPages({
- projectId: input.projectId,
- startDate: fmt(prevStart),
- endDate: fmt(prevEnd),
- timezone,
- });
- }),
-
- pageTimeseries: protectedProcedure
- .input(
- z.object({
- projectId: z.string(),
- range: zRange,
- interval: zTimeInterval,
- origin: z.string(),
- path: z.string(),
- })
- )
- .query(async ({ input }) => {
- const { timezone } = await getSettingsForProject(input.projectId);
- const { startDate, endDate } = getChartStartEndDate(input, timezone);
- return pagesService.getPageTimeseries({
- projectId: input.projectId,
- startDate,
- endDate,
- timezone,
- interval: input.interval,
- filterOrigin: input.origin,
- filterPath: input.path,
- });
- }),
-
- origin: protectedProcedure
- .input(z.object({ projectId: z.string() }))
- .query(({ input: { projectId } }) => getTopOrigins(projectId)),
-});
diff --git a/packages/trpc/src/routers/group.ts b/packages/trpc/src/routers/group.ts
deleted file mode 100644
index c971cda25..000000000
--- a/packages/trpc/src/routers/group.ts
+++ /dev/null
@@ -1,107 +0,0 @@
-// Dissolved into @openpanel/core's group module (M7-002): the ClickHouse
-// queries moved to packages/core/src/modules/group/group.service.ts and
-// src/group.sql.ts. This router stays (DELEGATE PATTERN) — it keeps V1's
-// protectedProcedure stack and delegates every handler body to core's group
-// functions, same as session.ts.
-
-import {
- createGroup,
- deleteGroup,
- getGroupActivity,
- getGroupById,
- getGroupListPage,
- getGroupMemberGrowth,
- getGroupMemberProfilesPage,
- getGroupMetrics,
- getGroupMostEvents,
- getGroupPopularRoutes,
- getGroupPropertyKeys,
- getGroupsByIds,
- getGroupTypes,
- updateGroup,
-} from '@openpanel/core';
-import { zCreateGroup, zUpdateGroup } from '@openpanel/validation';
-import { z } from 'zod';
-import { createTRPCRouter, protectedProcedure } from '../trpc';
-
-const zGroupRef = z.object({ id: z.string(), projectId: z.string() });
-
-export const groupRouter = createTRPCRouter({
- list: protectedProcedure
- .input(
- z.object({
- projectId: z.string(),
- cursor: z.number().optional(),
- take: z.number().default(50),
- search: z.string().optional(),
- type: z.string().optional(),
- })
- )
- .query(({ input }) => getGroupListPage(input)),
-
- byId: protectedProcedure
- .input(zGroupRef)
- .query(({ input: { id, projectId } }) => getGroupById(id, projectId)),
-
- create: protectedProcedure
- .input(zCreateGroup)
- .mutation(({ input }) => createGroup(input)),
-
- update: protectedProcedure
- .input(zUpdateGroup)
- .mutation(({ input: { id, projectId, ...data } }) =>
- updateGroup(id, projectId, data)
- ),
-
- delete: protectedProcedure
- .input(zGroupRef)
- .mutation(({ input: { id, projectId } }) => deleteGroup(id, projectId)),
-
- types: protectedProcedure
- .input(z.object({ projectId: z.string() }))
- .query(({ input: { projectId } }) => getGroupTypes(projectId)),
-
- metrics: protectedProcedure
- .input(zGroupRef)
- .query(({ input: { id, projectId } }) => getGroupMetrics(id, projectId)),
-
- activity: protectedProcedure
- .input(zGroupRef)
- .query(({ input: { id, projectId } }) => getGroupActivity(id, projectId)),
-
- memberGrowth: protectedProcedure
- .input(zGroupRef)
- .query(({ input: { id, projectId } }) =>
- getGroupMemberGrowth(id, projectId)
- ),
-
- listProfiles: protectedProcedure
- .input(
- z.object({
- projectId: z.string(),
- groupId: z.string(),
- cursor: z.number().optional(),
- take: z.number().default(50),
- search: z.string().optional(),
- })
- )
- .query(({ input }) => getGroupMemberProfilesPage(input)),
-
- mostEvents: protectedProcedure
- .input(zGroupRef)
- .query(({ input: { id, projectId } }) => getGroupMostEvents(id, projectId)),
-
- popularRoutes: protectedProcedure
- .input(zGroupRef)
- .query(({ input: { id, projectId } }) =>
- getGroupPopularRoutes(id, projectId)
- ),
-
- properties: protectedProcedure
- .input(z.object({ projectId: z.string() }))
- .query(({ input: { projectId } }) => getGroupPropertyKeys(projectId)),
-
- listByIds: protectedProcedure
- .input(z.object({ projectId: z.string(), ids: z.array(z.string()) }))
- .query(({ input: { projectId, ids } }) => getGroupsByIds(projectId, ids)),
-});
diff --git a/packages/trpc/src/routers/gsc.ts b/packages/trpc/src/routers/gsc.ts
deleted file mode 100644
index d86bd6df9..000000000
--- a/packages/trpc/src/routers/gsc.ts
+++ /dev/null
@@ -1,252 +0,0 @@
-// Dissolved into @openpanel/core's gsc module (M5-002): the OAuth token
-// lifecycle, the Search Console client, the ClickHouse read path and the
-// AI/search-engine breakdown logic moved to
-// packages/core/src/modules/gsc/gsc.service.ts. This router stays
-// (DELEGATE PATTERN): it keeps V1's protectedProcedure stack (session/access/
-// logger/rate-limit middleware) and its own gscConnection CRUD untouched, and
-// delegates every read/write of GSC data to the core service.
-import {
- Arctic,
- disconnectGscConnection,
- getGscAiEngines,
- getGscCannibalization,
- getGscConnection,
- getGscOverview,
- getGscPageDetails,
- getGscPages,
- getGscPreviousOverview,
- getGscQueries,
- getGscQueryDetails,
- getGscSearchEngines,
- googleGsc,
- listGscSites,
- resolveGscDateRange,
- selectGscSite,
-} from '@openpanel/core';
-import { gscQueue } from '@openpanel/queue';
-import { zRange, zTimeInterval } from '@openpanel/validation';
-import { z } from 'zod';
-import { getProjectAccess, requireProjectAccess } from '../access';
-import { TRPCForbiddenError } from '../errors';
-import { createTRPCRouter, protectedProcedure } from '../trpc';
-
-const OAUTH_COOKIE_MAX_AGE_SECONDS = 60 * 10;
-const GSC_OVERVIEW_INTERVALS = ['day', 'week', 'month'] as const;
-
-const zGscDateInput = z.object({
- projectId: z.string(),
- range: zRange,
- interval: zTimeInterval.optional().default('day'),
- startDate: z.string().nullish(),
- endDate: z.string().nullish(),
-});
-
-function toOverviewInterval(
- interval: string
-): (typeof GSC_OVERVIEW_INTERVALS)[number] {
- return (GSC_OVERVIEW_INTERVALS as readonly string[]).includes(interval)
- ? (interval as (typeof GSC_OVERVIEW_INTERVALS)[number])
- : 'day';
-}
-
-async function requireRead(userId: string, projectId: string) {
- const access = await getProjectAccess({ userId, projectId });
- if (!access) {
- throw new TRPCForbiddenError('You do not have access to this project');
- }
-}
-
-export const gscRouter = createTRPCRouter({
- getConnection: protectedProcedure
- .input(z.object({ projectId: z.string() }))
- .query(async ({ input, ctx }) => {
- await requireRead(ctx.session.userId, input.projectId);
- return getGscConnection(input.projectId);
- }),
-
- initiateOAuth: protectedProcedure
- .input(z.object({ projectId: z.string() }))
- .mutation(async ({ input, ctx }) => {
- await requireProjectAccess({
- userId: ctx.session.userId,
- projectId: input.projectId,
- level: 'write',
- });
-
- const state = Arctic.generateState();
- const codeVerifier = Arctic.generateCodeVerifier();
- const url = googleGsc.createAuthorizationURL(state, codeVerifier, [
- 'https://www.googleapis.com/auth/webmasters.readonly',
- ]);
- url.searchParams.set('access_type', 'offline');
- url.searchParams.set('prompt', 'consent');
-
- const cookieOpts = { maxAge: OAUTH_COOKIE_MAX_AGE_SECONDS, signed: true };
- ctx.setCookie('gsc_oauth_state', state, cookieOpts);
- ctx.setCookie('gsc_code_verifier', codeVerifier, cookieOpts);
- ctx.setCookie('gsc_project_id', input.projectId, cookieOpts);
-
- return { url: url.toString() };
- }),
-
- getSites: protectedProcedure
- .input(z.object({ projectId: z.string() }))
- .query(async ({ input, ctx }) => {
- await requireRead(ctx.session.userId, input.projectId);
- return listGscSites(input.projectId);
- }),
-
- selectSite: protectedProcedure
- .input(z.object({ projectId: z.string(), siteUrl: z.string() }))
- .mutation(async ({ input, ctx }) => {
- await requireProjectAccess({
- userId: ctx.session.userId,
- projectId: input.projectId,
- level: 'write',
- });
-
- await selectGscSite(input.projectId, input.siteUrl);
-
- await gscQueue.add('gscProjectBackfill', {
- type: 'gscProjectBackfill',
- payload: { projectId: input.projectId },
- });
-
- return { ok: true };
- }),
-
- disconnect: protectedProcedure
- .input(z.object({ projectId: z.string() }))
- .mutation(async ({ input, ctx }) => {
- await requireProjectAccess({
- userId: ctx.session.userId,
- projectId: input.projectId,
- level: 'write',
- });
-
- await disconnectGscConnection(input.projectId);
- return { ok: true };
- }),
-
- getOverview: protectedProcedure
- .input(zGscDateInput)
- .query(async ({ input, ctx }) => {
- await requireRead(ctx.session.userId, input.projectId);
- const { startDate, endDate } = await resolveGscDateRange(
- input.projectId,
- input
- );
- return getGscOverview(
- input.projectId,
- startDate,
- endDate,
- toOverviewInterval(input.interval)
- );
- }),
-
- getPages: protectedProcedure
- .input(
- zGscDateInput.extend({
- limit: z.number().min(1).max(10_000).optional().default(100),
- })
- )
- .query(async ({ input, ctx }) => {
- await requireRead(ctx.session.userId, input.projectId);
- const { startDate, endDate } = await resolveGscDateRange(
- input.projectId,
- input
- );
- return getGscPages(input.projectId, startDate, endDate, input.limit);
- }),
-
- getPageDetails: protectedProcedure
- .input(zGscDateInput.extend({ page: z.string() }))
- .query(async ({ input, ctx }) => {
- await requireRead(ctx.session.userId, input.projectId);
- const { startDate, endDate } = await resolveGscDateRange(
- input.projectId,
- input
- );
- return getGscPageDetails(input.projectId, input.page, startDate, endDate);
- }),
-
- getQueryDetails: protectedProcedure
- .input(zGscDateInput.extend({ query: z.string() }))
- .query(async ({ input, ctx }) => {
- await requireRead(ctx.session.userId, input.projectId);
- const { startDate, endDate } = await resolveGscDateRange(
- input.projectId,
- input
- );
- return getGscQueryDetails(
- input.projectId,
- input.query,
- startDate,
- endDate
- );
- }),
-
- getQueries: protectedProcedure
- .input(
- zGscDateInput.extend({
- limit: z.number().min(1).max(1000).optional().default(100),
- })
- )
- .query(async ({ input, ctx }) => {
- await requireRead(ctx.session.userId, input.projectId);
- const { startDate, endDate } = await resolveGscDateRange(
- input.projectId,
- input
- );
- return getGscQueries(input.projectId, startDate, endDate, input.limit);
- }),
-
- getSearchEngines: protectedProcedure
- .input(zGscDateInput)
- .query(async ({ input, ctx }) => {
- await requireRead(ctx.session.userId, input.projectId);
- const { startDate, endDate } = await resolveGscDateRange(
- input.projectId,
- input
- );
- return getGscSearchEngines(input.projectId, startDate, endDate);
- }),
-
- getAiEngines: protectedProcedure
- .input(zGscDateInput)
- .query(async ({ input, ctx }) => {
- await requireRead(ctx.session.userId, input.projectId);
- const { startDate, endDate } = await resolveGscDateRange(
- input.projectId,
- input
- );
- return getGscAiEngines(input.projectId, startDate, endDate);
- }),
-
- getPreviousOverview: protectedProcedure
- .input(zGscDateInput)
- .query(async ({ input, ctx }) => {
- await requireRead(ctx.session.userId, input.projectId);
- const { startDate, endDate } = await resolveGscDateRange(
- input.projectId,
- input
- );
- return getGscPreviousOverview(
- input.projectId,
- startDate,
- endDate,
- toOverviewInterval(input.interval)
- );
- }),
-
- getCannibalization: protectedProcedure
- .input(zGscDateInput)
- .query(async ({ input, ctx }) => {
- await requireRead(ctx.session.userId, input.projectId);
- const { startDate, endDate } = await resolveGscDateRange(
- input.projectId,
- input
- );
- return getGscCannibalization(input.projectId, startDate, endDate);
- }),
-});
diff --git a/packages/trpc/src/routers/import.ts b/packages/trpc/src/routers/import.ts
deleted file mode 100644
index 8171fa3b9..000000000
--- a/packages/trpc/src/routers/import.ts
+++ /dev/null
@@ -1,189 +0,0 @@
-import { z } from 'zod';
-
-import { db } from '@openpanel/db';
-import { importQueue } from '@openpanel/queue';
-import { zCreateImport } from '@openpanel/validation';
-
-import { getProjectAccess, requireProjectAccess } from '../access';
-import {
- TRPCForbiddenError,
- TRPCBadRequestError,
- TRPCNotFoundError,
-} from '../errors';
-import { createTRPCRouter, protectedProcedure } from '../trpc';
-
-export const importRouter = createTRPCRouter({
- list: protectedProcedure
- .input(z.object({ projectId: z.string() }))
- .query(async ({ input, ctx }) => {
- const access = await getProjectAccess({
- projectId: input.projectId,
- userId: ctx.session.userId,
- });
-
- if (!access) {
- throw new TRPCForbiddenError('You do not have access to this project');
- }
-
- return db.import.findMany({
- where: {
- projectId: input.projectId,
- },
- orderBy: {
- createdAt: 'desc',
- },
- });
- }),
-
- get: protectedProcedure
- .input(z.object({ id: z.string() }))
- .query(async ({ input, ctx }) => {
- const importRecord = await db.import.findUniqueOrThrow({
- where: {
- id: input.id,
- },
- include: {
- project: true,
- },
- });
-
- const access = await getProjectAccess({
- projectId: importRecord.projectId,
- userId: ctx.session.userId,
- });
-
- if (!access) {
- throw new TRPCForbiddenError('You do not have access to this import');
- }
-
- return importRecord;
- }),
-
- create: protectedProcedure
- .input(zCreateImport)
- .mutation(async ({ input, ctx }) => {
- await requireProjectAccess({
- userId: ctx.session.userId,
- projectId: input.projectId,
- level: 'write',
- });
-
- const organization = await db.organization.findFirst({
- where: {
- projects: {
- some: {
- id: input.projectId,
- },
- },
- },
- });
-
- if (!organization) {
- throw new TRPCNotFoundError(
- 'Could not start import, organization not found',
- );
- }
-
- if (!organization.isActive) {
- throw new TRPCBadRequestError(
- 'You cannot start an import without an active subscription!',
- );
- }
-
- // Create import record
- const importRecord = await db.import.create({
- data: {
- projectId: input.projectId,
- config: input.config,
- status: 'pending',
- },
- });
-
- // Add job to queue
- const job = await importQueue.add('import', {
- type: 'import',
- payload: {
- importId: importRecord.id,
- },
- });
-
- // Update import record with job ID
- await db.import.update({
- where: { id: importRecord.id },
- data: { jobId: job.id },
- });
-
- return {
- ...importRecord,
- jobId: job.id,
- };
- }),
-
- delete: protectedProcedure
- .input(z.object({ id: z.string() }))
- .mutation(async ({ input, ctx }) => {
- const importRecord = await db.import.findUniqueOrThrow({
- where: {
- id: input.id,
- },
- });
-
- await requireProjectAccess({
- userId: ctx.session.userId,
- projectId: importRecord.projectId,
- level: 'write',
- });
-
- if (importRecord.jobId) {
- const job = await importQueue.getJob(importRecord.jobId);
- if (job) {
- await job.remove();
- }
- }
-
- return db.import.delete({
- where: {
- id: input.id,
- },
- });
- }),
-
- retry: protectedProcedure
- .input(z.object({ id: z.string() }))
- .mutation(async ({ input, ctx }) => {
- const importRecord = await db.import.findUniqueOrThrow({
- where: {
- id: input.id,
- },
- });
-
- await requireProjectAccess({
- userId: ctx.session.userId,
- projectId: importRecord.projectId,
- level: 'write',
- });
-
- // Only allow retry for failed imports
- if (importRecord.status !== 'failed') {
- throw new Error('Only failed imports can be retried');
- }
-
- // Add new job to queue
- const job = await importQueue.add('import', {
- type: 'import',
- payload: {
- importId: importRecord.id,
- },
- });
-
- // Update import record
- return db.import.update({
- where: { id: importRecord.id },
- data: {
- jobId: job.id,
- status: 'pending',
- errorMessage: null,
- },
- });
- }),
-});
diff --git a/packages/trpc/src/routers/insight.ts b/packages/trpc/src/routers/insight.ts
deleted file mode 100644
index fd949c85f..000000000
--- a/packages/trpc/src/routers/insight.ts
+++ /dev/null
@@ -1,257 +0,0 @@
-// Dissolved into @openpanel/core's insight module (M5-001): the business
-// logic — the query/detection engine, the AI enrich/explain/narrative calls,
-// the digest and cleanup jobs — moved to
-// packages/core/src/modules/insight/insight.service.ts. This router stays
-// (DELEGATE PATTERN): it keeps V1's protectedProcedure stack (session/access/
-// logger/rate-limit middleware) untouched and delegates each handler body to
-// the core service.
-import { explainInsight, listAllInsights, listInsights } from '@openpanel/core';
-import { db } from '@openpanel/db';
-import type { InsightPayload } from '@openpanel/validation';
-import { z } from 'zod';
-import { getProjectAccess, requireProjectAccess } from '../access';
-import { TRPCForbiddenError } from '../errors';
-import { createTRPCRouter, protectedProcedure } from '../trpc';
-
-const DAY_MS = 24 * 60 * 60 * 1000;
-const EXPLAIN_COLUMNS = [
- 'referrer_name',
- 'country',
- 'device',
- 'utm_source',
-] as const;
-
-export const insightRouter = createTRPCRouter({
- list: protectedProcedure
- .input(
- z.object({
- projectId: z.string(),
- limit: z.number().min(1).max(100).optional().default(50),
- })
- )
- .query(async ({ input: { projectId, limit }, ctx }) => {
- const access = await getProjectAccess({
- userId: ctx.session.userId,
- projectId,
- });
-
- if (!access) {
- throw new TRPCForbiddenError('You do not have access to this project');
- }
-
- // Fetch more insights than needed to account for deduplication.
- // AI relevanceScore leads (un-enriched insights sort last via nulls:last),
- // with the statistical impactScore as the tiebreaker / fallback.
- const allInsights = await listInsights({
- projectId,
- limit: limit * 3,
- });
-
- // WindowKind priority: yesterday (1) > rolling_7d (2) > rolling_30d (3)
- const windowKindPriority: Record<string, number> = {
- yesterday: 1,
- rolling_7d: 2,
- rolling_30d: 3,
- };
-
- // Group by moduleKey + dimensionKey, keep only highest priority windowKind
- const deduplicated = new Map<string, (typeof allInsights)[0]>();
- for (const insight of allInsights) {
- const key = `${insight.moduleKey}:${insight.dimensionKey}`;
- const existing = deduplicated.get(key);
- const currentPriority = windowKindPriority[insight.windowKind] ?? 999;
- const existingPriority = existing
- ? (windowKindPriority[existing.windowKind] ?? 999)
- : 999;
-
- // Keep if no existing, or if current has higher priority (lower number)
- if (!existing || currentPriority < existingPriority) {
- deduplicated.set(key, insight);
- }
- }
-
- // Convert back to array, sort by relevanceScore (impactScore fallback),
- // and limit
- const insights = Array.from(deduplicated.values())
- .sort(
- (a, b) =>
- (b.relevanceScore ?? -1) - (a.relevanceScore ?? -1) ||
- (b.impactScore ?? 0) - (a.impactScore ?? 0)
- )
- .slice(0, limit)
- .map(({ impactScore, ...rest }) => rest); // Remove impactScore from response
-
- return insights;
- }),
-
- listAll: protectedProcedure
- .input(
- z.object({
- projectId: z.string(),
- limit: z.number().min(1).max(500).optional().default(200),
- })
- )
- .query(async ({ input: { projectId, limit }, ctx }) => {
- const access = await getProjectAccess({
- userId: ctx.session.userId,
- projectId,
- });
-
- if (!access) {
- throw new TRPCForbiddenError('You do not have access to this project');
- }
-
- return listAllInsights({ projectId, limit });
- }),
-
- // Phase 5: the "why". Decompose the insight's change across referrer/country/
- // device/utm (current vs baseline window), pull nearby references, and have
- // the AI explain which sub-segment drove it. On-demand (a button); the result
- // is cached per insight version so repeat clicks don't re-bill the LLM.
- explain: protectedProcedure
- .input(z.object({ insightId: z.string() }))
- .mutation(async ({ input: { insightId }, ctx }) => {
- const insight = await db.projectInsight.findUniqueOrThrow({
- where: { id: insightId },
- select: {
- projectId: true,
- title: true,
- aiSummary: true,
- summary: true,
- dimensionKey: true,
- windowKind: true,
- windowStart: true,
- windowEnd: true,
- payload: true,
- lastUpdatedAt: true,
- },
- });
-
- // Reads an existing insight and explains it. Nothing about the project
- // changes, so a read-level member may do it.
- await requireProjectAccess({
- userId: ctx.session.userId,
- projectId: insight.projectId,
- level: 'read',
- });
-
- // Current window from the insight; baseline = same span immediately before.
- const end = insight.windowEnd ?? new Date();
- const start = insight.windowStart ?? new Date(end.getTime() - 7 * DAY_MS);
- const spanMs = Math.max(end.getTime() - start.getTime(), DAY_MS);
- const baseEnd = new Date(start.getTime());
- const baseStart = new Date(start.getTime() - spanMs);
- const iso = (d: Date) => d.toISOString();
-
- const { getSegmentDailySeriesCore, getTrafficBreakdownCore } =
- await import('@openpanel/core');
-
- const breakdowns = await Promise.all(
- EXPLAIN_COLUMNS.map(async (column) => {
- const [cur, base] = await Promise.all([
- getTrafficBreakdownCore({
- projectId: insight.projectId,
- column,
- startDate: iso(start),
- endDate: iso(end),
- }),
- getTrafficBreakdownCore({
- projectId: insight.projectId,
- column,
- startDate: iso(baseStart),
- endDate: iso(baseEnd),
- }),
- ]);
- const compact = (rows: typeof cur) =>
- rows.slice(0, 8).map((r) => ({
- name: r.name ?? null,
- sessions: Number(r.sessions ?? 0),
- }));
- return { column, current: compact(cur), baseline: compact(base) };
- })
- );
-
- // Daily series for the insight's own segment, so the model can read the
- // shape of the change (a one-off spike vs sustained growth) instead of
- // only the current-vs-baseline totals. Best-effort: skip on page/entry
- // insights (events-table metrics) or anything we can't resolve.
- const payload = insight.payload as InsightPayload | null;
- const segment = payload?.dimensions?.[0];
- const primaryMetric = payload?.primaryMetric ?? 'sessions';
- let dailySeries:
- | {
- metric: string;
- current: { date: string; sessions: number }[];
- baseline: { date: string; sessions: number }[];
- }
- | undefined;
-
- if (segment?.key && segment.value) {
- const [curSeries, baseSeries] = await Promise.all([
- getSegmentDailySeriesCore({
- projectId: insight.projectId,
- column: segment.key,
- value: segment.value,
- startDate: iso(start),
- endDate: iso(end),
- }),
- getSegmentDailySeriesCore({
- projectId: insight.projectId,
- column: segment.key,
- value: segment.value,
- startDate: iso(baseStart),
- endDate: iso(baseEnd),
- }),
- ]);
-
- const toMetric = (points: typeof curSeries) =>
- points.map((p) => ({
- date: p.date.slice(0, 10),
- sessions: primaryMetric === 'pageviews' ? p.pageviews : p.sessions,
- }));
-
- if (curSeries.length > 0) {
- dailySeries = {
- metric: primaryMetric,
- current: toMetric(curSeries),
- baseline: toMetric(baseSeries),
- };
- }
- }
-
- const references = await db.reference.findMany({
- where: {
- projectId: insight.projectId,
- date: {
- gte: new Date(start.getTime() - 3 * DAY_MS),
- lte: new Date(end.getTime() + DAY_MS),
- },
- },
- orderBy: { date: 'desc' },
- take: 10,
- select: { title: true, date: true },
- });
-
- // `explainInsight` owns the cache-aside (keyed by insight id +
- // lastUpdatedAt, so a recompute invalidates it automatically).
- const cacheKey = `insight-explain:${insightId}:${insight.lastUpdatedAt.getTime()}`;
-
- return explainInsight(
- {
- insight: {
- title: insight.aiSummary ?? insight.title,
- dimension: insight.dimensionKey,
- window: insight.windowKind,
- summary: insight.summary ?? undefined,
- },
- dailySeries,
- breakdowns,
- references: references.map((r) => ({
- title: r.title,
- date: r.date.toISOString().slice(0, 10),
- })),
- },
- cacheKey
- );
- }),
-});
diff --git a/packages/trpc/src/routers/integration.ts b/packages/trpc/src/routers/integration.ts
deleted file mode 100644
index cb0413a94..000000000
--- a/packages/trpc/src/routers/integration.ts
+++ /dev/null
@@ -1,86 +0,0 @@
-// Dissolved into @openpanel/core's integration module (M6-006): the CRUD,
-// Slack OAuth install and connection-test bodies moved to
-// packages/core/src/modules/integration/integration.service.ts. This router
-// stays (DELEGATE PATTERN) — it keeps V1's protectedProcedure stack
-// (session/access/logger/rate-limit middleware) and delegates every handler
-// body to core's integration functions, same as notification's router does
-// (M6-005).
-
-import {
- createOrUpdateSlackIntegration,
- deleteIntegration,
- getIntegrationById,
- listIntegrationsForProject,
- testExportIntegrationConnection,
- testIntegrationConnection,
- upsertIntegration,
-} from '@openpanel/core';
-import {
- zCreateGCSExportIntegration,
- zCreateS3ExportIntegration,
- zCreateSlackIntegration,
- zIntegrationConfig,
-} from '@openpanel/validation';
-import { z } from 'zod';
-import { createTRPCRouter, protectedProcedure } from '../trpc';
-
-export const integrationRouter = createTRPCRouter({
- get: protectedProcedure
- .input(z.object({ id: z.string() }))
- .query(({ input, ctx }) =>
- getIntegrationById(ctx.session.userId, input.id)
- ),
- list: protectedProcedure
- .input(z.object({ projectId: z.string() }))
- .query(({ input, ctx }) =>
- listIntegrationsForProject(ctx.session.userId, input.projectId)
- ),
- createOrUpdateSlack: protectedProcedure
- .input(zCreateSlackIntegration)
- .mutation(({ input, ctx }) =>
- createOrUpdateSlackIntegration(ctx.session.userId, input)
- ),
- // Generic create/update for any form-configured integration. Per-type
- // behavior lives in the server plugin; no switch here.
- createOrUpdate: protectedProcedure
- .input(
- z.object({
- id: z.string().optional(),
- name: z.string().min(1),
- projectId: z.string().min(1),
- config: zIntegrationConfig,
- })
- )
- .mutation(({ input, ctx }) => upsertIntegration(ctx.session.userId, input)),
- // Back-compat alias for the export forms; delegates to the same generic path.
- // TODO: remove once the dashboard calls `createOrUpdate` directly.
- createOrUpdateExport: protectedProcedure
- .input(z.union([zCreateS3ExportIntegration, zCreateGCSExportIntegration]))
- .mutation(({ input, ctx }) => upsertIntegration(ctx.session.userId, input)),
- // Generic, registry-driven connection test. Gated on project write access:
- // it makes the server connect outbound to a caller-supplied destination with
- // caller-supplied credentials, so it must not be reachable by anyone who
- // merely holds a session.
- testConnection: protectedProcedure
- .input(
- z.object({
- projectId: z.string().min(1),
- config: zIntegrationConfig,
- })
- )
- .mutation(({ input, ctx }) =>
- testIntegrationConnection(ctx.session.userId, input)
- ),
- // Back-compat alias for the export forms; same gate as `testConnection`.
- // TODO: remove once the dashboard calls `testConnection` directly.
- testExportConnection: protectedProcedure
- .input(z.union([zCreateS3ExportIntegration, zCreateGCSExportIntegration]))
- .mutation(({ input, ctx }) =>
- testExportIntegrationConnection(ctx.session.userId, input)
- ),
- delete: protectedProcedure
- .input(z.object({ id: z.string() }))
- .mutation(({ input: { id }, ctx }) =>
- deleteIntegration(ctx.session.userId, id)
- ),
-});
diff --git a/packages/trpc/src/routers/notification.ts b/packages/trpc/src/routers/notification.ts
deleted file mode 100644
index 6b83ec6ac..000000000
--- a/packages/trpc/src/routers/notification.ts
+++ /dev/null
@@ -1,74 +0,0 @@
-// Dissolved into @openpanel/core's notification module (M6-005): the CRUD
-// and rule-write bodies moved to
-// packages/core/src/modules/notification/notification.service.ts. This
-// router stays (DELEGATE PATTERN) — it keeps V1's protectedProcedure stack
-// (session/access/logger/rate-limit middleware) and delegates every handler
-// body to core's notification functions, same as organization's router does
-// (M6-001).
-
-import {
- createOrUpdateNotificationRule,
- deleteNotificationRule,
- getNotificationRuleByIdOrThrow,
- getNotificationRulesByProjectId,
- listNotificationRules,
- listNotifications,
-} from '@openpanel/core';
-import { zCreateNotificationRule } from '@openpanel/validation';
-import { z } from 'zod';
-
-import { requireProjectAccess } from '../access';
-import { createTRPCRouter, protectedProcedure } from '../trpc';
-
-export const notificationRouter = createTRPCRouter({
- list: protectedProcedure
- .input(z.object({ projectId: z.string() }))
- .query(async ({ input }) => {
- return listNotifications(input.projectId);
- }),
- rules: protectedProcedure
- .input(z.object({ projectId: z.string() }))
- .query(async ({ input }) => {
- return listNotificationRules(input.projectId);
- }),
- createOrUpdateRule: protectedProcedure
- .input(zCreateNotificationRule)
- .mutation(async ({ input, ctx }) => {
- // Clear the cache for the project
- await getNotificationRulesByProjectId.clear(input.projectId);
-
- // Authorize the target project (covers both create and update; the
- // create branch previously had no access check) and verify every
- // connected integration belongs to this project or is a legacy
- // org-wide one in the same org — never another project's.
- await requireProjectAccess({
- userId: ctx.session.userId,
- projectId: input.projectId,
- level: 'write',
- });
-
- if (input.id) {
- const existing = await getNotificationRuleByIdOrThrow(input.id);
- await requireProjectAccess({
- userId: ctx.session.userId,
- projectId: existing.projectId,
- level: 'write',
- });
- }
-
- return createOrUpdateNotificationRule(input);
- }),
- deleteRule: protectedProcedure
- .input(z.object({ id: z.string() }))
- .mutation(async ({ input: { id }, ctx }) => {
- const rule = await getNotificationRuleByIdOrThrow(id);
-
- await requireProjectAccess({
- userId: ctx.session.userId,
- projectId: rule.projectId,
- level: 'write',
- });
-
- return deleteNotificationRule(id);
- }),
-});
diff --git a/packages/trpc/src/routers/onboarding.ts b/packages/trpc/src/routers/onboarding.ts
deleted file mode 100644
index c010de227..000000000
--- a/packages/trpc/src/routers/onboarding.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-// Dissolved into @openpanel/core's onboarding module (M6-003): the
-// org+project+client creation and the "can I skip onboarding" check moved to
-// packages/core/src/modules/onboarding/onboarding.service.ts. This router
-// stays (DELEGATE PATTERN) — it keeps V1's protectedProcedure stack
-// (session/access/logger/rate-limit middleware) and delegates every handler
-// body to core's onboarding functions, same as organization's router does
-// (M6-001).
-import { canSkipOnboarding, createOnboardingProject } from '@openpanel/core';
-import { zOnboardingProject } from '@openpanel/validation';
-import { createTRPCRouter, protectedProcedure, publicProcedure } from '../trpc';
-
-export const onboardingRouter = createTRPCRouter({
- skipOnboardingCheck: publicProcedure.query(({ ctx }) =>
- canSkipOnboarding(ctx.session.userId)
- ),
- project: protectedProcedure
- .input(zOnboardingProject)
- .mutation(({ input, ctx }) =>
- createOnboardingProject(input, ctx.session.userId!)
- ),
-});
diff --git a/packages/trpc/src/routers/organization.ts b/packages/trpc/src/routers/organization.ts
deleted file mode 100644
index 6b0c8a5d7..000000000
--- a/packages/trpc/src/routers/organization.ts
+++ /dev/null
@@ -1,254 +0,0 @@
-// Dissolved into @openpanel/core's organization module (M6-001): the CRUD
-// and mutation bodies moved to
-// packages/core/src/modules/organization/organization.service.ts (delete.service.ts
-// folded in with it). This router stays (DELEGATE PATTERN) — it keeps V1's
-// protectedProcedure stack (session/access/logger/rate-limit middleware) and
-// delegates every handler body to core's organization functions, same as
-// conversation's router does (M5-006).
-import {
- cancelOrganizationDeletion,
- getInviteById,
- getInviteOrThrow,
- getMembers,
- getOrganizationById,
- getOrganizations,
- inviteUserToOrganization,
- getInvites as loadInvites,
- removeOrganizationMember,
- revokeInvite as revokeInviteById,
- scheduleOrganizationDeletion,
- updateOrganization,
- updateOrganizationMemberAccess,
-} from '@openpanel/core';
-import {
- zEditOrganization,
- zInviteUser,
- zUpdateMemberAccess,
-} from '@openpanel/validation';
-import { z } from 'zod';
-import { getOrganizationAccess } from '../access';
-import { TRPCBadRequestError, TRPCForbiddenError } from '../errors';
-import {
- createTRPCRouter,
- protectedProcedure,
- protectedProcedureWithoutAccess,
- publicProcedure,
- rateLimitMiddleware,
-} from '../trpc';
-
-export const organizationRouter = createTRPCRouter({
- get: protectedProcedure
- .input(z.object({ organizationId: z.string() }))
- .query(async ({ input }) => {
- return getOrganizationById(input.organizationId);
- }),
-
- list: protectedProcedure.query(async ({ ctx }) => {
- return getOrganizations(ctx.session.userId);
- }),
-
- // Membership-exempt on purpose: any logged-in user may ask whether they have
- // access to a given org. Returns null when they're not a member (instead of
- // throwing), which the org-layout guard uses to render a not-found page.
- myAccess: protectedProcedureWithoutAccess
- .input(z.object({ organizationId: z.string() }))
- .query(async ({ input, ctx }) => {
- const access = await getOrganizationAccess({
- userId: ctx.session.userId,
- organizationId: input.organizationId,
- });
- if (!access) {
- return null;
- }
- return { role: access.role };
- }),
-
- update: protectedProcedure
- .input(zEditOrganization)
- .mutation(async ({ input, ctx }) => {
- const access = await getOrganizationAccess({
- userId: ctx.session.userId,
- organizationId: input.id,
- });
-
- if (access?.role !== 'org:admin') {
- throw new TRPCForbiddenError('You do not have access to this project');
- }
-
- return updateOrganization(input);
- }),
-
- delete: protectedProcedure
- .input(z.object({ organizationId: z.string() }))
- .mutation(async ({ input, ctx }) => {
- const access = await getOrganizationAccess({
- userId: ctx.session.userId,
- organizationId: input.organizationId,
- });
-
- if (access?.role !== 'org:admin') {
- throw new TRPCForbiddenError(
- 'You do not have access to this organization'
- );
- }
-
- // Schedules the organization and all of its projects for deletion in 24
- // hours (cancelable until then); throws if a live paid subscription
- // hasn't been cancelled yet. The hourly `delete` cron removes the
- // projects (and their ClickHouse events) and the organization in a
- // single pass once their `deleteAt` has passed.
- await scheduleOrganizationDeletion(input.organizationId);
-
- return true;
- }),
-
- cancelDeletion: protectedProcedure
- .input(z.object({ organizationId: z.string() }))
- .mutation(async ({ input, ctx }) => {
- const access = await getOrganizationAccess({
- userId: ctx.session.userId,
- organizationId: input.organizationId,
- });
-
- if (access?.role !== 'org:admin') {
- throw new TRPCForbiddenError(
- 'You do not have access to this organization'
- );
- }
-
- await cancelOrganizationDeletion(input.organizationId);
-
- return true;
- }),
-
- inviteUser: protectedProcedure
- .input(zInviteUser)
- .mutation(async ({ input, ctx }) => {
- const access = await getOrganizationAccess({
- userId: ctx.session.userId,
- organizationId: input.organizationId,
- });
-
- if (access?.role !== 'org:admin') {
- throw new TRPCForbiddenError('You do not have access to this project');
- }
-
- return inviteUserToOrganization({
- organizationId: input.organizationId,
- email: input.email,
- role: input.role,
- access: input.access ?? [],
- invitedById: ctx.session.userId,
- });
- }),
- revokeInvite: protectedProcedure
- .input(
- z.object({
- inviteId: z.string(),
- })
- )
- .mutation(async ({ input, ctx }) => {
- const invite = await getInviteOrThrow(input.inviteId);
-
- const access = await getOrganizationAccess({
- userId: ctx.session.userId,
- organizationId: invite.organizationId,
- });
-
- if (access?.role !== 'org:admin') {
- throw new TRPCForbiddenError('You do not have access to this project');
- }
-
- return revokeInviteById(input.inviteId);
- }),
-
- removeMember: protectedProcedure
- .input(
- z.object({
- organizationId: z.string(),
- userId: z.string(),
- id: z.string(),
- })
- )
- .mutation(async ({ input, ctx }) => {
- const access = await getOrganizationAccess({
- userId: ctx.session.userId,
- organizationId: input.organizationId,
- });
-
- if (access?.role !== 'org:admin') {
- throw new TRPCForbiddenError('You do not have access to this project');
- }
-
- await removeOrganizationMember({
- organizationId: input.organizationId,
- memberId: input.id,
- targetUserId: input.userId,
- requestedByUserId: ctx.session.userId,
- });
- }),
-
- updateMemberAccess: protectedProcedure
- .input(zUpdateMemberAccess)
- .mutation(async ({ input, ctx }) => {
- if (input.userId === ctx.session.userId) {
- throw new TRPCForbiddenError('You cannot update your own access');
- }
-
- const access = await getOrganizationAccess({
- userId: ctx.session.userId,
- organizationId: input.organizationId,
- });
-
- if (access?.role !== 'org:admin') {
- throw new TRPCForbiddenError('You do not have access to this project');
- }
-
- return updateOrganizationMemberAccess({
- organizationId: input.organizationId,
- targetUserId: input.userId,
- access: input.access,
- });
- }),
-
- members: protectedProcedure
- .input(z.object({ organizationId: z.string() }))
- .query(async ({ input, ctx }) => {
- const access = await getOrganizationAccess({
- userId: ctx.session.userId,
- organizationId: input.organizationId,
- });
- if (access?.role !== 'org:admin') {
- throw new TRPCForbiddenError('You do not have access to this project');
- }
- return getMembers(input.organizationId);
- }),
-
- invitations: protectedProcedure
- .input(z.object({ organizationId: z.string() }))
- .query(async ({ input, ctx }) => {
- const access = await getOrganizationAccess({
- userId: ctx.session.userId,
- organizationId: input.organizationId,
- });
- if (access?.role !== 'org:admin') {
- throw new TRPCForbiddenError('You do not have access to this project');
- }
- return loadInvites(input.organizationId);
- }),
-
- getInvite: publicProcedure
- .use(
- rateLimitMiddleware({
- max: 5,
- windowMs: 30_000,
- })
- )
- .input(z.object({ inviteId: z.string().optional() }))
- .query(async ({ input }) => {
- if (!input.inviteId) {
- throw new TRPCBadRequestError('Invite ID is required');
- }
- return getInviteById(input.inviteId);
- }),
-});
diff --git a/packages/trpc/src/routers/overview.ts b/packages/trpc/src/routers/overview.ts
deleted file mode 100644
index d09c5a79a..000000000
--- a/packages/trpc/src/routers/overview.ts
+++ /dev/null
@@ -1,454 +0,0 @@
-// Dissolved into @openpanel/core's overview module (M7-005): the ClickHouse
-// queries moved to packages/core/src/modules/overview/src/{overview,pages}.sql.ts
-// and the handler bodies to overview.service.ts/pages.service.ts. This router
-// stays (DELEGATE PATTERN) — it keeps V1's `publicProcedure` /
-// `overviewProcedure` (share-or-session) / `cacheMiddleware` stacks and
-// delegates every handler body to core's overview functions, same as chart.ts.
-//
-// `liveData`'s queries used to live inline here; they moved to
-// `overviewService.getLiveData` with everything else this module runs.
-
-import {
- getChartPrevStartEndDate,
- getChartStartEndDate,
- getConversionEventNames,
- getOrganizationSubscriptionChartEndDate,
- getReferrerSpikes,
- getSettingsForProject,
- overviewService,
- runFilterCommand,
- validateOverviewShareAccess,
- zGetMapDataInput,
- zGetMetricsInput,
- zGetTopEventsInput,
- zGetTopGenericInput,
- zGetTopGenericSeriesInput,
- zGetTopLinkOutInput,
- zGetTopPagesInput,
- zGetUserJourneyInput,
-} from '@openpanel/core';
-import { eventBuffer } from '@openpanel/queue/src/buffers';
-import {
- type IChartRange,
- pageContextSchema,
- zRange,
-} from '@openpanel/validation';
-import { format } from 'date-fns';
-import { z } from 'zod';
-import { getProjectAccess } from '../access';
-import { TRPCAccessError, TRPCForbiddenError } from '../errors';
-import {
- cacheMiddleware,
- createTRPCRouter,
- protectedProcedure,
- publicProcedure,
-} from '../trpc';
-
-const cacher = cacheMiddleware((input, opts) => {
- const range = input.range as IChartRange;
- if (opts.path === 'overview.liveData') {
- return 0;
- }
-
- switch (range) {
- case '30min':
- case 'today':
- case 'lastHour':
- case 'last24h':
- return 1;
- default:
- return 1;
- }
-});
-
-const overviewProcedure = publicProcedure.use(
- async ({ ctx, next, getRawInput }) => {
- const rawInput = (await getRawInput()) as {
- projectId: string;
- shareId?: string;
- };
-
- if (rawInput.shareId) {
- // validateOverviewShareAccess only throws for missing/non-public shares.
- // A password-protected share without the unlock cookie comes back as
- // `{ isValid: false }`, so ignoring the result leaves the data open to
- // anyone holding the link. The chart path does the same check.
- const shareValidation = await validateOverviewShareAccess(
- rawInput.shareId,
- rawInput.projectId,
- {
- cookies: ctx.cookies,
- session: ctx.session?.userId
- ? { userId: ctx.session.userId }
- : undefined,
- }
- );
- if (!shareValidation.isValid) {
- throw new TRPCForbiddenError('You do not have access to this share');
- }
- } else {
- if (!ctx.session?.userId) {
- throw new TRPCAccessError('Authentication required');
- }
- const access = await getProjectAccess({
- projectId: rawInput.projectId,
- userId: ctx.session.userId,
- });
- if (!access) {
- throw new TRPCForbiddenError('You do not have access to this project');
- }
- }
-
- return next();
- }
-);
-
-function getCurrentAndPrevious<
- T extends {
- startDate?: string | null;
- endDate?: string | null;
- range: IChartRange;
- projectId: string;
- },
->(input: T, fetchPrevious: boolean, timezone: string) {
- const current = getChartStartEndDate(input, timezone);
- const previous = getChartPrevStartEndDate(current);
-
- return async <R>(
- fn: (input: T & { startDate: string; endDate: string }) => Promise<R>
- ): Promise<{
- current: R;
- previous: R | null;
- }> => {
- const endDate = await getOrganizationSubscriptionChartEndDate(
- input.projectId,
- current.endDate
- );
- if (endDate) {
- current.endDate = endDate;
- // Only expired trial scenarios
- if (new Date(current.startDate) > new Date(current.endDate)) {
- current.startDate = current.endDate;
- }
- }
- const res = await Promise.all([
- fn({
- ...input,
- startDate: current.startDate,
- endDate: current.endDate,
- }),
- fetchPrevious
- ? fn({
- ...input,
- startDate: previous.startDate,
- endDate: previous.endDate,
- })
- : Promise.resolve(null),
- ]);
-
- return {
- current: res[0],
- previous: res[1],
- };
- };
-}
-
-export const overviewRouter = createTRPCRouter({
- liveVisitors: overviewProcedure
- .input(z.object({ projectId: z.string(), shareId: z.string().optional() }))
- .query(async ({ input }) => {
- return eventBuffer.getActiveVisitorCount(input.projectId);
- }),
-
- liveData: overviewProcedure
- .input(z.object({ projectId: z.string(), shareId: z.string().optional() }))
- .use(cacher)
- .query(async ({ input }) => {
- return overviewService.getLiveData(input.projectId);
- }),
- stats: overviewProcedure
- .input(
- zGetMetricsInput.omit({ startDate: true, endDate: true }).extend({
- startDate: z.string().nullish(),
- endDate: z.string().nullish(),
- range: zRange,
- shareId: z.string().optional(),
- })
- )
- .use(cacher)
- .query(async ({ input }) => {
- const { timezone } = await getSettingsForProject(input.projectId);
- const { current, previous } = await getCurrentAndPrevious(
- { ...input, timezone },
- true,
- timezone
- )(overviewService.getMetrics.bind(overviewService));
- return {
- metrics: {
- ...current.metrics,
- prev_bounce_rate: previous?.metrics.bounce_rate || null,
- prev_unique_visitors: previous?.metrics.unique_visitors || null,
- prev_total_screen_views: previous?.metrics.total_screen_views || null,
- prev_avg_session_duration:
- previous?.metrics.avg_session_duration || null,
- prev_views_per_session: previous?.metrics.views_per_session || null,
- prev_total_sessions: previous?.metrics.total_sessions || null,
- prev_total_revenue: previous?.metrics.total_revenue || null,
- },
- series: current.series.map((item, index) => {
- const prev = previous?.series[index];
- return {
- ...item,
- date: format(item.date, 'yyyy-MM-dd HH:mm:ss'),
- prev_bounce_rate: prev?.bounce_rate,
- prev_unique_visitors: prev?.unique_visitors,
- prev_total_screen_views: prev?.total_screen_views,
- prev_avg_session_duration: prev?.avg_session_duration,
- prev_views_per_session: prev?.views_per_session,
- prev_total_sessions: prev?.total_sessions,
- prev_total_revenue: prev?.total_revenue,
- };
- }),
- };
- }),
-
- getReferrerSpikes: overviewProcedure
- .input(
- zGetMetricsInput.omit({ startDate: true, endDate: true }).extend({
- startDate: z.string().nullish(),
- endDate: z.string().nullish(),
- range: zRange,
- shareId: z.string().optional(),
- })
- )
- .use(cacher)
- .query(async ({ input }) => {
- const { timezone } = await getSettingsForProject(input.projectId);
- const { startDate, endDate } = getChartStartEndDate(input, timezone);
- const clusters = await getReferrerSpikes({
- projectId: input.projectId,
- filters: input.filters,
- interval: input.interval,
- startDate,
- endDate,
- timezone,
- });
- // Reformat every spike date (and the cluster's anchor) to match
- // overview.stats' series date format, so markers x-align with the
- // chart's data points (xScale matches by Date identity).
- const fmt = (iso: string) => format(new Date(iso), 'yyyy-MM-dd HH:mm:ss');
- return clusters.map((cluster) => ({
- anchorDate: fmt(cluster.anchorDate),
- spikes: cluster.spikes.map((spike) => ({
- ...spike,
- date: fmt(spike.date),
- })),
- }));
- }),
-
- topPages: overviewProcedure
- .input(
- zGetTopPagesInput.omit({ startDate: true, endDate: true }).extend({
- startDate: z.string().nullish(),
- endDate: z.string().nullish(),
- range: zRange,
- mode: z.enum(['page', 'entry', 'exit', 'bot']),
- shareId: z.string().optional(),
- })
- )
- .use(cacher)
- .query(async ({ input }) => {
- const { timezone } = await getSettingsForProject(input.projectId);
- const { current } = await getCurrentAndPrevious(
- { ...input },
- false,
- timezone
- )(async (input) => {
- if (input.mode === 'page') {
- return overviewService.getTopPages({ ...input, timezone });
- }
-
- if (input.mode === 'bot') {
- return Promise.resolve([]);
- }
-
- return overviewService.getTopEntryExit({
- ...input,
- mode: input.mode,
- timezone,
- });
- });
-
- return current;
- }),
-
- topGeneric: overviewProcedure
- .input(
- zGetTopGenericInput.omit({ startDate: true, endDate: true }).extend({
- startDate: z.string().nullish(),
- endDate: z.string().nullish(),
- range: zRange,
- shareId: z.string().optional(),
- })
- )
- .use(cacher)
- .query(async ({ input }) => {
- const { timezone } = await getSettingsForProject(input.projectId);
- const { current } = await getCurrentAndPrevious(
- { ...input, timezone },
- false,
- timezone
- )(overviewService.getTopGeneric.bind(overviewService));
-
- return current;
- }),
-
- topGenericSeries: overviewProcedure
- .input(
- zGetTopGenericSeriesInput
- .omit({ startDate: true, endDate: true })
- .extend({
- startDate: z.string().nullish(),
- endDate: z.string().nullish(),
- range: zRange,
- shareId: z.string().optional(),
- })
- )
- .use(cacher)
- .query(async ({ input }) => {
- const { timezone } = await getSettingsForProject(input.projectId);
- const { current } = await getCurrentAndPrevious(
- { ...input, timezone },
- false,
- timezone
- )(overviewService.getTopGenericSeries.bind(overviewService));
-
- return current;
- }),
-
- userJourney: overviewProcedure
- .input(
- zGetUserJourneyInput.omit({ startDate: true, endDate: true }).extend({
- startDate: z.string().nullish(),
- endDate: z.string().nullish(),
- range: zRange,
- steps: z.number().min(2).max(10).default(5).optional(),
- shareId: z.string().optional(),
- })
- )
- .use(cacher)
- .query(async ({ input }) => {
- const { timezone } = await getSettingsForProject(input.projectId);
- const { current } = await getCurrentAndPrevious(
- { ...input, timezone },
- false,
- timezone
- )(async (input) => {
- return overviewService.getUserJourney({
- ...input,
- steps: input.steps ?? 5,
- timezone,
- });
- });
-
- return current;
- }),
-
- topEvents: overviewProcedure
- .input(
- zGetTopEventsInput.omit({ startDate: true, endDate: true }).extend({
- startDate: z.string().nullish(),
- endDate: z.string().nullish(),
- range: zRange,
- shareId: z.string().optional(),
- })
- )
- .use(cacher)
- .query(async ({ input }) => {
- const { timezone } = await getSettingsForProject(input.projectId);
- const { current } = await getCurrentAndPrevious(
- { ...input, timezone },
- false,
- timezone
- )(overviewService.getTopEvents.bind(overviewService));
-
- return current;
- }),
-
- topConversions: overviewProcedure
- .input(
- z.object({
- projectId: z.string(),
- shareId: z.string().optional(),
- })
- )
- .query(async ({ input }) => {
- return getConversionEventNames(input.projectId);
- }),
-
- topLinkOut: overviewProcedure
- .input(
- zGetTopLinkOutInput.omit({ startDate: true, endDate: true }).extend({
- startDate: z.string().nullish(),
- endDate: z.string().nullish(),
- range: zRange,
- shareId: z.string().optional(),
- })
- )
- .use(cacher)
- .query(async ({ input }) => {
- const { timezone } = await getSettingsForProject(input.projectId);
- const { current } = await getCurrentAndPrevious(
- { ...input, timezone },
- false,
- timezone
- )(overviewService.getTopLinkOut.bind(overviewService));
-
- return current;
- }),
-
- // One-shot AI command bar — converts natural-language requests
- // ("show 7 aug to 11 aug", "from google", "mobile only for august
- // last year") into structured filter changes the dashboard can apply
- // through the same handlers the chat panel uses.
- runFilterCommand: protectedProcedure
- // Computes filter changes for the caller's own UI; changes no project state.
- .meta({ readOnlyMutation: true })
- .input(
- z.object({
- projectId: z.string(),
- query: z.string().min(1).max(500),
- pageContext: pageContextSchema.optional(),
- })
- )
- .mutation(async ({ input }) => {
- const { timezone } = await getSettingsForProject(input.projectId);
- return runFilterCommand({
- query: input.query,
- projectId: input.projectId,
- pageContext: input.pageContext,
- timezone: timezone || 'UTC',
- });
- }),
-
- map: overviewProcedure
- .input(
- zGetMapDataInput.omit({ startDate: true, endDate: true }).extend({
- startDate: z.string().nullish(),
- endDate: z.string().nullish(),
- range: zRange,
- shareId: z.string().optional(),
- })
- )
- .use(cacher)
- .query(async ({ input }) => {
- const { timezone } = await getSettingsForProject(input.projectId);
- const { current } = await getCurrentAndPrevious(
- { ...input, timezone },
- false,
- timezone
- )(overviewService.getMapData.bind(overviewService));
-
- return current;
- }),
-});
diff --git a/packages/trpc/src/routers/profile.ts b/packages/trpc/src/routers/profile.ts
deleted file mode 100644
index fdb6fb3ff..000000000
--- a/packages/trpc/src/routers/profile.ts
+++ /dev/null
@@ -1,85 +0,0 @@
-// Dissolved into @openpanel/core's profile module (M7-002): the ClickHouse
-// queries moved to packages/core/src/modules/profile/profile.service.ts and
-// src/profile.sql.ts. This router stays (DELEGATE PATTERN) — it keeps V1's
-// protectedProcedure stack and delegates every handler body to core's
-// profile functions, same as session.ts.
-
-import {
- getPowerUsers,
- getProfileActivity,
- getProfileById,
- getProfileListPage,
- getProfileMetrics,
- getProfileMostEvents,
- getProfilePopularRoutes,
- getProfilePropertyNames,
- getProfileValues,
-} from '@openpanel/core';
-import { zChartEventFilter } from '@openpanel/validation';
-import { z } from 'zod';
-import { createTRPCRouter, protectedProcedure } from '../trpc';
-
-const zProfileRef = z.object({ profileId: z.string(), projectId: z.string() });
-
-export const profileRouter = createTRPCRouter({
- byId: protectedProcedure
- .input(zProfileRef)
- .query(({ input: { profileId, projectId } }) =>
- getProfileById(profileId, projectId)
- ),
-
- metrics: protectedProcedure
- .input(zProfileRef)
- .query(({ input: { profileId, projectId } }) =>
- getProfileMetrics(profileId, projectId)
- ),
-
- activity: protectedProcedure
- .input(zProfileRef)
- .query(({ input: { profileId, projectId } }) =>
- getProfileActivity(profileId, projectId)
- ),
-
- mostEvents: protectedProcedure
- .input(zProfileRef)
- .query(({ input: { profileId, projectId } }) =>
- getProfileMostEvents(profileId, projectId)
- ),
-
- popularRoutes: protectedProcedure
- .input(zProfileRef)
- .query(({ input: { profileId, projectId } }) =>
- getProfilePopularRoutes(profileId, projectId)
- ),
-
- properties: protectedProcedure
- .input(z.object({ projectId: z.string() }))
- .query(({ input: { projectId } }) => getProfilePropertyNames(projectId)),
-
- list: protectedProcedure
- .input(
- z.object({
- projectId: z.string(),
- cursor: z.number().optional(),
- take: z.number().default(50),
- search: z.string().optional(),
- isExternal: z.boolean().optional(),
- filters: z.array(zChartEventFilter).default([]),
- })
- )
- .query(({ input }) => getProfileListPage(input)),
-
- powerUsers: protectedProcedure
- .input(
- z.object({
- projectId: z.string(),
- cursor: z.number().optional(),
- take: z.number().default(50),
- })
- )
- .query(({ input }) => getPowerUsers(input)),
-
- values: protectedProcedure
- .input(z.object({ property: z.string(), projectId: z.string() }))
- .query(({ input }) => getProfileValues(input)),
-});
diff --git a/packages/trpc/src/routers/project.ts b/packages/trpc/src/routers/project.ts
deleted file mode 100644
index ec9c8ec0d..000000000
--- a/packages/trpc/src/routers/project.ts
+++ /dev/null
@@ -1,173 +0,0 @@
-// Dissolved into @openpanel/core's project module (M6-002): the CRUD and
-// mutation bodies moved to
-// packages/core/src/modules/project/project.service.ts. This router stays
-// (DELEGATE PATTERN) — it keeps V1's protectedProcedure stack (session/
-// access/logger/rate-limit middleware) and delegates every handler body to
-// core's project functions, same as organization's router does (M6-001).
-import {
- cancelProjectDeletion,
- createProjectForOrganization,
- getProjectActivationStatus,
- getProjectById,
- getProjects,
- getProjectWithClients,
- scheduleProjectDeletion,
- updateProjectForOrganization,
-} from '@openpanel/core';
-import { zOnboardingProject, zProjectUpdate } from '@openpanel/validation';
-import { z } from 'zod';
-import {
- getOrganizationAccess,
- getProjectAccess,
- requireProjectAccess,
- requireProjectAdmin,
-} from '../access';
-import { TRPCBadRequestError, TRPCForbiddenError } from '../errors';
-import { createTRPCRouter, protectedProcedure } from '../trpc';
-
-export const projectRouter = createTRPCRouter({
- getProjectWithClients: protectedProcedure
- .input(
- z.object({
- projectId: z.string(),
- })
- )
- .query(async ({ input: { projectId }, ctx }) => {
- const access = await getProjectAccess({
- userId: ctx.session.userId,
- projectId,
- });
-
- if (!access) {
- throw new TRPCForbiddenError('You do not have access to this project');
- }
-
- return getProjectWithClients(projectId);
- }),
-
- // Powers the activation checklist on the project overview: has the project
- // received data, built a report, and invited a teammate yet?
- activationStatus: protectedProcedure
- .input(
- z.object({
- projectId: z.string(),
- })
- )
- .query(async ({ input: { projectId }, ctx }) => {
- const access = await getProjectAccess({
- userId: ctx.session.userId,
- projectId,
- });
-
- if (!access) {
- throw new TRPCForbiddenError('You do not have access to this project');
- }
-
- return getProjectActivationStatus(projectId);
- }),
-
- list: protectedProcedure
- .input(
- z.object({
- organizationId: z.string().nullable(),
- })
- )
- .query(async ({ input: { organizationId }, ctx }) => {
- if (organizationId === null) {
- return [];
- }
- return getProjects({
- organizationId,
- userId: ctx.session.userId,
- });
- }),
-
- update: protectedProcedure
- .input(zProjectUpdate)
- .mutation(async ({ input, ctx }) => {
- await requireProjectAccess({
- userId: ctx.session.userId,
- projectId: input.id,
- level: 'write',
- });
-
- const project = await getProjectById(input.id);
- if (!project) {
- throw new TRPCForbiddenError('Project not found');
- }
-
- return updateProjectForOrganization(input.id, project.organizationId, {
- name: input.name,
- domain: input.domain,
- cors: input.cors,
- crossDomain: input.crossDomain,
- allowUnsafeRevenueTracking: input.allowUnsafeRevenueTracking,
- });
- }),
- create: protectedProcedure
- .input(zOnboardingProject)
- .mutation(async ({ input, ctx }) => {
- if (!input.organizationId) {
- throw new TRPCBadRequestError('Organization is required');
- }
-
- const access = await getOrganizationAccess({
- userId: ctx.session.userId,
- organizationId: input.organizationId,
- });
-
- if (access?.role !== 'org:admin') {
- throw new TRPCForbiddenError(
- 'Only organization admins can create projects'
- );
- }
-
- const { project, client } = await createProjectForOrganization(
- input.organizationId,
- {
- name: input.project,
- domain: input.domain,
- cors: input.cors,
- crossDomain: false,
- types: [],
- }
- );
-
- return { ...project, client };
- }),
- delete: protectedProcedure
- .input(
- z.object({
- projectId: z.string(),
- })
- )
- .mutation(async ({ input, ctx }) => {
- // Destroying a project is admin-tier, matching project.create.
- await requireProjectAdmin({
- userId: ctx.session.userId,
- projectId: input.projectId,
- message: 'Only organization admins can delete projects',
- });
-
- await scheduleProjectDeletion(input.projectId);
-
- return true;
- }),
- cancelDeletion: protectedProcedure
- .input(
- z.object({
- projectId: z.string(),
- })
- )
- .mutation(async ({ input, ctx }) => {
- await requireProjectAdmin({
- userId: ctx.session.userId,
- projectId: input.projectId,
- message: 'Only organization admins can cancel a project deletion',
- });
-
- await cancelProjectDeletion(input.projectId);
-
- return true;
- }),
-});
diff --git a/packages/trpc/src/routers/realtime.ts b/packages/trpc/src/routers/realtime.ts
deleted file mode 100644
index bcdc82a7f..000000000
--- a/packages/trpc/src/routers/realtime.ts
+++ /dev/null
@@ -1,76 +0,0 @@
-// Dissolved into @openpanel/core's realtime module (M6-007): the six
-// ClickHouse queries moved to
-// packages/core/src/modules/realtime/realtime.service.ts. This router stays
-// (DELEGATE PATTERN) — it keeps V1's protectedProcedure stack
-// (session/access/logger/rate-limit middleware, which already enforces
-// `projectId` read access via `enforceAccess`) and delegates every handler
-// body to core's realtime functions, same as notification.ts/reference.ts.
-//
-// V1's Fastify `/live` websocket controller is untouched (ADR-002/M6-007
-// notes: its `ws`-package socket has nothing in common with Elysia/Bun's
-// `ElysiaWS`), so this file has no ws surface to delegate — that logic was
-// ported fresh into core/realtime.routes.ts instead.
-
-import {
- getRealtimeActiveSessions,
- getRealtimeCoordinates,
- getRealtimeGeo,
- getRealtimeMapBadgeDetails,
- getRealtimePaths,
- getRealtimeReferrals,
-} from '@openpanel/core';
-import { z } from 'zod';
-import { createTRPCRouter, protectedProcedure } from '../trpc';
-
-const realtimeLocationSchema = z.object({
- country: z.string().optional(),
- city: z.string().optional(),
- lat: z.number().optional(),
- long: z.number().optional(),
-});
-
-const realtimeBadgeDetailScopeSchema = z.enum([
- 'country',
- 'city',
- 'coordinate',
- 'merged',
-]);
-
-export const realtimeRouter = createTRPCRouter({
- coordinates: protectedProcedure
- .input(z.object({ projectId: z.string() }))
- .query(async ({ input }) => {
- return getRealtimeCoordinates(input.projectId);
- }),
- mapBadgeDetails: protectedProcedure
- .input(
- z.object({
- detailScope: realtimeBadgeDetailScopeSchema,
- projectId: z.string(),
- locations: z.array(realtimeLocationSchema).min(1).max(200),
- })
- )
- .query(async ({ input }) => {
- return getRealtimeMapBadgeDetails(input);
- }),
- activeSessions: protectedProcedure
- .input(z.object({ projectId: z.string() }))
- .query(async ({ input }) => {
- return getRealtimeActiveSessions(input.projectId);
- }),
- paths: protectedProcedure
- .input(z.object({ projectId: z.string() }))
- .query(async ({ input }) => {
- return getRealtimePaths(input.projectId);
- }),
- referrals: protectedProcedure
- .input(z.object({ projectId: z.string() }))
- .query(async ({ input }) => {
- return getRealtimeReferrals(input.projectId);
- }),
- geo: protectedProcedure
- .input(z.object({ projectId: z.string() }))
- .query(async ({ input }) => {
- return getRealtimeGeo(input.projectId);
- }),
-});
diff --git a/packages/trpc/src/routers/reference.ts b/packages/trpc/src/routers/reference.ts
deleted file mode 100644
index 58fe87d3e..000000000
--- a/packages/trpc/src/routers/reference.ts
+++ /dev/null
@@ -1,89 +0,0 @@
-// Dissolved into @openpanel/core's reference module (M6-004): the
-// query/mutation bodies moved to
-// packages/core/src/modules/reference/reference.service.ts. This router
-// stays (DELEGATE PATTERN) — it keeps V1's protectedProcedure stack
-// (session/access/logger middleware) and delegates every handler body to
-// core's reference functions, same as organization's router does (M6-001).
-// `create` has no access check here either — same gap core's own router has
-// (ported verbatim, not fixed).
-
-import {
- createReference,
- deleteReference,
- getChartReferences,
- getReferenceByIdOrThrow,
- listReferences,
- updateReference,
-} from '@openpanel/core';
-import { zCreateReference, zRange } from '@openpanel/validation';
-import { z } from 'zod';
-import { getProjectAccess, requireProjectAccess } from '../access';
-import { TRPCForbiddenError } from '../errors';
-import { createTRPCRouter, protectedProcedure, publicProcedure } from '../trpc';
-
-export const referenceRouter = createTRPCRouter({
- getReferences: protectedProcedure
- .input(z.object({ projectId: z.string(), cursor: z.number().optional() }))
- .query(async ({ input, ctx }) => {
- const access = await getProjectAccess({
- userId: ctx.session.userId,
- projectId: input.projectId,
- });
-
- if (!access) {
- throw new TRPCForbiddenError('You do not have access to this project');
- }
-
- return listReferences(input);
- }),
-
- create: protectedProcedure
- .input(zCreateReference)
- .mutation(({ input }) => createReference(input)),
-
- update: protectedProcedure
- .input(
- z.object({
- id: z.string(),
- title: z.string(),
- description: z.string().nullish(),
- datetime: z.string(),
- })
- )
- .mutation(async ({ input, ctx }) => {
- const existing = await getReferenceByIdOrThrow(input.id);
-
- await requireProjectAccess({
- userId: ctx.session.userId,
- projectId: existing.projectId,
- level: 'write',
- });
-
- return updateReference(input);
- }),
-
- delete: protectedProcedure
- .input(z.object({ id: z.string() }))
- .mutation(async ({ input: { id }, ctx }) => {
- const reference = await getReferenceByIdOrThrow(id);
-
- await requireProjectAccess({
- userId: ctx.session.userId,
- projectId: reference.projectId,
- level: 'write',
- });
-
- return deleteReference(id);
- }),
-
- getChartReferences: publicProcedure
- .input(
- z.object({
- projectId: z.string(),
- startDate: z.string().nullish(),
- endDate: z.string().nullish(),
- range: zRange,
- })
- )
- .query(({ input }) => getChartReferences(input)),
-});
diff --git a/packages/trpc/src/routers/report.ts b/packages/trpc/src/routers/report.ts
deleted file mode 100644
index 930ffa53e..000000000
--- a/packages/trpc/src/routers/report.ts
+++ /dev/null
@@ -1,236 +0,0 @@
-// Dissolved into @openpanel/core's report module (M7-006): the transforms,
-// listReportsCore/getReportDataCore and the create/update/move/delete/
-// duplicate/layout mutation bodies moved to
-// packages/core/src/modules/report/report.service.ts, and the chart/report/
-// widget zod schemas (zReport included) moved to
-// packages/core/src/modules/report/report.constants.ts. This router stays
-// (DELEGATE PATTERN) — it keeps V1's `protectedProcedure` stack and
-// delegates every handler body to core's report functions, same as
-// overview.ts/chart.ts.
-
-import {
- createReport,
- deleteReport,
- duplicateReport,
- getDashboardById,
- getDashboardByIdOrThrow,
- getReportById,
- getReportByIdOrThrow,
- getReportLayouts,
- getReportsByDashboardId,
- moveReport,
- resetReportLayouts,
- updateReport,
- updateReportLayout,
- zReport,
-} from '@openpanel/core';
-import { z } from 'zod';
-import { getProjectAccess, requireProjectAccess } from '../access';
-import { TRPCForbiddenError, TRPCNotFoundError } from '../errors';
-import { createTRPCRouter, protectedProcedure } from '../trpc';
-
-export const reportRouter = createTRPCRouter({
- list: protectedProcedure
- .input(
- z.object({
- dashboardId: z.string(),
- projectId: z.string(),
- })
- )
- .query(async ({ input: { dashboardId, projectId } }) => {
- const dashboard = await getDashboardById(dashboardId, projectId);
- if (!dashboard) {
- throw new TRPCNotFoundError('Dashboard not found');
- }
- return getReportsByDashboardId(dashboardId);
- }),
- create: protectedProcedure
- .input(
- z.object({
- report: zReport.omit({ projectId: true }),
- dashboardId: z.string(),
- })
- )
- .mutation(async ({ input: { report, dashboardId }, ctx }) => {
- const dashboard = await getDashboardByIdOrThrow(dashboardId);
-
- await requireProjectAccess({
- userId: ctx.session.userId,
- projectId: dashboard.projectId,
- level: 'write',
- });
-
- return createReport({
- dashboardId,
- projectId: dashboard.projectId,
- report,
- });
- }),
- update: protectedProcedure
- .input(
- z.object({
- reportId: z.string(),
- report: zReport.omit({ projectId: true }),
- })
- )
- .mutation(async ({ input: { report, reportId }, ctx }) => {
- const dbReport = await getReportByIdOrThrow(reportId);
-
- await requireProjectAccess({
- userId: ctx.session.userId,
- projectId: dbReport.projectId,
- level: 'write',
- });
-
- return updateReport({ reportId, report });
- }),
- move: protectedProcedure
- .input(
- z.object({
- reportId: z.string(),
- dashboardId: z.string(),
- })
- )
- .mutation(async ({ input: { reportId, dashboardId }, ctx }) => {
- const dbReport = await getReportByIdOrThrow(reportId);
-
- await requireProjectAccess({
- userId: ctx.session.userId,
- projectId: dbReport.projectId,
- level: 'write',
- });
-
- return moveReport({ report: dbReport, dashboardId });
- }),
- delete: protectedProcedure
- .input(
- z.object({
- reportId: z.string(),
- })
- )
- .mutation(async ({ input: { reportId }, ctx }) => {
- const dbReport = await getReportByIdOrThrow(reportId);
-
- await requireProjectAccess({
- userId: ctx.session.userId,
- projectId: dbReport.projectId,
- level: 'write',
- });
-
- return deleteReport(reportId);
- }),
- duplicate: protectedProcedure
- .input(
- z.object({
- reportId: z.string(),
- })
- )
- .mutation(async ({ input: { reportId }, ctx }) => {
- const dbReport = await getReportByIdOrThrow(reportId);
-
- await requireProjectAccess({
- userId: ctx.session.userId,
- projectId: dbReport.projectId,
- level: 'write',
- });
-
- return duplicateReport(dbReport);
- }),
- get: protectedProcedure
- .input(
- z.object({
- reportId: z.string(),
- })
- )
- .query(async ({ input: { reportId }, ctx }) => {
- const report = await getReportById(reportId);
- if (!report) {
- throw new TRPCNotFoundError('Report not found');
- }
- const access = await getProjectAccess({
- userId: ctx.session.userId,
- projectId: report.projectId,
- });
- if (!access) {
- throw new TRPCForbiddenError('You do not have access to this project');
- }
- return report;
- }),
- updateLayout: protectedProcedure
- .input(
- z.object({
- reportId: z.string(),
- layout: z.object({
- x: z.number(),
- y: z.number(),
- w: z.number(),
- h: z.number(),
- minW: z.number().optional(),
- minH: z.number().optional(),
- maxW: z.number().optional(),
- maxH: z.number().optional(),
- }),
- })
- )
- .mutation(async ({ input: { reportId, layout }, ctx }) => {
- const dbReport = await getReportByIdOrThrow(reportId);
-
- await requireProjectAccess({
- userId: ctx.session.userId,
- projectId: dbReport.projectId,
- level: 'write',
- });
-
- return updateReportLayout({ reportId, layout });
- }),
- getLayouts: protectedProcedure
- .input(
- z.object({
- dashboardId: z.string(),
- projectId: z.string(),
- })
- )
- .query(async ({ input: { dashboardId, projectId }, ctx }) => {
- const access = await getProjectAccess({
- userId: ctx.session.userId,
- projectId,
- });
-
- if (!access) {
- throw new TRPCForbiddenError('You do not have access to this project');
- }
-
- // The access check above only proves the caller owns `projectId`. Bind
- // the caller-supplied `dashboardId` to that project as well, otherwise a
- // dashboard from another organization can be read through this handler.
- const dashboard = await getDashboardById(dashboardId, projectId);
- if (!dashboard) {
- throw new TRPCNotFoundError('Dashboard not found');
- }
-
- return getReportLayouts({ dashboardId, projectId });
- }),
- resetLayout: protectedProcedure
- .input(
- z.object({
- dashboardId: z.string(),
- projectId: z.string(),
- })
- )
- .mutation(async ({ input: { dashboardId, projectId }, ctx }) => {
- await requireProjectAccess({
- userId: ctx.session.userId,
- projectId,
- level: 'write',
- });
-
- // Same as `getLayouts`: bind the dashboard to the access-checked project
- // before deleting anything, so a foreign dashboard cannot be wiped.
- const dashboard = await getDashboardById(dashboardId, projectId);
- if (!dashboard) {
- throw new TRPCNotFoundError('Dashboard not found');
- }
-
- return resetReportLayouts({ dashboardId, projectId });
- }),
-});
diff --git a/packages/trpc/src/routers/session.ts b/packages/trpc/src/routers/session.ts
deleted file mode 100644
index ec1a5fead..000000000
--- a/packages/trpc/src/routers/session.ts
+++ /dev/null
@@ -1,68 +0,0 @@
-// Dissolved into @openpanel/core's session module (M7-001): the ClickHouse
-// queries moved to packages/core/src/modules/session/session.service.ts.
-// This router stays (DELEGATE PATTERN) — it keeps V1's protectedProcedure
-// stack and delegates every handler body to core's session functions, same
-// as realtime.ts/notification.ts. V1's unused `encodeCursor`/`decodeCursor`
-// went with it (packages/core/src/shared/pagination.ts owns the generic pair).
-
-import {
- getSessionById,
- getSessionDistinctValues,
- getSessionList,
- getSessionReplayChunksFrom,
- SESSION_DISTINCT_FIELDS,
-} from '@openpanel/core';
-import { zChartEventFilter } from '@openpanel/validation';
-import { z } from 'zod';
-import { createTRPCRouter, protectedProcedure } from '../trpc';
-
-export const sessionRouter = createTRPCRouter({
- list: protectedProcedure
- .input(
- z.object({
- projectId: z.string(),
- profileId: z.string().optional(),
- cursor: z.string().nullish(),
- filters: z.array(zChartEventFilter).default([]),
- startDate: z.date().optional(),
- endDate: z.date().optional(),
- search: z.string().optional(),
- take: z.number().default(50),
- })
- )
- .query(({ input }) => {
- return getSessionList({
- ...input,
- cursor: input.cursor ? new Date(input.cursor) : undefined,
- });
- }),
-
- distinctValues: protectedProcedure
- .input(
- z.object({
- projectId: z.string(),
- field: z.enum(SESSION_DISTINCT_FIELDS),
- })
- )
- .query(({ input }) => {
- return getSessionDistinctValues(input.projectId, input.field);
- }),
-
- byId: protectedProcedure
- .input(z.object({ sessionId: z.string(), projectId: z.string() }))
- .query(({ input: { sessionId, projectId } }) => {
- return getSessionById(sessionId, projectId);
- }),
-
- replayChunksFrom: protectedProcedure
- .input(
- z.object({
- sessionId: z.string(),
- projectId: z.string(),
- fromIndex: z.number().int().min(0).default(0),
- })
- )
- .query(({ input: { sessionId, projectId, fromIndex } }) => {
- return getSessionReplayChunksFrom(sessionId, projectId, fromIndex);
- }),
-});
diff --git a/packages/trpc/src/routers/share.test.ts b/packages/trpc/src/routers/share.test.ts
deleted file mode 100644
index c68400bd4..000000000
--- a/packages/trpc/src/routers/share.test.ts
+++ /dev/null
@@ -1,168 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-// vi.mock is hoisted above the module scope, so the spies have to be too.
-const {
- shareReportFindUnique,
- shareDashboardFindUnique,
- shareOverviewFindUnique,
-} = vi.hoisted(() => ({
- shareReportFindUnique: vi.fn(),
- shareDashboardFindUnique: vi.fn(),
- shareOverviewFindUnique: vi.fn(),
-}));
-
-// The share business logic itself moved to @openpanel/core (M6-004); share.ts
-// now only delegates to it. `@openpanel/core` is also mocked for `../access`'s
-// and `trpc.ts`'s own imports (unrelated to this file's assertions) — the
-// deep `@openpanel/db/src/*` paths below are what core's share functions
-// actually read through (lazy `await import(...)`, so vi.mock still applies
-// to the dynamic form). `createAccessChecks` (the permission ladder itself,
-// GHSA-f9rx-pxgw-c6rg's fix) stays real via importActual — everything it's
-// built from, plus share's own core reads, are the only stubs, one
-// vi.mock call, since every one of these now resolves through the same
-// @openpanel/core specifier (M9-CLEANUP-001) and a second/third call would
-// silently drop the earlier overrides.
-vi.mock('@openpanel/core', async () => ({
- ...(await vi.importActual<typeof import('@openpanel/core')>(
- '@openpanel/core',
- )),
- getProjectById: vi.fn(),
- getProjectAccess: vi.fn(),
- getOrganizationAccess: vi.fn(),
- getClientAccess: vi.fn(),
- canWriteProject: vi.fn(),
- runWithAlsSession: (_id: unknown, fn: () => unknown) => fn(),
- transformReport: (report: unknown) => report,
- getReportById: vi.fn(),
- getReportsByDashboardId: vi.fn(),
- getDashboardById: vi.fn(),
-}));
-
-vi.mock('@openpanel/db/src/prisma-client', () => ({
- db: {
- shareReport: { findUnique: shareReportFindUnique },
- shareDashboard: { findUnique: shareDashboardFindUnique },
- shareOverview: { findUnique: shareOverviewFindUnique },
- },
-}));
-
-import { shareRouter } from './share';
-
-const PASSWORD_HASH =
- '$argon2id$v=19$m=19456,t=2,p=1$NTb6p8dXsP2b1WpDU22i/w$ILi3tmTMYg5TSrjvVktAbixLHPH5PjvvbQypR9bZuoQ';
-
-const REPORT = {
- id: 'report-uuid',
- name: 'Q4 Revenue — CONFIDENTIAL',
- events: [{ name: 'checkout_completed_SECRET_EVENT' }],
- breakdowns: [{ name: 'CONFIDENTIAL_breakdown' }],
-};
-
-/** An unauthenticated caller: no session, no unlock cookie. */
-const anonCaller = (cookies: Record<string, string> = {}) =>
- shareRouter.createCaller({
- logger: { info: vi.fn(), error: vi.fn() },
- session: null,
- setCookie: vi.fn(),
- cookies: { get: (name: string) => cookies[name] },
- } as never);
-
-const privatePasswordProtectedShare = {
- id: 'SECRT1',
- public: false,
- password: PASSWORD_HASH,
- projectId: 'victim-project',
- organization: { name: 'VictimOrg' },
- project: { name: 'Victim Project' },
- report: REPORT,
- dashboard: { name: 'Confidential Dashboard' },
-};
-
-beforeEach(() => {
- vi.clearAllMocks();
-});
-
-/**
- * GHSA-7gv7-c464-9wh8: these three procedures spread the whole share row into
- * the response, so an unauthenticated caller holding a share link received the
- * argon2 password hash - and, for reports, the full report definition - while
- * the same response said they had no access.
- */
-describe('share lookups do not leak the password hash', () => {
- it('refuses a non-public report share outright', async () => {
- shareReportFindUnique.mockResolvedValue(privatePasswordProtectedShare);
-
- await expect(
- anonCaller().report({ shareId: 'SECRT1' }),
- ).rejects.toThrow('Report share not found');
- });
-
- it('refuses a non-public dashboard share outright', async () => {
- shareDashboardFindUnique.mockResolvedValue(privatePasswordProtectedShare);
-
- await expect(
- anonCaller().dashboard({ shareId: 'SECRT1' }),
- ).rejects.toThrow('Dashboard share not found');
- });
-
- it('refuses a non-public overview share outright', async () => {
- shareOverviewFindUnique.mockResolvedValue(privatePasswordProtectedShare);
-
- await expect(
- anonCaller().overview({ shareId: 'SECRT1' }),
- ).rejects.toThrow('Share not found');
- });
-
- it('withholds the hash and the report from a locked public share', async () => {
- shareReportFindUnique.mockResolvedValue({
- ...privatePasswordProtectedShare,
- public: true,
- });
-
- const res = await anonCaller().report({ shareId: 'SECRT1' });
-
- expect(res.requiresPassword).toBe(true);
- expect(JSON.stringify(res)).not.toContain('$argon2id');
- expect(JSON.stringify(res)).not.toContain('CONFIDENTIAL');
- expect(res).not.toHaveProperty('password');
- expect(res).not.toHaveProperty('report');
- expect(res).not.toHaveProperty('projectId');
- });
-
- it('withholds projectId from a locked overview share', async () => {
- shareOverviewFindUnique.mockResolvedValue({
- ...privatePasswordProtectedShare,
- public: true,
- });
-
- const res = await anonCaller().overview({ shareId: 'SECRT1' });
-
- expect(res.requiresPassword).toBe(true);
- expect(res).not.toHaveProperty('projectId');
- expect(JSON.stringify(res)).not.toContain('$argon2id');
- });
-
- it('serves the report once unlocked, still without the hash', async () => {
- shareReportFindUnique.mockResolvedValue({
- ...privatePasswordProtectedShare,
- public: true,
- });
-
- const res = await anonCaller({
- 'shared-report-SECRT1': '1',
- }).report({ shareId: 'SECRT1' });
-
- expect(res.requiresPassword).toBe(false);
- expect(res).toHaveProperty('report');
- expect(JSON.stringify(res)).not.toContain('$argon2id');
- });
-
- it('never selects the row by reportId, so object ids are not addressable', async () => {
- // The union input used to accept { reportId }, which let anyone knowing a
- // report id read the share row without ever seeing a share link.
- await expect(
- // @ts-expect-error - deliberately calling the removed input shape
- anonCaller().report({ reportId: 'report-uuid' }),
- ).rejects.toThrow();
- });
-});
diff --git a/packages/trpc/src/routers/share.ts b/packages/trpc/src/routers/share.ts
deleted file mode 100644
index 3abcd8d47..000000000
--- a/packages/trpc/src/routers/share.ts
+++ /dev/null
@@ -1,88 +0,0 @@
-// Dissolved into @openpanel/core's share module (M6-004): the query/mutation
-// bodies moved to packages/core/src/modules/share/share.service.ts. This
-// router stays (DELEGATE PATTERN) — it keeps V1's protectedProcedure stack
-// (session/access/logger middleware) and delegates every handler body to
-// core's share functions, same as reference's router does.
-
-import {
- createShareDashboard,
- createShareOverview,
- createShareReport,
- getShareDashboard,
- getShareDashboardReports,
- getShareDashboardSettings,
- getShareOverview,
- getShareOverviewSettings,
- getShareReport,
- getShareReportSettings,
- zShareDashboard,
- zShareOverview,
- zShareReport,
-} from '@openpanel/core';
-import { z } from 'zod';
-import { requireProjectAccess } from '../access';
-import { createTRPCRouter, protectedProcedure, publicProcedure } from '../trpc';
-
-export const shareRouter = createTRPCRouter({
- overview: publicProcedure
- .input(z.object({ shareId: z.string() }))
- .query(({ input, ctx }) => getShareOverview(input.shareId, ctx.cookies)),
-
- overviewSettings: protectedProcedure
- .input(z.object({ projectId: z.string() }))
- .query(({ input }) => getShareOverviewSettings(input.projectId)),
-
- createOverview: protectedProcedure
- .input(zShareOverview)
- .mutation(({ input }) => createShareOverview(input)),
-
- // Dashboard sharing
- dashboard: publicProcedure
- .input(z.object({ shareId: z.string() }))
- .query(({ input, ctx }) => getShareDashboard(input.shareId, ctx.cookies)),
-
- dashboardSettings: protectedProcedure
- .input(z.object({ projectId: z.string(), dashboardId: z.string() }))
- .query(({ input }) =>
- getShareDashboardSettings(input.projectId, input.dashboardId)
- ),
-
- createDashboard: protectedProcedure
- .input(zShareDashboard)
- .mutation(async ({ input, ctx }) => {
- await requireProjectAccess({
- userId: ctx.session.userId,
- projectId: input.projectId,
- level: 'write',
- });
- return createShareDashboard(input);
- }),
-
- dashboardReports: publicProcedure
- .input(z.object({ shareId: z.string() }))
- .query(({ input, ctx }) =>
- getShareDashboardReports(input.shareId, ctx.cookies)
- ),
-
- // Report sharing
- report: publicProcedure
- .input(z.object({ shareId: z.string() }))
- .query(({ input, ctx }) => getShareReport(input.shareId, ctx.cookies)),
-
- reportSettings: protectedProcedure
- .input(z.object({ projectId: z.string(), reportId: z.string() }))
- .query(({ input }) =>
- getShareReportSettings(input.projectId, input.reportId)
- ),
-
- createReport: protectedProcedure
- .input(zShareReport)
- .mutation(async ({ input, ctx }) => {
- await requireProjectAccess({
- userId: ctx.session.userId,
- projectId: input.projectId,
- level: 'write',
- });
- return createShareReport(input);
- }),
-});
diff --git a/packages/trpc/src/routers/subscription.ts b/packages/trpc/src/routers/subscription.ts
deleted file mode 100644
index 94d379196..000000000
--- a/packages/trpc/src/routers/subscription.ts
+++ /dev/null
@@ -1,74 +0,0 @@
-// Dissolved into @openpanel/core's subscription module (M6-006): the
-// checkout/products/usage/cancel/pause/resume/save-discount/portal bodies
-// moved to packages/core/src/modules/subscription/subscription.service.ts.
-// This router stays (DELEGATE PATTERN) — it keeps V1's protectedProcedure
-// stack (session/access/logger/rate-limit middleware) and delegates every
-// handler body to core's subscription functions, same as notification's
-// router does (M6-005).
-
-import {
- applySaveDiscount,
- cancelSubscription,
- checkout,
- getCurrentSubscriptionProduct,
- getUsage,
- listProducts,
- pauseSubscription,
- portal,
- resumeSubscription,
-} from '@openpanel/core';
-import {
- zCancelSubscription,
- zCheckout,
- zPauseSubscription,
-} from '@openpanel/validation';
-import { z } from 'zod';
-import { createTRPCRouter, protectedProcedure } from '../trpc';
-
-export const subscriptionRouter = createTRPCRouter({
- getCurrent: protectedProcedure
- .input(z.object({ organizationId: z.string() }))
- .query(({ input }) => getCurrentSubscriptionProduct(input.organizationId)),
-
- checkout: protectedProcedure
- .input(zCheckout)
- .mutation(({ input, ctx }) =>
- checkout(ctx.session.userId, input, ctx.remoteAddress)
- ),
-
- products: protectedProcedure
- .input(z.object({ organizationId: z.string() }))
- .query(({ input }) => listProducts(input.organizationId)),
-
- usage: protectedProcedure
- .input(z.object({ organizationId: z.string() }))
- .query(({ input }) => getUsage(input.organizationId)),
-
- cancelSubscription: protectedProcedure
- .input(zCancelSubscription)
- .mutation(({ input, ctx }) =>
- cancelSubscription(ctx.session.userId, input)
- ),
-
- pauseSubscription: protectedProcedure
- .input(zPauseSubscription)
- .mutation(({ input, ctx }) => pauseSubscription(ctx.session.userId, input)),
-
- resumeSubscription: protectedProcedure
- .input(z.object({ organizationId: z.string() }))
- .mutation(({ input, ctx }) =>
- resumeSubscription(ctx.session.userId, input.organizationId)
- ),
-
- applySaveDiscount: protectedProcedure
- .input(z.object({ organizationId: z.string() }))
- .mutation(({ input, ctx }) =>
- applySaveDiscount(ctx.session.userId, input.organizationId)
- ),
-
- portal: protectedProcedure
- .input(z.object({ organizationId: z.string() }))
- .mutation(({ input, ctx }) =>
- portal(ctx.session.userId, input.organizationId)
- ),
-});
diff --git a/packages/trpc/src/routers/user.ts b/packages/trpc/src/routers/user.ts
deleted file mode 100644
index cdb16dd1a..000000000
--- a/packages/trpc/src/routers/user.ts
+++ /dev/null
@@ -1,73 +0,0 @@
-// Dissolved into @openpanel/core's user module (M6-001): the CRUD itself
-// moved to packages/core/src/modules/user/user.service.ts. This router
-// stays (DELEGATE PATTERN) — it keeps V1's protectedProcedure stack
-// (session/access/logger/rate-limit middleware) and delegates every handler
-// body to core's user functions, same as conversation's router does
-// (M5-006).
-import {
- deleteSessionTokenCookie,
- deleteUserAccount,
- listUserDeletionBlockers,
- updateUserProfile,
-} from '@openpanel/core';
-import { z } from 'zod';
-import { createTRPCRouter, protectedProcedure } from '../trpc';
-
-export const userRouter = createTRPCRouter({
- // Organizations the user created that still have a blocking subscription
- // (active and not scheduled to cancel). The account cannot be deleted while
- // any of these exist.
- deletionBlockers: protectedProcedure.query(async ({ ctx }) => {
- return listUserDeletionBlockers(ctx.session.userId);
- }),
-
- delete: protectedProcedure.mutation(async ({ ctx }) => {
- await deleteUserAccount(ctx.session.userId);
- deleteSessionTokenCookie(ctx.setCookie);
-
- return true;
- }),
-
- update: protectedProcedure
- .input(
- z.object({
- firstName: z.string(),
- lastName: z.string(),
- })
- )
- .mutation(async ({ input, ctx }) => {
- return updateUserProfile({ userId: ctx.session.userId, ...input });
- }),
- debugPostCookie: protectedProcedure
- .input(
- z.object({
- sameSite: z.enum(['lax', 'strict', 'none']),
- domain: z.string(),
- })
- )
- .mutation(async ({ ctx, input }) => {
- ctx.setCookie('debugCookie', new Date().toISOString(), {
- domain: input.domain,
- sameSite: input.sameSite,
- httpOnly: true,
- secure: true,
- path: '/',
- });
- }),
- debugGetCookie: protectedProcedure
- .input(
- z.object({
- sameSite: z.enum(['lax', 'strict', 'none']),
- domain: z.string(),
- })
- )
- .query(async ({ ctx, input }) => {
- ctx.setCookie('debugCookie', new Date().toISOString(), {
- domain: input.domain,
- sameSite: input.sameSite,
- httpOnly: true,
- secure: true,
- path: '/',
- });
- }),
-});
diff --git a/packages/trpc/src/routers/widget.ts b/packages/trpc/src/routers/widget.ts
deleted file mode 100644
index 70c16baf5..000000000
--- a/packages/trpc/src/routers/widget.ts
+++ /dev/null
@@ -1,341 +0,0 @@
-// Ported into @openpanel/core's widget module (M7-006): `zWidgetOptions`/
-// `zWidgetType` moved to the report module's report.constants.ts (ADR-008's
-// module map: widget's own schemas are chart/report vocabulary, so widget
-// carries no `widget.constants.ts` of its own). This router is R + C-only
-// downstream, same as email.ts — there is no `widget.service.ts` to
-// delegate to, so V1 keeps its own ClickHouse/Postgres calls here, reading
-// the schemas core now owns instead of @openpanel/validation's copy.
-
-import {
- getSettingsForProject,
- zWidgetOptions,
- zWidgetType,
-} from '@openpanel/core';
-import { ch, clix, db, TABLE_NAMES } from '@openpanel/db';
-import { eventBuffer } from '@openpanel/queue/src/buffers';
-import { getCache } from '@openpanel/redis';
-import ShortUniqueId from 'short-unique-id';
-import { z } from 'zod';
-import { TRPCNotFoundError } from '../errors';
-import { createTRPCRouter, protectedProcedure, publicProcedure } from '../trpc';
-
-const uid = new ShortUniqueId({ length: 6 });
-
-// Helper to find widget by projectId and type
-async function findWidgetByType(projectId: string, type: string) {
- const widgets = await db.shareWidget.findMany({
- where: { projectId },
- });
- return widgets.find(
- (w) => (w.options as z.infer<typeof zWidgetOptions>)?.type === type
- );
-}
-
-export const widgetRouter = createTRPCRouter({
- // Get widget by projectId and type (returns null if not found or not public)
- get: protectedProcedure
- .input(z.object({ projectId: z.string(), type: zWidgetType }))
- .query(async ({ input }) => {
- const widget = await findWidgetByType(input.projectId, input.type);
-
- if (!widget) {
- return null;
- }
-
- return widget;
- }),
-
- // Toggle widget public status (creates if doesn't exist)
- toggle: protectedProcedure
- .input(
- z.object({
- projectId: z.string(),
- organizationId: z.string(),
- type: zWidgetType,
- enabled: z.boolean(),
- })
- )
- .mutation(async ({ input }) => {
- const existing = await findWidgetByType(input.projectId, input.type);
-
- if (existing) {
- return db.shareWidget.update({
- where: { id: existing.id },
- data: { public: input.enabled },
- });
- }
-
- // Create new widget with default options
- const defaultOptions =
- input.type === 'realtime'
- ? {
- type: 'realtime' as const,
- referrers: true,
- countries: true,
- paths: false,
- }
- : { type: 'counter' as const };
-
- return db.shareWidget.create({
- data: {
- id: uid.rnd(),
- projectId: input.projectId,
- organizationId: input.organizationId,
- public: input.enabled,
- options: defaultOptions,
- },
- });
- }),
-
- // Update widget options (for realtime widget)
- updateOptions: protectedProcedure
- .input(
- z.object({
- projectId: z.string(),
- organizationId: z.string(),
- options: zWidgetOptions,
- })
- )
- .mutation(async ({ input }) => {
- const existing = await findWidgetByType(
- input.projectId,
- input.options.type
- );
-
- if (existing) {
- return db.shareWidget.update({
- where: { id: existing.id },
- data: { options: input.options },
- });
- }
-
- // Create new widget if it doesn't exist
- return db.shareWidget.create({
- data: {
- id: uid.rnd(),
- projectId: input.projectId,
- organizationId: input.organizationId,
- public: false,
- options: input.options,
- },
- });
- }),
-
- counter: publicProcedure
- .input(z.object({ shareId: z.string() }))
- .query(async ({ input }) => {
- const widget = await db.shareWidget.findUnique({
- where: {
- id: input.shareId,
- },
- });
-
- if (!widget?.public) {
- throw new TRPCNotFoundError('Widget not found');
- }
-
- if (widget.options.type !== 'counter') {
- throw new TRPCNotFoundError('Invalid widget type');
- }
-
- return {
- projectId: widget.projectId,
- counter: await eventBuffer.getActiveVisitorCount(widget.projectId),
- };
- }),
-
- badge: publicProcedure
- .input(z.object({ shareId: z.string() }))
- .query(async ({ input }) => {
- const widget = await db.shareWidget.findUnique({
- where: {
- id: input.shareId,
- },
- });
-
- if (!widget?.public) {
- throw new TRPCNotFoundError('Widget not found');
- }
-
- if (widget.options.type !== 'counter') {
- throw new TRPCNotFoundError('Invalid widget type');
- }
-
- const { projectId } = widget;
- const { timezone } = await getSettingsForProject(projectId);
-
- // Cache for 5 minutes since this queries 30 days of data
- const cacheKey = `widget:badge:${projectId}`;
- const visitors = await getCache(
- cacheKey,
- 5 * 60, // 5 minutes
- async () => {
- const uniqueVisitorsQuery = clix(ch, timezone)
- .select<{ count: number }>(['uniq(profile_id) as count'])
- .from(TABLE_NAMES.events)
- .where('project_id', '=', projectId)
- .where('created_at', '>=', clix.exp('now() - INTERVAL 30 DAY'));
-
- const result = await uniqueVisitorsQuery.execute();
- return result[0]?.count || 0;
- }
- );
-
- return {
- projectId,
- visitors,
- };
- }),
-
- realtimeData: publicProcedure
- .input(z.object({ shareId: z.string() }))
- .query(async ({ input }) => {
- // Validate ShareWidget exists and is public
- const widget = await db.shareWidget.findUnique({
- where: {
- id: input.shareId,
- },
- include: {
- project: {
- select: {
- domain: true,
- name: true,
- },
- },
- },
- });
-
- if (!widget?.public) {
- throw new TRPCNotFoundError('Widget not found');
- }
-
- const { projectId, options } = widget;
-
- if (options.type !== 'realtime') {
- throw new TRPCNotFoundError('Invalid widget type');
- }
-
- const { timezone } = await getSettingsForProject(projectId);
-
- // Always fetch live count and histogram
- const totalSessionsQuery = clix(ch, timezone)
- .select<{ total_sessions: number }>([
- 'uniq(session_id) as total_sessions',
- ])
- .from(TABLE_NAMES.events)
- .where('project_id', '=', projectId)
- .where('created_at', '>=', clix.exp('now() - INTERVAL 30 MINUTE'));
-
- const minuteCountsQuery = clix(ch, timezone)
- .select<{
- minute: string;
- session_count: number;
- visitor_count: number;
- }>([
- `${clix.toStartOf('created_at', 'minute')} as minute`,
- 'uniq(session_id) as session_count',
- 'uniq(profile_id) as visitor_count',
- ])
- .from(TABLE_NAMES.events)
- .where('project_id', '=', projectId)
- .where('created_at', '>=', clix.exp('now() - INTERVAL 30 MINUTE'))
- .groupBy(['minute'])
- .orderBy('minute', 'ASC')
- .fill(
- clix.exp('toStartOfMinute(now() - INTERVAL 30 MINUTE)'),
- clix.exp('toStartOfMinute(now())'),
- clix.exp('INTERVAL 1 MINUTE')
- );
-
- // Conditionally fetch countries
- const countriesQueryPromise = options.countries
- ? clix(ch, timezone)
- .select<{
- country: string;
- count: number;
- }>(['country', 'uniq(session_id) as count'])
- .from(TABLE_NAMES.events)
- .where('project_id', '=', projectId)
- .where('created_at', '>=', clix.exp('now() - INTERVAL 30 MINUTE'))
- .where('country', '!=', '')
- .where('country', 'IS NOT NULL')
- .groupBy(['country'])
- .orderBy('count', 'DESC')
- .limit(10)
- .execute()
- : Promise.resolve<Array<{ country: string; count: number }>>([]);
-
- // Conditionally fetch referrers
- const referrersQueryPromise = options.referrers
- ? clix(ch, timezone)
- .select<{ referrer: string; count: number }>([
- 'referrer_name as referrer',
- 'uniq(session_id) as count',
- ])
- .from(TABLE_NAMES.events)
- .where('project_id', '=', projectId)
- .where('created_at', '>=', clix.exp('now() - INTERVAL 30 MINUTE'))
- .where('referrer_name', '!=', '')
- .where('referrer_name', 'IS NOT NULL')
- .groupBy(['referrer_name'])
- .orderBy('count', 'DESC')
- .limit(10)
- .execute()
- : Promise.resolve<Array<{ referrer: string; count: number }>>([]);
-
- // Conditionally fetch paths
- const pathsQueryPromise = options.paths
- ? clix(ch, timezone)
- .select<{ path: string; count: number }>([
- 'path',
- 'uniq(session_id) as count',
- ])
- .from(TABLE_NAMES.events)
- .where('project_id', '=', projectId)
- .where('created_at', '>=', clix.exp('now() - INTERVAL 30 MINUTE'))
- .where('path', '!=', '')
- .where('path', 'IS NOT NULL')
- .groupBy(['path'])
- .orderBy('count', 'DESC')
- .limit(10)
- .execute()
- : Promise.resolve<Array<{ path: string; count: number }>>([]);
-
- const [totalSessions, minuteCounts, countries, referrers, paths] =
- await Promise.all([
- totalSessionsQuery.execute(),
- minuteCountsQuery.execute(),
- countriesQueryPromise,
- referrersQueryPromise,
- pathsQueryPromise,
- ]);
-
- return {
- projectId,
- liveCount: totalSessions[0]?.total_sessions || 0,
- project: widget.project,
- histogram: minuteCounts.map((item) => ({
- minute: item.minute,
- sessionCount: item.session_count,
- visitorCount: item.visitor_count,
- timestamp: new Date(item.minute).getTime(),
- time: new Date(item.minute).toLocaleTimeString([], {
- hour: '2-digit',
- minute: '2-digit',
- }),
- })),
- countries: countries.map((item) => ({
- country: item.country,
- count: item.count,
- })),
- referrers: referrers.map((item) => ({
- referrer: item.referrer,
- count: item.count,
- })),
- paths: paths.map((item) => ({
- path: item.path,
- count: item.count,
- })),
- };
- }),
-});
diff --git a/packages/trpc/src/trpc.ts b/packages/trpc/src/trpc.ts
deleted file mode 100644
index 413fc1d11..000000000
--- a/packages/trpc/src/trpc.ts
+++ /dev/null
@@ -1,170 +0,0 @@
-// The tRPC procedure stack, on @openpanel/core's RPC base (ADR-009).
-//
-// There is exactly ONE tRPC instance in the repo: `initTRPC` is called in
-// core/src/rpc/base.ts and nowhere else, so the transformer, the
-// errorFormatter, `Meta` and the context type are single-sourced. M9-004
-// deleted the Fastify adapter and its `createContext` with the V1 boot; the
-// one mount left is `createTrpcFetchHandler`, called from `main.ts`.
-//
-// What still lives here is what core cannot import without pulling a database
-// into a package that must stay bootable with none: the procedures below need
-// `runWithAlsSession` and the access ladder's real lookups. They move into
-// core with auth at P10, at which point this file is a re-export.
-
-import {
- createCacheMiddleware,
- createRateLimitMiddleware,
- middleware,
- procedure,
- type RpcCache,
- type TrpcContext,
-} from '@openpanel/core';
-import { runWithAlsSession } from '@openpanel/core';
-import { getRedisCache } from '@openpanel/redis';
-import { TRPCError } from '@trpc/server';
-import { has } from 'ramda';
-import { getOrganizationAccess, requireProjectAccess } from './access';
-import { TRPCForbiddenError } from './errors';
-import { enforceRateLimit } from './rate-limit';
-
-export type { Meta } from '@openpanel/core';
-export { createTRPCRouter } from '@openpanel/core';
-
-/** What a procedure receives. Core's type, not a second declaration. */
-export type Context = TrpcContext;
-
-const enforceUserIsAuthed = middleware(async ({ ctx, next }) => {
- if (!ctx.session?.userId) {
- throw new TRPCError({ code: 'UNAUTHORIZED', message: 'Not authenticated' });
- }
-
- try {
- return next({
- ctx: {
- session: { ...ctx.session },
- },
- });
- } catch (error) {
- console.error('Failes to get user', error);
- throw new TRPCError({
- code: 'UNAUTHORIZED',
- message: 'Failed to get user',
- });
- }
-});
-
-// Only used on protected routes
-const enforceAccess = middleware(
- async ({ ctx, next, type, meta, getRawInput }) => {
- const sessionId = ctx.session?.session?.id ?? null;
- return runWithAlsSession(sessionId, async () => {
- const rawInput = await getRawInput();
- if (type === 'mutation' && ctx.demoMode) {
- throw new TRPCForbiddenError(
- 'You are not allowed to do this in demo mode'
- );
- }
-
- if (has('projectId', rawInput)) {
- // Fails closed: any procedure that takes a top-level projectId requires
- // write access to mutate, including ones added later. Procedures that
- // resolve the project from a reportId/dashboardId/etc. are invisible to
- // this check and call requireProjectAccess in the handler instead.
- const needsWrite = type === 'mutation' && !meta?.readOnlyMutation;
-
- await requireProjectAccess({
- userId: ctx.session.userId!,
- projectId: rawInput.projectId as string,
- level: needsWrite ? 'write' : 'read',
- });
- }
-
- if (has('organizationId', rawInput)) {
- const access = await getOrganizationAccess({
- userId: ctx.session.userId!,
- organizationId: rawInput.organizationId as string,
- });
-
- if (!access) {
- throw new TRPCForbiddenError(
- 'You do not have access to this organization'
- );
- }
- }
-
- return next();
- });
- }
-);
-
-const loggerMiddleware = middleware(
- async ({ ctx, next, getRawInput, path, input, type }) => {
- const rawInput = await getRawInput();
- // Only log mutations
- if (type === 'mutation') {
- ctx.logger.info(
- {
- path,
- rawInput,
- input,
- userId: ctx.session?.userId,
- organizationId: has('organizationId', rawInput)
- ? rawInput.organizationId
- : undefined,
- projectId: has('projectId', rawInput)
- ? rawInput.projectId
- : undefined,
- },
- 'TRPC mutation'
- );
- }
- return next();
- }
-);
-
-const sessionScopeMiddleware = middleware(async ({ ctx, next }) => {
- const sessionId = ctx.session?.session?.id ?? null;
- return runWithAlsSession(sessionId, async () => {
- return next();
- });
-});
-
-/**
- * Throttle a procedure by client IP, with an exponentially growing lockout for
- * repeat offenders. See `./rate-limit` for the escalation rules and for the log
- * line (`rate limit blocked`) that carries the offending IP.
- */
-export const rateLimitMiddleware = createRateLimitMiddleware(enforceRateLimit);
-
-export const publicProcedure = procedure
- .use(loggerMiddleware)
- .use(sessionScopeMiddleware);
-export const protectedProcedure = procedure
- .use(enforceUserIsAuthed)
- .use(enforceAccess)
- .use(loggerMiddleware)
- .use(sessionScopeMiddleware);
-// Authenticated but WITHOUT the org/project membership check. Use for endpoints
-// that must answer for any logged-in user (e.g. checking your own access to an
-// org you may not belong to) and return null instead of throwing.
-export const protectedProcedureWithoutAccess = procedure
- .use(enforceUserIsAuthed)
- .use(loggerMiddleware)
- .use(sessionScopeMiddleware);
-
-/**
- * The Redis handle is resolved per call, not at import: `getRedisCache()` opens
- * a connection, and V1 did not open one because a router module was loaded.
- */
-const rpcCache: RpcCache = {
- getJson: (key) => getRedisCache().getJson(key),
- setJson: (key, expireInSec, value) =>
- getRedisCache().setJson(key, expireInSec, value),
-};
-
-export const cacheMiddleware = createCacheMiddleware({
- cache: rpcCache,
- // A thunk, because V1 read NODE_ENV on every request rather than once when
- // the router module was first imported.
- serveFromCache: () => process.env.NODE_ENV === 'production',
-});
diff --git a/packages/trpc/tsconfig.json b/packages/trpc/tsconfig.json
deleted file mode 100644
index a4a54fb86..000000000
--- a/packages/trpc/tsconfig.json
+++ /dev/null
@@ -1,13 +0,0 @@
-{
- "extends": "@openpanel/tsconfig/base.json",
- "compilerOptions": {
- "baseUrl": ".",
- "paths": {
- "@/*": ["./src/*"]
- },
- "tsBuildInfoFile": "node_modules/.cache/tsbuildinfo.json",
- "strictNullChecks": true
- },
- "include": ["."],
- "exclude": ["node_modules"]
-}
diff --git a/packages/trpc/vitest.config.ts b/packages/trpc/vitest.config.ts
deleted file mode 100644
index f87a2039f..000000000
--- a/packages/trpc/vitest.config.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import { getSharedVitestConfig } from '../../vitest.shared';
-
-export default getSharedVitestConfig({ __dirname });
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 7368f07bf..6434fd3f8 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -92,15 +92,9 @@ importers:
'@openpanel/db':
specifier: workspace:*
version: link:../../packages/db
- '@openpanel/queue':
- specifier: workspace:*
- version: link:../../packages/queue
'@openpanel/redis':
specifier: workspace:*
version: link:../../packages/redis
- '@openpanel/trpc':
- specifier: workspace:*
- version: link:../../packages/trpc
elysia:
specifier: 1.4.30
@@ -935,9 +929,6 @@ importers:
'@openpanel/payments':
specifier: workspace:*
version: link:../payments
- '@openpanel/queue':
- specifier: workspace:*
- version: link:../queue
'@openpanel/redis':
specifier: workspace:*
version: link:../redis
@@ -1107,9 +1098,6 @@ importers:
'@openpanel/payments':
specifier: workspace:*
version: link:../payments
- '@openpanel/queue':
- specifier: workspace:^
- version: link:../queue
'@openpanel/redis':
specifier: workspace:*
version: link:../redis
@@ -1259,34 +1247,6 @@ importers:
specifier: 'catalog:'
version: 5.9.3
- packages/queue:
- dependencies:
- '@openpanel/core':
- specifier: workspace:*
- version: link:../core
- '@openpanel/db':
- specifier: workspace:*
- version: link:../db
- '@openpanel/redis':
- specifier: workspace:*
- version: link:../redis
- bullmq:
- specifier: ^5.63.0
- version: 5.63.0([email protected])
- kafkajs:
- specifier: ^2.2.4
- version: 2.2.4
- devDependencies:
- '@openpanel/tsconfig':
- specifier: workspace:*
- version: link:../../tooling/typescript
- '@types/node':
- specifier: 'catalog:'
- version: 24.10.1
- typescript:
- specifier: 'catalog:'
- version: 5.9.3
-
packages/redis:
dependencies:
'@openpanel/json':
@@ -1511,91 +1471,6 @@ importers:
specifier: 'catalog:'
version: 5.9.3
- packages/trpc:
- dependencies:
- '@better-agent/core':
- specifier: ^0.1.0-beta.3
- version: 0.1.0-beta.3
- '@openpanel/common':
- specifier: workspace:*
- version: link:../common
- '@openpanel/constants':
- specifier: workspace:*
- version: link:../constants
- '@openpanel/core':
- specifier: workspace:*
- version: link:../core
- '@openpanel/db':
- specifier: workspace:*
- version: link:../db
- '@openpanel/email':
- specifier: workspace:*
- version: link:../email
- '@openpanel/payments':
- specifier: workspace:^
- version: link:../payments
- '@openpanel/queue':
- specifier: workspace:*
- version: link:../queue
- '@openpanel/redis':
- specifier: workspace:*
- version: link:../redis
- '@openpanel/validation':
- specifier: workspace:*
- version: link:../validation
- '@trpc/client':
- specifier: ^11.17.0
- '@trpc/server':
- specifier: ^11.17.0
- version: 11.17.0([email protected])
- date-fns:
- specifier: ^3.3.1
- version: 3.3.1
- mathjs:
- specifier: ^12.3.2
- version: 12.3.2
- prisma-error-enum:
- specifier: ^0.1.3
- version: 0.1.3
- ramda:
- specifier: ^0.29.1
- version: 0.29.1
- short-unique-id:
- specifier: ^5.0.3
- version: 5.0.3
- sqlstring:
- specifier: ^2.3.3
- version: 2.3.3
- superjson:
- specifier: ^1.13.3
- version: 1.13.3
- uuid:
- specifier: ^9.0.1
- version: 9.0.1
- zod:
- specifier: 'catalog:'
- version: 4.3.6
- devDependencies:
- '@openpanel/tsconfig':
- specifier: workspace:*
- version: link:../../tooling/typescript
- '@types/node':
- specifier: 'catalog:'
- version: 24.10.1
- '@types/ramda':
- specifier: ^0.29.6
- version: 0.29.10
- '@types/sqlstring':
- specifier: ^2.3.2
- version: 2.3.2
- prisma:
- specifier: ^5.1.1
- version: 5.9.1
- typescript:
- specifier: 'catalog:'
- version: 5.9.3
-
packages/validation:
dependencies:
'@openpanel/constants':
@@ -4852,61 +4727,31 @@ packages:
'@cfworker/json-schema':
optional: true
- '@msgpackr-extract/[email protected]':
- resolution: {integrity: sha512-9bfjwDxIDWmmOKusUcqdS4Rw+SETlp9Dy39Xui9BEGEk19dDwH0jhipwFzEff/pFg95NKymc6TOTbRKcWeRqyQ==}
- cpu: [arm64]
- os: [darwin]
-
'@msgpackr-extract/[email protected]':
resolution: {integrity: sha512-LCkGo6JDfaBhgST7UpPWgNgLINpcpabaHfyz5OBx75nUYxBsaEPxjnyNjWpeb/xBup/682QnBfRBy2/LvPutZQ==}
cpu: [arm64]
os: [darwin]
- '@msgpackr-extract/[email protected]':
- resolution: {integrity: sha512-lwriRAHm1Yg4iDf23Oxm9n/t5Zpw1lVnxYU3HnJPTi2lJRkKTrps1KVgvL6m7WvmhYVt/FIsssWay+k45QHeuw==}
- cpu: [x64]
- os: [darwin]
-
'@msgpackr-extract/[email protected]':
resolution: {integrity: sha512-zExlW9zUJKZH/tOtVMttwjKa4Xm/3KcNjnE3dPN92uCktwavMxpgCA3MoJK/DOnTWsQgo224OaST27/mPNAf+w==}
cpu: [x64]
os: [darwin]
- '@msgpackr-extract/[email protected]':
- resolution: {integrity: sha512-FU20Bo66/f7He9Fp9sP2zaJ1Q8L9uLPZQDub/WlUip78JlPeMbVL8546HbZfcW9LNciEXc8d+tThSJjSC+tmsg==}
- cpu: [arm64]
- os: [linux]
-
'@msgpackr-extract/[email protected]':
resolution: {integrity: sha512-dgX0P/9wGPJeHFBG+ZmhgE6bmtMt7NP5CRBGyyktpopdk/mW4POnrpQsSLtKI1dwpc+pPLuXHDh6vvskyQE/sw==}
cpu: [arm64]
os: [linux]
- '@msgpackr-extract/[email protected]':
- resolution: {integrity: sha512-MOI9Dlfrpi2Cuc7i5dXdxPbFIgbDBGgKR5F2yWEa6FVEtSWncfVNKW5AKjImAQ6CZlBK9tympdsZJ2xThBiWWA==}
- cpu: [arm]
- os: [linux]
-
'@msgpackr-extract/[email protected]':
resolution: {integrity: sha512-Tg3yX65f5GbtXLkrYEHE5oibZG9epyYWas7FogTTEJeDEF9JlXJzKgXaNhT3UXlTOeA+AfZpYZYZ0uPj7Cfquw==}
cpu: [arm]
os: [linux]
- '@msgpackr-extract/[email protected]':
- resolution: {integrity: sha512-gsWNDCklNy7Ajk0vBBf9jEx04RUxuDQfBse918Ww+Qb9HCPoGzS+XJTLe96iN3BVK7grnLiYghP/M4L8VsaHeA==}
- cpu: [x64]
- os: [linux]
-
'@msgpackr-extract/[email protected]':
resolution: {integrity: sha512-8TNXMEjJc3QEy7R/x1INhgiU+XakDAFUzBhaz7+Rbrs8NH5UQeHQxxmzsSBJGyV6I1jW79undiQm8tOI+D+8FQ==}
cpu: [x64]
os: [linux]
- '@msgpackr-extract/[email protected]':
- resolution: {integrity: sha512-O+6Gs8UeDbyFpbSh2CPEz/UOrrdWPTBYNblZK5CxxLisYt4kGX3Sc+czffFonyjiGSq3jWLwJS/CCJc7tBr4sQ==}
- cpu: [x64]
- os: [win32]
-
'@msgpackr-extract/[email protected]':
resolution: {integrity: sha512-CmCXPQrkbwExx3j946/PtHWHbYJiCRBRDl4BlkRQcJB/YOwQxJRTpoo7aTsortjgoJ1x7opzTSxn7C+ASSLVjQ==}
cpu: [x64]
@@ -10397,9 +10242,6 @@ packages:
resolution: {integrity: sha512-uYBjakWipfaO/bXI7E8rq6kpwHRZK5cNYrUv2OzZSI/FvmdMyXJ2tG9dKcjEC5YHmHpUAwsargWIZNWdxb/bnQ==}
- resolution: {integrity: sha512-HT1iM3Jt4bZeg3Ru/MxrOy2iIItxcl1Pz5Ync1Vrot70jBpVguMxFEiSaDU57BwYwR4iwnObDnzct2lirKkX5A==}
-
resolution: {integrity: sha512-ie2/80FlcAF2pZM6NU90adIPPpvuqlPSqbRRW3t5ktgJMTrXRJ7D0e8gjTXgST4skpJeTitM0GKNUBEgrmBq3A==}
engines: {node: '>=14.17.0'}
@@ -10943,11 +10785,6 @@ packages:
resolution: {integrity: sha512-VQ2MBenTq1fWZUH9DJNGti7kKv6EeAuYr3cLwxUWhIu1baTaXh4Ib5W2CqHVqib4/MqbYGJqiL3Zb8GJZr3l4g==}
- resolution: {integrity: sha512-p0SaNjrHOnQeR8/VnfGbmg9te2kfyYSQ7Sc/j/6DtPL3JQvKxmjO9TSjNFpujqV3vEYYBvNNvXSxzyksBWAx1Q==}
- engines: {node: '>=12.0.0'}
- deprecated: v4 is no longer maintained, upgrade to v5
-
resolution: {integrity: sha512-izNAxJyRWUP8ljBoDSub5WyrVOUlT4SLGShswE7eoRBpp6QUsSycYxLBMJlbshgPBMcPT/nrfgjNY2918ayv2A==}
engines: {node: '>=18'}
@@ -14623,17 +14460,10 @@ packages:
resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}
- resolution: {integrity: sha512-SdzXp4kD/Qf8agZ9+iTu6eql0m3kWm1A2y1hkpTeVNENutaB0BwHlSvAIaMxwntmRUAUjon2V4L8Z/njd0Ct8A==}
- hasBin: true
-
resolution: {integrity: sha512-4kmO/MdyUIkLIvTPr8VHLil4AtoKIoniWPIEk5+CDy0xnWC84azhSFmuJ7PxZdsYtiP5kEeQsORAVIeMgxT+Hw==}
hasBin: true
- resolution: {integrity: sha512-UjkUHN0yqp9RWKy0Lplhh+wlpdt9oQBYgULZOiFhV3VclSF1JnSQWZ5r9gORQlNYaUKQoR8itv7g7z1xDDuACA==}
-
resolution: {integrity: sha512-p/pBCVO63CsvvpkomUnNNag6+n38rULuDA6HHe70o2gtC8ODI52foF/4ko2qQcp6OiErJXTmrZeXmsGGHsIQNQ==}
@@ -14819,10 +14649,6 @@ packages:
resolution: {integrity: sha512-LarFH0+6VfriEhqMMcLX2F7SwSXeWwnEAJEsYm5QKWchiVYVvJyV9v7UDvUv+w5HO23ZpQTXDv/GxdDdMyOuoQ==}
engines: {node: '>= 6.13.0'}
- resolution: {integrity: sha512-YlCCc6Wffkx0kHkmam79GKvDQ6x+QZkMjFGrIMxgFNILFvGSbCp2fCBC55pGTT9gVaz8Na5CLmxt/urtzRv36w==}
- hasBin: true
-
resolution: {integrity: sha512-s+w+rBWnpTMwSFbaE0UXsRlg7hU4FjekKU4eyAih5T8nJuNZT1nNsskXpxmeqSK9UzkBl6UgRlnKc8hz8IEqOw==}
hasBin: true
@@ -18048,10 +17874,6 @@ packages:
resolution: {integrity: sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==}
engines: {node: '>= 0.4.0'}
- resolution: {integrity: sha512-0/A9rDy9P7cJ+8w1c9WD9V//9Wj15Ce2MPz8Ri6032usz+NfePxx5AcN3bN+r6ZL6jEo066/yNYB3tn4pQEx+A==}
- hasBin: true
-
resolution: {integrity: sha512-DPSke0pXhTZgoF/d+WSt2QaKMCFSfx7QegxEWT+JOuHF5aWrKEn0G+ztjuJg/gG8/ItK+rbPCD/yNv8yyih6Cg==}
deprecated: uuid@10 and below is no longer supported. For ESM codebases, update to uuid@latest. For CommonJS codebases, use uuid@11 (but be aware this version will likely be deprecated in 2028).
@@ -23635,39 +23457,21 @@ snapshots:
transitivePeerDependencies:
- supports-color
- '@msgpackr-extract/[email protected]':
- optional: true
-
'@msgpackr-extract/[email protected]':
optional: true
- '@msgpackr-extract/[email protected]':
- optional: true
-
'@msgpackr-extract/[email protected]':
optional: true
- '@msgpackr-extract/[email protected]':
- optional: true
-
'@msgpackr-extract/[email protected]':
optional: true
- '@msgpackr-extract/[email protected]':
- optional: true
-
'@msgpackr-extract/[email protected]':
optional: true
- '@msgpackr-extract/[email protected]':
- optional: true
-
'@msgpackr-extract/[email protected]':
optional: true
- '@msgpackr-extract/[email protected]':
- optional: true
-
'@msgpackr-extract/[email protected]':
optional: true
@@ -30351,18 +30155,6 @@ snapshots:
- dependencies:
- cron-parser: 4.9.0
- ioredis: 5.8.2([email protected])
- msgpackr: 1.11.5
- node-abort-controller: 3.1.1
- semver: 7.7.2
- tslib: 2.7.0
- uuid: 11.1.0
- transitivePeerDependencies:
- - supports-color
-
dependencies:
cron-parser: 5.10.0
@@ -30956,10 +30748,6 @@ snapshots:
- dependencies:
- luxon: 3.7.2
-
dependencies:
luxon: 3.7.2
@@ -35582,18 +35370,6 @@ snapshots:
- dependencies:
- node-gyp-build-optional-packages: 5.0.7
- optionalDependencies:
- '@msgpackr-extract/msgpackr-extract-darwin-arm64': 3.0.2
- '@msgpackr-extract/msgpackr-extract-darwin-x64': 3.0.2
- '@msgpackr-extract/msgpackr-extract-linux-arm': 3.0.2
- '@msgpackr-extract/msgpackr-extract-linux-arm64': 3.0.2
- '@msgpackr-extract/msgpackr-extract-linux-x64': 3.0.2
- '@msgpackr-extract/msgpackr-extract-win32-x64': 3.0.2
- optional: true
-
dependencies:
node-gyp-build-optional-packages: 5.2.2
@@ -35606,10 +35382,6 @@ snapshots:
'@msgpackr-extract/msgpackr-extract-win32-x64': 3.0.4
optional: true
- optionalDependencies:
- msgpackr-extract: 3.0.2
-
optionalDependencies:
msgpackr-extract: 3.0.4
@@ -35988,9 +35760,6 @@ snapshots:
- optional: true
-
dependencies:
detect-libc: 2.1.2
@@ -39785,8 +39554,6 @@ snapshots:
-