Skip to content

Open-source status page, incident response and uptime monitoring

feat: instatus importer (#1973)

Maximilian Kaskeaeb006c8c455
diff --git a/apps/dashboard/src/components/forms/components/form-import.tsx b/apps/dashboard/src/components/forms/components/form-import.tsx
index 8ff2deec8..99844d806 100644
--- a/apps/dashboard/src/components/forms/components/form-import.tsx
+++ b/apps/dashboard/src/components/forms/components/form-import.tsx
@@ -12,7 +12,7 @@ import {
} from "@/components/forms/form-card";
import { useTRPC } from "@/lib/trpc/client";
import { zodResolver } from "@hookform/resolvers/zod";
-import { StatuspageIcon } from "@openstatus/icons";
+import { InstatusIcon, 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";
@@ -40,9 +40,10 @@ import { toast } from "sonner";
import { z } from "zod";
const schema = z.object({
- provider: z.enum(["statuspage"]),
+ provider: z.enum(["statuspage", "instatus"]),
apiKey: z.string().min(1, "API key is required"),
statuspagePageId: z.string().optional(),
+ instatusPageId: z.string().optional(),
includeStatusReports: z.boolean(),
includeSubscribers: z.boolean(),
includeComponents: z.boolean(),
@@ -75,6 +76,7 @@ export function FormImport({
provider: undefined,
apiKey: "",
statuspagePageId: "",
+ instatusPageId: "",
includeStatusReports: true,
includeSubscribers: false,
includeComponents: true,
@@ -85,6 +87,7 @@ export function FormImport({
const watchProvider = form.watch("provider");
const watchApiKey = form.watch("apiKey");
const watchStatuspagePageId = form.watch("statuspagePageId");
+ const watchInstatusPageId = form.watch("instatusPageId");
const previewMutation = useMutation(
trpc.import.preview.mutationOptions({
@@ -105,9 +108,16 @@ export function FormImport({
return;
}
previewMutation.mutate({
- provider: "statuspage",
+ provider: watchProvider,
apiKey: watchApiKey,
- statuspagePageId: watchStatuspagePageId || undefined,
+ statuspagePageId:
+ watchProvider === "statuspage"
+ ? watchStatuspagePageId || undefined
+ : undefined,
+ instatusPageId:
+ watchProvider === "instatus"
+ ? watchInstatusPageId || undefined
+ : undefined,
pageId,
});
}
@@ -178,6 +188,21 @@ export function FormImport({
Atlassian Statuspage
</FormLabel>
</FormItem>
+ <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="instatus"
+ className="sr-only"
+ />
+ </FormControl>
+ <InstatusIcon
+ 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">
+ Instatus
+ </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>
@@ -202,34 +227,59 @@ export function FormImport({
<FormControl>
<Input
type="password"
- placeholder="OAuth API key"
+ placeholder={
+ watchProvider === "instatus"
+ ? "Bearer API key"
+ : "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.
+ {watchProvider === "instatus"
+ ? "Your Instatus API key. Found in your Instatus account under Settings > API."
+ : "Your Statuspage API key. Found in your Statuspage account under Manage Account > API."}
</FormDescription>
</FormItem>
)}
/>
+ {watchProvider === "statuspage" ? (
+ <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>
+ )}
+ />
+ ) : null}
+ {watchProvider === "instatus" ? (
+ <FormField
+ control={form.control}
+ name="instatusPageId"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Page ID (optional)</FormLabel>
+ <FormControl>
+ <Input placeholder="e.g. clx1abc2def3" {...field} />
+ </FormControl>
+ <FormDescription>
+ Import a specific page. Leave empty to import all
+ pages.
+ </FormDescription>
+ </FormItem>
+ )}
+ />
+ ) : null}
<Button
type="button"
variant="secondary"
diff --git a/packages/api/src/router/import.ts b/packages/api/src/router/import.ts
index 2bbdf3844..c92c78e4a 100644
--- a/packages/api/src/router/import.ts
+++ b/packages/api/src/router/import.ts
@@ -9,16 +9,19 @@ export const importRouter = createTRPCRouter({
preview: protectedProcedure
.input(
z.object({
- provider: z.enum(["statuspage"]),
+ provider: z.enum(["statuspage", "instatus"]),
apiKey: z.string().min(1),
statuspagePageId: z.string().nullish(),
+ instatusPageId: z.string().nullish(),
pageId: z.number().optional(),
}),
)
.mutation(async (opts) => {
return previewImport({
+ provider: opts.input.provider,
apiKey: opts.input.apiKey,
statuspagePageId: opts.input.statuspagePageId ?? undefined,
+ instatusPageId: opts.input.instatusPageId ?? undefined,
workspaceId: opts.ctx.workspace.id,
pageId: opts.input.pageId,
limits: opts.ctx.workspace.limits,
@@ -28,10 +31,11 @@ export const importRouter = createTRPCRouter({
run: protectedProcedure
.input(
z.object({
- provider: z.enum(["statuspage"]),
+ provider: z.enum(["statuspage", "instatus"]),
apiKey: z.string().min(1),
pageId: z.number().optional(),
statuspagePageId: z.string().nullish(),
+ instatusPageId: z.string().nullish(),
options: z
.object({
includeStatusReports: z.boolean().default(true),
@@ -64,8 +68,10 @@ export const importRouter = createTRPCRouter({
}
return runImport({
+ provider: opts.input.provider,
apiKey: opts.input.apiKey,
statuspagePageId: opts.input.statuspagePageId ?? undefined,
+ instatusPageId: opts.input.instatusPageId ?? undefined,
workspaceId: opts.ctx.workspace.id,
pageId: opts.input.pageId,
options: opts.input.options,
diff --git a/packages/api/src/service/import.ts b/packages/api/src/service/import.ts
index e8a7a1eda..593aa2de6 100644
--- a/packages/api/src/service/import.ts
+++ b/packages/api/src/service/import.ts
@@ -17,6 +17,7 @@ import type {
PhaseResult,
ResourceResult,
} from "@openstatus/importers";
+import { createInstatusProvider } from "@openstatus/importers/instatus";
import { createStatuspageProvider } from "@openstatus/importers/statuspage";
import { TRPCError } from "@trpc/server";
@@ -26,6 +27,28 @@ type ImportOptions = {
includeComponents?: boolean;
};
+type ProviderName = "statuspage" | "instatus";
+
+function createProvider(name: ProviderName) {
+ return name === "instatus"
+ ? createInstatusProvider()
+ : createStatuspageProvider();
+}
+
+function buildProviderConfig(config: {
+ provider: ProviderName;
+ apiKey: string;
+ workspaceId: number;
+ pageId?: number;
+ statuspagePageId?: string;
+ instatusPageId?: string;
+}) {
+ const { provider, ...rest } = config;
+ return provider === "instatus"
+ ? { ...rest, instatusPageId: config.instatusPageId }
+ : { ...rest, statuspagePageId: config.statuspagePageId };
+}
+
/**
* Inspect an ImportSummary and push warnings into `summary.errors`
* for any limits that would be hit during import.
@@ -97,16 +120,19 @@ export async function addLimitWarnings(
}
export async function previewImport(config: {
+ provider: ProviderName;
apiKey: string;
statuspagePageId?: string;
+ instatusPageId?: string;
workspaceId: number;
pageId?: number;
limits: Limits;
}): Promise<ImportSummary> {
- const provider = createStatuspageProvider();
+ const provider = createProvider(config.provider);
+ const providerConfig = buildProviderConfig(config);
const validation = await provider.validate({
- ...config,
+ ...providerConfig,
dryRun: true,
});
if (!validation.valid) {
@@ -116,22 +142,25 @@ export async function previewImport(config: {
});
}
- const summary = await provider.run({ ...config, dryRun: true });
+ const summary = await provider.run({ ...providerConfig, dryRun: true });
await addLimitWarnings(summary, config);
return summary;
}
export async function runImport(config: {
+ provider: ProviderName;
apiKey: string;
statuspagePageId?: string;
+ instatusPageId?: string;
workspaceId: number;
pageId?: number;
options?: ImportOptions;
limits: Limits;
}): Promise<ImportSummary> {
- const provider = createStatuspageProvider();
+ const provider = createProvider(config.provider);
+ const providerConfig = buildProviderConfig(config);
- const validation = await provider.validate(config);
+ const validation = await provider.validate(providerConfig);
if (!validation.valid) {
throw new TRPCError({
code: "BAD_REQUEST",
@@ -140,7 +169,7 @@ export async function runImport(config: {
}
// Fetch and map all data
- const summary = await provider.run(config);
+ const summary = await provider.run(providerConfig);
// Add limit warnings (same as preview)
await addLimitWarnings(summary, config);
@@ -686,6 +715,7 @@ async function writeSubscribersPhase(
const data = resource.data as {
email: string;
pageId: number;
+ confirmed: boolean;
sourceComponentIds: string[];
};
@@ -714,6 +744,7 @@ async function writeSubscribersPhase(
email: data.email,
pageId,
channelType: "email",
+ acceptedAt: data.confirmed ? new Date() : undefined,
})
.returning({ id: pageSubscriber.id });
diff --git a/packages/icons/src/index.tsx b/packages/icons/src/index.tsx
index ff2b7cb8e..1f51368c3 100644
--- a/packages/icons/src/index.tsx
+++ b/packages/icons/src/index.tsx
@@ -12,3 +12,4 @@ export * from "./telegram";
export * from "./whatsapp";
export * from "./markdown";
export * from "./statuspage";
+export * from "./instatus";
diff --git a/packages/icons/src/instatus.tsx b/packages/icons/src/instatus.tsx
new file mode 100644
index 000000000..6a63a13eb
--- /dev/null
+++ b/packages/icons/src/instatus.tsx
@@ -0,0 +1,15 @@
+export function InstatusIcon(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>Instatus</title>
+ <path d="m16.994 21.028c3.5843-1.91 5.471-5.759 5.0561-9.5637-1.3206 1.0851-2.6237 2.3203-3.8709 3.6906-2.0656 2.2694-3.7476 4.6559-4.9953 6.9817 1.2946-0.09715 2.5907-0.45868 3.8101-1.1086zm-13.394-2.5626c-1.3408 1.8191-2.3771 4.4991-1.3032 5.3066 1.5151 1.1394 8.404-2.0133 13.908-8.8051 5.504-6.7918 7.3265-13.796 4.879-14.873-1.1283-0.49644-3.486 1.083-4.8394 2.3943l0.58412 0.31415c1.332-0.85276 3.5528-1.7338 1.4995 1.9758-0.0097 0.01768-0.01962 0.03541-0.02949 0.05317-2.9067-2.2075-6.9471-2.662-10.379-0.8328-4.7026 2.506-6.4831 8.3499-3.9771 13.052 0.58979 1.1067 1.3644 2.0516 2.2655 2.8168-3.5586 2.7493-2.6905 0.35965-2.1925-0.8162z" />
+ </svg>
+ );
+}
diff --git a/packages/importers/package.json b/packages/importers/package.json
index 508cd87d9..64e8c4702 100644
--- a/packages/importers/package.json
+++ b/packages/importers/package.json
@@ -7,7 +7,9 @@
".": "./src/index.ts",
"./types": "./src/types.ts",
"./statuspage": "./src/providers/statuspage/index.ts",
- "./statuspage/fixtures": "./src/providers/statuspage/fixtures.ts"
+ "./statuspage/fixtures": "./src/providers/statuspage/fixtures.ts",
+ "./instatus": "./src/providers/instatus/index.ts",
+ "./instatus/fixtures": "./src/providers/instatus/fixtures.ts"
},
"scripts": {
"test": "bun test",
diff --git a/packages/importers/src/index.ts b/packages/importers/src/index.ts
index 8fead1e8a..1932b40ca 100644
--- a/packages/importers/src/index.ts
+++ b/packages/importers/src/index.ts
@@ -9,9 +9,12 @@ export type {
export { createStatuspageProvider } from "./providers/statuspage";
export type { StatuspageImportConfig } from "./providers/statuspage";
+export { createInstatusProvider } from "./providers/instatus";
+export type { InstatusImportConfig } from "./providers/instatus";
+
/**
* Registry of all available import providers.
* Add new providers here as they are implemented.
*/
-export const IMPORT_PROVIDERS = ["statuspage"] as const;
+export const IMPORT_PROVIDERS = ["statuspage", "instatus"] as const;
export type ImportProviderName = (typeof IMPORT_PROVIDERS)[number];
diff --git a/packages/importers/src/providers/instatus/api-types.ts b/packages/importers/src/providers/instatus/api-types.ts
new file mode 100644
index 000000000..2fe1f611f
--- /dev/null
+++ b/packages/importers/src/providers/instatus/api-types.ts
@@ -0,0 +1,110 @@
+import { z } from "zod";
+
+export const InstatusPageSchema = z.object({
+ id: z.string(),
+ name: z.string(),
+ subdomain: z.string(),
+ customDomain: z.string().nullable(),
+ status: z.string(),
+ logoUrl: z.string().nullable(),
+ faviconUrl: z.string().nullable(),
+ websiteUrl: z.string().nullable(),
+ language: z.string().nullable(),
+ createdAt: z.string(),
+ updatedAt: z.string(),
+});
+
+export type InstatusPage = z.infer<typeof InstatusPageSchema>;
+
+export const InstatusComponentSchema = z.object({
+ id: z.string(),
+ name: z.string(),
+ description: z.string().nullable(),
+ status: z.enum([
+ "OPERATIONAL",
+ "UNDERMAINTENANCE",
+ "DEGRADEDPERFORMANCE",
+ "PARTIALOUTAGE",
+ "MAJOROUTAGE",
+ ]),
+ order: z.number(),
+ group: z.string().nullable().optional(),
+ showUptime: z.boolean().optional(),
+ grouped: z.boolean().optional(),
+});
+
+export type InstatusComponent = z.infer<typeof InstatusComponentSchema>;
+
+export const InstatusIncidentUpdateSchema = z.object({
+ id: z.string(),
+ message: z.string().nullable(),
+ messageHtml: z.string().nullable(),
+ status: z.enum(["INVESTIGATING", "IDENTIFIED", "MONITORING", "RESOLVED"]),
+ notify: z.boolean(),
+ started: z.string(),
+ createdAt: z.string(),
+});
+
+export type InstatusIncidentUpdate = z.infer<
+ typeof InstatusIncidentUpdateSchema
+>;
+
+const InstatusIncidentComponentRefSchema = z.object({
+ id: z.string(),
+ name: z.string().optional(),
+});
+
+export const InstatusIncidentSchema = z.object({
+ id: z.string(),
+ name: z.string(),
+ status: z.enum(["INVESTIGATING", "IDENTIFIED", "MONITORING", "RESOLVED"]),
+ started: z.string(),
+ resolved: z.string().nullable(),
+ updates: z.array(InstatusIncidentUpdateSchema).optional(),
+ components: z.array(InstatusIncidentComponentRefSchema).optional(),
+});
+
+export type InstatusIncident = z.infer<typeof InstatusIncidentSchema>;
+
+export const InstatusMaintenanceUpdateSchema = z.object({
+ id: z.string(),
+ message: z.string().nullable(),
+ messageHtml: z.string().nullable(),
+ status: z.enum(["NOTSTARTEDYET", "INPROGRESS", "COMPLETED"]),
+ notify: z.boolean(),
+ started: z.string(),
+});
+
+export type InstatusMaintenanceUpdate = z.infer<
+ typeof InstatusMaintenanceUpdateSchema
+>;
+
+export const InstatusMaintenanceSchema = z.object({
+ id: z.string(),
+ name: z.string(),
+ status: z.enum(["NOTSTARTEDYET", "INPROGRESS", "COMPLETED"]),
+ start: z.string(),
+ duration: z.number().nullable(),
+ updates: z.array(InstatusMaintenanceUpdateSchema).optional(),
+ components: z.array(InstatusIncidentComponentRefSchema).optional(),
+});
+
+export type InstatusMaintenance = z.infer<typeof InstatusMaintenanceSchema>;
+
+// Subscriber component refs can have localized `name` (object) unlike
+// incident/maintenance refs which use plain strings. We only need the ID.
+const InstatusSubscriberComponentRefSchema = z
+ .object({ id: z.string() })
+ .loose();
+
+export const InstatusSubscriberSchema = z.object({
+ id: z.string(),
+ email: z.string().nullable(),
+ phone: z.string().nullable(),
+ webhook: z.string().nullable(),
+ confirmed: z.boolean(),
+ all: z.boolean(),
+ components: z.array(InstatusSubscriberComponentRefSchema).optional(),
+});
+
+export type InstatusSubscriber = z.infer<typeof InstatusSubscriberSchema>;
diff --git a/packages/importers/src/providers/instatus/client.test.ts b/packages/importers/src/providers/instatus/client.test.ts
new file mode 100644
index 000000000..0fade1742
--- /dev/null
+++ b/packages/importers/src/providers/instatus/client.test.ts
@@ -0,0 +1,151 @@
+import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test";
+import { createInstatusClient } from "./client";
+import {
+ MOCK_COMPONENTS,
+ MOCK_INCIDENTS,
+ MOCK_MAINTENANCES,
+ 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 unknown as typeof globalThis.fetch;
+}
+
+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 unknown as typeof globalThis.fetch;
+}
+
+describe("InstatusClient", () => {
+ let client: ReturnType<typeof createInstatusClient>;
+
+ beforeEach(() => {
+ client = createInstatusClient("test-api-key");
+ });
+
+ afterEach(() => {
+ globalThis.fetch = originalFetch;
+ });
+
+ test("getPages returns parsed pages with pagination", async () => {
+ mockFetchPaginated(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("in_page_001");
+ expect(components).toEqual(MOCK_COMPONENTS);
+ expect(components).toHaveLength(5);
+ });
+
+ test("getIncidents returns parsed incidents with updates", async () => {
+ mockFetchPaginated(MOCK_INCIDENTS);
+ const incidents = await client.getIncidents("in_page_001");
+ expect(incidents).toEqual(MOCK_INCIDENTS);
+ expect(incidents).toHaveLength(2);
+ expect(incidents[0].updates).toHaveLength(4);
+ expect(incidents[1].status).toBe("IDENTIFIED");
+ });
+
+ test("getMaintenances returns parsed maintenances", async () => {
+ mockFetchPaginated(MOCK_MAINTENANCES);
+ const maintenances = await client.getMaintenances("in_page_001");
+ expect(maintenances).toEqual(MOCK_MAINTENANCES);
+ expect(maintenances).toHaveLength(2);
+ expect(maintenances[0].duration).toBe(240);
+ });
+
+ test("getSubscribers returns parsed subscribers", async () => {
+ mockFetchPaginated(MOCK_SUBSCRIBERS);
+ const subscribers = await client.getSubscribers("in_page_001");
+ expect(subscribers).toEqual(MOCK_SUBSCRIBERS);
+ expect(subscribers).toHaveLength(5);
+ expect(subscribers[0].email).toBe("[email protected]");
+ expect(subscribers[2].phone).toBe("+15551234567");
+ });
+
+ test("throws on API error (401)", async () => {
+ mockFetch({ error: "Unauthorized" }, 401);
+ await expect(client.getPages()).rejects.toThrow(
+ "Instatus API error: 401 Unauthorized for /v2/pages",
+ );
+ });
+
+ test("getPage returns a single parsed page", async () => {
+ mockFetch(MOCK_PAGES[0]);
+ const singlePage = await client.getPage("in_page_001");
+ expect(singlePage).toEqual(MOCK_PAGES[0]);
+ expect(singlePage.id).toBe("in_page_001");
+ });
+
+ test("sends correct Bearer auth header", async () => {
+ mockFetchPaginated(MOCK_PAGES);
+ await client.getPages();
+ const fetchMock = globalThis.fetch as unknown as ReturnType<typeof mock>;
+ const [url, options] = fetchMock.mock.calls[0] as [string, RequestInit];
+ expect(url).toBe("https://api.instatus.com/v2/pages?page=1&per_page=100");
+ expect((options.headers as Record<string, string>).Authorization).toBe(
+ "Bearer test-api-key",
+ );
+ });
+
+ test("pagination handles response length exactly equal to per_page", async () => {
+ // Create exactly per_page items so the loop makes one extra fetch
+ const items = Array.from({ length: 100 }, (_, i) => ({
+ ...MOCK_COMPONENTS[0],
+ id: `comp_${i}`,
+ name: `Component ${i}`,
+ }));
+
+ let callCount = 0;
+ globalThis.fetch = mock(() => {
+ callCount++;
+ // First call: 100 items (= per_page), second call: empty array
+ const body = callCount === 1 ? items : [];
+ return Promise.resolve(
+ new Response(JSON.stringify(body), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ }),
+ );
+ }) as unknown as typeof globalThis.fetch;
+
+ const result = await client.getComponents("in_page_001");
+ expect(result).toHaveLength(100);
+ // Should have made 2 calls: first returns 100, second returns [] to terminate
+ expect(callCount).toBe(2);
+ });
+
+ test("uses v1 for incidents and v2 for other endpoints", async () => {
+ mockFetchPaginated(MOCK_INCIDENTS);
+ await client.getIncidents("in_page_001");
+ const fetchMock = globalThis.fetch as unknown as ReturnType<typeof mock>;
+ const [url] = fetchMock.mock.calls[0] as [string, RequestInit];
+ expect(url).toContain("/v1/in_page_001/incidents");
+ });
+});
diff --git a/packages/importers/src/providers/instatus/client.ts b/packages/importers/src/providers/instatus/client.ts
new file mode 100644
index 000000000..5c5fa6322
--- /dev/null
+++ b/packages/importers/src/providers/instatus/client.ts
@@ -0,0 +1,80 @@
+import { z } from "zod";
+import {
+ type InstatusComponent,
+ InstatusComponentSchema,
+ type InstatusIncident,
+ InstatusIncidentSchema,
+ type InstatusMaintenance,
+ InstatusMaintenanceSchema,
+ type InstatusPage,
+ InstatusPageSchema,
+ type InstatusSubscriber,
+ InstatusSubscriberSchema,
+} from "./api-types";
+
+export type InstatusClient = {
+ getPages: () => Promise<InstatusPage[]>;
+ getPage: (pageId: string) => Promise<InstatusPage>;
+ getComponents: (pageId: string) => Promise<InstatusComponent[]>;
+ getIncidents: (pageId: string) => Promise<InstatusIncident[]>;
+ getMaintenances: (pageId: string) => Promise<InstatusMaintenance[]>;
+ getSubscribers: (pageId: string) => Promise<InstatusSubscriber[]>;
+};
+
+export function createInstatusClient(
+ apiKey: string,
+ baseUrl = "https://api.instatus.com",
+): InstatusClient {
+ async function request<T>(path: string, schema: z.ZodType<T>): Promise<T> {
+ const url = `${baseUrl}${path}`;
+ const response = await fetch(url, {
+ headers: {
+ Authorization: `Bearer ${apiKey}`,
+ "Content-Type": "application/json",
+ },
+ });
+
+ if (!response.ok) {
+ throw new Error(
+ `Instatus 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: () => requestAllPages("/v2/pages", InstatusPageSchema),
+ getPage: (pageId) => request(`/v2/${pageId}`, InstatusPageSchema),
+ getComponents: (pageId) =>
+ requestAllPages(`/v2/${pageId}/components`, InstatusComponentSchema),
+ // Instatus only exposes incidents via v1 — there is no v2 equivalent.
+ getIncidents: (pageId) =>
+ requestAllPages(`/v1/${pageId}/incidents`, InstatusIncidentSchema),
+ getMaintenances: (pageId) =>
+ requestAllPages(`/v2/${pageId}/maintenances`, InstatusMaintenanceSchema),
+ getSubscribers: (pageId) =>
+ requestAllPages(`/v2/${pageId}/subscribers`, InstatusSubscriberSchema),
+ };
+}
diff --git a/packages/importers/src/providers/instatus/fixtures.ts b/packages/importers/src/providers/instatus/fixtures.ts
new file mode 100644
index 000000000..11a85c957
--- /dev/null
+++ b/packages/importers/src/providers/instatus/fixtures.ts
@@ -0,0 +1,267 @@
+import type {
+ InstatusComponent,
+ InstatusIncident,
+ InstatusMaintenance,
+ InstatusPage,
+ InstatusSubscriber,
+} from "./api-types";
+
+export const MOCK_PAGES: InstatusPage[] = [
+ {
+ id: "in_page_001",
+ name: "Acme Corp Status",
+ subdomain: "acmecorp",
+ customDomain: "status.acmecorp.com",
+ status: "UP",
+ logoUrl: "https://instatus.com/logo.png",
+ faviconUrl: "https://instatus.com/favicon.png",
+ websiteUrl: "https://acmecorp.com",
+ language: "en",
+ createdAt: "2024-01-15T10:00:00.000Z",
+ updatedAt: "2024-06-01T12:00:00.000Z",
+ },
+];
+
+export const MOCK_COMPONENTS: InstatusComponent[] = [
+ {
+ id: "in_comp_group_001",
+ name: "Core Services",
+ description: "Core infrastructure services",
+ status: "OPERATIONAL",
+ order: 0,
+ group: null,
+ showUptime: true,
+ grouped: false,
+ },
+ {
+ id: "in_comp_001",
+ name: "API Gateway",
+ description: "Main API gateway for all services",
+ status: "OPERATIONAL",
+ order: 1,
+ group: "in_comp_group_001",
+ showUptime: true,
+ grouped: true,
+ },
+ {
+ id: "in_comp_002",
+ name: "Authentication Service",
+ description: "Handles user authentication and authorization",
+ status: "OPERATIONAL",
+ order: 2,
+ group: "in_comp_group_001",
+ showUptime: true,
+ grouped: true,
+ },
+ {
+ id: "in_comp_003",
+ name: "Dashboard",
+ description: "Web dashboard application",
+ status: "DEGRADEDPERFORMANCE",
+ order: 3,
+ group: null,
+ showUptime: true,
+ grouped: false,
+ },
+ {
+ id: "in_comp_004",
+ name: "CDN",
+ description: null,
+ status: "OPERATIONAL",
+ order: 4,
+ group: null,
+ showUptime: false,
+ grouped: false,
+ },
+];
+
+export const MOCK_INCIDENTS: InstatusIncident[] = [
+ {
+ id: "in_incident_001",
+ name: "API Gateway Elevated Error Rates",
+ status: "RESOLVED",
+ started: "2024-06-10T14:00:00.000Z",
+ resolved: "2024-06-10T16:45:00.000Z",
+ updates: [
+ {
+ id: "in_update_001",
+ message:
+ "We are investigating elevated error rates on the API Gateway.",
+ messageHtml:
+ "<p>We are investigating elevated error rates on the API Gateway.</p>",
+ status: "INVESTIGATING",
+ notify: true,
+ started: "2024-06-10T14:00:00.000Z",
+ createdAt: "2024-06-10T14:00:00.000Z",
+ },
+ {
+ id: "in_update_002",
+ message:
+ "The issue has been identified as a misconfigured load balancer rule.",
+ messageHtml:
+ "<p>The issue has been identified as a misconfigured load balancer rule.</p>",
+ status: "IDENTIFIED",
+ notify: true,
+ started: "2024-06-10T14:30:00.000Z",
+ createdAt: "2024-06-10T14:30:00.000Z",
+ },
+ {
+ id: "in_update_003",
+ message: "A fix has been deployed and we are monitoring the results.",
+ messageHtml:
+ "<p>A fix has been deployed and we are monitoring the results.</p>",
+ status: "MONITORING",
+ notify: true,
+ started: "2024-06-10T16:00:00.000Z",
+ createdAt: "2024-06-10T16:00:00.000Z",
+ },
+ {
+ id: "in_update_004",
+ message:
+ "The issue has been fully resolved. Error rates are back to normal.",
+ messageHtml:
+ "<p>The issue has been fully resolved. Error rates are back to normal.</p>",
+ status: "RESOLVED",
+ notify: true,
+ started: "2024-06-10T16:45:00.000Z",
+ createdAt: "2024-06-10T16:45:00.000Z",
+ },
+ ],
+ components: [{ id: "in_comp_001", name: "API Gateway" }],
+ },
+ {
+ id: "in_incident_002",
+ name: "Dashboard Slow Response Times",
+ status: "IDENTIFIED",
+ started: "2024-06-11T09:00:00.000Z",
+ resolved: null,
+ updates: [
+ {
+ id: "in_update_005",
+ message:
+ "We are investigating reports of slow response times on the Dashboard.",
+ messageHtml:
+ "<p>We are investigating reports of slow response times on the Dashboard.</p>",
+ status: "INVESTIGATING",
+ notify: true,
+ started: "2024-06-11T09:00:00.000Z",
+ createdAt: "2024-06-11T09:00:00.000Z",
+ },
+ {
+ id: "in_update_006",
+ message:
+ "The issue has been traced to a slow database query affecting the main dashboard view.",
+ messageHtml:
+ "<p>The issue has been traced to a slow database query affecting the main dashboard view.</p>",
+ status: "IDENTIFIED",
+ notify: true,
+ started: "2024-06-11T09:45:00.000Z",
+ createdAt: "2024-06-11T09:45:00.000Z",
+ },
+ ],
+ components: [{ id: "in_comp_003", name: "Dashboard" }],
+ },
+];
+
+export const MOCK_MAINTENANCES: InstatusMaintenance[] = [
+ {
+ id: "in_maint_001",
+ name: "Scheduled Database Maintenance",
+ status: "NOTSTARTEDYET",
+ start: "2024-06-20T02:00:00.000Z",
+ duration: 240,
+ updates: [
+ {
+ id: "in_maint_update_001",
+ message:
+ "We will be performing scheduled database maintenance. Some services may experience brief interruptions.",
+ messageHtml:
+ "<p>We will be performing scheduled database maintenance. Some services may experience brief interruptions.</p>",
+ status: "NOTSTARTEDYET",
+ notify: true,
+ started: "2024-06-12T10:00:00.000Z",
+ },
+ ],
+ components: [
+ { id: "in_comp_001", name: "API Gateway" },
+ { id: "in_comp_002", name: "Authentication Service" },
+ ],
+ },
+ {
+ id: "in_maint_002",
+ name: "CDN Cache Purge",
+ status: "COMPLETED",
+ start: "2024-06-15T03:00:00.000Z",
+ duration: 30,
+ updates: [
+ {
+ id: "in_maint_update_002",
+ message: "Starting CDN cache purge.",
+ messageHtml: "<p>Starting CDN cache purge.</p>",
+ status: "INPROGRESS",
+ notify: true,
+ started: "2024-06-15T03:00:00.000Z",
+ },
+ {
+ id: "in_maint_update_003",
+ message: "Cache purge completed successfully.",
+ messageHtml: "<p>Cache purge completed successfully.</p>",
+ status: "COMPLETED",
+ notify: true,
+ started: "2024-06-15T03:25:00.000Z",
+ },
+ ],
+ components: [{ id: "in_comp_004", name: "CDN" }],
+ },
+];
+
+export const MOCK_SUBSCRIBERS: InstatusSubscriber[] = [
+ {
+ id: "in_sub_001",
+ email: "[email protected]",
+ phone: null,
+ webhook: null,
+ confirmed: true,
+ all: true,
+ components: [],
+ },
+ {
+ id: "in_sub_002",
+ email: "[email protected]",
+ phone: null,
+ webhook: null,
+ confirmed: true,
+ all: false,
+ components: [
+ { id: "in_comp_001", name: "API Gateway" },
+ { id: "in_comp_003", name: "Dashboard" },
+ ],
+ },
+ {
+ id: "in_sub_003",
+ email: null,
+ phone: "+15551234567",
+ webhook: null,
+ confirmed: true,
+ all: true,
+ components: [],
+ },
+ {
+ id: "in_sub_004",
+ email: null,
+ phone: null,
+ webhook: "https://hooks.acmecorp.com/instatus",
+ confirmed: true,
+ all: true,
+ components: [],
+ },
+ {
+ id: "in_sub_005",
+ email: null,
+ phone: null,
+ webhook: null,
+ confirmed: true,
+ all: true,
+ components: [],
+ },
+];
diff --git a/packages/importers/src/providers/instatus/index.ts b/packages/importers/src/providers/instatus/index.ts
new file mode 100644
index 000000000..0cdf159de
--- /dev/null
+++ b/packages/importers/src/providers/instatus/index.ts
@@ -0,0 +1,22 @@
+export { createInstatusClient } from "./client";
+export type { InstatusClient } from "./client";
+export type {
+ InstatusComponent,
+ InstatusIncident,
+ InstatusIncidentUpdate,
+ InstatusMaintenance,
+ InstatusMaintenanceUpdate,
+ InstatusPage,
+ InstatusSubscriber,
+} from "./api-types";
+export {
+ InstatusComponentSchema,
+ InstatusIncidentSchema,
+ InstatusIncidentUpdateSchema,
+ InstatusMaintenanceSchema,
+ InstatusMaintenanceUpdateSchema,
+ InstatusPageSchema,
+ InstatusSubscriberSchema,
+} from "./api-types";
+export { createInstatusProvider } from "./provider";
+export type { InstatusImportConfig } from "./provider";
diff --git a/packages/importers/src/providers/instatus/mapper.test.ts b/packages/importers/src/providers/instatus/mapper.test.ts
new file mode 100644
index 000000000..f9e8dc30b
--- /dev/null
+++ b/packages/importers/src/providers/instatus/mapper.test.ts
@@ -0,0 +1,224 @@
+import { describe, expect, it } from "bun:test";
+import {
+ MOCK_COMPONENTS,
+ MOCK_INCIDENTS,
+ MOCK_MAINTENANCES,
+ MOCK_PAGES,
+ MOCK_SUBSCRIBERS,
+} from "./fixtures";
+import {
+ mapComponent,
+ mapComponentGroup,
+ mapIncidentStatus,
+ mapIncidentToStatusReport,
+ mapMaintenanceToMaintenance,
+ mapPage,
+ mapSubscriber,
+ partitionComponents,
+} 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: "",
+ slug: "acmecorp",
+ customDomain: "status.acmecorp.com",
+ published: true,
+ icon: "",
+ });
+ });
+
+ it("handles null customDomain", () => {
+ const page = { ...MOCK_PAGES[0], customDomain: null };
+ const result = mapPage(page, 1);
+ expect(result.customDomain).toBe("");
+ });
+});
+
+describe("partitionComponents", () => {
+ it("separates groups from regular components", () => {
+ const result = partitionComponents(MOCK_COMPONENTS);
+ expect(result.groups).toHaveLength(1);
+ expect(result.groups[0].id).toBe("in_comp_group_001");
+ expect(result.components).toHaveLength(4);
+ expect(result.warnings).toHaveLength(0);
+ });
+
+ it("returns empty groups when no components reference a group", () => {
+ const noGroupComponents = MOCK_COMPONENTS.filter((c) => c.group === null);
+ const result = partitionComponents(noGroupComponents);
+ expect(result.groups).toHaveLength(0);
+ expect(result.components).toHaveLength(noGroupComponents.length);
+ expect(result.warnings).toHaveLength(0);
+ });
+
+ it("creates synthetic group with warning when group ID not found", () => {
+ const components = [
+ {
+ id: "comp_1",
+ name: "Orphaned Component",
+ description: null,
+ status: "OPERATIONAL" as const,
+ order: 0,
+ group: "missing_group_id",
+ showUptime: true,
+ grouped: true,
+ },
+ ];
+ const result = partitionComponents(components);
+ expect(result.groups).toHaveLength(1);
+ expect(result.groups[0].id).toBe("missing_group_id");
+ expect(result.groups[0].name).toBe("missing_group_id");
+ expect(result.components).toHaveLength(1);
+ expect(result.warnings).toHaveLength(1);
+ expect(result.warnings[0]).toContain("missing_group_id");
+ });
+});
+
+describe("mapComponentGroup", () => {
+ it("maps a group component", () => {
+ const group = MOCK_COMPONENTS[0]; // in_comp_group_001
+ const result = mapComponentGroup(group, 1, 10);
+ expect(result).toEqual({
+ workspaceId: 1,
+ pageId: 10,
+ name: "Core Services",
+ });
+ });
+});
+
+describe("mapComponent", () => {
+ it("maps a component with all fields", () => {
+ const result = mapComponent(MOCK_COMPONENTS[1], 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 order from component order field", () => {
+ const result = mapComponent(MOCK_COMPONENTS[3], 1, 10);
+ expect(result.order).toBe(3);
+ });
+});
+
+describe("mapIncidentStatus", () => {
+ it.each([
+ ["INVESTIGATING", "investigating"],
+ ["IDENTIFIED", "identified"],
+ ["MONITORING", "monitoring"],
+ ["RESOLVED", "resolved"],
+ ] as const)("maps %s to %s", (input, expected) => {
+ expect(mapIncidentStatus(input)).toBe(expected);
+ });
+
+ it("defaults to investigating for unknown status", () => {
+ expect(mapIncidentStatus("UNKNOWN")).toBe("investigating");
+ });
+});
+
+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(["in_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(["in_comp_003"]);
+ });
+});
+
+describe("mapMaintenanceToMaintenance", () => {
+ it("maps a maintenance with duration", () => {
+ const result = mapMaintenanceToMaintenance(MOCK_MAINTENANCES[0], 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")); // +240 minutes
+ expect(result.message).toContain("scheduled database maintenance");
+ });
+
+ it("uses same from and to when duration is null, without aliasing", () => {
+ const m = { ...MOCK_MAINTENANCES[0], duration: null };
+ const result = mapMaintenanceToMaintenance(m, 1, 10);
+ expect(result.from).toEqual(result.to);
+ expect(result.from).not.toBe(result.to);
+ });
+
+ it("maps maintenance with multiple updates", () => {
+ const result = mapMaintenanceToMaintenance(MOCK_MAINTENANCES[1], 1, 10);
+ expect(result.message).toContain("Starting CDN cache purge");
+ expect(result.message).toContain("Cache purge completed successfully");
+ });
+});
+
+describe("mapSubscriber", () => {
+ it("maps email subscriber with all components", () => {
+ const result = mapSubscriber(MOCK_SUBSCRIBERS[0], 10);
+ expect(result).toEqual({
+ email: "[email protected]",
+ pageId: 10,
+ confirmed: true,
+ sourceComponentIds: [],
+ });
+ });
+
+ it("maps email subscriber with specific components", () => {
+ const result = mapSubscriber(MOCK_SUBSCRIBERS[1], 10);
+ expect(result).toEqual({
+ email: "[email protected]",
+ pageId: 10,
+ confirmed: true,
+ sourceComponentIds: ["in_comp_001", "in_comp_003"],
+ });
+ });
+
+ it("maps unconfirmed subscriber with confirmed: false", () => {
+ const unconfirmed = { ...MOCK_SUBSCRIBERS[0], confirmed: false };
+ const result = mapSubscriber(unconfirmed, 10);
+ expect(result).toEqual({
+ email: "[email protected]",
+ pageId: 10,
+ confirmed: false,
+ sourceComponentIds: [],
+ });
+ });
+
+ it("extracts component IDs from object references", () => {
+ const result = mapSubscriber(MOCK_SUBSCRIBERS[1], 10);
+ expect(result?.sourceComponentIds).toEqual(["in_comp_001", "in_comp_003"]);
+ });
+
+ it("returns null for phone subscriber", () => {
+ expect(mapSubscriber(MOCK_SUBSCRIBERS[2], 10)).toBeNull();
+ });
+
+ it("returns null for webhook subscriber", () => {
+ expect(mapSubscriber(MOCK_SUBSCRIBERS[3], 10)).toBeNull();
+ });
+
+ it("returns null for subscriber with no email/phone/webhook", () => {
+ expect(mapSubscriber(MOCK_SUBSCRIBERS[4], 10)).toBeNull();
+ });
+});
diff --git a/packages/importers/src/providers/instatus/mapper.ts b/packages/importers/src/providers/instatus/mapper.ts
new file mode 100644
index 000000000..cb3a3c7a2
--- /dev/null
+++ b/packages/importers/src/providers/instatus/mapper.ts
@@ -0,0 +1,201 @@
+import type {
+ InstatusComponent,
+ InstatusIncident,
+ InstatusMaintenance,
+ InstatusPage,
+ InstatusSubscriber,
+} from "./api-types";
+
+export type StatusReportStatus =
+ | "investigating"
+ | "identified"
+ | "monitoring"
+ | "resolved";
+
+export function mapPage(page: InstatusPage, workspaceId: number) {
+ return {
+ workspaceId,
+ title: page.name,
+ description: "",
+ slug: page.subdomain,
+ customDomain: page.customDomain ?? "",
+ published: true,
+ icon: "",
+ };
+}
+
+export function partitionComponents(components: InstatusComponent[]): {
+ groups: InstatusComponent[];
+ components: InstatusComponent[];
+ warnings: string[];
+} {
+ const groupIds = new Set<string>();
+ for (const c of components) {
+ if (c.group) {
+ groupIds.add(c.group);
+ }
+ }
+
+ const componentById = new Map(components.map((c) => [c.id, c]));
+ const groups: InstatusComponent[] = [];
+ const regular: InstatusComponent[] = [];
+ const warnings: string[] = [];
+
+ // Collect groups: real components that are referenced as groups
+ for (const groupId of Array.from(groupIds)) {
+ const groupComponent = componentById.get(groupId);
+ if (groupComponent) {
+ groups.push(groupComponent);
+ } else {
+ // Group ID referenced but not found in component list — create synthetic group
+ groups.push({
+ id: groupId,
+ name: groupId,
+ description: null,
+ status: "OPERATIONAL",
+ order: 0,
+ group: null,
+ showUptime: false,
+ grouped: false,
+ });
+ warnings.push(
+ `Component group "${groupId}" referenced but not found in component list. Using ID as name.`,
+ );
+ }
+ }
+
+ // Collect regular components (not used as groups)
+ for (const c of components) {
+ if (!groupIds.has(c.id)) {
+ regular.push(c);
+ }
+ }
+
+ return { groups, components: regular, warnings };
+}
+
+export function mapComponentGroup(
+ group: InstatusComponent,
+ workspaceId: number,
+ pageId?: number,
+) {
+ return {
+ workspaceId,
+ pageId,
+ name: group.name,
+ };
+}
+
+export function mapComponent(
+ component: InstatusComponent,
+ workspaceId: number,
+ pageId?: number,
+) {
+ return {
+ workspaceId,
+ pageId,
+ type: "static" as const,
+ monitorId: null,
+ name: component.name,
+ description: component.description ?? null,
+ order: component.order ?? 0,
+ };
+}
+
+export function mapIncidentStatus(status: string): StatusReportStatus {
+ const lower = status.toLowerCase();
+ if (
+ lower === "investigating" ||
+ lower === "identified" ||
+ lower === "monitoring" ||
+ lower === "resolved"
+ ) {
+ return lower;
+ }
+ return "investigating";
+}
+
+export function mapIncidentToStatusReport(
+ incident: InstatusIncident,
+ workspaceId: number,
+ pageId?: number,
+) {
+ const updates = [...(incident.updates ?? [])].sort(
+ (a, b) => new Date(a.started).getTime() - new Date(b.started).getTime(),
+ );
+
+ const mappedUpdates = updates.map((u) => ({
+ status: mapIncidentStatus(u.status),
+ message: u.message ?? "",
+ date: new Date(u.started),
+ }));
+
+ const lastUpdate = updates[updates.length - 1];
+ const reportStatus = lastUpdate
+ ? mapIncidentStatus(lastUpdate.status)
+ : "investigating";
+
+ const sourceComponentIds: string[] = (incident.components ?? []).map(
+ (c) => c.id,
+ );
+
+ return {
+ report: {
+ title: incident.name,
+ status: reportStatus,
+ workspaceId,
+ pageId,
+ },
+ updates: mappedUpdates,
+ sourceComponentIds,
+ };
+}
+
+export function mapMaintenanceToMaintenance(
+ m: InstatusMaintenance,
+ workspaceId: number,
+ pageId?: number,
+) {
+ const updates = m.updates ?? [];
+ const message = updates
+ .map((u) => u.message ?? "")
+ .filter(Boolean)
+ .join("\n");
+
+ const from = new Date(m.start);
+ const duration = m.duration ?? 0;
+ const to =
+ duration > 0
+ ? new Date(from.getTime() + duration * 60_000)
+ : new Date(from);
+
+ return {
+ title: m.name,
+ message,
+ from,
+ to,
+ workspaceId,
+ pageId,
+ };
+}
+
+export function mapSubscriber(
+ subscriber: InstatusSubscriber,
+ pageId?: number,
+): {
+ email: string;
+ pageId?: number;
+ confirmed: boolean;
+ sourceComponentIds: string[];
+} | null {
+ if (!subscriber.email) return null;
+
+ return {
+ email: subscriber.email,
+ pageId,
+ confirmed: subscriber.confirmed ?? false,
+ sourceComponentIds: subscriber.all
+ ? []
+ : (subscriber.components ?? []).map((c) => c.id),
+ };
+}
diff --git a/packages/importers/src/providers/instatus/provider.test.ts b/packages/importers/src/providers/instatus/provider.test.ts
new file mode 100644
index 000000000..e35ff7635
--- /dev/null
+++ b/packages/importers/src/providers/instatus/provider.test.ts
@@ -0,0 +1,162 @@
+import { afterAll, beforeAll, describe, expect, it } from "bun:test";
+import {
+ MOCK_COMPONENTS,
+ MOCK_INCIDENTS,
+ MOCK_MAINTENANCES,
+ MOCK_PAGES,
+ MOCK_SUBSCRIBERS,
+} from "./fixtures";
+import { type InstatusImportConfig, createInstatusProvider } 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.match(/\/v2\/pages(\?|$)/)) {
+ const pageParam = new URL(url).searchParams.get("page");
+ return Promise.resolve(
+ Response.json(pageParam === "1" || !pageParam ? MOCK_PAGES : []),
+ );
+ }
+ if (url.match(/\/v2\/[^/]+\/components(\?|$)/)) {
+ const pageParam = new URL(url).searchParams.get("page");
+ return Promise.resolve(
+ Response.json(pageParam === "1" || !pageParam ? MOCK_COMPONENTS : []),
+ );
+ }
+ if (url.match(/\/v1\/[^/]+\/incidents(\?|$)/)) {
+ const pageParam = new URL(url).searchParams.get("page");
+ return Promise.resolve(
+ Response.json(pageParam === "1" || !pageParam ? MOCK_INCIDENTS : []),
+ );
+ }
+ if (url.match(/\/v2\/[^/]+\/maintenances(\?|$)/)) {
+ const pageParam = new URL(url).searchParams.get("page");
+ return Promise.resolve(
+ Response.json(pageParam === "1" || !pageParam ? MOCK_MAINTENANCES : []),
+ );
+ }
+ if (url.match(/\/v2\/[^/]+\/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("InstatusImportProvider", () => {
+ const originalFetch = globalThis.fetch;
+
+ beforeAll(() => {
+ globalThis.fetch = createMockFetch() as typeof fetch;
+ });
+
+ afterAll(() => {
+ globalThis.fetch = originalFetch;
+ });
+
+ it("has name 'instatus'", () => {
+ const provider = createInstatusProvider();
+ expect(provider.name).toBe("instatus");
+ });
+
+ it("validate returns valid for working key", async () => {
+ const provider = createInstatusProvider();
+ const result = await provider.validate({
+ apiKey: "test-key",
+ workspaceId: 1,
+ });
+ expect(result).toEqual({ valid: true });
+ });
+
+ it("validate returns user-friendly error for 401", async () => {
+ const prev = globalThis.fetch;
+ globalThis.fetch = createMockFetch({ failAuth: true }) as typeof fetch;
+
+ const provider = createInstatusProvider();
+ const result = await provider.validate({
+ apiKey: "bad-key",
+ workspaceId: 1,
+ });
+ expect(result.valid).toBe(false);
+ expect(result.error).toContain("Invalid Instatus API key");
+ expect(result.error).toContain("instatus.com/app/developer");
+
+ globalThis.fetch = prev;
+ });
+
+ it("run with dryRun returns correct phase counts", async () => {
+ const provider = createInstatusProvider();
+ const config: InstatusImportConfig = {
+ apiKey: "test-key",
+ workspaceId: 1,
+ dryRun: true,
+ };
+
+ const summary = await provider.run(config);
+
+ expect(summary.provider).toBe("instatus");
+ 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 (in_comp_group_001 is referenced by other components)
+ expect(findPhase("componentGroups")?.resources).toHaveLength(1);
+
+ // 4 regular components (group component excluded)
+ expect(findPhase("components")?.resources).toHaveLength(4);
+
+ // 2 incidents
+ expect(findPhase("incidents")?.resources).toHaveLength(2);
+
+ // 2 maintenances (from dedicated endpoint)
+ expect(findPhase("maintenances")?.resources).toHaveLength(2);
+
+ // 2 email subscribers (phone, webhook, and empty all skipped)
+ expect(findPhase("subscribers")?.resources).toHaveLength(2);
+ });
+
+ it("filters by instatusPageId when provided", async () => {
+ const provider = createInstatusProvider();
+
+ // Filter by matching page ID — should return data
+ const matching = await provider.run({
+ apiKey: "test-key",
+ workspaceId: 1,
+ dryRun: true,
+ instatusPageId: "in_page_001",
+ });
+ const findPhase = (name: string) =>
+ matching.phases.find((p) => p.phase === name);
+ expect(findPhase("page")?.resources).toHaveLength(1);
+
+ // Filter by non-existent page ID — should return failed with error
+ const nonMatching = await provider.run({
+ apiKey: "test-key",
+ workspaceId: 1,
+ dryRun: true,
+ instatusPageId: "nonexistent",
+ });
+ expect(nonMatching.status).toBe("failed");
+ expect(nonMatching.errors).toHaveLength(1);
+ expect(nonMatching.errors[0]).toContain("nonexistent");
+ });
+});
diff --git a/packages/importers/src/providers/instatus/provider.ts b/packages/importers/src/providers/instatus/provider.ts
new file mode 100644
index 000000000..f69f9d635
--- /dev/null
+++ b/packages/importers/src/providers/instatus/provider.ts
@@ -0,0 +1,198 @@
+import type {
+ ImportConfig,
+ ImportProvider,
+ PhaseResult,
+ ResourceResult,
+} from "../../types";
+import { createInstatusClient } from "./client";
+import {
+ mapComponent,
+ mapComponentGroup,
+ mapIncidentToStatusReport,
+ mapMaintenanceToMaintenance,
+ mapPage,
+ mapSubscriber,
+ partitionComponents,
+} from "./mapper";
+
+export interface InstatusImportConfig extends ImportConfig {
+ instatusPageId?: string;
+}
+
+export function createInstatusProvider(): ImportProvider<InstatusImportConfig> {
+ return {
+ name: "instatus",
+
+ validate: async (config) => {
+ try {
+ const client = createInstatusClient(config.apiKey);
+ await client.getPages();
+ return { valid: true };
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ if (message.includes("401")) {
+ return {
+ valid: false,
+ error:
+ "Invalid Instatus API key. You can find your key at instatus.com/app/developer.",
+ };
+ }
+ return { valid: false, error: message };
+ }
+ },
+
+ run: async (config) => {
+ const startedAt = new Date();
+ const client = createInstatusClient(config.apiKey);
+ const phases: PhaseResult[] = [];
+
+ let pages = await client.getPages();
+ if (config.instatusPageId) {
+ pages = pages.filter((p) => p.id === config.instatusPageId);
+ if (pages.length === 0) {
+ return {
+ provider: "instatus",
+ status: "failed",
+ startedAt,
+ completedAt: new Date(),
+ phases: [],
+ errors: [
+ `No page found with ID "${config.instatusPageId}". Check the page ID and try again.`,
+ ],
+ };
+ }
+ }
+
+ let skippedSubscribers = 0;
+ const allPartitionWarnings: string[] = [];
+
+ for (const pg of pages) {
+ const [allComponents, incidents, maintenances, subscribers] =
+ await Promise.all([
+ client.getComponents(pg.id),
+ client.getIncidents(pg.id),
+ client.getMaintenances(pg.id),
+ client.getSubscribers(pg.id),
+ ]);
+
+ const { groups, components, warnings } =
+ partitionComponents(allComponents);
+ allPartitionWarnings.push(...warnings);
+
+ // Page phase
+ const mappedPage = mapPage(pg, config.workspaceId);
+ phases.push({
+ phase: "page",
+ status: "completed",
+ resources: [
+ {
+ sourceId: pg.id,
+ name: pg.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,
+ },
+ }));
+ phases.push({
+ phase: "components",
+ status: "completed",
+ resources: componentResources,
+ });
+
+ // Incidents phase (status reports)
+ const incidentResources: ResourceResult[] = incidents.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[] = maintenances.map(
+ (m) => ({
+ sourceId: m.id,
+ name: m.name,
+ status: "created" as const,
+ data: {
+ ...mapMaintenanceToMaintenance(m, config.workspaceId, pageId),
+ sourceComponentIds: (m.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.id,
+ status: "created",
+ data: mapped,
+ });
+ } else {
+ skippedSubscribers++;
+ }
+ }
+ phases.push({
+ phase: "subscribers",
+ status: "completed",
+ resources: subscriberResources,
+ });
+ }
+
+ const errors: string[] = [...allPartitionWarnings];
+ if (skippedSubscribers > 0) {
+ errors.push(
+ `Only email subscribers are supported. ${skippedSubscribers} non-email subscriber${skippedSubscribers === 1 ? " was" : "s were"} skipped.`,
+ );
+ }
+
+ return {
+ provider: "instatus",
+ status: "completed",
+ startedAt,
+ completedAt: new Date(),
+ phases,
+ errors,
+ };
+ },
+ };
+}
diff --git a/packages/importers/src/providers/statuspage/mapper.test.ts b/packages/importers/src/providers/statuspage/mapper.test.ts
index 450d8ee02..98a5d6370 100644
--- a/packages/importers/src/providers/statuspage/mapper.test.ts
+++ b/packages/importers/src/providers/statuspage/mapper.test.ts
@@ -143,6 +143,7 @@ describe("mapSubscriber", () => {
expect(result).toEqual({
pageId: 10,
+ confirmed: true,
sourceComponentIds: [],
});
});
@@ -152,6 +153,7 @@ describe("mapSubscriber", () => {
expect(result).toEqual({
pageId: 10,
+ confirmed: true,
sourceComponentIds: ["sp_comp_001", "sp_comp_003"],
});
});
diff --git a/packages/importers/src/providers/statuspage/mapper.ts b/packages/importers/src/providers/statuspage/mapper.ts
index 22873de9e..e3609c0bd 100644
--- a/packages/importers/src/providers/statuspage/mapper.ts
+++ b/packages/importers/src/providers/statuspage/mapper.ts
@@ -146,6 +146,7 @@ export function mapSubscriber(
): {
email: string;
pageId?: number;
+ confirmed: boolean;
sourceComponentIds: string[];
} | null {
if (subscriber.mode !== "email") return null;
@@ -153,6 +154,7 @@ export function mapSubscriber(
return {
email: subscriber.email ?? "",
pageId,
+ confirmed: true,
sourceComponentIds: subscriber.components ?? [],
};
}