Skip to content

Open-source status page, incident response and uptime monitoring

Migration to OpenStatus from Atlassian StatusPage (#1933)

Moulik Aggarwal76e68b1979e0
diff --git a/apps/dashboard/package.json b/apps/dashboard/package.json
index 9378c1ab4..dc5e29703 100644
--- a/apps/dashboard/package.json
+++ b/apps/dashboard/package.json
@@ -30,6 +30,7 @@
"@openstatus/error": "workspace:*",
"@openstatus/header-analysis": "workspace:*",
"@openstatus/icons": "workspace:*",
+ "@openstatus/importers": "workspace:*",
"@openstatus/notification-discord": "workspace:*",
"@openstatus/notification-emails": "workspace:*",
"@openstatus/notification-google-chat": "workspace:*",
diff --git a/apps/dashboard/src/components/forms/components/form-import.tsx b/apps/dashboard/src/components/forms/components/form-import.tsx
new file mode 100644
index 000000000..8ff2deec8
--- /dev/null
+++ b/apps/dashboard/src/components/forms/components/form-import.tsx
@@ -0,0 +1,352 @@
+"use client";
+
+import { Note } from "@/components/common/note";
+import {
+ FormCard,
+ FormCardContent,
+ FormCardDescription,
+ FormCardFooter,
+ FormCardHeader,
+ FormCardSeparator,
+ FormCardTitle,
+} from "@/components/forms/form-card";
+import { useTRPC } from "@/lib/trpc/client";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { StatuspageIcon } from "@openstatus/icons";
+import type { ImportSummary } from "@openstatus/importers/types";
+import { Badge } from "@openstatus/ui/components/ui/badge";
+import { Button } from "@openstatus/ui/components/ui/button";
+import {
+ Form,
+ FormControl,
+ FormDescription,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@openstatus/ui/components/ui/form";
+import { Input } from "@openstatus/ui/components/ui/input";
+import {
+ RadioGroup,
+ RadioGroupItem,
+} from "@openstatus/ui/components/ui/radio-group";
+import { Switch } from "@openstatus/ui/components/ui/switch";
+import { useMutation } from "@tanstack/react-query";
+import { isTRPCClientError } from "@trpc/client";
+import { AlertTriangle } from "lucide-react";
+import { useTransition } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const schema = z.object({
+ provider: z.enum(["statuspage"]),
+ apiKey: z.string().min(1, "API key is required"),
+ statuspagePageId: z.string().optional(),
+ includeStatusReports: z.boolean(),
+ includeSubscribers: z.boolean(),
+ includeComponents: z.boolean(),
+});
+
+export type ImportFormValues = z.input<typeof schema>;
+
+function getPhaseCount(preview: ImportSummary, phase: string): number {
+ return preview.phases.find((p) => p.phase === phase)?.resources.length ?? 0;
+}
+
+const PHASE_LABELS: Record<string, string> = {
+ componentGroups: "Component Groups",
+ components: "Components",
+ incidents: "Status Reports",
+ maintenances: "Maintenances",
+ subscribers: "Subscribers",
+};
+
+export function FormImport({
+ pageId,
+ onSubmit,
+}: {
+ pageId: number;
+ onSubmit: (values: ImportFormValues) => Promise<ImportSummary>;
+}) {
+ const form = useForm<ImportFormValues>({
+ resolver: zodResolver(schema),
+ defaultValues: {
+ provider: undefined,
+ apiKey: "",
+ statuspagePageId: "",
+ includeStatusReports: true,
+ includeSubscribers: false,
+ includeComponents: true,
+ },
+ });
+ const [isPending, startTransition] = useTransition();
+ const trpc = useTRPC();
+ const watchProvider = form.watch("provider");
+ const watchApiKey = form.watch("apiKey");
+ const watchStatuspagePageId = form.watch("statuspagePageId");
+
+ const previewMutation = useMutation(
+ trpc.import.preview.mutationOptions({
+ onError: (error) => {
+ if (isTRPCClientError(error)) {
+ toast.error(error.message);
+ } else {
+ toast.error("Failed to preview import");
+ }
+ },
+ }),
+ );
+
+ async function runPreview() {
+ const apiKey = form.getValues("apiKey");
+ if (!apiKey) {
+ form.setError("apiKey", { message: "API key is required" });
+ return;
+ }
+ previewMutation.mutate({
+ provider: "statuspage",
+ apiKey: watchApiKey,
+ statuspagePageId: watchStatuspagePageId || undefined,
+ pageId,
+ });
+ }
+
+ function submitAction(values: ImportFormValues) {
+ if (isPending || !previewMutation.data) return;
+
+ startTransition(async () => {
+ try {
+ const promise = onSubmit(values);
+ toast.promise(promise, {
+ loading: "Importing...",
+ success: (result) => {
+ if (result.status === "partial")
+ return "Import completed with warnings";
+ return "Import completed";
+ },
+ error: (error) => {
+ if (isTRPCClientError(error)) {
+ return error.message;
+ }
+ return "Import failed";
+ },
+ });
+ await promise;
+ } catch (error) {
+ console.error(error);
+ }
+ });
+ }
+ return (
+ <Form {...form}>
+ <form onSubmit={form.handleSubmit(submitAction)}>
+ <FormCard>
+ <FormCardHeader>
+ <FormCardTitle>Import</FormCardTitle>
+ <FormCardDescription>
+ Import components, incidents, and subscribers from an external
+ status page provider.
+ </FormCardDescription>
+ </FormCardHeader>
+ <FormCardSeparator />
+ <FormCardContent>
+ <FormField
+ control={form.control}
+ name="provider"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Provider</FormLabel>
+ <FormControl>
+ <RadioGroup
+ onValueChange={field.onChange}
+ defaultValue={field.value}
+ className="grid grid-cols-2 gap-4 sm:grid-cols-4"
+ >
+ <FormItem className="relative flex cursor-pointer flex-row items-center gap-3 rounded-md border border-input px-2 py-3 text-center shadow-xs outline-none transition-[color,box-shadow] has-data-[state=checked]:border-primary/50 has-focus-visible:border-ring has-focus-visible:ring-[3px] has-focus-visible:ring-ring/50">
+ <FormControl>
+ <RadioGroupItem
+ value="statuspage"
+ className="sr-only"
+ />
+ </FormControl>
+ <StatuspageIcon
+ className="size-4 shrink-0 text-foreground"
+ aria-hidden="true"
+ />
+ <FormLabel className="cursor-pointer font-medium text-foreground text-xs leading-none after:absolute after:inset-0">
+ Atlassian Statuspage
+ </FormLabel>
+ </FormItem>
+ <div className="col-span-1 self-end text-muted-foreground text-xs sm:place-self-end">
+ Missing a provider?{" "}
+ <a href="mailto:[email protected]">Contact us</a>
+ </div>
+ </RadioGroup>
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ </FormCardContent>
+ {watchProvider ? (
+ <>
+ <FormCardSeparator />
+ <FormCardContent className="grid gap-4">
+ <FormField
+ control={form.control}
+ name="apiKey"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>API Key</FormLabel>
+ <FormControl>
+ <Input
+ type="password"
+ placeholder="OAuth API key"
+ {...field}
+ />
+ </FormControl>
+ <FormMessage />
+ <FormDescription>
+ Your Statuspage API key. Found in your Statuspage
+ account under Manage Account &gt; API.
+ </FormDescription>
+ </FormItem>
+ )}
+ />
+ <FormField
+ control={form.control}
+ name="statuspagePageId"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Page ID (optional)</FormLabel>
+ <FormControl>
+ <Input placeholder="e.g. abc123def456" {...field} />
+ </FormControl>
+ <FormDescription>
+ Import a specific page. Leave empty to import across
+ pages.
+ </FormDescription>
+ </FormItem>
+ )}
+ />
+ <Button
+ type="button"
+ variant="secondary"
+ onClick={runPreview}
+ disabled={previewMutation.isPending}
+ >
+ {previewMutation.isPending
+ ? "Loading preview..."
+ : "Preview Import"}
+ </Button>
+ </FormCardContent>
+ </>
+ ) : null}
+ {previewMutation.data ? (
+ <>
+ <FormCardSeparator />
+ <FormCardContent className="grid gap-4">
+ <div>
+ <FormLabel>Preview</FormLabel>
+ <div className="mt-2 flex flex-wrap gap-2">
+ {Object.entries(PHASE_LABELS).map(([key, label]) => {
+ const count = getPhaseCount(previewMutation.data, key);
+ if (count === 0) return null;
+ return (
+ <Badge key={key} variant="secondary">
+ {label}: {count}
+ </Badge>
+ );
+ })}
+ </div>
+ </div>
+ {previewMutation.data.errors.length > 0 ? (
+ <Note color="error" size="sm">
+ <AlertTriangle />
+ <p className="text-sm">
+ {previewMutation.data.errors.join(" ")}
+ </p>
+ </Note>
+ ) : null}
+ <FormField
+ control={form.control}
+ name="includeStatusReports"
+ render={({ field }) => (
+ <FormItem className="flex flex-row items-center justify-between">
+ <div className="space-y-0.5">
+ <FormLabel>Status Reports & Maintenances</FormLabel>
+ <FormDescription>
+ Import incidents as status reports and scheduled
+ maintenances.
+ </FormDescription>
+ </div>
+ <FormControl>
+ <Switch
+ checked={field.value}
+ onCheckedChange={field.onChange}
+ />
+ </FormControl>
+ </FormItem>
+ )}
+ />
+ <FormField
+ control={form.control}
+ name="includeComponents"
+ render={({ field }) => (
+ <FormItem className="flex flex-row items-center justify-between">
+ <div className="space-y-0.5">
+ <FormLabel>Components</FormLabel>
+ <FormDescription>
+ Import components and groups.
+ </FormDescription>
+ </div>
+ <FormControl>
+ <Switch
+ checked={field.value}
+ onCheckedChange={field.onChange}
+ />
+ </FormControl>
+ </FormItem>
+ )}
+ />
+ <FormField
+ control={form.control}
+ name="includeSubscribers"
+ render={({ field }) => (
+ <FormItem className="flex flex-row items-center justify-between">
+ <div className="space-y-0.5">
+ <FormLabel>Subscribers</FormLabel>
+ <FormDescription>
+ Import email subscribers.
+ </FormDescription>
+ </div>
+ <FormControl>
+ <Switch
+ checked={field.value}
+ onCheckedChange={field.onChange}
+ />
+ </FormControl>
+ </FormItem>
+ )}
+ />
+ </FormCardContent>
+ </>
+ ) : null}
+ <FormCardFooter>
+ <Button
+ type="submit"
+ disabled={
+ !previewMutation.data ||
+ isPending ||
+ previewMutation.data.errors.length > 0
+ }
+ >
+ {isPending ? "Importing..." : "Import"}
+ </Button>
+ </FormCardFooter>
+ </FormCard>
+ </form>
+ </Form>
+ );
+}
diff --git a/apps/dashboard/src/components/forms/components/update.tsx b/apps/dashboard/src/components/forms/components/update.tsx
index d8d0128c8..73626fbd5 100644
--- a/apps/dashboard/src/components/forms/components/update.tsx
+++ b/apps/dashboard/src/components/forms/components/update.tsx
@@ -4,12 +4,15 @@ import { FormComponents } from "@/components/forms/components/form-components";
import { useTRPC } from "@/lib/trpc/client";
import { useMutation, useQuery } from "@tanstack/react-query";
import { useParams } from "next/navigation";
+import { useState } from "react";
import { FormCardGroup } from "../form-card";
import { FormConfiguration } from "../status-page/form-configuration";
+import { FormImport, type ImportFormValues } from "./form-import";
export function FormComponentsUpdate() {
const { id } = useParams<{ id: string }>();
const trpc = useTRPC();
+ const [formKey, setFormKey] = useState(0);
const { data: statusPage, refetch } = useQuery(
trpc.page.get.queryOptions({ id: Number.parseInt(id) }),
);
@@ -34,6 +37,15 @@ export function FormComponentsUpdate() {
}),
);
+ const importMutation = useMutation(
+ trpc.import.run.mutationOptions({
+ onSuccess: async () => {
+ await Promise.all([refetch(), refetchComponents()]);
+ setFormKey((k) => k + 1);
+ },
+ }),
+ );
+
if (!statusPage || !pageComponents || !monitors || !workspace) return null;
// Separate standalone components from grouped components
@@ -81,7 +93,9 @@ export function FormComponentsUpdate() {
return (
<FormCardGroup>
+ {/* key forces remount after import so useForm picks up new defaultValues */}
<FormComponents
+ key={formKey}
pageComponents={standaloneComponents}
monitors={monitors}
allPageComponents={pageComponents}
@@ -115,6 +129,22 @@ export function FormComponentsUpdate() {
}}
configLink={configLink}
/>
+ <FormImport
+ pageId={statusPage.id}
+ onSubmit={async (values: ImportFormValues) => {
+ return await importMutation.mutateAsync({
+ provider: values.provider,
+ apiKey: values.apiKey,
+ pageId: statusPage.id,
+ statuspagePageId: values.statuspagePageId ?? undefined,
+ options: {
+ includeStatusReports: values.includeStatusReports,
+ includeSubscribers: values.includeSubscribers,
+ includeComponents: values.includeComponents,
+ },
+ });
+ }}
+ />
</FormCardGroup>
);
}
diff --git a/packages/api/package.json b/packages/api/package.json
index db3d77a7a..bc156aacb 100644
--- a/packages/api/package.json
+++ b/packages/api/package.json
@@ -14,6 +14,7 @@
"@openstatus/db": "workspace:*",
"@openstatus/emails": "workspace:*",
"@openstatus/error": "workspace:*",
+ "@openstatus/importers": "workspace:*",
"@openstatus/notification-google-chat": "workspace:*",
"@openstatus/notification-grafana-oncall": "workspace:*",
"@openstatus/notification-telegram": "workspace:*",
diff --git a/packages/api/src/edge.ts b/packages/api/src/edge.ts
index 7dc1a4639..49972c733 100644
--- a/packages/api/src/edge.ts
+++ b/packages/api/src/edge.ts
@@ -2,6 +2,7 @@ import { blobRouter } from "./router/blob";
import { checkerRouter } from "./router/checker";
import { domainRouter } from "./router/domain";
import { feedbackRouter } from "./router/feedback";
+import { importRouter } from "./router/import";
import { incidentRouter } from "./router/incident";
import { invitationRouter } from "./router/invitation";
import { maintenanceRouter } from "./router/maintenance";
@@ -42,4 +43,5 @@ export const edgeRouter = createTRPCRouter({
feedback: feedbackRouter,
statusPage: statusPageRouter,
privateLocation: privateLocationRouter,
+ import: importRouter,
});
diff --git a/packages/api/src/router/import.test.ts b/packages/api/src/router/import.test.ts
new file mode 100644
index 000000000..e5684a246
--- /dev/null
+++ b/packages/api/src/router/import.test.ts
@@ -0,0 +1,532 @@
+import { afterAll, beforeAll, expect, test } from "bun:test";
+import { db, eq, inArray } from "@openstatus/db";
+import {
+ maintenance,
+ maintenancesToPageComponents,
+ page,
+ pageComponent,
+ pageComponentGroup,
+ statusReport,
+ statusReportUpdate,
+ statusReportsToPageComponents,
+} from "@openstatus/db/src/schema";
+import { allPlans } from "@openstatus/db/src/schema/plan/config";
+import type { Limits } from "@openstatus/db/src/schema/plan/schema";
+import {
+ MOCK_COMPONENTS,
+ MOCK_COMPONENT_GROUPS,
+ MOCK_INCIDENTS,
+ MOCK_PAGES,
+ MOCK_SUBSCRIBERS,
+} from "@openstatus/importers/statuspage/fixtures";
+
+import { edgeRouter } from "../edge";
+import { previewImport, runImport } from "../service/import";
+import { createInnerTRPCContext } from "../trpc";
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+const originalFetch = globalThis.fetch;
+
+function mockStatuspageFetch() {
+ globalThis.fetch = ((url: string | URL | Request) => {
+ const urlStr = typeof url === "string" ? url : url.toString();
+ let data: unknown = [];
+
+ // For paginated endpoints, return empty on page > 1
+ const pageParam = urlStr.includes("?")
+ ? new URL(urlStr).searchParams.get("page")
+ : null;
+ const isFirstPage = !pageParam || pageParam === "1";
+
+ if (urlStr.endsWith("/pages")) data = MOCK_PAGES;
+ else if (urlStr.includes("/component-groups"))
+ data = isFirstPage ? MOCK_COMPONENT_GROUPS : [];
+ else if (urlStr.includes("/components"))
+ data = isFirstPage ? MOCK_COMPONENTS : [];
+ else if (urlStr.includes("/incidents/scheduled"))
+ data = isFirstPage
+ ? MOCK_INCIDENTS.filter((i) => i.scheduled_for != null)
+ : [];
+ else if (urlStr.includes("/incidents"))
+ data = isFirstPage ? MOCK_INCIDENTS : [];
+ else if (urlStr.includes("/subscribers"))
+ data = isFirstPage ? MOCK_SUBSCRIBERS : [];
+
+ return Promise.resolve(
+ new Response(JSON.stringify(data), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ }),
+ );
+ }) as typeof globalThis.fetch;
+}
+
+function restoreFetch() {
+ globalThis.fetch = originalFetch;
+}
+
+function makeCaller(limitsOverride?: Partial<Limits>) {
+ const limits = { ...allPlans.starter.limits, ...limitsOverride };
+ const ctx = createInnerTRPCContext({
+ req: undefined,
+ session: { user: { id: "1" } },
+ // @ts-expect-error - minimal workspace for test
+ workspace: { id: 1, limits },
+ });
+ return edgeRouter.createCaller(ctx);
+}
+
+// Track all created IDs for cleanup
+const createdIds = {
+ pages: [] as number[],
+ componentGroups: [] as number[],
+ components: [] as number[],
+ statusReports: [] as number[],
+ maintenances: [] as number[],
+};
+
+async function cleanup() {
+ // Delete in reverse dependency order
+
+ // 1. statusReportsToPageComponents
+ if (createdIds.statusReports.length > 0) {
+ await db
+ .delete(statusReportsToPageComponents)
+ .where(
+ inArray(
+ statusReportsToPageComponents.statusReportId,
+ createdIds.statusReports,
+ ),
+ );
+ }
+
+ // 2. maintenancesToPageComponents
+ if (createdIds.maintenances.length > 0) {
+ await db
+ .delete(maintenancesToPageComponents)
+ .where(
+ inArray(
+ maintenancesToPageComponents.maintenanceId,
+ createdIds.maintenances,
+ ),
+ );
+ }
+
+ // 3. statusReportUpdate (via statusReportId)
+ if (createdIds.statusReports.length > 0) {
+ await db
+ .delete(statusReportUpdate)
+ .where(
+ inArray(statusReportUpdate.statusReportId, createdIds.statusReports),
+ );
+ }
+
+ // 4. statusReport
+ if (createdIds.statusReports.length > 0) {
+ await db
+ .delete(statusReport)
+ .where(inArray(statusReport.id, createdIds.statusReports));
+ }
+
+ // 5. maintenance
+ if (createdIds.maintenances.length > 0) {
+ await db
+ .delete(maintenance)
+ .where(inArray(maintenance.id, createdIds.maintenances));
+ }
+
+ // 6. pageComponent
+ if (createdIds.components.length > 0) {
+ await db
+ .delete(pageComponent)
+ .where(inArray(pageComponent.id, createdIds.components));
+ }
+
+ // 7. pageComponentGroup
+ if (createdIds.componentGroups.length > 0) {
+ await db
+ .delete(pageComponentGroup)
+ .where(inArray(pageComponentGroup.id, createdIds.componentGroups));
+ }
+
+ // 8. page (only ones we created, never the seeded page 1)
+ if (createdIds.pages.length > 0) {
+ await db.delete(page).where(inArray(page.id, createdIds.pages));
+ }
+
+ // Reset trackers
+ createdIds.pages = [];
+ createdIds.componentGroups = [];
+ createdIds.components = [];
+ createdIds.statusReports = [];
+ createdIds.maintenances = [];
+}
+
+/** Collect IDs from import summary phases for cleanup tracking. */
+function trackCreatedIds(summary: {
+ phases: Array<{
+ phase: string;
+ resources: Array<{ openstatusId?: number; status: string }>;
+ }>;
+}) {
+ for (const phase of summary.phases) {
+ const ids = phase.resources
+ .filter((r) => r.status === "created" && r.openstatusId)
+ .map((r) => r.openstatusId as number);
+
+ switch (phase.phase) {
+ case "page":
+ createdIds.pages.push(...ids);
+ break;
+ case "componentGroups":
+ createdIds.componentGroups.push(...ids);
+ break;
+ case "components":
+ createdIds.components.push(...ids);
+ break;
+ case "incidents":
+ createdIds.statusReports.push(...ids);
+ break;
+ case "maintenances":
+ createdIds.maintenances.push(...ids);
+ break;
+ }
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Tests
+// ---------------------------------------------------------------------------
+
+beforeAll(() => {
+ mockStatuspageFetch();
+});
+
+afterAll(async () => {
+ restoreFetch();
+ await cleanup();
+});
+
+const caller = makeCaller();
+
+test("preview returns mapped data without DB writes", async () => {
+ const result = await caller.import.preview({
+ provider: "statuspage",
+ apiKey: "test-key",
+ });
+
+ expect(result.provider).toBe("statuspage");
+ expect(result.phases.length).toBeGreaterThan(0);
+
+ // Check that expected phases exist
+ const phaseNames = result.phases.map((p) => p.phase);
+ expect(phaseNames).toContain("page");
+ expect(phaseNames).toContain("components");
+ expect(phaseNames).toContain("componentGroups");
+
+ // Verify resource counts match fixture data
+ const pagePh = result.phases.find((p) => p.phase === "page");
+ expect(pagePh?.resources.length).toBe(MOCK_PAGES.length);
+
+ const compPh = result.phases.find((p) => p.phase === "components");
+ expect(compPh?.resources.length).toBe(MOCK_COMPONENTS.length);
+
+ const groupPh = result.phases.find((p) => p.phase === "componentGroups");
+ expect(groupPh?.resources.length).toBe(MOCK_COMPONENT_GROUPS.length);
+
+ // Verify no pages were created in DB with the slug from mock
+ const dbPage = await db
+ .select()
+ .from(page)
+ .where(eq(page.slug, "acmecorp"))
+ .get();
+ expect(dbPage).toBeUndefined();
+});
+
+test("run creates page, components, and groups in DB", async () => {
+ const result = await caller.import.run({
+ provider: "statuspage",
+ apiKey: "test-key",
+ options: { includeStatusReports: true, includeSubscribers: false },
+ });
+
+ trackCreatedIds(result);
+
+ // Overall status should be completed (subscribers skipped but that's fine)
+ expect(["completed", "partial"]).toContain(result.status);
+
+ // Page should be created with slug "acmecorp"
+ const dbPage = await db
+ .select()
+ .from(page)
+ .where(eq(page.slug, "acmecorp"))
+ .get();
+ if (!dbPage)
+ throw new Error("Expected page to be created with slug 'acmecorp'");
+ expect(dbPage.title).toBe("Acme Corp Status");
+ expect(dbPage.workspaceId).toBe(1);
+
+ // Components should be created
+ const dbComponents = await db
+ .select()
+ .from(pageComponent)
+ .where(eq(pageComponent.pageId, dbPage.id))
+ .all();
+ expect(dbComponents.length).toBe(MOCK_COMPONENTS.length);
+
+ // Groups should be created
+ const dbGroups = await db
+ .select()
+ .from(pageComponentGroup)
+ .where(eq(pageComponentGroup.pageId, dbPage.id))
+ .all();
+ expect(dbGroups.length).toBe(MOCK_COMPONENT_GROUPS.length);
+
+ // Subscribers phase should be skipped
+ const subPhase = result.phases.find((p) => p.phase === "subscribers");
+ expect(subPhase?.status).toBe("skipped");
+
+ // Clean up for next tests
+ await cleanup();
+});
+
+test("run with existing pageId imports into that page", async () => {
+ const result = await caller.import.run({
+ provider: "statuspage",
+ apiKey: "test-key",
+ pageId: 1,
+ options: { includeStatusReports: false, includeSubscribers: false },
+ });
+
+ trackCreatedIds(result);
+
+ expect(["completed", "partial"]).toContain(result.status);
+
+ // Page phase should show "skipped" since we used an existing page
+ const pagePhase = result.phases.find((p) => p.phase === "page");
+ expect(pagePhase?.resources[0]?.status).toBe("skipped");
+ expect(pagePhase?.resources[0]?.openstatusId).toBe(1);
+
+ // Components should be created under page 1
+ const dbComponents = await db
+ .select()
+ .from(pageComponent)
+ .where(eq(pageComponent.pageId, 1))
+ .all();
+ // At least the components we imported should exist
+ const importedCompNames = MOCK_COMPONENTS.map((c) => c.name);
+ const matchingComps = dbComponents.filter((c) =>
+ importedCompNames.includes(c.name),
+ );
+ expect(matchingComps.length).toBe(MOCK_COMPONENTS.length);
+
+ await cleanup();
+});
+
+test("re-run skips already-imported resources (idempotency)", async () => {
+ // First run
+ const result1 = await caller.import.run({
+ provider: "statuspage",
+ apiKey: "test-key",
+ options: { includeStatusReports: false, includeSubscribers: false },
+ });
+ trackCreatedIds(result1);
+
+ // Second run (same data)
+ const result2 = await caller.import.run({
+ provider: "statuspage",
+ apiKey: "test-key",
+ options: { includeStatusReports: false, includeSubscribers: false },
+ });
+ // Don't track again - same resources should be skipped
+
+ // Page should be skipped on second run
+ const pagePhase = result2.phases.find((p) => p.phase === "page");
+ expect(pagePhase?.resources[0]?.status).toBe("skipped");
+
+ // Components should be skipped on second run
+ const compPhase = result2.phases.find((p) => p.phase === "components");
+ const allSkipped = compPhase?.resources.every((r) => r.status === "skipped");
+ expect(allSkipped).toBe(true);
+
+ // Groups should be skipped on second run
+ const groupPhase = result2.phases.find((p) => p.phase === "componentGroups");
+ const allGroupsSkipped = groupPhase?.resources.every(
+ (r) => r.status === "skipped",
+ );
+ expect(allGroupsSkipped).toBe(true);
+
+ await cleanup();
+});
+
+test("run with includeStatusReports creates status reports", async () => {
+ const result = await caller.import.run({
+ provider: "statuspage",
+ apiKey: "test-key",
+ options: { includeStatusReports: true, includeSubscribers: false },
+ });
+
+ trackCreatedIds(result);
+
+ // Incidents phase should be completed
+ const incPhase = result.phases.find((p) => p.phase === "incidents");
+ expect(incPhase).toBeDefined();
+ expect(incPhase?.status).toBe("completed");
+
+ if (!incPhase) throw new Error("Expected incidents phase to exist");
+
+ // Verify status reports were created in DB
+ const createdReportIds = incPhase.resources
+ .filter((r) => r.status === "created" && r.openstatusId)
+ .map((r) => r.openstatusId as number);
+ expect(createdReportIds.length).toBeGreaterThan(0);
+
+ // Check that status report updates were created
+ const updates = await db
+ .select()
+ .from(statusReportUpdate)
+ .where(inArray(statusReportUpdate.statusReportId, createdReportIds))
+ .all();
+ expect(updates.length).toBeGreaterThan(0);
+
+ // Check that statusReportsToPageComponents links exist
+ const links = await db
+ .select()
+ .from(statusReportsToPageComponents)
+ .where(
+ inArray(statusReportsToPageComponents.statusReportId, createdReportIds),
+ )
+ .all();
+ expect(links.length).toBeGreaterThan(0);
+
+ // Maintenances phase should also have entries (scheduled incident)
+ const maintPhase = result.phases.find((p) => p.phase === "maintenances");
+ if (!maintPhase) throw new Error("Expected maintenances phase to exist");
+ const createdMaintIds = maintPhase.resources
+ .filter((r) => r.status === "created" && r.openstatusId)
+ .map((r) => r.openstatusId as number);
+ expect(createdMaintIds.length).toBeGreaterThan(0);
+
+ await cleanup();
+});
+
+// ---------------------------------------------------------------------------
+// Limit warnings (call service directly to control limits)
+// ---------------------------------------------------------------------------
+
+const freeLimits = { ...allPlans.free.limits };
+const starterLimits = { ...allPlans.starter.limits };
+
+test("preview shows component limit warning on free plan", async () => {
+ const result = await previewImport({
+ apiKey: "test-key",
+ workspaceId: 1,
+ limits: { ...freeLimits, "page-components": 3 },
+ });
+
+ expect(result.errors.length).toBeGreaterThan(0);
+ expect(result.errors.some((e) => e.includes("3 of 4"))).toBe(true);
+});
+
+test("preview shows custom domain warning on free plan", async () => {
+ const result = await previewImport({
+ apiKey: "test-key",
+ workspaceId: 1,
+ limits: { ...freeLimits, "custom-domain": false },
+ });
+
+ expect(result.errors.some((e) => e.includes("Custom domain"))).toBe(true);
+});
+
+test("preview shows subscriber warning on free plan", async () => {
+ const result = await previewImport({
+ apiKey: "test-key",
+ workspaceId: 1,
+ limits: { ...freeLimits, "status-subscribers": false },
+ });
+
+ expect(result.errors.some((e) => e.includes("Subscribers"))).toBe(true);
+});
+
+test("preview shows no warnings on starter plan", async () => {
+ const result = await previewImport({
+ apiKey: "test-key",
+ workspaceId: 1,
+ limits: starterLimits,
+ });
+
+ // Only informational warnings about non-email subscribers are expected
+ const limitWarnings = result.errors.filter(
+ (e) => !e.includes("non-email subscriber"),
+ );
+ expect(limitWarnings).toEqual([]);
+});
+
+test("run enforces component limit by truncating", async () => {
+ // Create a dedicated page so we control the state entirely
+ const [testPage] = await db
+ .insert(page)
+ .values({
+ workspaceId: 1,
+ title: "Truncation Test Page",
+ description: "",
+ slug: "truncation-test",
+ customDomain: "",
+ icon: "",
+ })
+ .returning({ id: page.id });
+
+ if (!testPage) throw new Error("Failed to create test page");
+ createdIds.pages.push(testPage.id);
+
+ const result = await runImport({
+ apiKey: "test-key",
+ workspaceId: 1,
+ pageId: testPage.id,
+ limits: { ...starterLimits, "page-components": 2 },
+ options: { includeStatusReports: false, includeSubscribers: false },
+ });
+
+ trackCreatedIds(result);
+
+ // Should have warning about component limit
+ expect(
+ result.errors.some(
+ (e) =>
+ e.includes("page-components") ||
+ e.includes("Component limit") ||
+ e.includes("components can be imported") ||
+ e.includes("plan limit"),
+ ),
+ ).toBe(true);
+
+ // Components phase should show enforcement (either truncated or fully blocked)
+ const compPhase = result.phases.find((p) => p.phase === "components");
+ expect(compPhase).toBeDefined();
+ // With limit of 2, not all 4 mock components should be created
+ const created =
+ compPhase?.resources.filter((r) => r.status === "created") ?? [];
+ expect(created.length).toBeLessThanOrEqual(2);
+
+ await cleanup();
+});
+
+test("run skips subscribers on free plan", async () => {
+ const result = await runImport({
+ apiKey: "test-key",
+ workspaceId: 1,
+ limits: { ...freeLimits, "status-subscribers": false },
+ options: { includeStatusReports: false, includeSubscribers: true },
+ });
+
+ trackCreatedIds(result);
+
+ const subPhase = result.phases.find((p) => p.phase === "subscribers");
+ expect(subPhase?.status).toBe("skipped");
+ expect(result.errors.some((e) => e.includes("Subscribers"))).toBe(true);
+
+ await cleanup();
+});
diff --git a/packages/api/src/router/import.ts b/packages/api/src/router/import.ts
new file mode 100644
index 000000000..2bbdf3844
--- /dev/null
+++ b/packages/api/src/router/import.ts
@@ -0,0 +1,75 @@
+import { and, db, eq } from "@openstatus/db";
+import { page } from "@openstatus/db/src/schema";
+import { TRPCError } from "@trpc/server";
+import { z } from "zod";
+import { previewImport, runImport } from "../service/import";
+import { createTRPCRouter, protectedProcedure } from "../trpc";
+
+export const importRouter = createTRPCRouter({
+ preview: protectedProcedure
+ .input(
+ z.object({
+ provider: z.enum(["statuspage"]),
+ apiKey: z.string().min(1),
+ statuspagePageId: z.string().nullish(),
+ pageId: z.number().optional(),
+ }),
+ )
+ .mutation(async (opts) => {
+ return previewImport({
+ apiKey: opts.input.apiKey,
+ statuspagePageId: opts.input.statuspagePageId ?? undefined,
+ workspaceId: opts.ctx.workspace.id,
+ pageId: opts.input.pageId,
+ limits: opts.ctx.workspace.limits,
+ });
+ }),
+
+ run: protectedProcedure
+ .input(
+ z.object({
+ provider: z.enum(["statuspage"]),
+ apiKey: z.string().min(1),
+ pageId: z.number().optional(),
+ statuspagePageId: z.string().nullish(),
+ options: z
+ .object({
+ includeStatusReports: z.boolean().default(true),
+ includeSubscribers: z.boolean().default(false),
+ includeComponents: z.boolean().default(true),
+ })
+ .optional(),
+ }),
+ )
+ .mutation(async (opts) => {
+ // If pageId provided, verify it belongs to workspace
+ if (opts.input.pageId) {
+ const existing = await db
+ .select()
+ .from(page)
+ .where(
+ and(
+ eq(page.id, opts.input.pageId),
+ eq(page.workspaceId, opts.ctx.workspace.id),
+ ),
+ )
+ .get();
+
+ if (!existing) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Page not found or does not belong to this workspace",
+ });
+ }
+ }
+
+ return runImport({
+ apiKey: opts.input.apiKey,
+ statuspagePageId: opts.input.statuspagePageId ?? undefined,
+ workspaceId: opts.ctx.workspace.id,
+ pageId: opts.input.pageId,
+ options: opts.input.options,
+ limits: opts.ctx.workspace.limits,
+ });
+ }),
+});
diff --git a/packages/api/src/service/import.test.ts b/packages/api/src/service/import.test.ts
new file mode 100644
index 000000000..633c806cf
--- /dev/null
+++ b/packages/api/src/service/import.test.ts
@@ -0,0 +1,363 @@
+import { describe, expect, test } from "bun:test";
+import { allPlans } from "@openstatus/db/src/schema/plan/config";
+import type { Limits } from "@openstatus/db/src/schema/plan/schema";
+import type { ImportSummary } from "@openstatus/importers";
+import { addLimitWarnings } from "./import";
+
+function makeSummary(overrides?: Partial<ImportSummary>): ImportSummary {
+ return {
+ provider: "statuspage",
+ status: "completed",
+ startedAt: new Date(),
+ completedAt: new Date(),
+ phases: [],
+ errors: [],
+ ...overrides,
+ };
+}
+
+function makeLimits(overrides?: Partial<Limits>): Limits {
+ return { ...allPlans.free.limits, ...overrides };
+}
+
+describe("addLimitWarnings", () => {
+ // -------------------------------------------------------------------------
+ // Component limits
+ // -------------------------------------------------------------------------
+ describe("component limits", () => {
+ test("no warning when under limit", async () => {
+ const summary = makeSummary({
+ phases: [
+ {
+ phase: "components",
+ status: "completed",
+ resources: [
+ { sourceId: "1", name: "A", status: "created" },
+ { sourceId: "2", name: "B", status: "created" },
+ ],
+ },
+ ],
+ });
+
+ await addLimitWarnings(summary, {
+ limits: makeLimits({ "page-components": 20 }),
+ workspaceId: 1,
+ });
+
+ expect(summary.errors).toEqual([]);
+ });
+
+ test("no warning when exactly at limit", async () => {
+ const summary = makeSummary({
+ phases: [
+ {
+ phase: "components",
+ status: "completed",
+ resources: [
+ { sourceId: "1", name: "A", status: "created" },
+ { sourceId: "2", name: "B", status: "created" },
+ { sourceId: "3", name: "C", status: "created" },
+ ],
+ },
+ ],
+ });
+
+ await addLimitWarnings(summary, {
+ limits: makeLimits({ "page-components": 3 }),
+ workspaceId: 1,
+ });
+
+ expect(summary.errors).toEqual([]);
+ });
+
+ test("warns when import exceeds limit (no existing components)", async () => {
+ const summary = makeSummary({
+ phases: [
+ {
+ phase: "components",
+ status: "completed",
+ resources: [
+ { sourceId: "1", name: "A", status: "created" },
+ { sourceId: "2", name: "B", status: "created" },
+ { sourceId: "3", name: "C", status: "created" },
+ { sourceId: "4", name: "D", status: "created" },
+ ],
+ },
+ ],
+ });
+
+ await addLimitWarnings(summary, {
+ limits: makeLimits({ "page-components": 3 }),
+ workspaceId: 1,
+ });
+
+ expect(summary.errors.length).toBe(1);
+ expect(summary.errors[0]).toContain("3 of 4");
+ });
+
+ test("no warning when components phase is empty", async () => {
+ const summary = makeSummary({
+ phases: [{ phase: "components", status: "completed", resources: [] }],
+ });
+
+ await addLimitWarnings(summary, {
+ limits: makeLimits({ "page-components": 3 }),
+ workspaceId: 1,
+ });
+
+ expect(summary.errors).toEqual([]);
+ });
+
+ test("no warning when components phase is missing", async () => {
+ const summary = makeSummary({
+ phases: [{ phase: "page", status: "completed", resources: [] }],
+ });
+
+ await addLimitWarnings(summary, {
+ limits: makeLimits({ "page-components": 3 }),
+ workspaceId: 1,
+ });
+
+ expect(summary.errors).toEqual([]);
+ });
+ });
+
+ // -------------------------------------------------------------------------
+ // Custom domain
+ // -------------------------------------------------------------------------
+ describe("custom domain", () => {
+ test("warns when custom domain present on free plan", async () => {
+ const summary = makeSummary({
+ phases: [
+ {
+ phase: "page",
+ status: "completed",
+ resources: [
+ {
+ sourceId: "p1",
+ name: "My Page",
+ status: "created",
+ data: { customDomain: "status.example.com" },
+ },
+ ],
+ },
+ ],
+ });
+
+ await addLimitWarnings(summary, {
+ limits: makeLimits({ "custom-domain": false }),
+ workspaceId: 1,
+ });
+
+ expect(summary.errors.length).toBe(1);
+ expect(summary.errors[0]).toContain("Custom domain");
+ });
+
+ test("no warning when custom domain is empty", async () => {
+ const summary = makeSummary({
+ phases: [
+ {
+ phase: "page",
+ status: "completed",
+ resources: [
+ {
+ sourceId: "p1",
+ name: "My Page",
+ status: "created",
+ data: { customDomain: "" },
+ },
+ ],
+ },
+ ],
+ });
+
+ await addLimitWarnings(summary, {
+ limits: makeLimits({ "custom-domain": false }),
+ workspaceId: 1,
+ });
+
+ expect(summary.errors).toEqual([]);
+ });
+
+ test("no warning on paid plan with custom domain", async () => {
+ const summary = makeSummary({
+ phases: [
+ {
+ phase: "page",
+ status: "completed",
+ resources: [
+ {
+ sourceId: "p1",
+ name: "My Page",
+ status: "created",
+ data: { customDomain: "status.example.com" },
+ },
+ ],
+ },
+ ],
+ });
+
+ await addLimitWarnings(summary, {
+ limits: makeLimits({ "custom-domain": true }),
+ workspaceId: 1,
+ });
+
+ expect(summary.errors).toEqual([]);
+ });
+ });
+
+ // -------------------------------------------------------------------------
+ // Subscribers
+ // -------------------------------------------------------------------------
+ describe("subscribers", () => {
+ test("warns when subscribers present on free plan", async () => {
+ const summary = makeSummary({
+ phases: [
+ {
+ phase: "subscribers",
+ status: "completed",
+ resources: [
+ { sourceId: "s1", name: "[email protected]", status: "created" },
+ { sourceId: "s2", name: "[email protected]", status: "created" },
+ ],
+ },
+ ],
+ });
+
+ await addLimitWarnings(summary, {
+ limits: makeLimits({ "status-subscribers": false }),
+ workspaceId: 1,
+ });
+
+ expect(summary.errors.length).toBe(1);
+ expect(summary.errors[0]).toContain("Subscribers");
+ });
+
+ test("no warning when subscribers phase is empty", async () => {
+ const summary = makeSummary({
+ phases: [{ phase: "subscribers", status: "completed", resources: [] }],
+ });
+
+ await addLimitWarnings(summary, {
+ limits: makeLimits({ "status-subscribers": false }),
+ workspaceId: 1,
+ });
+
+ expect(summary.errors).toEqual([]);
+ });
+
+ test("no warning on paid plan with subscribers", async () => {
+ const summary = makeSummary({
+ phases: [
+ {
+ phase: "subscribers",
+ status: "completed",
+ resources: [
+ { sourceId: "s1", name: "[email protected]", status: "created" },
+ ],
+ },
+ ],
+ });
+
+ await addLimitWarnings(summary, {
+ limits: makeLimits({ "status-subscribers": true }),
+ workspaceId: 1,
+ });
+
+ expect(summary.errors).toEqual([]);
+ });
+ });
+
+ // -------------------------------------------------------------------------
+ // Combined
+ // -------------------------------------------------------------------------
+ test("reports multiple warnings at once", async () => {
+ const summary = makeSummary({
+ phases: [
+ {
+ phase: "page",
+ status: "completed",
+ resources: [
+ {
+ sourceId: "p1",
+ name: "Page",
+ status: "created",
+ data: { customDomain: "status.example.com" },
+ },
+ ],
+ },
+ {
+ phase: "components",
+ status: "completed",
+ resources: [
+ { sourceId: "1", name: "A", status: "created" },
+ { sourceId: "2", name: "B", status: "created" },
+ { sourceId: "3", name: "C", status: "created" },
+ { sourceId: "4", name: "D", status: "created" },
+ ],
+ },
+ {
+ phase: "subscribers",
+ status: "completed",
+ resources: [
+ { sourceId: "s1", name: "[email protected]", status: "created" },
+ ],
+ },
+ ],
+ });
+
+ // Free plan: page-components=3, custom-domain=false, status-subscribers=false
+ await addLimitWarnings(summary, {
+ limits: makeLimits(),
+ workspaceId: 1,
+ });
+
+ expect(summary.errors.length).toBe(3);
+ expect(summary.errors.some((e) => e.includes("3 of 4"))).toBe(true);
+ expect(summary.errors.some((e) => e.includes("Custom domain"))).toBe(true);
+ expect(summary.errors.some((e) => e.includes("Subscribers"))).toBe(true);
+ });
+
+ test("no warnings on starter plan within limits", async () => {
+ const summary = makeSummary({
+ phases: [
+ {
+ phase: "page",
+ status: "completed",
+ resources: [
+ {
+ sourceId: "p1",
+ name: "Page",
+ status: "created",
+ data: { customDomain: "status.example.com" },
+ },
+ ],
+ },
+ {
+ phase: "components",
+ status: "completed",
+ resources: [
+ { sourceId: "1", name: "A", status: "created" },
+ { sourceId: "2", name: "B", status: "created" },
+ { sourceId: "3", name: "C", status: "created" },
+ { sourceId: "4", name: "D", status: "created" },
+ ],
+ },
+ {
+ phase: "subscribers",
+ status: "completed",
+ resources: [
+ { sourceId: "s1", name: "[email protected]", status: "created" },
+ ],
+ },
+ ],
+ });
+
+ await addLimitWarnings(summary, {
+ limits: { ...allPlans.starter.limits },
+ workspaceId: 1,
+ });
+
+ expect(summary.errors).toEqual([]);
+ });
+});
diff --git a/packages/api/src/service/import.ts b/packages/api/src/service/import.ts
new file mode 100644
index 000000000..e8a7a1eda
--- /dev/null
+++ b/packages/api/src/service/import.ts
@@ -0,0 +1,753 @@
+import { and, db, eq } from "@openstatus/db";
+import {
+ maintenance,
+ maintenancesToPageComponents,
+ page,
+ pageComponent,
+ pageComponentGroup,
+ pageSubscriber,
+ pageSubscriberToPageComponent,
+ statusReport,
+ statusReportUpdate,
+ statusReportsToPageComponents,
+} from "@openstatus/db/src/schema";
+import type { Limits } from "@openstatus/db/src/schema/plan/schema";
+import type {
+ ImportSummary,
+ PhaseResult,
+ ResourceResult,
+} from "@openstatus/importers";
+import { createStatuspageProvider } from "@openstatus/importers/statuspage";
+import { TRPCError } from "@trpc/server";
+
+type ImportOptions = {
+ includeStatusReports?: boolean;
+ includeSubscribers?: boolean;
+ includeComponents?: boolean;
+};
+
+/**
+ * Inspect an ImportSummary and push warnings into `summary.errors`
+ * for any limits that would be hit during import.
+ *
+ * Used by both preview (to show warnings upfront) and run (before writes).
+ */
+export async function addLimitWarnings(
+ summary: ImportSummary,
+ config: {
+ limits: Limits;
+ workspaceId: number;
+ pageId?: number;
+ },
+): Promise<void> {
+ // 1. Component count limit
+ const componentsPhase = summary.phases.find((p) => p.phase === "components");
+ if (componentsPhase && componentsPhase.resources.length > 0) {
+ const maxComponents = config.limits["page-components"];
+ let existingCount = 0;
+ if (config.pageId) {
+ const existing = await db
+ .select()
+ .from(pageComponent)
+ .where(
+ and(
+ eq(pageComponent.pageId, config.pageId),
+ eq(pageComponent.workspaceId, config.workspaceId),
+ ),
+ )
+ .all();
+ existingCount = existing.length;
+ }
+ const remaining = maxComponents - existingCount;
+ if (remaining <= 0) {
+ summary.errors.push(
+ `Component limit reached (${maxComponents}). Upgrade your plan to import components.`,
+ );
+ } else if (componentsPhase.resources.length > remaining) {
+ summary.errors.push(
+ `Only ${remaining} of ${componentsPhase.resources.length} components can be imported due to plan limit (${maxComponents}).`,
+ );
+ }
+ }
+
+ // 2. Custom domain
+ if (!config.limits["custom-domain"]) {
+ const pagePhase = summary.phases.find((p) => p.phase === "page");
+ const pageData = pagePhase?.resources[0]?.data as
+ | { customDomain?: string }
+ | undefined;
+ if (pageData?.customDomain) {
+ summary.errors.push(
+ "Custom domain will be stripped during import. Upgrade your plan to use custom domains.",
+ );
+ }
+ }
+
+ // 3. Subscribers
+ if (!config.limits["status-subscribers"]) {
+ const subscribersPhase = summary.phases.find(
+ (p) => p.phase === "subscribers",
+ );
+ if (subscribersPhase && subscribersPhase.resources.length > 0) {
+ summary.errors.push(
+ "Subscribers cannot be imported on your current plan. Upgrade to enable status page subscribers.",
+ );
+ }
+ }
+}
+
+export async function previewImport(config: {
+ apiKey: string;
+ statuspagePageId?: string;
+ workspaceId: number;
+ pageId?: number;
+ limits: Limits;
+}): Promise<ImportSummary> {
+ const provider = createStatuspageProvider();
+
+ const validation = await provider.validate({
+ ...config,
+ dryRun: true,
+ });
+ if (!validation.valid) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: `Provider validation failed: ${validation.error}`,
+ });
+ }
+
+ const summary = await provider.run({ ...config, dryRun: true });
+ await addLimitWarnings(summary, config);
+ return summary;
+}
+
+export async function runImport(config: {
+ apiKey: string;
+ statuspagePageId?: string;
+ workspaceId: number;
+ pageId?: number;
+ options?: ImportOptions;
+ limits: Limits;
+}): Promise<ImportSummary> {
+ const provider = createStatuspageProvider();
+
+ const validation = await provider.validate(config);
+ if (!validation.valid) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: `Provider validation failed: ${validation.error}`,
+ });
+ }
+
+ // Fetch and map all data
+ const summary = await provider.run(config);
+
+ // Add limit warnings (same as preview)
+ await addLimitWarnings(summary, config);
+
+ // Now write to DB phase by phase
+ const idMaps = {
+ groups: new Map<string, number>(), // sourceId -> openstatusId
+ components: new Map<string, number>(), // sourceId -> openstatusId
+ };
+
+ let targetPageId = config.pageId;
+ let phaseAborted = false;
+
+ for (const phase of summary.phases) {
+ if (phaseAborted) {
+ phase.status = "skipped";
+ continue;
+ }
+
+ try {
+ switch (phase.phase) {
+ case "page":
+ targetPageId = await writePagePhase(
+ phase,
+ config.workspaceId,
+ config.pageId,
+ config.limits,
+ );
+ break;
+ case "componentGroups":
+ if (targetPageId && config.options?.includeComponents !== false) {
+ await writeComponentGroupsPhase(
+ phase,
+ config.workspaceId,
+ targetPageId,
+ idMaps.groups,
+ );
+ } else if (config.options?.includeComponents === false) {
+ phase.status = "skipped";
+ }
+ break;
+ case "components":
+ if (targetPageId && config.options?.includeComponents !== false) {
+ // Check page-components limit
+ const existingCount = await db
+ .select()
+ .from(pageComponent)
+ .where(
+ and(
+ eq(pageComponent.pageId, targetPageId),
+ eq(pageComponent.workspaceId, config.workspaceId),
+ ),
+ )
+ .all();
+ const maxComponents = config.limits["page-components"];
+ const remaining = maxComponents - existingCount.length;
+ if (remaining <= 0) {
+ phase.status = "failed";
+ break;
+ }
+ if (phase.resources.length > remaining) {
+ // Trim resources to fit within limit
+ const skipped = phase.resources.splice(remaining);
+ for (const r of skipped) {
+ r.status = "skipped";
+ r.error = `Skipped: would exceed component limit (${maxComponents})`;
+ }
+ phase.resources.push(...skipped);
+ }
+ await writeComponentsPhase(
+ phase,
+ config.workspaceId,
+ targetPageId,
+ idMaps.groups,
+ idMaps.components,
+ );
+ } else if (config.options?.includeComponents === false) {
+ phase.status = "skipped";
+ }
+ break;
+ case "incidents":
+ if (targetPageId && config.options?.includeStatusReports !== false) {
+ await writeIncidentsPhase(
+ phase,
+ config.workspaceId,
+ targetPageId,
+ idMaps.components,
+ );
+ } else if (config.options?.includeStatusReports === false) {
+ phase.status = "skipped";
+ }
+ break;
+ case "maintenances":
+ if (targetPageId && config.options?.includeStatusReports !== false) {
+ await writeMaintenancesPhase(
+ phase,
+ config.workspaceId,
+ targetPageId,
+ idMaps.components,
+ );
+ } else if (config.options?.includeStatusReports === false) {
+ phase.status = "skipped";
+ }
+ break;
+ case "subscribers":
+ if (targetPageId && config.options?.includeSubscribers) {
+ if (!config.limits["status-subscribers"]) {
+ phase.status = "skipped";
+ break;
+ }
+ await writeSubscribersPhase(phase, targetPageId, idMaps.components);
+ } else {
+ phase.status = "skipped";
+ }
+ break;
+ }
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ summary.errors.push(`Phase "${phase.phase}" failed: ${msg}`);
+ phase.status = "failed";
+ phaseAborted = true;
+ }
+ }
+
+ // Compute overall status
+ const hasFailures = summary.phases.some((p) => p.status === "failed");
+ const hasPartial = summary.phases.some((p) => p.status === "partial");
+ const allSkippedOrCompleted = summary.phases.every(
+ (p) => p.status === "completed" || p.status === "skipped",
+ );
+
+ summary.status = hasFailures
+ ? "failed"
+ : hasPartial
+ ? "partial"
+ : allSkippedOrCompleted
+ ? "completed"
+ : "partial";
+ summary.completedAt = new Date();
+
+ return summary;
+}
+
+// ---------------------------------------------------------------------------
+// Phase writers
+// ---------------------------------------------------------------------------
+
+function computePhaseStatus(
+ resources: ResourceResult[],
+): PhaseResult["status"] {
+ if (resources.length === 0) return "completed";
+ const allFailed = resources.every((r) => r.status === "failed");
+ if (allFailed) return "failed";
+ const hasFailed = resources.some((r) => r.status === "failed");
+ if (hasFailed) return "partial";
+ return "completed";
+}
+
+async function writePagePhase(
+ phase: PhaseResult,
+ workspaceId: number,
+ existingPageId?: number,
+ limits?: Limits,
+): Promise<number> {
+ const resource = phase.resources[0];
+ if (!resource?.data) {
+ throw new Error("No page data found in phase");
+ }
+
+ const data = resource.data as {
+ workspaceId: number;
+ title: string;
+ description: string;
+ slug: string;
+ customDomain: string;
+ published: boolean;
+ icon: string;
+ };
+
+ // Strip custom domain if not allowed by plan
+ if (limits && !limits["custom-domain"]) {
+ data.customDomain = "";
+ }
+
+ // If a page ID was provided, verify and update it
+ if (existingPageId) {
+ const existing = await db
+ .select()
+ .from(page)
+ .where(
+ and(eq(page.id, existingPageId), eq(page.workspaceId, workspaceId)),
+ )
+ .get();
+
+ if (!existing) {
+ throw new Error(
+ "Provided page not found or does not belong to workspace",
+ );
+ }
+
+ await db
+ .update(page)
+ .set({ title: data.title, description: data.description })
+ .where(eq(page.id, existingPageId));
+
+ resource.openstatusId = existingPageId;
+ resource.status = "skipped";
+ phase.status = "completed";
+ return existingPageId;
+ }
+
+ // Check idempotency by slug (scoped to workspace)
+ const existingBySlug = await db
+ .select()
+ .from(page)
+ .where(and(eq(page.slug, data.slug), eq(page.workspaceId, workspaceId)))
+ .get();
+
+ if (existingBySlug) {
+ resource.openstatusId = existingBySlug.id;
+ resource.status = "skipped";
+ phase.status = "completed";
+ return existingBySlug.id;
+ }
+
+ // Insert new page
+ const [inserted] = await db
+ .insert(page)
+ .values({
+ workspaceId: data.workspaceId,
+ title: data.title,
+ description: data.description,
+ slug: data.slug,
+ customDomain: data.customDomain,
+ published: data.published,
+ icon: data.icon,
+ })
+ .returning({ id: page.id });
+
+ if (!inserted) {
+ throw new Error("Failed to insert page");
+ }
+
+ resource.openstatusId = inserted.id;
+ resource.status = "created";
+ phase.status = "completed";
+ return inserted.id;
+}
+
+async function writeComponentGroupsPhase(
+ phase: PhaseResult,
+ workspaceId: number,
+ pageId: number,
+ groupIdMap: Map<string, number>,
+): Promise<void> {
+ for (const resource of phase.resources) {
+ try {
+ const data = resource.data as {
+ workspaceId: number;
+ pageId: number;
+ name: string;
+ };
+
+ // Check idempotency by name + pageId
+ const existing = await db
+ .select()
+ .from(pageComponentGroup)
+ .where(
+ and(
+ eq(pageComponentGroup.name, data.name),
+ eq(pageComponentGroup.pageId, pageId),
+ ),
+ )
+ .get();
+
+ if (existing) {
+ groupIdMap.set(resource.sourceId, existing.id);
+ resource.openstatusId = existing.id;
+ resource.status = "skipped";
+ continue;
+ }
+
+ const [inserted] = await db
+ .insert(pageComponentGroup)
+ .values({
+ workspaceId,
+ pageId,
+ name: data.name,
+ })
+ .returning({ id: pageComponentGroup.id });
+
+ if (!inserted) {
+ resource.status = "failed";
+ resource.error = "Insert returned no result";
+ continue;
+ }
+
+ groupIdMap.set(resource.sourceId, inserted.id);
+ resource.openstatusId = inserted.id;
+ resource.status = "created";
+ } catch (err) {
+ resource.status = "failed";
+ resource.error = err instanceof Error ? err.message : String(err);
+ }
+ }
+
+ phase.status = computePhaseStatus(phase.resources);
+}
+
+async function writeComponentsPhase(
+ phase: PhaseResult,
+ workspaceId: number,
+ pageId: number,
+ groupIdMap: Map<string, number>,
+ componentIdMap: Map<string, number>,
+): Promise<void> {
+ for (const resource of phase.resources) {
+ if (resource.status === "skipped") continue;
+
+ try {
+ const data = resource.data as {
+ workspaceId: number;
+ pageId: number;
+ type: "static";
+ monitorId: null;
+ name: string;
+ description: string | null;
+ order: number;
+ sourceGroupId: string | null;
+ };
+
+ // Check idempotency by name + pageId
+ const existing = await db
+ .select()
+ .from(pageComponent)
+ .where(
+ and(
+ eq(pageComponent.name, data.name),
+ eq(pageComponent.pageId, pageId),
+ ),
+ )
+ .get();
+
+ if (existing) {
+ componentIdMap.set(resource.sourceId, existing.id);
+ resource.openstatusId = existing.id;
+ resource.status = "skipped";
+ continue;
+ }
+
+ // Resolve group ID from source group ID
+ const resolvedGroupId = data.sourceGroupId
+ ? groupIdMap.get(data.sourceGroupId) ?? null
+ : null;
+
+ const [inserted] = await db
+ .insert(pageComponent)
+ .values({
+ workspaceId,
+ pageId,
+ type: data.type,
+ monitorId: data.monitorId,
+ name: data.name,
+ description: data.description,
+ order: data.order,
+ groupId: resolvedGroupId,
+ })
+ .returning({ id: pageComponent.id });
+
+ if (!inserted) {
+ resource.status = "failed";
+ resource.error = "Insert returned no result";
+ continue;
+ }
+
+ componentIdMap.set(resource.sourceId, inserted.id);
+ resource.openstatusId = inserted.id;
+ resource.status = "created";
+ } catch (err) {
+ resource.status = "failed";
+ resource.error = err instanceof Error ? err.message : String(err);
+ }
+ }
+
+ phase.status = computePhaseStatus(phase.resources);
+}
+
+async function writeIncidentsPhase(
+ phase: PhaseResult,
+ workspaceId: number,
+ pageId: number,
+ componentIdMap: Map<string, number>,
+): Promise<void> {
+ for (const resource of phase.resources) {
+ try {
+ const data = resource.data as {
+ report: {
+ title: string;
+ status: "investigating" | "identified" | "monitoring" | "resolved";
+ workspaceId: number;
+ pageId: number;
+ };
+ updates: Array<{
+ status: "investigating" | "identified" | "monitoring" | "resolved";
+ message: string;
+ date: Date;
+ }>;
+ sourceComponentIds: string[];
+ };
+
+ // Insert status report
+ const [insertedReport] = await db
+ .insert(statusReport)
+ .values({
+ title: data.report.title,
+ status: data.report.status,
+ workspaceId,
+ pageId,
+ })
+ .returning({ id: statusReport.id });
+
+ if (!insertedReport) {
+ resource.status = "failed";
+ resource.error = "Failed to insert status report";
+ continue;
+ }
+
+ // Insert status report updates
+ if (data.updates.length > 0) {
+ await db.insert(statusReportUpdate).values(
+ data.updates.map((u) => ({
+ status: u.status,
+ message: u.message,
+ date: u.date,
+ statusReportId: insertedReport.id,
+ })),
+ );
+ }
+
+ // Link to page components
+ const componentLinks: Array<{
+ statusReportId: number;
+ pageComponentId: number;
+ }> = [];
+ for (const sourceCompId of data.sourceComponentIds) {
+ const osCompId = componentIdMap.get(sourceCompId);
+ if (osCompId) {
+ componentLinks.push({
+ statusReportId: insertedReport.id,
+ pageComponentId: osCompId,
+ });
+ }
+ }
+ if (componentLinks.length > 0) {
+ await db.insert(statusReportsToPageComponents).values(componentLinks);
+ }
+
+ resource.openstatusId = insertedReport.id;
+ resource.status = "created";
+ } catch (err) {
+ resource.status = "failed";
+ resource.error = err instanceof Error ? err.message : String(err);
+ }
+ }
+
+ phase.status = computePhaseStatus(phase.resources);
+}
+
+async function writeMaintenancesPhase(
+ phase: PhaseResult,
+ workspaceId: number,
+ pageId: number,
+ componentIdMap: Map<string, number>,
+): Promise<void> {
+ for (const resource of phase.resources) {
+ try {
+ const data = resource.data as {
+ title: string;
+ message: string;
+ from: Date;
+ to: Date;
+ workspaceId: number;
+ pageId: number;
+ sourceComponentIds: string[];
+ };
+
+ // Insert maintenance
+ const [inserted] = await db
+ .insert(maintenance)
+ .values({
+ title: data.title,
+ message: data.message,
+ from: data.from,
+ to: data.to,
+ workspaceId,
+ pageId,
+ })
+ .returning({ id: maintenance.id });
+
+ if (!inserted) {
+ resource.status = "failed";
+ resource.error = "Failed to insert maintenance";
+ continue;
+ }
+
+ // Link to page components
+ const componentLinks: Array<{
+ maintenanceId: number;
+ pageComponentId: number;
+ }> = [];
+ for (const sourceCompId of data.sourceComponentIds) {
+ const osCompId = componentIdMap.get(sourceCompId);
+ if (osCompId) {
+ componentLinks.push({
+ maintenanceId: inserted.id,
+ pageComponentId: osCompId,
+ });
+ }
+ }
+ if (componentLinks.length > 0) {
+ await db.insert(maintenancesToPageComponents).values(componentLinks);
+ }
+
+ resource.openstatusId = inserted.id;
+ resource.status = "created";
+ } catch (err) {
+ resource.status = "failed";
+ resource.error = err instanceof Error ? err.message : String(err);
+ }
+ }
+
+ phase.status = computePhaseStatus(phase.resources);
+}
+
+// TODO: migrate to new `pageSubscription` + `pageSubscriptionToPageComponent` tables
+async function writeSubscribersPhase(
+ phase: PhaseResult,
+ pageId: number,
+ componentIdMap: Map<string, number>,
+): Promise<void> {
+ for (const resource of phase.resources) {
+ try {
+ const data = resource.data as {
+ email: string;
+ pageId: number;
+ sourceComponentIds: string[];
+ };
+
+ // Idempotency check by email + pageId
+ const existing = await db
+ .select()
+ .from(pageSubscriber)
+ .where(
+ and(
+ eq(pageSubscriber.email, data.email),
+ eq(pageSubscriber.pageId, pageId),
+ eq(pageSubscriber.channelType, "email"),
+ ),
+ )
+ .get();
+
+ if (existing) {
+ resource.openstatusId = existing.id;
+ resource.status = "skipped";
+ continue;
+ }
+
+ const [inserted] = await db
+ .insert(pageSubscriber)
+ .values({
+ email: data.email,
+ pageId,
+ channelType: "email",
+ })
+ .returning({ id: pageSubscriber.id });
+
+ if (!inserted) {
+ resource.status = "failed";
+ resource.error = "Insert returned no result";
+ continue;
+ }
+
+ // Link to page components
+ const componentLinks: Array<{
+ pageSubscriberId: number;
+ pageComponentId: number;
+ }> = [];
+ for (const sourceCompId of data.sourceComponentIds) {
+ const osCompId = componentIdMap.get(sourceCompId);
+ if (osCompId) {
+ componentLinks.push({
+ pageSubscriberId: inserted.id,
+ pageComponentId: osCompId,
+ });
+ }
+ }
+ if (componentLinks.length > 0) {
+ await db.insert(pageSubscriberToPageComponent).values(componentLinks);
+ }
+
+ resource.openstatusId = inserted.id;
+ resource.status = "created";
+ } catch (err) {
+ resource.status = "failed";
+ resource.error = err instanceof Error ? err.message : String(err);
+ }
+ }
+
+ phase.status = computePhaseStatus(phase.resources);
+}
diff --git a/packages/icons/src/index.tsx b/packages/icons/src/index.tsx
index 5781b1af7..ff2b7cb8e 100644
--- a/packages/icons/src/index.tsx
+++ b/packages/icons/src/index.tsx
@@ -11,3 +11,4 @@ export * from "./koyeb";
export * from "./telegram";
export * from "./whatsapp";
export * from "./markdown";
+export * from "./statuspage";
diff --git a/packages/icons/src/statuspage.tsx b/packages/icons/src/statuspage.tsx
new file mode 100644
index 000000000..f859dc806
--- /dev/null
+++ b/packages/icons/src/statuspage.tsx
@@ -0,0 +1,15 @@
+export function StatuspageIcon(props: React.ComponentProps<"svg">) {
+ return (
+ <svg
+ role="img"
+ viewBox="0 0 24 24"
+ xmlns="http://www.w3.org/2000/svg"
+ stroke="currentColor"
+ fill="currentColor"
+ {...props}
+ >
+ <title>Statuspage</title>
+ <path d="M12.008 9.597a5.623 5.623 0 1 1 0 11.245 5.623 5.623 0 0 1 0-11.245zM.154 8.717l3.02 3.574a.639.639 0 0 0 .913.068c4.885-4.379 10.97-4.379 15.84 0a.642.642 0 0 0 .916-.068l3.006-3.574a.646.646 0 0 0-.075-.906c-7.1-6.204-16.462-6.204-23.555 0a.65.65 0 0 0-.065.906z" />
+ </svg>
+ );
+}
diff --git a/packages/importers/package.json b/packages/importers/package.json
new file mode 100644
index 000000000..508cd87d9
--- /dev/null
+++ b/packages/importers/package.json
@@ -0,0 +1,24 @@
+{
+ "name": "@openstatus/importers",
+ "version": "0.1.0",
+ "private": true,
+ "type": "module",
+ "exports": {
+ ".": "./src/index.ts",
+ "./types": "./src/types.ts",
+ "./statuspage": "./src/providers/statuspage/index.ts",
+ "./statuspage/fixtures": "./src/providers/statuspage/fixtures.ts"
+ },
+ "scripts": {
+ "test": "bun test",
+ "test:watch": "bun test --watch",
+ "tsc": "tsc --noEmit"
+ },
+ "dependencies": {
+ "zod": "4.1.13"
+ },
+ "devDependencies": {
+ "@openstatus/tsconfig": "workspace:*",
+ "typescript": "5.9.3"
+ }
+}
diff --git a/packages/importers/src/index.ts b/packages/importers/src/index.ts
new file mode 100644
index 000000000..8fead1e8a
--- /dev/null
+++ b/packages/importers/src/index.ts
@@ -0,0 +1,17 @@
+export type {
+ ImportConfig,
+ ImportProvider,
+ ImportSummary,
+ PhaseResult,
+ ResourceResult,
+} from "./types";
+
+export { createStatuspageProvider } from "./providers/statuspage";
+export type { StatuspageImportConfig } from "./providers/statuspage";
+
+/**
+ * Registry of all available import providers.
+ * Add new providers here as they are implemented.
+ */
+export const IMPORT_PROVIDERS = ["statuspage"] as const;
+export type ImportProviderName = (typeof IMPORT_PROVIDERS)[number];
diff --git a/packages/importers/src/providers/statuspage/api-types.ts b/packages/importers/src/providers/statuspage/api-types.ts
new file mode 100644
index 000000000..a9585b80f
--- /dev/null
+++ b/packages/importers/src/providers/statuspage/api-types.ts
@@ -0,0 +1,141 @@
+import { z } from "zod";
+
+export const StatuspageComponentSchema = z.object({
+ id: z.string(),
+ page_id: z.string(),
+ group_id: z.string().nullable(),
+ name: z.string(),
+ description: z.string().nullable(),
+ position: z.number(),
+ status: z.enum([
+ "operational",
+ "degraded_performance",
+ "partial_outage",
+ "major_outage",
+ "under_maintenance",
+ ]),
+ showcase: z.boolean(),
+ only_show_if_degraded: z.boolean(),
+ group: z.boolean(),
+ start_date: z.string().nullable(),
+ created_at: z.string(),
+ updated_at: z.string(),
+});
+
+export type StatuspageComponent = z.infer<typeof StatuspageComponentSchema>;
+
+export const StatuspageGroupComponentSchema = z.object({
+ id: z.string(),
+ page_id: z.string(),
+ name: z.string(),
+ description: z.string().nullable(),
+ components: z.array(z.string()),
+ position: z.number(),
+ created_at: z.string(),
+ updated_at: z.string(),
+});
+
+export type StatuspageGroupComponent = z.infer<
+ typeof StatuspageGroupComponentSchema
+>;
+
+export const StatuspageIncidentUpdateSchema = z.object({
+ id: z.string(),
+ incident_id: z.string(),
+ status: z.enum([
+ "investigating",
+ "identified",
+ "monitoring",
+ "resolved",
+ "scheduled",
+ "in_progress",
+ "verifying",
+ "completed",
+ ]),
+ body: z.string().nullable(),
+ display_at: z.string().nullable(),
+ deliver_notifications: z.boolean(),
+ affected_components: z
+ .array(
+ z.object({
+ code: z.string(),
+ name: z.string(),
+ old_status: z.string(),
+ new_status: z.string(),
+ }),
+ )
+ .nullable(),
+ created_at: z.string(),
+ updated_at: z.string(),
+});
+
+export type StatuspageIncidentUpdate = z.infer<
+ typeof StatuspageIncidentUpdateSchema
+>;
+
+export const StatuspageIncidentSchema = z.object({
+ id: z.string(),
+ page_id: z.string(),
+ name: z.string(),
+ status: z.enum([
+ "investigating",
+ "identified",
+ "monitoring",
+ "resolved",
+ "scheduled",
+ "in_progress",
+ "verifying",
+ "completed",
+ ]),
+ impact: z.enum(["none", "minor", "major", "critical"]).nullable(),
+ shortlink: z.string().nullable(),
+ scheduled_for: z.string().nullable(),
+ scheduled_until: z.string().nullable(),
+ resolved_at: z.string().nullable(),
+ monitoring_at: z.string().nullable(),
+ created_at: z.string(),
+ updated_at: z.string(),
+ incident_updates: z.array(StatuspageIncidentUpdateSchema).optional(),
+ components: z.array(StatuspageComponentSchema).optional(),
+ postmortem_body: z.string().nullable(),
+ metadata: z.unknown().nullable(),
+});
+
+export type StatuspageIncident = z.infer<typeof StatuspageIncidentSchema>;
+
+export const StatuspageSubscriberSchema = z.object({
+ id: z.string(),
+ page_id: z.string(),
+ mode: z.enum(["email", "sms", "slack", "webhook", "integration_partner"]),
+ email: z.string().nullable(),
+ endpoint: z.string().nullable(),
+ phone_number: z.string().nullable(),
+ phone_country: z.string().nullable(),
+ display_phone_number: z.string().nullable(),
+ obfuscated_channel_name: z.string().nullable(),
+ workspace_name: z.string().nullable(),
+ components: z.array(z.string()).nullable(),
+ quarantined_at: z.string().nullable(),
+ created_at: z.string(),
+});
+
+export type StatuspageSubscriber = z.infer<typeof StatuspageSubscriberSchema>;
+
+export const StatuspagePageSchema = z.object({
+ id: z.string(),
+ name: z.string(),
+ page_description: z.string().nullable(),
+ subdomain: z.string(),
+ domain: z.string().nullable(),
+ url: z.string().nullable(),
+ support_url: z.string().nullable(),
+ time_zone: z.string().nullable(),
+ allow_page_subscribers: z.boolean(),
+ allow_email_subscribers: z.boolean(),
+ allow_sms_subscribers: z.boolean(),
+ allow_webhook_subscribers: z.boolean(),
+ created_at: z.string(),
+ updated_at: z.string(),
+});
+
+export type StatuspagePage = z.infer<typeof StatuspagePageSchema>;
diff --git a/packages/importers/src/providers/statuspage/client.test.ts b/packages/importers/src/providers/statuspage/client.test.ts
new file mode 100644
index 000000000..b8a9e5106
--- /dev/null
+++ b/packages/importers/src/providers/statuspage/client.test.ts
@@ -0,0 +1,147 @@
+import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test";
+import { createStatuspageClient } from "./client";
+import {
+ MOCK_COMPONENTS,
+ MOCK_COMPONENT_GROUPS,
+ MOCK_INCIDENTS,
+ MOCK_PAGES,
+ MOCK_SUBSCRIBERS,
+} from "./fixtures";
+
+const originalFetch = globalThis.fetch;
+
+function mockFetch(data: unknown, status = 200) {
+ globalThis.fetch = mock(() =>
+ Promise.resolve(
+ new Response(JSON.stringify(data), {
+ status,
+ statusText: status === 200 ? "OK" : "Unauthorized",
+ headers: { "Content-Type": "application/json" },
+ }),
+ ),
+ ) as typeof globalThis.fetch;
+}
+
+/**
+ * Mock fetch for paginated endpoints: returns `data` on first call, `[]` on subsequent calls.
+ */
+function mockFetchPaginated(data: unknown, status = 200) {
+ let callCount = 0;
+ globalThis.fetch = mock(() => {
+ callCount++;
+ const body = callCount === 1 ? data : [];
+ return Promise.resolve(
+ new Response(JSON.stringify(body), {
+ status,
+ statusText: status === 200 ? "OK" : "Unauthorized",
+ headers: { "Content-Type": "application/json" },
+ }),
+ );
+ }) as typeof globalThis.fetch;
+}
+
+describe("StatuspageClient", () => {
+ let client: ReturnType<typeof createStatuspageClient>;
+
+ beforeEach(() => {
+ client = createStatuspageClient("test-api-key");
+ });
+
+ afterEach(() => {
+ globalThis.fetch = originalFetch;
+ });
+
+ test("getPages returns parsed pages", async () => {
+ mockFetch(MOCK_PAGES);
+ const pages = await client.getPages();
+ expect(pages).toEqual(MOCK_PAGES);
+ expect(pages).toHaveLength(1);
+ expect(pages[0].name).toBe("Acme Corp Status");
+ });
+
+ test("getComponents returns parsed components", async () => {
+ mockFetchPaginated(MOCK_COMPONENTS);
+ const components = await client.getComponents("sp_page_001");
+ expect(components).toEqual(MOCK_COMPONENTS);
+ expect(components).toHaveLength(4);
+ expect(components[2].status).toBe("degraded_performance");
+ });
+
+ test("getComponentGroups returns parsed groups", async () => {
+ mockFetchPaginated(MOCK_COMPONENT_GROUPS);
+ const groups = await client.getComponentGroups("sp_page_001");
+ expect(groups).toEqual(MOCK_COMPONENT_GROUPS);
+ expect(groups).toHaveLength(1);
+ expect(groups[0].name).toBe("Core Services");
+ expect(groups[0].components).toEqual(["sp_comp_001", "sp_comp_002"]);
+ });
+
+ test("getIncidents returns parsed incidents with updates", async () => {
+ mockFetchPaginated(MOCK_INCIDENTS);
+ const incidents = await client.getIncidents("sp_page_001");
+ expect(incidents).toEqual(MOCK_INCIDENTS);
+ expect(incidents).toHaveLength(3);
+ expect(incidents[0].incident_updates).toHaveLength(4);
+ expect(incidents[0].postmortem_body).toBeTruthy();
+ expect(incidents[1].status).toBe("identified");
+ expect(incidents[2].scheduled_for).toBe("2024-06-20T02:00:00.000Z");
+ });
+
+ test("getSubscribers returns parsed subscribers", async () => {
+ mockFetchPaginated(MOCK_SUBSCRIBERS);
+ const subscribers = await client.getSubscribers("sp_page_001");
+ expect(subscribers).toEqual(MOCK_SUBSCRIBERS);
+ expect(subscribers).toHaveLength(5);
+ expect(subscribers[0].mode).toBe("email");
+ expect(subscribers[2].mode).toBe("webhook");
+ expect(subscribers[3].mode).toBe("sms");
+ expect(subscribers[4].mode).toBe("slack");
+ });
+
+ test("throws on API error (401)", async () => {
+ mockFetch({ error: "Unauthorized" }, 401);
+ await expect(client.getPages()).rejects.toThrow(
+ "Statuspage API error: 401 Unauthorized for /pages",
+ );
+ });
+
+ test("getPage returns a single parsed page", async () => {
+ mockFetch(MOCK_PAGES[0]);
+ const singlePage = await client.getPage("sp_page_001");
+ expect(singlePage).toEqual(MOCK_PAGES[0]);
+ expect(singlePage.id).toBe("sp_page_001");
+ expect(singlePage.name).toBe("Acme Corp Status");
+ });
+
+ test("getPage calls correct URL path", async () => {
+ mockFetch(MOCK_PAGES[0]);
+ await client.getPage("sp_page_001");
+ const fetchMock = globalThis.fetch as ReturnType<typeof mock>;
+ const [url] = fetchMock.mock.calls[0] as [string, RequestInit];
+ expect(url).toBe("https://api.statuspage.io/v1/pages/sp_page_001");
+ });
+
+ test("getPage throws on non-200 response", async () => {
+ mockFetch({ error: "Not Found" }, 404);
+ await expect(client.getPage("nonexistent")).rejects.toThrow(
+ "Statuspage API error: 404",
+ );
+ });
+
+ test("getPage throws on schema mismatch", async () => {
+ mockFetch({ id: 123, unexpected: true });
+ await expect(client.getPage("sp_page_001")).rejects.toThrow();
+ });
+
+ test("sends correct auth header", async () => {
+ mockFetch(MOCK_PAGES);
+ await client.getPages();
+ const fetchMock = globalThis.fetch as ReturnType<typeof mock>;
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const [url, options] = fetchMock.mock.calls[0] as [string, RequestInit];
+ expect(url).toBe("https://api.statuspage.io/v1/pages");
+ expect((options.headers as Record<string, string>).Authorization).toBe(
+ "OAuth test-api-key",
+ );
+ });
+});
diff --git a/packages/importers/src/providers/statuspage/client.ts b/packages/importers/src/providers/statuspage/client.ts
new file mode 100644
index 000000000..328fe721e
--- /dev/null
+++ b/packages/importers/src/providers/statuspage/client.ts
@@ -0,0 +1,86 @@
+import { z } from "zod";
+import {
+ type StatuspageComponent,
+ StatuspageComponentSchema,
+ type StatuspageGroupComponent,
+ StatuspageGroupComponentSchema,
+ type StatuspageIncident,
+ StatuspageIncidentSchema,
+ type StatuspagePage,
+ StatuspagePageSchema,
+ type StatuspageSubscriber,
+ StatuspageSubscriberSchema,
+} from "./api-types";
+
+export type StatuspageClient = {
+ getPages: () => Promise<StatuspagePage[]>;
+ getPage: (pageId: string) => Promise<StatuspagePage>;
+ getComponents: (pageId: string) => Promise<StatuspageComponent[]>;
+ getComponentGroups: (pageId: string) => Promise<StatuspageGroupComponent[]>;
+ getIncidents: (pageId: string) => Promise<StatuspageIncident[]>;
+ // NOTE: could add getScheduledStatusReports if we need the dedicated /incidents/scheduled endpoint
+ getSubscribers: (pageId: string) => Promise<StatuspageSubscriber[]>;
+};
+
+export function createStatuspageClient(
+ apiKey: string,
+ baseUrl = "https://api.statuspage.io/v1",
+): StatuspageClient {
+ async function request<T>(path: string, schema: z.ZodType<T>): Promise<T> {
+ const url = `${baseUrl}${path}`;
+ const response = await fetch(url, {
+ headers: {
+ Authorization: `OAuth ${apiKey}`,
+ "Content-Type": "application/json",
+ },
+ });
+
+ if (!response.ok) {
+ throw new Error(
+ `Statuspage API error: ${response.status} ${response.statusText} for ${path}`,
+ );
+ }
+
+ const data = await response.json();
+ return schema.parse(data);
+ }
+
+ async function requestAllPages<T>(
+ path: string,
+ itemSchema: z.ZodType<T>,
+ perPage = 100,
+ ): Promise<T[]> {
+ const all: T[] = [];
+ let page = 1;
+ while (true) {
+ const separator = path.includes("?") ? "&" : "?";
+ const items = await request(
+ `${path}${separator}page=${page}&per_page=${perPage}`,
+ z.array(itemSchema),
+ );
+ all.push(...items);
+ if (items.length < perPage) break;
+ page++;
+ }
+ return all;
+ }
+
+ return {
+ getPages: () => request("/pages", z.array(StatuspagePageSchema)),
+ getPage: (pageId) => request(`/pages/${pageId}`, StatuspagePageSchema),
+ getComponents: (pageId) =>
+ requestAllPages(`/pages/${pageId}/components`, StatuspageComponentSchema),
+ getComponentGroups: (pageId) =>
+ requestAllPages(
+ `/pages/${pageId}/component-groups`,
+ StatuspageGroupComponentSchema,
+ ),
+ getIncidents: (pageId) =>
+ requestAllPages(`/pages/${pageId}/incidents`, StatuspageIncidentSchema),
+ getSubscribers: (pageId) =>
+ requestAllPages(
+ `/pages/${pageId}/subscribers`,
+ StatuspageSubscriberSchema,
+ ),
+ };
+}
diff --git a/packages/importers/src/providers/statuspage/fixtures.ts b/packages/importers/src/providers/statuspage/fixtures.ts
new file mode 100644
index 000000000..dbe63ccc5
--- /dev/null
+++ b/packages/importers/src/providers/statuspage/fixtures.ts
@@ -0,0 +1,373 @@
+import type {
+ StatuspageComponent,
+ StatuspageGroupComponent,
+ StatuspageIncident,
+ StatuspagePage,
+ StatuspageSubscriber,
+} from "./api-types";
+
+export const MOCK_PAGES: StatuspagePage[] = [
+ {
+ id: "sp_page_001",
+ name: "Acme Corp Status",
+ page_description: "Current status and incidents for Acme Corp services",
+ subdomain: "acmecorp",
+ domain: "status.acmecorp.com",
+ url: "https://status.acmecorp.com",
+ support_url: "https://support.acmecorp.com",
+ time_zone: "America/New_York",
+ allow_page_subscribers: true,
+ allow_email_subscribers: true,
+ allow_sms_subscribers: true,
+ allow_webhook_subscribers: true,
+ created_at: "2024-01-15T10:00:00.000Z",
+ updated_at: "2024-06-01T12:00:00.000Z",
+ },
+];
+
+export const MOCK_COMPONENTS: StatuspageComponent[] = [
+ {
+ id: "sp_comp_001",
+ page_id: "sp_page_001",
+ group_id: "sp_group_001",
+ name: "API Gateway",
+ description: "Main API gateway for all services",
+ position: 1,
+ status: "operational",
+ showcase: true,
+ only_show_if_degraded: false,
+ group: false,
+ start_date: "2024-01-15",
+ created_at: "2024-01-15T10:00:00.000Z",
+ updated_at: "2024-06-01T12:00:00.000Z",
+ },
+ {
+ id: "sp_comp_002",
+ page_id: "sp_page_001",
+ group_id: "sp_group_001",
+ name: "Authentication Service",
+ description: "Handles user authentication and authorization",
+ position: 2,
+ status: "operational",
+ showcase: true,
+ only_show_if_degraded: false,
+ group: false,
+ start_date: "2024-01-15",
+ created_at: "2024-01-15T10:05:00.000Z",
+ updated_at: "2024-06-01T12:00:00.000Z",
+ },
+ {
+ id: "sp_comp_003",
+ page_id: "sp_page_001",
+ group_id: null,
+ name: "Dashboard",
+ description: "Web dashboard application",
+ position: 3,
+ status: "degraded_performance",
+ showcase: true,
+ only_show_if_degraded: false,
+ group: false,
+ start_date: "2024-02-01",
+ created_at: "2024-02-01T08:00:00.000Z",
+ updated_at: "2024-06-10T15:30:00.000Z",
+ },
+ {
+ id: "sp_comp_004",
+ page_id: "sp_page_001",
+ group_id: null,
+ name: "CDN",
+ description: null,
+ position: 4,
+ status: "operational",
+ showcase: true,
+ only_show_if_degraded: true,
+ group: false,
+ start_date: null,
+ created_at: "2024-03-10T09:00:00.000Z",
+ updated_at: "2024-06-01T12:00:00.000Z",
+ },
+];
+
+export const MOCK_COMPONENT_GROUPS: StatuspageGroupComponent[] = [
+ {
+ id: "sp_group_001",
+ page_id: "sp_page_001",
+ name: "Core Services",
+ description: "Core infrastructure services",
+ components: ["sp_comp_001", "sp_comp_002"],
+ position: 1,
+ created_at: "2024-01-15T10:00:00.000Z",
+ updated_at: "2024-06-01T12:00:00.000Z",
+ },
+];
+
+export const MOCK_INCIDENTS: StatuspageIncident[] = [
+ {
+ id: "sp_incident_001",
+ page_id: "sp_page_001",
+ name: "API Gateway Elevated Error Rates",
+ status: "resolved",
+ impact: "major",
+ shortlink: "https://stspg.io/abc123",
+ scheduled_for: null,
+ scheduled_until: null,
+ resolved_at: "2024-06-10T16:45:00.000Z",
+ monitoring_at: "2024-06-10T16:00:00.000Z",
+ created_at: "2024-06-10T14:00:00.000Z",
+ updated_at: "2024-06-10T16:45:00.000Z",
+ incident_updates: [
+ {
+ id: "sp_update_001",
+ incident_id: "sp_incident_001",
+ status: "investigating",
+ body: "We are investigating elevated error rates on the API Gateway.",
+ display_at: "2024-06-10T14:00:00.000Z",
+ deliver_notifications: true,
+ affected_components: [
+ {
+ code: "sp_comp_001",
+ name: "API Gateway",
+ old_status: "operational",
+ new_status: "major_outage",
+ },
+ ],
+ created_at: "2024-06-10T14:00:00.000Z",
+ updated_at: "2024-06-10T14:00:00.000Z",
+ },
+ {
+ id: "sp_update_002",
+ incident_id: "sp_incident_001",
+ status: "identified",
+ body: "The issue has been identified as a misconfigured load balancer rule.",
+ display_at: "2024-06-10T14:30:00.000Z",
+ deliver_notifications: true,
+ affected_components: [
+ {
+ code: "sp_comp_001",
+ name: "API Gateway",
+ old_status: "major_outage",
+ new_status: "major_outage",
+ },
+ ],
+ created_at: "2024-06-10T14:30:00.000Z",
+ updated_at: "2024-06-10T14:30:00.000Z",
+ },
+ {
+ id: "sp_update_003",
+ incident_id: "sp_incident_001",
+ status: "monitoring",
+ body: "A fix has been deployed and we are monitoring the results.",
+ display_at: "2024-06-10T16:00:00.000Z",
+ deliver_notifications: true,
+ affected_components: [
+ {
+ code: "sp_comp_001",
+ name: "API Gateway",
+ old_status: "major_outage",
+ new_status: "degraded_performance",
+ },
+ ],
+ created_at: "2024-06-10T16:00:00.000Z",
+ updated_at: "2024-06-10T16:00:00.000Z",
+ },
+ {
+ id: "sp_update_004",
+ incident_id: "sp_incident_001",
+ status: "resolved",
+ body: "The issue has been fully resolved. Error rates are back to normal.",
+ display_at: "2024-06-10T16:45:00.000Z",
+ deliver_notifications: true,
+ affected_components: [
+ {
+ code: "sp_comp_001",
+ name: "API Gateway",
+ old_status: "degraded_performance",
+ new_status: "operational",
+ },
+ ],
+ created_at: "2024-06-10T16:45:00.000Z",
+ updated_at: "2024-06-10T16:45:00.000Z",
+ },
+ ],
+ components: [MOCK_COMPONENTS[0]],
+ postmortem_body:
+ "## Summary\n\nOn June 10, 2024, our API Gateway experienced elevated error rates due to a misconfigured load balancer rule. The issue was resolved within 2 hours and 45 minutes.\n\n## Root Cause\n\nA deployment at 13:55 UTC introduced an incorrect routing rule that caused 30% of requests to fail.\n\n## Resolution\n\nThe faulty rule was reverted and a fix was deployed.",
+ metadata: null,
+ },
+ {
+ id: "sp_incident_002",
+ page_id: "sp_page_001",
+ name: "Dashboard Slow Response Times",
+ status: "identified",
+ impact: "minor",
+ shortlink: "https://stspg.io/def456",
+ scheduled_for: null,
+ scheduled_until: null,
+ resolved_at: null,
+ monitoring_at: null,
+ created_at: "2024-06-11T09:00:00.000Z",
+ updated_at: "2024-06-11T09:45:00.000Z",
+ incident_updates: [
+ {
+ id: "sp_update_005",
+ incident_id: "sp_incident_002",
+ status: "investigating",
+ body: "We are investigating reports of slow response times on the Dashboard.",
+ display_at: "2024-06-11T09:00:00.000Z",
+ deliver_notifications: true,
+ affected_components: [
+ {
+ code: "sp_comp_003",
+ name: "Dashboard",
+ old_status: "operational",
+ new_status: "degraded_performance",
+ },
+ ],
+ created_at: "2024-06-11T09:00:00.000Z",
+ updated_at: "2024-06-11T09:00:00.000Z",
+ },
+ {
+ id: "sp_update_006",
+ incident_id: "sp_incident_002",
+ status: "identified",
+ body: "The issue has been traced to a slow database query affecting the main dashboard view.",
+ display_at: "2024-06-11T09:45:00.000Z",
+ deliver_notifications: true,
+ affected_components: [
+ {
+ code: "sp_comp_003",
+ name: "Dashboard",
+ old_status: "degraded_performance",
+ new_status: "degraded_performance",
+ },
+ ],
+ created_at: "2024-06-11T09:45:00.000Z",
+ updated_at: "2024-06-11T09:45:00.000Z",
+ },
+ ],
+ components: [MOCK_COMPONENTS[2]],
+ postmortem_body: null,
+ metadata: null,
+ },
+ {
+ id: "sp_incident_003",
+ page_id: "sp_page_001",
+ name: "Scheduled Database Maintenance",
+ status: "scheduled",
+ impact: "none",
+ shortlink: "https://stspg.io/ghi789",
+ scheduled_for: "2024-06-20T02:00:00.000Z",
+ scheduled_until: "2024-06-20T06:00:00.000Z",
+ resolved_at: null,
+ monitoring_at: null,
+ created_at: "2024-06-12T10:00:00.000Z",
+ updated_at: "2024-06-12T10:00:00.000Z",
+ incident_updates: [
+ {
+ id: "sp_update_007",
+ incident_id: "sp_incident_003",
+ status: "scheduled",
+ body: "We will be performing scheduled database maintenance. Some services may experience brief interruptions.",
+ display_at: "2024-06-12T10:00:00.000Z",
+ deliver_notifications: true,
+ affected_components: [
+ {
+ code: "sp_comp_001",
+ name: "API Gateway",
+ old_status: "operational",
+ new_status: "under_maintenance",
+ },
+ {
+ code: "sp_comp_002",
+ name: "Authentication Service",
+ old_status: "operational",
+ new_status: "under_maintenance",
+ },
+ ],
+ created_at: "2024-06-12T10:00:00.000Z",
+ updated_at: "2024-06-12T10:00:00.000Z",
+ },
+ ],
+ components: [MOCK_COMPONENTS[0], MOCK_COMPONENTS[1]],
+ postmortem_body: null,
+ metadata: null,
+ },
+];
+
+export const MOCK_SUBSCRIBERS: StatuspageSubscriber[] = [
+ {
+ id: "sp_sub_001",
+ page_id: "sp_page_001",
+ mode: "email",
+ email: "[email protected]",
+ endpoint: null,
+ phone_number: null,
+ phone_country: null,
+ display_phone_number: null,
+ obfuscated_channel_name: null,
+ workspace_name: null,
+ components: null,
+ quarantined_at: null,
+ created_at: "2024-02-01T10:00:00.000Z",
+ },
+ {
+ id: "sp_sub_002",
+ page_id: "sp_page_001",
+ mode: "email",
+ email: "[email protected]",
+ endpoint: null,
+ phone_number: null,
+ phone_country: null,
+ display_phone_number: null,
+ obfuscated_channel_name: null,
+ workspace_name: null,
+ components: ["sp_comp_001", "sp_comp_003"],
+ quarantined_at: null,
+ created_at: "2024-02-15T14:30:00.000Z",
+ },
+ {
+ id: "sp_sub_003",
+ page_id: "sp_page_001",
+ mode: "webhook",
+ email: null,
+ endpoint: "https://hooks.acmecorp.com/statuspage",
+ phone_number: null,
+ phone_country: null,
+ display_phone_number: null,
+ obfuscated_channel_name: null,
+ workspace_name: null,
+ components: null,
+ quarantined_at: null,
+ created_at: "2024-03-01T09:00:00.000Z",
+ },
+ {
+ id: "sp_sub_004",
+ page_id: "sp_page_001",
+ mode: "sms",
+ email: null,
+ endpoint: null,
+ phone_number: "+15551234567",
+ phone_country: "US",
+ display_phone_number: "+1 (555) 123-4567",
+ obfuscated_channel_name: null,
+ workspace_name: null,
+ components: ["sp_comp_001"],
+ quarantined_at: null,
+ created_at: "2024-03-10T11:00:00.000Z",
+ },
+ {
+ id: "sp_sub_005",
+ page_id: "sp_page_001",
+ mode: "slack",
+ email: null,
+ endpoint: null,
+ phone_number: null,
+ phone_country: null,
+ display_phone_number: null,
+ obfuscated_channel_name: "#ops-alerts",
+ workspace_name: "Acme Corp",
+ components: null,
+ quarantined_at: null,
+ created_at: "2024-04-01T08:00:00.000Z",
+ },
+];
diff --git a/packages/importers/src/providers/statuspage/index.ts b/packages/importers/src/providers/statuspage/index.ts
new file mode 100644
index 000000000..dc515de14
--- /dev/null
+++ b/packages/importers/src/providers/statuspage/index.ts
@@ -0,0 +1,20 @@
+export { createStatuspageClient } from "./client";
+export type { StatuspageClient } from "./client";
+export type {
+ StatuspageComponent,
+ StatuspageGroupComponent,
+ StatuspageIncident,
+ StatuspageIncidentUpdate,
+ StatuspagePage,
+ StatuspageSubscriber,
+} from "./api-types";
+export {
+ StatuspageComponentSchema,
+ StatuspageGroupComponentSchema,
+ StatuspageIncidentSchema,
+ StatuspageIncidentUpdateSchema,
+ StatuspagePageSchema,
+ StatuspageSubscriberSchema,
+} from "./api-types";
+export { createStatuspageProvider } from "./provider";
+export type { StatuspageImportConfig } from "./provider";
diff --git a/packages/importers/src/providers/statuspage/mapper.test.ts b/packages/importers/src/providers/statuspage/mapper.test.ts
new file mode 100644
index 000000000..450d8ee02
--- /dev/null
+++ b/packages/importers/src/providers/statuspage/mapper.test.ts
@@ -0,0 +1,170 @@
+import { describe, expect, it } from "bun:test";
+import {
+ MOCK_COMPONENTS,
+ MOCK_COMPONENT_GROUPS,
+ MOCK_INCIDENTS,
+ MOCK_PAGES,
+ MOCK_SUBSCRIBERS,
+} from "./fixtures";
+import {
+ isScheduledIncident,
+ mapComponent,
+ mapComponentGroup,
+ mapIncidentToMaintenance,
+ mapIncidentToStatusReport,
+ mapIncidentUpdateStatus,
+ mapPage,
+ mapSubscriber,
+} from "./mapper";
+
+describe("mapPage", () => {
+ it("maps a page with all fields", () => {
+ const result = mapPage(MOCK_PAGES[0], 1);
+ expect(result).toEqual({
+ workspaceId: 1,
+ title: "Acme Corp Status",
+ description: "Current status and incidents for Acme Corp services",
+ slug: "acmecorp",
+ customDomain: "status.acmecorp.com",
+ published: true,
+ icon: "",
+ });
+ });
+
+ it("handles null domain", () => {
+ const page = { ...MOCK_PAGES[0], domain: null };
+ const result = mapPage(page, 1);
+ expect(result.customDomain).toBe("");
+ });
+});
+
+describe("mapComponent", () => {
+ it("maps a component with all fields", () => {
+ const result = mapComponent(MOCK_COMPONENTS[0], 1, 10);
+ expect(result).toEqual({
+ workspaceId: 1,
+ pageId: 10,
+ type: "static",
+ monitorId: null,
+ name: "API Gateway",
+ description: "Main API gateway for all services",
+ order: 1,
+ });
+ });
+
+ it("maps position to order", () => {
+ const result = mapComponent(MOCK_COMPONENTS[2], 1, 10);
+ expect(result.order).toBe(3);
+ });
+});
+
+describe("mapComponentGroup", () => {
+ it("maps a component group", () => {
+ const result = mapComponentGroup(MOCK_COMPONENT_GROUPS[0], 1, 10);
+ expect(result).toEqual({
+ workspaceId: 1,
+ pageId: 10,
+ name: "Core Services",
+ });
+ });
+});
+
+describe("isScheduledIncident", () => {
+ it("returns true for scheduled incidents", () => {
+ expect(isScheduledIncident(MOCK_INCIDENTS[2])).toBe(true);
+ });
+
+ it("returns false for realtime incidents", () => {
+ expect(isScheduledIncident(MOCK_INCIDENTS[0])).toBe(false);
+ expect(isScheduledIncident(MOCK_INCIDENTS[1])).toBe(false);
+ });
+});
+
+describe("mapIncidentToStatusReport", () => {
+ it("maps a resolved incident with 4 updates", () => {
+ const result = mapIncidentToStatusReport(MOCK_INCIDENTS[0], 1, 10);
+ expect(result.report.title).toBe("API Gateway Elevated Error Rates");
+ expect(result.report.status).toBe("resolved");
+ expect(result.report.workspaceId).toBe(1);
+ expect(result.report.pageId).toBe(10);
+ expect(result.updates).toHaveLength(4);
+ expect(result.updates[0].status).toBe("investigating");
+ expect(result.updates[1].status).toBe("identified");
+ expect(result.updates[2].status).toBe("monitoring");
+ expect(result.updates[3].status).toBe("resolved");
+ expect(result.sourceComponentIds).toEqual(["sp_comp_001"]);
+ });
+
+ it("maps an ongoing incident", () => {
+ const result = mapIncidentToStatusReport(MOCK_INCIDENTS[1], 1, 10);
+ expect(result.report.status).toBe("identified");
+ expect(result.updates).toHaveLength(2);
+ expect(result.sourceComponentIds).toEqual(["sp_comp_003"]);
+ });
+
+ it("appends postmortem to last update", () => {
+ const result = mapIncidentToStatusReport(MOCK_INCIDENTS[0], 1, 10);
+ const lastUpdate = result.updates[result.updates.length - 1];
+ expect(lastUpdate.message).toContain("---\n\n**Postmortem**\n\n");
+ expect(lastUpdate.message).toContain("## Summary");
+ });
+});
+
+describe("mapIncidentUpdateStatus", () => {
+ it.each([
+ ["investigating", "investigating"],
+ ["identified", "identified"],
+ ["monitoring", "monitoring"],
+ ["resolved", "resolved"],
+ ["scheduled", "investigating"],
+ ["in_progress", "investigating"],
+ ["verifying", "monitoring"],
+ ["completed", "resolved"],
+ ] as const)("maps %s to %s", (input, expected) => {
+ expect(mapIncidentUpdateStatus(input)).toBe(expected);
+ });
+});
+
+describe("mapIncidentToMaintenance", () => {
+ it("maps a scheduled incident to maintenance", () => {
+ const result = mapIncidentToMaintenance(MOCK_INCIDENTS[2], 1, 10);
+ expect(result.title).toBe("Scheduled Database Maintenance");
+ expect(result.workspaceId).toBe(1);
+ expect(result.pageId).toBe(10);
+ expect(result.from).toEqual(new Date("2024-06-20T02:00:00.000Z"));
+ expect(result.to).toEqual(new Date("2024-06-20T06:00:00.000Z"));
+ expect(result.message).toContain("scheduled database maintenance");
+ });
+});
+
+describe("mapSubscriber", () => {
+ it("maps email subscriber", () => {
+ const result = mapSubscriber(MOCK_SUBSCRIBERS[0], 10);
+ expect(result).toEqual({
+ email: "[email protected]",
+ pageId: 10,
+ sourceComponentIds: [],
+ });
+ });
+
+ it("maps email subscriber with component subscriptions", () => {
+ const result = mapSubscriber(MOCK_SUBSCRIBERS[1], 10);
+ expect(result).toEqual({
+ email: "[email protected]",
+ pageId: 10,
+ sourceComponentIds: ["sp_comp_001", "sp_comp_003"],
+ });
+ });
+
+ it("returns null for webhook subscriber", () => {
+ expect(mapSubscriber(MOCK_SUBSCRIBERS[2], 10)).toBeNull();
+ });
+
+ it("returns null for sms subscriber", () => {
+ expect(mapSubscriber(MOCK_SUBSCRIBERS[3], 10)).toBeNull();
+ });
+
+ it("returns null for slack subscriber", () => {
+ expect(mapSubscriber(MOCK_SUBSCRIBERS[4], 10)).toBeNull();
+ });
+});
diff --git a/packages/importers/src/providers/statuspage/mapper.ts b/packages/importers/src/providers/statuspage/mapper.ts
new file mode 100644
index 000000000..22873de9e
--- /dev/null
+++ b/packages/importers/src/providers/statuspage/mapper.ts
@@ -0,0 +1,158 @@
+import type {
+ StatuspageComponent,
+ StatuspageGroupComponent,
+ StatuspageIncident,
+ StatuspagePage,
+ StatuspageSubscriber,
+} from "./api-types";
+
+export type StatusReportStatus =
+ | "investigating"
+ | "identified"
+ | "monitoring"
+ | "resolved";
+
+export function mapPage(page: StatuspagePage, workspaceId: number) {
+ return {
+ workspaceId,
+ title: page.name,
+ description: page.page_description ?? "",
+ slug: page.subdomain,
+ customDomain: page.domain ?? "",
+ published: true,
+ icon: "",
+ };
+}
+
+export function mapComponent(
+ component: StatuspageComponent,
+ workspaceId: number,
+ pageId?: number,
+) {
+ return {
+ workspaceId,
+ pageId,
+ type: "static" as const,
+ monitorId: null,
+ name: component.name,
+ description: component.description ?? null,
+ order: component.position ?? 0,
+ };
+}
+
+export function mapComponentGroup(
+ group: StatuspageGroupComponent,
+ workspaceId: number,
+ pageId?: number,
+) {
+ return {
+ workspaceId,
+ pageId,
+ name: group.name,
+ };
+}
+
+const INCIDENT_UPDATE_STATUS_MAP: Record<string, StatusReportStatus> = {
+ investigating: "investigating",
+ identified: "identified",
+ monitoring: "monitoring",
+ resolved: "resolved",
+ scheduled: "investigating",
+ in_progress: "investigating",
+ verifying: "monitoring",
+ completed: "resolved",
+};
+
+export function mapIncidentUpdateStatus(status: string): StatusReportStatus {
+ return INCIDENT_UPDATE_STATUS_MAP[status] ?? "investigating";
+}
+
+export function isScheduledIncident(incident: StatuspageIncident): boolean {
+ return incident.scheduled_for != null;
+}
+
+export function mapIncidentToStatusReport(
+ incident: StatuspageIncident,
+ workspaceId: number,
+ pageId?: number,
+) {
+ const updates = [...(incident.incident_updates ?? [])].sort(
+ (a, b) =>
+ new Date(a.created_at).getTime() - new Date(b.created_at).getTime(),
+ );
+
+ const mappedUpdates = updates.map((u) => ({
+ status: mapIncidentUpdateStatus(u.status),
+ message: u.body ?? "",
+ date: new Date(u.created_at),
+ }));
+
+ if (incident.postmortem_body && mappedUpdates.length > 0) {
+ const last = mappedUpdates[mappedUpdates.length - 1];
+ last.message = `${last.message}\n\n---\n\n**Postmortem**\n\n${incident.postmortem_body}`;
+ }
+
+ const lastUpdate = updates[updates.length - 1];
+ const reportStatus = lastUpdate
+ ? mapIncidentUpdateStatus(lastUpdate.status)
+ : "investigating";
+
+ const sourceComponentIds: string[] = [];
+ if (incident.components) {
+ for (const comp of incident.components) {
+ sourceComponentIds.push(comp.id);
+ }
+ }
+
+ return {
+ report: {
+ title: incident.name,
+ status: reportStatus,
+ workspaceId,
+ pageId,
+ },
+ updates: mappedUpdates,
+ sourceComponentIds,
+ };
+}
+
+export function mapIncidentToMaintenance(
+ incident: StatuspageIncident,
+ workspaceId: number,
+ pageId?: number,
+) {
+ const updates = incident.incident_updates ?? [];
+ const message = updates.map((u) => u.body ?? "").join("\n");
+
+ if (!incident.scheduled_for) {
+ throw new Error(
+ `Incident "${incident.name}" is missing scheduled_for date`,
+ );
+ }
+
+ return {
+ title: incident.name,
+ message,
+ from: new Date(incident.scheduled_for),
+ to: new Date(incident.scheduled_until ?? incident.scheduled_for),
+ workspaceId,
+ pageId,
+ };
+}
+
+export function mapSubscriber(
+ subscriber: StatuspageSubscriber,
+ pageId?: number,
+): {
+ email: string;
+ pageId?: number;
+ sourceComponentIds: string[];
+} | null {
+ if (subscriber.mode !== "email") return null;
+
+ return {
+ email: subscriber.email ?? "",
+ pageId,
+ sourceComponentIds: subscriber.components ?? [],
+ };
+}
diff --git a/packages/importers/src/providers/statuspage/provider.test.ts b/packages/importers/src/providers/statuspage/provider.test.ts
new file mode 100644
index 000000000..b05aca28d
--- /dev/null
+++ b/packages/importers/src/providers/statuspage/provider.test.ts
@@ -0,0 +1,137 @@
+import { afterAll, beforeAll, describe, expect, it } from "bun:test";
+import {
+ MOCK_COMPONENTS,
+ MOCK_COMPONENT_GROUPS,
+ MOCK_INCIDENTS,
+ MOCK_PAGES,
+ MOCK_SUBSCRIBERS,
+} from "./fixtures";
+import {
+ type StatuspageImportConfig,
+ createStatuspageProvider,
+} from "./provider";
+
+function createMockFetch(options?: { failAuth?: boolean }) {
+ return (input: string | URL | Request): Promise<Response> => {
+ const url = typeof input === "string" ? input : input.toString();
+
+ if (options?.failAuth) {
+ return Promise.resolve(
+ new Response(JSON.stringify({ error: "Unauthorized" }), {
+ status: 401,
+ statusText: "Unauthorized",
+ }),
+ );
+ }
+
+ if (url.endsWith("/pages")) {
+ return Promise.resolve(Response.json(MOCK_PAGES));
+ }
+ if (url.match(/\/pages\/[^/]+\/components(\?|$)/)) {
+ const pageParam = new URL(url).searchParams.get("page");
+ return Promise.resolve(
+ Response.json(pageParam === "1" || !pageParam ? MOCK_COMPONENTS : []),
+ );
+ }
+ if (url.match(/\/pages\/[^/]+\/component-groups(\?|$)/)) {
+ const pageParam = new URL(url).searchParams.get("page");
+ return Promise.resolve(
+ Response.json(
+ pageParam === "1" || !pageParam ? MOCK_COMPONENT_GROUPS : [],
+ ),
+ );
+ }
+ if (url.match(/\/pages\/[^/]+\/incidents(\?|$)/)) {
+ const pageParam = new URL(url).searchParams.get("page");
+ return Promise.resolve(
+ Response.json(pageParam === "1" || !pageParam ? MOCK_INCIDENTS : []),
+ );
+ }
+ if (url.match(/\/pages\/[^/]+\/subscribers(\?|$)/)) {
+ const pageParam = new URL(url).searchParams.get("page");
+ return Promise.resolve(
+ Response.json(pageParam === "1" || !pageParam ? MOCK_SUBSCRIBERS : []),
+ );
+ }
+
+ return Promise.resolve(
+ new Response("Not Found", { status: 404, statusText: "Not Found" }),
+ );
+ };
+}
+
+describe("StatuspageImportProvider", () => {
+ const originalFetch = globalThis.fetch;
+
+ beforeAll(() => {
+ globalThis.fetch = createMockFetch() as typeof fetch;
+ });
+
+ afterAll(() => {
+ globalThis.fetch = originalFetch;
+ });
+
+ it("has name 'statuspage'", () => {
+ const provider = createStatuspageProvider();
+ expect(provider.name).toBe("statuspage");
+ });
+
+ it("validate returns valid for working key", async () => {
+ const provider = createStatuspageProvider();
+ const result = await provider.validate({
+ apiKey: "test-key",
+ workspaceId: 1,
+ });
+ expect(result).toEqual({ valid: true });
+ });
+
+ it("validate returns error for 401", async () => {
+ const prev = globalThis.fetch;
+ globalThis.fetch = createMockFetch({ failAuth: true }) as typeof fetch;
+
+ const provider = createStatuspageProvider();
+ const result = await provider.validate({
+ apiKey: "bad-key",
+ workspaceId: 1,
+ });
+ expect(result.valid).toBe(false);
+ expect(result.error).toBeDefined();
+
+ globalThis.fetch = prev;
+ });
+
+ it("run with dryRun returns correct phase counts", async () => {
+ const provider = createStatuspageProvider();
+ const config: StatuspageImportConfig = {
+ apiKey: "test-key",
+ workspaceId: 1,
+ dryRun: true,
+ };
+
+ const summary = await provider.run(config);
+
+ expect(summary.provider).toBe("statuspage");
+ expect(summary.status).toBe("completed");
+
+ const findPhase = (name: string) =>
+ summary.phases.find((p) => p.phase === name);
+
+ // 1 page
+ expect(findPhase("page")?.resources).toHaveLength(1);
+
+ // 1 component group
+ expect(findPhase("componentGroups")?.resources).toHaveLength(1);
+
+ // 4 components
+ expect(findPhase("components")?.resources).toHaveLength(4);
+
+ // 2 realtime incidents (incident_001 and incident_002; incident_003 is scheduled)
+ expect(findPhase("incidents")?.resources).toHaveLength(2);
+
+ // 1 maintenance (incident_003)
+ expect(findPhase("maintenances")?.resources).toHaveLength(1);
+
+ // 2 subscribers: 2 email only (webhook + sms + slack skipped)
+ expect(findPhase("subscribers")?.resources).toHaveLength(2);
+ });
+});
diff --git a/packages/importers/src/providers/statuspage/provider.ts b/packages/importers/src/providers/statuspage/provider.ts
new file mode 100644
index 000000000..7e337e549
--- /dev/null
+++ b/packages/importers/src/providers/statuspage/provider.ts
@@ -0,0 +1,189 @@
+import type {
+ ImportConfig,
+ ImportProvider,
+ PhaseResult,
+ ResourceResult,
+} from "../../types";
+import type { StatuspageIncident } from "./api-types";
+import { createStatuspageClient } from "./client";
+import {
+ isScheduledIncident,
+ mapComponent,
+ mapComponentGroup,
+ mapIncidentToMaintenance,
+ mapIncidentToStatusReport,
+ mapPage,
+ mapSubscriber,
+} from "./mapper";
+
+export interface StatuspageImportConfig extends ImportConfig {
+ statuspagePageId?: string;
+}
+
+export function createStatuspageProvider(): ImportProvider<StatuspageImportConfig> {
+ return {
+ name: "statuspage",
+
+ validate: async (config) => {
+ try {
+ const client = createStatuspageClient(config.apiKey);
+ await client.getPages();
+ return { valid: true };
+ } catch (err) {
+ return {
+ valid: false,
+ error: err instanceof Error ? err.message : String(err),
+ };
+ }
+ },
+
+ run: async (config) => {
+ const startedAt = new Date();
+ const client = createStatuspageClient(config.apiKey);
+ const phases: PhaseResult[] = [];
+
+ let pages = await client.getPages();
+ if (config.statuspagePageId) {
+ pages = pages.filter((p) => p.id === config.statuspagePageId);
+ }
+
+ let skippedSubscribers = 0;
+
+ for (const page of pages) {
+ const [components, groups, incidents, subscribers] = await Promise.all([
+ client.getComponents(page.id),
+ client.getComponentGroups(page.id),
+ client.getIncidents(page.id),
+ client.getSubscribers(page.id),
+ ]);
+
+ // Page phase
+ const mappedPage = mapPage(page, config.workspaceId);
+ phases.push({
+ phase: "page",
+ status: "completed",
+ resources: [
+ {
+ sourceId: page.id,
+ name: page.name,
+ status: "created",
+ data: mappedPage,
+ },
+ ],
+ });
+
+ const pageId = config.pageId;
+
+ // Component groups phase
+ const groupResources: ResourceResult[] = groups.map((g) => ({
+ sourceId: g.id,
+ name: g.name,
+ status: "created" as const,
+ data: mapComponentGroup(g, config.workspaceId, pageId),
+ }));
+ phases.push({
+ phase: "componentGroups",
+ status: "completed",
+ resources: groupResources,
+ });
+
+ // Components phase
+ const componentResources: ResourceResult[] = components.map((c) => ({
+ sourceId: c.id,
+ name: c.name,
+ status: "created" as const,
+ data: {
+ ...mapComponent(c, config.workspaceId, pageId),
+ sourceGroupId: c.group_id,
+ },
+ }));
+ phases.push({
+ phase: "components",
+ status: "completed",
+ resources: componentResources,
+ });
+
+ // Split incidents
+ const realtimeIncidents: StatuspageIncident[] = [];
+ const scheduledIncidents: StatuspageIncident[] = [];
+ for (const inc of incidents) {
+ if (isScheduledIncident(inc)) {
+ scheduledIncidents.push(inc);
+ } else {
+ realtimeIncidents.push(inc);
+ }
+ }
+
+ // Incidents phase (status reports)
+ const incidentResources: ResourceResult[] = realtimeIncidents.map(
+ (inc) => ({
+ sourceId: inc.id,
+ name: inc.name,
+ status: "created" as const,
+ data: mapIncidentToStatusReport(inc, config.workspaceId, pageId),
+ }),
+ );
+ phases.push({
+ phase: "incidents",
+ status: "completed",
+ resources: incidentResources,
+ });
+
+ // Maintenances phase
+ const maintenanceResources: ResourceResult[] = scheduledIncidents.map(
+ (inc) => ({
+ sourceId: inc.id,
+ name: inc.name,
+ status: "created" as const,
+ data: {
+ ...mapIncidentToMaintenance(inc, config.workspaceId, pageId),
+ sourceComponentIds: (inc.components ?? []).map((c) => c.id),
+ },
+ }),
+ );
+ phases.push({
+ phase: "maintenances",
+ status: "completed",
+ resources: maintenanceResources,
+ });
+
+ // Subscribers phase
+ const subscriberResources: ResourceResult[] = [];
+ for (const sub of subscribers) {
+ const mapped = mapSubscriber(sub, pageId);
+ if (mapped) {
+ subscriberResources.push({
+ sourceId: sub.id,
+ name: sub.email ?? sub.endpoint ?? sub.id,
+ status: "created",
+ data: mapped,
+ });
+ } else {
+ skippedSubscribers++;
+ }
+ }
+ phases.push({
+ phase: "subscribers",
+ status: "completed",
+ resources: subscriberResources,
+ });
+ }
+
+ const errors: string[] = [];
+ if (skippedSubscribers > 0) {
+ errors.push(
+ `Only email subscribers are supported. ${skippedSubscribers} non-email subscriber${skippedSubscribers === 1 ? " was" : "s were"} skipped.`,
+ );
+ }
+
+ return {
+ provider: "statuspage",
+ status: "completed",
+ startedAt,
+ completedAt: new Date(),
+ phases,
+ errors,
+ };
+ },
+ };
+}
diff --git a/packages/importers/src/types.ts b/packages/importers/src/types.ts
new file mode 100644
index 000000000..1744666e2
--- /dev/null
+++ b/packages/importers/src/types.ts
@@ -0,0 +1,51 @@
+/**
+ * Result of importing a single resource.
+ */
+export type ResourceResult = {
+ sourceId: string;
+ openstatusId?: number;
+ name: string;
+ status: "created" | "skipped" | "failed";
+ error?: string;
+ data?: unknown;
+};
+
+/**
+ * Result of a single import phase (e.g., "components", "incidents").
+ */
+export type PhaseResult = {
+ phase: string;
+ status: "completed" | "partial" | "failed" | "skipped";
+ resources: ResourceResult[];
+};
+
+/**
+ * Summary returned after a full import completes.
+ */
+export type ImportSummary = {
+ provider: string;
+ status: "completed" | "partial" | "failed";
+ startedAt: Date;
+ completedAt: Date;
+ phases: PhaseResult[];
+ errors: string[];
+};
+
+/**
+ * Configuration passed to any import provider.
+ */
+export type ImportConfig = {
+ apiKey: string;
+ workspaceId: number;
+ pageId?: number;
+ dryRun?: boolean;
+};
+
+/**
+ * Every import provider must conform to this type.
+ */
+export type ImportProvider<TConfig extends ImportConfig = ImportConfig> = {
+ name: string;
+ validate: (config: TConfig) => Promise<{ valid: boolean; error?: string }>;
+ run: (config: TConfig) => Promise<ImportSummary>;
+};
diff --git a/packages/importers/tsconfig.json b/packages/importers/tsconfig.json
new file mode 100644
index 000000000..22dfcb384
--- /dev/null
+++ b/packages/importers/tsconfig.json
@@ -0,0 +1,8 @@
+{
+ "extends": "@openstatus/tsconfig/base.json",
+ "compilerOptions": {
+ "outDir": "./dist",
+ "rootDir": "./src"
+ },
+ "include": ["src"]
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index da66f5d4a..15c56da8f 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -98,6 +98,9 @@ importers:
'@openstatus/icons':
specifier: workspace:*
version: link:../../packages/icons
+ '@openstatus/importers':
+ specifier: workspace:*
+ version: link:../../packages/importers
'@openstatus/notification-discord':
specifier: workspace:*
version: link:../../packages/notifications/discord
@@ -1216,6 +1219,9 @@ importers:
'@openstatus/error':
specifier: workspace:*
version: link:../error
+ '@openstatus/importers':
+ specifier: workspace:*
+ version: link:../importers
'@openstatus/notification-google-chat':
specifier: workspace:*
version: link:../notifications/google-chat
@@ -1451,6 +1457,19 @@ importers:
specifier: 5.9.3
version: 5.9.3
+ packages/importers:
+ dependencies:
+ zod:
+ specifier: 4.1.13
+ version: 4.1.13
+ devDependencies:
+ '@openstatus/tsconfig':
+ specifier: workspace:*
+ version: link:../tsconfig
+ typescript:
+ specifier: 5.9.3
+ version: 5.9.3
+
packages/notifications/base:
dependencies:
'@openstatus/db':