Skip to content

Open-source status page, incident response and uptime monitoring

feat: component subscriptions (#1901)

Maximilian Kaske4ce1431854ed
diff --git a/apps/dashboard/src/app/(dashboard)/status-pages/[id]/subscribers/page.tsx b/apps/dashboard/src/app/(dashboard)/status-pages/[id]/subscribers/page.tsx
index 46376a025..74d62d7aa 100644
--- a/apps/dashboard/src/app/(dashboard)/status-pages/[id]/subscribers/page.tsx
+++ b/apps/dashboard/src/app/(dashboard)/status-pages/[id]/subscribers/page.tsx
@@ -24,35 +24,40 @@ import { columns } from "@/components/data-table/subscribers/columns";
import { UpgradeDialog } from "@/components/dialogs/upgrade";
import { DataTable } from "@/components/ui/data-table/data-table";
import { useTRPC } from "@/lib/trpc/client";
+import type { RouterOutputs } from "@openstatus/api";
import { useQuery } from "@tanstack/react-query";
import { Lock } from "lucide-react";
import { useParams } from "next/navigation";
import { useState } from "react";
+type Subscriber = RouterOutputs["pageSubscriber"]["list"][number];
+
const EXAMPLES = [
{
id: 1,
createdAt: new Date(),
- updatedAt: null,
pageId: 1,
- token: null,
+ channelType: "email",
acceptedAt: new Date(),
- expiresAt: new Date(),
unsubscribedAt: null,
+ components: [],
+ isEntirePage: true,
+ webhookUrl: null,
},
{
id: 2,
createdAt: new Date(),
- updatedAt: null,
pageId: 1,
- token: null,
+ channelType: "email",
acceptedAt: new Date(),
- expiresAt: new Date(),
unsubscribedAt: null,
+ components: [],
+ isEntirePage: true,
+ webhookUrl: null,
},
-];
+] satisfies Subscriber[];
export default function Page() {
const { id } = useParams<{ id: string }>();
diff --git a/apps/dashboard/src/components/forms/components/update.tsx b/apps/dashboard/src/components/forms/components/update.tsx
index 30de31345..d8d0128c8 100644
--- a/apps/dashboard/src/components/forms/components/update.tsx
+++ b/apps/dashboard/src/components/forms/components/update.tsx
@@ -90,11 +90,8 @@ export function FormComponentsUpdate() {
onSubmit={async (values) => {
await updateComponentsMutation.mutateAsync({
pageId: Number.parseInt(id),
- components: values.components.map(({ id, ...rest }) => rest),
- groups: values.groups.map(({ id, components, ...rest }) => ({
- ...rest,
- components: components.map(({ id, ...c }) => c),
- })),
+ components: values.components,
+ groups: values.groups.map(({ id: _groupId, ...rest }) => rest),
});
}}
/>
diff --git a/apps/server/.dockerignore b/apps/server/.dockerignore
index a6903313b..c8236a8b4 100644
--- a/apps/server/.dockerignore
+++ b/apps/server/.dockerignore
@@ -1,4 +1,4 @@
-# This file is generated by Dofigen v2.6.0
+# This file is generated by Dofigen v2.7.0
# See https://github.com/lenra-io/dofigen
node_modules
diff --git a/apps/server/Dockerfile b/apps/server/Dockerfile
index 4a23bb6bd..241e0ba2d 100644
--- a/apps/server/Dockerfile
+++ b/apps/server/Dockerfile
@@ -1,5 +1,5 @@
# syntax=docker/dockerfile:1.19.0
-# This file is generated by Dofigen v2.6.0
+# This file is generated by Dofigen v2.7.0
# See https://github.com/lenra-io/dofigen
# install
@@ -37,6 +37,7 @@ RUN \
--mount=type=bind,target=packages/upstash/package.json,source=packages/upstash/package.json \
--mount=type=bind,target=packages/utils/package.json,source=packages/utils/package.json \
--mount=type=bind,target=packages/tsconfig/package.json,source=packages/tsconfig/package.json \
+ --mount=type=bind,target=packages/subscriptions/package.json,source=packages/subscriptions/package.json \
--mount=type=bind,target=packages/assertions/package.json,source=packages/assertions/package.json \
--mount=type=bind,target=packages/theme-store/package.json,source=packages/theme-store/package.json \
--mount=type=cache,target=/root/.bun/install/cache,sharing=locked \
@@ -60,11 +61,11 @@ COPY \
RUN bun build --compile --sourcemap src/index.ts --outfile=app
# runtime
-FROM debian@sha256:b32674fb57780ad57d7b0749242d3f585f462f4ec4a60ae0adacd945f9cb9734 AS runtime
+FROM debian@sha256:4333240150a6924f878e05ec2c998aec95238010e0e4d2fec6161c90128c4652 AS runtime
LABEL \
- io.dofigen.version="2.6.0" \
+ io.dofigen.version="2.7.0" \
org.opencontainers.image.authors="OpenStatus Team" \
- org.opencontainers.image.base.digest="sha256:b32674fb57780ad57d7b0749242d3f585f462f4ec4a60ae0adacd945f9cb9734" \
+ org.opencontainers.image.base.digest="sha256:4333240150a6924f878e05ec2c998aec95238010e0e4d2fec6161c90128c4652" \
org.opencontainers.image.base.name="docker.io/debian:bullseye-slim" \
org.opencontainers.image.description="REST API server with Hono framework for OpenStatus" \
org.opencontainers.image.source="https://github.com/openstatusHQ/openstatus" \
diff --git a/apps/server/dofigen.lock b/apps/server/dofigen.lock
index 6f5142585..446e52ff3 100644
--- a/apps/server/dofigen.lock
+++ b/apps/server/dofigen.lock
@@ -15,8 +15,8 @@ effective: |
path: oven/bun
digest: sha256:f20d9cf365ab35529384f1717687c739c92e6f39157a35a95ef06f4049a10e4a
label:
- org.opencontainers.image.base.name: docker.io/oven/bun:1.3.6
org.opencontainers.image.base.digest: sha256:f20d9cf365ab35529384f1717687c739c92e6f39157a35a95ef06f4049a10e4a
+ org.opencontainers.image.base.name: docker.io/oven/bun:1.3.6
org.opencontainers.image.stage: install
workdir: /app/
run:
@@ -78,6 +78,8 @@ effective: |
source: packages/utils/package.json
- target: packages/tsconfig/package.json
source: packages/tsconfig/package.json
+ - target: packages/subscriptions/package.json
+ source: packages/subscriptions/package.json
- target: packages/assertions/package.json
source: packages/assertions/package.json
- target: packages/theme-store/package.json
@@ -87,8 +89,8 @@ effective: |
path: oven/bun
digest: sha256:f20d9cf365ab35529384f1717687c739c92e6f39157a35a95ef06f4049a10e4a
label:
- org.opencontainers.image.stage: build
org.opencontainers.image.base.digest: sha256:f20d9cf365ab35529384f1717687c739c92e6f39157a35a95ef06f4049a10e4a
+ org.opencontainers.image.stage: build
org.opencontainers.image.base.name: docker.io/oven/bun:1.3.6
workdir: /app/apps/server
env:
@@ -105,16 +107,16 @@ effective: |
- bun build --compile --sourcemap src/index.ts --outfile=app
fromImage:
path: debian
- digest: sha256:b32674fb57780ad57d7b0749242d3f585f462f4ec4a60ae0adacd945f9cb9734
+ digest: sha256:4333240150a6924f878e05ec2c998aec95238010e0e4d2fec6161c90128c4652
label:
- io.dofigen.version: 2.6.0
+ org.opencontainers.image.authors: OpenStatus Team
+ io.dofigen.version: 2.7.0
+ org.opencontainers.image.base.digest: sha256:4333240150a6924f878e05ec2c998aec95238010e0e4d2fec6161c90128c4652
+ org.opencontainers.image.description: REST API server with Hono framework for OpenStatus
org.opencontainers.image.vendor: OpenStatus
- org.opencontainers.image.base.digest: sha256:b32674fb57780ad57d7b0749242d3f585f462f4ec4a60ae0adacd945f9cb9734
org.opencontainers.image.source: https://github.com/openstatusHQ/openstatus
- org.opencontainers.image.base.name: docker.io/debian:bullseye-slim
- org.opencontainers.image.description: REST API server with Hono framework for OpenStatus
- org.opencontainers.image.authors: OpenStatus Team
org.opencontainers.image.title: OpenStatus Server
+ org.opencontainers.image.base.name: docker.io/debian:bullseye-slim
user:
user: '1000'
group: '1000'
@@ -141,17 +143,17 @@ effective: |
retries: 3
images:
docker.io:
- library:
- debian:
- bullseye-slim:
- digest: sha256:b32674fb57780ad57d7b0749242d3f585f462f4ec4a60ae0adacd945f9cb9734
oven:
bun:
1.3.6:
digest: sha256:f20d9cf365ab35529384f1717687c739c92e6f39157a35a95ef06f4049a10e4a
+ library:
+ debian:
+ bullseye-slim:
+ digest: sha256:4333240150a6924f878e05ec2c998aec95238010e0e4d2fec6161c90128c4652
resources:
dofigen.yml:
- hash: 534b1d0a16fe15d3ca9a01f090b1303ac7c2e011607e25167357592a6a987129
+ hash: d3a2fdcc47230fbc3d4bf7c1298d053cc7f7cc63b035b6c19809554394304328
content: |
# Files to exclude from Docker context
ignore:
@@ -200,6 +202,7 @@ resources:
- packages/upstash/package.json
- packages/utils/package.json
- packages/tsconfig/package.json
+ - packages/subscriptions/package.json
- packages/assertions/package.json
- packages/theme-store/package.json
run: bun install --production --frozen-lockfile --verbose
diff --git a/apps/server/dofigen.yml b/apps/server/dofigen.yml
index febe21276..1b9a86b3a 100644
--- a/apps/server/dofigen.yml
+++ b/apps/server/dofigen.yml
@@ -45,6 +45,7 @@ builders:
- packages/upstash/package.json
- packages/utils/package.json
- packages/tsconfig/package.json
+ - packages/subscriptions/package.json
- packages/assertions/package.json
- packages/theme-store/package.json
run: bun install --production --frozen-lockfile --verbose
diff --git a/apps/server/package.json b/apps/server/package.json
index 5428b5bcf..5c3ea5b07 100644
--- a/apps/server/package.json
+++ b/apps/server/package.json
@@ -24,6 +24,7 @@
"@logtape/otel": "2.0.1",
"@logtape/sentry": "2.0.1",
"@openstatus/analytics": "workspace:*",
+ "@openstatus/subscriptions": "workspace:*",
"@openstatus/notification-discord": "workspace:*",
"@openstatus/notification-google-chat": "workspace:*",
"@openstatus/notification-grafana-oncall": "workspace:*",
diff --git a/apps/server/src/libs/test/preload.ts b/apps/server/src/libs/test/preload.ts
index aa1a088bb..1ee432e14 100644
--- a/apps/server/src/libs/test/preload.ts
+++ b/apps/server/src/libs/test/preload.ts
@@ -1,5 +1,19 @@
import { mock } from "bun:test";
+// Subscription dispatch spies — accessible in tests via globalThis.__subscriptionSpies
+const dispatchStatusReportUpdateSpy = mock((_id: number) => Promise.resolve());
+const dispatchMaintenanceUpdateSpy = mock((_id: number) => Promise.resolve());
+
+(globalThis as Record<string, unknown>).__subscriptionSpies = {
+ dispatchStatusReportUpdate: dispatchStatusReportUpdateSpy,
+ dispatchMaintenanceUpdate: dispatchMaintenanceUpdateSpy,
+};
+
+mock.module("@openstatus/subscriptions", () => ({
+ dispatchStatusReportUpdate: dispatchStatusReportUpdateSpy,
+ dispatchMaintenanceUpdate: dispatchMaintenanceUpdateSpy,
+}));
+
const testRedisStore = new Map<string, string>();
(globalThis as Record<string, unknown>).__testRedisStore = testRedisStore;
diff --git a/apps/server/src/routes/rpc/services/maintenance/__tests__/maintenance.test.ts b/apps/server/src/routes/rpc/services/maintenance/__tests__/maintenance.test.ts
index 04ca7bedb..b24b23b40 100644
--- a/apps/server/src/routes/rpc/services/maintenance/__tests__/maintenance.test.ts
+++ b/apps/server/src/routes/rpc/services/maintenance/__tests__/maintenance.test.ts
@@ -1,4 +1,4 @@
-import { afterAll, beforeAll, describe, expect, spyOn, test } from "bun:test";
+import { afterAll, beforeAll, describe, expect, test } from "bun:test";
import { db, eq } from "@openstatus/db";
import {
maintenance,
@@ -7,15 +7,14 @@ import {
pageComponent,
pageSubscriber,
} from "@openstatus/db/src/schema";
-import { EmailClient } from "@openstatus/emails";
import { app } from "@/index";
-// Mock the sendMaintenanceNotification method
-const sendMaintenanceNotificationMock = spyOn(
- EmailClient.prototype,
- "sendMaintenanceNotification",
-).mockResolvedValue(undefined);
+const subscriptionSpies = (globalThis as Record<string, unknown>)
+ .__subscriptionSpies as {
+ dispatchStatusReportUpdate: ReturnType<typeof import("bun:test").mock>;
+ dispatchMaintenanceUpdate: ReturnType<typeof import("bun:test").mock>;
+};
/**
* Helper to make ConnectRPC requests using the Connect protocol (JSON).
@@ -458,7 +457,7 @@ describe("MaintenanceService.CreateMaintenance", () => {
});
test("creates maintenance with notify=true", async () => {
- sendMaintenanceNotificationMock.mockClear();
+ subscriptionSpies.dispatchMaintenanceUpdate.mockClear();
const fromDate = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);
const toDate = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000 + 3600000);
@@ -483,12 +482,9 @@ describe("MaintenanceService.CreateMaintenance", () => {
expect(data).toHaveProperty("maintenance");
expect(data.maintenance.title).toBe(`${TEST_PREFIX}-with-notify`);
- // Verify notification was sent
- expect(sendMaintenanceNotificationMock).toHaveBeenCalledTimes(1);
- const mockCall = sendMaintenanceNotificationMock.mock.calls[0][0];
- expect(mockCall.maintenanceTitle).toBe(`${TEST_PREFIX}-with-notify`);
- expect(mockCall.message).toBe(
- "Notifying subscribers about this maintenance.",
+ // Verify dispatcher was called (dispatchers are mocked in preload.ts)
+ expect(subscriptionSpies.dispatchMaintenanceUpdate).toHaveBeenCalledTimes(
+ 1,
);
// Clean up
@@ -506,7 +502,7 @@ describe("MaintenanceService.CreateMaintenance", () => {
});
test("creates maintenance with notify=false (default)", async () => {
- sendMaintenanceNotificationMock.mockClear();
+ subscriptionSpies.dispatchMaintenanceUpdate.mockClear();
const fromDate = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);
const toDate = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000 + 3600000);
@@ -531,8 +527,8 @@ describe("MaintenanceService.CreateMaintenance", () => {
expect(data).toHaveProperty("maintenance");
expect(data.maintenance.title).toBe(`${TEST_PREFIX}-no-notify`);
- // Verify notification was NOT sent
- expect(sendMaintenanceNotificationMock).not.toHaveBeenCalled();
+ // Verify dispatcher was NOT called
+ expect(subscriptionSpies.dispatchMaintenanceUpdate).not.toHaveBeenCalled();
// Clean up
await db
diff --git a/apps/server/src/routes/rpc/services/maintenance/index.ts b/apps/server/src/routes/rpc/services/maintenance/index.ts
index 846c112b7..12a266773 100644
--- a/apps/server/src/routes/rpc/services/maintenance/index.ts
+++ b/apps/server/src/routes/rpc/services/maintenance/index.ts
@@ -1,33 +1,21 @@
import type { ServiceImpl } from "@connectrpc/connect";
-import {
- and,
- db,
- desc,
- eq,
- inArray,
- isNotNull,
- isNull,
- sql,
-} from "@openstatus/db";
+import { and, db, desc, eq, inArray, sql } from "@openstatus/db";
import {
maintenance,
maintenancesToPageComponents,
page,
pageComponent,
- pageSubscriber,
} from "@openstatus/db/src/schema";
import type { Limits } from "@openstatus/db/src/schema/plan/schema";
-import { EmailClient } from "@openstatus/emails";
import type { MaintenanceService } from "@openstatus/proto/maintenance/v1";
-import { env } from "@/env";
+import { dispatchMaintenanceUpdate } from "@openstatus/subscriptions";
+
import { getRpcContext } from "../../interceptors";
import {
dbMaintenanceToProto,
dbMaintenanceToProtoSummary,
} from "./converters";
-
-const emailClient = new EmailClient({ apiKey: env.RESEND_API_KEY });
import {
invalidDateFormatError,
invalidDateRangeError,
@@ -199,84 +187,19 @@ async function validatePageExists(
/**
* Helper to send maintenance notifications to page subscribers.
+ * Uses the subscription dispatcher for component-aware filtering.
*/
async function sendMaintenanceNotification(params: {
maintenanceId: number;
- pageId: number;
- maintenanceTitle: string;
- message: string;
- from: Date;
- to: Date;
limits: Limits;
}) {
- const { pageId, maintenanceTitle, message, from, to, limits } = params;
+ const { maintenanceId, limits } = params;
- // Check if workspace has status-subscribers feature enabled
if (!limits["status-subscribers"]) {
return;
}
- // Get page info
- const pageInfo = await db.query.page.findFirst({
- where: eq(page.id, pageId),
- });
-
- if (!pageInfo) {
- return;
- }
-
- // Get verified subscribers who haven't unsubscribed
- const subscribers = await db
- .select()
- .from(pageSubscriber)
- .where(
- and(
- eq(pageSubscriber.pageId, pageId),
- isNotNull(pageSubscriber.acceptedAt),
- isNull(pageSubscriber.unsubscribedAt),
- ),
- )
- .all();
-
- const validSubscribers = subscribers.filter(
- (s): s is typeof s & { token: string } =>
- s.token !== null && s.acceptedAt !== null && s.unsubscribedAt === null,
- );
-
- if (validSubscribers.length === 0) {
- return;
- }
-
- // Get page components for this maintenance
- const maintenanceWithComponents = await db.query.maintenance.findFirst({
- where: eq(maintenance.id, params.maintenanceId),
- with: {
- maintenancesToPageComponents: {
- with: { pageComponent: true },
- },
- },
- });
-
- const pageComponents =
- maintenanceWithComponents?.maintenancesToPageComponents.map(
- (i) => i.pageComponent.name,
- ) ?? [];
-
- // Send notification emails
- await emailClient.sendMaintenanceNotification({
- subscribers: validSubscribers.map((subscriber) => ({
- email: subscriber.email,
- token: subscriber.token,
- })),
- pageTitle: pageInfo.title,
- pageSlug: pageInfo.slug,
- customDomain: pageInfo.customDomain,
- maintenanceTitle,
- message,
- from: from.toISOString(),
- to: to.toISOString(),
- pageComponents,
- });
+ await dispatchMaintenanceUpdate(maintenanceId);
}
/**
@@ -349,11 +272,6 @@ export const maintenanceServiceImpl: ServiceImpl<typeof MaintenanceService> = {
if (req.notify) {
await sendMaintenanceNotification({
maintenanceId: newMaintenance.id,
- pageId: providedPageId,
- maintenanceTitle: newMaintenance.title,
- message: newMaintenance.message,
- from: fromDate,
- to: toDate,
limits: rpcCtx.workspace.limits,
});
}
diff --git a/apps/server/src/routes/rpc/services/status-report/__tests__/status-report.test.ts b/apps/server/src/routes/rpc/services/status-report/__tests__/status-report.test.ts
index 5ac95a720..2ddb09625 100644
--- a/apps/server/src/routes/rpc/services/status-report/__tests__/status-report.test.ts
+++ b/apps/server/src/routes/rpc/services/status-report/__tests__/status-report.test.ts
@@ -1,4 +1,4 @@
-import { afterAll, beforeAll, describe, expect, spyOn, test } from "bun:test";
+import { afterAll, beforeAll, describe, expect, test } from "bun:test";
import { db, eq } from "@openstatus/db";
import {
page,
@@ -8,17 +8,16 @@ import {
statusReportUpdate,
statusReportsToPageComponents,
} from "@openstatus/db/src/schema";
-import { EmailClient } from "@openstatus/emails";
import { StatusReportStatus } from "@openstatus/proto/status_report/v1";
import { app } from "@/index";
import { protoStatusToDb } from "../converters";
-// Mock the sendStatusReportUpdate method
-const sendStatusReportUpdateMock = spyOn(
- EmailClient.prototype,
- "sendStatusReportUpdate",
-).mockResolvedValue(undefined);
+const subscriptionSpies = (globalThis as Record<string, unknown>)
+ .__subscriptionSpies as {
+ dispatchStatusReportUpdate: ReturnType<typeof import("bun:test").mock>;
+ dispatchMaintenanceUpdate: ReturnType<typeof import("bun:test").mock>;
+};
/**
* Helper to make ConnectRPC requests using the Connect protocol (JSON).
@@ -520,7 +519,7 @@ describe("StatusReportService.CreateStatusReport", () => {
});
test("creates status report with notify=true", async () => {
- sendStatusReportUpdateMock.mockClear();
+ subscriptionSpies.dispatchStatusReportUpdate.mockClear();
const res = await connectRequest(
"CreateStatusReport",
@@ -543,12 +542,10 @@ describe("StatusReportService.CreateStatusReport", () => {
expect(data.statusReport.title).toBe(`${TEST_PREFIX}-with-notify`);
expect(data.statusReport.updates).toHaveLength(1);
- // Verify notification was sent
- expect(sendStatusReportUpdateMock).toHaveBeenCalledTimes(1);
- const mockCall = sendStatusReportUpdateMock.mock.calls[0][0];
- expect(mockCall.reportTitle).toBe(`${TEST_PREFIX}-with-notify`);
- expect(mockCall.status).toBe("investigating");
- expect(mockCall.message).toBe("Notifying subscribers about this issue.");
+ // Verify dispatcher was called (dispatchers are mocked in preload.ts)
+ expect(subscriptionSpies.dispatchStatusReportUpdate).toHaveBeenCalledTimes(
+ 1,
+ );
// Clean up
await db
@@ -570,7 +567,7 @@ describe("StatusReportService.CreateStatusReport", () => {
});
test("creates status report with notify=false (default)", async () => {
- sendStatusReportUpdateMock.mockClear();
+ subscriptionSpies.dispatchStatusReportUpdate.mockClear();
const res = await connectRequest(
"CreateStatusReport",
@@ -592,8 +589,8 @@ describe("StatusReportService.CreateStatusReport", () => {
expect(data).toHaveProperty("statusReport");
expect(data.statusReport.title).toBe(`${TEST_PREFIX}-no-notify`);
- // Verify notification was NOT sent
- expect(sendStatusReportUpdateMock).not.toHaveBeenCalled();
+ // Verify dispatcher was NOT called
+ expect(subscriptionSpies.dispatchStatusReportUpdate).not.toHaveBeenCalled();
// Clean up
await db
@@ -1403,7 +1400,7 @@ describe("StatusReportService.AddStatusReportUpdate", () => {
});
test("adds update with notify=true", async () => {
- sendStatusReportUpdateMock.mockClear();
+ subscriptionSpies.dispatchStatusReportUpdate.mockClear();
const res = await connectRequest(
"AddStatusReportUpdate",
@@ -1429,18 +1426,14 @@ describe("StatusReportService.AddStatusReportUpdate", () => {
);
expect(newUpdate).toBeDefined();
- // Verify notification was sent
- expect(sendStatusReportUpdateMock).toHaveBeenCalledTimes(1);
- const mockCall = sendStatusReportUpdateMock.mock.calls[0][0];
- expect(mockCall.reportTitle).toBe(`${TEST_PREFIX}-for-notify`);
- expect(mockCall.status).toBe("identified");
- expect(mockCall.message).toBe(
- "We identified the issue and are notifying subscribers.",
+ // Verify dispatcher was called (dispatchers are mocked in preload.ts)
+ expect(subscriptionSpies.dispatchStatusReportUpdate).toHaveBeenCalledTimes(
+ 1,
);
});
test("adds update with notify=false", async () => {
- sendStatusReportUpdateMock.mockClear();
+ subscriptionSpies.dispatchStatusReportUpdate.mockClear();
const res = await connectRequest(
"AddStatusReportUpdate",
@@ -1460,8 +1453,8 @@ describe("StatusReportService.AddStatusReportUpdate", () => {
expect(data).toHaveProperty("statusReport");
expect(data.statusReport.status).toBe("STATUS_REPORT_STATUS_MONITORING");
- // Verify notification was NOT sent
- expect(sendStatusReportUpdateMock).not.toHaveBeenCalled();
+ // Verify dispatcher was NOT called
+ expect(subscriptionSpies.dispatchStatusReportUpdate).not.toHaveBeenCalled();
});
test("updates status report status when adding update", async () => {
diff --git a/apps/server/src/routes/rpc/services/status-report/index.ts b/apps/server/src/routes/rpc/services/status-report/index.ts
index 8d17c5571..bfe379315 100644
--- a/apps/server/src/routes/rpc/services/status-report/index.ts
+++ b/apps/server/src/routes/rpc/services/status-report/index.ts
@@ -1,32 +1,21 @@
import type { ServiceImpl } from "@connectrpc/connect";
-import {
- and,
- db,
- desc,
- eq,
- inArray,
- isNotNull,
- isNull,
- sql,
-} from "@openstatus/db";
+import { and, db, desc, eq, inArray, sql } from "@openstatus/db";
// Type that works with both db instance and transaction
type DB = typeof db;
type Transaction = Parameters<Parameters<DB["transaction"]>[0]>[0];
import {
- page,
pageComponent,
- pageSubscriber,
statusReport,
statusReportUpdate,
statusReportsToPageComponents,
} from "@openstatus/db/src/schema";
import type { Limits } from "@openstatus/db/src/schema/plan/schema";
-import { EmailClient } from "@openstatus/emails";
import type { StatusReportService } from "@openstatus/proto/status_report/v1";
import { StatusReportStatus } from "@openstatus/proto/status_report/v1";
-import { env } from "@/env";
+import { dispatchStatusReportUpdate } from "@openstatus/subscriptions";
+
import { getRpcContext } from "../../interceptors";
import {
dbReportToProto,
@@ -44,89 +33,21 @@ import {
statusReportUpdateFailedError,
} from "./errors";
-const emailClient = new EmailClient({ apiKey: env.RESEND_API_KEY });
-
/**
* Helper to send status report notifications to page subscribers.
+ * Uses the subscription dispatcher for component-aware filtering.
*/
export async function sendStatusReportNotification(params: {
- statusReportId: number;
- pageId: number;
- reportTitle: string;
- status: "investigating" | "identified" | "monitoring" | "resolved";
- message: string;
- date: Date;
+ statusReportUpdateId: number;
limits: Limits;
}) {
- const { statusReportId, pageId, reportTitle, status, message, date, limits } =
- params;
+ const { statusReportUpdateId, limits } = params;
- // Check if workspace has status-subscribers feature enabled
if (!limits["status-subscribers"]) {
return;
}
- // Get page info
- const pageInfo = await db.query.page.findFirst({
- where: eq(page.id, pageId),
- });
-
- if (!pageInfo) {
- return;
- }
-
- // Get verified subscribers who haven't unsubscribed
- const subscribers = await db
- .select()
- .from(pageSubscriber)
- .where(
- and(
- eq(pageSubscriber.pageId, pageId),
- isNotNull(pageSubscriber.acceptedAt),
- isNull(pageSubscriber.unsubscribedAt),
- ),
- )
- .all();
-
- const validSubscribers = subscribers.filter(
- (s): s is typeof s & { token: string } =>
- s.token !== null && s.acceptedAt !== null && s.unsubscribedAt === null,
- );
-
- if (validSubscribers.length === 0) {
- return;
- }
-
- // Get page components for this status report
- const statusReportWithComponents = await db.query.statusReport.findFirst({
- where: eq(statusReport.id, statusReportId),
- with: {
- statusReportsToPageComponents: {
- with: { pageComponent: true },
- },
- },
- });
-
- const pageComponents =
- statusReportWithComponents?.statusReportsToPageComponents.map(
- (i) => i.pageComponent.name,
- ) ?? [];
-
- // Send notification emails
- await emailClient.sendStatusReportUpdate({
- subscribers: validSubscribers.map((subscriber) => ({
- email: subscriber.email,
- token: subscriber.token,
- })),
- pageTitle: pageInfo.title,
- pageSlug: pageInfo.slug,
- customDomain: pageInfo.customDomain,
- reportTitle,
- status,
- message,
- date: date.toISOString(),
- pageComponents,
- });
+ await dispatchStatusReportUpdate(statusReportUpdateId);
}
/**
@@ -273,7 +194,11 @@ export const statusReportServiceImpl: ServiceImpl<typeof StatusReportService> =
const date = parseDate(req.date);
// Create status report, associations, and initial update in a transaction
- const { report: newReport, pageId } = await db.transaction(async (tx) => {
+ const {
+ report: newReport,
+ newUpdate,
+ pageId,
+ } = await db.transaction(async (tx) => {
// Validate page component IDs inside transaction to prevent TOCTOU race condition
const validatedComponents = await validatePageComponentIds(
req.pageComponentIds,
@@ -296,8 +221,9 @@ export const statusReportServiceImpl: ServiceImpl<typeof StatusReportService> =
);
}
- // Use the derived pageId from components (null if no components)
- const pageId = Number(providedPageId);
+ // Use the derived pageId from components, or parse the provided one
+ const pageId =
+ derivedPageId ?? (providedPageId ? Number(providedPageId) : null);
// Create the status report
const report = await tx
@@ -338,18 +264,13 @@ export const statusReportServiceImpl: ServiceImpl<typeof StatusReportService> =
throw statusReportCreateFailedError();
}
- return { report, pageId };
+ return { report, newUpdate, pageId };
});
// Send notifications if requested (outside transaction)
if (req.notify) {
await sendStatusReportNotification({
- statusReportId: newReport.id,
- pageId,
- reportTitle: newReport.title,
- status: protoStatusToDb(req.status),
- message: req.message,
- date,
+ statusReportUpdateId: newUpdate.id,
limits: rpcCtx.workspace.limits,
});
}
@@ -544,7 +465,7 @@ export const statusReportServiceImpl: ServiceImpl<typeof StatusReportService> =
const date = req.date ? parseDate(req.date) : new Date();
// Create update and update status report in a transaction
- const updatedReport = await db.transaction(async (tx) => {
+ const { updatedReport, newUpdate } = await db.transaction(async (tx) => {
// Create the update
const newUpdate = await tx
.insert(statusReportUpdate)
@@ -576,18 +497,13 @@ export const statusReportServiceImpl: ServiceImpl<typeof StatusReportService> =
throw statusReportUpdateFailedError(req.statusReportId);
}
- return updated;
+ return { updatedReport: updated, newUpdate };
});
// Send notifications if requested (outside transaction)
if (req.notify && updatedReport.pageId) {
await sendStatusReportNotification({
- statusReportId: updatedReport.id,
- pageId: updatedReport.pageId,
- reportTitle: updatedReport.title,
- status: protoStatusToDb(req.status),
- message: req.message,
- date,
+ statusReportUpdateId: newUpdate.id,
limits: rpcCtx.workspace.limits,
});
}
diff --git a/apps/server/src/routes/v1/maintenances/post.test.ts b/apps/server/src/routes/v1/maintenances/post.test.ts
index c456cf2d7..8080c1075 100644
--- a/apps/server/src/routes/v1/maintenances/post.test.ts
+++ b/apps/server/src/routes/v1/maintenances/post.test.ts
@@ -1,9 +1,21 @@
-import { expect, test } from "bun:test";
+import { beforeEach, expect, test } from "bun:test";
import { app } from "@/index";
import { db, eq } from "@openstatus/db";
import { maintenance } from "@openstatus/db/src/schema";
import { MaintenanceSchema } from "./schema";
+// biome-ignore lint/suspicious/noExplicitAny: test utility
+const spies = (globalThis as any).__subscriptionSpies as {
+ dispatchMaintenanceUpdate: {
+ mockClear: () => void;
+ mock: { calls: number[][] };
+ };
+};
+
+beforeEach(() => {
+ spies.dispatchMaintenanceUpdate.mockClear();
+});
+
test("create a valid maintenance without monitorIds", async () => {
const from = new Date();
const to = new Date(from.getTime() + 3600000); // 1 hour later
@@ -177,10 +189,7 @@ test("create a maintenance with multiple monitorIds", async () => {
}
});
-test("create a maintenance with multiple monitorIds", async () => {
- const from = new Date();
- const to = new Date(from.getTime() + 3600000); // 1 hour later
-
+test("create a maintenance with invalid dates should return 400", async () => {
const res = await app.request("/v1/maintenance", {
method: "POST",
headers: {
@@ -188,53 +197,55 @@ test("create a maintenance with multiple monitorIds", async () => {
"content-type": "application/json",
},
body: JSON.stringify({
- title: "Multi-Monitor Maintenance",
- message: "Maintenance affecting multiple monitors",
- from: from.toISOString(),
- to: to.toISOString(),
- monitorIds: [1, 2],
+ title: "Invalid Maintenance",
+ message: "Test message",
+ from: "invalid-date",
+ to: "invalid-date",
pageId: 1,
}),
});
- const result = MaintenanceSchema.safeParse(await res.json());
-
- expect(res.status).toBe(200);
- expect(result.success).toBe(true);
- expect(result.data?.monitorIds?.length).toBe(2);
- expect(result.data?.monitorIds).toEqual(expect.arrayContaining([1, 2]));
- // Cleanup: delete the created maintenance
- if (result.success) {
- await db.delete(maintenance).where(eq(maintenance.id, result.data.id));
- }
+ expect(res.status).toBe(400);
});
-test("create a maintenance with invalid dates should return 400", async () => {
+test("no auth key should return 401", async () => {
const res = await app.request("/v1/maintenance", {
method: "POST",
headers: {
- "x-openstatus-key": "1",
"content-type": "application/json",
},
- body: JSON.stringify({
- title: "Invalid Maintenance",
- message: "Test message",
- from: "invalid-date",
- to: "invalid-date",
- pageId: 1,
- }),
});
- expect(res.status).toBe(400);
+ expect(res.status).toBe(401);
});
-test("no auth key should return 401", async () => {
+test("create a maintenance calls dispatchMaintenanceUpdate", async () => {
+ const from = new Date();
+ const to = new Date(from.getTime() + 3600000);
+
const res = await app.request("/v1/maintenance", {
method: "POST",
headers: {
+ "x-openstatus-key": "1",
"content-type": "application/json",
},
+ body: JSON.stringify({
+ title: "Dispatch Test Maintenance",
+ message: "Testing dispatcher integration",
+ from: from.toISOString(),
+ to: to.toISOString(),
+ monitorIds: [1],
+ pageId: 1,
+ }),
});
- expect(res.status).toBe(401);
+ expect(res.status).toBe(200);
+ const result = MaintenanceSchema.safeParse(await res.json());
+ expect(result.success).toBe(true);
+ expect(spies.dispatchMaintenanceUpdate.mock.calls.length).toBe(1);
+ expect(spies.dispatchMaintenanceUpdate.mock.calls[0][0]).toBeNumber();
+
+ if (result.success) {
+ await db.delete(maintenance).where(eq(maintenance.id, result.data.id));
+ }
});
diff --git a/apps/server/src/routes/v1/maintenances/post.ts b/apps/server/src/routes/v1/maintenances/post.ts
index 20053fbec..4abcc5f02 100644
--- a/apps/server/src/routes/v1/maintenances/post.ts
+++ b/apps/server/src/routes/v1/maintenances/post.ts
@@ -1,21 +1,18 @@
-import { env } from "@/env";
import { OpenStatusApiError, openApiErrorResponses } from "@/libs/errors";
import { trackMiddleware } from "@/libs/middlewares";
import { createRoute } from "@hono/zod-openapi";
import { Events } from "@openstatus/analytics";
-import { and, db, eq, inArray, isNotNull, isNull } from "@openstatus/db";
-import { monitor, page, pageSubscriber } from "@openstatus/db/src/schema";
+import { and, db, eq, inArray, isNull } from "@openstatus/db";
+import { monitor, page } from "@openstatus/db/src/schema";
import { maintenance } from "@openstatus/db/src/schema/maintenances";
import {
maintenancesToPageComponents,
pageComponent,
} from "@openstatus/db/src/schema/page_components";
-import { EmailClient } from "@openstatus/emails";
+import { dispatchMaintenanceUpdate } from "@openstatus/subscriptions";
import type { maintenancesApi } from "./index";
import { MaintenanceSchema } from "./schema";
-const emailClient = new EmailClient({ apiKey: env.RESEND_API_KEY });
-
const postRoute = createRoute({
method: "post",
tags: ["maintenance"],
@@ -52,25 +49,6 @@ export function registerPostMaintenance(api: typeof maintenancesApi) {
const { monitorIds, pageId } = input;
- const _monitors = await db
- .select()
- .from(monitor)
- .where(
- and(
- inArray(monitor.id, monitorIds),
- eq(monitor.workspaceId, workspaceId),
- isNull(monitor.deletedAt),
- ),
- )
- .all();
-
- if (_monitors.length !== monitorIds.length) {
- throw new OpenStatusApiError({
- code: "BAD_REQUEST",
- message: `Some of the monitors ${monitorIds.join(", ")} not found`,
- });
- }
-
if (input.from > input.to) {
throw new OpenStatusApiError({
code: "BAD_REQUEST",
@@ -78,20 +56,39 @@ export function registerPostMaintenance(api: typeof maintenancesApi) {
});
}
- const _page = await db
- .select()
- .from(page)
- .where(and(eq(page.id, pageId), eq(page.workspaceId, workspaceId)))
- .get();
+ const _newMaintenance = await db.transaction(async (tx) => {
+ const _monitors = await tx
+ .select()
+ .from(monitor)
+ .where(
+ and(
+ inArray(monitor.id, monitorIds),
+ eq(monitor.workspaceId, workspaceId),
+ isNull(monitor.deletedAt),
+ ),
+ )
+ .all();
- if (!_page) {
- throw new OpenStatusApiError({
- code: "BAD_REQUEST",
- message: `Page ${pageId} not found`,
- });
- }
+ if (_monitors.length !== monitorIds.length) {
+ throw new OpenStatusApiError({
+ code: "BAD_REQUEST",
+ message: `Some of the monitors ${monitorIds.join(", ")} not found`,
+ });
+ }
+
+ const _page = await tx
+ .select()
+ .from(page)
+ .where(and(eq(page.id, pageId), eq(page.workspaceId, workspaceId)))
+ .get();
+
+ if (!_page) {
+ throw new OpenStatusApiError({
+ code: "BAD_REQUEST",
+ message: `Page ${pageId} not found`,
+ });
+ }
- const _newMaintenance = await db.transaction(async (tx) => {
const newMaintenance = await tx
.insert(maintenance)
.values({
@@ -132,67 +129,7 @@ export function registerPostMaintenance(api: typeof maintenancesApi) {
});
if (limits["status-subscribers"] && _newMaintenance.pageId) {
- const subscribers = await db
- .select()
- .from(pageSubscriber)
- .where(
- and(
- eq(pageSubscriber.pageId, _newMaintenance.pageId),
- isNotNull(pageSubscriber.acceptedAt),
- isNull(pageSubscriber.unsubscribedAt),
- ),
- )
- .all();
-
- const _page = await db.query.page.findFirst({
- where: and(
- eq(page.id, _newMaintenance.pageId),
- eq(page.workspaceId, workspaceId),
- ),
- });
-
- const _maintenance = await db.query.maintenance.findFirst({
- where: eq(maintenance.id, _newMaintenance.id),
- with: {
- maintenancesToPageComponents: {
- with: {
- pageComponent: true,
- },
- },
- },
- });
-
- if (!_maintenance) {
- throw new OpenStatusApiError({
- code: "INTERNAL_SERVER_ERROR",
- message: "Maintenance not found",
- });
- }
-
- const validSubscribers = subscribers.filter(
- (s): s is typeof s & { token: string } =>
- s.token !== null &&
- s.acceptedAt !== null &&
- s.unsubscribedAt === null,
- );
- if (_page && validSubscribers.length > 0) {
- await emailClient.sendStatusReportUpdate({
- subscribers: validSubscribers.map((subscriber) => ({
- email: subscriber.email,
- token: subscriber.token,
- })),
- pageTitle: _page.title,
- pageSlug: _page.slug,
- customDomain: _page.customDomain,
- reportTitle: _maintenance.title,
- status: "maintenance",
- message: _maintenance.message,
- date: _maintenance.from.toISOString(),
- pageComponents: _maintenance.maintenancesToPageComponents.map(
- (i) => i.pageComponent.name,
- ),
- });
- }
+ await dispatchMaintenanceUpdate(_newMaintenance.id);
}
const data = MaintenanceSchema.parse({
diff --git a/apps/server/src/routes/v1/statusReportUpdates/post.test.ts b/apps/server/src/routes/v1/statusReportUpdates/post.test.ts
index 233dc48dc..0ab372730 100644
--- a/apps/server/src/routes/v1/statusReportUpdates/post.test.ts
+++ b/apps/server/src/routes/v1/statusReportUpdates/post.test.ts
@@ -1,8 +1,20 @@
-import { expect, test } from "bun:test";
+import { beforeEach, expect, test } from "bun:test";
import { app } from "@/index";
import { StatusReportUpdateSchema } from "./schema";
+// biome-ignore lint/suspicious/noExplicitAny: test utility
+const spies = (globalThis as any).__subscriptionSpies as {
+ dispatchStatusReportUpdate: {
+ mockClear: () => void;
+ mock: { calls: number[][] };
+ };
+};
+
+beforeEach(() => {
+ spies.dispatchStatusReportUpdate.mockClear();
+});
+
test("create a valid status report update", async () => {
const res = await app.request("/v1/status_report_update", {
method: "POST",
@@ -265,3 +277,43 @@ test("create status report update with empty message should return 400", async (
expect(res.status).toBe(400);
});
+
+test("create status report update with non-existent statusReportId should return 404", async () => {
+ const res = await app.request("/v1/status_report_update", {
+ method: "POST",
+ headers: {
+ "x-openstatus-key": "1",
+ "content-type": "application/json",
+ },
+ body: JSON.stringify({
+ status: "investigating",
+ date: new Date().toISOString(),
+ message: "Update for non-existent report",
+ statusReportId: 9999,
+ }),
+ });
+
+ expect(res.status).toBe(404);
+});
+
+test("create a status report update calls dispatchStatusReportUpdate", async () => {
+ const res = await app.request("/v1/status_report_update", {
+ method: "POST",
+ headers: {
+ "x-openstatus-key": "1",
+ "content-type": "application/json",
+ },
+ body: JSON.stringify({
+ status: "investigating",
+ date: new Date().toISOString(),
+ message: "Testing dispatcher integration",
+ statusReportId: 1,
+ }),
+ });
+
+ expect(res.status).toBe(200);
+ const result = StatusReportUpdateSchema.safeParse(await res.json());
+ expect(result.success).toBe(true);
+ expect(spies.dispatchStatusReportUpdate.mock.calls.length).toBe(1);
+ expect(spies.dispatchStatusReportUpdate.mock.calls[0][0]).toBeNumber();
+});
diff --git a/apps/server/src/routes/v1/statusReportUpdates/post.ts b/apps/server/src/routes/v1/statusReportUpdates/post.ts
index b55bd6087..a452c1725 100644
--- a/apps/server/src/routes/v1/statusReportUpdates/post.ts
+++ b/apps/server/src/routes/v1/statusReportUpdates/post.ts
@@ -1,21 +1,13 @@
import { createRoute } from "@hono/zod-openapi";
-import { and, db, eq, isNotNull, isNull } from "@openstatus/db";
-import {
- page,
- pageSubscriber,
- statusReport,
- statusReportUpdate,
-} from "@openstatus/db/src/schema";
+import { and, db, eq } from "@openstatus/db";
+import { statusReport, statusReportUpdate } from "@openstatus/db/src/schema";
-import { env } from "@/env";
import { OpenStatusApiError, openApiErrorResponses } from "@/libs/errors";
-import { EmailClient } from "@openstatus/emails";
+import { dispatchStatusReportUpdate } from "@openstatus/subscriptions";
import type { statusReportUpdatesApi } from "./index";
import { StatusReportUpdateSchema } from "./schema";
-const emailClient = new EmailClient({ apiKey: env.RESEND_API_KEY });
-
const createStatusUpdate = createRoute({
method: "post",
tags: ["status_report_update"],
@@ -73,65 +65,30 @@ export function registerPostStatusReportUpdate(
});
}
- const _statusReportUpdate = await db
- .insert(statusReportUpdate)
- .values({
- ...input,
- date: new Date(input.date),
- statusReportId: _statusReport.id,
- })
- .returning()
- .get();
-
- await db
- .update(statusReport)
- .set({
- status: input.status,
- updatedAt: new Date(),
- })
- .where(eq(statusReport.id, _statusReport.id));
+ const _statusReportUpdate = await db.transaction(async (tx) => {
+ const update = await tx
+ .insert(statusReportUpdate)
+ .values({
+ ...input,
+ date: new Date(input.date),
+ statusReportId: _statusReport.id,
+ })
+ .returning()
+ .get();
- if (limits["status-subscribers"] && _statusReport.pageId) {
- const subscribers = await db
- .select()
- .from(pageSubscriber)
- .where(
- and(
- eq(pageSubscriber.pageId, _statusReport.pageId),
- isNotNull(pageSubscriber.acceptedAt),
- isNull(pageSubscriber.unsubscribedAt),
- ),
- )
- .all();
+ await tx
+ .update(statusReport)
+ .set({
+ status: input.status,
+ updatedAt: new Date(),
+ })
+ .where(eq(statusReport.id, _statusReport.id));
- const _page = await db.query.page.findFirst({
- where: eq(page.id, _statusReport.pageId),
- });
+ return update;
+ });
- const validSubscribers = subscribers.filter(
- (s): s is typeof s & { token: string } =>
- s.token !== null &&
- s.acceptedAt !== null &&
- s.unsubscribedAt === null,
- );
- if (_page && validSubscribers.length > 0) {
- await emailClient.sendStatusReportUpdate({
- subscribers: validSubscribers.map((subscriber) => ({
- email: subscriber.email,
- token: subscriber.token,
- })),
- pageTitle: _page.title,
- pageSlug: _page.slug,
- customDomain: _page.customDomain,
- reportTitle: _statusReport.title,
- status: _statusReportUpdate.status,
- message: _statusReportUpdate.message,
- date: _statusReportUpdate.date.toISOString(),
- pageComponents: _statusReport.statusReportsToPageComponents.map(
- (i) => i.pageComponent.name,
- ),
- });
- }
+ if (limits["status-subscribers"] && _statusReport.pageId) {
+ await dispatchStatusReportUpdate(_statusReportUpdate.id);
}
const data = StatusReportUpdateSchema.parse(_statusReportUpdate);
diff --git a/apps/server/src/routes/v1/statusReports/post.test.ts b/apps/server/src/routes/v1/statusReports/post.test.ts
index 02a3c3c09..ad66cb01f 100644
--- a/apps/server/src/routes/v1/statusReports/post.test.ts
+++ b/apps/server/src/routes/v1/statusReports/post.test.ts
@@ -1,4 +1,4 @@
-import { expect, test } from "bun:test";
+import { beforeEach, expect, test } from "bun:test";
import { app } from "@/index";
import { db, eq } from "@openstatus/db";
@@ -9,6 +9,18 @@ import {
} from "@openstatus/db/src/schema";
import { StatusReportSchema } from "./schema";
+// biome-ignore lint/suspicious/noExplicitAny: test utility
+const spies = (globalThis as any).__subscriptionSpies as {
+ dispatchStatusReportUpdate: {
+ mockClear: () => void;
+ mock: { calls: number[][] };
+ };
+};
+
+beforeEach(() => {
+ spies.dispatchStatusReportUpdate.mockClear();
+});
+
test("create a valid status report", async () => {
const date = new Date();
date.setMilliseconds(0);
@@ -165,6 +177,40 @@ test("no auth key should return 401", async () => {
expect(res.status).toBe(401);
});
+test("create a status report calls dispatchStatusReportUpdate", async () => {
+ const date = new Date();
+ date.setMilliseconds(0);
+
+ const res = await app.request("/v1/status_report", {
+ method: "POST",
+ headers: {
+ "x-openstatus-key": "1",
+ "content-type": "application/json",
+ },
+ body: JSON.stringify({
+ status: "investigating",
+ title: "Dispatch Test Report",
+ message: "Testing dispatcher integration",
+ monitorIds: [1],
+ date: date.toISOString(),
+ pageId: 1,
+ }),
+ });
+
+ expect(res.status).toBe(200);
+ const result = StatusReportSchema.safeParse(await res.json());
+ expect(result.success).toBe(true);
+ expect(spies.dispatchStatusReportUpdate.mock.calls.length).toBe(1);
+ expect(spies.dispatchStatusReportUpdate.mock.calls[0][0]).toBeNumber();
+
+ if (result.success) {
+ await db
+ .delete(statusReport)
+ .where(eq(statusReport.id, result.data.id))
+ .run();
+ }
+});
+
test("create a status report links correctly to statusReportsToPageComponents", async () => {
const date = new Date();
date.setMilliseconds(0);
diff --git a/apps/server/src/routes/v1/statusReports/post.ts b/apps/server/src/routes/v1/statusReports/post.ts
index e2050dab3..cc940c68d 100644
--- a/apps/server/src/routes/v1/statusReports/post.ts
+++ b/apps/server/src/routes/v1/statusReports/post.ts
@@ -1,24 +1,20 @@
import { createRoute, z } from "@hono/zod-openapi";
-import { and, db, eq, inArray, isNotNull, isNull } from "@openstatus/db";
+import { and, db, eq, inArray, isNull } from "@openstatus/db";
import {
monitor,
page,
pageComponent,
- pageSubscriber,
statusReport,
statusReportUpdate,
statusReportsToPageComponents,
} from "@openstatus/db/src/schema";
-import { env } from "@/env";
import { OpenStatusApiError, openApiErrorResponses } from "@/libs/errors";
-import { EmailClient } from "@openstatus/emails";
+import { dispatchStatusReportUpdate } from "@openstatus/subscriptions";
import type { statusReportsApi } from "./index";
import { StatusReportSchema } from "./schema";
-const emailClient = new EmailClient({ apiKey: env.RESEND_API_KEY });
-
const postRoute = createRoute({
method: "post",
tags: ["status_report"],
@@ -100,120 +96,71 @@ export function registerPostStatusReport(api: typeof statusReportsApi) {
});
}
- const _newStatusReport = await db
- .insert(statusReport)
- .values({
- status: input.status,
- title: input.title,
- pageId: input.pageId,
- workspaceId: workspaceId,
- })
- .returning()
- .get();
-
- const _newStatusReportUpdate = await db
- .insert(statusReportUpdate)
- .values({
- status: input.status,
- message: input.message,
- date: input.date,
- statusReportId: _newStatusReport.id,
- })
- .returning()
- .get();
-
- if (!_newStatusReport.pageId) {
- throw new OpenStatusApiError({
- code: "BAD_REQUEST",
- message: "Page ID is required",
- });
- }
-
- if (input.monitorIds?.length) {
- // Find matching page_components for the monitors on this page
- const components = await db
- .select({ id: pageComponent.id })
- .from(pageComponent)
- .where(
- and(
- inArray(pageComponent.monitorId, input.monitorIds),
- eq(pageComponent.pageId, _newStatusReport.pageId),
- eq(pageComponent.type, "monitor"),
- ),
- )
- .all();
-
- // Insert to statusReportsToPageComponents
- if (components.length > 0) {
- await db
- .insert(statusReportsToPageComponents)
- .values(
- components.map((c) => ({
- statusReportId: _newStatusReport.id,
- pageComponentId: c.id,
- })),
- )
- .run();
- }
- }
+ const { _newStatusReport, _newStatusReportUpdate } = await db.transaction(
+ async (tx) => {
+ const _newStatusReport = await tx
+ .insert(statusReport)
+ .values({
+ status: input.status,
+ title: input.title,
+ pageId: input.pageId,
+ workspaceId: workspaceId,
+ })
+ .returning()
+ .get();
+
+ const _newStatusReportUpdate = await tx
+ .insert(statusReportUpdate)
+ .values({
+ status: input.status,
+ message: input.message,
+ date: input.date,
+ statusReportId: _newStatusReport.id,
+ })
+ .returning()
+ .get();
+
+ if (!_newStatusReport.pageId) {
+ throw new OpenStatusApiError({
+ code: "BAD_REQUEST",
+ message: "Page ID is required",
+ });
+ }
+
+ if (input.monitorIds?.length) {
+ // Find matching page_components for the monitors on this page
+ const components = await tx
+ .select({ id: pageComponent.id })
+ .from(pageComponent)
+ .where(
+ and(
+ inArray(pageComponent.monitorId, input.monitorIds),
+ eq(pageComponent.pageId, _newStatusReport.pageId),
+ eq(pageComponent.type, "monitor"),
+ ),
+ )
+ .all();
+
+ // Insert to statusReportsToPageComponents
+ if (components.length > 0) {
+ await tx
+ .insert(statusReportsToPageComponents)
+ .values(
+ components.map((c) => ({
+ statusReportId: _newStatusReport.id,
+ pageComponentId: c.id,
+ })),
+ )
+ .run();
+ }
+ }
+
+ return { _newStatusReport, _newStatusReportUpdate };
+ },
+ );
if (limits["status-subscribers"] && _newStatusReport.pageId) {
- const subscribers = await db
- .select()
- .from(pageSubscriber)
- .where(
- and(
- eq(pageSubscriber.pageId, _newStatusReport.pageId),
- isNotNull(pageSubscriber.acceptedAt),
- isNull(pageSubscriber.unsubscribedAt),
- ),
- )
- .all();
-
- const pageInfo = await db.query.page.findFirst({
- where: eq(page.id, _newStatusReport.pageId),
- });
-
- const _statusReport = await db.query.statusReport.findFirst({
- where: eq(statusReport.id, _newStatusReport.id),
- with: {
- statusReportsToPageComponents: {
- with: { pageComponent: true },
- },
- },
- });
-
- if (!_statusReport) {
- throw new OpenStatusApiError({
- code: "INTERNAL_SERVER_ERROR",
- message: "Status report not found",
- });
- }
-
- const validSubscribers = subscribers.filter(
- (s): s is typeof s & { token: string } =>
- s.token !== null &&
- s.acceptedAt !== null &&
- s.unsubscribedAt === null,
- );
- if (pageInfo && validSubscribers.length > 0) {
- await emailClient.sendStatusReportUpdate({
- subscribers: validSubscribers.map((subscriber) => ({
- email: subscriber.email,
- token: subscriber.token,
- })),
- pageTitle: pageInfo.title,
- pageSlug: pageInfo.slug,
- customDomain: pageInfo.customDomain,
- reportTitle: _newStatusReport.title,
- status: _newStatusReportUpdate.status,
- message: _newStatusReportUpdate.message,
- date: _newStatusReportUpdate.date.toISOString(),
- pageComponents: _statusReport.statusReportsToPageComponents.map(
- (i) => i.pageComponent.name,
- ),
- });
- }
+ await dispatchStatusReportUpdate(_newStatusReportUpdate.id);
}
const data = StatusReportSchema.parse({
diff --git a/apps/status-page/next-env.d.ts b/apps/status-page/next-env.d.ts
index 9edff1c7c..c4b7818fb 100644
--- a/apps/status-page/next-env.d.ts
+++ b/apps/status-page/next-env.d.ts
@@ -1,6 +1,6 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
-import "./.next/types/routes.d.ts";
+import "./.next/dev/types/routes.d.ts";
// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
diff --git a/apps/status-page/src/app/(status-page)/[domain]/(public)/manage/[token]/layout.tsx b/apps/status-page/src/app/(status-page)/[domain]/(public)/manage/[token]/layout.tsx
new file mode 100644
index 000000000..f90f987a7
--- /dev/null
+++ b/apps/status-page/src/app/(status-page)/[domain]/(public)/manage/[token]/layout.tsx
@@ -0,0 +1,19 @@
+import { HydrateClient, getQueryClient, trpc } from "@/lib/trpc/server";
+
+export default async function Layout({
+ children,
+ params,
+}: {
+ children: React.ReactNode;
+ params: Promise<{ token: string; domain: string }>;
+}) {
+ const { token, domain } = await params;
+ const queryClient = getQueryClient();
+ await queryClient.prefetchQuery(
+ trpc.statusPage.getSubscriptionByToken.queryOptions({
+ token,
+ slug: domain,
+ }),
+ );
+ return <HydrateClient>{children}</HydrateClient>;
+}
diff --git a/apps/status-page/src/app/(status-page)/[domain]/(public)/manage/[token]/page.tsx b/apps/status-page/src/app/(status-page)/[domain]/(public)/manage/[token]/page.tsx
new file mode 100644
index 000000000..f9a3655fd
--- /dev/null
+++ b/apps/status-page/src/app/(status-page)/[domain]/(public)/manage/[token]/page.tsx
@@ -0,0 +1,183 @@
+"use client";
+
+import { ButtonBack } from "@/components/button/button-back";
+import {
+ FormCard,
+ FormCardContent,
+ FormCardDescription,
+ FormCardFooter,
+ FormCardFooterInfo,
+ FormCardHeader,
+ FormCardTitle,
+} from "@/components/forms/form-card";
+import { FormManageSubscription } from "@/components/forms/form-manage-subscription";
+import {
+ StatusBlankContainer,
+ StatusBlankContent,
+ StatusBlankDescription,
+ StatusBlankLink,
+ StatusBlankTitle,
+} from "@/components/status-page/status-blank";
+import { useTRPC } from "@/lib/trpc/client";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+ AlertDialogTrigger,
+} from "@openstatus/ui/components/ui/alert-dialog";
+import { Button } from "@openstatus/ui/components/ui/button";
+import { useMutation, useQuery } from "@tanstack/react-query";
+import { isTRPCClientError } from "@trpc/client";
+import { useParams } from "next/navigation";
+import { toast } from "sonner";
+
+export default function VerifyPage() {
+ const trpc = useTRPC();
+ const { token, domain } = useParams<{ token: string; domain: string }>();
+ const { data: page } = useQuery(
+ trpc.statusPage.get.queryOptions({ slug: domain }),
+ );
+ const { data: subscription, refetch } = useQuery(
+ trpc.statusPage.getSubscriptionByToken.queryOptions({
+ slug: domain,
+ token,
+ }),
+ );
+ const manageSubscriptionMutation = useMutation(
+ trpc.statusPage.updateSubscription.mutationOptions({}),
+ );
+ const unsubscribeMutation = useMutation(
+ trpc.statusPage.unsubscribe.mutationOptions({
+ onSuccess: () => {
+ refetch();
+ toast.success("Unsubscribed successfully");
+ },
+ onError: (error) => {
+ if (isTRPCClientError(error)) {
+ toast.error(error.message);
+ } else {
+ toast.error("Failed to unsubscribe");
+ }
+ },
+ }),
+ );
+
+ if (!subscription)
+ return (
+ <StatusBlankContainer>
+ <StatusBlankContent>
+ <StatusBlankTitle>Invalid subscription token</StatusBlankTitle>
+ <StatusBlankDescription>
+ This subscription token is no longer valid. You may have already
+ unsubscribed or the link has expired.
+ </StatusBlankDescription>
+ <StatusBlankLink href="../">Go back</StatusBlankLink>
+ </StatusBlankContent>
+ </StatusBlankContainer>
+ );
+
+ return (
+ <div className="flex flex-col gap-4">
+ <div className="flex w-full flex-row items-center justify-between gap-2 py-0.5">
+ <ButtonBack href="../" />
+ </div>
+ <FormCard>
+ <FormCardHeader>
+ <FormCardTitle>{subscription.email}</FormCardTitle>
+ <FormCardDescription>
+ Manage your subscription to receive updates on the status page.
+ </FormCardDescription>
+ </FormCardHeader>
+ <FormCardContent>
+ <FormManageSubscription
+ id="manage-subscription-form"
+ defaultValues={{
+ pageComponents: subscription?.componentIds ?? [],
+ subscribeComponents:
+ (subscription?.componentIds?.length ?? 0) > 0,
+ }}
+ page={page}
+ onSubmit={async (values) => {
+ await manageSubscriptionMutation.mutateAsync({
+ slug: domain,
+ token,
+ ...values,
+ });
+ }}
+ />
+ </FormCardContent>
+ <FormCardFooter>
+ <FormCardFooterInfo>
+ {subscription.unsubscribedAt ? (
+ <span className="text-destructive">
+ Unsubscribed on{" "}
+ {Intl.DateTimeFormat("en-US", {
+ year: "numeric",
+ month: "long",
+ day: "numeric",
+ }).format(subscription.unsubscribedAt)}
+ </span>
+ ) : null}
+ </FormCardFooterInfo>
+ <div className="flex flex-row gap-2">
+ <AlertDialog>
+ <AlertDialogTrigger asChild>
+ <Button
+ size="sm"
+ variant="ghost"
+ className="text-destructive hover:bg-destructive/10 hover:text-destructive focus-visible:ring-destructive/20 dark:hover:bg-destructive/10"
+ disabled={
+ unsubscribeMutation.isPending ||
+ !!subscription.unsubscribedAt
+ }
+ >
+ {unsubscribeMutation.isPending
+ ? "Unsubscribing..."
+ : "Unsubscribe"}
+ </Button>
+ </AlertDialogTrigger>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Unsubscribe</AlertDialogTitle>
+ <AlertDialogDescription>
+ Are you sure you want to unsubscribe from this status page?
+ You will no longer receive updates.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ onClick={() =>
+ unsubscribeMutation.mutate({ token, domain })
+ }
+ >
+ Unsubscribe
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ <Button
+ size="sm"
+ variant="outline"
+ type="submit"
+ form="manage-subscription-form"
+ disabled={
+ manageSubscriptionMutation.isPending ||
+ !!subscription.unsubscribedAt
+ }
+ >
+ {manageSubscriptionMutation.isPending
+ ? "Submitting..."
+ : "Submit"}
+ </Button>
+ </div>
+ </FormCardFooter>
+ </FormCard>
+ </div>
+ );
+}
diff --git a/apps/status-page/src/app/(status-page)/[domain]/(public)/manage/layout.tsx b/apps/status-page/src/app/(status-page)/[domain]/(public)/manage/layout.tsx
new file mode 100644
index 000000000..0c5c7f7f5
--- /dev/null
+++ b/apps/status-page/src/app/(status-page)/[domain]/(public)/manage/layout.tsx
@@ -0,0 +1,36 @@
+"use client";
+
+import {
+ Status,
+ StatusContent,
+ StatusDescription,
+ StatusHeader,
+ StatusTitle,
+} from "@/components/status-page/status";
+import { useTRPC } from "@/lib/trpc/client";
+import { useQuery } from "@tanstack/react-query";
+import { useParams } from "next/navigation";
+
+export default function EventLayout({
+ children,
+}: {
+ children: React.ReactNode;
+}) {
+ const { domain } = useParams<{ domain: string }>();
+ const trpc = useTRPC();
+ const { data: page } = useQuery(
+ trpc.statusPage.get.queryOptions({ slug: domain }),
+ );
+
+ if (!page) return null;
+
+ return (
+ <Status>
+ <StatusHeader>
+ <StatusTitle>{page.title}</StatusTitle>
+ <StatusDescription>{page.description}</StatusDescription>
+ </StatusHeader>
+ <StatusContent>{children}</StatusContent>
+ </Status>
+ );
+}
diff --git a/apps/status-page/src/components/forms/form-card.tsx b/apps/status-page/src/components/forms/form-card.tsx
new file mode 100644
index 000000000..05f0508bb
--- /dev/null
+++ b/apps/status-page/src/components/forms/form-card.tsx
@@ -0,0 +1,216 @@
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardFooter,
+ CardHeader,
+ CardTitle,
+} from "@openstatus/ui/components/ui/card";
+import { Separator } from "@openstatus/ui/components/ui/separator";
+import { cn } from "@openstatus/ui/lib/utils";
+
+import { type VariantProps, cva } from "class-variance-authority";
+
+// py-0
+const formCardVariants = cva(
+ "group relative w-full overflow-hidden py-0 shadow-none gap-4",
+ {
+ variants: {
+ variant: {
+ default: "",
+ destructive: "border-destructive",
+ info: "border-info",
+ },
+ defaultVariants: {
+ variant: "default",
+ },
+ },
+ },
+);
+
+// NOTE: Add a formcardprovider to share the variant prop
+
+export function FormCard({
+ children,
+ className,
+ variant,
+ ...props
+}: React.ComponentProps<"div"> & VariantProps<typeof formCardVariants>) {
+ return (
+ <Card className={cn(formCardVariants({ variant }), className)} {...props}>
+ {children}
+ </Card>
+ );
+}
+
+export function FormCardHeader({
+ children,
+ className,
+ ...props
+}: React.ComponentProps<"div">) {
+ return (
+ <CardHeader
+ className={cn(
+ "px-4 pt-4 group-has-data-[slot=card-upgrade]:pointer-events-none group-has-data-[slot=card-upgrade]:opacity-50 [.border-b]:pb-4",
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ </CardHeader>
+ );
+}
+
+export function FormCardTitle({ children }: { children: React.ReactNode }) {
+ return <CardTitle>{children}</CardTitle>;
+}
+
+export function FormCardDescription({
+ children,
+}: {
+ children: React.ReactNode;
+}) {
+ return <CardDescription>{children}</CardDescription>;
+}
+
+export function FormCardContent({
+ children,
+ className,
+ ...props
+}: React.ComponentProps<"div">) {
+ return (
+ <CardContent
+ className={cn(
+ "px-4 group-has-data-[slot=card-upgrade]:pointer-events-none group-has-data-[slot=card-upgrade]:opacity-50",
+ "has-data-[slot=card-content-upgrade]:pointer-events-none has-data-[slot=card-content-upgrade]:opacity-50",
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ </CardContent>
+ );
+}
+
+export function FormCardSeparator({
+ ...props
+}: React.ComponentProps<typeof Separator>) {
+ return <Separator {...props} />;
+}
+
+const formCardFooterVariants = cva(
+ "border-t flex items-center gap-2 pb-4 px-4 [&>:last-child]:ml-auto [.border-t]:pt-4",
+ {
+ variants: {
+ variant: {
+ default: "",
+ destructive: "border-destructive bg-destructive/5",
+ info: "border-info bg-info/5",
+ },
+ defaultVariants: {
+ variant: "default",
+ },
+ },
+ },
+);
+
+export function FormCardFooter({
+ children,
+ className,
+ variant,
+ ...props
+}: React.ComponentProps<"div"> & VariantProps<typeof formCardFooterVariants>) {
+ return (
+ <CardFooter
+ className={cn(formCardFooterVariants({ variant }), className)}
+ {...props}
+ >
+ {children}
+ </CardFooter>
+ );
+}
+
+export function FormCardFooterInfo({
+ children,
+ className,
+ ...props
+}: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="card-footer-info"
+ className={cn("text-muted-foreground text-sm", className)}
+ {...props}
+ >
+ {children}
+ </div>
+ );
+}
+
+export function FormCardGroup({
+ children,
+ className,
+ ...props
+}: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="card-group"
+ className={cn("flex flex-col gap-4", className)}
+ {...props}
+ >
+ {children}
+ </div>
+ );
+}
+
+export function FormCardUpgrade({
+ children,
+ className,
+ ...props
+}: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="card-upgrade"
+ className={cn("hidden", className)}
+ {...props}
+ >
+ {children}
+ </div>
+ );
+}
+
+// NOTE; this is for a very specific case where we don't want to disable the whole content
+// and instead disable specpfic card content (e.g. for add-ons)
+export function FormCardContentUpgrade({
+ children,
+ className,
+ ...props
+}: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="card-content-upgrade"
+ className={cn("hidden", className)}
+ {...props}
+ >
+ {children}
+ </div>
+ );
+}
+
+export function FormCardEmpty({
+ children,
+ className,
+ ...props
+}: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="card-empty"
+ className={cn(
+ "pointer-events-none absolute inset-0 z-10 bg-background opacity-70 blur",
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ </div>
+ );
+}
diff --git a/apps/status-page/src/components/forms/form-manage-subscription.tsx b/apps/status-page/src/components/forms/form-manage-subscription.tsx
new file mode 100644
index 000000000..396889326
--- /dev/null
+++ b/apps/status-page/src/components/forms/form-manage-subscription.tsx
@@ -0,0 +1,236 @@
+"use client";
+
+import {
+ StatusBlankContainer,
+ StatusBlankDescription,
+ StatusBlankTitle,
+} from "@/components/status-page/status-blank";
+import { zodResolver } from "@hookform/resolvers/zod";
+import type { RouterOutputs } from "@openstatus/api";
+import { Checkbox } from "@openstatus/ui/components/ui/checkbox";
+import { Form } from "@openstatus/ui/components/ui/form";
+import {
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+} from "@openstatus/ui/components/ui/form";
+import { Separator } from "@openstatus/ui/components/ui/separator";
+import { cn } from "@openstatus/ui/lib/utils";
+import { isTRPCClientError } from "@trpc/client";
+import { useTransition } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+type Page = NonNullable<RouterOutputs["statusPage"]["get"]>;
+
+const schema = z.object({
+ pageComponents: z.array(z.number().int().positive()),
+ subscribeComponents: z.boolean(),
+});
+
+export type FormValues = z.infer<typeof schema>;
+
+export function FormManageSubscription({
+ page,
+ defaultValues,
+ onSubmit,
+ className,
+ ...props
+}: Omit<React.ComponentProps<"form">, "onSubmit"> & {
+ onSubmit: (values: FormValues) => Promise<void>;
+ onSubmitCallback?: () => void;
+ page?: Page | null;
+ defaultValues?: FormValues;
+}) {
+ const form = useForm<FormValues>({
+ resolver: zodResolver(schema),
+ defaultValues: {
+ pageComponents: defaultValues?.pageComponents ?? [],
+ subscribeComponents: defaultValues?.subscribeComponents ?? true,
+ },
+ });
+ const [isPending, startTransition] = useTransition();
+
+ function submitAction(values: FormValues) {
+ if (isPending) return;
+
+ startTransition(async () => {
+ try {
+ const promise = onSubmit(values);
+ toast.promise(promise, {
+ loading: "Updating subscription...",
+ success: "Subscription updated",
+ error: (error) => {
+ if (isTRPCClientError(error)) {
+ return error.message;
+ }
+ return "Failed to update subscription";
+ },
+ });
+ await promise;
+ } catch (error) {
+ console.error(error);
+ }
+ });
+ }
+
+ return (
+ <Form {...form}>
+ <form
+ onSubmit={form.handleSubmit(submitAction)}
+ className={cn("flex flex-col gap-2", className)}
+ {...props}
+ >
+ <FormField
+ control={form.control}
+ name="subscribeComponents"
+ render={({ field }) => (
+ <FormItem className="flex items-center gap-2">
+ <FormControl>
+ <Checkbox
+ checked={field.value}
+ onCheckedChange={(checked) => {
+ field.onChange(checked);
+ }}
+ />
+ </FormControl>
+ <FormLabel>Subscribe to specific components</FormLabel>
+ </FormItem>
+ )}
+ />
+ {form.watch("subscribeComponents") ? (
+ <>
+ <Separator className="my-2" />
+ {page?.trackers && page.trackers.length > 0 ? (
+ page.trackers.map((tracker) => {
+ if (tracker.type === "group") {
+ const groupIds = tracker.components.map((c) => c.id);
+ return (
+ <div key={tracker.groupId} className="flex flex-col gap-2">
+ <FormField
+ control={form.control}
+ name="pageComponents"
+ render={({ field }) => {
+ const allChecked = groupIds.every((id) =>
+ field.value?.includes(id),
+ );
+ const someChecked = groupIds.some((id) =>
+ field.value?.includes(id),
+ );
+ return (
+ <FormItem className="flex items-center gap-2">
+ <FormControl>
+ <Checkbox
+ checked={
+ allChecked
+ ? true
+ : someChecked
+ ? "indeterminate"
+ : false
+ }
+ onCheckedChange={(checked) => {
+ const value = field.value ?? [];
+ if (checked) {
+ field.onChange([
+ ...new Set([...value, ...groupIds]),
+ ]);
+ } else {
+ field.onChange(
+ value.filter(
+ (id) => !groupIds.includes(id),
+ ),
+ );
+ }
+ }}
+ />
+ </FormControl>
+ <FormLabel>{tracker.groupName}</FormLabel>
+ </FormItem>
+ );
+ }}
+ />
+ {tracker.components.map((component) => (
+ <FormField
+ key={component.id}
+ control={form.control}
+ name="pageComponents"
+ render={({ field }) => (
+ <FormItem className="flex items-center gap-2 pl-6">
+ <FormControl>
+ <Checkbox
+ checked={field.value?.includes(component.id)}
+ onCheckedChange={(checked) => {
+ const value = field.value ?? [];
+ if (checked) {
+ field.onChange([...value, component.id]);
+ } else {
+ field.onChange(
+ value.filter(
+ (id) => id !== component.id,
+ ),
+ );
+ }
+ }}
+ />
+ </FormControl>
+ <FormLabel>{component.name}</FormLabel>
+ </FormItem>
+ )}
+ />
+ ))}
+ </div>
+ );
+ }
+ return (
+ <FormField
+ key={tracker.component.id}
+ control={form.control}
+ name="pageComponents"
+ render={({ field }) => (
+ <FormItem className="flex items-center gap-2">
+ <FormControl>
+ <Checkbox
+ checked={field.value?.includes(
+ tracker.component.id,
+ )}
+ onCheckedChange={(checked) => {
+ const value = field.value ?? [];
+ if (checked) {
+ field.onChange([
+ ...value,
+ tracker.component.id,
+ ]);
+ } else {
+ field.onChange(
+ value.filter(
+ (id) => id !== tracker.component.id,
+ ),
+ );
+ }
+ }}
+ />
+ </FormControl>
+ <FormLabel>{tracker.component.name}</FormLabel>
+ </FormItem>
+ )}
+ />
+ );
+ })
+ ) : (
+ <StatusBlankContainer>
+ <StatusBlankTitle>
+ No components to subscribe to
+ </StatusBlankTitle>
+ <StatusBlankDescription>
+ This status page has no components to subscribe to.
+ </StatusBlankDescription>
+ </StatusBlankContainer>
+ )}
+ </>
+ ) : null}
+ </form>
+ </Form>
+ );
+}
diff --git a/apps/status-page/src/components/forms/form-subscribe-email.tsx b/apps/status-page/src/components/forms/form-subscribe-email.tsx
index b17a905e1..4cadc6994 100644
--- a/apps/status-page/src/components/forms/form-subscribe-email.tsx
+++ b/apps/status-page/src/components/forms/form-subscribe-email.tsx
@@ -1,6 +1,13 @@
"use client";
+import {
+ StatusBlankContainer,
+ StatusBlankDescription,
+ StatusBlankTitle,
+} from "@/components/status-page/status-blank";
import { zodResolver } from "@hookform/resolvers/zod";
+import type { RouterOutputs } from "@openstatus/api";
+import { Checkbox } from "@openstatus/ui/components/ui/checkbox";
import { Form } from "@openstatus/ui/components/ui/form";
import {
FormControl,
@@ -9,29 +16,43 @@ import {
FormLabel,
} from "@openstatus/ui/components/ui/form";
import { Input } from "@openstatus/ui/components/ui/input";
+import { Separator } from "@openstatus/ui/components/ui/separator";
+import { cn } from "@openstatus/ui/lib/utils";
import { isTRPCClientError } from "@trpc/client";
import { useTransition } from "react";
import { useForm } from "react-hook-form";
import { toast } from "sonner";
import { z } from "zod";
+// TODO: remove after implementing the feature
+const HIDE_SUBSCRIBE_COMPONENTS = true;
+
+type Page = NonNullable<RouterOutputs["statusPage"]["get"]>;
+
const schema = z.object({
email: z.email(),
+ subscribeComponents: z.boolean(),
+ pageComponents: z.array(z.number().int().positive()),
});
-type FormValues = z.infer<typeof schema>;
+export type FormValues = z.infer<typeof schema>;
export function FormSubscribeEmail({
+ page,
onSubmit,
+ className,
...props
}: Omit<React.ComponentProps<"form">, "onSubmit"> & {
onSubmit: (values: FormValues) => Promise<void>;
onSubmitCallback?: () => void;
+ page?: Page | null;
}) {
const form = useForm<FormValues>({
resolver: zodResolver(schema),
defaultValues: {
email: "",
+ subscribeComponents: false,
+ pageComponents: [],
},
});
const [isPending, startTransition] = useTransition();
@@ -61,12 +82,16 @@ export function FormSubscribeEmail({
return (
<Form {...form}>
- <form onSubmit={form.handleSubmit(submitAction)} {...props}>
+ <form
+ onSubmit={form.handleSubmit(submitAction)}
+ className={cn("flex flex-col gap-2", className)}
+ {...props}
+ >
<FormField
control={form.control}
name="email"
render={({ field }) => (
- <FormItem>
+ <FormItem className="px-2">
<FormLabel className="sr-only">Email</FormLabel>
<FormControl>
<Input placeholder="[email protected]" {...field} />
@@ -74,6 +99,168 @@ export function FormSubscribeEmail({
</FormItem>
)}
/>
+ {HIDE_SUBSCRIBE_COMPONENTS ? null : (
+ <>
+ <FormField
+ control={form.control}
+ name="subscribeComponents"
+ render={({ field }) => (
+ <FormItem className="flex items-center gap-2 px-2">
+ <FormControl>
+ <Checkbox
+ checked={field.value}
+ onCheckedChange={field.onChange}
+ />
+ </FormControl>
+ <FormLabel>Subscribe to specific components</FormLabel>
+ </FormItem>
+ )}
+ />
+ {form.watch("subscribeComponents") && (
+ <>
+ <Separator />
+ <div className="-my-2 flex max-h-56 flex-col gap-2 overflow-y-auto bg-muted p-2 px-2">
+ {page?.trackers && page.trackers.length > 0 ? (
+ page.trackers.map((tracker) => {
+ if (tracker.type === "group") {
+ const groupIds = tracker.components.map((c) => c.id);
+ return (
+ <div
+ key={tracker.groupId}
+ className="flex flex-col gap-2"
+ >
+ <FormField
+ control={form.control}
+ name="pageComponents"
+ render={({ field }) => {
+ const allChecked = groupIds.every((id) =>
+ field.value?.includes(id),
+ );
+ const someChecked = groupIds.some((id) =>
+ field.value?.includes(id),
+ );
+ return (
+ <FormItem className="flex items-center gap-2">
+ <FormControl>
+ <Checkbox
+ checked={
+ allChecked
+ ? true
+ : someChecked
+ ? "indeterminate"
+ : false
+ }
+ onCheckedChange={(checked) => {
+ const value = field.value ?? [];
+ if (checked) {
+ field.onChange([
+ ...new Set([
+ ...value,
+ ...groupIds,
+ ]),
+ ]);
+ } else {
+ field.onChange(
+ value.filter(
+ (id) => !groupIds.includes(id),
+ ),
+ );
+ }
+ }}
+ />
+ </FormControl>
+ <FormLabel>{tracker.groupName}</FormLabel>
+ </FormItem>
+ );
+ }}
+ />
+ {tracker.components.map((component) => (
+ <FormField
+ key={component.id}
+ control={form.control}
+ name="pageComponents"
+ render={({ field }) => (
+ <FormItem className="flex items-center gap-2 pl-6">
+ <FormControl>
+ <Checkbox
+ checked={field.value?.includes(
+ component.id,
+ )}
+ onCheckedChange={(checked) => {
+ const value = field.value ?? [];
+ if (checked) {
+ field.onChange([
+ ...value,
+ component.id,
+ ]);
+ } else {
+ field.onChange(
+ value.filter(
+ (id) => id !== component.id,
+ ),
+ );
+ }
+ }}
+ />
+ </FormControl>
+ <FormLabel>{component.name}</FormLabel>
+ </FormItem>
+ )}
+ />
+ ))}
+ </div>
+ );
+ }
+ return (
+ <FormField
+ key={tracker.component.id}
+ control={form.control}
+ name="pageComponents"
+ render={({ field }) => (
+ <FormItem className="flex items-center gap-2">
+ <FormControl>
+ <Checkbox
+ checked={field.value?.includes(
+ tracker.component.id,
+ )}
+ onCheckedChange={(checked) => {
+ const value = field.value ?? [];
+ if (checked) {
+ field.onChange([
+ ...value,
+ tracker.component.id,
+ ]);
+ } else {
+ field.onChange(
+ value.filter(
+ (id) => id !== tracker.component.id,
+ ),
+ );
+ }
+ }}
+ />
+ </FormControl>
+ <FormLabel>{tracker.component.name}</FormLabel>
+ </FormItem>
+ )}
+ />
+ );
+ })
+ ) : (
+ <StatusBlankContainer>
+ <StatusBlankTitle>
+ No components to subscribe to
+ </StatusBlankTitle>
+ <StatusBlankDescription>
+ This page has no components to subscribe to.
+ </StatusBlankDescription>
+ </StatusBlankContainer>
+ )}
+ </div>
+ </>
+ )}
+ </>
+ )}
</form>
</Form>
);
diff --git a/apps/status-page/src/components/nav/header.tsx b/apps/status-page/src/components/nav/header.tsx
index 16802631e..fbcbbacef 100644
--- a/apps/status-page/src/components/nav/header.tsx
+++ b/apps/status-page/src/components/nav/header.tsx
@@ -79,16 +79,15 @@ export function Header(props: React.ComponentProps<"header">) {
});
const sendPageSubscriptionMutation = useMutation(
- trpc.emailRouter.sendPageSubscription.mutationOptions({}),
+ trpc.emailRouter.sendPageSubscriptionVerification.mutationOptions({}),
);
const subscribeMutation = useMutation(
trpc.statusPage.subscribe.mutationOptions({
- onSuccess: (id) => {
- console.log("subscribeMutation onSuccess", id);
- if (!id) return;
+ onSuccess: (data) => {
+ if (!data?.id || !data?.token) return;
sendPageSubscriptionMutation.mutate(
- { id },
+ { id: data.id, token: data.token },
{
onError: (error) => {
if (isTRPCClientError(error)) {
@@ -148,8 +147,8 @@ export function Header(props: React.ComponentProps<"header">) {
) : null}
<StatusUpdates
types={getStatusUpdateTypes(page)}
- onSubscribe={async (email) => {
- await subscribeMutation.mutateAsync({ slug: domain, email });
+ onSubscribe={async (values) => {
+ await subscribeMutation.mutateAsync({ slug: domain, ...values });
}}
page={page}
/>
diff --git a/apps/status-page/src/components/status-page/status-updates.tsx b/apps/status-page/src/components/status-page/status-updates.tsx
index ab1860c64..fe61ec6de 100644
--- a/apps/status-page/src/components/status-page/status-updates.tsx
+++ b/apps/status-page/src/components/status-page/status-updates.tsx
@@ -1,6 +1,9 @@
"use client";
-import { FormSubscribeEmail } from "@/components/forms/form-subscribe-email";
+import {
+ FormSubscribeEmail,
+ type FormValues,
+} from "@/components/forms/form-subscribe-email";
import { getBaseUrl } from "@/lib/base-url";
import type { RouterOutputs } from "@openstatus/api";
import { Button } from "@openstatus/ui/components/ui/button";
@@ -42,7 +45,7 @@ function getUpdateLink(type: "rss" | "json" | "atom", page?: Page | null) {
interface StatusUpdatesProps extends React.ComponentProps<typeof Button> {
types?: StatusUpdateType[];
page?: Page | null;
- onSubscribe?: (value: string) => Promise<void> | void;
+ onSubscribe?: (values: FormValues) => Promise<void> | void;
}
export function StatusUpdates({
@@ -92,19 +95,21 @@ export function StatusUpdates({
<SuccessMessage />
) : (
<>
- <div className="flex flex-col gap-2 border-b px-2 pb-2">
- <p className="text-sm">
+ <div className="flex flex-col gap-2">
+ <p className="px-2 text-sm">
Get email notifications whenever a report has been created
or resolved
</p>
<FormSubscribeEmail
id="email-form"
+ page={page}
onSubmit={async (values) => {
- await onSubscribe?.(values.email);
+ await onSubscribe?.(values);
setSuccess(true);
}}
/>
</div>
+ <Separator />
<div className="px-2 pb-2">
<Button className="w-full" type="submit" form="email-form">
Subscribe
diff --git a/apps/web/src/lib/metadata/structured-data.ts b/apps/web/src/lib/metadata/structured-data.ts
index 69f64aa0f..51640ee76 100644
--- a/apps/web/src/lib/metadata/structured-data.ts
+++ b/apps/web/src/lib/metadata/structured-data.ts
@@ -85,6 +85,7 @@ export const getJsonLDProduct = (): WithContext<Product> => {
name: "openstatus",
description:
"Open-source uptime and synthetic monitoring with status pages.",
+ image: `${BASE_URL}/assets/logos/OpenStatus-Logo.svg`,
url: BASE_URL,
brand: {
"@type": "Brand",
diff --git a/packages/api/package.json b/packages/api/package.json
index 42c7e7f99..db3d77a7a 100644
--- a/packages/api/package.json
+++ b/packages/api/package.json
@@ -9,6 +9,7 @@
},
"dependencies": {
"@openstatus/analytics": "workspace:*",
+ "@openstatus/subscriptions": "workspace:*",
"@openstatus/assertions": "workspace:*",
"@openstatus/db": "workspace:*",
"@openstatus/emails": "workspace:*",
diff --git a/packages/api/src/router/email/index.ts b/packages/api/src/router/email/index.ts
index 00893d48a..fe3f69c8c 100644
--- a/packages/api/src/router/email/index.ts
+++ b/packages/api/src/router/email/index.ts
@@ -1,6 +1,6 @@
import { z } from "zod";
-import { and, eq, isNotNull } from "@openstatus/db";
+import { and, eq } from "@openstatus/db";
import {
invitation,
maintenance,
@@ -9,6 +9,11 @@ import {
statusReportUpdate,
} from "@openstatus/db/src/schema";
import { EmailClient } from "@openstatus/emails";
+import {
+ dispatchMaintenanceUpdate,
+ dispatchStatusReportUpdate,
+ getChannel,
+} from "@openstatus/subscriptions";
import { TRPCError } from "@trpc/server";
import { env } from "../../env";
import {
@@ -20,125 +25,175 @@ import {
const emailClient = new EmailClient({ apiKey: env.RESEND_API_KEY });
export const emailRouter = createTRPCRouter({
+ /**
+ * PUBLIC: Send verification email for a new page subscription
+ * Called after upsert to trigger the verification flow
+ */
+ sendPageSubscriptionVerification: publicProcedure
+ .input(
+ z.object({
+ id: z.number().int().positive(),
+ token: z.uuid(),
+ }),
+ )
+ .mutation(async (opts) => {
+ const subscriber = await opts.ctx.db.query.pageSubscriber.findFirst({
+ where: and(
+ eq(pageSubscriber.id, opts.input.id),
+ eq(pageSubscriber.token, opts.input.token),
+ ),
+ with: {
+ page: {
+ with: {
+ workspace: true,
+ },
+ },
+ },
+ });
+
+ if (!subscriber) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Subscriber not found",
+ });
+ }
+
+ const workspace = selectWorkspaceSchema.safeParse(
+ subscriber.page?.workspace,
+ );
+
+ if (!workspace.success) {
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "Invalid workspace",
+ });
+ }
+
+ if (!workspace.data.limits["status-subscribers"]) {
+ return;
+ }
+
+ if (!subscriber.email) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: "No email associated with this subscription",
+ });
+ }
+
+ if (subscriber.acceptedAt) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: "Subscription already verified",
+ });
+ }
+
+ if (!subscriber.token) {
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "Subscription has no verification token",
+ });
+ }
+
+ const verifyUrl = subscriber.page.customDomain
+ ? `https://${subscriber.page.customDomain}/verify/${subscriber.token}`
+ : `https://${subscriber.page.slug}.openstatus.dev/verify/${subscriber.token}`;
+
+ const channel = getChannel("email");
+ if (!channel) {
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "Email channel not found",
+ });
+ }
+
+ await channel.sendVerification?.(
+ {
+ id: subscriber.id,
+ pageId: subscriber.pageId,
+ pageName: subscriber.page.title,
+ pageSlug: subscriber.page.slug,
+ customDomain: subscriber.page.customDomain,
+ componentIds: [],
+ channelType: "email",
+ email: subscriber.email,
+ token: subscriber.token,
+ acceptedAt: subscriber.acceptedAt ?? undefined,
+ },
+ verifyUrl,
+ );
+
+ return { success: true };
+ }),
+
+ /**
+ * PROTECTED: Send status report update notifications via dispatcher
+ */
sendStatusReport: protectedProcedure
.input(z.object({ id: z.number() }))
.mutation(async (opts) => {
const limits = opts.ctx.workspace.limits;
- if (limits["status-subscribers"]) {
- const _statusReportUpdate =
- await opts.ctx.db.query.statusReportUpdate.findFirst({
- where: eq(statusReportUpdate.id, opts.input.id),
- with: {
- statusReport: {
- with: {
- statusReportsToPageComponents: {
- with: {
- pageComponent: true,
- },
- },
- page: {
- with: {
- pageSubscribers: {
- where: isNotNull(pageSubscriber.acceptedAt),
- },
- },
- },
- },
- },
- },
- });
-
- if (!_statusReportUpdate) return;
- if (!_statusReportUpdate.statusReport.page) return;
- if (
- _statusReportUpdate.statusReport.page.workspaceId !==
- opts.ctx.workspace.id
- )
- return;
- const validSubscribers =
- _statusReportUpdate.statusReport.page.pageSubscribers.filter(
- (s): s is typeof s & { token: string } =>
- s.token !== null &&
- s.acceptedAt !== null &&
- s.unsubscribedAt === null,
- );
- if (!validSubscribers.length) return;
-
- await emailClient.sendStatusReportUpdate({
- subscribers: validSubscribers.map((subscriber) => ({
- email: subscriber.email,
- token: subscriber.token,
- })),
- pageTitle: _statusReportUpdate.statusReport.page.title,
- pageSlug: _statusReportUpdate.statusReport.page.slug,
- customDomain: _statusReportUpdate.statusReport.page.customDomain,
- reportTitle: _statusReportUpdate.statusReport.title,
- status: _statusReportUpdate.status,
- message: _statusReportUpdate.message,
- date: new Date(_statusReportUpdate.date).toISOString(),
- pageComponents:
- _statusReportUpdate.statusReport.statusReportsToPageComponents.map(
- (i) => i.pageComponent.name,
- ),
+ if (!limits["status-subscribers"]) {
+ return;
+ }
+
+ const update = await opts.ctx.db.query.statusReportUpdate.findFirst({
+ where: eq(statusReportUpdate.id, opts.input.id),
+ with: {
+ statusReport: true,
+ },
+ });
+
+ if (!update?.statusReport) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Status report update not found",
+ });
+ }
+
+ if (update.statusReport.workspaceId !== opts.ctx.workspace.id) {
+ throw new TRPCError({
+ code: "FORBIDDEN",
+ message: "Status report does not belong to your workspace",
});
}
+
+ await dispatchStatusReportUpdate(opts.input.id);
+
+ return { success: true };
}),
+
+ /**
+ * PROTECTED: Send maintenance notifications via dispatcher
+ */
sendMaintenance: protectedProcedure
.input(z.object({ id: z.number() }))
.mutation(async (opts) => {
const limits = opts.ctx.workspace.limits;
- if (limits["status-subscribers"]) {
- const _maintenance = await opts.ctx.db.query.maintenance.findFirst({
- where: and(
- eq(maintenance.id, opts.input.id),
- eq(maintenance.workspaceId, opts.ctx.workspace.id),
- ),
- with: {
- maintenancesToPageComponents: {
- with: {
- pageComponent: true,
- },
- },
- page: {
- with: {
- pageSubscribers: {
- where: isNotNull(pageSubscriber.acceptedAt),
- },
- },
- },
- },
- });
+ if (!limits["status-subscribers"]) {
+ return;
+ }
- if (!_maintenance) return;
- if (!_maintenance.page) return;
- const validSubscribers = _maintenance.page.pageSubscribers.filter(
- (s): s is typeof s & { token: string } =>
- s.token !== null &&
- s.acceptedAt !== null &&
- s.unsubscribedAt === null,
- );
- if (!validSubscribers.length) return;
-
- await emailClient.sendStatusReportUpdate({
- subscribers: validSubscribers.map((subscriber) => ({
- email: subscriber.email,
- token: subscriber.token,
- })),
- pageTitle: _maintenance.page.title,
- pageSlug: _maintenance.page.slug,
- customDomain: _maintenance.page.customDomain,
- reportTitle: _maintenance.title,
- status: "maintenance",
- message: _maintenance.message,
- date: new Date(_maintenance.from).toISOString(),
- pageComponents: _maintenance.maintenancesToPageComponents.map(
- (i) => i.pageComponent.name,
- ),
+ const _maintenance = await opts.ctx.db.query.maintenance.findFirst({
+ where: and(
+ eq(maintenance.id, opts.input.id),
+ eq(maintenance.workspaceId, opts.ctx.workspace.id),
+ ),
+ });
+
+ if (!_maintenance) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Maintenance not found",
});
}
+
+ await dispatchMaintenanceUpdate(opts.input.id);
+
+ return { success: true };
}),
+
sendTeamInvitation: protectedProcedure
.input(z.object({ id: z.number(), baseUrl: z.string().optional() }))
.mutation(async (opts) => {
@@ -163,53 +218,4 @@ export const emailRouter = createTRPCRouter({
});
}
}),
-
- sendPageSubscription: publicProcedure
- .input(z.object({ id: z.number() }))
- .mutation(async (opts) => {
- const _pageSubscriber = await opts.ctx.db.query.pageSubscriber.findFirst({
- where: eq(pageSubscriber.id, opts.input.id),
- with: {
- page: {
- with: {
- workspace: true,
- },
- },
- },
- });
-
- if (!_pageSubscriber || !_pageSubscriber.token) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "Page subscriber not found",
- });
- }
-
- const workspace = selectWorkspaceSchema.safeParse(
- _pageSubscriber.page.workspace,
- );
-
- if (!workspace.success) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "Workspace not found",
- });
- }
- if (!workspace.data.limits["status-subscribers"]) {
- throw new TRPCError({
- code: "FORBIDDEN",
- message: "Upgrade to use status subscribers",
- });
- }
-
- const link = _pageSubscriber.page.customDomain
- ? `https://${_pageSubscriber.page.customDomain}/verify/${_pageSubscriber.token}`
- : `https://${_pageSubscriber.page.slug}.openstatus.dev/verify/${_pageSubscriber.token}`;
-
- await emailClient.sendPageSubscription({
- to: _pageSubscriber.email,
- page: _pageSubscriber.page.title,
- link,
- });
- }),
});
diff --git a/packages/api/src/router/pageSubscriber.ts b/packages/api/src/router/pageSubscriber.ts
index 7549de442..cb4e2f4a3 100644
--- a/packages/api/src/router/pageSubscriber.ts
+++ b/packages/api/src/router/pageSubscriber.ts
@@ -1,11 +1,230 @@
import { and, eq } from "@openstatus/db";
import { page, pageSubscriber } from "@openstatus/db/src/schema";
+import {
+ getSubscriptionByToken,
+ hasPendingUnexpiredSubscription,
+ unsubscribe,
+ updateSubscriptionScope,
+ upsertEmailSubscription,
+ verifySubscription,
+} from "@openstatus/subscriptions";
import { TRPCError } from "@trpc/server";
import { z } from "zod";
-import { createTRPCRouter, protectedProcedure } from "../trpc";
+import { createTRPCRouter, protectedProcedure, publicProcedure } from "../trpc";
export const pageSubscriberRouter = createTRPCRouter({
+ /**
+ * PUBLIC: Subscribe to a status page (or update existing subscription)
+ */
+ upsert: publicProcedure
+ .input(
+ z.object({
+ email: z.email(),
+ pageId: z.number().int().positive(),
+ componentIds: z.array(z.number().int().positive()).optional(),
+ }),
+ )
+ .mutation(async (opts) => {
+ // Guard against email spam: reject if a pending (unverified, unexpired) subscription exists
+ const isPending = await hasPendingUnexpiredSubscription(
+ opts.input.email,
+ opts.input.pageId,
+ );
+ if (isPending) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message:
+ "A confirmation link was already sent. Please check your email or wait until it expires to request a new one.",
+ });
+ }
+
+ try {
+ const subscription = await upsertEmailSubscription({
+ email: opts.input.email,
+ pageId: opts.input.pageId,
+ componentIds: opts.input.componentIds,
+ });
+
+ return {
+ success: true,
+ subscription: {
+ id: subscription.id,
+ acceptedAt: subscription.acceptedAt,
+ componentIds: subscription.componentIds,
+ },
+ };
+ } catch (error) {
+ if (error instanceof Error) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: error.message,
+ });
+ }
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: "Failed to create subscription",
+ });
+ }
+ }),
+
+ /**
+ * PUBLIC: Verify email subscription by token
+ */
+ verify: publicProcedure
+ .input(
+ z.object({
+ token: z.uuid(),
+ domain: z.string().toLowerCase().optional(),
+ }),
+ )
+ .mutation(async (opts) => {
+ try {
+ const subscription = await verifySubscription(
+ opts.input.token,
+ opts.input.domain,
+ );
+
+ if (!subscription) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Subscription not found or token invalid",
+ });
+ }
+
+ return {
+ success: true,
+ subscription: {
+ id: subscription.id,
+ email: subscription.email,
+ pageSlug: subscription.pageSlug,
+ pageName: subscription.pageName,
+ componentIds: subscription.componentIds,
+ },
+ };
+ } catch (error) {
+ if (error instanceof TRPCError) throw error;
+ if (error instanceof Error) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: error.message,
+ });
+ }
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: "Failed to verify subscription",
+ });
+ }
+ }),
+
+ /**
+ * PUBLIC: Get subscription by token (for management UI)
+ */
+ getByToken: publicProcedure
+ .input(
+ z.object({
+ token: z.string(),
+ domain: z.string().toLowerCase().optional(),
+ }),
+ )
+ .query(async (opts) => {
+ const subscription = await getSubscriptionByToken(
+ opts.input.token,
+ opts.input.domain,
+ );
+
+ if (!subscription) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Subscription not found",
+ });
+ }
+
+ return {
+ id: subscription.id,
+ email: subscription.email,
+ pageName: subscription.pageName,
+ pageSlug: subscription.pageSlug,
+ customDomain: subscription.customDomain,
+ channelType: subscription.channelType,
+ componentIds: subscription.componentIds,
+ acceptedAt: subscription.acceptedAt,
+ unsubscribedAt: subscription.unsubscribedAt,
+ };
+ }),
+
+ /**
+ * PUBLIC: Update subscription scope (replace components)
+ */
+ updateScope: publicProcedure
+ .input(
+ z.object({
+ token: z.string(),
+ componentIds: z.array(z.number().int().positive()),
+ domain: z.string().toLowerCase().optional(),
+ }),
+ )
+ .mutation(async (opts) => {
+ try {
+ const subscription = await updateSubscriptionScope({
+ token: opts.input.token,
+ componentIds: opts.input.componentIds,
+ domain: opts.input.domain,
+ });
+
+ return {
+ success: true,
+ subscription: {
+ id: subscription.id,
+ componentIds: subscription.componentIds,
+ },
+ };
+ } catch (error) {
+ if (error instanceof Error) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: error.message,
+ });
+ }
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: "Failed to update subscription scope",
+ });
+ }
+ }),
+
+ /**
+ * PUBLIC: Unsubscribe by token
+ */
+ unsubscribe: publicProcedure
+ .input(
+ z.object({
+ token: z.string(),
+ domain: z.string().toLowerCase().optional(),
+ }),
+ )
+ .mutation(async (opts) => {
+ try {
+ await unsubscribe(opts.input.token, opts.input.domain);
+
+ return { success: true };
+ } catch (error) {
+ if (error instanceof Error) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: error.message,
+ });
+ }
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: "Failed to unsubscribe",
+ });
+ }
+ }),
+
+ /**
+ * PROTECTED: List all subscriptions for a page (dashboard)
+ */
list: protectedProcedure
.input(
z.object({
@@ -29,14 +248,44 @@ export const pageSubscriberRouter = createTRPCRouter({
});
}
- return await tx.query.pageSubscriber.findMany({
+ const subscriptions = await tx.query.pageSubscriber.findMany({
where: eq(pageSubscriber.pageId, _page.id),
+ with: {
+ components: {
+ with: {
+ pageComponent: true,
+ },
+ },
+ },
+ orderBy: (subs, { desc, asc }) =>
+ opts.input.order === "asc"
+ ? asc(subs.createdAt)
+ : desc(subs.createdAt),
});
+
+ return subscriptions.map((sub) => ({
+ id: sub.id,
+ channelType: sub.channelType,
+ email: sub.email,
+ webhookUrl: sub.webhookUrl,
+ acceptedAt: sub.acceptedAt,
+ unsubscribedAt: sub.unsubscribedAt,
+ createdAt: sub.createdAt,
+ components: sub.components.map((c) => ({
+ id: c.pageComponent.id,
+ name: c.pageComponent.name,
+ })),
+ isEntirePage: sub.components.length === 0,
+ pageId: sub.pageId,
+ }));
});
return data;
}),
+ /**
+ * PROTECTED: Delete a subscription (dashboard)
+ */
delete: protectedProcedure
.input(z.object({ id: z.number(), pageId: z.number() }))
.mutation(async (opts) => {
@@ -73,5 +322,7 @@ export const pageSubscriberRouter = createTRPCRouter({
.delete(pageSubscriber)
.where(eq(pageSubscriber.id, opts.input.id));
});
+
+ return { success: true };
}),
});
diff --git a/packages/api/src/router/statusPage.ts b/packages/api/src/router/statusPage.ts
index 602b6089f..06ed7f4c4 100644
--- a/packages/api/src/router/statusPage.ts
+++ b/packages/api/src/router/statusPage.ts
@@ -6,7 +6,6 @@ import {
page,
pageComponent,
pageConfigurationSchema,
- pageSubscriber,
selectMaintenancePageSchema,
selectPageComponentWithMonitorRelation,
selectPublicMonitorSchema,
@@ -16,6 +15,14 @@ import {
selectWorkspaceSchema,
statusReport,
} from "@openstatus/db/src/schema";
+import {
+ getSubscriptionByToken,
+ hasPendingUnexpiredSubscription,
+ unsubscribe,
+ updateSubscriptionScope,
+ upsertEmailSubscription,
+ verifySubscription,
+} from "@openstatus/subscriptions";
import { Events } from "@openstatus/analytics";
import { TRPCError } from "@trpc/server";
@@ -1004,7 +1011,14 @@ export const statusPageRouter = createTRPCRouter({
subscribe: publicProcedure
.meta({ track: Events.SubscribePage, trackProps: ["slug", "email"] })
- .input(z.object({ slug: z.string().toLowerCase(), email: z.email() }))
+ .input(
+ z.object({
+ slug: z.string().toLowerCase(),
+ email: z.email(),
+ subscribeComponents: z.boolean(),
+ pageComponents: z.array(z.number().int().positive()),
+ }),
+ )
.mutation(async (opts) => {
if (!opts.input.slug) return null;
@@ -1038,71 +1052,89 @@ export const statusPageRouter = createTRPCRouter({
});
}
- // Check for existing subscriber (active or unsubscribed)
- const _existingSubscriber =
- await opts.ctx.db.query.pageSubscriber.findFirst({
- where: and(
- eq(pageSubscriber.pageId, _page.id),
- eq(pageSubscriber.email, opts.input.email),
- ),
+ // Guard against email spam: reject if a pending (unverified, unexpired) subscription exists
+ const isPending = await hasPendingUnexpiredSubscription(
+ opts.input.email,
+ _page.id,
+ );
+ if (isPending) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message:
+ "A confirmation link was already sent. Please check your email or wait until it expires to request a new one.",
});
+ }
- // If already subscribed and verified (not unsubscribed), reject
- if (
- _existingSubscriber?.acceptedAt &&
- !_existingSubscriber.unsubscribedAt
- ) {
+ const subscription = await upsertEmailSubscription({
+ email: opts.input.email,
+ pageId: _page.id,
+ componentIds: opts.input.subscribeComponents
+ ? opts.input.pageComponents
+ : [],
+ });
+
+ // Already verified — no need to send another verification email
+ if (subscription.acceptedAt) {
throw new TRPCError({
code: "BAD_REQUEST",
message: "Email already subscribed",
});
}
- // Handle re-subscription: clear unsubscribedAt, regenerate token, reset acceptedAt
- if (_existingSubscriber?.unsubscribedAt) {
- const updatedSubscriber = await opts.ctx.db
- .update(pageSubscriber)
- .set({
- unsubscribedAt: null,
- acceptedAt: null,
- token: crypto.randomUUID(),
- expiresAt: new Date(Date.now() + 1000 * 60 * 60 * 24 * 7),
- })
- .where(eq(pageSubscriber.id, _existingSubscriber.id))
- .returning()
- .get();
-
- return updatedSubscriber.id;
- }
+ return { id: subscription.id, token: subscription.token };
+ }),
+
+ getSubscriptionByToken: publicProcedure
+ .input(z.object({ slug: z.string().toLowerCase(), token: z.uuid() }))
+ .query(async (opts) => {
+ if (!opts.input.slug) return null;
+
+ const subscription = await getSubscriptionByToken(
+ opts.input.token,
+ opts.input.slug,
+ );
- // Handle pending re-subscription (not yet verified): regenerate token
- if (_existingSubscriber && !_existingSubscriber.acceptedAt) {
- const updatedSubscriber = await opts.ctx.db
- .update(pageSubscriber)
- .set({
- token: crypto.randomUUID(),
- expiresAt: new Date(Date.now() + 1000 * 60 * 60 * 24 * 7),
- })
- .where(eq(pageSubscriber.id, _existingSubscriber.id))
- .returning()
- .get();
-
- return updatedSubscriber.id;
+ if (!subscription) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Subscription not found",
+ });
}
- // New subscription
- const _pageSubscriber = await opts.ctx.db
- .insert(pageSubscriber)
- .values({
- pageId: _page.id,
- email: opts.input.email,
- token: crypto.randomUUID(),
- expiresAt: new Date(Date.now() + 1000 * 60 * 60 * 24 * 7),
- })
- .returning()
- .get();
+ return subscription;
+ }),
+
+ updateSubscription: publicProcedure
+ .input(
+ z.object({
+ slug: z.string().toLowerCase(),
+ token: z.uuid(),
+ subscribeComponents: z.boolean(),
+ pageComponents: z.array(z.number().int().positive()),
+ }),
+ )
+ .mutation(async (opts) => {
+ if (!opts.input.slug) return null;
- return _pageSubscriber.id;
+ try {
+ await updateSubscriptionScope({
+ token: opts.input.token,
+ componentIds: opts.input.subscribeComponents
+ ? opts.input.pageComponents
+ : [],
+ domain: opts.input.slug,
+ });
+ } catch (error) {
+ if (error instanceof Error) {
+ const code = error.message.toLowerCase().includes("not found")
+ ? "NOT_FOUND"
+ : "BAD_REQUEST";
+ throw new TRPCError({ code, message: error.message });
+ }
+ throw error;
+ }
+
+ return { success: true };
}),
validateEmailDomain: publicProcedure
@@ -1148,46 +1180,31 @@ export const statusPageRouter = createTRPCRouter({
verifyEmail: publicProcedure
.meta({ track: Events.VerifySubscribePage, trackProps: ["slug"] })
- .input(z.object({ slug: z.string().toLowerCase(), token: z.string() }))
+ .input(z.object({ slug: z.string().toLowerCase(), token: z.uuid() }))
.mutation(async (opts) => {
if (!opts.input.slug) return null;
- const _page = await opts.ctx.db.query.page.findFirst({
- where: sql`lower(${page.slug}) = ${opts.input.slug} OR lower(${page.customDomain}) = ${opts.input.slug}`,
- });
-
- if (!_page) return null;
-
- const _pageSubscriber = await opts.ctx.db.query.pageSubscriber.findFirst({
- where: and(
- eq(pageSubscriber.token, opts.input.token),
- eq(pageSubscriber.pageId, _page.id),
- ),
- });
+ try {
+ const subscription = await verifySubscription(
+ opts.input.token,
+ opts.input.slug,
+ );
- if (_pageSubscriber?.acceptedAt) {
- throw new TRPCError({
- code: "BAD_REQUEST",
- message: "Email already verified",
- });
- }
+ if (!subscription) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Subscription not found",
+ });
+ }
- if (!_pageSubscriber) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "Subscription not found",
- });
+ return subscription;
+ } catch (error) {
+ if (error instanceof TRPCError) throw error;
+ if (error instanceof Error) {
+ throw new TRPCError({ code: "BAD_REQUEST", message: error.message });
+ }
+ throw error;
}
-
- await opts.ctx.db
- .update(pageSubscriber)
- .set({
- acceptedAt: new Date(),
- })
- .where(eq(pageSubscriber.id, _pageSubscriber.id))
- .execute();
-
- return _pageSubscriber;
}),
verifyPassword: publicProcedure
@@ -1224,94 +1241,38 @@ export const statusPageRouter = createTRPCRouter({
}),
getSubscriberByToken: publicProcedure
- .input(
- z.object({ token: z.string().uuid(), domain: z.string().toLowerCase() }),
- )
+ .input(z.object({ token: z.uuid(), domain: z.string().toLowerCase() }))
.query(async (opts) => {
- const _page = await opts.ctx.db.query.page.findFirst({
- where: sql`lower(${page.slug}) = ${opts.input.domain} OR lower(${page.customDomain}) = ${opts.input.domain}`,
- });
-
- if (!_page) return null;
-
- const _pageSubscriber = await opts.ctx.db.query.pageSubscriber.findFirst({
- where: and(
- eq(pageSubscriber.token, opts.input.token),
- eq(pageSubscriber.pageId, _page.id),
- ),
- });
-
- // Return null if not found or already unsubscribed
- if (!_pageSubscriber) {
- return null;
- }
+ const subscription = await getSubscriptionByToken(
+ opts.input.token,
+ opts.input.domain,
+ );
- if (_pageSubscriber.unsubscribedAt) {
+ if (
+ !subscription ||
+ subscription.unsubscribedAt ||
+ subscription.channelType !== "email"
+ ) {
return null;
}
- // Mask email: show first character, then ***, then @domain
- const email = _pageSubscriber.email;
- const [localPart, domain] = email.split("@");
- const maskedEmail =
- localPart.length > 0 ? `${localPart[0]}***@${domain}` : `***@${domain}`;
-
return {
- pageName: _page.title,
- maskedEmail,
+ pageName: subscription.pageName,
+ maskedEmail: subscription.email,
};
}),
unsubscribe: publicProcedure
- .input(
- z.object({ token: z.string().uuid(), domain: z.string().toLowerCase() }),
- )
+ .input(z.object({ token: z.uuid(), domain: z.string().toLowerCase() }))
.mutation(async (opts) => {
- const _page = await opts.ctx.db.query.page.findFirst({
- where: sql`lower(${page.slug}) = ${opts.input.domain} OR lower(${page.customDomain}) = ${opts.input.domain}`,
- });
-
- if (!_page) return null;
-
- const _pageSubscriber = await opts.ctx.db.query.pageSubscriber.findFirst({
- where: and(
- eq(pageSubscriber.token, opts.input.token),
- eq(pageSubscriber.pageId, _page.id),
- ),
- });
-
- if (!_pageSubscriber) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "Subscription not found",
- });
- }
-
- if (!_pageSubscriber.acceptedAt) {
- throw new TRPCError({
- code: "BAD_REQUEST",
- message: "Subscription not yet verified",
- });
- }
-
- if (_pageSubscriber.unsubscribedAt) {
- throw new TRPCError({
- code: "BAD_REQUEST",
- message: "Already unsubscribed",
- });
+ try {
+ await unsubscribe(opts.input.token, opts.input.domain);
+ return { success: true };
+ } catch (error) {
+ if (error instanceof Error) {
+ throw new TRPCError({ code: "BAD_REQUEST", message: error.message });
+ }
+ throw error;
}
-
- await opts.ctx.db
- .update(pageSubscriber)
- .set({
- unsubscribedAt: new Date(),
- })
- .where(eq(pageSubscriber.id, _pageSubscriber.id))
- .execute();
-
- return {
- success: true,
- pageName: _page.title,
- };
}),
});
diff --git a/packages/db/drizzle/0056_violet_shotgun.sql b/packages/db/drizzle/0056_violet_shotgun.sql
new file mode 100644
index 000000000..dfcf9472c
--- /dev/null
+++ b/packages/db/drizzle/0056_violet_shotgun.sql
@@ -0,0 +1,33 @@
+CREATE TABLE `page_subscriber_to_page_component` (
+ `page_subscriber_id` integer NOT NULL,
+ `page_component_id` integer NOT NULL,
+ `created_at` integer DEFAULT (strftime('%s', 'now')),
+ PRIMARY KEY(`page_subscriber_id`, `page_component_id`),
+ FOREIGN KEY (`page_subscriber_id`) REFERENCES `page_subscriber`(`id`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`page_component_id`) REFERENCES `page_component`(`id`) ON UPDATE no action ON DELETE cascade
+);
+--> statement-breakpoint
+PRAGMA foreign_keys=OFF;--> statement-breakpoint
+CREATE TABLE `__new_page_subscriber` (
+ `id` integer PRIMARY KEY NOT NULL,
+ `email` text NOT NULL,
+ `page_id` integer NOT NULL,
+ `channel_type` text DEFAULT 'email' NOT NULL,
+ `webhook_url` text,
+ `channel_config` text,
+ `token` text,
+ `accepted_at` integer,
+ `expires_at` integer,
+ `unsubscribed_at` integer,
+ `created_at` integer DEFAULT (strftime('%s', 'now')),
+ `updated_at` integer DEFAULT (strftime('%s', 'now')),
+ FOREIGN KEY (`page_id`) REFERENCES `page`(`id`) ON UPDATE no action ON DELETE cascade,
+ CONSTRAINT "page_subscriber_channel_check" CHECK(("__new_page_subscriber"."channel_type" = 'email' AND "__new_page_subscriber"."email" IS NOT NULL AND "__new_page_subscriber"."webhook_url" IS NULL) OR ("__new_page_subscriber"."channel_type" = 'webhook' AND "__new_page_subscriber"."webhook_url" IS NOT NULL AND "__new_page_subscriber"."email" IS NULL))
+);
+--> statement-breakpoint
+INSERT INTO `__new_page_subscriber`("id", "email", "page_id", "channel_type", "webhook_url", "channel_config", "token", "accepted_at", "expires_at", "unsubscribed_at", "created_at", "updated_at") SELECT "id", "email", "page_id", 'email', NULL, NULL, "token", "accepted_at", "expires_at", "unsubscribed_at", "created_at", "updated_at" FROM `page_subscriber`;--> statement-breakpoint
+DROP TABLE `page_subscriber`;--> statement-breakpoint
+ALTER TABLE `__new_page_subscriber` RENAME TO `page_subscriber`;--> statement-breakpoint
+PRAGMA foreign_keys=ON;--> statement-breakpoint
+CREATE UNIQUE INDEX `idx_page_subscriber_email_page_active` ON `page_subscriber` (LOWER("email"),`page_id`) WHERE "page_subscriber"."unsubscribed_at" IS NULL AND "page_subscriber"."channel_type" = 'email';--> statement-breakpoint
+CREATE UNIQUE INDEX `idx_page_subscriber_webhook_page_active` ON `page_subscriber` (`webhook_url`,`page_id`) WHERE "page_subscriber"."unsubscribed_at" IS NULL AND "page_subscriber"."channel_type" = 'webhook';
\ No newline at end of file
diff --git a/packages/db/drizzle/meta/0056_snapshot.json b/packages/db/drizzle/meta/0056_snapshot.json
new file mode 100644
index 000000000..d48855cff
--- /dev/null
+++ b/packages/db/drizzle/meta/0056_snapshot.json
@@ -0,0 +1,3580 @@
+{
+ "version": "6",
+ "dialect": "sqlite",
+ "id": "b585a66a-babd-44de-85a7-b154332cd51b",
+ "prevId": "4f344b53-2e8a-400d-be39-8018d77ff0a9",
+ "tables": {
+ "workspace": {
+ "name": "workspace",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "slug": {
+ "name": "slug",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "stripe_id": {
+ "name": "stripe_id",
+ "type": "text(256)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "subscription_id": {
+ "name": "subscription_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "plan": {
+ "name": "plan",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "ends_at": {
+ "name": "ends_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "paid_until": {
+ "name": "paid_until",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "limits": {
+ "name": "limits",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "dsn": {
+ "name": "dsn",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "workspace_slug_unique": {
+ "name": "workspace_slug_unique",
+ "columns": [
+ "slug"
+ ],
+ "isUnique": true
+ },
+ "workspace_stripe_id_unique": {
+ "name": "workspace_stripe_id_unique",
+ "columns": [
+ "stripe_id"
+ ],
+ "isUnique": true
+ },
+ "workspace_id_dsn_unique": {
+ "name": "workspace_id_dsn_unique",
+ "columns": [
+ "id",
+ "dsn"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "account": {
+ "name": "account",
+ "columns": {
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "provider_account_id": {
+ "name": "provider_account_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "refresh_token": {
+ "name": "refresh_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "access_token": {
+ "name": "access_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "token_type": {
+ "name": "token_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "id_token": {
+ "name": "id_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "session_state": {
+ "name": "session_state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "account_user_id_user_id_fk": {
+ "name": "account_user_id_user_id_fk",
+ "tableFrom": "account",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "account_provider_provider_account_id_pk": {
+ "columns": [
+ "provider",
+ "provider_account_id"
+ ],
+ "name": "account_provider_provider_account_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "session": {
+ "name": "session",
+ "columns": {
+ "session_token": {
+ "name": "session_token",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires": {
+ "name": "expires",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "session_user_id_user_id_fk": {
+ "name": "session_user_id_user_id_fk",
+ "tableFrom": "session",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "user": {
+ "name": "user",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tenant_id": {
+ "name": "tenant_id",
+ "type": "text(256)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "first_name": {
+ "name": "first_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "last_name": {
+ "name": "last_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "photo_url": {
+ "name": "photo_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "emailVerified": {
+ "name": "emailVerified",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {
+ "user_tenant_id_unique": {
+ "name": "user_tenant_id_unique",
+ "columns": [
+ "tenant_id"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "users_to_workspaces": {
+ "name": "users_to_workspaces",
+ "columns": {
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'member'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "users_to_workspaces_user_id_user_id_fk": {
+ "name": "users_to_workspaces_user_id_user_id_fk",
+ "tableFrom": "users_to_workspaces",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "users_to_workspaces_workspace_id_workspace_id_fk": {
+ "name": "users_to_workspaces_workspace_id_workspace_id_fk",
+ "tableFrom": "users_to_workspaces",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "users_to_workspaces_user_id_workspace_id_pk": {
+ "columns": [
+ "user_id",
+ "workspace_id"
+ ],
+ "name": "users_to_workspaces_user_id_workspace_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "verification_token": {
+ "name": "verification_token",
+ "columns": {
+ "identifier": {
+ "name": "identifier",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires": {
+ "name": "expires",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "verification_token_identifier_token_pk": {
+ "columns": [
+ "identifier",
+ "token"
+ ],
+ "name": "verification_token_identifier_token_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "status_report_to_monitors": {
+ "name": "status_report_to_monitors",
+ "columns": {
+ "monitor_id": {
+ "name": "monitor_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status_report_id": {
+ "name": "status_report_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "status_report_to_monitors_monitor_id_monitor_id_fk": {
+ "name": "status_report_to_monitors_monitor_id_monitor_id_fk",
+ "tableFrom": "status_report_to_monitors",
+ "tableTo": "monitor",
+ "columnsFrom": [
+ "monitor_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "status_report_to_monitors_status_report_id_status_report_id_fk": {
+ "name": "status_report_to_monitors_status_report_id_status_report_id_fk",
+ "tableFrom": "status_report_to_monitors",
+ "tableTo": "status_report",
+ "columnsFrom": [
+ "status_report_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "status_report_to_monitors_monitor_id_status_report_id_pk": {
+ "columns": [
+ "monitor_id",
+ "status_report_id"
+ ],
+ "name": "status_report_to_monitors_monitor_id_status_report_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "status_report": {
+ "name": "status_report",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text(256)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "page_id": {
+ "name": "page_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "status_report_workspace_id_workspace_id_fk": {
+ "name": "status_report_workspace_id_workspace_id_fk",
+ "tableFrom": "status_report",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "status_report_page_id_page_id_fk": {
+ "name": "status_report_page_id_page_id_fk",
+ "tableFrom": "status_report",
+ "tableTo": "page",
+ "columnsFrom": [
+ "page_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "status_report_update": {
+ "name": "status_report_update",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "date": {
+ "name": "date",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "message": {
+ "name": "message",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status_report_id": {
+ "name": "status_report_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "status_report_update_status_report_id_status_report_id_fk": {
+ "name": "status_report_update_status_report_id_status_report_id_fk",
+ "tableFrom": "status_report_update",
+ "tableTo": "status_report",
+ "columnsFrom": [
+ "status_report_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "integration": {
+ "name": "integration",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text(256)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "credential": {
+ "name": "credential",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "external_id": {
+ "name": "external_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "data": {
+ "name": "data",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "integration_workspace_id_workspace_id_fk": {
+ "name": "integration_workspace_id_workspace_id_fk",
+ "tableFrom": "integration",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "page": {
+ "name": "page",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "icon": {
+ "name": "icon",
+ "type": "text(256)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "slug": {
+ "name": "slug",
+ "type": "text(256)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "custom_domain": {
+ "name": "custom_domain",
+ "type": "text(256)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "published": {
+ "name": "published",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": false
+ },
+ "force_theme": {
+ "name": "force_theme",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'system'"
+ },
+ "password": {
+ "name": "password",
+ "type": "text(256)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "password_protected": {
+ "name": "password_protected",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": false
+ },
+ "access_type": {
+ "name": "access_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "'public'"
+ },
+ "auth_email_domains": {
+ "name": "auth_email_domains",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "homepage_url": {
+ "name": "homepage_url",
+ "type": "text(256)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "contact_url": {
+ "name": "contact_url",
+ "type": "text(256)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "legacy_page": {
+ "name": "legacy_page",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ },
+ "configuration": {
+ "name": "configuration",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "show_monitor_values": {
+ "name": "show_monitor_values",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {
+ "page_slug_unique": {
+ "name": "page_slug_unique",
+ "columns": [
+ "slug"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "page_workspace_id_workspace_id_fk": {
+ "name": "page_workspace_id_workspace_id_fk",
+ "tableFrom": "page",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "monitor": {
+ "name": "monitor",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "job_type": {
+ "name": "job_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'http'"
+ },
+ "periodicity": {
+ "name": "periodicity",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'other'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'active'"
+ },
+ "active": {
+ "name": "active",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": false
+ },
+ "regions": {
+ "name": "regions",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "url": {
+ "name": "url",
+ "type": "text(2048)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text(256)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "external_name": {
+ "name": "external_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "headers": {
+ "name": "headers",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "body": {
+ "name": "body",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "method": {
+ "name": "method",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "'GET'"
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "timeout": {
+ "name": "timeout",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 45000
+ },
+ "degraded_after": {
+ "name": "degraded_after",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "assertions": {
+ "name": "assertions",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "otel_endpoint": {
+ "name": "otel_endpoint",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "otel_headers": {
+ "name": "otel_headers",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "public": {
+ "name": "public",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": false
+ },
+ "retry": {
+ "name": "retry",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": 3
+ },
+ "follow_redirects": {
+ "name": "follow_redirects",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "deleted_at": {
+ "name": "deleted_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "monitor_workspace_id_workspace_id_fk": {
+ "name": "monitor_workspace_id_workspace_id_fk",
+ "tableFrom": "monitor",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "monitors_to_pages": {
+ "name": "monitors_to_pages",
+ "columns": {
+ "monitor_id": {
+ "name": "monitor_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "page_id": {
+ "name": "page_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "order": {
+ "name": "order",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": 0
+ },
+ "monitor_group_id": {
+ "name": "monitor_group_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "group_order": {
+ "name": "group_order",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": 0
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "monitors_to_pages_monitor_id_monitor_id_fk": {
+ "name": "monitors_to_pages_monitor_id_monitor_id_fk",
+ "tableFrom": "monitors_to_pages",
+ "tableTo": "monitor",
+ "columnsFrom": [
+ "monitor_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "monitors_to_pages_page_id_page_id_fk": {
+ "name": "monitors_to_pages_page_id_page_id_fk",
+ "tableFrom": "monitors_to_pages",
+ "tableTo": "page",
+ "columnsFrom": [
+ "page_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "monitors_to_pages_monitor_group_id_monitor_group_id_fk": {
+ "name": "monitors_to_pages_monitor_group_id_monitor_group_id_fk",
+ "tableFrom": "monitors_to_pages",
+ "tableTo": "monitor_group",
+ "columnsFrom": [
+ "monitor_group_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "monitors_to_pages_monitor_id_page_id_pk": {
+ "columns": [
+ "monitor_id",
+ "page_id"
+ ],
+ "name": "monitors_to_pages_monitor_id_page_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "page_subscriber": {
+ "name": "page_subscriber",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "page_id": {
+ "name": "page_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "channel_type": {
+ "name": "channel_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'email'"
+ },
+ "webhook_url": {
+ "name": "webhook_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "channel_config": {
+ "name": "channel_config",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "accepted_at": {
+ "name": "accepted_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "unsubscribed_at": {
+ "name": "unsubscribed_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {
+ "idx_page_subscriber_email_page_active": {
+ "name": "idx_page_subscriber_email_page_active",
+ "columns": [
+ "LOWER(\"email\")",
+ "page_id"
+ ],
+ "isUnique": true,
+ "where": "\"page_subscriber\".\"unsubscribed_at\" IS NULL AND \"page_subscriber\".\"channel_type\" = 'email'"
+ },
+ "idx_page_subscriber_webhook_page_active": {
+ "name": "idx_page_subscriber_webhook_page_active",
+ "columns": [
+ "webhook_url",
+ "page_id"
+ ],
+ "isUnique": true,
+ "where": "\"page_subscriber\".\"unsubscribed_at\" IS NULL AND \"page_subscriber\".\"channel_type\" = 'webhook'"
+ }
+ },
+ "foreignKeys": {
+ "page_subscriber_page_id_page_id_fk": {
+ "name": "page_subscriber_page_id_page_id_fk",
+ "tableFrom": "page_subscriber",
+ "tableTo": "page",
+ "columnsFrom": [
+ "page_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {
+ "page_subscriber_channel_check": {
+ "name": "page_subscriber_channel_check",
+ "value": "(\"page_subscriber\".\"channel_type\" = 'email' AND \"page_subscriber\".\"email\" IS NOT NULL AND \"page_subscriber\".\"webhook_url\" IS NULL) OR (\"page_subscriber\".\"channel_type\" = 'webhook' AND \"page_subscriber\".\"webhook_url\" IS NOT NULL AND \"page_subscriber\".\"email\" IS NULL)"
+ }
+ }
+ },
+ "page_subscriber_to_page_component": {
+ "name": "page_subscriber_to_page_component",
+ "columns": {
+ "page_subscriber_id": {
+ "name": "page_subscriber_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "page_component_id": {
+ "name": "page_component_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "page_subscriber_to_page_component_page_subscriber_id_page_subscriber_id_fk": {
+ "name": "page_subscriber_to_page_component_page_subscriber_id_page_subscriber_id_fk",
+ "tableFrom": "page_subscriber_to_page_component",
+ "tableTo": "page_subscriber",
+ "columnsFrom": [
+ "page_subscriber_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "page_subscriber_to_page_component_page_component_id_page_component_id_fk": {
+ "name": "page_subscriber_to_page_component_page_component_id_page_component_id_fk",
+ "tableFrom": "page_subscriber_to_page_component",
+ "tableTo": "page_component",
+ "columnsFrom": [
+ "page_component_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "page_subscriber_to_page_component_page_subscriber_id_page_component_id_pk": {
+ "columns": [
+ "page_subscriber_id",
+ "page_component_id"
+ ],
+ "name": "page_subscriber_to_page_component_page_subscriber_id_page_component_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "notification": {
+ "name": "notification",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "data": {
+ "name": "data",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "notification_workspace_id_workspace_id_fk": {
+ "name": "notification_workspace_id_workspace_id_fk",
+ "tableFrom": "notification",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "notification_trigger": {
+ "name": "notification_trigger",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "monitor_id": {
+ "name": "monitor_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "notification_id": {
+ "name": "notification_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "cron_timestamp": {
+ "name": "cron_timestamp",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "notification_id_monitor_id_crontimestampe": {
+ "name": "notification_id_monitor_id_crontimestampe",
+ "columns": [
+ "notification_id",
+ "monitor_id",
+ "cron_timestamp"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "notification_trigger_monitor_id_monitor_id_fk": {
+ "name": "notification_trigger_monitor_id_monitor_id_fk",
+ "tableFrom": "notification_trigger",
+ "tableTo": "monitor",
+ "columnsFrom": [
+ "monitor_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "notification_trigger_notification_id_notification_id_fk": {
+ "name": "notification_trigger_notification_id_notification_id_fk",
+ "tableFrom": "notification_trigger",
+ "tableTo": "notification",
+ "columnsFrom": [
+ "notification_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "notifications_to_monitors": {
+ "name": "notifications_to_monitors",
+ "columns": {
+ "monitor_id": {
+ "name": "monitor_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "notification_id": {
+ "name": "notification_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "notifications_to_monitors_monitor_id_monitor_id_fk": {
+ "name": "notifications_to_monitors_monitor_id_monitor_id_fk",
+ "tableFrom": "notifications_to_monitors",
+ "tableTo": "monitor",
+ "columnsFrom": [
+ "monitor_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "notifications_to_monitors_notification_id_notification_id_fk": {
+ "name": "notifications_to_monitors_notification_id_notification_id_fk",
+ "tableFrom": "notifications_to_monitors",
+ "tableTo": "notification",
+ "columnsFrom": [
+ "notification_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "notifications_to_monitors_monitor_id_notification_id_pk": {
+ "columns": [
+ "monitor_id",
+ "notification_id"
+ ],
+ "name": "notifications_to_monitors_monitor_id_notification_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "monitor_status": {
+ "name": "monitor_status",
+ "columns": {
+ "monitor_id": {
+ "name": "monitor_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "region": {
+ "name": "region",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'active'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {
+ "monitor_status_idx": {
+ "name": "monitor_status_idx",
+ "columns": [
+ "monitor_id",
+ "region"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "monitor_status_monitor_id_monitor_id_fk": {
+ "name": "monitor_status_monitor_id_monitor_id_fk",
+ "tableFrom": "monitor_status",
+ "tableTo": "monitor",
+ "columnsFrom": [
+ "monitor_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "monitor_status_monitor_id_region_pk": {
+ "columns": [
+ "monitor_id",
+ "region"
+ ],
+ "name": "monitor_status_monitor_id_region_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "invitation": {
+ "name": "invitation",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'member'"
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "accepted_at": {
+ "name": "accepted_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "incident": {
+ "name": "incident",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "summary": {
+ "name": "summary",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'triage'"
+ },
+ "monitor_id": {
+ "name": "monitor_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "acknowledged_at": {
+ "name": "acknowledged_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "acknowledged_by": {
+ "name": "acknowledged_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "resolved_at": {
+ "name": "resolved_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "resolved_by": {
+ "name": "resolved_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "incident_screenshot_url": {
+ "name": "incident_screenshot_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "recovery_screenshot_url": {
+ "name": "recovery_screenshot_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "auto_resolved": {
+ "name": "auto_resolved",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {
+ "incident_monitor_id_started_at_unique": {
+ "name": "incident_monitor_id_started_at_unique",
+ "columns": [
+ "monitor_id",
+ "started_at"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "incident_monitor_id_monitor_id_fk": {
+ "name": "incident_monitor_id_monitor_id_fk",
+ "tableFrom": "incident",
+ "tableTo": "monitor",
+ "columnsFrom": [
+ "monitor_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set default",
+ "onUpdate": "no action"
+ },
+ "incident_workspace_id_workspace_id_fk": {
+ "name": "incident_workspace_id_workspace_id_fk",
+ "tableFrom": "incident",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "incident_acknowledged_by_user_id_fk": {
+ "name": "incident_acknowledged_by_user_id_fk",
+ "tableFrom": "incident",
+ "tableTo": "user",
+ "columnsFrom": [
+ "acknowledged_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "incident_resolved_by_user_id_fk": {
+ "name": "incident_resolved_by_user_id_fk",
+ "tableFrom": "incident",
+ "tableTo": "user",
+ "columnsFrom": [
+ "resolved_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "monitor_tag": {
+ "name": "monitor_tag",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "monitor_tag_workspace_id_workspace_id_fk": {
+ "name": "monitor_tag_workspace_id_workspace_id_fk",
+ "tableFrom": "monitor_tag",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "monitor_tag_to_monitor": {
+ "name": "monitor_tag_to_monitor",
+ "columns": {
+ "monitor_id": {
+ "name": "monitor_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "monitor_tag_id": {
+ "name": "monitor_tag_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "monitor_tag_to_monitor_monitor_id_monitor_id_fk": {
+ "name": "monitor_tag_to_monitor_monitor_id_monitor_id_fk",
+ "tableFrom": "monitor_tag_to_monitor",
+ "tableTo": "monitor",
+ "columnsFrom": [
+ "monitor_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "monitor_tag_to_monitor_monitor_tag_id_monitor_tag_id_fk": {
+ "name": "monitor_tag_to_monitor_monitor_tag_id_monitor_tag_id_fk",
+ "tableFrom": "monitor_tag_to_monitor",
+ "tableTo": "monitor_tag",
+ "columnsFrom": [
+ "monitor_tag_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "monitor_tag_to_monitor_monitor_id_monitor_tag_id_pk": {
+ "columns": [
+ "monitor_id",
+ "monitor_tag_id"
+ ],
+ "name": "monitor_tag_to_monitor_monitor_id_monitor_tag_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "application": {
+ "name": "application",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "dsn": {
+ "name": "dsn",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {
+ "application_dsn_unique": {
+ "name": "application_dsn_unique",
+ "columns": [
+ "dsn"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "application_workspace_id_workspace_id_fk": {
+ "name": "application_workspace_id_workspace_id_fk",
+ "tableFrom": "application",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "maintenance": {
+ "name": "maintenance",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text(256)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "message": {
+ "name": "message",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "from": {
+ "name": "from",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "to": {
+ "name": "to",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "page_id": {
+ "name": "page_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "maintenance_workspace_id_workspace_id_fk": {
+ "name": "maintenance_workspace_id_workspace_id_fk",
+ "tableFrom": "maintenance",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "maintenance_page_id_page_id_fk": {
+ "name": "maintenance_page_id_page_id_fk",
+ "tableFrom": "maintenance",
+ "tableTo": "page",
+ "columnsFrom": [
+ "page_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "maintenance_to_monitor": {
+ "name": "maintenance_to_monitor",
+ "columns": {
+ "maintenance_id": {
+ "name": "maintenance_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "monitor_id": {
+ "name": "monitor_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "maintenance_to_monitor_maintenance_id_maintenance_id_fk": {
+ "name": "maintenance_to_monitor_maintenance_id_maintenance_id_fk",
+ "tableFrom": "maintenance_to_monitor",
+ "tableTo": "maintenance",
+ "columnsFrom": [
+ "maintenance_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "maintenance_to_monitor_monitor_id_monitor_id_fk": {
+ "name": "maintenance_to_monitor_monitor_id_monitor_id_fk",
+ "tableFrom": "maintenance_to_monitor",
+ "tableTo": "monitor",
+ "columnsFrom": [
+ "monitor_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "maintenance_to_monitor_maintenance_id_monitor_id_pk": {
+ "columns": [
+ "maintenance_id",
+ "monitor_id"
+ ],
+ "name": "maintenance_to_monitor_maintenance_id_monitor_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "check": {
+ "name": "check",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "regions": {
+ "name": "regions",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "url": {
+ "name": "url",
+ "type": "text(4096)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "headers": {
+ "name": "headers",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "body": {
+ "name": "body",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "method": {
+ "name": "method",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "'GET'"
+ },
+ "count_requests": {
+ "name": "count_requests",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": 1
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "check_workspace_id_workspace_id_fk": {
+ "name": "check_workspace_id_workspace_id_fk",
+ "tableFrom": "check",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "monitor_run": {
+ "name": "monitor_run",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "monitor_id": {
+ "name": "monitor_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "runned_at": {
+ "name": "runned_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "monitor_run_workspace_id_workspace_id_fk": {
+ "name": "monitor_run_workspace_id_workspace_id_fk",
+ "tableFrom": "monitor_run",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "monitor_run_monitor_id_monitor_id_fk": {
+ "name": "monitor_run_monitor_id_monitor_id_fk",
+ "tableFrom": "monitor_run",
+ "tableTo": "monitor",
+ "columnsFrom": [
+ "monitor_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "private_location": {
+ "name": "private_location",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "last_seen_at": {
+ "name": "last_seen_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "private_location_workspace_id_workspace_id_fk": {
+ "name": "private_location_workspace_id_workspace_id_fk",
+ "tableFrom": "private_location",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "private_location_to_monitor": {
+ "name": "private_location_to_monitor",
+ "columns": {
+ "private_location_id": {
+ "name": "private_location_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "monitor_id": {
+ "name": "monitor_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "deleted_at": {
+ "name": "deleted_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "private_location_to_monitor_private_location_id_private_location_id_fk": {
+ "name": "private_location_to_monitor_private_location_id_private_location_id_fk",
+ "tableFrom": "private_location_to_monitor",
+ "tableTo": "private_location",
+ "columnsFrom": [
+ "private_location_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "private_location_to_monitor_monitor_id_monitor_id_fk": {
+ "name": "private_location_to_monitor_monitor_id_monitor_id_fk",
+ "tableFrom": "private_location_to_monitor",
+ "tableTo": "monitor",
+ "columnsFrom": [
+ "monitor_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "monitor_group": {
+ "name": "monitor_group",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "page_id": {
+ "name": "page_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "monitor_group_workspace_id_workspace_id_fk": {
+ "name": "monitor_group_workspace_id_workspace_id_fk",
+ "tableFrom": "monitor_group",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "monitor_group_page_id_page_id_fk": {
+ "name": "monitor_group_page_id_page_id_fk",
+ "tableFrom": "monitor_group",
+ "tableTo": "page",
+ "columnsFrom": [
+ "page_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "viewer": {
+ "name": "viewer",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "emailVerified": {
+ "name": "emailVerified",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "image": {
+ "name": "image",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {
+ "viewer_email_unique": {
+ "name": "viewer_email_unique",
+ "columns": [
+ "email"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "viewer_accounts": {
+ "name": "viewer_accounts",
+ "columns": {
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "providerAccountId": {
+ "name": "providerAccountId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "refresh_token": {
+ "name": "refresh_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "access_token": {
+ "name": "access_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "token_type": {
+ "name": "token_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "id_token": {
+ "name": "id_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "session_state": {
+ "name": "session_state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "viewer_accounts_user_id_viewer_id_fk": {
+ "name": "viewer_accounts_user_id_viewer_id_fk",
+ "tableFrom": "viewer_accounts",
+ "tableTo": "viewer",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "viewer_accounts_provider_providerAccountId_pk": {
+ "columns": [
+ "provider",
+ "providerAccountId"
+ ],
+ "name": "viewer_accounts_provider_providerAccountId_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "viewer_session": {
+ "name": "viewer_session",
+ "columns": {
+ "session_token": {
+ "name": "session_token",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires": {
+ "name": "expires",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "viewer_session_user_id_viewer_id_fk": {
+ "name": "viewer_session_user_id_viewer_id_fk",
+ "tableFrom": "viewer_session",
+ "tableTo": "viewer",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "api_key": {
+ "name": "api_key",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "prefix": {
+ "name": "prefix",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "hashed_token": {
+ "name": "hashed_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_by_id": {
+ "name": "created_by_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_used_at": {
+ "name": "last_used_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "api_key_prefix_unique": {
+ "name": "api_key_prefix_unique",
+ "columns": [
+ "prefix"
+ ],
+ "isUnique": true
+ },
+ "api_key_hashed_token_unique": {
+ "name": "api_key_hashed_token_unique",
+ "columns": [
+ "hashed_token"
+ ],
+ "isUnique": true
+ },
+ "api_key_prefix_idx": {
+ "name": "api_key_prefix_idx",
+ "columns": [
+ "prefix"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "api_key_workspace_id_workspace_id_fk": {
+ "name": "api_key_workspace_id_workspace_id_fk",
+ "tableFrom": "api_key",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "api_key_created_by_id_user_id_fk": {
+ "name": "api_key_created_by_id_user_id_fk",
+ "tableFrom": "api_key",
+ "tableTo": "user",
+ "columnsFrom": [
+ "created_by_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "maintenance_to_page_component": {
+ "name": "maintenance_to_page_component",
+ "columns": {
+ "maintenance_id": {
+ "name": "maintenance_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "page_component_id": {
+ "name": "page_component_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "maintenance_to_page_component_maintenance_id_maintenance_id_fk": {
+ "name": "maintenance_to_page_component_maintenance_id_maintenance_id_fk",
+ "tableFrom": "maintenance_to_page_component",
+ "tableTo": "maintenance",
+ "columnsFrom": [
+ "maintenance_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "maintenance_to_page_component_page_component_id_page_component_id_fk": {
+ "name": "maintenance_to_page_component_page_component_id_page_component_id_fk",
+ "tableFrom": "maintenance_to_page_component",
+ "tableTo": "page_component",
+ "columnsFrom": [
+ "page_component_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "maintenance_to_page_component_maintenance_id_page_component_id_pk": {
+ "columns": [
+ "maintenance_id",
+ "page_component_id"
+ ],
+ "name": "maintenance_to_page_component_maintenance_id_page_component_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "page_component": {
+ "name": "page_component",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "page_id": {
+ "name": "page_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'monitor'"
+ },
+ "monitor_id": {
+ "name": "monitor_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "order": {
+ "name": "order",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": 0
+ },
+ "group_id": {
+ "name": "group_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "group_order": {
+ "name": "group_order",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": 0
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {
+ "page_component_page_id_monitor_id_unique": {
+ "name": "page_component_page_id_monitor_id_unique",
+ "columns": [
+ "page_id",
+ "monitor_id"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "page_component_workspace_id_workspace_id_fk": {
+ "name": "page_component_workspace_id_workspace_id_fk",
+ "tableFrom": "page_component",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "page_component_page_id_page_id_fk": {
+ "name": "page_component_page_id_page_id_fk",
+ "tableFrom": "page_component",
+ "tableTo": "page",
+ "columnsFrom": [
+ "page_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "page_component_monitor_id_monitor_id_fk": {
+ "name": "page_component_monitor_id_monitor_id_fk",
+ "tableFrom": "page_component",
+ "tableTo": "monitor",
+ "columnsFrom": [
+ "monitor_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "page_component_group_id_page_component_groups_id_fk": {
+ "name": "page_component_group_id_page_component_groups_id_fk",
+ "tableFrom": "page_component",
+ "tableTo": "page_component_groups",
+ "columnsFrom": [
+ "group_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {
+ "page_component_type_check": {
+ "name": "page_component_type_check",
+ "value": "\"page_component\".\"type\" = 'monitor' AND \"page_component\".\"monitor_id\" IS NOT NULL OR \"page_component\".\"type\" = 'static' AND \"page_component\".\"monitor_id\" IS NULL"
+ }
+ }
+ },
+ "status_report_to_page_component": {
+ "name": "status_report_to_page_component",
+ "columns": {
+ "status_report_id": {
+ "name": "status_report_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "page_component_id": {
+ "name": "page_component_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "status_report_to_page_component_status_report_id_status_report_id_fk": {
+ "name": "status_report_to_page_component_status_report_id_status_report_id_fk",
+ "tableFrom": "status_report_to_page_component",
+ "tableTo": "status_report",
+ "columnsFrom": [
+ "status_report_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "status_report_to_page_component_page_component_id_page_component_id_fk": {
+ "name": "status_report_to_page_component_page_component_id_page_component_id_fk",
+ "tableFrom": "status_report_to_page_component",
+ "tableTo": "page_component",
+ "columnsFrom": [
+ "page_component_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "status_report_to_page_component_status_report_id_page_component_id_pk": {
+ "columns": [
+ "status_report_id",
+ "page_component_id"
+ ],
+ "name": "status_report_to_page_component_status_report_id_page_component_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "page_component_groups": {
+ "name": "page_component_groups",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "page_id": {
+ "name": "page_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "page_component_groups_workspace_id_workspace_id_fk": {
+ "name": "page_component_groups_workspace_id_workspace_id_fk",
+ "tableFrom": "page_component_groups",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "page_component_groups_page_id_page_id_fk": {
+ "name": "page_component_groups_page_id_page_id_fk",
+ "tableFrom": "page_component_groups",
+ "tableTo": "page",
+ "columnsFrom": [
+ "page_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ }
+ },
+ "views": {},
+ "enums": {},
+ "_meta": {
+ "schemas": {},
+ "tables": {},
+ "columns": {}
+ },
+ "internal": {
+ "indexes": {
+ "idx_page_subscriber_email_page_active": {
+ "columns": {
+ "LOWER(\"email\")": {
+ "isExpression": true
+ }
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/packages/db/drizzle/meta/_journal.json b/packages/db/drizzle/meta/_journal.json
index 7a7bb2637..7b6617639 100644
--- a/packages/db/drizzle/meta/_journal.json
+++ b/packages/db/drizzle/meta/_journal.json
@@ -393,6 +393,13 @@
"when": 1769675142003,
"tag": "0055_spicy_bastion",
"breakpoints": true
+ },
+ {
+ "idx": 56,
+ "version": "6",
+ "when": 1772280814493,
+ "tag": "0056_violet_shotgun",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/packages/db/src/schema/page_subscribers/index.ts b/packages/db/src/schema/page_subscribers/index.ts
index 46f6a2182..c6bb1a418 100644
--- a/packages/db/src/schema/page_subscribers/index.ts
+++ b/packages/db/src/schema/page_subscribers/index.ts
@@ -1,3 +1,4 @@
export * from "./page_subscribers";
+export * from "./page_subscriber_to_page_component";
export * from "./validation";
export type * from "./validation";
diff --git a/packages/db/src/schema/page_subscribers/page_subscriber_to_page_component.ts b/packages/db/src/schema/page_subscribers/page_subscriber_to_page_component.ts
new file mode 100644
index 000000000..2e520df49
--- /dev/null
+++ b/packages/db/src/schema/page_subscribers/page_subscriber_to_page_component.ts
@@ -0,0 +1,37 @@
+import { relations, sql } from "drizzle-orm";
+import { integer, primaryKey, sqliteTable } from "drizzle-orm/sqlite-core";
+
+import { pageComponent } from "../page_components";
+import { pageSubscriber } from "./page_subscribers";
+
+export const pageSubscriberToPageComponent = sqliteTable(
+ "page_subscriber_to_page_component",
+ {
+ pageSubscriberId: integer("page_subscriber_id")
+ .notNull()
+ .references(() => pageSubscriber.id, { onDelete: "cascade" }),
+ pageComponentId: integer("page_component_id")
+ .notNull()
+ .references(() => pageComponent.id, { onDelete: "cascade" }),
+ createdAt: integer("created_at", { mode: "timestamp" }).default(
+ sql`(strftime('%s', 'now'))`,
+ ),
+ },
+ (t) => ({
+ pk: primaryKey({ columns: [t.pageSubscriberId, t.pageComponentId] }),
+ }),
+);
+
+export const pageSubscriberToPageComponentRelations = relations(
+ pageSubscriberToPageComponent,
+ ({ one }) => ({
+ pageSubscriber: one(pageSubscriber, {
+ fields: [pageSubscriberToPageComponent.pageSubscriberId],
+ references: [pageSubscriber.id],
+ }),
+ pageComponent: one(pageComponent, {
+ fields: [pageSubscriberToPageComponent.pageComponentId],
+ references: [pageComponent.id],
+ }),
+ }),
+);
diff --git a/packages/db/src/schema/page_subscribers/page_subscribers.ts b/packages/db/src/schema/page_subscribers/page_subscribers.ts
index d6c8ff2a8..dd5ebb3c8 100644
--- a/packages/db/src/schema/page_subscribers/page_subscribers.ts
+++ b/packages/db/src/schema/page_subscribers/page_subscribers.ts
@@ -1,31 +1,77 @@
import { relations, sql } from "drizzle-orm";
-import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core";
+import {
+ check,
+ integer,
+ sqliteTable,
+ text,
+ uniqueIndex,
+} from "drizzle-orm/sqlite-core";
import { page } from "../pages";
+import { pageSubscriberToPageComponent } from "./page_subscriber_to_page_component";
-export const pageSubscriber = sqliteTable("page_subscriber", {
- id: integer("id").primaryKey(),
- email: text("email").notNull(),
-
- pageId: integer("page_id")
- .notNull()
- .references(() => page.id, { onDelete: "cascade" }),
-
- token: text("token"),
- acceptedAt: integer("accepted_at", { mode: "timestamp" }),
- expiresAt: integer("expires_at", { mode: "timestamp" }),
- unsubscribedAt: integer("unsubscribed_at", { mode: "timestamp" }),
- createdAt: integer("created_at", { mode: "timestamp" }).default(
- sql`(strftime('%s', 'now'))`,
- ),
- updatedAt: integer("updated_at", { mode: "timestamp" }).default(
- sql`(strftime('%s', 'now'))`,
- ),
-});
-
-export const pageSubscriberRelation = relations(pageSubscriber, ({ one }) => ({
- page: one(page, {
- fields: [pageSubscriber.pageId],
- references: [page.id],
+export const pageSubscriber = sqliteTable(
+ "page_subscriber",
+ {
+ id: integer("id").primaryKey(),
+ email: text("email").notNull(),
+
+ pageId: integer("page_id")
+ .notNull()
+ .references(() => page.id, { onDelete: "cascade" }),
+
+ // Added: channel type discriminator
+ channelType: text("channel_type", {
+ enum: ["email", "webhook"],
+ })
+ .notNull()
+ .default("email"),
+
+ // Added: webhook-specific fields (null for email channel)
+ webhookUrl: text("webhook_url"),
+ channelConfig: text("channel_config"),
+
+ token: text("token"),
+ acceptedAt: integer("accepted_at", { mode: "timestamp" }),
+ expiresAt: integer("expires_at", { mode: "timestamp" }),
+ unsubscribedAt: integer("unsubscribed_at", { mode: "timestamp" }),
+ createdAt: integer("created_at", { mode: "timestamp" }).default(
+ sql`(strftime('%s', 'now'))`,
+ ),
+ updatedAt: integer("updated_at", { mode: "timestamp" }).default(
+ sql`(strftime('%s', 'now'))`,
+ ),
+ },
+ (table) => ({
+ // Partial unique index: one active email subscription per page
+ emailPageActiveIdx: uniqueIndex("idx_page_subscriber_email_page_active")
+ .on(sql`LOWER(${table.email})`, table.pageId)
+ .where(
+ sql`${table.unsubscribedAt} IS NULL AND ${table.channelType} = 'email'`,
+ ),
+
+ // Partial unique index: one active webhook subscription per page
+ webhookPageActiveIdx: uniqueIndex("idx_page_subscriber_webhook_page_active")
+ .on(table.webhookUrl, table.pageId)
+ .where(
+ sql`${table.unsubscribedAt} IS NULL AND ${table.channelType} = 'webhook'`,
+ ),
+
+ // CHECK constraint: only correct identifier populated per channel type
+ channelCheck: check(
+ "page_subscriber_channel_check",
+ sql`(${table.channelType} = 'email' AND ${table.email} IS NOT NULL AND ${table.webhookUrl} IS NULL) OR (${table.channelType} = 'webhook' AND ${table.webhookUrl} IS NOT NULL AND ${table.email} IS NULL)`,
+ ),
+ }),
+);
+
+export const pageSubscriberRelation = relations(
+ pageSubscriber,
+ ({ one, many }) => ({
+ page: one(page, {
+ fields: [pageSubscriber.pageId],
+ references: [page.id],
+ }),
+ components: many(pageSubscriberToPageComponent),
}),
-}));
+);
diff --git a/packages/db/src/schema/page_subscribers/validation.ts b/packages/db/src/schema/page_subscribers/validation.ts
index d1052757f..ce2420f77 100644
--- a/packages/db/src/schema/page_subscribers/validation.ts
+++ b/packages/db/src/schema/page_subscribers/validation.ts
@@ -3,11 +3,78 @@ import { z } from "zod";
import { pageSubscriber } from "./page_subscribers";
+// Base schemas (auto-generated from Drizzle schema)
+export const selectPageSubscriberSchema = createSelectSchema(pageSubscriber);
export const insertPageSubscriberSchema = createInsertSchema(pageSubscriber, {
- email: z.email(),
+ email: z.email().nullable(),
});
-export const selectPageSubscriberSchema = createSelectSchema(pageSubscriber);
+// Channel config schema for webhook
+export const webhookChannelConfigSchema = z.object({
+ headers: z
+ .array(
+ z.object({
+ key: z.string().min(1),
+ value: z.string(),
+ }),
+ )
+ .optional(),
+ secret: z.string().optional(),
+});
+
+// Discriminated union for type-safe subscribers
+export const pageSubscriberSchema = z.discriminatedUnion("channelType", [
+ // Email channel
+ z.object({
+ id: z.number(),
+ pageId: z.number(),
+ channelType: z.literal("email"),
+ email: z.email(),
+ webhookUrl: z.null(),
+ channelConfig: z.null(),
+ token: z.string().nullable(),
+ acceptedAt: z.date().nullable(),
+ expiresAt: z.date().nullable(),
+ unsubscribedAt: z.date().nullable(),
+ createdAt: z.date().nullable(),
+ updatedAt: z.date().nullable(),
+ }),
+ // Webhook channel
+ z.object({
+ id: z.number(),
+ pageId: z.number(),
+ channelType: z.literal("webhook"),
+ email: z.null(),
+ webhookUrl: z.string().url(),
+ channelConfig: z
+ .string()
+ .nullable()
+ .transform((str) => {
+ if (!str) return null;
+ try {
+ return JSON.parse(str);
+ } catch {
+ return null;
+ }
+ })
+ .pipe(webhookChannelConfigSchema.nullable()),
+ token: z.string().nullable(),
+ acceptedAt: z.date().nullable(),
+ expiresAt: z.date().nullable(),
+ unsubscribedAt: z.date().nullable(),
+ createdAt: z.date().nullable(),
+ updatedAt: z.date().nullable(),
+ }),
+]);
export type InsertPageSubscriber = z.infer<typeof insertPageSubscriberSchema>;
export type PageSubscriber = z.infer<typeof selectPageSubscriberSchema>;
+export type ChannelType = "email" | "webhook";
+export type EmailSubscriber = Extract<
+ z.infer<typeof pageSubscriberSchema>,
+ { channelType: "email" }
+>;
+export type WebhookSubscriber = Extract<
+ z.infer<typeof pageSubscriberSchema>,
+ { channelType: "webhook" }
+>;
diff --git a/packages/emails/emails/status-report.tsx b/packages/emails/emails/status-report.tsx
index a02d158af..aeea46045 100644
--- a/packages/emails/emails/status-report.tsx
+++ b/packages/emails/emails/status-report.tsx
@@ -31,7 +31,8 @@ export const StatusReportSchema = z.object({
message: z.string(),
reportTitle: z.string(),
pageComponents: z.array(z.string()),
- unsubscribeUrl: z.string().url().optional(),
+ unsubscribeUrl: z.url(),
+ manageUrl: z.url(),
});
export type StatusReportProps = z.infer<typeof StatusReportSchema>;
@@ -61,6 +62,7 @@ function StatusReportEmail({
pageTitle,
pageComponents,
unsubscribeUrl,
+ manageUrl,
}: StatusReportProps) {
return (
<Html>
@@ -123,7 +125,13 @@ function StatusReportEmail({
>
Unsubscribe
</Link>{" "}
- from these notifications.
+ ・{" "}
+ <Link
+ href={manageUrl}
+ style={{ color: "#6b7280", textDecoration: "underline" }}
+ >
+ Manage notifications
+ </Link>
</Text>
</Section>
)}
@@ -163,6 +171,8 @@ We'll post another update by **19:00 UTC** today or sooner if critical developme
pageComponents: ["OpenStatus API", "OpenStatus Webhook"],
unsubscribeUrl:
"https://status.openstatus.dev/unsubscribe/550e8400-e29b-41d4-a716-446655440000",
+ manageUrl:
+ "https://status.openstatus.dev/manage/550e8400-e29b-41d4-a716-446655440000",
};
export default StatusReportEmail;
diff --git a/packages/emails/package.json b/packages/emails/package.json
index 039cccab9..d3d80e2a8 100644
--- a/packages/emails/package.json
+++ b/packages/emails/package.json
@@ -4,7 +4,8 @@
"description": "",
"main": "./src/index.ts",
"scripts": {
- "dev:email": "email dev"
+ "dev:email": "email dev",
+ "test": "bun test"
},
"keywords": [],
"author": "",
diff --git a/packages/emails/src/client.integration.test.tsx b/packages/emails/src/client.integration.test.tsx
index 3e5517ee9..20a8ebef5 100644
--- a/packages/emails/src/client.integration.test.tsx
+++ b/packages/emails/src/client.integration.test.tsx
@@ -7,6 +7,7 @@ import StatusReportEmail from "../emails/status-report";
describe("Status Report Email - Unsubscribe Link in Body", () => {
const unsubscribeUrl =
"https://openstatus.openstatus.dev/unsubscribe/test-token";
+ const manageUrl = "https://openstatus.openstatus.dev/manage/test-token";
test("should include unsubscribe link in email body when URL is provided", async () => {
const html = await render(
@@ -16,8 +17,9 @@ describe("Status Report Email - Unsubscribe Link in Body", () => {
status="investigating"
date={new Date().toISOString()}
message="Test message"
- monitors={["Monitor 1"]}
+ pageComponents={["Monitor 1"]}
unsubscribeUrl={unsubscribeUrl}
+ manageUrl={manageUrl}
/>,
);
@@ -33,7 +35,8 @@ describe("Status Report Email - Unsubscribe Link in Body", () => {
status="investigating"
date={new Date().toISOString()}
message="Test message"
- monitors={["Monitor 1"]}
+ pageComponents={["Monitor 1"]}
+ manageUrl={manageUrl}
/>,
);
@@ -49,8 +52,9 @@ describe("Status Report Email - Unsubscribe Link in Body", () => {
status="investigating"
date={new Date().toISOString()}
message="Test message"
- monitors={["Monitor 1"]}
+ pageComponents={["Monitor 1"]}
unsubscribeUrl={unsubscribeUrl}
+ manageUrl={manageUrl}
/>,
);
@@ -66,8 +70,9 @@ describe("Status Report Email - Unsubscribe Link in Body", () => {
status="investigating"
date={new Date().toISOString()}
message="Test message"
- monitors={["Monitor 1"]}
+ pageComponents={["Monitor 1"]}
unsubscribeUrl={unsubscribeUrl}
+ manageUrl={manageUrl}
/>,
);
@@ -84,8 +89,9 @@ describe("Status Report Email - Email Content Validation", () => {
status: "investigating" as const,
date: "2024-01-15T10:00:00.000Z",
message: "We are investigating the issue",
- monitors: ["API", "Web"],
+ pageComponents: ["API", "Web"],
unsubscribeUrl: "https://openstatus.openstatus.dev/unsubscribe/test",
+ manageUrl: "https://openstatus.openstatus.dev/manage/test",
};
const html = await render(<StatusReportEmail {...props} />);
@@ -115,8 +121,9 @@ describe("Status Report Email - Email Content Validation", () => {
status={status}
date={new Date().toISOString()}
message="Test"
- monitors={[]}
+ pageComponents={[]}
unsubscribeUrl="https://example.com/unsubscribe"
+ manageUrl="https://example.com/manage"
/>,
);
diff --git a/packages/emails/src/client.tsx b/packages/emails/src/client.tsx
index aa3e01b77..c2d2dea50 100644
--- a/packages/emails/src/client.tsx
+++ b/packages/emails/src/client.tsx
@@ -90,7 +90,7 @@ export class EmailClient {
}
public async sendStatusReportUpdate(
- req: StatusReportProps & {
+ req: Omit<StatusReportProps, "unsubscribeUrl" | "manageUrl"> & {
subscribers: Array<{ email: string; token: string }>;
pageSlug: string;
customDomain?: string | null;
@@ -115,12 +115,17 @@ export class EmailClient {
this.client.batch.send(
recipients.map((subscriber) => {
const unsubscribeUrl = `${statusPageBaseUrl}/unsubscribe/${subscriber.token}`;
+ const manageUrl = `${statusPageBaseUrl}/manage/${subscriber.token}`;
return {
from: `${req.pageTitle} <[email protected]>`,
subject: req.reportTitle,
to: subscriber.email,
react: (
- <StatusReportEmail {...req} unsubscribeUrl={unsubscribeUrl} />
+ <StatusReportEmail
+ {...req}
+ unsubscribeUrl={unsubscribeUrl}
+ manageUrl={manageUrl}
+ />
),
};
}),
@@ -293,6 +298,7 @@ export class EmailClient {
this.client.batch.send(
recipients.map((subscriber) => {
const unsubscribeUrl = `${statusPageBaseUrl}/unsubscribe/${subscriber.token}`;
+ const manageUrl = `${statusPageBaseUrl}/manage/${subscriber.token}`;
return {
from: `${req.pageTitle} <[email protected]>`,
subject: `Scheduled Maintenance: ${req.maintenanceTitle}`,
@@ -306,6 +312,7 @@ export class EmailClient {
message={req.message}
pageComponents={req.pageComponents}
unsubscribeUrl={unsubscribeUrl}
+ manageUrl={manageUrl}
/>
),
};
diff --git a/packages/subscriptions/bunfig.toml b/packages/subscriptions/bunfig.toml
new file mode 100644
index 000000000..0a8c0cafd
--- /dev/null
+++ b/packages/subscriptions/bunfig.toml
@@ -0,0 +1,2 @@
+[test]
+preload = ["./src/test-preload.ts"]
diff --git a/packages/subscriptions/package.json b/packages/subscriptions/package.json
new file mode 100644
index 000000000..86b00b051
--- /dev/null
+++ b/packages/subscriptions/package.json
@@ -0,0 +1,26 @@
+{
+ "name": "@openstatus/subscriptions",
+ "version": "0.0.0",
+ "type": "module",
+ "main": "./src/index.ts",
+ "types": "./src/index.ts",
+ "exports": {
+ ".": {
+ "import": "./src/index.ts",
+ "types": "./src/index.ts"
+ }
+ },
+ "scripts": {
+ "test": "bun test"
+ },
+ "dependencies": {
+ "@openstatus/db": "workspace:*",
+ "@openstatus/emails": "workspace:*",
+ "zod": "4.1.13"
+ },
+ "devDependencies": {
+ "@openstatus/tsconfig": "workspace:*",
+ "@types/bun": "latest",
+ "typescript": "5.9.3"
+ }
+}
diff --git a/packages/subscriptions/src/channels/email.test.ts b/packages/subscriptions/src/channels/email.test.ts
new file mode 100644
index 000000000..dbde2a4d0
--- /dev/null
+++ b/packages/subscriptions/src/channels/email.test.ts
@@ -0,0 +1,142 @@
+import { beforeEach, describe, expect, spyOn, test } from "bun:test";
+import { EmailClient } from "@openstatus/emails";
+import type { PageUpdate, Subscription } from "../types";
+import {
+ sendEmailNotifications,
+ sendEmailVerification,
+ validateEmailConfig,
+} from "./email";
+
+// RESEND_API_KEY is set in test-preload.ts (see bunfig.toml) so @openstatus/emails
+// loads successfully and EmailClient prototype methods can be spied on.
+
+const sendPageSubscriptionMock = spyOn(
+ EmailClient.prototype,
+ "sendPageSubscription",
+).mockResolvedValue(undefined);
+
+const sendStatusReportUpdateMock = spyOn(
+ EmailClient.prototype,
+ "sendStatusReportUpdate",
+).mockResolvedValue(undefined);
+
+function makeSub(overrides: Partial<Subscription> = {}): Subscription {
+ return {
+ id: 1,
+ pageId: 1,
+ pageName: "Test Page",
+ pageSlug: "test",
+ channelType: "email",
+ email: "[email protected]",
+ token: "token-123",
+ componentIds: [],
+ ...overrides,
+ };
+}
+
+function makeUpdate(overrides: Partial<PageUpdate> = {}): PageUpdate {
+ return {
+ id: 1,
+ pageId: 1,
+ title: "Test Incident",
+ status: "investigating",
+ message: "We are investigating.",
+ pageComponentIds: [],
+ pageComponents: [],
+ date: new Date().toISOString(),
+ ...overrides,
+ };
+}
+
+beforeEach(() => {
+ sendPageSubscriptionMock.mockClear();
+ sendStatusReportUpdateMock.mockClear();
+});
+
+// ─── validateEmailConfig ──────────────────────────────────────────────────────
+
+describe("validateEmailConfig", () => {
+ test("returns valid for a valid email address", async () => {
+ const result = await validateEmailConfig("[email protected]");
+ expect(result.valid).toBe(true);
+ });
+
+ test("returns invalid for a plain string without @", async () => {
+ const result = await validateEmailConfig("not-an-email");
+ expect(result.valid).toBe(false);
+ expect(result.error).toBeDefined();
+ });
+
+ test("returns invalid for non-string input", async () => {
+ const result = await validateEmailConfig(42);
+ expect(result.valid).toBe(false);
+ });
+
+ test("returns invalid for null", async () => {
+ const result = await validateEmailConfig(null);
+ expect(result.valid).toBe(false);
+ });
+});
+
+// ─── sendEmailVerification ────────────────────────────────────────────────────
+
+describe("sendEmailVerification", () => {
+ test("throws when subscription has no email", async () => {
+ const sub = makeSub({ email: undefined });
+ await expect(
+ sendEmailVerification(sub, "https://example.com/verify/token"),
+ ).rejects.toThrow("Email is required");
+ });
+
+ test("calls sendPageSubscription with the correct arguments", async () => {
+ const sub = makeSub({ email: "[email protected]", pageName: "My Page" });
+ await sendEmailVerification(sub, "https://example.com/verify/abc");
+
+ expect(sendPageSubscriptionMock).toHaveBeenCalledTimes(1);
+ const [args] = sendPageSubscriptionMock.mock.calls[0];
+ expect(args.to).toBe("[email protected]");
+ expect(args.link).toBe("https://example.com/verify/abc");
+ expect(args.page).toBe("My Page");
+ });
+});
+
+// ─── sendEmailNotifications ───────────────────────────────────────────────────
+
+describe("sendEmailNotifications", () => {
+ test("does nothing for an empty subscriptions array", async () => {
+ await sendEmailNotifications([], makeUpdate());
+ expect(sendStatusReportUpdateMock).not.toHaveBeenCalled();
+ });
+
+ test("filters out subscriptions without an email address", async () => {
+ const sub = makeSub({ email: undefined });
+ await sendEmailNotifications([sub], makeUpdate());
+ expect(sendStatusReportUpdateMock).not.toHaveBeenCalled();
+ });
+
+ test("calls sendStatusReportUpdate once with all valid subscribers", async () => {
+ const sub1 = makeSub({ email: "[email protected]", token: "token-a" });
+ const sub2 = makeSub({ email: "[email protected]", token: "token-b" });
+ const update = makeUpdate({ title: "Outage", status: "resolved" });
+
+ await sendEmailNotifications([sub1, sub2], update);
+
+ expect(sendStatusReportUpdateMock).toHaveBeenCalledTimes(1);
+ const [args] = sendStatusReportUpdateMock.mock.calls[0];
+ expect(args.subscribers).toHaveLength(2);
+ expect(args.subscribers[0].email).toBe("[email protected]");
+ expect(args.subscribers[1].email).toBe("[email protected]");
+ expect(args.reportTitle).toBe("Outage");
+ expect(args.status).toBe("resolved");
+ });
+
+ test("passes page components to sendStatusReportUpdate", async () => {
+ const sub = makeSub({ email: "[email protected]" });
+ const update = makeUpdate({ pageComponents: ["API", "Database"] });
+
+ await sendEmailNotifications([sub], update);
+
+ const [args] = sendStatusReportUpdateMock.mock.calls[0];
+ expect(args.pageComponents).toEqual(["API", "Database"]);
+ });
+});
diff --git a/packages/subscriptions/src/channels/email.ts b/packages/subscriptions/src/channels/email.ts
new file mode 100644
index 000000000..925119f0e
--- /dev/null
+++ b/packages/subscriptions/src/channels/email.ts
@@ -0,0 +1,79 @@
+import { EmailClient } from "@openstatus/emails";
+import { z } from "zod";
+import type { PageUpdate, Subscription } from "../types";
+
+let emailClient: EmailClient | null = null;
+
+function getEmailClient(): EmailClient {
+ if (!emailClient) {
+ if (!process.env.RESEND_API_KEY) {
+ throw new Error(
+ "RESEND_API_KEY environment variable is required for email notifications",
+ );
+ }
+ emailClient = new EmailClient({
+ apiKey: process.env.RESEND_API_KEY,
+ });
+ }
+ return emailClient;
+}
+
+export async function validateEmailConfig(config: unknown) {
+ const email = z.email().safeParse(config);
+ return { valid: email.success, error: email.error?.message };
+}
+
+function hasEmailAndToken(
+ sub: Subscription,
+): sub is Subscription & { email: string; token: string } {
+ return (
+ sub.email !== undefined &&
+ sub.email !== null &&
+ sub.token !== undefined &&
+ sub.token !== null
+ );
+}
+
+export async function sendEmailVerification(
+ subscription: Subscription,
+ verifyUrl: string,
+) {
+ if (!subscription.email) {
+ throw new Error("Email is required for email channel");
+ }
+
+ const client = getEmailClient();
+ await client.sendPageSubscription({
+ to: subscription.email,
+ link: verifyUrl,
+ page: subscription.pageName,
+ });
+}
+
+export async function sendEmailNotifications(
+ subscriptions: Subscription[],
+ pageUpdate: PageUpdate,
+) {
+ if (subscriptions.length === 0) return;
+
+ const validSubscriptions = subscriptions.filter(hasEmailAndToken);
+ if (validSubscriptions.length === 0) return;
+
+ const firstSub = validSubscriptions[0];
+
+ const client = getEmailClient();
+ await client.sendStatusReportUpdate({
+ subscribers: validSubscriptions.map((sub) => ({
+ email: sub.email,
+ token: sub.token,
+ })),
+ pageTitle: firstSub.pageName,
+ pageSlug: firstSub.pageSlug,
+ customDomain: firstSub.customDomain,
+ reportTitle: pageUpdate.title,
+ status: pageUpdate.status,
+ message: pageUpdate.message,
+ date: pageUpdate.date,
+ pageComponents: pageUpdate.pageComponents,
+ });
+}
diff --git a/packages/subscriptions/src/channels/index.test.ts b/packages/subscriptions/src/channels/index.test.ts
new file mode 100644
index 000000000..342165968
--- /dev/null
+++ b/packages/subscriptions/src/channels/index.test.ts
@@ -0,0 +1,28 @@
+import { describe, expect, test } from "bun:test";
+import { getChannel } from "./index";
+
+describe("getChannel", () => {
+ test('returns email channel for "email"', () => {
+ const channel = getChannel("email");
+ expect(channel).not.toBeNull();
+ expect(channel?.id).toBe("email");
+ expect(typeof channel?.sendNotifications).toBe("function");
+ expect(typeof channel?.sendVerification).toBe("function");
+ expect(typeof channel?.validateConfig).toBe("function");
+ });
+
+ test('returns webhook channel for "webhook"', () => {
+ const channel = getChannel("webhook");
+ expect(channel).not.toBeNull();
+ expect(channel?.id).toBe("webhook");
+ expect(typeof channel?.sendNotifications).toBe("function");
+ expect(typeof channel?.sendVerification).toBe("function");
+ expect(typeof channel?.validateConfig).toBe("function");
+ });
+
+ test("returns null for unknown channel types", () => {
+ expect(getChannel("sms")).toBeNull();
+ expect(getChannel("slack")).toBeNull();
+ expect(getChannel("")).toBeNull();
+ });
+});
diff --git a/packages/subscriptions/src/channels/index.ts b/packages/subscriptions/src/channels/index.ts
new file mode 100644
index 000000000..5bdccda68
--- /dev/null
+++ b/packages/subscriptions/src/channels/index.ts
@@ -0,0 +1,34 @@
+import type { SubscriptionChannel } from "../types";
+import {
+ sendEmailNotifications,
+ sendEmailVerification,
+ validateEmailConfig,
+} from "./email";
+import {
+ sendWebhookNotifications,
+ sendWebhookVerification,
+ validateWebhookConfig,
+} from "./webhook";
+
+export function getChannel(channelType: string): SubscriptionChannel | null {
+ switch (channelType) {
+ case "email": {
+ return {
+ id: "email",
+ sendNotifications: sendEmailNotifications,
+ sendVerification: sendEmailVerification,
+ validateConfig: validateEmailConfig,
+ };
+ }
+ case "webhook": {
+ return {
+ id: "webhook",
+ sendNotifications: sendWebhookNotifications,
+ sendVerification: sendWebhookVerification,
+ validateConfig: validateWebhookConfig,
+ };
+ }
+ default:
+ return null;
+ }
+}
diff --git a/packages/subscriptions/src/channels/webhook.test.ts b/packages/subscriptions/src/channels/webhook.test.ts
new file mode 100644
index 000000000..4d96558e3
--- /dev/null
+++ b/packages/subscriptions/src/channels/webhook.test.ts
@@ -0,0 +1,202 @@
+import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test";
+import type { PageUpdate, Subscription } from "../types";
+import {
+ sendWebhookNotifications,
+ sendWebhookVerification,
+ validateWebhookConfig,
+} from "./webhook";
+
+// biome-ignore lint/suspicious/noExplicitAny: test spy
+let fetchMock: any;
+
+function makeSub(overrides: Partial<Subscription> = {}): Subscription {
+ return {
+ id: 1,
+ pageId: 1,
+ pageName: "Test Page",
+ pageSlug: "test",
+ channelType: "webhook",
+ webhookUrl: "https://example.com/webhook",
+ token: "token-123",
+ componentIds: [],
+ ...overrides,
+ };
+}
+
+function makeUpdate(overrides: Partial<PageUpdate> = {}): PageUpdate {
+ return {
+ id: 1,
+ pageId: 1,
+ title: "Test Incident",
+ status: "investigating",
+ message: "We are investigating.",
+ pageComponentIds: [],
+ pageComponents: ["API", "Database"],
+ date: new Date().toISOString(),
+ ...overrides,
+ };
+}
+
+beforeEach(() => {
+ fetchMock = spyOn(global, "fetch");
+});
+
+afterEach(() => {
+ fetchMock.mockRestore();
+});
+
+// ─── validateWebhookConfig ────────────────────────────────────────────────────
+
+describe("validateWebhookConfig", () => {
+ test("returns valid for an empty config", async () => {
+ const result = await validateWebhookConfig({});
+ expect(result.valid).toBe(true);
+ });
+
+ test("returns valid with optional headers and secret", async () => {
+ const result = await validateWebhookConfig({
+ headers: [{ key: "Authorization", value: "Bearer token" }],
+ secret: "my-secret",
+ });
+ expect(result.valid).toBe(true);
+ });
+
+ test("returns invalid when a header is missing a key", async () => {
+ const result = await validateWebhookConfig({
+ headers: [{ key: "", value: "v" }], // key must be min length 1
+ });
+ expect(result.valid).toBe(false);
+ });
+
+ test("returns invalid for a non-object value", async () => {
+ const result = await validateWebhookConfig("not-an-object");
+ expect(result.valid).toBe(false);
+ expect(result.error).toBeDefined();
+ });
+
+ test("returns valid with only headers", async () => {
+ const result = await validateWebhookConfig({ headers: [] });
+ expect(result.valid).toBe(true);
+ });
+});
+
+// ─── sendWebhookVerification ──────────────────────────────────────────────────
+
+describe("sendWebhookVerification", () => {
+ test("throws when subscription has no webhookUrl", async () => {
+ const sub = makeSub({ webhookUrl: undefined });
+ await expect(
+ sendWebhookVerification(sub, "https://example.com/verify/token"),
+ ).rejects.toThrow("Webhook URL is required");
+ });
+
+ test("resolves when fetch returns 200", async () => {
+ fetchMock.mockResolvedValue(new Response(null, { status: 200 }));
+ const sub = makeSub();
+ await expect(
+ sendWebhookVerification(sub, "https://example.com/verify/abc"),
+ ).resolves.toBeUndefined();
+ });
+
+ test("throws when fetch returns a non-ok status", async () => {
+ fetchMock.mockResolvedValue(
+ new Response(null, { status: 500, statusText: "Server Error" }),
+ );
+ const sub = makeSub();
+ await expect(
+ sendWebhookVerification(sub, "https://example.com/verify/abc"),
+ ).rejects.toThrow("Webhook verification failed: 500");
+ });
+
+ test("posts to the correct URL with the expected payload", async () => {
+ fetchMock.mockResolvedValue(new Response(null, { status: 200 }));
+ const sub = makeSub({
+ token: "my-token",
+ webhookUrl: "https://hooks.example.com/sub",
+ });
+ await sendWebhookVerification(sub, "https://example.com/verify/my-token");
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const [url, init] = fetchMock.mock.calls[0];
+ expect(url).toBe("https://hooks.example.com/sub");
+ expect(init?.method).toBe("POST");
+ const body = JSON.parse(init?.body as string);
+ expect(body.type).toBe("verification");
+ expect(body.token).toBe("my-token");
+ expect(body.verifyUrl).toBe("https://example.com/verify/my-token");
+ });
+});
+
+// ─── sendWebhookNotifications ─────────────────────────────────────────────────
+
+describe("sendWebhookNotifications", () => {
+ test("skips subscriptions without a webhookUrl", async () => {
+ const sub = makeSub({ webhookUrl: undefined });
+ await sendWebhookNotifications([sub], makeUpdate());
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ test("sends a POST request to each webhook URL", async () => {
+ fetchMock.mockResolvedValue(new Response(null, { status: 200 }));
+ const sub1 = makeSub({ webhookUrl: "https://hook1.example.com" });
+ const sub2 = makeSub({ webhookUrl: "https://hook2.example.com" });
+
+ await sendWebhookNotifications([sub1, sub2], makeUpdate());
+
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ const urls = fetchMock.mock.calls.map(([url]: [string]) => url);
+ expect(urls).toContain("https://hook1.example.com");
+ expect(urls).toContain("https://hook2.example.com");
+ });
+
+ test("sends the correct payload shape", async () => {
+ fetchMock.mockResolvedValue(new Response(null, { status: 200 }));
+ const sub = makeSub({ pageId: 42, pageName: "My Page" });
+ const update = makeUpdate({
+ title: "Outage",
+ status: "resolved",
+ pageComponents: ["API"],
+ });
+
+ await sendWebhookNotifications([sub], update);
+
+ const [, init] = fetchMock.mock.calls[0];
+ const body = JSON.parse(init?.body as string);
+ expect(body.type).toBe("page_update");
+ expect(body.page.id).toBe(42);
+ expect(body.page.name).toBe("My Page");
+ expect(body.update.status).toBe("resolved");
+ expect(body.update.title).toBe("Outage");
+ expect(body.update.pageComponents).toEqual(["API"]);
+ });
+
+ test("applies custom headers from channelConfig", async () => {
+ fetchMock.mockResolvedValue(new Response(null, { status: 200 }));
+ const sub = makeSub({
+ channelConfig: JSON.stringify({
+ headers: [{ key: "X-Custom-Header", value: "my-value" }],
+ }),
+ });
+
+ await sendWebhookNotifications([sub], makeUpdate());
+
+ const [, init] = fetchMock.mock.calls[0];
+ const headers = init?.headers as Record<string, string>;
+ expect(headers["X-Custom-Header"]).toBe("my-value");
+ });
+
+ test("continues sending to remaining webhooks when one fails", async () => {
+ fetchMock
+ .mockRejectedValueOnce(new Error("Network error"))
+ .mockResolvedValueOnce(new Response(null, { status: 200 }));
+
+ const sub1 = makeSub({ webhookUrl: "https://fail.example.com" });
+ const sub2 = makeSub({ webhookUrl: "https://succeed.example.com" });
+
+ await expect(
+ sendWebhookNotifications([sub1, sub2], makeUpdate()),
+ ).resolves.toBeUndefined();
+
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/packages/subscriptions/src/channels/webhook.ts b/packages/subscriptions/src/channels/webhook.ts
new file mode 100644
index 000000000..f834c225c
--- /dev/null
+++ b/packages/subscriptions/src/channels/webhook.ts
@@ -0,0 +1,122 @@
+import { z } from "zod";
+import type { PageUpdate, Subscription } from "../types";
+
+export async function validateWebhookConfig(config: unknown) {
+ const schema = z.object({
+ headers: z
+ .array(
+ z.object({
+ key: z.string().min(1),
+ value: z.string(),
+ }),
+ )
+ .optional(),
+ secret: z.string().optional(),
+ });
+ const result = schema.safeParse(config);
+ return { valid: result.success, error: result.error?.message };
+}
+
+function hasWebhookUrl(
+ sub: Subscription,
+): sub is Subscription & { webhookUrl: string } {
+ return sub.webhookUrl !== undefined && sub.webhookUrl !== null;
+}
+
+export async function sendWebhookVerification(
+ subscription: Subscription,
+ verifyUrl: string,
+) {
+ if (!subscription.webhookUrl) {
+ throw new Error("Webhook URL is required for webhook channel");
+ }
+
+ const response = await fetch(subscription.webhookUrl, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ type: "verification",
+ token: subscription.token,
+ verifyUrl,
+ }),
+ signal: AbortSignal.timeout(10000),
+ });
+
+ if (!response.ok) {
+ throw new Error(
+ `Webhook verification failed: ${response.status} ${response.statusText}`,
+ );
+ }
+}
+
+export async function sendWebhookNotifications(
+ subscriptions: Subscription[],
+ pageUpdate: PageUpdate,
+) {
+ const validSubscriptions = subscriptions.filter(hasWebhookUrl);
+ if (validSubscriptions.length === 0) return;
+
+ await Promise.allSettled(
+ validSubscriptions.map(async (subscription) => {
+ let config: Record<string, unknown> = {};
+ try {
+ config = subscription.channelConfig
+ ? JSON.parse(subscription.channelConfig)
+ : {};
+ } catch {
+ console.error(
+ `Invalid channelConfig JSON for subscription ${subscription.id}`,
+ );
+ }
+
+ const payload = {
+ type: "page_update",
+ page: { id: subscription.pageId, name: subscription.pageName },
+ update: {
+ id: pageUpdate.id,
+ title: pageUpdate.title,
+ status: pageUpdate.status,
+ message: pageUpdate.message,
+ pageComponents: pageUpdate.pageComponents,
+ date: pageUpdate.date,
+ },
+ };
+
+ const headers: Record<string, string> = {
+ "Content-Type": "application/json",
+ "User-Agent": "OpenStatus-Webhooks/1.0",
+ };
+
+ if (config.headers) {
+ for (const header of config.headers as {
+ key: string;
+ value: string;
+ }[]) {
+ headers[header.key] = header.value;
+ }
+ }
+
+ try {
+ const response = await fetch(subscription.webhookUrl, {
+ method: "POST",
+ headers,
+ body: JSON.stringify(payload),
+ signal: AbortSignal.timeout(10000),
+ });
+
+ if (!response.ok) {
+ console.error(
+ `Webhook notification failed for ${subscription.webhookUrl}: ${response.status} ${response.statusText}`,
+ );
+ throw new Error(`Webhook returned ${response.status}`);
+ }
+ } catch (error) {
+ console.error(
+ `Failed to send webhook notification to ${subscription.webhookUrl}:`,
+ error,
+ );
+ throw error;
+ }
+ }),
+ );
+}
diff --git a/packages/subscriptions/src/dispatcher.test.ts b/packages/subscriptions/src/dispatcher.test.ts
new file mode 100644
index 000000000..fd0f33eb0
--- /dev/null
+++ b/packages/subscriptions/src/dispatcher.test.ts
@@ -0,0 +1,193 @@
+import {
+ afterAll,
+ beforeAll,
+ beforeEach,
+ describe,
+ expect,
+ spyOn,
+ test,
+} from "bun:test";
+import { db, eq } from "@openstatus/db";
+import {
+ pageSubscriber,
+ pageSubscriberToPageComponent,
+} from "@openstatus/db/src/schema";
+import { EmailClient } from "@openstatus/emails";
+import { dispatchPageUpdate } from "./dispatcher";
+import type { PageUpdate } from "./types";
+
+// RESEND_API_KEY is set in test-preload.ts (see bunfig.toml) so @openstatus/emails
+// loads successfully and EmailClient prototype methods can be spied on.
+
+const sendStatusReportUpdateMock = spyOn(
+ EmailClient.prototype,
+ "sendStatusReportUpdate",
+).mockResolvedValue(undefined);
+
+// IDs present in the seeded database
+const PAGE_ID = 1; // slug: "status"
+const COMPONENT_1 = 1;
+const COMPONENT_2 = 2;
+
+const EMAILS = {
+ entirePage: "[email protected]",
+ component1: "[email protected]",
+ component2: "[email protected]",
+};
+
+// Captured IDs after insert
+let _subEntirePageId: number;
+let subComponent1Id: number;
+let subComponent2Id: number;
+
+function makePageUpdate(overrides: Partial<PageUpdate> = {}): PageUpdate {
+ return {
+ id: 1,
+ pageId: PAGE_ID,
+ title: "Test Incident",
+ status: "investigating",
+ message: "We are investigating.",
+ pageComponentIds: [],
+ pageComponents: [],
+ date: new Date().toISOString(),
+ ...overrides,
+ };
+}
+
+async function cleanAll() {
+ for (const email of Object.values(EMAILS)) {
+ await db.delete(pageSubscriber).where(eq(pageSubscriber.email, email));
+ }
+}
+
+beforeAll(async () => {
+ await cleanAll();
+
+ const insertAccepted = async (email: string) => {
+ return db
+ .insert(pageSubscriber)
+ .values({
+ channelType: "email",
+ email,
+ pageId: PAGE_ID,
+ token: crypto.randomUUID(),
+ acceptedAt: new Date(),
+ expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
+ })
+ .returning()
+ .get();
+ };
+
+ const subEntirePage = await insertAccepted(EMAILS.entirePage);
+ const subComponent1 = await insertAccepted(EMAILS.component1);
+ const subComponent2 = await insertAccepted(EMAILS.component2);
+
+ _subEntirePageId = subEntirePage.id;
+ subComponent1Id = subComponent1.id;
+ subComponent2Id = subComponent2.id;
+
+ // subEntirePage has no component associations → entire-page scope
+ // subComponent1 subscribes to component 1 only
+ await db
+ .insert(pageSubscriberToPageComponent)
+ .values({ pageSubscriberId: subComponent1Id, pageComponentId: COMPONENT_1 })
+ .run();
+
+ // subComponent2 subscribes to component 2 only
+ await db
+ .insert(pageSubscriberToPageComponent)
+ .values({ pageSubscriberId: subComponent2Id, pageComponentId: COMPONENT_2 })
+ .run();
+});
+
+afterAll(cleanAll);
+
+beforeEach(() => {
+ sendStatusReportUpdateMock.mockClear();
+});
+
+// ─── dispatchPageUpdate - component filtering ─────────────────────────────────
+
+describe("dispatchPageUpdate - component filtering", () => {
+ test("notifies entire-page and component-1 subscriber when update affects component 1", async () => {
+ await dispatchPageUpdate(
+ makePageUpdate({ pageComponentIds: [COMPONENT_1] }),
+ );
+
+ expect(sendStatusReportUpdateMock).toHaveBeenCalledTimes(1);
+ const { subscribers } = sendStatusReportUpdateMock.mock.calls[0][0];
+ const emails = subscribers.map((s: { email: string }) => s.email);
+
+ expect(emails).toContain(EMAILS.entirePage);
+ expect(emails).toContain(EMAILS.component1);
+ expect(emails).not.toContain(EMAILS.component2);
+ });
+
+ test("notifies entire-page and component-2 subscriber when update affects component 2", async () => {
+ await dispatchPageUpdate(
+ makePageUpdate({ pageComponentIds: [COMPONENT_2] }),
+ );
+
+ const { subscribers } = sendStatusReportUpdateMock.mock.calls[0][0];
+ const emails = subscribers.map((s: { email: string }) => s.email);
+
+ expect(emails).toContain(EMAILS.entirePage);
+ expect(emails).toContain(EMAILS.component2);
+ expect(emails).not.toContain(EMAILS.component1);
+ });
+
+ test("notifies all subscribers when update affects both components", async () => {
+ await dispatchPageUpdate(
+ makePageUpdate({ pageComponentIds: [COMPONENT_1, COMPONENT_2] }),
+ );
+
+ const { subscribers } = sendStatusReportUpdateMock.mock.calls[0][0];
+ const emails = subscribers.map((s: { email: string }) => s.email);
+
+ expect(emails).toContain(EMAILS.entirePage);
+ expect(emails).toContain(EMAILS.component1);
+ expect(emails).toContain(EMAILS.component2);
+ });
+
+ test("notifies only the entire-page subscriber when update has no affected components", async () => {
+ await dispatchPageUpdate(makePageUpdate({ pageComponentIds: [] }));
+
+ expect(sendStatusReportUpdateMock).toHaveBeenCalledTimes(1);
+ const { subscribers } = sendStatusReportUpdateMock.mock.calls[0][0];
+
+ expect(subscribers).toHaveLength(1);
+ expect(subscribers[0].email).toBe(EMAILS.entirePage);
+ });
+
+ test("does not notify component subscribers when update affects a different component", async () => {
+ // Only component 1 is affected — component 2 subscriber should be skipped
+ await dispatchPageUpdate(
+ makePageUpdate({ pageComponentIds: [COMPONENT_1] }),
+ );
+
+ const { subscribers } = sendStatusReportUpdateMock.mock.calls[0][0];
+ const emails = subscribers.map((s: { email: string }) => s.email);
+
+ expect(emails).not.toContain(EMAILS.component2);
+ });
+});
+
+// ─── dispatchPageUpdate - edge cases ─────────────────────────────────────────
+
+describe("dispatchPageUpdate - edge cases", () => {
+ test("does not call sendNotifications for a non-existent page", async () => {
+ await dispatchPageUpdate(
+ makePageUpdate({ pageId: 99999, pageComponentIds: [COMPONENT_1] }),
+ );
+
+ expect(sendStatusReportUpdateMock).not.toHaveBeenCalled();
+ });
+
+ test("does not propagate channel failure — resolves even when sendStatusReportUpdate throws", async () => {
+ sendStatusReportUpdateMock.mockRejectedValueOnce(new Error("SMTP failure"));
+
+ await expect(
+ dispatchPageUpdate(makePageUpdate({ pageComponentIds: [] })),
+ ).resolves.toBeUndefined();
+ });
+});
diff --git a/packages/subscriptions/src/dispatcher.ts b/packages/subscriptions/src/dispatcher.ts
new file mode 100644
index 000000000..0d707dc1c
--- /dev/null
+++ b/packages/subscriptions/src/dispatcher.ts
@@ -0,0 +1,188 @@
+import { and, db, eq, isNotNull, isNull } from "@openstatus/db";
+import {
+ maintenance,
+ page,
+ pageSubscriber,
+ statusReportUpdate,
+} from "@openstatus/db/src/schema";
+import { getChannel } from "./channels";
+import type { PageUpdate, Subscription } from "./types";
+
+/**
+ * Dispatch notifications for a status report update
+ */
+export async function dispatchStatusReportUpdate(statusReportUpdateId: number) {
+ const update = await db.query.statusReportUpdate.findFirst({
+ where: eq(statusReportUpdate.id, statusReportUpdateId),
+ with: {
+ statusReport: {
+ with: {
+ statusReportsToPageComponents: {
+ with: { pageComponent: true },
+ },
+ },
+ },
+ },
+ });
+
+ if (!update?.statusReport) {
+ console.error(`Status report update ${statusReportUpdateId} not found`);
+ return;
+ }
+
+ if (!update.statusReport.pageId) {
+ console.error(`Status report ${update.statusReport.id} has no page ID`);
+ return;
+ }
+
+ const pageComponents = update.statusReport.statusReportsToPageComponents.map(
+ (i) => i.pageComponent,
+ );
+
+ await dispatchPageUpdate({
+ id: update.statusReport.id,
+ pageId: update.statusReport.pageId,
+ title: update.statusReport.title,
+ status: update.status as PageUpdate["status"],
+ message: update.message,
+ pageComponentIds: pageComponents.map((c) => c.id),
+ pageComponents: pageComponents.map((c) => c.name),
+ date: update.date.toISOString(),
+ });
+}
+
+/**
+ * Dispatch notifications for a maintenance update
+ */
+export async function dispatchMaintenanceUpdate(maintenanceId: number) {
+ const maintenanceWithComponents = await db.query.maintenance.findFirst({
+ where: eq(maintenance.id, maintenanceId),
+ with: {
+ maintenancesToPageComponents: {
+ with: { pageComponent: true },
+ },
+ },
+ });
+
+ if (!maintenanceWithComponents) {
+ console.error(`Maintenance ${maintenanceId} not found`);
+ return;
+ }
+
+ if (!maintenanceWithComponents.pageId) {
+ console.error(`Maintenance ${maintenanceId} has no page ID`);
+ return;
+ }
+
+ const pageComponents =
+ maintenanceWithComponents.maintenancesToPageComponents.map(
+ (i) => i.pageComponent,
+ );
+
+ await dispatchPageUpdate({
+ id: maintenanceWithComponents.id,
+ pageId: maintenanceWithComponents.pageId,
+ title: maintenanceWithComponents.title,
+ status: "maintenance",
+ message: maintenanceWithComponents.message,
+ pageComponentIds: pageComponents.map((c) => c.id),
+ pageComponents: pageComponents.map((c) => c.name),
+ date: `${maintenanceWithComponents.from.toISOString()} - ${maintenanceWithComponents.to.toISOString()}`,
+ });
+}
+
+/**
+ * Dispatch notifications for a page update to all matching subscriptions
+ *
+ * - Entire page subscriptions (empty componentIds): always notified
+ * - Component subscriptions: only notified if any affected component matches
+ */
+export async function dispatchPageUpdate(pageUpdate: PageUpdate) {
+ const affectedComponentIds = pageUpdate.pageComponentIds;
+
+ const pageData = await db
+ .select({
+ id: page.id,
+ name: page.title,
+ slug: page.slug,
+ customDomain: page.customDomain,
+ })
+ .from(page)
+ .where(eq(page.id, pageUpdate.pageId))
+ .get();
+
+ if (!pageData) {
+ console.error(`Page ${pageUpdate.pageId} not found`);
+ return;
+ }
+
+ const subscribersWithComponents = await db.query.pageSubscriber.findMany({
+ where: and(
+ eq(pageSubscriber.pageId, pageUpdate.pageId),
+ isNotNull(pageSubscriber.acceptedAt),
+ isNull(pageSubscriber.unsubscribedAt),
+ ),
+ with: {
+ components: true,
+ },
+ });
+
+ const matchingSubscriptions: Subscription[] = subscribersWithComponents
+ .map((sub) => ({
+ id: sub.id,
+ pageId: sub.pageId,
+ pageName: pageData.name,
+ pageSlug: pageData.slug,
+ customDomain: pageData.customDomain,
+ channelType: sub.channelType as "email" | "webhook",
+ email: sub.email ?? undefined,
+ webhookUrl: sub.webhookUrl ?? undefined,
+ channelConfig: sub.channelConfig ?? undefined,
+ token: sub.token ?? undefined,
+ acceptedAt: sub.acceptedAt ?? undefined,
+ componentIds: sub.components.map((c) => c.pageComponentId),
+ }))
+ .filter((sub) => {
+ // Entire page subscription matches all updates
+ if (sub.componentIds.length === 0) return true;
+
+ // Component subscription: check for overlap
+ return affectedComponentIds.some((id) => sub.componentIds.includes(id));
+ });
+
+ if (matchingSubscriptions.length === 0) {
+ console.log(`No matching subscriptions for page update ${pageUpdate.id}`);
+ return;
+ }
+
+ const byChannel = matchingSubscriptions.reduce(
+ (acc, sub) => {
+ if (!acc[sub.channelType]) {
+ acc[sub.channelType] = [];
+ }
+ acc[sub.channelType].push(sub);
+ return acc;
+ },
+ {} as Record<string, Subscription[]>,
+ );
+
+ await Promise.allSettled(
+ Object.entries(byChannel).map(async ([channelType, subs]) => {
+ const channel = getChannel(channelType);
+ if (!channel) {
+ console.error(`Unknown channel type: ${channelType}`);
+ return;
+ }
+
+ try {
+ await channel.sendNotifications(subs, pageUpdate);
+ console.log(`Sent ${subs.length} notifications via ${channelType}`);
+ } catch (error) {
+ console.error(
+ `Failed to send notifications via ${channelType}:`,
+ error,
+ );
+ }
+ }),
+ );
+}
diff --git a/packages/subscriptions/src/index.ts b/packages/subscriptions/src/index.ts
new file mode 100644
index 000000000..df36411e8
--- /dev/null
+++ b/packages/subscriptions/src/index.ts
@@ -0,0 +1,32 @@
+// Export channel functions
+export {
+ sendEmailNotifications,
+ sendEmailVerification,
+ validateEmailConfig,
+} from "./channels/email";
+export {
+ sendWebhookNotifications,
+ sendWebhookVerification,
+ validateWebhookConfig,
+} from "./channels/webhook";
+export { getChannel } from "./channels/index";
+
+// Export dispatcher functions
+export {
+ dispatchStatusReportUpdate,
+ dispatchMaintenanceUpdate,
+ dispatchPageUpdate,
+} from "./dispatcher";
+
+// Export service functions
+export {
+ upsertEmailSubscription,
+ hasPendingUnexpiredSubscription,
+ verifySubscription,
+ getSubscriptionByToken,
+ updateSubscriptionScope,
+ unsubscribe,
+} from "./service";
+
+// Export types
+export type { Subscription, PageUpdate, SubscriptionChannel } from "./types";
diff --git a/packages/subscriptions/src/service.test.ts b/packages/subscriptions/src/service.test.ts
new file mode 100644
index 000000000..e6b687699
--- /dev/null
+++ b/packages/subscriptions/src/service.test.ts
@@ -0,0 +1,397 @@
+import { afterAll, beforeAll, describe, expect, test } from "bun:test";
+import { and, db, eq, isNull } from "@openstatus/db";
+import { pageSubscriber } from "@openstatus/db/src/schema";
+import {
+ getSubscriptionByToken,
+ unsubscribe,
+ updateSubscriptionScope,
+ upsertEmailSubscription,
+ verifySubscription,
+} from "./service";
+
+// IDs present in the seeded database
+const PAGE_ID = 1; // slug: "status", customDomain: ""
+const COMPONENT_1 = 1;
+const COMPONENT_2 = 2;
+
+// One email per describe block to keep them fully independent
+const EMAILS = {
+ upsert: "[email protected]",
+ verify: "[email protected]",
+ verifyExpired: "[email protected]",
+ getByToken: "[email protected]",
+ scope: "[email protected]",
+ scopeUnverified: "[email protected]",
+ scopeUnsubbed: "[email protected]",
+ unsub: "[email protected]",
+};
+
+async function cleanAll() {
+ for (const email of Object.values(EMAILS)) {
+ await db.delete(pageSubscriber).where(eq(pageSubscriber.email, email));
+ }
+}
+
+beforeAll(cleanAll);
+afterAll(cleanAll);
+
+// ─── upsertEmailSubscription ──────────────────────────────────────────────────
+
+describe("upsertEmailSubscription", () => {
+ const email = EMAILS.upsert;
+
+ beforeAll(async () => {
+ await db.delete(pageSubscriber).where(eq(pageSubscriber.email, email));
+ });
+
+ test("creates a new subscription for an unknown email", async () => {
+ const result = await upsertEmailSubscription({ email, pageId: PAGE_ID });
+
+ expect(result.email).toBe(email);
+ expect(result.pageId).toBe(PAGE_ID);
+ expect(result.token).toBeDefined();
+ expect(result.acceptedAt).toBeUndefined();
+ expect(result.componentIds).toEqual([]);
+ });
+
+ test("does not create a duplicate row when called again", async () => {
+ await upsertEmailSubscription({ email, pageId: PAGE_ID });
+
+ const rows = await db.query.pageSubscriber.findMany({
+ where: eq(pageSubscriber.email, email),
+ });
+
+ expect(rows).toHaveLength(1);
+ });
+
+ test("merges new components into an existing subscription", async () => {
+ const result = await upsertEmailSubscription({
+ email,
+ pageId: PAGE_ID,
+ componentIds: [COMPONENT_1],
+ });
+
+ expect(result.componentIds).toContain(COMPONENT_1);
+ });
+
+ test("refreshes expiresAt for a still-pending subscription", async () => {
+ const before = new Date();
+ await upsertEmailSubscription({ email, pageId: PAGE_ID });
+
+ const row = await db.query.pageSubscriber.findFirst({
+ where: eq(pageSubscriber.email, email),
+ });
+
+ expect(row?.expiresAt?.getTime()).toBeGreaterThan(before.getTime());
+ });
+
+ test("stores email in lowercase regardless of input casing", async () => {
+ await db.delete(pageSubscriber).where(eq(pageSubscriber.email, email));
+
+ const result = await upsertEmailSubscription({
+ email: email.toUpperCase(),
+ pageId: PAGE_ID,
+ });
+
+ expect(result.email).toBe(email);
+ });
+
+ test("creates a new row (does not reactivate) when email was previously unsubscribed", async () => {
+ const existing = await db.query.pageSubscriber.findFirst({
+ where: eq(pageSubscriber.email, email),
+ });
+
+ if (!existing) {
+ throw new Error("Existing subscriber not found");
+ }
+
+ await db
+ .update(pageSubscriber)
+ .set({ acceptedAt: new Date(), unsubscribedAt: new Date() })
+ .where(eq(pageSubscriber.id, existing.id))
+ .run();
+
+ const result = await upsertEmailSubscription({
+ email,
+ pageId: PAGE_ID,
+ componentIds: [COMPONENT_1],
+ });
+
+ // A brand-new row — not a mutation of the old one
+ expect(result.id).not.toBe(existing.id);
+ expect(result.acceptedAt).toBeUndefined(); // requires re-verification
+ expect(result.componentIds).toEqual([COMPONENT_1]);
+
+ // Old row is preserved with its unsubscribedAt intact
+ const oldRow = await db.query.pageSubscriber.findFirst({
+ where: eq(pageSubscriber.id, existing.id),
+ });
+ expect(oldRow?.unsubscribedAt).toBeDefined();
+ });
+
+ test("creates a new row when email was unsubscribed before ever verifying", async () => {
+ // Find the currently active (pending, never verified) row left by the previous test
+ const pending = await db.query.pageSubscriber.findFirst({
+ where: and(
+ eq(pageSubscriber.email, email),
+ isNull(pageSubscriber.unsubscribedAt),
+ ),
+ });
+ if (!pending) throw new Error("Pending subscriber not found");
+ expect(pending.acceptedAt).toBeNull(); // confirm it was never verified
+
+ await db
+ .update(pageSubscriber)
+ .set({ unsubscribedAt: new Date() })
+ .where(eq(pageSubscriber.id, pending.id))
+ .run();
+
+ const result = await upsertEmailSubscription({ email, pageId: PAGE_ID });
+
+ expect(result.id).not.toBe(pending.id);
+ expect(result.acceptedAt).toBeUndefined();
+
+ // Old unverified+unsubscribed row still has both fields set correctly
+ const oldRow = await db.query.pageSubscriber.findFirst({
+ where: eq(pageSubscriber.id, pending.id),
+ });
+ expect(oldRow?.unsubscribedAt).toBeDefined();
+ expect(oldRow?.acceptedAt).toBeNull();
+ });
+
+ test("throws for component IDs that do not belong to this page", async () => {
+ await expect(
+ upsertEmailSubscription({ email, pageId: PAGE_ID, componentIds: [9999] }),
+ ).rejects.toThrow("Invalid components: 9999");
+ });
+
+ test("throws for a page ID that does not exist", async () => {
+ await expect(
+ upsertEmailSubscription({ email, pageId: 99999 }),
+ ).rejects.toThrow("Page 99999 not found");
+ });
+});
+
+// ─── verifySubscription ───────────────────────────────────────────────────────
+
+describe("verifySubscription", () => {
+ const email = EMAILS.verify;
+ let pendingToken: string;
+
+ beforeAll(async () => {
+ await db.delete(pageSubscriber).where(eq(pageSubscriber.email, email));
+ const sub = await upsertEmailSubscription({ email, pageId: PAGE_ID });
+ if (!sub.token) {
+ throw new Error("Token is undefined");
+ }
+ pendingToken = sub.token;
+ });
+
+ test("returns null for an unknown token", async () => {
+ const result = await verifySubscription("non-existent-token-xyz");
+ expect(result).toBeNull();
+ });
+
+ test("returns null when domain does not match page slug", async () => {
+ const result = await verifySubscription(pendingToken, "wrong-domain");
+ expect(result).toBeNull();
+ });
+
+ test("marks the subscription as accepted on first verification", async () => {
+ const result = await verifySubscription(pendingToken, "status");
+ expect(result).not.toBeNull();
+ expect(result?.acceptedAt).toBeDefined();
+ });
+
+ test("returns an already-accepted subscription idempotently", async () => {
+ // pendingToken now points to an accepted subscription from the previous test
+ const result = await verifySubscription(pendingToken, "status");
+ expect(result).not.toBeNull();
+ expect(result?.acceptedAt).toBeDefined();
+ });
+
+ test("throws for a token with an expired expiresAt", async () => {
+ const expiredEmail = EMAILS.verifyExpired;
+ await db
+ .delete(pageSubscriber)
+ .where(eq(pageSubscriber.email, expiredEmail));
+
+ await db
+ .insert(pageSubscriber)
+ .values({
+ channelType: "email",
+ email: expiredEmail,
+ pageId: PAGE_ID,
+ token: "expired-token-xyz",
+ expiresAt: new Date(Date.now() - 1000), // 1 second in the past
+ })
+ .run();
+
+ await expect(verifySubscription("expired-token-xyz")).rejects.toThrow(
+ "Verification token expired",
+ );
+ });
+});
+
+// ─── getSubscriptionByToken ───────────────────────────────────────────────────
+
+describe("getSubscriptionByToken", () => {
+ const email = EMAILS.getByToken;
+ let token: string;
+
+ beforeAll(async () => {
+ await db.delete(pageSubscriber).where(eq(pageSubscriber.email, email));
+ const sub = await upsertEmailSubscription({ email, pageId: PAGE_ID });
+ if (!sub.token) {
+ throw new Error("Token is undefined");
+ }
+ token = sub.token;
+ });
+
+ test("returns null for an unknown token", async () => {
+ const result = await getSubscriptionByToken("unknown-token-xyz");
+ expect(result).toBeNull();
+ });
+
+ test("returns null when domain does not match", async () => {
+ const result = await getSubscriptionByToken(token, "wrong-domain");
+ expect(result).toBeNull();
+ });
+
+ test('masks the email address as "x***@domain"', async () => {
+ const result = await getSubscriptionByToken(token);
+ expect(result).not.toBeNull();
+ // "[email protected]" → "s***@example.com"
+ expect(result?.email).toMatch(/^s\*\*\*@example\.com$/);
+ expect(result?.email).not.toBe(email);
+ });
+
+ test("returns subscription data for a valid token and matching domain", async () => {
+ const result = await getSubscriptionByToken(token, "status");
+ expect(result).not.toBeNull();
+ expect(result?.pageId).toBe(PAGE_ID);
+ expect(result?.pageSlug).toBe("status");
+ });
+});
+
+// ─── updateSubscriptionScope ──────────────────────────────────────────────────
+
+describe("updateSubscriptionScope", () => {
+ const email = EMAILS.scope;
+ let token: string;
+
+ beforeAll(async () => {
+ await db.delete(pageSubscriber).where(eq(pageSubscriber.email, email));
+ const sub = await upsertEmailSubscription({
+ email,
+ pageId: PAGE_ID,
+ componentIds: [COMPONENT_1],
+ });
+ if (!sub.token) {
+ throw new Error("Token is undefined");
+ }
+ token = sub.token;
+ // Verify so acceptedAt is set — required by the guard added to updateSubscriptionScope
+ await verifySubscription(token);
+ });
+
+ test("throws for an unknown token", async () => {
+ await expect(
+ updateSubscriptionScope({ token: "unknown-token-xyz", componentIds: [] }),
+ ).rejects.toThrow("Subscription not found");
+ });
+
+ test("throws when subscription is not yet verified", async () => {
+ await db
+ .delete(pageSubscriber)
+ .where(eq(pageSubscriber.email, EMAILS.scopeUnverified));
+ const sub = await upsertEmailSubscription({
+ email: EMAILS.scopeUnverified,
+ pageId: PAGE_ID,
+ });
+ if (!sub.token) throw new Error("Token is undefined");
+
+ await expect(
+ updateSubscriptionScope({ token: sub.token, componentIds: [] }),
+ ).rejects.toThrow("Subscription not yet verified");
+ });
+
+ test("throws when subscription is unsubscribed", async () => {
+ await db
+ .delete(pageSubscriber)
+ .where(eq(pageSubscriber.email, EMAILS.scopeUnsubbed));
+ const sub = await upsertEmailSubscription({
+ email: EMAILS.scopeUnsubbed,
+ pageId: PAGE_ID,
+ });
+ if (!sub.token) throw new Error("Token is undefined");
+ await verifySubscription(sub.token);
+ await unsubscribe(sub.token);
+
+ await expect(
+ updateSubscriptionScope({ token: sub.token, componentIds: [] }),
+ ).rejects.toThrow("Subscription is unsubscribed");
+ });
+
+ test("replaces existing component scope with new ones", async () => {
+ const result = await updateSubscriptionScope({
+ token,
+ componentIds: [COMPONENT_2],
+ });
+
+ expect(result.componentIds).toEqual([COMPONENT_2]);
+ expect(result.componentIds).not.toContain(COMPONENT_1);
+ });
+
+ test("can clear all components (switches to entire-page scope)", async () => {
+ const result = await updateSubscriptionScope({ token, componentIds: [] });
+ expect(result.componentIds).toEqual([]);
+ });
+
+ test("throws when a component does not belong to this page", async () => {
+ await expect(
+ updateSubscriptionScope({ token, componentIds: [9999] }),
+ ).rejects.toThrow("Some components do not belong to this page");
+ });
+});
+
+// ─── unsubscribe ──────────────────────────────────────────────────────────────
+
+describe("unsubscribe", () => {
+ const email = EMAILS.unsub;
+ let token: string;
+
+ beforeAll(async () => {
+ await db.delete(pageSubscriber).where(eq(pageSubscriber.email, email));
+ const sub = await upsertEmailSubscription({ email, pageId: PAGE_ID });
+ if (!sub.token) {
+ throw new Error("Token is undefined");
+ }
+ token = sub.token;
+ });
+
+ test("throws for an unknown token", async () => {
+ await expect(unsubscribe("unknown-token-xyz")).rejects.toThrow(
+ "Subscription not found",
+ );
+ });
+
+ test("throws when the domain does not match", async () => {
+ await expect(unsubscribe(token, "wrong-domain")).rejects.toThrow(
+ "Subscription not found",
+ );
+ });
+
+ test("sets unsubscribedAt on a valid token", async () => {
+ await expect(unsubscribe(token, "status")).resolves.toBeUndefined();
+
+ const row = await db.query.pageSubscriber.findFirst({
+ where: eq(pageSubscriber.token, token),
+ });
+ expect(row?.unsubscribedAt).toBeDefined();
+ });
+
+ test("resolves silently if the subscription is already unsubscribed", async () => {
+ await expect(unsubscribe(token)).resolves.toBeUndefined();
+ });
+});
diff --git a/packages/subscriptions/src/service.ts b/packages/subscriptions/src/service.ts
new file mode 100644
index 000000000..c61e4e643
--- /dev/null
+++ b/packages/subscriptions/src/service.ts
@@ -0,0 +1,463 @@
+import { and, db, eq, inArray, isNull } from "@openstatus/db";
+import {
+ page,
+ pageComponent,
+ pageSubscriber,
+ pageSubscriberToPageComponent,
+} from "@openstatus/db/src/schema";
+
+/**
+ * Subscription Service Layer
+ * Handles all subscription CRUD operations
+ */
+
+// Verification token expiry configuration
+const VERIFICATION_EXPIRY_DAYS = 7;
+const VERIFICATION_EXPIRY_MS = VERIFICATION_EXPIRY_DAYS * 24 * 60 * 60 * 1000;
+
+/**
+ * Mask email address for privacy (e.g., "[email protected]" -> "j***@example.com")
+ */
+function maskEmail(email: string): string {
+ const [localPart, domain] = email.split("@");
+ if (!domain) return email;
+
+ const masked = localPart.length > 0 ? `${localPart[0]}***` : "***";
+ return `${masked}@${domain}`;
+}
+
+interface UpsertEmailSubscriptionInput {
+ email: string;
+ pageId: number;
+ componentIds?: number[]; // Empty = entire page
+}
+
+interface UpdateSubscriptionScopeInput {
+ token: string;
+ componentIds: number[]; // New scope (replaces current)
+ domain?: string; // Optional domain validation
+}
+
+/**
+ * Create or update email subscription (ADD behavior)
+ *
+ * - If no subscription exists (or only unsubscribed ones): creates new subscription
+ * - If pending subscription exists: merges components and refreshes expiry
+ * - If verified subscription exists: returns as-is (caller handles "already subscribed")
+ */
+export async function upsertEmailSubscription(
+ input: UpsertEmailSubscriptionInput,
+) {
+ const { email, pageId, componentIds = [] } = input;
+
+ const pageData = await db.query.page.findFirst({
+ where: eq(page.id, pageId),
+ });
+
+ if (!pageData) {
+ throw new Error(`Page ${pageId} not found`);
+ }
+
+ // Validate component IDs belong to this page
+ if (componentIds.length > 0) {
+ const validComponents = await db
+ .select({ id: pageComponent.id })
+ .from(pageComponent)
+ .where(
+ and(
+ eq(pageComponent.pageId, pageId),
+ inArray(pageComponent.id, componentIds),
+ ),
+ )
+ .all();
+
+ if (validComponents.length !== componentIds.length) {
+ const validIds = validComponents.map((c) => c.id);
+ const invalidIds = componentIds.filter((id) => !validIds.includes(id));
+ throw new Error(`Invalid components: ${invalidIds.join(", ")}`);
+ }
+ }
+
+ // Check for active subscription
+ const existing = await db.query.pageSubscriber.findFirst({
+ where: and(
+ eq(pageSubscriber.email, email.toLowerCase()),
+ eq(pageSubscriber.pageId, pageId),
+ eq(pageSubscriber.channelType, "email"),
+ isNull(pageSubscriber.unsubscribedAt),
+ ),
+ with: {
+ components: true,
+ },
+ });
+
+ if (existing) {
+ // Already verified — return as-is without merging components.
+ // The caller (tRPC subscribe) will throw "Email already subscribed" on acceptedAt.
+ if (existing.acceptedAt) {
+ return {
+ id: existing.id,
+ pageId: existing.pageId,
+ pageName: pageData.title,
+ pageSlug: pageData.slug,
+ customDomain: pageData.customDomain,
+ channelType: existing.channelType,
+ email: existing.email ?? undefined,
+ token: existing.token,
+ acceptedAt: existing.acceptedAt,
+ componentIds: existing.components.map((c) => c.pageComponentId),
+ };
+ }
+
+ // Pending — merge new components and refresh expiry
+ const currentIds = existing.components.map((c) => c.pageComponentId);
+ const mergedIds = [...new Set([...currentIds, ...componentIds])];
+
+ const newIds = mergedIds.filter((id) => !currentIds.includes(id));
+ if (newIds.length > 0) {
+ await db
+ .insert(pageSubscriberToPageComponent)
+ .values(
+ newIds.map((compId) => ({
+ pageSubscriberId: existing.id,
+ pageComponentId: compId,
+ })),
+ )
+ .onConflictDoNothing()
+ .run();
+ }
+
+ const newExpiresAt = new Date(Date.now() + VERIFICATION_EXPIRY_MS);
+ await db
+ .update(pageSubscriber)
+ .set({ expiresAt: newExpiresAt, updatedAt: new Date() })
+ .where(eq(pageSubscriber.id, existing.id))
+ .run();
+
+ return {
+ id: existing.id,
+ pageId: existing.pageId,
+ pageName: pageData.title,
+ pageSlug: pageData.slug,
+ customDomain: pageData.customDomain,
+ channelType: existing.channelType,
+ email: existing.email ?? undefined,
+ token: existing.token,
+ acceptedAt: undefined,
+ componentIds: mergedIds,
+ };
+ }
+
+ // No existing subscription — create new one
+ const token = crypto.randomUUID();
+ const expiresAt = new Date(Date.now() + VERIFICATION_EXPIRY_MS);
+
+ const subscription = await db.transaction(async (tx) => {
+ const sub = await tx
+ .insert(pageSubscriber)
+ .values({
+ channelType: "email",
+ email: email.toLowerCase(),
+ webhookUrl: null,
+ pageId,
+ token,
+ expiresAt,
+ })
+ .returning()
+ .get();
+
+ if (componentIds.length > 0) {
+ await tx
+ .insert(pageSubscriberToPageComponent)
+ .values(
+ componentIds.map((compId) => ({
+ pageSubscriberId: sub.id,
+ pageComponentId: compId,
+ })),
+ )
+ .run();
+ }
+
+ return sub;
+ });
+
+ return {
+ id: subscription.id,
+ pageId: subscription.pageId,
+ pageName: pageData.title,
+ pageSlug: pageData.slug,
+ customDomain: pageData.customDomain,
+ channelType: "email" as const,
+ email: subscription.email ?? undefined,
+ token: subscription.token,
+ acceptedAt: subscription.acceptedAt ?? undefined,
+ unsubscribedAt: subscription.unsubscribedAt ?? undefined,
+ componentIds,
+ };
+}
+
+/**
+ * Verify a subscription by token
+ */
+export async function verifySubscription(token: string, domain?: string) {
+ const subscription = await db.query.pageSubscriber.findFirst({
+ where: eq(pageSubscriber.token, token),
+ with: {
+ page: true,
+ components: true,
+ },
+ });
+
+ if (!subscription) {
+ return null;
+ }
+
+ // Validate domain if provided
+ if (domain) {
+ const domainLower = domain.toLowerCase();
+ const pageSlugLower = subscription.page.slug.toLowerCase();
+ const customDomainLower = subscription.page.customDomain?.toLowerCase();
+
+ if (domainLower !== pageSlugLower && domainLower !== customDomainLower) {
+ return null;
+ }
+ }
+
+ // Already accepted
+ if (subscription.acceptedAt) {
+ return {
+ id: subscription.id,
+ pageId: subscription.pageId,
+ pageName: subscription.page.title,
+ pageSlug: subscription.page.slug,
+ customDomain: subscription.page.customDomain,
+ channelType: subscription.channelType as "email" | "webhook",
+ email: subscription.email ?? undefined,
+ webhookUrl: subscription.webhookUrl ?? undefined,
+ token: subscription.token,
+ acceptedAt: subscription.acceptedAt ?? undefined,
+ unsubscribedAt: subscription.unsubscribedAt ?? undefined,
+ componentIds: subscription.components.map((c) => c.pageComponentId),
+ };
+ }
+
+ // Check if expired
+ if (subscription.expiresAt && subscription.expiresAt < new Date()) {
+ throw new Error("Verification token expired");
+ }
+
+ // Mark as accepted
+ const updated = await db
+ .update(pageSubscriber)
+ .set({ acceptedAt: new Date(), updatedAt: new Date() })
+ .where(eq(pageSubscriber.id, subscription.id))
+ .returning()
+ .get();
+
+ return {
+ id: updated.id,
+ pageId: updated.pageId,
+ pageName: subscription.page.title,
+ pageSlug: subscription.page.slug,
+ customDomain: subscription.page.customDomain,
+ channelType: updated.channelType as "email" | "webhook",
+ email: updated.email ?? undefined,
+ webhookUrl: updated.webhookUrl ?? undefined,
+ token: updated.token,
+ acceptedAt: updated.acceptedAt ?? undefined,
+ componentIds: subscription.components.map((c) => c.pageComponentId),
+ };
+}
+
+/**
+ * Get subscription by token (for management UI)
+ */
+export async function getSubscriptionByToken(token: string, domain?: string) {
+ const subscription = await db.query.pageSubscriber.findFirst({
+ where: eq(pageSubscriber.token, token),
+ with: {
+ page: true,
+ components: true,
+ },
+ });
+
+ if (!subscription) {
+ return null;
+ }
+
+ if (domain) {
+ const domainLower = domain.toLowerCase();
+ const pageSlugLower = subscription.page.slug.toLowerCase();
+ const customDomainLower = subscription.page.customDomain?.toLowerCase();
+
+ if (domainLower !== pageSlugLower && domainLower !== customDomainLower) {
+ return null;
+ }
+ }
+
+ return {
+ id: subscription.id,
+ pageId: subscription.pageId,
+ pageName: subscription.page.title,
+ pageSlug: subscription.page.slug,
+ customDomain: subscription.page.customDomain,
+ channelType: subscription.channelType as "email" | "webhook",
+ email: subscription.email ? maskEmail(subscription.email) : undefined,
+ webhookUrl: subscription.webhookUrl ?? undefined,
+ acceptedAt: subscription.acceptedAt ?? undefined,
+ unsubscribedAt: subscription.unsubscribedAt ?? undefined,
+ componentIds: subscription.components.map((c) => c.pageComponentId),
+ };
+}
+
+/**
+ * Check whether an email already has a pending (unverified, unexpired) subscription for a page.
+ * Used to prevent re-sending verification emails for already-pending subscriptions.
+ */
+export async function hasPendingUnexpiredSubscription(
+ email: string,
+ pageId: number,
+): Promise<boolean> {
+ const existing = await db.query.pageSubscriber.findFirst({
+ where: and(
+ eq(pageSubscriber.email, email.toLowerCase()),
+ eq(pageSubscriber.pageId, pageId),
+ eq(pageSubscriber.channelType, "email"),
+ isNull(pageSubscriber.unsubscribedAt),
+ isNull(pageSubscriber.acceptedAt),
+ ),
+ });
+ return !!(existing?.expiresAt && existing.expiresAt > new Date());
+}
+
+/**
+ * Update subscription scope (replace all components)
+ */
+export async function updateSubscriptionScope(
+ input: UpdateSubscriptionScopeInput,
+) {
+ const { token, componentIds, domain } = input;
+
+ const subscription = await db.query.pageSubscriber.findFirst({
+ where: eq(pageSubscriber.token, token),
+ with: {
+ page: true,
+ components: true,
+ },
+ });
+
+ if (!subscription) {
+ throw new Error("Subscription not found");
+ }
+
+ if (domain) {
+ const domainLower = domain.toLowerCase();
+ const pageSlugLower = subscription.page.slug.toLowerCase();
+ const customDomainLower = subscription.page.customDomain?.toLowerCase();
+
+ if (domainLower !== pageSlugLower && domainLower !== customDomainLower) {
+ throw new Error("Subscription not found");
+ }
+ }
+
+ if (!subscription.acceptedAt) {
+ throw new Error("Subscription not yet verified");
+ }
+
+ if (subscription.unsubscribedAt) {
+ throw new Error("Subscription is unsubscribed");
+ }
+
+ if (componentIds.length > 0) {
+ const validComponents = await db
+ .select({ id: pageComponent.id })
+ .from(pageComponent)
+ .where(
+ and(
+ eq(pageComponent.pageId, subscription.pageId),
+ inArray(pageComponent.id, componentIds),
+ ),
+ )
+ .all();
+
+ if (validComponents.length !== componentIds.length) {
+ throw new Error("Some components do not belong to this page");
+ }
+ }
+
+ await db.transaction(async (tx) => {
+ await tx
+ .delete(pageSubscriberToPageComponent)
+ .where(
+ eq(pageSubscriberToPageComponent.pageSubscriberId, subscription.id),
+ )
+ .run();
+
+ if (componentIds.length > 0) {
+ await tx
+ .insert(pageSubscriberToPageComponent)
+ .values(
+ componentIds.map((id) => ({
+ pageSubscriberId: subscription.id,
+ pageComponentId: id,
+ })),
+ )
+ .run();
+ }
+
+ await tx
+ .update(pageSubscriber)
+ .set({ updatedAt: new Date() })
+ .where(eq(pageSubscriber.id, subscription.id))
+ .run();
+ });
+
+ return {
+ id: subscription.id,
+ pageId: subscription.pageId,
+ pageName: subscription.page.title,
+ pageSlug: subscription.page.slug,
+ customDomain: subscription.page.customDomain,
+ channelType: subscription.channelType as "email" | "webhook",
+ email: subscription.email ?? undefined,
+ token: subscription.token,
+ acceptedAt: subscription.acceptedAt ?? undefined,
+ componentIds,
+ };
+}
+
+/**
+ * Unsubscribe by token
+ */
+export async function unsubscribe(token: string, domain?: string) {
+ const subscription = await db.query.pageSubscriber.findFirst({
+ where: eq(pageSubscriber.token, token),
+ with: {
+ page: true,
+ },
+ });
+
+ if (!subscription) {
+ throw new Error("Subscription not found");
+ }
+
+ if (domain) {
+ const domainLower = domain.toLowerCase();
+ const pageSlugLower = subscription.page.slug.toLowerCase();
+ const customDomainLower = subscription.page.customDomain?.toLowerCase();
+
+ if (domainLower !== pageSlugLower && domainLower !== customDomainLower) {
+ throw new Error("Subscription not found");
+ }
+ }
+
+ if (subscription.unsubscribedAt) {
+ return;
+ }
+
+ await db
+ .update(pageSubscriber)
+ .set({ unsubscribedAt: new Date(), updatedAt: new Date() })
+ .where(eq(pageSubscriber.id, subscription.id))
+ .run();
+}
diff --git a/packages/subscriptions/src/test-preload.ts b/packages/subscriptions/src/test-preload.ts
new file mode 100644
index 000000000..291707044
--- /dev/null
+++ b/packages/subscriptions/src/test-preload.ts
@@ -0,0 +1,6 @@
+/**
+ * Preload file for bun test.
+ * Runs before any test file is loaded, ensuring env vars are set
+ * before module-level env validations (e.g. @openstatus/emails) fire.
+ */
+process.env.RESEND_API_KEY = "test-key";
diff --git a/packages/subscriptions/src/types.ts b/packages/subscriptions/src/types.ts
new file mode 100644
index 000000000..735780203
--- /dev/null
+++ b/packages/subscriptions/src/types.ts
@@ -0,0 +1,63 @@
+// Core types for the subscription system
+
+export interface Subscription {
+ id: number;
+ pageId: number;
+ pageName: string; // For templates
+ pageSlug: string; // For management URLs
+ customDomain?: string | null; // For custom domain URLs
+ componentIds: number[]; // Empty = entire page
+
+ // Channel (only ONE identifier populated based on channelType)
+ channelType: "email" | "webhook";
+ email?: string; // For email channel
+ webhookUrl?: string; // For webhook channel
+ channelConfig?: string; // JSON string for headers, secrets, etc.
+
+ token?: string;
+ acceptedAt?: Date;
+ unsubscribedAt?: Date;
+}
+
+/**
+ * Generic page update (status reports, maintenance, incidents, etc.)
+ * Used for all types of notifications sent to subscribers
+ */
+export interface PageUpdate {
+ id: number;
+ pageId: number;
+ title: string;
+ status:
+ | "investigating"
+ | "identified"
+ | "monitoring"
+ | "resolved"
+ | "maintenance";
+ message: string;
+ pageComponentIds: number[]; // For subscription matching
+ pageComponents: string[]; // Component names for display
+ date: string; // can be single string or "from - to"
+}
+
+/**
+ * Interface for notification channels (email, webhook, etc.)
+ * Channels handle the actual delivery of notifications.
+ */
+export interface SubscriptionChannel {
+ id: string;
+
+ // Validate channel-specific config
+ validateConfig(config: unknown): Promise<{ valid: boolean; error?: string }>;
+
+ // Send verification if needed
+ sendVerification?(
+ subscription: Subscription,
+ verifyUrl: string,
+ ): Promise<void>;
+
+ // Send notifications to multiple subscribers (batched)
+ sendNotifications(
+ subscriptions: Subscription[],
+ pageUpdate: PageUpdate,
+ ): Promise<void>;
+}
diff --git a/packages/subscriptions/tsconfig.json b/packages/subscriptions/tsconfig.json
new file mode 100644
index 000000000..0b8670d63
--- /dev/null
+++ b/packages/subscriptions/tsconfig.json
@@ -0,0 +1,5 @@
+{
+ "extends": "@openstatus/tsconfig/react-library.json",
+ "include": [".", "src"],
+ "exclude": ["dist", "build", "node_modules"]
+}
diff --git a/packages/ui/src/components/ui/button.tsx b/packages/ui/src/components/ui/button.tsx
index 89e974f65..5fb967ef4 100644
--- a/packages/ui/src/components/ui/button.tsx
+++ b/packages/ui/src/components/ui/button.tsx
@@ -2,7 +2,7 @@ import { Slot } from "@radix-ui/react-slot";
import { type VariantProps, cva } from "class-variance-authority";
import type * as React from "react";
-import { cn } from "@/lib/utils";
+import { cn } from "@openstatus/ui/lib/utils";
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 77ac43e78..0cae14fe8 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -536,6 +536,9 @@ importers:
'@openstatus/regions':
specifier: workspace:*
version: link:../../packages/regions
+ '@openstatus/subscriptions':
+ specifier: workspace:*
+ version: link:../../packages/subscriptions
'@openstatus/tinybird':
specifier: workspace:*
version: link:../../packages/tinybird
@@ -1318,6 +1321,9 @@ importers:
'@openstatus/regions':
specifier: workspace:*
version: link:../regions
+ '@openstatus/subscriptions':
+ specifier: workspace:*
+ version: link:../subscriptions
'@openstatus/tinybird':
specifier: workspace:*
version: link:../tinybird
@@ -2017,6 +2023,28 @@ importers:
specifier: latest
version: 1.3.9
+ packages/subscriptions:
+ dependencies:
+ '@openstatus/db':
+ specifier: workspace:*
+ version: link:../db
+ '@openstatus/emails':
+ specifier: workspace:*
+ version: link:../emails
+ zod:
+ specifier: 4.1.13
+ version: 4.1.13
+ devDependencies:
+ '@openstatus/tsconfig':
+ specifier: workspace:*
+ version: link:../tsconfig
+ '@types/bun':
+ specifier: latest
+ version: 1.3.9
+ typescript:
+ specifier: 5.9.3
+ version: 5.9.3
+
packages/theme-store:
devDependencies:
'@openstatus/tsconfig':