Skip to content

Open-source status page, incident response and uptime monitoring

feat(services): migrate status-report domain (PR 1/N) (#2101)

Maximilian Kaske8a353d502997
diff --git a/apps/server/Dockerfile b/apps/server/Dockerfile
index f709a64dd..81c9c19bf 100644
--- a/apps/server/Dockerfile
+++ b/apps/server/Dockerfile
@@ -41,6 +41,8 @@ RUN \
--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=bind,target=packages/locales/package.json,source=packages/locales/package.json \
+ --mount=type=bind,target=packages/services/package.json,source=packages/services/package.json \
+ --mount=type=bind,target=packages/importers/package.json,source=packages/importers/package.json \
--mount=type=cache,target=/root/.bun/install/cache,sharing=locked \
bun install --production --frozen-lockfile --verbose
@@ -62,11 +64,11 @@ COPY \
RUN bun build --compile --sourcemap src/index.ts --outfile=app
# runtime
-FROM debian@sha256:4333240150a6924f878e05ec2c998aec95238010e0e4d2fec6161c90128c4652 AS runtime
+FROM debian@sha256:1a4701c321b1d28b1ff5f0230e766791e4b79b1d4c6c7a70064f4b297b1a330f AS runtime
LABEL \
io.dofigen.version="2.7.0" \
org.opencontainers.image.authors="OpenStatus Team" \
- org.opencontainers.image.base.digest="sha256:4333240150a6924f878e05ec2c998aec95238010e0e4d2fec6161c90128c4652" \
+ org.opencontainers.image.base.digest="sha256:1a4701c321b1d28b1ff5f0230e766791e4b79b1d4c6c7a70064f4b297b1a330f" \
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 75ce09238..542b6342f 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.stage: install
+ org.opencontainers.image.base.name: docker.io/oven/bun:1.3.6
org.opencontainers.image.base.digest: sha256:f20d9cf365ab35529384f1717687c739c92e6f39157a35a95ef06f4049a10e4a
workdir: /app/
run:
@@ -86,14 +86,18 @@ effective: |
source: packages/theme-store/package.json
- target: packages/locales/package.json
source: packages/locales/package.json
+ - target: packages/services/package.json
+ source: packages/services/package.json
+ - target: packages/importers/package.json
+ source: packages/importers/package.json
build:
fromImage:
path: oven/bun
digest: sha256:f20d9cf365ab35529384f1717687c739c92e6f39157a35a95ef06f4049a10e4a
label:
- org.opencontainers.image.base.name: docker.io/oven/bun:1.3.6
org.opencontainers.image.stage: build
org.opencontainers.image.base.digest: sha256:f20d9cf365ab35529384f1717687c739c92e6f39157a35a95ef06f4049a10e4a
+ org.opencontainers.image.base.name: docker.io/oven/bun:1.3.6
workdir: /app/apps/server
env:
NODE_ENV: production
@@ -109,16 +113,16 @@ effective: |
- bun build --compile --sourcemap src/index.ts --outfile=app
fromImage:
path: debian
- digest: sha256:4333240150a6924f878e05ec2c998aec95238010e0e4d2fec6161c90128c4652
+ digest: sha256:1a4701c321b1d28b1ff5f0230e766791e4b79b1d4c6c7a70064f4b297b1a330f
label:
- org.opencontainers.image.authors: OpenStatus Team
+ io.dofigen.version: 2.7.0
org.opencontainers.image.source: https://github.com/openstatusHQ/openstatus
+ org.opencontainers.image.base.digest: sha256:1a4701c321b1d28b1ff5f0230e766791e4b79b1d4c6c7a70064f4b297b1a330f
org.opencontainers.image.base.name: docker.io/debian:bullseye-slim
- io.dofigen.version: 2.7.0
+ org.opencontainers.image.title: OpenStatus Server
org.opencontainers.image.description: REST API server with Hono framework for OpenStatus
- org.opencontainers.image.base.digest: sha256:4333240150a6924f878e05ec2c998aec95238010e0e4d2fec6161c90128c4652
org.opencontainers.image.vendor: OpenStatus
- org.opencontainers.image.title: OpenStatus Server
+ org.opencontainers.image.authors: OpenStatus Team
user:
user: '1000'
group: '1000'
@@ -145,17 +149,17 @@ effective: |
retries: 3
images:
docker.io:
- library:
- debian:
- bullseye-slim:
- digest: sha256:4333240150a6924f878e05ec2c998aec95238010e0e4d2fec6161c90128c4652
oven:
bun:
1.3.6:
digest: sha256:f20d9cf365ab35529384f1717687c739c92e6f39157a35a95ef06f4049a10e4a
+ library:
+ debian:
+ bullseye-slim:
+ digest: sha256:1a4701c321b1d28b1ff5f0230e766791e4b79b1d4c6c7a70064f4b297b1a330f
resources:
dofigen.yml:
- hash: 733fba04030ad149a064b72cece51b1e515655e1b723263c61c881e301e388da
+ hash: 0b4934ac4087020f7814554afb8423bb611e051830041107fdecd32afaa8dc28
content: |
# Files to exclude from Docker context
ignore:
@@ -208,6 +212,8 @@ resources:
- packages/assertions/package.json
- packages/theme-store/package.json
- packages/locales/package.json
+ - packages/services/package.json
+ - packages/importers/package.json
run: bun install --production --frozen-lockfile --verbose
cache:
- /root/.bun/install/cache
diff --git a/apps/server/dofigen.yml b/apps/server/dofigen.yml
index 61cf3b550..5827aedad 100644
--- a/apps/server/dofigen.yml
+++ b/apps/server/dofigen.yml
@@ -49,6 +49,8 @@ builders:
- packages/assertions/package.json
- packages/theme-store/package.json
- packages/locales/package.json
+ - packages/services/package.json
+ - packages/importers/package.json
run: bun install --production --frozen-lockfile --verbose
cache:
- /root/.bun/install/cache
diff --git a/apps/server/package.json b/apps/server/package.json
index 292d6be13..0b5c88a46 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/services": "workspace:*",
"@openstatus/subscriptions": "workspace:*",
"@openstatus/notification-discord": "workspace:*",
"@openstatus/notification-google-chat": "workspace:*",
diff --git a/apps/server/src/routes/rpc/adapter.ts b/apps/server/src/routes/rpc/adapter.ts
new file mode 100644
index 000000000..030949737
--- /dev/null
+++ b/apps/server/src/routes/rpc/adapter.ts
@@ -0,0 +1,57 @@
+import { Code, ConnectError } from "@connectrpc/connect";
+import { type ServiceContext, ServiceError } from "@openstatus/services";
+import { ZodError } from "zod";
+
+import type { RpcContext } from "./interceptors";
+
+/**
+ * Translate Connect RPC auth context into a `ServiceContext`.
+ *
+ * TODO: Once the auth interceptor captures the API key id, expose it here
+ * as `actor.keyId`. Until then we synthesise `ws:<workspaceId>` so audit
+ * records still have a non-empty actor identifier — see the plan's open
+ * question "Does Connect's auth interceptor capture API key ID today?".
+ */
+export function toServiceCtx(rpcCtx: RpcContext): ServiceContext {
+ return {
+ workspace: rpcCtx.workspace,
+ actor: { type: "apiKey", keyId: `ws:${rpcCtx.workspace.id}` },
+ requestId: rpcCtx.requestId,
+ };
+}
+
+/**
+ * Map any error thrown by a service call to a `ConnectError`. Preserves the
+ * existing Connect error surface — granular reasons carried by the caller's
+ * per-handler error helpers (in `errors.ts`) still bypass this mapper since
+ * they throw `ConnectError` directly.
+ */
+export function toConnectError(err: unknown): never {
+ if (err instanceof ConnectError) throw err;
+ if (err instanceof ZodError) {
+ throw new ConnectError(
+ `Invalid request: ${err.message}`,
+ Code.InvalidArgument,
+ );
+ }
+ if (err instanceof ServiceError) {
+ switch (err.code) {
+ case "NOT_FOUND":
+ throw new ConnectError(err.message, Code.NotFound);
+ case "FORBIDDEN":
+ throw new ConnectError(err.message, Code.PermissionDenied);
+ case "UNAUTHORIZED":
+ throw new ConnectError(err.message, Code.Unauthenticated);
+ case "CONFLICT":
+ throw new ConnectError(err.message, Code.InvalidArgument);
+ case "VALIDATION":
+ throw new ConnectError(err.message, Code.InvalidArgument);
+ case "LIMIT_EXCEEDED":
+ throw new ConnectError(err.message, Code.ResourceExhausted);
+ case "INTERNAL":
+ throw new ConnectError(err.message, Code.Internal);
+ }
+ }
+ const message = err instanceof Error ? err.message : "Unknown error";
+ throw new ConnectError(message, Code.Internal);
+}
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 1acf3f9b7..5ff15060a 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
@@ -394,7 +394,10 @@ describe("StatusReportService.CreateStatusReport", () => {
expect(res.status).toBe(400);
const data = await res.json();
- expect(data.message).toContain("does not match the page ID");
+ // Service throws `ConflictError("pageId X does not match the page
+ // (Y) of the selected components.")` — assertion matches the new
+ // service-layer wording.
+ expect(data.message).toContain("does not match the page");
});
test("creates status report when pageId matches component page", 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 4f42bf8e9..6a01a3b46 100644
--- a/apps/server/src/routes/rpc/services/status-report/index.ts
+++ b/apps/server/src/routes/rpc/services/status-report/index.ts
@@ -1,178 +1,25 @@
-import type { ServiceImpl } from "@connectrpc/connect";
-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 {
- pageComponent,
- statusReport,
- statusReportUpdate,
- statusReportsToPageComponents,
-} from "@openstatus/db/src/schema";
-import type { Limits } from "@openstatus/db/src/schema/plan/schema";
+import { Code, ConnectError, type ServiceImpl } from "@connectrpc/connect";
import type { StatusReportService } from "@openstatus/proto/status_report/v1";
import { StatusReportStatus } from "@openstatus/proto/status_report/v1";
-
-import { dispatchStatusReportUpdate } from "@openstatus/subscriptions";
-
+import {
+ addStatusReportUpdate,
+ createStatusReport,
+ deleteStatusReport,
+ getStatusReport,
+ listStatusReports,
+ notifyStatusReport,
+ updateStatusReport,
+} from "@openstatus/services/status-report";
+
+import { toConnectError, toServiceCtx } from "../../adapter";
import { getRpcContext } from "../../interceptors";
import {
dbReportToProto,
dbReportToProtoSummary,
protoStatusToDb,
} from "./converters";
-import {
- invalidDateFormatError,
- pageComponentNotFoundError,
- pageComponentsMixedPagesError,
- pageIdComponentMismatchError,
- statusReportCreateFailedError,
- statusReportIdRequiredError,
- statusReportNotFoundError,
- statusReportUpdateFailedError,
-} from "./errors";
-
-/**
- * Helper to send status report notifications to page subscribers.
- * Uses the subscription dispatcher for component-aware filtering.
- */
-export async function sendStatusReportNotification(params: {
- statusReportUpdateId: number;
- limits: Limits;
-}) {
- const { statusReportUpdateId, limits } = params;
-
- if (!limits["status-subscribers"]) {
- return;
- }
-
- await dispatchStatusReportUpdate(statusReportUpdateId);
-}
-
-/**
- * Helper to get a status report by ID with workspace scope.
- */
-export async function getStatusReportById(id: number, workspaceId: number) {
- return db
- .select()
- .from(statusReport)
- .where(
- and(eq(statusReport.id, id), eq(statusReport.workspaceId, workspaceId)),
- )
- .get();
-}
-
-/**
- * Helper to get page component IDs for a status report.
- */
-export async function getPageComponentIdsForReport(statusReportId: number) {
- const components = await db
- .select({ pageComponentId: statusReportsToPageComponents.pageComponentId })
- .from(statusReportsToPageComponents)
- .where(eq(statusReportsToPageComponents.statusReportId, statusReportId))
- .all();
-
- return components.map((c) => String(c.pageComponentId));
-}
-
-/**
- * Helper to get updates for a status report, ordered by date descending.
- */
-async function getUpdatesForReport(statusReportId: number) {
- return db
- .select()
- .from(statusReportUpdate)
- .where(eq(statusReportUpdate.statusReportId, statusReportId))
- .orderBy(desc(statusReportUpdate.date))
- .all();
-}
-
-/**
- * Result of validating page component IDs.
- */
-interface ValidatedPageComponents {
- componentIds: number[];
- pageId: number | null;
-}
-
-/**
- * Helper to validate page component IDs belong to the workspace and same page.
- * Accepts an optional transaction to ensure atomicity with subsequent operations.
- */
-export async function validatePageComponentIds(
- pageComponentIds: string[],
- workspaceId: number,
- tx: DB | Transaction = db,
-): Promise<ValidatedPageComponents> {
- if (pageComponentIds.length === 0) {
- return { componentIds: [], pageId: null };
- }
-
- const numericIds = pageComponentIds.map((id) => Number(id));
-
- const validComponents = await tx
- .select({ id: pageComponent.id, pageId: pageComponent.pageId })
- .from(pageComponent)
- .where(
- and(
- inArray(pageComponent.id, numericIds),
- eq(pageComponent.workspaceId, workspaceId),
- ),
- )
- .all();
-
- const validComponentsMap = new Map(
- validComponents.map((c) => [c.id, c.pageId]),
- );
-
- // Check all requested IDs exist
- for (const id of numericIds) {
- if (!validComponentsMap.has(id)) {
- throw pageComponentNotFoundError(String(id));
- }
- }
-
- // Validate all components belong to the same page
- const pageIds = new Set(validComponents.map((c) => c.pageId));
- if (pageIds.size > 1) {
- throw pageComponentsMixedPagesError();
- }
-
- const pageId = validComponents[0]?.pageId ?? null;
+import { invalidDateFormatError, statusReportIdRequiredError } from "./errors";
- return { componentIds: numericIds, pageId };
-}
-
-/**
- * Helper to update page component associations for a status report.
- * Accepts an optional transaction to ensure atomicity.
- */
-export async function updatePageComponentAssociations(
- statusReportId: number,
- pageComponentIds: number[],
- tx: DB | Transaction = db,
-) {
- // Delete existing associations
- await tx
- .delete(statusReportsToPageComponents)
- .where(eq(statusReportsToPageComponents.statusReportId, statusReportId));
-
- // Insert new associations
- if (pageComponentIds.length > 0) {
- await tx.insert(statusReportsToPageComponents).values(
- pageComponentIds.map((pageComponentId) => ({
- statusReportId,
- pageComponentId,
- })),
- );
- }
-}
-
-/**
- * Parses and validates a date string.
- * Throws invalidDateFormatError if the date is invalid.
- */
function parseDate(dateString: string): Date {
const date = new Date(dateString);
if (Number.isNaN(date.getTime())) {
@@ -181,336 +28,213 @@ function parseDate(dateString: string): Date {
return date;
}
-/**
- * Status report service implementation for ConnectRPC.
- */
+function parsePageComponentIds(ids: ReadonlyArray<string>): number[] {
+ return ids.map((id) => {
+ const n = Number(id);
+ if (!Number.isFinite(n)) {
+ throw new ConnectError(
+ `Invalid page component id: "${id}"`,
+ Code.InvalidArgument,
+ );
+ }
+ return n;
+ });
+}
+
export const statusReportServiceImpl: ServiceImpl<typeof StatusReportService> =
{
async createStatusReport(req, ctx) {
- const rpcCtx = getRpcContext(ctx);
- const workspaceId = rpcCtx.workspace.id;
-
- // Parse and validate the date before the transaction
- const date = parseDate(req.date);
-
- // Create status report, associations, and initial update in a transaction
- const { report: newReport, newUpdate } = await db.transaction(
- async (tx) => {
- // Validate page component IDs inside transaction to prevent TOCTOU race condition
- const validatedComponents = await validatePageComponentIds(
- req.pageComponentIds,
- workspaceId,
- tx,
- );
-
- // Validate that provided pageId matches the components' page
- const derivedPageId = validatedComponents.pageId;
- const providedPageId = req.pageId?.trim();
- if (
- derivedPageId !== null &&
- providedPageId &&
- providedPageId !== "" &&
- Number(providedPageId) !== derivedPageId
- ) {
- throw pageIdComponentMismatchError(
- providedPageId,
- String(derivedPageId),
- );
- }
-
- // 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
- .insert(statusReport)
- .values({
- workspaceId,
- pageId,
- title: req.title,
- status: protoStatusToDb(req.status),
- })
- .returning()
- .get();
+ try {
+ const rpcCtx = getRpcContext(ctx);
+ const sCtx = toServiceCtx(rpcCtx);
- if (!report) {
- throw statusReportCreateFailedError();
- }
-
- // Create page component associations
- await updatePageComponentAssociations(
- report.id,
- validatedComponents.componentIds,
- tx,
- );
-
- // Create the initial update
- const newUpdate = await tx
- .insert(statusReportUpdate)
- .values({
- statusReportId: report.id,
- status: protoStatusToDb(req.status),
- date,
- message: req.message,
- })
- .returning()
- .get();
+ const pageId = req.pageId?.trim() ? Number(req.pageId.trim()) : null;
+ if (pageId === null) {
+ throw statusReportIdRequiredError();
+ }
- if (!newUpdate) {
- throw statusReportCreateFailedError();
- }
+ const { statusReport, initialUpdate } = await createStatusReport({
+ ctx: sCtx,
+ input: {
+ title: req.title,
+ status: protoStatusToDb(req.status),
+ message: req.message,
+ date: parseDate(req.date),
+ pageId,
+ pageComponentIds: parsePageComponentIds(req.pageComponentIds),
+ },
+ });
- return { report, newUpdate, pageId };
- },
- );
+ if (req.notify) {
+ await notifyStatusReport({
+ ctx: sCtx,
+ input: { statusReportUpdateId: initialUpdate.id },
+ });
+ }
- // Send notifications if requested (outside transaction)
- if (req.notify) {
- await sendStatusReportNotification({
- statusReportUpdateId: newUpdate.id,
- limits: rpcCtx.workspace.limits,
+ const full = await getStatusReport({
+ ctx: sCtx,
+ input: { id: statusReport.id },
});
+ return {
+ statusReport: dbReportToProto(
+ full,
+ full.pageComponentIds.map(String),
+ full.updates,
+ ),
+ };
+ } catch (err) {
+ toConnectError(err);
}
-
- // Fetch the updates for the response
- const updates = await getUpdatesForReport(newReport.id);
-
- return {
- statusReport: dbReportToProto(newReport, req.pageComponentIds, updates),
- };
},
async getStatusReport(req, ctx) {
- const rpcCtx = getRpcContext(ctx);
- const workspaceId = rpcCtx.workspace.id;
-
- if (!req.id || req.id.trim() === "") {
- throw statusReportIdRequiredError();
- }
+ try {
+ const rpcCtx = getRpcContext(ctx);
+ if (!req.id || req.id.trim() === "") {
+ throw statusReportIdRequiredError();
+ }
- const report = await getStatusReportById(Number(req.id), workspaceId);
- if (!report) {
- throw statusReportNotFoundError(req.id);
+ const full = await getStatusReport({
+ ctx: toServiceCtx(rpcCtx),
+ input: { id: Number(req.id) },
+ });
+ return {
+ statusReport: dbReportToProto(
+ full,
+ full.pageComponentIds.map(String),
+ full.updates,
+ ),
+ };
+ } catch (err) {
+ toConnectError(err);
}
-
- const pageComponentIds = await getPageComponentIdsForReport(report.id);
- const updates = await getUpdatesForReport(report.id);
-
- return {
- statusReport: dbReportToProto(report, pageComponentIds, updates),
- };
},
async listStatusReports(req, ctx) {
- const rpcCtx = getRpcContext(ctx);
- const workspaceId = rpcCtx.workspace.id;
-
- const limit = Math.min(Math.max(req.limit ?? 50, 1), 100);
- const offset = req.offset ?? 0;
-
- // Build conditions
- const conditions = [eq(statusReport.workspaceId, workspaceId)];
+ try {
+ const rpcCtx = getRpcContext(ctx);
+
+ const statuses =
+ req.statuses.length > 0
+ ? req.statuses
+ .filter((s) => s !== StatusReportStatus.UNSPECIFIED)
+ .map(protoStatusToDb)
+ : [];
+
+ const { items, totalSize } = await listStatusReports({
+ ctx: toServiceCtx(rpcCtx),
+ input: {
+ limit: Math.min(Math.max(req.limit ?? 50, 1), 100),
+ offset: req.offset ?? 0,
+ statuses,
+ order: "desc",
+ },
+ });
- // Add status filter if provided
- if (req.statuses.length > 0) {
- const dbStatuses = req.statuses
- .filter((s) => s !== StatusReportStatus.UNSPECIFIED)
- .map(protoStatusToDb);
- if (dbStatuses.length > 0) {
- conditions.push(inArray(statusReport.status, dbStatuses));
- }
+ return {
+ statusReports: items.map((r) =>
+ dbReportToProtoSummary(r, r.pageComponentIds.map(String)),
+ ),
+ totalSize,
+ };
+ } catch (err) {
+ toConnectError(err);
}
-
- // Get total count
- const countResult = await db
- .select({ count: sql<number>`count(*)` })
- .from(statusReport)
- .where(and(...conditions))
- .get();
-
- const totalCount = countResult?.count ?? 0;
-
- // Get status reports
- const reports = await db
- .select()
- .from(statusReport)
- .where(and(...conditions))
- .orderBy(desc(statusReport.createdAt))
- .limit(limit)
- .offset(offset)
- .all();
-
- // Get page component IDs for each report
- const statusReports = await Promise.all(
- reports.map(async (report) => {
- const pageComponentIds = await getPageComponentIdsForReport(
- report.id,
- );
- return dbReportToProtoSummary(report, pageComponentIds);
- }),
- );
-
- return {
- statusReports,
- totalSize: totalCount,
- };
},
async updateStatusReport(req, ctx) {
- const rpcCtx = getRpcContext(ctx);
- const workspaceId = rpcCtx.workspace.id;
-
- if (!req.id || req.id.trim() === "") {
- throw statusReportIdRequiredError();
- }
-
- const report = await getStatusReportById(Number(req.id), workspaceId);
- if (!report) {
- throw statusReportNotFoundError(req.id);
- }
-
- // Update report, associations in a transaction
- const updatedReport = await db.transaction(async (tx) => {
- const updateValues: Record<string, unknown> = {
- updatedAt: new Date(),
- };
-
- if (req.title !== undefined && req.title !== "") {
- updateValues.title = req.title;
+ try {
+ const rpcCtx = getRpcContext(ctx);
+ const sCtx = toServiceCtx(rpcCtx);
+ if (!req.id || req.id.trim() === "") {
+ throw statusReportIdRequiredError();
}
- if (req.updatePageComponentIds) {
- const validatedComponents = await validatePageComponentIds(
- req.pageComponentIds,
- workspaceId,
- tx,
- );
-
- updateValues.pageId = validatedComponents.pageId;
-
- await updatePageComponentAssociations(
- report.id,
- validatedComponents.componentIds,
- tx,
- );
- }
-
- const updated = await tx
- .update(statusReport)
- .set(updateValues)
- .where(eq(statusReport.id, report.id))
- .returning()
- .get();
-
- if (!updated) {
- throw statusReportUpdateFailedError(req.id);
- }
-
- return updated;
- });
-
- // Fetch updated data
- const pageComponentIds = await getPageComponentIdsForReport(
- updatedReport.id,
- );
- const updates = await getUpdatesForReport(updatedReport.id);
+ const id = Number(req.id);
+ await updateStatusReport({
+ ctx: sCtx,
+ input: {
+ id,
+ title:
+ req.title !== undefined && req.title !== ""
+ ? req.title
+ : undefined,
+ pageComponentIds: req.updatePageComponentIds
+ ? parsePageComponentIds(req.pageComponentIds)
+ : undefined,
+ },
+ });
- return {
- statusReport: dbReportToProto(updatedReport, pageComponentIds, updates),
- };
+ const full = await getStatusReport({ ctx: sCtx, input: { id } });
+ return {
+ statusReport: dbReportToProto(
+ full,
+ full.pageComponentIds.map(String),
+ full.updates,
+ ),
+ };
+ } catch (err) {
+ toConnectError(err);
+ }
},
async deleteStatusReport(req, ctx) {
- const rpcCtx = getRpcContext(ctx);
- const workspaceId = rpcCtx.workspace.id;
-
- if (!req.id || req.id.trim() === "") {
- throw statusReportIdRequiredError();
- }
-
- const report = await getStatusReportById(Number(req.id), workspaceId);
- if (!report) {
- throw statusReportNotFoundError(req.id);
+ try {
+ const rpcCtx = getRpcContext(ctx);
+ if (!req.id || req.id.trim() === "") {
+ throw statusReportIdRequiredError();
+ }
+ await deleteStatusReport({
+ ctx: toServiceCtx(rpcCtx),
+ input: { id: Number(req.id) },
+ });
+ return { success: true };
+ } catch (err) {
+ toConnectError(err);
}
-
- // Delete the status report (cascade will delete updates and associations)
- await db.delete(statusReport).where(eq(statusReport.id, report.id));
-
- return { success: true };
},
async addStatusReportUpdate(req, ctx) {
- const rpcCtx = getRpcContext(ctx);
- const workspaceId = rpcCtx.workspace.id;
-
- if (!req.statusReportId || req.statusReportId.trim() === "") {
- throw statusReportIdRequiredError();
- }
-
- const report = await getStatusReportById(
- Number(req.statusReportId),
- workspaceId,
- );
- if (!report) {
- throw statusReportNotFoundError(req.statusReportId);
- }
-
- // Parse and validate the date or use current time
- const date = req.date ? parseDate(req.date) : new Date();
-
- // Create update and update status report in a transaction
- const { updatedReport, newUpdate } = await db.transaction(async (tx) => {
- // Create the update
- const newUpdate = await tx
- .insert(statusReportUpdate)
- .values({
- statusReportId: report.id,
- status: protoStatusToDb(req.status),
- date,
- message: req.message,
- })
- .returning()
- .get();
-
- if (!newUpdate) {
- throw statusReportUpdateFailedError(req.statusReportId);
+ try {
+ const rpcCtx = getRpcContext(ctx);
+ const sCtx = toServiceCtx(rpcCtx);
+ if (!req.statusReportId || req.statusReportId.trim() === "") {
+ throw statusReportIdRequiredError();
}
- // Update the status report's status and updatedAt
- const updated = await tx
- .update(statusReport)
- .set({
- status: protoStatusToDb(req.status),
- updatedAt: new Date(),
- })
- .where(eq(statusReport.id, report.id))
- .returning()
- .get();
-
- if (!updated) {
- throw statusReportUpdateFailedError(req.statusReportId);
+ const statusReportId = Number(req.statusReportId);
+ const { statusReport: updatedReport, statusReportUpdate: newUpdate } =
+ await addStatusReportUpdate({
+ ctx: sCtx,
+ input: {
+ statusReportId,
+ status: protoStatusToDb(req.status),
+ message: req.message,
+ date: req.date ? parseDate(req.date) : undefined,
+ },
+ });
+
+ if (req.notify && updatedReport.pageId) {
+ await notifyStatusReport({
+ ctx: sCtx,
+ input: { statusReportUpdateId: newUpdate.id },
+ });
}
- return { updatedReport: updated, newUpdate };
- });
-
- // Send notifications if requested (outside transaction)
- if (req.notify && updatedReport.pageId) {
- await sendStatusReportNotification({
- statusReportUpdateId: newUpdate.id,
- limits: rpcCtx.workspace.limits,
+ const full = await getStatusReport({
+ ctx: sCtx,
+ input: { id: statusReportId },
});
+ return {
+ statusReport: dbReportToProto(
+ full,
+ full.pageComponentIds.map(String),
+ full.updates,
+ ),
+ };
+ } catch (err) {
+ toConnectError(err);
}
-
- // Fetch all updates
- const pageComponentIds = await getPageComponentIdsForReport(
- updatedReport.id,
- );
- const updates = await getUpdatesForReport(updatedReport.id);
-
- return {
- statusReport: dbReportToProto(updatedReport, pageComponentIds, updates),
- };
},
};
diff --git a/apps/server/src/routes/slack/interactions.ts b/apps/server/src/routes/slack/interactions.ts
index 2900f76bc..088c100a0 100644
--- a/apps/server/src/routes/slack/interactions.ts
+++ b/apps/server/src/routes/slack/interactions.ts
@@ -4,20 +4,20 @@ import {
maintenancesToPageComponents,
page,
pageComponent,
- statusReport,
- statusReportUpdate,
} from "@openstatus/db/src/schema";
+import {
+ addStatusReportUpdate,
+ createStatusReport,
+ notifyStatusReport,
+ resolveStatusReport,
+ updateStatusReport,
+} from "@openstatus/services/status-report";
import { WebClient } from "@slack/web-api";
import type { Context } from "hono";
import { sendMaintenanceNotification } from "../rpc/services/maintenance";
-import {
- getStatusReportById,
- sendStatusReportNotification,
- updatePageComponentAssociations,
- validatePageComponentIds,
-} from "../rpc/services/status-report";
import { consume, get } from "./confirmation-store";
import type { PendingAction } from "./confirmation-store";
+import { toServiceCtx, toSlackMessage } from "./service-adapter";
import { resolveWorkspace } from "./workspace-resolver";
interface SlackInteractionPayload {
@@ -112,13 +112,16 @@ export async function handleSlackInteraction(c: Context) {
const notify = type === "approve_notify";
try {
- await executeAction(consumed, notify, slack, channelId, messageTs);
+ await executeAction(consumed, notify, slack, channelId, messageTs, {
+ slackUserId: userId,
+ teamId,
+ });
} catch (err) {
console.error("[slack] action execution error:", err);
await slack.chat.update({
channel: channelId,
ts: messageTs,
- text: ":x: Something went wrong. Please try again.",
+ text: toSlackMessage(err),
blocks: [],
});
}
@@ -159,84 +162,57 @@ async function executeAction(
slack: WebClient,
channelId: string,
messageTs: string,
+ origin: { slackUserId: string; teamId: string | undefined },
) {
const { action, workspaceId, limits } = pending;
+ // Hoisted out of the switch: every service-backed branch below uses
+ // the same ctx, and `toServiceCtx` loads the workspace row from the
+ // db. Computing it once halves the per-action db traffic. Lazy enough
+ // — the `createMaintenance` branch still goes direct to db (migrates
+ // in PR 2) and doesn't need ctx, but the extra lookup there is
+ // negligible against the maintenance write volume.
+ const ctx = await toServiceCtx({
+ pending,
+ slackUserId: origin.slackUserId,
+ teamId: origin.teamId,
+ });
+
switch (action.type) {
case "createStatusReport": {
const { title, status, message, pageId, pageComponentIds } =
action.params;
+ if (pageId == null) {
+ throw new Error("pageId is required to create a status report");
+ }
- const result = await db.transaction(async (tx) => {
- const validated = pageComponentIds?.length
- ? await validatePageComponentIds(pageComponentIds, workspaceId, tx)
- : { componentIds: [], pageId: null };
-
- // Validate that provided pageId matches the components' page
- if (
- validated.pageId !== null &&
- pageId != null &&
- pageId !== validated.pageId
- ) {
- throw new Error(
- `pageId ${pageId} does not match the page (${validated.pageId}) that the selected components belong to`,
- );
- }
-
- // Prefer the validated pageId derived from components
- const resolvedPageId = validated.pageId ?? pageId;
-
- const report = await tx
- .insert(statusReport)
- .values({
- workspaceId,
- pageId: resolvedPageId,
- title,
- status,
- })
- .returning()
- .get();
-
- if (validated.componentIds.length > 0) {
- await updatePageComponentAssociations(
- report.id,
- validated.componentIds,
- tx,
- );
- }
-
- const newUpdate = await tx
- .insert(statusReportUpdate)
- .values({
- statusReportId: report.id,
- status,
- date: new Date(),
- message,
- })
- .returning()
- .get();
-
- return { report, updateId: newUpdate.id };
+ const { statusReport: report, initialUpdate } = await createStatusReport({
+ ctx,
+ input: {
+ title,
+ status,
+ message,
+ date: new Date(),
+ pageId,
+ pageComponentIds: pageComponentIds?.map((id) => Number(id)) ?? [],
+ },
});
- if (!result || !result.report.pageId) {
- throw new Error("Failed to create status report");
- }
+
if (notify) {
- await sendStatusReportNotification({
- statusReportUpdateId: result.updateId,
- limits,
+ await notifyStatusReport({
+ ctx,
+ input: { statusReportUpdateId: initialUpdate.id },
});
}
- const reportUrl = await getReportUrl(
- result.report.pageId,
- result.report.id,
- );
+ const reportUrl = report.pageId
+ ? await getReportUrl(report.pageId, report.id)
+ : null;
await slack.chat.update({
channel: channelId,
ts: messageTs,
- text: `:white_check_mark: Status report *${title}* created${notify ? " and subscribers notified" : ""}.\n<${reportUrl}|View on status page>`,
+ text: `:white_check_mark: Status report *${title}* created${notify ? " and subscribers notified" : ""}.${reportUrl ? `\n<${reportUrl}|View on status page>` : ""}`,
blocks: [],
});
break;
@@ -244,47 +220,27 @@ async function executeAction(
case "addStatusReportUpdate": {
const { statusReportId, status, message } = action.params;
-
- const report = await getStatusReportById(statusReportId, workspaceId);
- if (!report) {
- throw new Error("Status report not found");
- }
-
- const updateId = await db.transaction(async (tx) => {
- const newUpdate = await tx
- .insert(statusReportUpdate)
- .values({
- statusReportId: report.id,
- status,
- date: new Date(),
- message,
- })
- .returning()
- .get();
-
- await tx
- .update(statusReport)
- .set({ status, updatedAt: new Date() })
- .where(eq(statusReport.id, report.id));
-
- return newUpdate.id;
- });
+ const { statusReport: report, statusReportUpdate: update } =
+ await addStatusReportUpdate({
+ ctx,
+ input: { statusReportId, status, message },
+ });
if (notify && report.pageId) {
- await sendStatusReportNotification({
- statusReportUpdateId: updateId,
- limits,
+ await notifyStatusReport({
+ ctx,
+ input: { statusReportUpdateId: update.id },
});
}
- const updateReportUrl = report.pageId
+ const reportUrl = report.pageId
? await getReportUrl(report.pageId, report.id)
: null;
await slack.chat.update({
channel: channelId,
ts: messageTs,
- text: `:white_check_mark: Update added to *${report.title}* (${status})${notify ? " and subscribers notified" : ""}.\n>${message}${updateReportUrl ? `\n<${updateReportUrl}|View on status page>` : ""}`,
+ text: `:white_check_mark: Update added to *${report.title}* (${status})${notify ? " and subscribers notified" : ""}.\n>${message}${reportUrl ? `\n<${reportUrl}|View on status page>` : ""}`,
blocks: [],
});
break;
@@ -292,35 +248,15 @@ async function executeAction(
case "updateStatusReport": {
const { statusReportId, title, pageComponentIds } = action.params;
-
- const report = await getStatusReportById(statusReportId, workspaceId);
- if (!report) {
- throw new Error("Status report not found");
- }
-
- await db.transaction(async (tx) => {
- if (pageComponentIds) {
- const validated = await validatePageComponentIds(
- pageComponentIds,
- workspaceId,
- tx,
- );
- await updatePageComponentAssociations(
- report.id,
- validated.componentIds,
- tx,
- );
- }
-
- const updateValues: Record<string, unknown> = {
- updatedAt: new Date(),
- };
- if (title) updateValues.title = title;
-
- await tx
- .update(statusReport)
- .set(updateValues)
- .where(eq(statusReport.id, report.id));
+ const report = await updateStatusReport({
+ ctx,
+ input: {
+ id: statusReportId,
+ title: title ?? undefined,
+ pageComponentIds: pageComponentIds
+ ? pageComponentIds.map((id) => Number(id))
+ : undefined,
+ },
});
await slack.chat.update({
@@ -334,53 +270,34 @@ async function executeAction(
case "resolveStatusReport": {
const { statusReportId, message } = action.params;
-
- const report = await getStatusReportById(statusReportId, workspaceId);
- if (!report) {
- throw new Error("Status report not found");
- }
-
- const resolveUpdateId = await db.transaction(async (tx) => {
- const newUpdate = await tx
- .insert(statusReportUpdate)
- .values({
- statusReportId: report.id,
- status: "resolved",
- date: new Date(),
- message,
- })
- .returning()
- .get();
-
- await tx
- .update(statusReport)
- .set({ status: "resolved", updatedAt: new Date() })
- .where(eq(statusReport.id, report.id));
-
- return newUpdate.id;
- });
+ const { statusReport: report, statusReportUpdate: update } =
+ await resolveStatusReport({
+ ctx,
+ input: { statusReportId, message },
+ });
if (notify && report.pageId) {
- await sendStatusReportNotification({
- statusReportUpdateId: resolveUpdateId,
- limits,
+ await notifyStatusReport({
+ ctx,
+ input: { statusReportUpdateId: update.id },
});
}
- const resolveReportUrl = report.pageId
+ const reportUrl = report.pageId
? await getReportUrl(report.pageId, report.id)
: null;
await slack.chat.update({
channel: channelId,
ts: messageTs,
- text: `:white_check_mark: *${report.title}* resolved${notify ? " and subscribers notified" : ""}.${message ? `\n>${message}` : ""}${resolveReportUrl ? `\n<${resolveReportUrl}|View on status page>` : ""}`,
+ text: `:white_check_mark: *${report.title}* resolved${notify ? " and subscribers notified" : ""}.${message ? `\n>${message}` : ""}${reportUrl ? `\n<${reportUrl}|View on status page>` : ""}`,
blocks: [],
});
break;
}
case "createMaintenance": {
+ // Maintenance migrates in PR 2; still writes to db directly here.
const {
title,
message,
diff --git a/apps/server/src/routes/slack/service-adapter.ts b/apps/server/src/routes/slack/service-adapter.ts
new file mode 100644
index 000000000..93540be09
--- /dev/null
+++ b/apps/server/src/routes/slack/service-adapter.ts
@@ -0,0 +1,75 @@
+import { db, eq } from "@openstatus/db";
+import {
+ selectWorkspaceSchema,
+ workspace as workspaceTable,
+} from "@openstatus/db/src/schema";
+import { type ServiceContext, ServiceError } from "@openstatus/services";
+import { ZodError } from "zod";
+
+import type { PendingAction } from "./confirmation-store";
+
+/**
+ * Build a `ServiceContext` for a Slack-originated action. Loads the
+ * workspace fresh since `PendingAction` only stores its id, and we want
+ * services to see the latest plan/limits state at execution time.
+ */
+export async function toServiceCtx(args: {
+ pending: PendingAction;
+ slackUserId: string;
+ teamId: string | undefined;
+ requestId?: string;
+}): Promise<ServiceContext> {
+ const row = await db
+ .select()
+ .from(workspaceTable)
+ .where(eq(workspaceTable.id, args.pending.workspaceId))
+ .get();
+ if (!row) {
+ throw new Error(
+ `slack: workspace ${args.pending.workspaceId} not found at action execute time`,
+ );
+ }
+ const workspace = selectWorkspaceSchema.parse(row);
+ return {
+ workspace,
+ actor: {
+ type: "slack",
+ teamId: args.teamId ?? "",
+ slackUserId: args.slackUserId,
+ },
+ requestId: args.requestId,
+ };
+}
+
+/**
+ * Convert a service (or unknown) error into a Slack-friendly message.
+ * Slack's UI is single-line plain text, so we surface actionable text only
+ * and leave full error details to logtape/Sentry observability sinks.
+ *
+ * `NOT_FOUND` messages are sanitised before reaching Slack because
+ * `NotFoundError` formats as `"<entity> <id> not found"` (e.g.
+ * `"page_component 17 not found"`) — internal row IDs have no meaning
+ * to Slack users and shouldn't leak out of the service boundary. Other
+ * `ServiceError` subclasses take a hand-written message at their call
+ * site, so they're safe to forward verbatim.
+ */
+export function toSlackMessage(err: unknown): string {
+ if (err instanceof ZodError) {
+ return ":x: The request was invalid.";
+ }
+ if (err instanceof ServiceError) {
+ switch (err.code) {
+ case "NOT_FOUND":
+ return ":x: Couldn't find what you were looking for.";
+ case "FORBIDDEN":
+ case "UNAUTHORIZED":
+ case "CONFLICT":
+ case "VALIDATION":
+ case "LIMIT_EXCEEDED":
+ return `:x: ${err.message}`;
+ case "INTERNAL":
+ return ":x: Something went wrong. Please try again.";
+ }
+ }
+ return ":x: Something went wrong. Please try again.";
+}
diff --git a/biome.jsonc b/biome.jsonc
index b2d1fb24e..845914bbe 100644
--- a/biome.jsonc
+++ b/biome.jsonc
@@ -78,5 +78,42 @@
"*.astro",
".astro"
]
- }
+ },
+ // Overrides: scope the `@openstatus/db` / drizzle import ban to files that
+ // have been migrated onto `@openstatus/services`. The include list grows
+ // one domain per migration PR; when every domain has migrated, the final
+ // PR broadens this to cover all routers/handlers and drops the db dep
+ // from `packages/api` and `apps/server` outright.
+ "overrides": [
+ {
+ "include": [
+ "packages/api/src/router/statusReport.ts",
+ "apps/server/src/routes/rpc/services/status-report/**"
+ ],
+ "ignore": [
+ // Tests legitimately manage db state for fixtures and cleanup.
+ "**/__tests__/**",
+ "**/*.test.ts"
+ ],
+ "linter": {
+ "rules": {
+ "nursery": {
+ "noRestrictedImports": {
+ "level": "error",
+ "options": {
+ "paths": {
+ "@openstatus/db": "Use @openstatus/services instead (domain has migrated to the service layer).",
+ "@openstatus/db/src/schema": "Use @openstatus/services instead.",
+ "@openstatus/db/src/schema/plan/utils": "Use @openstatus/services instead.",
+ "@openstatus/db/src/schema/plan/schema": "Use @openstatus/services instead.",
+ "@openstatus/db/src/schema/plan/config": "Use @openstatus/services instead.",
+ "drizzle-orm": "Use @openstatus/services instead."
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ ]
}
diff --git a/packages/api/package.json b/packages/api/package.json
index 076ee8da0..895867b61 100644
--- a/packages/api/package.json
+++ b/packages/api/package.json
@@ -26,6 +26,7 @@
"@openstatus/notification-twillio-whatsapp": "workspace:*",
"@openstatus/notification-webhook": "workspace:*",
"@openstatus/regions": "workspace:*",
+ "@openstatus/services": "workspace:*",
"@openstatus/subscriptions": "workspace:*",
"@openstatus/tinybird": "workspace:*",
"@openstatus/upstash": "workspace:*",
diff --git a/packages/api/src/router/email/index.ts b/packages/api/src/router/email/index.ts
index fe3f69c8c..638015f6c 100644
--- a/packages/api/src/router/email/index.ts
+++ b/packages/api/src/router/email/index.ts
@@ -6,16 +6,16 @@ import {
maintenance,
pageSubscriber,
selectWorkspaceSchema,
- statusReportUpdate,
} from "@openstatus/db/src/schema";
import { EmailClient } from "@openstatus/emails";
+import { notifyStatusReport } from "@openstatus/services/status-report";
import {
dispatchMaintenanceUpdate,
- dispatchStatusReportUpdate,
getChannel,
} from "@openstatus/subscriptions";
import { TRPCError } from "@trpc/server";
import { env } from "../../env";
+import { toServiceCtx, toTRPCError } from "../../service-adapter";
import {
createTRPCRouter,
protectedProcedure,
@@ -131,36 +131,15 @@ export const emailRouter = createTRPCRouter({
sendStatusReport: protectedProcedure
.input(z.object({ id: z.number() }))
.mutation(async (opts) => {
- const limits = opts.ctx.workspace.limits;
-
- 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",
+ try {
+ await notifyStatusReport({
+ ctx: toServiceCtx(opts.ctx),
+ input: { statusReportUpdateId: opts.input.id },
});
+ return { success: true };
+ } catch (err) {
+ toTRPCError(err);
}
-
- 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 };
}),
/**
diff --git a/packages/api/src/router/statusReport.test.ts b/packages/api/src/router/statusReport.test.ts
index 987399e1a..b1c28b97a 100644
--- a/packages/api/src/router/statusReport.test.ts
+++ b/packages/api/src/router/statusReport.test.ts
@@ -199,7 +199,11 @@ test("statusReport.create rejects pageComponents from another workspace", async
throw new Error("Should have thrown");
} catch (e) {
expect(e).toBeInstanceOf(TRPCError);
- expect((e as TRPCError).code).toBe("FORBIDDEN");
+ // Cross-workspace component IDs resolve to `NOT_FOUND` (not
+ // `FORBIDDEN`) — the service doesn't leak existence of resources
+ // in other workspaces, so callers see them as missing rather than
+ // off-limits. This is the new services-migration behavior.
+ expect((e as TRPCError).code).toBe("NOT_FOUND");
}
});
@@ -222,7 +226,8 @@ test("statusReport.updateStatus rejects pageComponents from another workspace",
throw new Error("Should have thrown");
} catch (e) {
expect(e).toBeInstanceOf(TRPCError);
- expect((e as TRPCError).code).toBe("FORBIDDEN");
+ // See cross-workspace note in `statusReport.create` test above.
+ expect((e as TRPCError).code).toBe("NOT_FOUND");
}
// Verify the report was NOT modified
diff --git a/packages/api/src/router/statusReport.ts b/packages/api/src/router/statusReport.ts
index a5124bc63..f10e38a2a 100644
--- a/packages/api/src/router/statusReport.ts
+++ b/packages/api/src/router/statusReport.ts
@@ -1,400 +1,235 @@
-import { z } from "zod";
-
-import { type SQL, and, asc, desc, eq, gte } from "@openstatus/db";
+import { Events } from "@openstatus/analytics";
+import { NotFoundError } from "@openstatus/services";
import {
- insertStatusReportUpdateSchema,
- page,
- pageComponent,
- selectPageComponentSchema,
- selectPageSchema,
- selectStatusReportSchema,
- selectStatusReportUpdateSchema,
- statusReport,
- statusReportStatus,
- statusReportUpdate,
- statusReportsToPageComponents,
-} from "@openstatus/db/src/schema";
+ AddStatusReportUpdateInput,
+ CreateStatusReportInput,
+ addStatusReportUpdate,
+ createStatusReport,
+ deleteStatusReport,
+ deleteStatusReportUpdate,
+ getStatusReport,
+ listStatusReports,
+ updateStatusReport,
+ updateStatusReportUpdate,
+} from "@openstatus/services/status-report";
+import { z } from "zod";
-import { Events } from "@openstatus/analytics";
-import { TRPCError } from "@trpc/server";
+import { toServiceCtx, toTRPCError } from "../service-adapter";
import { createTRPCRouter, protectedProcedure } from "../trpc";
-import { getPeriodDate, periods } from "./utils";
-
-export const statusReportRouter = createTRPCRouter({
- createStatusReportUpdate: protectedProcedure
- .meta({ track: Events.CreateReportUpdate })
- .input(
- insertStatusReportUpdateSchema.extend({
- notifySubscribers: z.boolean().nullish(),
- }),
- )
- .mutation(async (opts) => {
- // update parent status report with latest status
- const _statusReport = await opts.ctx.db
- .update(statusReport)
- .set({ status: opts.input.status, updatedAt: new Date() })
- .where(
- and(
- eq(statusReport.id, opts.input.statusReportId),
- eq(statusReport.workspaceId, opts.ctx.workspace.id),
- ),
- )
- .returning()
- .get();
-
- if (!_statusReport) return;
-
- const { id, ...statusReportUpdateInput } = opts.input;
-
- const updatedValue = await opts.ctx.db
- .insert(statusReportUpdate)
- .values(statusReportUpdateInput)
- .returning()
- .get();
-
- return {
- ...selectStatusReportUpdateSchema.parse(updatedValue),
- notifySubscribers: opts.input.notifySubscribers,
- };
- }),
+import { periods } from "./utils";
+
+// tRPC-side input schemas. These preserve the existing wire contract exactly;
+// each procedure adapts between this shape and the canonical service schema.
+
+const createStatusReportTRPCInput = z.object({
+ title: z.string(),
+ status: CreateStatusReportInput.shape.status,
+ pageId: z.number(),
+ pageComponents: z.array(z.number()),
+ date: z.coerce.date(),
+ message: z.string(),
+ notifySubscribers: z.boolean().nullish(),
+});
- updateStatusReportUpdate: protectedProcedure
- .meta({ track: Events.UpdateReportUpdate })
- .input(insertStatusReportUpdateSchema)
- .mutation(async (opts) => {
- const statusReportUpdateInput = opts.input;
+const createStatusReportUpdateTRPCInput = z.object({
+ id: z.number().optional(),
+ statusReportId: z.number(),
+ status: AddStatusReportUpdateInput.shape.status,
+ message: z.string(),
+ date: z.coerce.date().optional(),
+ notifySubscribers: z.boolean().nullish(),
+});
- if (!statusReportUpdateInput.id) return;
+const updateStatusReportUpdateTRPCInput = z.object({
+ id: z.number(),
+ statusReportId: z.number().optional(),
+ status: AddStatusReportUpdateInput.shape.status.optional(),
+ message: z.string().optional(),
+ date: z.coerce.date().optional(),
+});
- const existing = await opts.ctx.db.query.statusReportUpdate.findFirst({
- where: eq(statusReportUpdate.id, statusReportUpdateInput.id),
- with: { statusReport: true },
- });
+const updateStatusTRPCInput = z.object({
+ id: z.number(),
+ pageComponents: z.array(z.number()),
+ title: z.string(),
+ status: CreateStatusReportInput.shape.status,
+});
- if (existing?.statusReport.workspaceId !== opts.ctx.workspace.id) {
- throw new TRPCError({
- code: "FORBIDDEN",
- message: "You are not allowed to update this status report update",
+export const statusReportRouter = createTRPCRouter({
+ create: protectedProcedure
+ .meta({ track: Events.CreateReport })
+ .input(createStatusReportTRPCInput)
+ .mutation(async ({ ctx, input }) => {
+ try {
+ const { initialUpdate } = await createStatusReport({
+ ctx: toServiceCtx(ctx),
+ input: {
+ title: input.title,
+ status: input.status,
+ pageId: input.pageId,
+ pageComponentIds: input.pageComponents,
+ date: input.date,
+ message: input.message,
+ },
});
+ // Preserve the original "return the initial update row with
+ // notifySubscribers merged in" shape the dashboard consumes.
+ return { ...initialUpdate, notifySubscribers: input.notifySubscribers };
+ } catch (err) {
+ toTRPCError(err);
}
-
- const { id, statusReportId, ...updateFields } = statusReportUpdateInput;
- const currentStatusReportUpdate = await opts.ctx.db
- .update(statusReportUpdate)
- .set({ ...updateFields, updatedAt: new Date() })
- .where(eq(statusReportUpdate.id, statusReportUpdateInput.id))
- .returning()
- .get();
-
- return selectStatusReportUpdateSchema.parse(currentStatusReportUpdate);
}),
- get: protectedProcedure
- .input(z.object({ id: z.number() }))
- .query(async (opts) => {
- const result = await opts.ctx.db.query.statusReport.findFirst({
- where: and(
- eq(statusReport.id, opts.input.id),
- eq(statusReport.workspaceId, opts.ctx.workspace.id),
- ),
- with: {
- statusReportUpdates: true,
- statusReportsToPageComponents: { with: { pageComponent: true } },
- page: { with: { pageComponents: true } },
- },
- });
-
- if (!result) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "Status report not found",
- });
- }
-
- return selectStatusReportSchema
- .extend({
- updates: z.array(selectStatusReportUpdateSchema).prefault([]),
- pageComponents: z.array(selectPageComponentSchema).prefault([]),
- page: selectPageSchema.extend({
- pageComponents: z.array(selectPageComponentSchema).prefault([]),
- }),
- })
- .parse({
- ...result,
- updates: result.statusReportUpdates,
- pageComponents: result.statusReportsToPageComponents.map(
- ({ pageComponent }) => pageComponent,
- ),
+ createStatusReportUpdate: protectedProcedure
+ .meta({ track: Events.CreateReportUpdate })
+ .input(createStatusReportUpdateTRPCInput)
+ .mutation(async ({ ctx, input }) => {
+ try {
+ const { statusReportUpdate } = await addStatusReportUpdate({
+ ctx: toServiceCtx(ctx),
+ input: {
+ statusReportId: input.statusReportId,
+ status: input.status,
+ message: input.message,
+ date: input.date,
+ },
});
- }),
-
- list: protectedProcedure
- .input(
- z.object({
- period: z.enum(periods).optional(),
- order: z.enum(["asc", "desc"]).optional(),
- pageId: z.number().optional(),
- }),
- )
- .query(async (opts) => {
- const whereConditions: SQL[] = [
- eq(statusReport.workspaceId, opts.ctx.workspace.id),
- ];
-
- if (opts.input?.period) {
- whereConditions.push(
- gte(statusReport.createdAt, getPeriodDate(opts.input.period)),
- );
- }
-
- if (opts.input?.pageId) {
- whereConditions.push(eq(statusReport.pageId, opts.input.pageId));
+ return {
+ ...statusReportUpdate,
+ notifySubscribers: input.notifySubscribers,
+ };
+ } catch (err) {
+ toTRPCError(err);
}
-
- const result = await opts.ctx.db.query.statusReport.findMany({
- where: and(...whereConditions),
- with: {
- statusReportUpdates: true,
- statusReportsToPageComponents: { with: { pageComponent: true } },
- page: { with: { pageComponents: true } },
- },
- orderBy: (statusReport) => [
- opts.input.order === "asc"
- ? asc(statusReport.createdAt)
- : desc(statusReport.createdAt),
- ],
- });
-
- return selectStatusReportSchema
- .extend({
- updates: z.array(selectStatusReportUpdateSchema).prefault([]),
- pageComponents: z.array(selectPageComponentSchema).prefault([]),
- page: selectPageSchema.extend({
- pageComponents: z.array(selectPageComponentSchema).prefault([]),
- }),
- })
- .array()
- .parse(
- result.map((report) => ({
- ...report,
- updates: report.statusReportUpdates,
- pageComponents: report.statusReportsToPageComponents.map(
- ({ pageComponent }) => pageComponent,
- ),
- })),
- );
}),
- create: protectedProcedure
- .meta({ track: Events.CreateReport })
- .input(
- z.object({
- title: z.string(),
- status: z.enum(statusReportStatus),
- pageId: z.number(),
- pageComponents: z.array(z.number()),
- date: z.coerce.date(),
- message: z.string(),
- notifySubscribers: z.boolean().nullish(),
- }),
- )
- .mutation(async (opts) => {
- const existingPage = await opts.ctx.db.query.page.findFirst({
- where: and(
- eq(page.id, opts.input.pageId),
- eq(page.workspaceId, opts.ctx.workspace.id),
- ),
- });
-
- if (!existingPage) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "Page not found.",
- });
- }
-
- if (opts.input.pageComponents.length > 0) {
- const components = await opts.ctx.db.query.pageComponent.findMany({
- where: and(
- eq(pageComponent.pageId, opts.input.pageId),
- eq(pageComponent.workspaceId, opts.ctx.workspace.id),
- ),
+ updateStatusReportUpdate: protectedProcedure
+ .meta({ track: Events.UpdateReportUpdate })
+ .input(updateStatusReportUpdateTRPCInput)
+ .mutation(async ({ ctx, input }) => {
+ try {
+ return await updateStatusReportUpdate({
+ ctx: toServiceCtx(ctx),
+ input: {
+ id: input.id,
+ status: input.status,
+ message: input.message,
+ date: input.date,
+ },
});
- const validIds = new Set(components.map((c) => c.id));
- const invalid = opts.input.pageComponents.filter(
- (id) => !validIds.has(id),
- );
- if (invalid.length > 0) {
- throw new TRPCError({
- code: "FORBIDDEN",
- message: "Invalid page component IDs.",
- });
- }
+ } catch (err) {
+ toTRPCError(err);
}
-
- return opts.ctx.db.transaction(async (tx) => {
- const newStatusReport = await tx
- .insert(statusReport)
- .values({
- workspaceId: opts.ctx.workspace.id,
- title: opts.input.title,
- status: opts.input.status,
- pageId: opts.input.pageId,
- })
- .returning()
- .get();
-
- const newStatusReportUpdate = await tx
- .insert(statusReportUpdate)
- .values({
- statusReportId: newStatusReport.id,
- status: opts.input.status,
- date: opts.input.date,
- message: opts.input.message,
- })
- .returning()
- .get();
-
- if (opts.input.pageComponents.length > 0) {
- await tx
- .insert(statusReportsToPageComponents)
- .values(
- opts.input.pageComponents.map((pageComponent) => ({
- pageComponentId: pageComponent,
- statusReportId: newStatusReport.id,
- })),
- )
- .run();
- }
-
- return {
- ...newStatusReportUpdate,
- notifySubscribers: opts.input.notifySubscribers,
- };
- });
}),
updateStatus: protectedProcedure
.meta({ track: Events.UpdateReport })
- .input(
- z.object({
- id: z.number(),
- pageComponents: z.array(z.number()),
- title: z.string(),
- status: z.enum(statusReportStatus),
- }),
- )
- .mutation(async (opts) => {
- const existing = await opts.ctx.db.query.statusReport.findFirst({
- where: and(
- eq(statusReport.id, opts.input.id),
- eq(statusReport.workspaceId, opts.ctx.workspace.id),
- ),
- });
-
- if (!existing || !existing.pageId) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "Status report not found",
- });
- }
-
- if (opts.input.pageComponents.length > 0) {
- const components = await opts.ctx.db.query.pageComponent.findMany({
- where: and(
- eq(pageComponent.pageId, existing.pageId),
- eq(pageComponent.workspaceId, opts.ctx.workspace.id),
- ),
+ .input(updateStatusTRPCInput)
+ .mutation(async ({ ctx, input }) => {
+ try {
+ await updateStatusReport({
+ ctx: toServiceCtx(ctx),
+ input: {
+ id: input.id,
+ title: input.title,
+ status: input.status,
+ pageComponentIds: input.pageComponents,
+ },
});
- const validIds = new Set(components.map((c) => c.id));
- const invalid = opts.input.pageComponents.filter(
- (id) => !validIds.has(id),
- );
- if (invalid.length > 0) {
- throw new TRPCError({
- code: "FORBIDDEN",
- message: "Invalid page component IDs.",
- });
- }
+ } catch (err) {
+ toTRPCError(err);
}
-
- await opts.ctx.db.transaction(async (tx) => {
- await tx
- .update(statusReport)
- .set({
- title: opts.input.title,
- status: opts.input.status,
- updatedAt: new Date(),
- })
- .where(
- and(
- eq(statusReport.id, opts.input.id),
- eq(statusReport.workspaceId, opts.ctx.workspace.id),
- ),
- )
- .run();
-
- await tx
- .delete(statusReportsToPageComponents)
- .where(
- eq(statusReportsToPageComponents.statusReportId, opts.input.id),
- )
- .run();
-
- if (opts.input.pageComponents.length > 0) {
- await tx
- .insert(statusReportsToPageComponents)
- .values(
- opts.input.pageComponents.map((pageComponent) => ({
- pageComponentId: pageComponent,
- statusReportId: opts.input.id,
- })),
- )
- .run();
- }
- });
}),
delete: protectedProcedure
.meta({ track: Events.DeleteReport })
.input(z.object({ id: z.number() }))
- .mutation(async (opts) => {
- const whereConditions: SQL[] = [
- eq(statusReport.id, opts.input.id),
- eq(statusReport.workspaceId, opts.ctx.workspace.id),
- ];
-
- await opts.ctx.db.transaction(async (tx) => {
- await tx
- .delete(statusReport)
- .where(and(...whereConditions))
- .run();
- });
+ .mutation(async ({ ctx, input }) => {
+ try {
+ await deleteStatusReport({
+ ctx: toServiceCtx(ctx),
+ input: { id: input.id },
+ });
+ } catch (err) {
+ // Preserve the pre-migration idempotent behaviour — the old tRPC
+ // delete silently succeeded when the row was already gone.
+ if (err instanceof NotFoundError) return;
+ toTRPCError(err);
+ }
}),
deleteUpdate: protectedProcedure
.meta({ track: Events.DeleteReportUpdate })
.input(z.object({ id: z.number() }))
- .mutation(async (opts) => {
- await opts.ctx.db.transaction(async (tx) => {
- const update = await tx.query.statusReportUpdate.findFirst({
- where: eq(statusReportUpdate.id, opts.input.id),
- with: {
- statusReport: true,
- },
+ .mutation(async ({ ctx, input }) => {
+ try {
+ await deleteStatusReportUpdate({
+ ctx: toServiceCtx(ctx),
+ input: { id: input.id },
});
+ } catch (err) {
+ toTRPCError(err);
+ }
+ }),
- if (update?.statusReport.workspaceId !== opts.ctx.workspace.id) {
- throw new TRPCError({
- code: "FORBIDDEN",
- message: "You are not allowed to delete this update",
- });
- }
+ get: protectedProcedure
+ .input(z.object({ id: z.number() }))
+ .query(async ({ ctx, input }) => {
+ try {
+ const result = await getStatusReport({
+ ctx: toServiceCtx(ctx),
+ input: { id: input.id },
+ });
+ return narrowPage(result);
+ } catch (err) {
+ toTRPCError(err);
+ }
+ }),
- await tx
- .delete(statusReportUpdate)
- .where(eq(statusReportUpdate.id, opts.input.id))
- .run();
- });
+ list: protectedProcedure
+ .input(
+ z.object({
+ period: z.enum(periods).optional(),
+ order: z.enum(["asc", "desc"]).optional(),
+ pageId: z.number().optional(),
+ }),
+ )
+ .query(async ({ ctx, input }) => {
+ try {
+ const { items } = await listStatusReports({
+ ctx: toServiceCtx(ctx),
+ input: {
+ pageId: input.pageId,
+ period: input.period,
+ order: input.order ?? "desc",
+ // tRPC consumers (dashboard) want the full set — no paging UI
+ // today. Pass a sentinel ceiling rather than silently truncating;
+ // Connect's separate handler imposes its own max=100.
+ limit: 10_000,
+ offset: 0,
+ statuses: [],
+ },
+ });
+ return items.map(narrowPage);
+ } catch (err) {
+ toTRPCError(err);
+ }
}),
});
+
+/**
+ * Narrow the service's nullable `page` field to a required one for the tRPC
+ * return type. Every status report is expected to have a `pageId` (and
+ * therefore a `page`) by the dashboard's schema; a null page here is a
+ * data-integrity signal we surface rather than silently return.
+ */
+function narrowPage<T extends { id: number; page: unknown }>(
+ report: T,
+): T & { page: NonNullable<T["page"]> } {
+ if (report.page == null) {
+ throw new Error(
+ `status report ${report.id} has no associated page (data inconsistency)`,
+ );
+ }
+ return report as T & { page: NonNullable<T["page"]> };
+}
diff --git a/packages/api/src/service-adapter.ts b/packages/api/src/service-adapter.ts
new file mode 100644
index 000000000..48f127c5a
--- /dev/null
+++ b/packages/api/src/service-adapter.ts
@@ -0,0 +1,80 @@
+import { TRPCError } from "@trpc/server";
+import { ZodError } from "zod";
+
+import { type ServiceContext, ServiceError } from "@openstatus/services";
+
+import type { Context } from "./trpc";
+
+type AuthedContext = Context & {
+ user: { id: number };
+ workspace: NonNullable<Context["workspace"]>;
+};
+
+/**
+ * Translate a tRPC `protectedProcedure` context into a `ServiceContext`.
+ * Workspace + actor come from the authed middleware output; `requestId` is
+ * best-effort from upstream headers.
+ */
+export function toServiceCtx(ctx: AuthedContext): ServiceContext {
+ return {
+ workspace: ctx.workspace,
+ actor: { type: "user", userId: ctx.user.id },
+ requestId: ctx.req?.headers.get("x-request-id") ?? undefined,
+ };
+}
+
+/**
+ * Map any error thrown by a service call to a `TRPCError`. `ZodError`
+ * bubbles up unchanged so tRPC's `errorFormatter` can surface field-level
+ * issues as-is. Internal errors carry the cause for Sentry/logtape but do
+ * not leak it in the user-facing `message`.
+ */
+export function toTRPCError(err: unknown): never {
+ if (err instanceof TRPCError) throw err;
+ if (err instanceof ZodError) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: "Invalid input",
+ cause: err,
+ });
+ }
+ if (err instanceof ServiceError) {
+ switch (err.code) {
+ case "NOT_FOUND":
+ throw new TRPCError({ code: "NOT_FOUND", message: err.message });
+ case "FORBIDDEN":
+ throw new TRPCError({ code: "FORBIDDEN", message: err.message });
+ case "UNAUTHORIZED":
+ throw new TRPCError({ code: "UNAUTHORIZED", message: err.message });
+ case "CONFLICT":
+ throw new TRPCError({ code: "CONFLICT", message: err.message });
+ case "VALIDATION":
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: err.message,
+ cause: err.cause,
+ });
+ case "LIMIT_EXCEEDED":
+ // Quota exhaustion semantically maps to TOO_MANY_REQUESTS (429),
+ // not FORBIDDEN (403). Mirrors the Connect adapter's
+ // Code.ResourceExhausted mapping — both surfaces should say
+ // "you've hit a plan quota" rather than "you can't do this."
+ throw new TRPCError({
+ code: "TOO_MANY_REQUESTS",
+ message: err.message,
+ });
+ case "INTERNAL":
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: err.message,
+ cause: err.cause,
+ });
+ }
+ }
+ const message = err instanceof Error ? err.message : "Unknown error";
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message,
+ cause: err,
+ });
+}
diff --git a/packages/services/bunfig.toml b/packages/services/bunfig.toml
new file mode 100644
index 000000000..b79d13805
--- /dev/null
+++ b/packages/services/bunfig.toml
@@ -0,0 +1,4 @@
+[test]
+# Runs before every test file — stubs env vars required by transitive
+# imports from `@openstatus/subscriptions` → `@openstatus/emails`.
+preload = ["./test/preload.ts"]
diff --git a/packages/services/package.json b/packages/services/package.json
index 4fb6d59c1..a0cc8360f 100644
--- a/packages/services/package.json
+++ b/packages/services/package.json
@@ -8,6 +8,10 @@
".": {
"import": "./src/index.ts",
"types": "./src/index.ts"
+ },
+ "./status-report": {
+ "import": "./src/status-report/index.ts",
+ "types": "./src/status-report/index.ts"
}
},
"scripts": {
@@ -16,6 +20,7 @@
"dependencies": {
"@logtape/logtape": "2.0.1",
"@openstatus/db": "workspace:*",
+ "@openstatus/subscriptions": "workspace:*",
"zod": "4.1.13"
},
"devDependencies": {
diff --git a/packages/services/src/status-report/__tests__/status-report.test.ts b/packages/services/src/status-report/__tests__/status-report.test.ts
new file mode 100644
index 000000000..9c3aeba13
--- /dev/null
+++ b/packages/services/src/status-report/__tests__/status-report.test.ts
@@ -0,0 +1,569 @@
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ beforeEach,
+ describe,
+ expect,
+ test,
+} from "bun:test";
+import { db, eq, inArray } from "@openstatus/db";
+import {
+ page,
+ pageComponent,
+ pageSubscriber,
+ statusReport,
+ statusReportUpdate,
+ statusReportsToPageComponents,
+} from "@openstatus/db/src/schema";
+
+import {
+ SEEDED_WORKSPACE_FREE_ID,
+ SEEDED_WORKSPACE_TEAM_ID,
+} from "../../../test/fixtures";
+import {
+ expectAuditRow,
+ loadSeededWorkspace,
+ makeSlackCtx,
+ makeUserCtx,
+ withAuditBuffer,
+} from "../../../test/helpers";
+import type { AuditLogRecord } from "../../audit";
+import type { ServiceContext } from "../../context";
+import { ForbiddenError, NotFoundError } from "../../errors";
+import { addStatusReportUpdate } from "../add-update";
+import { createStatusReport } from "../create";
+import { deleteStatusReport, deleteStatusReportUpdate } from "../delete";
+import { getStatusReport, listStatusReports } from "../list";
+import { notifyStatusReport } from "../notify";
+import { resolveStatusReport } from "../resolve";
+import { updateStatusReport, updateStatusReportUpdate } from "../update";
+
+// Subscription-dispatcher spies are installed by `test/preload.ts` and
+// exposed on globalThis so we can assert notification dispatch without
+// sending real emails.
+const subscriptionSpies = (globalThis as Record<string, unknown>)
+ .__subscriptionSpies as
+ | {
+ dispatchStatusReportUpdate: {
+ mockClear: () => void;
+ mock: { calls: unknown[][] };
+ };
+ dispatchMaintenanceUpdate: {
+ mockClear: () => void;
+ mock: { calls: unknown[][] };
+ };
+ }
+ | undefined;
+
+const TEST_PREFIX = "svc-status-report-test";
+
+let teamCtx: ServiceContext;
+let freeCtx: ServiceContext;
+let testPageId: number;
+let testPageComponentId: number;
+let auditBuffer: AuditLogRecord[];
+let auditReset: () => void;
+
+/**
+ * Tests push created statusReport ids here instead of issuing an inline
+ * `db.delete()` at the end of their body. `afterEach` drains the array,
+ * so cleanup runs even when an assertion throws midway through a test —
+ * otherwise a failing assertion leaves orphans that flake subsequent
+ * runs. Individual tests can still push additional ids mid-test if they
+ * create multiple reports.
+ */
+const createdReportIds: number[] = [];
+
+beforeAll(async () => {
+ const team = await loadSeededWorkspace(SEEDED_WORKSPACE_TEAM_ID);
+ const free = await loadSeededWorkspace(SEEDED_WORKSPACE_FREE_ID);
+ teamCtx = makeUserCtx(team, { userId: 1 });
+ freeCtx = makeUserCtx(free, { userId: 2 });
+
+ const pageRow = await db
+ .insert(page)
+ .values({
+ workspaceId: team.id,
+ title: `${TEST_PREFIX}-page`,
+ description: "test page",
+ slug: `${TEST_PREFIX}-page-slug`,
+ customDomain: "",
+ })
+ .returning()
+ .get();
+ testPageId = pageRow.id;
+
+ const componentRow = await db
+ .insert(pageComponent)
+ .values({
+ workspaceId: team.id,
+ pageId: testPageId,
+ name: `${TEST_PREFIX}-component`,
+ type: "static",
+ })
+ .returning()
+ .get();
+ testPageComponentId = componentRow.id;
+});
+
+afterAll(async () => {
+ await db
+ .delete(pageSubscriber)
+ .where(eq(pageSubscriber.pageId, testPageId))
+ .catch(() => undefined);
+ await db
+ .delete(pageComponent)
+ .where(eq(pageComponent.id, testPageComponentId))
+ .catch(() => undefined);
+ await db
+ .delete(page)
+ .where(eq(page.id, testPageId))
+ .catch(() => undefined);
+});
+
+beforeEach(() => {
+ const hooks = withAuditBuffer();
+ auditBuffer = hooks.buffer;
+ auditReset = hooks.reset;
+ subscriptionSpies?.dispatchStatusReportUpdate.mockClear();
+});
+
+afterEach(async () => {
+ auditReset();
+ if (createdReportIds.length > 0) {
+ await db
+ .delete(statusReport)
+ .where(inArray(statusReport.id, createdReportIds))
+ .catch(() => undefined);
+ createdReportIds.length = 0;
+ }
+});
+
+describe("createStatusReport", () => {
+ test("creates report + initial update + associations and emits audit", async () => {
+ const { statusReport: report, initialUpdate } = await createStatusReport({
+ ctx: teamCtx,
+ input: {
+ title: `${TEST_PREFIX}-create-happy`,
+ status: "investigating",
+ message: "starting investigation",
+ date: new Date(),
+ pageId: testPageId,
+ pageComponentIds: [testPageComponentId],
+ },
+ });
+
+ expect(report.id).toBeGreaterThan(0);
+ expect(report.title).toBe(`${TEST_PREFIX}-create-happy`);
+ expect(report.pageId).toBe(testPageId);
+ expect(initialUpdate.statusReportId).toBe(report.id);
+ expect(initialUpdate.message).toBe("starting investigation");
+
+ const assoc = await db
+ .select()
+ .from(statusReportsToPageComponents)
+ .where(eq(statusReportsToPageComponents.statusReportId, report.id))
+ .all();
+ expect(assoc.map((a) => a.pageComponentId)).toEqual([testPageComponentId]);
+
+ await expectAuditRow(auditBuffer, {
+ action: "status_report.create",
+ entityType: "status_report",
+ entityId: report.id,
+ });
+
+ createdReportIds.push(report.id);
+ });
+
+ test("throws NotFoundError when the page is not in the workspace", async () => {
+ await expect(
+ createStatusReport({
+ ctx: freeCtx,
+ input: {
+ title: `${TEST_PREFIX}-create-cross-ws`,
+ status: "investigating",
+ message: "should fail",
+ date: new Date(),
+ pageId: testPageId, // page belongs to team workspace
+ pageComponentIds: [],
+ },
+ }),
+ ).rejects.toBeInstanceOf(NotFoundError);
+ });
+});
+
+describe("addStatusReportUpdate", () => {
+ test("appends an update and bumps parent status", async () => {
+ const { statusReport: report } = await createStatusReport({
+ ctx: teamCtx,
+ input: {
+ title: `${TEST_PREFIX}-add-update`,
+ status: "investigating",
+ message: "initial",
+ date: new Date(),
+ pageId: testPageId,
+ pageComponentIds: [],
+ },
+ });
+
+ const { statusReport: bumped, statusReportUpdate: newUpdate } =
+ await addStatusReportUpdate({
+ ctx: teamCtx,
+ input: {
+ statusReportId: report.id,
+ status: "monitoring",
+ message: "moved to monitoring",
+ },
+ });
+
+ expect(bumped.status).toBe("monitoring");
+ expect(newUpdate.status).toBe("monitoring");
+ expect(newUpdate.statusReportId).toBe(report.id);
+
+ await expectAuditRow(auditBuffer, {
+ action: "status_report.add_update",
+ entityType: "status_report_update",
+ entityId: newUpdate.id,
+ });
+
+ createdReportIds.push(report.id);
+ });
+
+ test("throws NotFoundError for a status report in another workspace", async () => {
+ const { statusReport: report } = await createStatusReport({
+ ctx: teamCtx,
+ input: {
+ title: `${TEST_PREFIX}-cross-ws-add`,
+ status: "investigating",
+ message: "m",
+ date: new Date(),
+ pageId: testPageId,
+ pageComponentIds: [],
+ },
+ });
+
+ await expect(
+ addStatusReportUpdate({
+ ctx: freeCtx,
+ input: {
+ statusReportId: report.id,
+ status: "monitoring",
+ message: "cross-ws",
+ },
+ }),
+ ).rejects.toBeInstanceOf(NotFoundError);
+
+ createdReportIds.push(report.id);
+ });
+});
+
+describe("resolveStatusReport", () => {
+ test("appends a resolved update and flips parent status", async () => {
+ const { statusReport: report } = await createStatusReport({
+ ctx: teamCtx,
+ input: {
+ title: `${TEST_PREFIX}-resolve`,
+ status: "investigating",
+ message: "oops",
+ date: new Date(),
+ pageId: testPageId,
+ pageComponentIds: [],
+ },
+ });
+
+ const { statusReport: resolved } = await resolveStatusReport({
+ ctx: teamCtx,
+ input: { statusReportId: report.id, message: "all clear" },
+ });
+ expect(resolved.status).toBe("resolved");
+ createdReportIds.push(report.id);
+ });
+});
+
+describe("updateStatusReport", () => {
+ test("updates title and replaces associations", async () => {
+ const { statusReport: report } = await createStatusReport({
+ ctx: teamCtx,
+ input: {
+ title: `${TEST_PREFIX}-update`,
+ status: "investigating",
+ message: "m",
+ date: new Date(),
+ pageId: testPageId,
+ pageComponentIds: [testPageComponentId],
+ },
+ });
+
+ const updated = await updateStatusReport({
+ ctx: teamCtx,
+ input: {
+ id: report.id,
+ title: `${TEST_PREFIX}-update-renamed`,
+ pageComponentIds: [],
+ },
+ });
+ expect(updated.title).toBe(`${TEST_PREFIX}-update-renamed`);
+
+ const assoc = await db
+ .select()
+ .from(statusReportsToPageComponents)
+ .where(eq(statusReportsToPageComponents.statusReportId, report.id))
+ .all();
+ expect(assoc).toHaveLength(0);
+
+ createdReportIds.push(report.id);
+ });
+});
+
+describe("deleteStatusReport", () => {
+ test("cascades updates + associations", async () => {
+ const { statusReport: report, initialUpdate } = await createStatusReport({
+ ctx: teamCtx,
+ input: {
+ title: `${TEST_PREFIX}-delete`,
+ status: "investigating",
+ message: "m",
+ date: new Date(),
+ pageId: testPageId,
+ pageComponentIds: [testPageComponentId],
+ },
+ });
+
+ await deleteStatusReport({ ctx: teamCtx, input: { id: report.id } });
+
+ const remainingReport = await db
+ .select()
+ .from(statusReport)
+ .where(eq(statusReport.id, report.id))
+ .all();
+ const remainingUpdate = await db
+ .select()
+ .from(statusReportUpdate)
+ .where(eq(statusReportUpdate.id, initialUpdate.id))
+ .all();
+ const remainingAssoc = await db
+ .select()
+ .from(statusReportsToPageComponents)
+ .where(eq(statusReportsToPageComponents.statusReportId, report.id))
+ .all();
+ expect(remainingReport).toHaveLength(0);
+ expect(remainingUpdate).toHaveLength(0);
+ expect(remainingAssoc).toHaveLength(0);
+ });
+
+ test("throws NotFoundError for cross-workspace delete", async () => {
+ const { statusReport: report } = await createStatusReport({
+ ctx: teamCtx,
+ input: {
+ title: `${TEST_PREFIX}-cross-ws-delete`,
+ status: "investigating",
+ message: "m",
+ date: new Date(),
+ pageId: testPageId,
+ pageComponentIds: [],
+ },
+ });
+
+ await expect(
+ deleteStatusReport({ ctx: freeCtx, input: { id: report.id } }),
+ ).rejects.toBeInstanceOf(NotFoundError);
+
+ createdReportIds.push(report.id);
+ });
+});
+
+describe("deleteStatusReportUpdate", () => {
+ test("removes a single update and emits audit", async () => {
+ const { statusReport: report } = await createStatusReport({
+ ctx: teamCtx,
+ input: {
+ title: `${TEST_PREFIX}-delete-update`,
+ status: "investigating",
+ message: "m",
+ date: new Date(),
+ pageId: testPageId,
+ pageComponentIds: [],
+ },
+ });
+ const { statusReportUpdate: newUpdate } = await addStatusReportUpdate({
+ ctx: teamCtx,
+ input: {
+ statusReportId: report.id,
+ status: "monitoring",
+ message: "to be deleted",
+ },
+ });
+
+ await deleteStatusReportUpdate({
+ ctx: teamCtx,
+ input: { id: newUpdate.id },
+ });
+
+ const remaining = await db
+ .select()
+ .from(statusReportUpdate)
+ .where(eq(statusReportUpdate.id, newUpdate.id))
+ .all();
+ expect(remaining).toHaveLength(0);
+
+ createdReportIds.push(report.id);
+ });
+});
+
+describe("updateStatusReportUpdate", () => {
+ test("edits message + date; returns updated row", async () => {
+ const { statusReport: report, initialUpdate } = await createStatusReport({
+ ctx: teamCtx,
+ input: {
+ title: `${TEST_PREFIX}-edit-update`,
+ status: "investigating",
+ message: "before",
+ date: new Date(),
+ pageId: testPageId,
+ pageComponentIds: [],
+ },
+ });
+
+ const edited = await updateStatusReportUpdate({
+ ctx: teamCtx,
+ input: { id: initialUpdate.id, message: "after" },
+ });
+ expect(edited.message).toBe("after");
+
+ createdReportIds.push(report.id);
+ });
+
+ test("throws ForbiddenError for cross-workspace edit", async () => {
+ const { statusReport: report, initialUpdate } = await createStatusReport({
+ ctx: teamCtx,
+ input: {
+ title: `${TEST_PREFIX}-cross-ws-edit`,
+ status: "investigating",
+ message: "m",
+ date: new Date(),
+ pageId: testPageId,
+ pageComponentIds: [],
+ },
+ });
+
+ await expect(
+ updateStatusReportUpdate({
+ ctx: freeCtx,
+ input: { id: initialUpdate.id, message: "blocked" },
+ }),
+ ).rejects.toBeInstanceOf(ForbiddenError);
+
+ createdReportIds.push(report.id);
+ });
+});
+
+describe("listStatusReports / getStatusReport", () => {
+ test("respects workspace isolation", async () => {
+ const { statusReport: report } = await createStatusReport({
+ ctx: teamCtx,
+ input: {
+ title: `${TEST_PREFIX}-isolation`,
+ status: "investigating",
+ message: "m",
+ date: new Date(),
+ pageId: testPageId,
+ pageComponentIds: [],
+ },
+ });
+
+ await expect(
+ getStatusReport({ ctx: freeCtx, input: { id: report.id } }),
+ ).rejects.toBeInstanceOf(NotFoundError);
+
+ const { items: freeItems } = await listStatusReports({
+ ctx: freeCtx,
+ input: {
+ limit: 100,
+ offset: 0,
+ statuses: [],
+ order: "desc",
+ pageId: testPageId,
+ },
+ });
+ expect(freeItems.find((r) => r.id === report.id)).toBeUndefined();
+
+ createdReportIds.push(report.id);
+ });
+
+ test("returns totalSize and enriched relations", async () => {
+ const { statusReport: report } = await createStatusReport({
+ ctx: teamCtx,
+ input: {
+ title: `${TEST_PREFIX}-list-enrich`,
+ status: "investigating",
+ message: "m",
+ date: new Date(),
+ pageId: testPageId,
+ pageComponentIds: [testPageComponentId],
+ },
+ });
+
+ const full = await getStatusReport({
+ ctx: teamCtx,
+ input: { id: report.id },
+ });
+ expect(full.updates).toHaveLength(1);
+ expect(full.pageComponents.map((c) => c.id)).toEqual([testPageComponentId]);
+ expect(full.page?.id).toBe(testPageId);
+
+ createdReportIds.push(report.id);
+ });
+});
+
+describe("notifyStatusReport", () => {
+ test("throws when update belongs to another workspace", async () => {
+ const { statusReport: report, initialUpdate } = await createStatusReport({
+ ctx: teamCtx,
+ input: {
+ title: `${TEST_PREFIX}-notify-cross-ws`,
+ status: "investigating",
+ message: "m",
+ date: new Date(),
+ pageId: testPageId,
+ pageComponentIds: [],
+ },
+ });
+
+ await expect(
+ notifyStatusReport({
+ ctx: freeCtx,
+ input: { statusReportUpdateId: initialUpdate.id },
+ }),
+ ).rejects.toBeInstanceOf(ForbiddenError);
+
+ createdReportIds.push(report.id);
+ });
+});
+
+describe("slack actor path", () => {
+ test("createStatusReport succeeds with a slack actor", async () => {
+ const ctx = makeSlackCtx(teamCtx.workspace, {
+ teamId: "T123",
+ slackUserId: "U123",
+ });
+ const { statusReport: report } = await createStatusReport({
+ ctx,
+ input: {
+ title: `${TEST_PREFIX}-slack`,
+ status: "investigating",
+ message: "via slack",
+ date: new Date(),
+ pageId: testPageId,
+ pageComponentIds: [],
+ },
+ });
+ await expectAuditRow(auditBuffer, {
+ action: "status_report.create",
+ entityType: "status_report",
+ entityId: report.id,
+ actorType: "slack",
+ });
+ createdReportIds.push(report.id);
+ });
+});
diff --git a/packages/services/src/status-report/add-update.ts b/packages/services/src/status-report/add-update.ts
new file mode 100644
index 000000000..a75020982
--- /dev/null
+++ b/packages/services/src/status-report/add-update.ts
@@ -0,0 +1,66 @@
+import { eq } from "@openstatus/db";
+import { statusReport, statusReportUpdate } from "@openstatus/db/src/schema";
+
+import { emitAudit } from "../audit";
+import { type ServiceContext, withTransaction } from "../context";
+import { InternalServiceError } from "../errors";
+import type { StatusReport, StatusReportUpdate } from "../types";
+import { getReportInWorkspace } from "./internal";
+import { AddStatusReportUpdateInput } from "./schemas";
+
+export type AddStatusReportUpdateResult = {
+ statusReport: StatusReport;
+ statusReportUpdate: StatusReportUpdate;
+};
+
+export async function addStatusReportUpdate(args: {
+ ctx: ServiceContext;
+ input: AddStatusReportUpdateInput;
+}): Promise<AddStatusReportUpdateResult> {
+ const { ctx } = args;
+ const input = AddStatusReportUpdateInput.parse(args.input);
+
+ return withTransaction(ctx, async (tx) => {
+ const report = await getReportInWorkspace({
+ tx,
+ id: input.statusReportId,
+ workspaceId: ctx.workspace.id,
+ });
+
+ const date = input.date ?? new Date();
+
+ const newUpdate = await tx
+ .insert(statusReportUpdate)
+ .values({
+ statusReportId: report.id,
+ status: input.status,
+ date,
+ message: input.message,
+ })
+ .returning()
+ .get();
+
+ const updatedReport = await tx
+ .update(statusReport)
+ .set({ status: input.status, updatedAt: new Date() })
+ .where(eq(statusReport.id, report.id))
+ .returning()
+ .get();
+
+ if (!updatedReport) {
+ throw new InternalServiceError(
+ `failed to bump status report ${report.id} after adding update`,
+ );
+ }
+
+ await emitAudit(tx, ctx, {
+ action: "status_report.add_update",
+ entityType: "status_report_update",
+ entityId: newUpdate.id,
+ after: newUpdate,
+ metadata: { statusReportId: report.id, status: input.status },
+ });
+
+ return { statusReport: updatedReport, statusReportUpdate: newUpdate };
+ });
+}
diff --git a/packages/services/src/status-report/create.ts b/packages/services/src/status-report/create.ts
new file mode 100644
index 000000000..320e43f29
--- /dev/null
+++ b/packages/services/src/status-report/create.ts
@@ -0,0 +1,89 @@
+import { and, eq } from "@openstatus/db";
+import {
+ page,
+ statusReport,
+ statusReportUpdate,
+} from "@openstatus/db/src/schema";
+
+import { emitAudit } from "../audit";
+import { type ServiceContext, withTransaction } from "../context";
+import { ConflictError, NotFoundError } from "../errors";
+import type { StatusReport, StatusReportUpdate } from "../types";
+import {
+ updatePageComponentAssociations,
+ validatePageComponentIds,
+} from "./internal";
+import { CreateStatusReportInput } from "./schemas";
+
+export type CreateStatusReportResult = {
+ statusReport: StatusReport;
+ initialUpdate: StatusReportUpdate;
+};
+
+export async function createStatusReport(args: {
+ ctx: ServiceContext;
+ input: CreateStatusReportInput;
+}): Promise<CreateStatusReportResult> {
+ const { ctx } = args;
+ const input = CreateStatusReportInput.parse(args.input);
+
+ return withTransaction(ctx, async (tx) => {
+ const page_ = await tx
+ .select({ id: page.id })
+ .from(page)
+ .where(
+ and(eq(page.id, input.pageId), eq(page.workspaceId, ctx.workspace.id)),
+ )
+ .get();
+ if (!page_) throw new NotFoundError("page", input.pageId);
+
+ const validated = await validatePageComponentIds({
+ tx,
+ workspaceId: ctx.workspace.id,
+ pageComponentIds: input.pageComponentIds,
+ });
+
+ if (validated.pageId !== null && validated.pageId !== input.pageId) {
+ throw new ConflictError(
+ `pageId ${input.pageId} does not match the page (${validated.pageId}) of the selected components.`,
+ );
+ }
+
+ const newReport = await tx
+ .insert(statusReport)
+ .values({
+ workspaceId: ctx.workspace.id,
+ pageId: input.pageId,
+ title: input.title,
+ status: input.status,
+ })
+ .returning()
+ .get();
+
+ await updatePageComponentAssociations({
+ tx,
+ statusReportId: newReport.id,
+ componentIds: validated.componentIds,
+ });
+
+ const initialUpdate = await tx
+ .insert(statusReportUpdate)
+ .values({
+ statusReportId: newReport.id,
+ status: input.status,
+ date: input.date,
+ message: input.message,
+ })
+ .returning()
+ .get();
+
+ await emitAudit(tx, ctx, {
+ action: "status_report.create",
+ entityType: "status_report",
+ entityId: newReport.id,
+ after: newReport,
+ });
+
+ return { statusReport: newReport, initialUpdate };
+ });
+}
diff --git a/packages/services/src/status-report/delete.ts b/packages/services/src/status-report/delete.ts
new file mode 100644
index 000000000..c5d75c2fb
--- /dev/null
+++ b/packages/services/src/status-report/delete.ts
@@ -0,0 +1,67 @@
+import { eq } from "@openstatus/db";
+import { statusReport, statusReportUpdate } from "@openstatus/db/src/schema";
+
+import { emitAudit } from "../audit";
+import { type ServiceContext, withTransaction } from "../context";
+import { getReportInWorkspace, getReportUpdateInWorkspace } from "./internal";
+import {
+ DeleteStatusReportInput,
+ DeleteStatusReportUpdateInput,
+} from "./schemas";
+
+/**
+ * Delete a status report. Cascade removes updates and
+ * `status_reports_to_page_components` rows.
+ */
+export async function deleteStatusReport(args: {
+ ctx: ServiceContext;
+ input: DeleteStatusReportInput;
+}): Promise<void> {
+ const { ctx } = args;
+ const input = DeleteStatusReportInput.parse(args.input);
+
+ await withTransaction(ctx, async (tx) => {
+ const report = await getReportInWorkspace({
+ tx,
+ id: input.id,
+ workspaceId: ctx.workspace.id,
+ });
+
+ await tx.delete(statusReport).where(eq(statusReport.id, report.id));
+
+ await emitAudit(tx, ctx, {
+ action: "status_report.delete",
+ entityType: "status_report",
+ entityId: report.id,
+ before: report,
+ });
+ });
+}
+
+/** Delete a single status-report update row. */
+export async function deleteStatusReportUpdate(args: {
+ ctx: ServiceContext;
+ input: DeleteStatusReportUpdateInput;
+}): Promise<void> {
+ const { ctx } = args;
+ const input = DeleteStatusReportUpdateInput.parse(args.input);
+
+ await withTransaction(ctx, async (tx) => {
+ const existing = await getReportUpdateInWorkspace({
+ tx,
+ id: input.id,
+ workspaceId: ctx.workspace.id,
+ });
+
+ await tx
+ .delete(statusReportUpdate)
+ .where(eq(statusReportUpdate.id, existing.id));
+
+ await emitAudit(tx, ctx, {
+ action: "status_report.delete_update",
+ entityType: "status_report_update",
+ entityId: existing.id,
+ before: existing,
+ });
+ });
+}
diff --git a/packages/services/src/status-report/index.ts b/packages/services/src/status-report/index.ts
new file mode 100644
index 000000000..ffa5dfc7e
--- /dev/null
+++ b/packages/services/src/status-report/index.ts
@@ -0,0 +1,42 @@
+export {
+ type AddStatusReportUpdateResult,
+ addStatusReportUpdate,
+} from "./add-update";
+export {
+ type CreateStatusReportResult,
+ createStatusReport,
+} from "./create";
+export {
+ deleteStatusReport,
+ deleteStatusReportUpdate,
+} from "./delete";
+export {
+ getStatusReport,
+ listStatusReports,
+ type ListStatusReportsResult,
+ type StatusReportWithRelations,
+} from "./list";
+export { notifyStatusReport } from "./notify";
+export { resolveStatusReport } from "./resolve";
+export {
+ updateStatusReport,
+ updateStatusReportUpdate,
+} from "./update";
+
+export {
+ AddStatusReportUpdateInput,
+ CreateStatusReportInput,
+ DeleteStatusReportInput,
+ DeleteStatusReportUpdateInput,
+ GetStatusReportInput,
+ ListStatusReportsInput,
+ NotifyStatusReportInput,
+ ResolveStatusReportInput,
+ type StatusReportListPeriod,
+ statusReportListPeriodSchema,
+ statusReportListPeriods,
+ type StatusReportStatus,
+ statusReportStatusSchema,
+ UpdateStatusReportInput,
+ UpdateStatusReportUpdateInput,
+} from "./schemas";
diff --git a/packages/services/src/status-report/internal.ts b/packages/services/src/status-report/internal.ts
new file mode 100644
index 000000000..b43311a5f
--- /dev/null
+++ b/packages/services/src/status-report/internal.ts
@@ -0,0 +1,162 @@
+import { and, desc, eq, inArray } from "@openstatus/db";
+import {
+ pageComponent,
+ statusReport,
+ statusReportUpdate,
+ statusReportsToPageComponents,
+} from "@openstatus/db/src/schema";
+
+import type { DB } from "../context";
+import { ConflictError, ForbiddenError, NotFoundError } from "../errors";
+
+export type ValidatedPageComponents = {
+ componentIds: number[];
+ /**
+ * The page all components belong to. `null` when no components were
+ * requested (empty input → report is not tied to a page via components).
+ */
+ pageId: number | null;
+};
+
+/**
+ * Validate that every id in `pageComponentIds` exists, belongs to the
+ * workspace, and — if there is more than one — that they all belong to the
+ * same page. Returns the canonical numeric ids and the derived pageId.
+ *
+ * Must run inside the caller's transaction when used as part of a mutation to
+ * close the TOCTOU window between validation and association writes.
+ */
+export async function validatePageComponentIds(args: {
+ tx: DB;
+ workspaceId: number;
+ pageComponentIds: ReadonlyArray<number>;
+}): Promise<ValidatedPageComponents> {
+ const { tx, workspaceId, pageComponentIds } = args;
+ if (pageComponentIds.length === 0) {
+ return { componentIds: [], pageId: null };
+ }
+
+ // Dedupe up-front — duplicate ids in the input would violate the composite
+ // PK on `status_reports_to_page_components` during insert.
+ const ids = Array.from(new Set(pageComponentIds));
+ const valid = await tx
+ .select({ id: pageComponent.id, pageId: pageComponent.pageId })
+ .from(pageComponent)
+ .where(
+ and(
+ inArray(pageComponent.id, ids),
+ eq(pageComponent.workspaceId, workspaceId),
+ ),
+ )
+ .all();
+
+ const validById = new Map(valid.map((c) => [c.id, c.pageId]));
+ for (const id of ids) {
+ if (!validById.has(id)) {
+ throw new NotFoundError("page_component", id);
+ }
+ }
+
+ const pageIds = new Set(valid.map((c) => c.pageId));
+ if (pageIds.size > 1) {
+ throw new ConflictError(
+ "All page components must belong to the same page.",
+ );
+ }
+
+ return { componentIds: ids, pageId: valid[0]?.pageId ?? null };
+}
+
+/** Replace the set of page-component associations for a report. */
+export async function updatePageComponentAssociations(args: {
+ tx: DB;
+ statusReportId: number;
+ componentIds: ReadonlyArray<number>;
+}): Promise<void> {
+ const { tx, statusReportId, componentIds } = args;
+
+ await tx
+ .delete(statusReportsToPageComponents)
+ .where(eq(statusReportsToPageComponents.statusReportId, statusReportId));
+
+ if (componentIds.length > 0) {
+ await tx.insert(statusReportsToPageComponents).values(
+ componentIds.map((pageComponentId) => ({
+ statusReportId,
+ pageComponentId,
+ })),
+ );
+ }
+}
+
+/** Load a status report by id, scoped to the workspace. Throws on miss. */
+export async function getReportInWorkspace(args: {
+ tx: DB;
+ id: number;
+ workspaceId: number;
+}) {
+ const { tx, id, workspaceId } = args;
+ const row = await tx
+ .select()
+ .from(statusReport)
+ .where(
+ and(eq(statusReport.id, id), eq(statusReport.workspaceId, workspaceId)),
+ )
+ .get();
+ if (!row) throw new NotFoundError("status_report", id);
+ return row;
+}
+
+/**
+ * Load a status report update and verify its parent report belongs to the
+ * workspace. Used by mutation services that target a single update row.
+ */
+export async function getReportUpdateInWorkspace(args: {
+ tx: DB;
+ id: number;
+ workspaceId: number;
+}) {
+ const { tx, id, workspaceId } = args;
+ const row = await tx
+ .select({
+ update: statusReportUpdate,
+ reportWorkspaceId: statusReport.workspaceId,
+ })
+ .from(statusReportUpdate)
+ .innerJoin(
+ statusReport,
+ eq(statusReportUpdate.statusReportId, statusReport.id),
+ )
+ .where(eq(statusReportUpdate.id, id))
+ .get();
+ if (!row) throw new NotFoundError("status_report_update", id);
+ if (row.reportWorkspaceId !== workspaceId) {
+ throw new ForbiddenError(
+ "Status report update does not belong to this workspace.",
+ );
+ }
+ return row.update;
+}
+
+/** Fetch all updates for a report, newest-first. */
+export async function getUpdatesForReport(tx: DB, statusReportId: number) {
+ return tx
+ .select()
+ .from(statusReportUpdate)
+ .where(eq(statusReportUpdate.statusReportId, statusReportId))
+ .orderBy(desc(statusReportUpdate.date))
+ .all();
+}
+
+/** Fetch the associated component ids for a report. */
+export async function getPageComponentIdsForReport(
+ tx: DB,
+ statusReportId: number,
+) {
+ const rows = await tx
+ .select({ pageComponentId: statusReportsToPageComponents.pageComponentId })
+ .from(statusReportsToPageComponents)
+ .where(eq(statusReportsToPageComponents.statusReportId, statusReportId))
+ .all();
+ return rows.map((r) => r.pageComponentId);
+}
diff --git a/packages/services/src/status-report/list.ts b/packages/services/src/status-report/list.ts
new file mode 100644
index 000000000..07710d609
--- /dev/null
+++ b/packages/services/src/status-report/list.ts
@@ -0,0 +1,224 @@
+import {
+ type SQL,
+ and,
+ asc,
+ db as defaultDb,
+ desc,
+ eq,
+ gte,
+ inArray,
+ sql,
+} from "@openstatus/db";
+import {
+ pageComponent,
+ page as pageTable,
+ selectPageSchema,
+ statusReport,
+ statusReportUpdate,
+ statusReportsToPageComponents,
+} from "@openstatus/db/src/schema";
+
+import type { DB, ServiceContext } from "../context";
+import type {
+ Page,
+ PageComponent,
+ StatusReport,
+ StatusReportUpdate,
+} from "../types";
+import { getReportInWorkspace } from "./internal";
+import {
+ GetStatusReportInput,
+ ListStatusReportsInput,
+ type StatusReportListPeriod,
+} from "./schemas";
+
+function periodToSince(period: StatusReportListPeriod): Date {
+ const day = 24 * 60 * 60 * 1000;
+ const now = Date.now();
+ switch (period) {
+ case "1d":
+ return new Date(now - 1 * day);
+ case "7d":
+ return new Date(now - 7 * day);
+ case "14d":
+ return new Date(now - 14 * day);
+ }
+}
+
+export type StatusReportWithRelations = StatusReport & {
+ updates: StatusReportUpdate[];
+ pageComponents: PageComponent[];
+ /** Flat list of associated component ids. Convenience for proto conversion. */
+ pageComponentIds: number[];
+ /**
+ * The owning page with its full component roster. `null` when the report
+ * has no `pageId` — rare today but schema-allowed.
+ */
+ page: (Page & { pageComponents: PageComponent[] }) | null;
+};
+
+export type ListStatusReportsResult = {
+ items: StatusReportWithRelations[];
+ totalSize: number;
+};
+
+/**
+ * Load relations for a set of status reports in three batched queries
+ * (updates, component associations, pages + page components) regardless of
+ * how many reports were passed in. Avoids the O(N) per-row pattern that
+ * pairs badly with the dashboard's effectively-unlimited list request.
+ */
+async function enrichReportsBatch(
+ db: DB,
+ rows: StatusReport[],
+): Promise<StatusReportWithRelations[]> {
+ if (rows.length === 0) return [];
+
+ const reportIds = rows.map((r) => r.id);
+ const pageIdsSet = new Set<number>();
+ for (const r of rows) if (r.pageId != null) pageIdsSet.add(r.pageId);
+ const pageIds = Array.from(pageIdsSet);
+
+ // One query: all updates for all reports, newest-first.
+ const allUpdates = await db
+ .select()
+ .from(statusReportUpdate)
+ .where(inArray(statusReportUpdate.statusReportId, reportIds))
+ .orderBy(desc(statusReportUpdate.date))
+ .all();
+ const updatesByReport = new Map<number, StatusReportUpdate[]>();
+ for (const u of allUpdates) {
+ const arr = updatesByReport.get(u.statusReportId);
+ if (arr) arr.push(u);
+ else updatesByReport.set(u.statusReportId, [u]);
+ }
+
+ // One query: all component associations joined to their components.
+ // Explicit column selection with aliases avoids depending on drizzle's
+ // auto-derived `row.<object_name>` keys — those are named after the
+ // exported JS variable, so a rename in the schema silently breaks the
+ // row shape at runtime.
+ const assocRows = await db
+ .select({
+ reportId: statusReportsToPageComponents.statusReportId,
+ component: pageComponent,
+ })
+ .from(pageComponent)
+ .innerJoin(
+ statusReportsToPageComponents,
+ eq(statusReportsToPageComponents.pageComponentId, pageComponent.id),
+ )
+ .where(inArray(statusReportsToPageComponents.statusReportId, reportIds))
+ .all();
+ const componentsByReport = new Map<number, PageComponent[]>();
+ for (const row of assocRows) {
+ const component = row.component as unknown as PageComponent;
+ const arr = componentsByReport.get(row.reportId);
+ if (arr) arr.push(component);
+ else componentsByReport.set(row.reportId, [component]);
+ }
+
+ // Two queries: distinct pages + their component rosters. Keyed by pageId so
+ // multiple reports sharing a page share the same Page object.
+ const pageById = new Map<
+ number,
+ Page & { pageComponents: PageComponent[] }
+ >();
+ if (pageIds.length > 0) {
+ const [pageRows, pageSiblings] = await Promise.all([
+ db.select().from(pageTable).where(inArray(pageTable.id, pageIds)).all(),
+ db
+ .select()
+ .from(pageComponent)
+ .where(inArray(pageComponent.pageId, pageIds))
+ .all(),
+ ]);
+ const siblingsByPageId = new Map<number, PageComponent[]>();
+ for (const c of pageSiblings) {
+ const arr = siblingsByPageId.get(c.pageId);
+ if (arr) arr.push(c as unknown as PageComponent);
+ else siblingsByPageId.set(c.pageId, [c as unknown as PageComponent]);
+ }
+ for (const p of pageRows) {
+ pageById.set(p.id, {
+ ...selectPageSchema.parse(p),
+ pageComponents: siblingsByPageId.get(p.id) ?? [],
+ });
+ }
+ }
+
+ return rows.map((r) => {
+ const components = componentsByReport.get(r.id) ?? [];
+ return {
+ ...r,
+ updates: updatesByReport.get(r.id) ?? [],
+ pageComponents: components,
+ pageComponentIds: components.map((c) => c.id),
+ page: r.pageId != null ? pageById.get(r.pageId) ?? null : null,
+ };
+ });
+}
+
+export async function listStatusReports(args: {
+ ctx: ServiceContext;
+ input: ListStatusReportsInput;
+}): Promise<ListStatusReportsResult> {
+ const { ctx } = args;
+ const input = ListStatusReportsInput.parse(args.input);
+ const db = ctx.db ?? defaultDb;
+
+ const conditions: SQL[] = [eq(statusReport.workspaceId, ctx.workspace.id)];
+ if (input.statuses.length > 0) {
+ conditions.push(inArray(statusReport.status, input.statuses));
+ }
+ if (input.pageId !== undefined) {
+ conditions.push(eq(statusReport.pageId, input.pageId));
+ }
+ if (input.period !== undefined) {
+ conditions.push(gte(statusReport.createdAt, periodToSince(input.period)));
+ }
+ const whereClause = and(...conditions);
+
+ const [countRow, rows] = await Promise.all([
+ db
+ .select({ count: sql<number>`count(*)` })
+ .from(statusReport)
+ .where(whereClause)
+ .get(),
+ db
+ .select()
+ .from(statusReport)
+ .where(whereClause)
+ .orderBy(
+ input.order === "asc"
+ ? asc(statusReport.createdAt)
+ : desc(statusReport.createdAt),
+ )
+ .limit(input.limit)
+ .offset(input.offset)
+ .all(),
+ ]);
+
+ const totalSize = countRow?.count ?? 0;
+ const items = await enrichReportsBatch(db, rows);
+ return { items, totalSize };
+}
+
+export async function getStatusReport(args: {
+ ctx: ServiceContext;
+ input: GetStatusReportInput;
+}): Promise<StatusReportWithRelations> {
+ const { ctx } = args;
+ const input = GetStatusReportInput.parse(args.input);
+ const db = ctx.db ?? defaultDb;
+
+ const report = await getReportInWorkspace({
+ tx: db,
+ id: input.id,
+ workspaceId: ctx.workspace.id,
+ });
+ const [enriched] = await enrichReportsBatch(db, [report]);
+ // `enrichReportsBatch` guarantees a 1:1 mapping for a non-empty input.
+ // biome-ignore lint/style/noNonNullAssertion: always non-null for len === 1
+ return enriched!;
+}
diff --git a/packages/services/src/status-report/notify.ts b/packages/services/src/status-report/notify.ts
new file mode 100644
index 000000000..1f3ec1c45
--- /dev/null
+++ b/packages/services/src/status-report/notify.ts
@@ -0,0 +1,63 @@
+import { db as defaultDb, eq } from "@openstatus/db";
+import { statusReport, statusReportUpdate } from "@openstatus/db/src/schema";
+import { dispatchStatusReportUpdate } from "@openstatus/subscriptions";
+
+import { emitAudit } from "../audit";
+import type { ServiceContext } from "../context";
+import { ForbiddenError, NotFoundError } from "../errors";
+import { NotifyStatusReportInput } from "./schemas";
+
+/**
+ * Dispatch subscriber notifications for a specific status-report update.
+ * Separate from the mutation services because the dashboard runs on the Edge
+ * runtime and cannot fire-and-forget — callers invoke this as a second,
+ * awaited call after the mutation (see service-layer-plan.md §Notifications).
+ *
+ * Enforces:
+ * - Workspace owns the target update (via join to the parent report).
+ * - Plan has `status-subscribers` enabled — otherwise no-op.
+ */
+export async function notifyStatusReport(args: {
+ ctx: ServiceContext;
+ input: NotifyStatusReportInput;
+}): Promise<void> {
+ const { ctx } = args;
+ const input = NotifyStatusReportInput.parse(args.input);
+ const db = ctx.db ?? defaultDb;
+
+ const row = await db
+ .select({
+ updateId: statusReportUpdate.id,
+ reportWorkspaceId: statusReport.workspaceId,
+ })
+ .from(statusReportUpdate)
+ .innerJoin(
+ statusReport,
+ eq(statusReportUpdate.statusReportId, statusReport.id),
+ )
+ .where(eq(statusReportUpdate.id, input.statusReportUpdateId))
+ .get();
+
+ if (!row) {
+ throw new NotFoundError("status_report_update", input.statusReportUpdateId);
+ }
+ if (row.reportWorkspaceId !== ctx.workspace.id) {
+ throw new ForbiddenError(
+ "Status report update does not belong to this workspace.",
+ );
+ }
+
+ if (!ctx.workspace.limits["status-subscribers"]) {
+ // Plan does not enable subscribers — silently skip, matching existing
+ // `emailRouter.sendStatusReport` behaviour.
+ return;
+ }
+
+ await dispatchStatusReportUpdate(input.statusReportUpdateId);
+
+ await emitAudit(db, ctx, {
+ action: "status_report.notify",
+ entityType: "status_report_update",
+ entityId: input.statusReportUpdateId,
+ });
+}
diff --git a/packages/services/src/status-report/resolve.ts b/packages/services/src/status-report/resolve.ts
new file mode 100644
index 000000000..727c3286c
--- /dev/null
+++ b/packages/services/src/status-report/resolve.ts
@@ -0,0 +1,27 @@
+import type { ServiceContext } from "../context";
+import {
+ type AddStatusReportUpdateResult,
+ addStatusReportUpdate,
+} from "./add-update";
+import { ResolveStatusReportInput } from "./schemas";
+
+/**
+ * Convenience over addStatusReportUpdate with status="resolved". Exists so
+ * Slack's `resolveStatusReport` action has a named call site with matching
+ * intent; audit action is still `status_report.add_update` (same db path).
+ */
+export async function resolveStatusReport(args: {
+ ctx: ServiceContext;
+ input: ResolveStatusReportInput;
+}): Promise<AddStatusReportUpdateResult> {
+ const input = ResolveStatusReportInput.parse(args.input);
+ return addStatusReportUpdate({
+ ctx: args.ctx,
+ input: {
+ statusReportId: input.statusReportId,
+ status: "resolved",
+ message: input.message,
+ date: input.date,
+ },
+ });
+}
diff --git a/packages/services/src/status-report/schemas.ts b/packages/services/src/status-report/schemas.ts
new file mode 100644
index 000000000..5aa0ca418
--- /dev/null
+++ b/packages/services/src/status-report/schemas.ts
@@ -0,0 +1,92 @@
+import { statusReportStatusSchema } from "@openstatus/db/src/schema";
+import { z } from "zod";
+
+export { statusReportStatusSchema };
+export type StatusReportStatus = z.infer<typeof statusReportStatusSchema>;
+
+/** Periods supported by the status-report list filter — matches tRPC today. */
+export const statusReportListPeriods = ["1d", "7d", "14d"] as const;
+export type StatusReportListPeriod = (typeof statusReportListPeriods)[number];
+export const statusReportListPeriodSchema = z.enum(statusReportListPeriods);
+
+export const CreateStatusReportInput = z.object({
+ title: z.string().min(1).max(256),
+ status: statusReportStatusSchema,
+ message: z.string(),
+ date: z.coerce.date(),
+ pageId: z.number().int(),
+ pageComponentIds: z.array(z.number().int()).default([]),
+});
+export type CreateStatusReportInput = z.infer<typeof CreateStatusReportInput>;
+
+export const UpdateStatusReportInput = z.object({
+ id: z.number().int(),
+ title: z.string().min(1).max(256).optional(),
+ status: statusReportStatusSchema.optional(),
+ /** When provided, replaces the full association set (empty array clears). */
+ pageComponentIds: z.array(z.number().int()).optional(),
+});
+export type UpdateStatusReportInput = z.infer<typeof UpdateStatusReportInput>;
+
+export const AddStatusReportUpdateInput = z.object({
+ statusReportId: z.number().int(),
+ status: statusReportStatusSchema,
+ message: z.string(),
+ date: z.coerce.date().optional(),
+});
+export type AddStatusReportUpdateInput = z.infer<
+ typeof AddStatusReportUpdateInput
+>;
+
+export const UpdateStatusReportUpdateInput = z.object({
+ id: z.number().int(),
+ status: statusReportStatusSchema.optional(),
+ message: z.string().optional(),
+ date: z.coerce.date().optional(),
+});
+export type UpdateStatusReportUpdateInput = z.infer<
+ typeof UpdateStatusReportUpdateInput
+>;
+
+export const ResolveStatusReportInput = z.object({
+ statusReportId: z.number().int(),
+ message: z.string(),
+ date: z.coerce.date().optional(),
+});
+export type ResolveStatusReportInput = z.infer<typeof ResolveStatusReportInput>;
+
+export const DeleteStatusReportInput = z.object({
+ id: z.number().int(),
+});
+export type DeleteStatusReportInput = z.infer<typeof DeleteStatusReportInput>;
+
+export const DeleteStatusReportUpdateInput = z.object({
+ id: z.number().int(),
+});
+export type DeleteStatusReportUpdateInput = z.infer<
+ typeof DeleteStatusReportUpdateInput
+>;
+
+export const GetStatusReportInput = z.object({
+ id: z.number().int(),
+});
+export type GetStatusReportInput = z.infer<typeof GetStatusReportInput>;
+
+// `limit` is intentionally unbounded at the schema level: API-style callers
+// (Connect) should cap in their adapter (external API boundary); dashboard
+// callers need the full set today and don't paginate. A huge sentinel lets
+// tRPC pass "effectively unlimited" without changing the surface.
+export const ListStatusReportsInput = z.object({
+ limit: z.number().int().min(1).default(50),
+ offset: z.number().int().min(0).default(0),
+ statuses: z.array(statusReportStatusSchema).default([]),
+ pageId: z.number().int().optional(),
+ period: statusReportListPeriodSchema.optional(),
+ order: z.enum(["asc", "desc"]).default("desc"),
+});
+export type ListStatusReportsInput = z.infer<typeof ListStatusReportsInput>;
+
+export const NotifyStatusReportInput = z.object({
+ statusReportUpdateId: z.number().int(),
+});
+export type NotifyStatusReportInput = z.infer<typeof NotifyStatusReportInput>;
diff --git a/packages/services/src/status-report/update.ts b/packages/services/src/status-report/update.ts
new file mode 100644
index 000000000..cdcad1213
--- /dev/null
+++ b/packages/services/src/status-report/update.ts
@@ -0,0 +1,138 @@
+import { eq } from "@openstatus/db";
+import { statusReport, statusReportUpdate } from "@openstatus/db/src/schema";
+
+import { emitAudit } from "../audit";
+import { type ServiceContext, withTransaction } from "../context";
+import { InternalServiceError } from "../errors";
+import type { StatusReport, StatusReportUpdate } from "../types";
+import {
+ getReportInWorkspace,
+ getReportUpdateInWorkspace,
+ updatePageComponentAssociations,
+ validatePageComponentIds,
+} from "./internal";
+import {
+ UpdateStatusReportInput,
+ UpdateStatusReportUpdateInput,
+} from "./schemas";
+
+/**
+ * Update status-report metadata (title / status) and optionally replace the
+ * full set of page-component associations. Passing
+ * `pageComponentIds: []` clears the associations (and nulls `pageId`);
+ * omitting the field leaves both untouched.
+ *
+ * The report's `pageId` follows its components: when the caller supplies
+ * a new set of associations the report moves to whatever page those
+ * components live on. Mixed-page inputs are rejected upstream by
+ * `validatePageComponentIds` (all ids must share a page), so the only
+ * states here are "one page" or "no components".
+ */
+export async function updateStatusReport(args: {
+ ctx: ServiceContext;
+ input: UpdateStatusReportInput;
+}): Promise<StatusReport> {
+ const { ctx } = args;
+ const input = UpdateStatusReportInput.parse(args.input);
+
+ return withTransaction(ctx, async (tx) => {
+ const report = await getReportInWorkspace({
+ tx,
+ id: input.id,
+ workspaceId: ctx.workspace.id,
+ });
+
+ const updateValues: Record<string, unknown> = { updatedAt: new Date() };
+ if (input.title !== undefined) updateValues.title = input.title;
+ if (input.status !== undefined) updateValues.status = input.status;
+
+ if (input.pageComponentIds !== undefined) {
+ const validated = await validatePageComponentIds({
+ tx,
+ workspaceId: ctx.workspace.id,
+ pageComponentIds: input.pageComponentIds,
+ });
+
+ // `pageId` follows the association set: a new non-empty set moves
+ // the report to that page; an empty set nulls it. This is the
+ // behavior the Connect `UpdateStatusReport` tests have encoded
+ // since the original handler — no caller today wants a "report
+ // pinned to page X regardless of its components" guarantee.
+ updateValues.pageId = validated.pageId;
+
+ await updatePageComponentAssociations({
+ tx,
+ statusReportId: report.id,
+ componentIds: validated.componentIds,
+ });
+ }
+
+ const updated = await tx
+ .update(statusReport)
+ .set(updateValues)
+ .where(eq(statusReport.id, report.id))
+ .returning()
+ .get();
+
+ if (!updated) {
+ throw new InternalServiceError(
+ `failed to update status report ${report.id}`,
+ );
+ }
+
+ await emitAudit(tx, ctx, {
+ action: "status_report.update",
+ entityType: "status_report",
+ entityId: updated.id,
+ before: report,
+ after: updated,
+ });
+
+ return updated;
+ });
+}
+
+/** Edit a single status-report update row (message / date / status). */
+export async function updateStatusReportUpdate(args: {
+ ctx: ServiceContext;
+ input: UpdateStatusReportUpdateInput;
+}): Promise<StatusReportUpdate> {
+ const { ctx } = args;
+ const input = UpdateStatusReportUpdateInput.parse(args.input);
+
+ return withTransaction(ctx, async (tx) => {
+ const existing = await getReportUpdateInWorkspace({
+ tx,
+ id: input.id,
+ workspaceId: ctx.workspace.id,
+ });
+
+ const updateValues: Record<string, unknown> = { updatedAt: new Date() };
+ if (input.status !== undefined) updateValues.status = input.status;
+ if (input.message !== undefined) updateValues.message = input.message;
+ if (input.date !== undefined) updateValues.date = input.date;
+
+ const updated = await tx
+ .update(statusReportUpdate)
+ .set(updateValues)
+ .where(eq(statusReportUpdate.id, existing.id))
+ .returning()
+ .get();
+
+ if (!updated) {
+ throw new InternalServiceError(
+ `failed to update status report update ${existing.id}`,
+ );
+ }
+
+ await emitAudit(tx, ctx, {
+ action: "status_report.update_update",
+ entityType: "status_report_update",
+ entityId: updated.id,
+ before: existing,
+ after: updated,
+ });
+
+ return updated;
+ });
+}
diff --git a/packages/services/src/types.ts b/packages/services/src/types.ts
index a0e5199f6..08ea58063 100644
--- a/packages/services/src/types.ts
+++ b/packages/services/src/types.ts
@@ -13,3 +13,11 @@ export type {
WorkspacePlan,
WorkspaceRole,
} from "@openstatus/db/src/schema";
+
+export type {
+ StatusReport,
+ StatusReportStatus,
+ StatusReportUpdate,
+} from "@openstatus/db/src/schema";
+
+export type { Page, PageComponent } from "@openstatus/db/src/schema";
diff --git a/packages/services/test/preload.ts b/packages/services/test/preload.ts
new file mode 100644
index 000000000..930c5f61f
--- /dev/null
+++ b/packages/services/test/preload.ts
@@ -0,0 +1,14 @@
+// Bun test preload. Runs once before any test file is imported.
+//
+// `packages/services/src/status-report/notify.ts` imports
+// `@openstatus/subscriptions`, which transitively imports
+// `@openstatus/emails`. `@openstatus/emails` validates `RESEND_API_KEY`
+// via `@t3-oss/env-core` at module-load time and throws on missing.
+//
+// Tests never exercise the real dispatch path — they assert on db state
+// and audit rows. Stubbing the env var lets the import graph resolve
+// without plumbing a real Resend key (which CI / local dev shouldn't
+// need just to run unit tests).
+if (!process.env.RESEND_API_KEY) {
+ process.env.RESEND_API_KEY = "re_test_stub";
+}
diff --git a/packages/services/tsconfig.json b/packages/services/tsconfig.json
index a4b10770f..4f1fc5013 100644
--- a/packages/services/tsconfig.json
+++ b/packages/services/tsconfig.json
@@ -1,5 +1,5 @@
{
- "extends": "@openstatus/tsconfig/base.json",
+ "extends": "@openstatus/tsconfig/react-library.json",
"include": ["src", "test"],
"exclude": ["dist", "build", "node_modules"]
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 5a7a7bfa7..19e3539dd 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -73,7 +73,7 @@ importers:
version: 0.15.15
'@openpanel/nextjs':
specifier: 1.2.0
'@openstatus/analytics':
specifier: workspace:*
version: link:../../packages/analytics
@@ -187,7 +187,7 @@ importers:
'@sentry/nextjs':
specifier: 10.31.0
'@stripe/stripe-js':
specifier: 2.1.6
version: 2.1.6
@@ -202,7 +202,7 @@ importers:
'@trpc/next':
specifier: 11.4.4
'@trpc/react-query':
specifier: 11.4.4
@@ -235,13 +235,13 @@ importers:
next-auth:
specifier: 5.0.0-beta.29
next-themes:
specifier: 0.4.6
nuqs:
specifier: 2.8.5
random-word-slugs:
specifier: 0.1.7
version: 0.1.7
@@ -512,6 +512,9 @@ importers:
'@openstatus/regions':
specifier: workspace:*
version: link:../../packages/regions
+ '@openstatus/services':
+ specifier: workspace:*
+ version: link:../../packages/services
'@openstatus/subscriptions':
specifier: workspace:*
version: link:../../packages/subscriptions
@@ -620,7 +623,7 @@ importers:
version: 0.15.15
'@openpanel/nextjs':
specifier: 1.2.0
'@openstatus/analytics':
specifier: workspace:*
version: link:../../packages/analytics
@@ -665,7 +668,7 @@ importers:
'@sentry/nextjs':
specifier: 10.31.0
'@stripe/stripe-js':
specifier: 2.1.6
version: 2.1.6
@@ -680,7 +683,7 @@ importers:
'@trpc/next':
specifier: 11.4.4
'@trpc/react-query':
specifier: 11.4.4
@@ -716,19 +719,19 @@ importers:
next-auth:
specifier: 5.0.0-beta.29
next-intl:
specifier: ^4.8.3
next-plausible:
specifier: 3.12.5
next-themes:
specifier: 0.4.6
nuqs:
specifier: 2.8.5
react:
specifier: 19.2.3
version: 19.2.3
@@ -825,7 +828,7 @@ importers:
version: 0.15.15
'@openpanel/nextjs':
specifier: 1.2.0
'@openstatus/analytics':
specifier: workspace:*
version: link:../../packages/analytics
@@ -897,7 +900,7 @@ importers:
version: link:../../packages/utils
'@sentry/nextjs':
specifier: 10.31.0
'@stripe/stripe-js':
specifier: 2.1.6
version: 2.1.6
@@ -924,7 +927,7 @@ importers:
'@trpc/next':
specifier: 11.4.4
'@trpc/react-query':
specifier: 11.4.4
@@ -975,19 +978,19 @@ importers:
next-auth:
specifier: 5.0.0-beta.29
next-mdx-remote:
specifier: 6.0.0
version: 6.0.0(@types/[email protected])([email protected])
next-plausible:
specifier: 3.12.5
next-themes:
specifier: 0.4.6
nuqs:
specifier: 2.8.5
random-word-slugs:
specifier: 0.1.7
version: 0.1.7
@@ -1276,6 +1279,9 @@ importers:
'@openstatus/regions':
specifier: workspace:*
version: link:../regions
+ '@openstatus/services':
+ specifier: workspace:*
+ version: link:../services
'@openstatus/subscriptions':
specifier: workspace:*
version: link:../subscriptions
@@ -1413,7 +1419,7 @@ importers:
version: 0.31.4
next-auth:
specifier: 5.0.0-beta.29
typescript:
specifier: 5.9.3
version: 5.9.3
@@ -2023,6 +2029,9 @@ importers:
'@openstatus/db':
specifier: workspace:*
version: link:../db
+ '@openstatus/subscriptions':
+ specifier: workspace:*
+ version: link:../subscriptions
zod:
specifier: 4.1.13
version: 4.1.13
@@ -14860,7 +14869,7 @@ snapshots:
'@openpanel/web': 1.0.1
dependencies:
'@openpanel/web': 1.1.0
@@ -17197,7 +17206,7 @@ snapshots:
'@sentry/types': 8.9.2
'@sentry/utils': 8.9.2
dependencies:
'@opentelemetry/api': 1.9.0
'@opentelemetry/semantic-conventions': 1.38.0
@@ -17977,7 +17986,7 @@ snapshots:
'@trpc/server': 11.4.4([email protected])
typescript: 5.9.3
dependencies:
'@trpc/server': 11.4.4([email protected])
@@ -21650,7 +21659,7 @@ snapshots:
dependencies:
'@auth/core': 0.40.0
@@ -21689,7 +21698,7 @@ snapshots:
- '@types/react'
- supports-color
dependencies:
react: 19.2.3
@@ -21811,7 +21820,7 @@ snapshots:
dependencies:
boolbase: 1.0.0
dependencies:
'@standard-schema/spec': 1.0.0
react: 19.2.3