Skip to content

Open-source status page, incident response and uptime monitoring

refactor: share one checker payload builder and drop dead code (#2992)

Maximilian Kaskece51ab0c64f6
diff --git a/apps/dashboard/src/components/chart/chart-bar-uptime-light.tsx b/apps/dashboard/src/components/chart/chart-bar-uptime-light.tsx
deleted file mode 100644
index 51fa98764..000000000
--- a/apps/dashboard/src/components/chart/chart-bar-uptime-light.tsx
+++ /dev/null
@@ -1,97 +0,0 @@
-"use client";
-
-import type { Region } from "@openstatus/db/src/schema/constants";
-import {
- type ChartConfig,
- ChartContainer,
- ChartTooltip,
- ChartTooltipContent,
-} from "@openstatus/ui/components/ui/chart";
-import { Skeleton } from "@openstatus/ui/components/ui/skeleton";
-import { useQuery } from "@tanstack/react-query";
-import { Bar, BarChart, XAxis } from "recharts";
-
-import { TableCellEmpty } from "@/components/data-table/table-cell-empty";
-import { mapUptime } from "@/data/metrics.client";
-import { formatDateTime } from "@/lib/formatter";
-import { useTRPC } from "@/lib/trpc/client";
-// import { startOfDay, subDays } from "date-fns";
-
-const chartConfig = {
- ok: {
- label: "Success",
- color: "var(--color-success)",
- },
- degraded: {
- label: "Degraded",
- color: "var(--color-warning)",
- },
- error: {
- label: "Error",
- color: "var(--color-destructive)",
- },
-} satisfies ChartConfig;
-
-export function ChartBarUptimeLight({
- monitorId,
- type,
- regions,
-}: {
- monitorId: string;
- type: "http" | "tcp" | "dns" | "icmp" | "grpc";
- regions?: Region[];
-}) {
- const trpc = useTRPC();
-
- const { data: uptime, isLoading } = useQuery(
- trpc.tinybird.uptime.queryOptions({
- interval: 60 * 24,
- // fromDate: startOfDay(subDays(new Date(), 7)).toISOString(), // FIXME:
- period: "7d",
- monitorId,
- regions,
- type,
- }),
- );
-
- if (isLoading) {
- return <Skeleton className="my-auto h-5 w-full" />;
- }
-
- const refinedUptime = uptime ? mapUptime(uptime) : [];
-
- if (refinedUptime.length === 0) {
- return <TableCellEmpty>No data</TableCellEmpty>;
- }
-
- return (
- <ChartContainer config={chartConfig} className="h-[28px] w-full">
- <BarChart accessibilityLayer data={refinedUptime} barCategoryGap={1}>
- <ChartTooltip
- cursor={false}
- allowEscapeViewBox={{ x: false, y: true }}
- wrapperStyle={{ zIndex: 1 }}
- content={
- <ChartTooltipContent
- indicator="dot"
- labelFormatter={(_, payload) =>
- formatDateTime(new Date(payload[0]?.payload.interval))
- }
- />
- }
- />
- <Bar dataKey="ok" stackId="a" fill="var(--color-ok)" />
- <Bar dataKey="error" stackId="a" fill="var(--color-error)" />
- <Bar dataKey="degraded" stackId="a" fill="var(--color-degraded)" />
- <XAxis
- dataKey="interval"
- tickLine={false}
- tickMargin={8}
- minTickGap={10}
- axisLine={false}
- hide
- />
- </BarChart>
- </ChartContainer>
- );
-}
diff --git a/apps/dashboard/src/components/common/wheel-picker.tsx b/apps/dashboard/src/components/common/wheel-picker.tsx
deleted file mode 100644
index 681234d86..000000000
--- a/apps/dashboard/src/components/common/wheel-picker.tsx
+++ /dev/null
@@ -1,295 +0,0 @@
-"use client";
-
-import * as React from "react";
-
-import { cn } from "@/lib/utils";
-
-// ---------------------------------------------------------------------------------------------------------------------
-// Context -------------------------------------------------------------------------------------------------------------
-// ---------------------------------------------------------------------------------------------------------------------
-
-interface WheelPickerContextValue {
- items: string[];
- currentIndex: number;
- onIndexChange: (index: number) => void;
- theta: number; // angle between two items
- radius: number; // translateZ distance
- count: number; // items including placeholders
-}
-
-const WheelPickerContext = React.createContext<WheelPickerContextValue | null>(
- null,
-);
-
-const useWheelPickerContext = () => {
- const ctx = React.useContext(WheelPickerContext);
- if (!ctx) {
- throw new Error(
- "[WheelPicker] sub component must be rendered within <WheelPicker /> root",
- );
- }
- return ctx;
-};
-
-// ---------------------------------------------------------------------------------------------------------------------
-// WheelPicker (Root / Provider) ---------------------------------------------------------------------------------------
-// ---------------------------------------------------------------------------------------------------------------------
-
-export interface WheelPickerProps extends React.HTMLAttributes<HTMLDivElement> {
- items: string[];
- /** 0-based index of the currently selected item. Defaults to 0. */
- currentIndex: number;
- /** Callback that is invoked with the currently selected item (string) whenever the selection changes */
- onIndexChange: (index: number) => void;
- /** Radius (in `px`) of the carousel – tweak to fit line height of text (Default: 28) */
- radius?: number;
-}
-
-const WheelPicker = React.forwardRef<HTMLDivElement, WheelPickerProps>(
- (
- {
- items,
- currentIndex,
- onIndexChange,
- radius: radiusProp = 28,
- className,
- children,
- ...props
- },
- ref,
- ) => {
- // internal render count includes two placeholders at start & end
- const count = items.length + 2;
- const theta = (2 * Math.PI) / count;
-
- const contextValue = React.useMemo<WheelPickerContextValue>(
- () => ({
- items,
- currentIndex,
- onIndexChange,
- theta,
- radius: radiusProp,
- count,
- }),
- [items, currentIndex, onIndexChange, theta, radiusProp, count],
- );
-
- return (
- <WheelPickerContext.Provider value={contextValue}>
- <div ref={ref} className={className} {...props}>
- {children}
- </div>
- </WheelPickerContext.Provider>
- );
- },
-);
-WheelPicker.displayName = "WheelPicker";
-
-// ---------------------------------------------------------------------------------------------------------------------
-// WheelPickerSelect ---------------------------------------------------------------------------------------------------
-// ---------------------------------------------------------------------------------------------------------------------
-
-export type WheelPickerSelectProps = React.HTMLAttributes<HTMLDivElement>;
-
-const WheelPickerSelect = React.forwardRef<
- HTMLDivElement,
- WheelPickerSelectProps
->(({ className, children, ...props }, ref) => {
- const { items, currentIndex, onIndexChange } = useWheelPickerContext();
-
- const moveBy = React.useCallback(
- (delta: number) => {
- const itemsLength = items.length;
- let newIndex = currentIndex + delta;
-
- // Handle wrapping
- if (newIndex < 0) {
- newIndex = itemsLength - 1;
- } else if (newIndex >= itemsLength) {
- newIndex = 0;
- }
-
- onIndexChange(newIndex);
- },
- [currentIndex, items.length, onIndexChange],
- );
-
- const handleKeyDown = React.useCallback(
- (e: React.KeyboardEvent<HTMLDivElement>) => {
- switch (e.key) {
- case "ArrowUp":
- case "ArrowLeft":
- e.preventDefault();
- moveBy(1);
- break;
- case "ArrowDown":
- case "ArrowRight":
- e.preventDefault();
- moveBy(-1);
- break;
- case "Home":
- e.preventDefault();
- onIndexChange(0);
- break;
- case "End":
- e.preventDefault();
- onIndexChange(items.length - 1);
- break;
- }
- },
- [moveBy, onIndexChange, items.length],
- );
-
- return (
- <div
- ref={ref}
- data-slot="wheel-select"
- role="listbox"
- aria-label="Select option"
- aria-activedescendant={`wheel-option-${currentIndex}`}
- tabIndex={0}
- className={cn(
- "focus:border-ring focus:ring-ring/50 relative h-6 w-full rounded-md border border-transparent text-left focus:ring-2 focus:outline-none",
- className,
- )}
- onKeyDown={handleKeyDown}
- {...props}
- >
- {children}
- </div>
- );
-});
-WheelPickerSelect.displayName = "WheelPickerSelect";
-
-// ---------------------------------------------------------------------------------------------------------------------
-// WheelPickerOptions --------------------------------------------------------------------------------------------------
-// ---------------------------------------------------------------------------------------------------------------------
-
-export type WheelPickerOptionsProps = React.HTMLAttributes<HTMLDivElement>;
-
-const WheelPickerOptions = React.forwardRef<
- HTMLDivElement,
- WheelPickerOptionsProps
->(({ className, ...props }, ref) => {
- const { items, currentIndex, onIndexChange, theta, radius } =
- useWheelPickerContext();
-
- return (
- <div
- ref={ref}
- data-slot="wheel-options"
- className={cn(
- "h-full w-full rounded-md [perspective:1000px] [transform-style:preserve-3d]",
- className,
- )}
- {...props}
- >
- <div
- className="relative h-full w-full transition-transform duration-500 ease-out [transform-style:preserve-3d]"
- style={{
- transform: `translateZ(-${radius}px) rotateX(${
- -(currentIndex + 1) * theta
- }rad)`,
- }}
- >
- {/* First placeholder */}
- <WheelPickerEmpty position="first" />
-
- {/* Real items */}
- {items.map((item, idx) => {
- // Render index = item index + 1 (accounting for first placeholder)
- const renderIdx = idx + 1;
- const angle = theta * renderIdx;
- const isSelected = idx === currentIndex;
- return (
- <div
- key={item}
- data-slot="wheel-option"
- id={`wheel-option-${idx}`}
- role="option"
- aria-selected={isSelected}
- className={cn(
- "absolute inset-0 flex cursor-pointer items-center justify-start transition-transform duration-500 ease-out select-none [backface-visibility:hidden]",
- )}
- style={{
- transform: `rotateX(${angle}rad) translateZ(${radius}px)`,
- transformStyle: "preserve-3d",
- }}
- onClick={(e) => {
- if (!isSelected) {
- e.preventDefault();
- e.stopPropagation();
- onIndexChange(idx);
- }
- }}
- >
- <span
- className={cn(
- "text-xs transition-colors",
- isSelected ? "text-foreground" : "text-muted-foreground/70",
- )}
- >
- {item}
- </span>
- </div>
- );
- })}
-
- {/* Last placeholder */}
- <WheelPickerEmpty position="last" />
- </div>
- </div>
- );
-});
-WheelPickerOptions.displayName = "WheelPickerOptions";
-
-// ---------------------------------------------------------------------------------------------------------------------
-// WheelPickerEmpty (placeholders) -------------------------------------------------------------------------------------
-// ---------------------------------------------------------------------------------------------------------------------
-
-type PlaceholderPosition = "first" | "last";
-
-export interface WheelPickerEmptyProps extends React.HTMLAttributes<HTMLDivElement> {
- position: PlaceholderPosition;
-}
-
-const WheelPickerEmpty = React.forwardRef<
- HTMLDivElement,
- WheelPickerEmptyProps
->(({ position, className, ...props }, ref) => {
- const { theta, radius, count, currentIndex } = useWheelPickerContext();
-
- const renderIdx = position === "first" ? 0 : count - 1;
- const angle = theta * renderIdx;
-
- return (
- <div
- ref={ref}
- data-slot="wheel-empty"
- id={`wheel-option-${renderIdx}`}
- role="option"
- aria-selected={currentIndex === renderIdx}
- aria-disabled
- className={cn(
- "absolute inset-0 select-none [backface-visibility:hidden]",
- className,
- )}
- style={{
- transform: `rotateX(${angle}rad) translateZ(${radius}px)`,
- transformStyle: "preserve-3d",
- }}
- onClick={(e) => {
- e.preventDefault();
- e.stopPropagation();
- }}
- {...props}
- />
- );
-});
-WheelPickerEmpty.displayName = "WheelPickerEmpty";
-
-// ---------------------------------------------------------------------------------------------------------------------
-// Exports -------------------------------------------------------------------------------------------------------------
-// ---------------------------------------------------------------------------------------------------------------------
-
-export { WheelPicker, WheelPickerSelect, WheelPickerOptions, WheelPickerEmpty };
diff --git a/apps/dashboard/src/components/controls-search/command-tags.tsx b/apps/dashboard/src/components/controls-search/command-tags.tsx
deleted file mode 100644
index 9c531f849..000000000
--- a/apps/dashboard/src/components/controls-search/command-tags.tsx
+++ /dev/null
@@ -1,88 +0,0 @@
-"use client";
-
-import { Check } from "@openstatus/icons";
-import { Button } from "@openstatus/ui/components/ui/button";
-import {
- Command,
- CommandEmpty,
- CommandGroup,
- CommandInput,
- CommandItem,
- CommandList,
-} from "@openstatus/ui/components/ui/command";
-import {
- Popover,
- PopoverContent,
- PopoverTrigger,
-} from "@openstatus/ui/components/ui/popover";
-import { cn } from "@openstatus/ui/lib/utils";
-import { useQuery } from "@tanstack/react-query";
-import { parseAsArrayOf, parseAsString, useQueryState } from "nuqs";
-
-import { useTRPC } from "@/lib/trpc/client";
-
-export function CommandTags() {
- const trpc = useTRPC();
- const { data: tags } = useQuery(trpc.monitorTag.list.queryOptions());
- const [selectedTags, setSelectedTags] = useQueryState(
- "tags",
- parseAsArrayOf(parseAsString).withDefault([]).withOptions({
- shallow: false,
- }),
- );
-
- return (
- <Popover>
- <PopoverTrigger asChild>
- <Button variant="outline" size="sm">
- {selectedTags.length === (tags?.length ?? 0)
- ? "All Tags"
- : `${selectedTags.length} Tags`}
- </Button>
- </PopoverTrigger>
- <PopoverContent
- align="start"
- className="relative w-[200px] overflow-hidden p-0"
- >
- <Command>
- <CommandInput placeholder="Search tag..." />
- <CommandList>
- <CommandGroup>
- {tags?.map((tag) => (
- <CommandItem
- key={tag.id}
- value={tag.name}
- keywords={[tag.name]}
- onSelect={() => {
- setSelectedTags((prev) =>
- prev.includes(tag.name)
- ? prev.filter((r) => r !== tag.name)
- : [...prev, tag.name],
- );
- }}
- >
- <div className="flex items-center gap-2">
- <span
- className="size-2.5 rounded-full"
- style={{ backgroundColor: tag.color }}
- />
- {tag.name}
- </div>
- <Check
- className={cn(
- "ml-auto",
- selectedTags.includes(tag.name)
- ? "opacity-100"
- : "opacity-0",
- )}
- />
- </CommandItem>
- ))}
- </CommandGroup>
- <CommandEmpty>No tag found.</CommandEmpty>
- </CommandList>
- </Command>
- </PopoverContent>
- </Popover>
- );
-}
diff --git a/apps/dashboard/src/components/controls-search/dropdown-status.tsx b/apps/dashboard/src/components/controls-search/dropdown-status.tsx
deleted file mode 100644
index 7de7cc454..000000000
--- a/apps/dashboard/src/components/controls-search/dropdown-status.tsx
+++ /dev/null
@@ -1,49 +0,0 @@
-"use client";
-
-import { Check } from "@openstatus/icons";
-import { Button } from "@openstatus/ui/components/ui/button";
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuGroup,
- DropdownMenuItem,
- DropdownMenuLabel,
- DropdownMenuTrigger,
-} from "@openstatus/ui/components/ui/dropdown-menu";
-import { cn } from "@openstatus/ui/lib/utils";
-import { parseAsStringLiteral, useQueryState } from "nuqs";
-
-import { STATUS } from "@/data/metrics.client";
-
-const parseStatus = parseAsStringLiteral(STATUS);
-
-export function DropdownStatus() {
- const [status, setStatus] = useQueryState("status", parseStatus);
-
- return (
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button variant="outline" size="sm" className="capitalize">
- {status ?? "All Status"}
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="start">
- <DropdownMenuGroup>
- <DropdownMenuLabel className="text-muted-foreground text-xs font-medium">
- Request Status
- </DropdownMenuLabel>
- {STATUS.map((item) => (
- <DropdownMenuItem
- key={item}
- onSelect={() => setStatus(item)}
- className={cn("capitalize")}
- >
- {item}
- {status === item ? <Check className="ml-auto shrink-0" /> : null}
- </DropdownMenuItem>
- ))}
- </DropdownMenuGroup>
- </DropdownMenuContent>
- </DropdownMenu>
- );
-}
diff --git a/apps/dashboard/src/components/controls-search/dropdown-trigger.tsx b/apps/dashboard/src/components/controls-search/dropdown-trigger.tsx
deleted file mode 100644
index db2515d89..000000000
--- a/apps/dashboard/src/components/controls-search/dropdown-trigger.tsx
+++ /dev/null
@@ -1,49 +0,0 @@
-"use client";
-
-import { Check } from "@openstatus/icons";
-import { Button } from "@openstatus/ui/components/ui/button";
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuGroup,
- DropdownMenuItem,
- DropdownMenuLabel,
- DropdownMenuTrigger,
-} from "@openstatus/ui/components/ui/dropdown-menu";
-import { cn } from "@openstatus/ui/lib/utils";
-import { parseAsStringLiteral, useQueryState } from "nuqs";
-
-import { TRIGGER } from "@/data/metrics.client";
-
-const parseTrigger = parseAsStringLiteral(TRIGGER);
-
-export function DropdownTrigger() {
- const [trigger, setTrigger] = useQueryState("trigger", parseTrigger);
-
- return (
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button variant="outline" size="sm" className="capitalize">
- {trigger ?? "All Trigger"}
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="start">
- <DropdownMenuGroup>
- <DropdownMenuLabel className="text-muted-foreground text-xs font-medium">
- Trigger
- </DropdownMenuLabel>
- {TRIGGER.map((item) => (
- <DropdownMenuItem
- key={item}
- onSelect={() => setTrigger(item)}
- className={cn("capitalize")}
- >
- {item === "cron" ? "Scheduled" : "API"}
- {trigger === item ? <Check className="ml-auto shrink-0" /> : null}
- </DropdownMenuItem>
- ))}
- </DropdownMenuGroup>
- </DropdownMenuContent>
- </DropdownMenu>
- );
-}
diff --git a/apps/dashboard/src/components/data-table/page-components/columns.tsx b/apps/dashboard/src/components/data-table/page-components/columns.tsx
deleted file mode 100644
index b7b7b49f0..000000000
--- a/apps/dashboard/src/components/data-table/page-components/columns.tsx
+++ /dev/null
@@ -1,62 +0,0 @@
-"use client";
-
-import type { RouterOutputs } from "@openstatus/api";
-import type { ColumnDef } from "@tanstack/react-table";
-
-import { DataTableColumnHeader } from "@/components/ui/data-table/data-table-column-header";
-
-import { TableCellEmpty } from "../table-cell-empty";
-import { DataTableRowActions } from "./data-table-row-actions";
-
-type PageComponent = RouterOutputs["pageComponent"]["list"][number];
-
-export const columns: ColumnDef<PageComponent>[] = [
- {
- accessorKey: "name",
- header: "Name",
- enableSorting: false,
- enableHiding: false,
- },
- {
- accessorKey: "description",
- header: "Description",
- enableSorting: false,
- cell: ({ row }) => {
- const value = row.getValue("description");
- if (!value) return <TableCellEmpty>No description</TableCellEmpty>;
- return (
- <span className="text-muted-foreground max-w-[200px] truncate">
- {String(value)}
- </span>
- );
- },
- },
- {
- accessorKey: "type",
- header: ({ column }) => (
- <DataTableColumnHeader column={column} title="Type" />
- ),
- cell: ({ row }) => {
- const value = row.getValue("type");
- return <span className="capitalize">{String(value)}</span>;
- },
- },
- {
- accessorKey: "order",
- header: ({ column }) => (
- <DataTableColumnHeader column={column} title="Order" />
- ),
- cell: ({ row }) => {
- const value = row.getValue("order");
- if (value == null) return <TableCellEmpty>Unset</TableCellEmpty>;
- return <span>{String(value)}</span>;
- },
- },
- {
- id: "actions",
- cell: ({ row }) => <DataTableRowActions row={row} />,
- meta: {
- cellClassName: "w-8",
- },
- },
-];
diff --git a/apps/dashboard/src/components/data-table/page-components/data-table-row-actions.tsx b/apps/dashboard/src/components/data-table/page-components/data-table-row-actions.tsx
deleted file mode 100644
index c637e9398..000000000
--- a/apps/dashboard/src/components/data-table/page-components/data-table-row-actions.tsx
+++ /dev/null
@@ -1,47 +0,0 @@
-"use client";
-
-import type { RouterOutputs } from "@openstatus/api";
-import { useMutation, useQueryClient } from "@tanstack/react-query";
-import type { Row } from "@tanstack/react-table";
-
-import { QuickActions } from "@/components/dropdowns/quick-actions";
-import { getActions } from "@/data/page-components.client";
-import { useTRPC } from "@/lib/trpc/client";
-
-type PageComponent = RouterOutputs["pageComponent"]["list"][number];
-
-interface DataTableRowActionsProps {
- row: Row<PageComponent>;
-}
-
-export function DataTableRowActions({ row }: DataTableRowActionsProps) {
- const trpc = useTRPC();
- const actions = getActions({});
- const queryClient = useQueryClient();
-
- const deletePageComponentMutation = useMutation(
- trpc.pageComponent.delete.mutationOptions({
- onSuccess: () => {
- queryClient.refetchQueries({
- queryKey: trpc.pageComponent.list.queryKey({
- pageId: row.original.pageId ?? undefined,
- }),
- });
- },
- }),
- );
-
- return (
- <QuickActions
- actions={actions}
- deleteAction={{
- confirmationValue: row.original.name ?? "component",
- submitAction: async () => {
- await deletePageComponentMutation.mutateAsync({
- id: row.original.id,
- });
- },
- }}
- />
- );
-}
diff --git a/apps/dashboard/src/components/date-picker.tsx b/apps/dashboard/src/components/date-picker.tsx
deleted file mode 100644
index 8fb2954de..000000000
--- a/apps/dashboard/src/components/date-picker.tsx
+++ /dev/null
@@ -1,128 +0,0 @@
-"use client";
-
-import { Button } from "@openstatus/ui/components/ui/button";
-import { Calendar } from "@openstatus/ui/components/ui/calendar";
-import { Input } from "@openstatus/ui/components/ui/input";
-import { Kbd } from "@openstatus/ui/components/ui/kbd";
-import { Label } from "@openstatus/ui/components/ui/label";
-import { Separator } from "@openstatus/ui/components/ui/separator";
-import { endOfDay } from "date-fns";
-import { useState } from "react";
-import type { DateRange } from "react-day-picker";
-
-import { formatDateForInput } from "@/lib/formatter";
-
-type DatePickerProps = {
- range: DateRange;
- onSelect: (range: DateRange) => void;
- presets: { id: string; label: string; values: DateRange; shortcut: string }[];
-};
-
-export function DatePicker({ range, onSelect, presets }: DatePickerProps) {
- const [today] = useState(new Date());
- const disableBefore = presets[presets.length - 1]?.values?.from;
-
- return (
- <div>
- <div className="flex flex-row">
- <div className="relative py-4">
- <div className="h-full">
- <div className="flex flex-col px-1">
- <div className="text-muted-foreground px-3 py-1 text-xs font-medium">
- Presets
- </div>
- {presets.map((preset) => {
- const isSelected =
- range.from?.getTime() === preset.values.from?.getTime() &&
- range.to?.getTime() === preset.values.to?.getTime();
-
- return (
- <Button
- key={preset.id}
- variant={isSelected ? "outline" : "ghost"}
- size="sm"
- className="w-full justify-between border border-transparent"
- onClick={() => {
- onSelect(preset.values);
- }}
- >
- <span>{preset.label}</span>
- <Kbd className="font-mono uppercase">{preset.shortcut}</Kbd>
- </Button>
- );
- })}
- </div>
- </div>
- </div>
- <Separator orientation="vertical" className="h-auto! w-px" />
- <div className="flex flex-1 items-center justify-center">
- <Calendar
- mode="range"
- selected={range}
- onSelect={(newDate) => {
- if (newDate) {
- onSelect({
- ...newDate,
- to: newDate.to ? endOfDay(newDate.to) : undefined,
- });
- }
- }}
- className="p-2"
- disabled={[
- { after: today }, // Dates before today
- { before: disableBefore ?? today }, // Dates before last action
- ]}
- />
- </div>
- </div>
- <Separator />
- <div className="flex flex-col gap-2 px-3 py-4">
- <p className="text-muted-foreground px-1 text-xs font-medium">
- Custom Range
- </p>
- <div className="grid gap-2 sm:grid-cols-2">
- <div className="grid w-full gap-1.5">
- <Label htmlFor="from" className="px-1">
- Start
- </Label>
- <Input
- type="datetime-local"
- id="from"
- name="from"
- min={formatDateForInput(disableBefore ?? today)}
- max={formatDateForInput(today)}
- value={range.from ? formatDateForInput(range.from) : ""}
- onChange={(e) => {
- const newDate = new Date(e.target.value);
- if (!Number.isNaN(newDate.getTime())) {
- onSelect({ ...range, from: newDate });
- }
- }}
- disabled={!range.from}
- />
- </div>
- <div className="grid w-full gap-1.5">
- <Label htmlFor="to" className="px-1">
- End
- </Label>
- <Input
- type="datetime-local"
- id="to"
- name="to"
- min={formatDateForInput(range.from ?? today)}
- max={formatDateForInput(today)}
- value={range.to ? formatDateForInput(range.to) : ""}
- onChange={(e) => {
- const newDate = new Date(e.target.value);
- if (!Number.isNaN(newDate.getTime())) {
- onSelect({ ...range, to: newDate });
- }
- }}
- disabled={!range.to}
- />
- </div>
- </div>
- </div>
- </div>
- );
-}
diff --git a/apps/dashboard/src/components/development-indicator.tsx b/apps/dashboard/src/components/development-indicator.tsx
deleted file mode 100644
index 651bd3ffb..000000000
--- a/apps/dashboard/src/components/development-indicator.tsx
+++ /dev/null
@@ -1,45 +0,0 @@
-"use client";
-
-import { Kbd } from "@openstatus/ui/components/ui/kbd";
-import {
- Tooltip,
- TooltipContent,
- TooltipProvider,
- TooltipTrigger,
-} from "@openstatus/ui/components/ui/tooltip";
-import { useIsMobile } from "@openstatus/ui/hooks/use-mobile";
-import * as Portal from "@radix-ui/react-portal";
-
-export function DevelopmentIndicator() {
- const isMobile = useIsMobile();
-
- if (process.env.NODE_ENV !== "production") return null;
-
- return (
- <Portal.Root>
- <div className="border-destructive pointer-events-none fixed inset-0 z-[9999] border-2" />
- <div className="fixed inset-x-0 bottom-0 z-[9999] select-none">
- <div className="flex items-center justify-center">
- <TooltipProvider delayDuration={0}>
- <Tooltip>
- <TooltipTrigger>
- <div className="bg-destructive text-background w-fit rounded-t-sm px-2 py-1 font-mono text-xs">
- In Beta
- </div>
- </TooltipTrigger>
- <TooltipContent side="top">
- {!isMobile ? (
- <p>
- Press <Kbd>F</Kbd> key to provide feedback.
- </p>
- ) : (
- <p>Use a larger screen to provide feedback.</p>
- )}
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- </div>
- </div>
- </Portal.Root>
- );
-}
diff --git a/apps/dashboard/src/components/forms/monitor/form-status-pages.tsx b/apps/dashboard/src/components/forms/monitor/form-status-pages.tsx
deleted file mode 100644
index 652a21ad7..000000000
--- a/apps/dashboard/src/components/forms/monitor/form-status-pages.tsx
+++ /dev/null
@@ -1,239 +0,0 @@
-"use client";
-
-import { zodResolver } from "@hookform/resolvers/zod";
-import { Badge } from "@openstatus/ui/components/ui/badge";
-import { Button } from "@openstatus/ui/components/ui/button";
-import { Checkbox } from "@openstatus/ui/components/ui/checkbox";
-import {
- Form,
- FormControl,
- FormDescription,
- FormField,
- FormItem,
- FormLabel,
- FormMessage,
-} from "@openstatus/ui/components/ui/form";
-import { Input } from "@openstatus/ui/components/ui/input";
-import { cn } from "@openstatus/ui/lib/utils";
-import { isTRPCClientError } from "@trpc/client";
-import { useTransition } from "react";
-import { useForm } from "react-hook-form";
-import { toast } from "sonner";
-import { z } from "zod";
-
-import {
- EmptyStateContainer,
- EmptyStateTitle,
-} from "@/components/content/empty-state";
-import {
- FormCard,
- FormCardContent,
- FormCardDescription,
- FormCardFooter,
- FormCardHeader,
- FormCardSeparator,
- FormCardTitle,
-} from "@/components/forms/form-card";
-
-const schema = z.object({
- description: z.string().optional(),
- externalName: z.string().optional(),
- statusPages: z.array(z.number()),
-});
-
-type FormValues = z.infer<typeof schema>;
-
-export function FormStatusPages({
- defaultValues,
- onSubmit,
- statusPages,
- ...props
-}: Omit<React.ComponentProps<"form">, "onSubmit"> & {
- defaultValues?: FormValues;
- onSubmit: (values: FormValues) => Promise<void>;
- statusPages: { id: number; title: string; slug: string }[];
-}) {
- const form = useForm<FormValues>({
- resolver: zodResolver(schema),
- defaultValues: defaultValues ?? {
- description: "",
- externalName: "",
- statusPages: [],
- },
- });
- const [isPending, startTransition] = useTransition();
- const watchStatusPages = form.watch("statusPages");
-
- function submitAction(values: FormValues) {
- if (isPending) return;
-
- startTransition(async () => {
- try {
- const promise = onSubmit(values);
- toast.promise(promise, {
- loading: "Saving...",
- success: () => "Saved",
- error: (error) => {
- if (isTRPCClientError(error)) {
- return error.message;
- }
- return "Failed to save";
- },
- });
- await promise;
- } catch (error) {
- console.error(error);
- }
- });
- }
-
- return (
- <Form {...form}>
- <form onSubmit={form.handleSubmit(submitAction)} {...props}>
- <FormCard>
- <FormCardHeader>
- <FormCardTitle>Status Pages</FormCardTitle>
- <FormCardDescription>
- Add status pages to your monitor and configure the external name
- and description to be shown on the status page.
- </FormCardDescription>
- </FormCardHeader>
- <FormCardContent className="grid gap-4 sm:grid-cols-3">
- <FormField
- control={form.control}
- name="externalName"
- render={({ field }) => (
- <FormItem className="sm:col-span-2">
- <FormLabel>External Name</FormLabel>
- <FormControl>
- <Input placeholder="OpenStatus API" {...field} />
- </FormControl>
- <FormDescription>
- External name on the status page, the feed or subscribers
- notifications. If not provided, monitor&apos;s name will be
- used.
- </FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={form.control}
- name="description"
- render={({ field }) => (
- <FormItem className="sm:col-span-full">
- <FormLabel>Description</FormLabel>
- <FormControl>
- <Input placeholder="My Status Page" {...field} />
- </FormControl>
- <FormDescription>
- A tooltip with extra information about the monitor will be
- displayed.
- </FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
- </FormCardContent>
- <FormCardSeparator />
- <FormCardContent>
- {statusPages.length > 0 ? (
- <FormField
- control={form.control}
- name="statusPages"
- render={() => (
- <FormItem>
- <div className="flex items-center justify-between">
- <FormLabel className="text-base">
- List of Status Pages
- </FormLabel>
- <Button
- variant="ghost"
- size="sm"
- type="button"
- className={cn(
- watchStatusPages.length === statusPages.length &&
- "text-muted-foreground",
- )}
- onClick={() => {
- const allSelected = statusPages.every((item) =>
- watchStatusPages.includes(item.id),
- );
-
- if (!allSelected) {
- form.setValue(
- "statusPages",
- statusPages.map((item) => item.id),
- );
- } else {
- form.setValue("statusPages", []);
- }
- }}
- >
- Select all
- </Button>
- </div>
- {statusPages.map((item) => (
- <FormField
- key={item.id}
- control={form.control}
- name="statusPages"
- render={({ field }) => {
- return (
- <FormItem
- key={item.id}
- className="flex items-center"
- >
- <FormControl>
- <Checkbox
- checked={
- field.value?.includes(item.id) || false
- }
- onCheckedChange={(checked) => {
- return checked
- ? field.onChange([
- ...field.value,
- item.id,
- ])
- : field.onChange(
- field.value?.filter(
- (value) => value !== item.id,
- ),
- );
- }}
- />
- </FormControl>
- <FormLabel className="text-sm font-normal">
- {item.title}{" "}
- <Badge
- variant="secondary"
- className="px-1.5 py-px font-mono text-[10px]"
- >
- {item.slug}
- </Badge>
- </FormLabel>
- </FormItem>
- );
- }}
- />
- ))}
- <FormMessage />
- </FormItem>
- )}
- />
- ) : (
- <EmptyStateContainer>
- <EmptyStateTitle>No status pages</EmptyStateTitle>
- </EmptyStateContainer>
- )}
- </FormCardContent>
- <FormCardFooter>
- <Button type="submit" disabled={isPending}>
- {isPending ? "Submitting..." : "Submit"}
- </Button>
- </FormCardFooter>
- </FormCard>
- </form>
- </Form>
- );
-}
diff --git a/apps/dashboard/src/components/forms/status-page/form-monitors.tsx b/apps/dashboard/src/components/forms/status-page/form-monitors.tsx
deleted file mode 100644
index 4108b4c81..000000000
--- a/apps/dashboard/src/components/forms/status-page/form-monitors.tsx
+++ /dev/null
@@ -1,813 +0,0 @@
-"use client";
-
-import type { UniqueIdentifier } from "@dnd-kit/core";
-import { zodResolver } from "@hookform/resolvers/zod";
-import { Check, Expand, DragHandle, Add, Delete } from "@openstatus/icons";
-import {
- AlertDialog,
- AlertDialogAction,
- AlertDialogCancel,
- AlertDialogContent,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle,
- AlertDialogTrigger,
-} from "@openstatus/ui/components/ui/alert-dialog";
-import { Button } from "@openstatus/ui/components/ui/button";
-import {
- Command,
- CommandEmpty,
- CommandGroup,
- CommandInput,
- CommandItem,
- CommandList,
-} from "@openstatus/ui/components/ui/command";
-import {
- Form,
- FormControl,
- FormDescription,
- FormField,
- FormItem,
- FormLabel,
- FormMessage,
-} from "@openstatus/ui/components/ui/form";
-import { Input } from "@openstatus/ui/components/ui/input";
-import { PopoverContent } from "@openstatus/ui/components/ui/popover";
-import { Popover, PopoverTrigger } from "@openstatus/ui/components/ui/popover";
-import {
- Tooltip,
- TooltipContent,
- TooltipProvider,
- TooltipTrigger,
-} from "@openstatus/ui/components/ui/tooltip";
-import { cn } from "@openstatus/ui/lib/utils";
-import { isTRPCClientError } from "@trpc/client";
-import { useCallback, useEffect, useState, useTransition } from "react";
-import { type UseFormReturn, useForm } from "react-hook-form";
-import { toast } from "sonner";
-import { z } from "zod";
-
-import { Link } from "@/components/common/link";
-import {
- EmptyStateContainer,
- EmptyStateTitle,
-} from "@/components/content/empty-state";
-import {
- FormCard,
- FormCardContent,
- FormCardDescription,
- FormCardFooter,
- FormCardFooterInfo,
- FormCardHeader,
- FormCardSeparator,
- FormCardTitle,
-} from "@/components/forms/form-card";
-import {
- Sortable,
- SortableContent,
- SortableItem,
- SortableItemHandle,
- SortableOverlay,
-} from "@/components/ui/sortable";
-
-type Monitor = {
- id: number;
- name: string;
- externalName: string | null;
- url: string;
- active: boolean | null;
-};
-
-type MonitorGroup = {
- id: number;
- name: string;
- monitors: Monitor[];
-};
-
-const monitorSchema = z.object({
- id: z.number(),
- order: z.number(),
- active: z.boolean().nullable(),
-});
-
-const schema = z.object({
- monitors: z.array(monitorSchema),
- groups: z.array(
- z.object({
- id: z.number(),
- order: z.number(),
- name: z.string(),
- monitors: z.array(monitorSchema).min(1, {
- error: "At least one monitor is required",
- }),
- }),
- ),
-});
-
-const getSortedMonitors = (
- monitors: Monitor[],
- monitorData: { id: number; order: number }[],
-) => {
- const orderMap = new Map(monitorData?.map((m) => [m.id, m.order]) ?? []);
-
- return monitors
- .filter((monitor) => orderMap.has(monitor.id))
- .sort((a, b) => {
- const aOrder = orderMap.get(a.id) ?? 0;
- const bOrder = orderMap.get(b.id) ?? 0;
- return aOrder - bOrder;
- });
-};
-
-const getSortedItems = (
- monitors: Monitor[],
- monitorData: { id: number; order: number }[],
- groups: Array<{
- id: number;
- order: number;
- name: string;
- monitors: Array<{ id: number; order: number; active: boolean | null }>;
- }>,
-): (Monitor | MonitorGroup)[] => {
- // Create map of monitor orders
- const monitorOrderMap = new Map(monitorData.map((m) => [m.id, m.order]));
-
- // Create array of monitors with their orders
- const monitorsWithOrder = monitors
- .filter((monitor) => monitorOrderMap.has(monitor.id))
- .map((monitor) => ({
- item: monitor,
- order: monitorOrderMap.get(monitor.id) ?? 0,
- }));
-
- // Create array of groups with their orders
- const groupsWithOrder = groups.map((group) => ({
- item: {
- id: group.id,
- name: group.name,
- monitors: getSortedMonitors(monitors, group.monitors),
- } as MonitorGroup,
- order: group.order,
- }));
-
- // Combine and sort by order
- return [...monitorsWithOrder, ...groupsWithOrder]
- .sort((a, b) => a.order - b.order)
- .map((entry) => entry.item);
-};
-
-type FormValues = z.infer<typeof schema>;
-
-export function FormMonitors({
- defaultValues,
- onSubmit,
- monitors,
- legacy,
- ...props
-}: Omit<React.ComponentProps<"form">, "onSubmit"> & {
- defaultValues?: FormValues;
- monitors: Monitor[];
- /**
- * Whether the status page is legacy or new
- */
- legacy: boolean;
- onSubmit: (values: FormValues) => Promise<void>;
-}) {
- const form = useForm<FormValues>({
- resolver: zodResolver(schema),
- defaultValues: defaultValues ?? {},
- });
- const [isPending, startTransition] = useTransition();
- const watchMonitors = form.watch("monitors");
- const watchGroups = form.watch("groups");
- const [data, setData] = useState<(Monitor | MonitorGroup)[]>(
- getSortedItems(
- monitors,
- defaultValues?.monitors ?? [],
- defaultValues?.groups ?? [],
- ),
- );
-
- // Get all monitor IDs that are already used in groups
- const monitorsInGroups = new Set(
- (watchGroups ?? []).flatMap((g) => g.monitors.map((m) => m.id)),
- );
-
- useEffect(() => {
- const sortedItems = getSortedItems(
- monitors,
- watchMonitors,
- watchGroups ?? [],
- );
- setData(sortedItems);
- }, [watchMonitors, watchGroups, monitors]);
-
- const onValueChange = useCallback(
- (newItems: (Monitor | MonitorGroup)[]) => {
- setData(newItems);
-
- // Update monitors with their position in the overall list
- const monitors = newItems
- .map((item, index) => ({ item, index }))
- .filter(
- (entry): entry is { item: Monitor; index: number } =>
- "url" in entry.item,
- )
- .map(({ item, index }) => ({
- id: item.id,
- order: index,
- active: item.active,
- }));
- form.setValue("monitors", monitors);
-
- // Update groups with their position in the overall list
- const existingGroups = form.getValues("groups") ?? [];
- const groups = newItems
- .map((item, index) => ({ item, index }))
- .filter(
- (entry): entry is { item: MonitorGroup; index: number } =>
- "monitors" in entry.item && !("url" in entry.item),
- )
- .map(({ item, index }) => {
- const existingGroup = existingGroups.find((g) => g.id === item.id);
- return existingGroup
- ? {
- ...existingGroup,
- order: index,
- }
- : {
- id: item.id,
- order: index,
- name: item.name,
- monitors: [],
- };
- });
- form.setValue("groups", groups);
- },
- [form],
- );
-
- const getItemValue = useCallback(
- (item: Monitor | MonitorGroup) => item.id,
- [],
- );
-
- const handleAddGroup = useCallback(() => {
- const newGroupId = Date.now();
- const existingGroups = form.getValues("groups") ?? [];
- const existingMonitors = form.getValues("monitors") ?? [];
- const order = existingGroups.length + existingMonitors.length;
- const newGroups = [
- ...existingGroups,
- { id: newGroupId, order, name: "", monitors: [] },
- ];
- form.setValue("groups", newGroups);
- setData((prev) => [
- ...prev,
- { id: newGroupId, order, name: "", monitors: [] },
- ]);
- }, [form]);
-
- const handleDeleteGroup = useCallback(
- (groupId: number) => {
- const existingGroups = form.getValues("groups") ?? [];
- form.setValue(
- "groups",
- existingGroups.filter((g) => g.id !== groupId),
- );
- setData((prev) => prev.filter((item) => item.id !== groupId));
- },
- [form],
- );
-
- const renderOverlay = useCallback(
- ({ value }: { value: UniqueIdentifier }) => {
- const monitor = data.find((item) => item.id === value);
- if (!monitor) return null;
-
- if ("url" in monitor) {
- return (
- <MonitorRow
- monitor={monitor}
- form={form}
- className="border-x border-transparent px-2"
- />
- );
- }
-
- const groups = form.getValues("groups") ?? [];
- const groupIndex = groups.findIndex((g) => g.id === monitor.id);
- return (
- <MonitorGroup
- group={monitor}
- groupIndex={groupIndex}
- onDeleteGroup={handleDeleteGroup}
- form={form}
- monitors={monitors}
- />
- );
- },
- [data, handleDeleteGroup, form, monitors],
- );
-
- function submitAction(values: FormValues) {
- if (isPending) return;
-
- startTransition(async () => {
- try {
- const promise = onSubmit(values);
- toast.promise(promise, {
- loading: "Saving...",
- success: "Saved",
- error: (error) => {
- if (isTRPCClientError(error)) {
- return error.message;
- }
- return "Failed to save";
- },
- });
- await promise;
- } catch (error) {
- console.error(error);
- }
- });
- }
-
- return (
- <Form {...form}>
- <form onSubmit={form.handleSubmit(submitAction)} {...props}>
- <FormCard>
- <FormCardHeader>
- <FormCardTitle>Monitors</FormCardTitle>
- <FormCardDescription>
- Connect your monitors to your status page.
- </FormCardDescription>
- </FormCardHeader>
- <FormCardContent className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3">
- <FormField
- control={form.control}
- name="monitors"
- render={({ field }) => (
- <FormItem className="flex flex-col">
- <FormLabel className="sr-only">Monitors</FormLabel>
- <Popover>
- <PopoverTrigger asChild>
- <FormControl>
- <Button
- variant="outline"
- role="combobox"
- className={cn(
- "w-full justify-between",
- !field.value && "text-muted-foreground",
- )}
- >
- {field.value.length > 0
- ? `${field.value.length} monitors selected`
- : "Select monitors"}
- <Expand className="opacity-50" />
- </Button>
- </FormControl>
- </PopoverTrigger>
- <PopoverContent className="p-0">
- <Command>
- <CommandInput
- placeholder="Search monitors..."
- className="h-9"
- />
- <CommandList>
- <CommandEmpty>No monitors found.</CommandEmpty>
- <CommandGroup>
- {monitors.map((monitor) => {
- const isInGroup = monitorsInGroups.has(
- monitor.id,
- );
- const isSelected = field.value.some(
- (m) => m.id === monitor.id,
- );
- return (
- <CommandItem
- value={monitor.name}
- key={monitor.id}
- disabled={isInGroup}
- onSelect={() => {
- if (isSelected) {
- form.setValue(
- "monitors",
- field.value.filter(
- (m) => m.id !== monitor.id,
- ),
- );
- } else {
- form.setValue("monitors", [
- ...field.value,
- {
- id: monitor.id,
- order: watchMonitors.length,
- active: monitor.active,
- },
- ]);
- }
- }}
- >
- {monitor.name}
- <Check
- className={cn(
- "ml-auto",
- isSelected ? "opacity-100" : "opacity-0",
- )}
- />
- </CommandItem>
- );
- })}
- </CommandGroup>
- </CommandList>
- </Command>
- </PopoverContent>
- </Popover>
- <FormDescription>Choose monitors to display.</FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
- {legacy ? (
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger asChild>
- <span className="w-full">
- <Button
- variant="outline"
- type="button"
- className="w-full"
- disabled={legacy}
- >
- <Add />
- Add Group
- </Button>
- </span>
- </TooltipTrigger>
- <TooltipContent>
- <p>
- Enable the new redesign to add groups to your status page.
- </p>
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- ) : (
- <Button
- variant="outline"
- type="button"
- className="w-full"
- onClick={handleAddGroup}
- >
- <Add />
- Add Group
- </Button>
- )}
- </FormCardContent>
- <FormCardSeparator />
- <FormCardContent>
- <Sortable
- value={data}
- onValueChange={onValueChange}
- getItemValue={getItemValue}
- orientation="vertical"
- >
- {data.length ? (
- <SortableContent className="grid gap-2">
- {data.map((item) => {
- if ("url" in item) {
- return (
- <MonitorRow
- key={`${item.id}-monitor`}
- className="border-x border-transparent px-2"
- monitor={item}
- form={form}
- />
- );
- }
- const groups = form.getValues("groups") ?? [];
- const groupIndex = groups.findIndex(
- (g) => g.id === item.id,
- );
- return (
- <MonitorGroup
- key={`${item.id}-group`}
- group={item}
- groupIndex={groupIndex}
- onDeleteGroup={handleDeleteGroup}
- form={form}
- monitors={monitors}
- />
- );
- })}
- <SortableOverlay>{renderOverlay}</SortableOverlay>
- </SortableContent>
- ) : (
- <EmptyStateContainer>
- <EmptyStateTitle>No monitors selected</EmptyStateTitle>
- </EmptyStateContainer>
- )}
- </Sortable>
- </FormCardContent>
- <FormCardFooter>
- <FormCardFooterInfo>
- Learn more about monitor <Link href="#">display options</Link>.
- </FormCardFooterInfo>
- <Button type="submit" disabled={isPending}>
- {isPending ? "Submitting..." : "Submit"}
- </Button>
- </FormCardFooter>
- </FormCard>
- </form>
- </Form>
- );
-}
-
-interface MonitorRowProps extends Omit<
- React.ComponentPropsWithoutRef<typeof SortableItem>,
- "value"
-> {
- monitor: Monitor;
- form: UseFormReturn<FormValues>;
-}
-
-function MonitorRow({ monitor, className, ...props }: MonitorRowProps) {
- return (
- <SortableItem
- value={monitor.id}
- asChild
- className={cn("rounded-md", className)}
- {...props}
- >
- <div className="grid h-9 grid-cols-3 gap-2">
- <div className="flex flex-row items-center gap-4 self-center">
- <SortableItemHandle>
- <DragHandle
- size={16}
- aria-hidden="true"
- className="text-muted-foreground"
- />
- </SortableItemHandle>
- <span className="truncate text-sm">
- {monitor.name}{" "}
- <span className="text-muted-foreground">
- {monitor.externalName ? `(${monitor.externalName})` : ""}
- </span>
- </span>
- </div>
- <div className="text-muted-foreground self-center truncate text-sm">
- {monitor.url}
- </div>
- <div className="text-muted-foreground self-center truncate text-sm">
- {monitor.active ? "Active" : "Inactive"}
- </div>
- </div>
- </SortableItem>
- );
-}
-
-interface MonitorGroupProps extends Omit<
- React.ComponentPropsWithoutRef<typeof SortableItem>,
- "value"
-> {
- group: MonitorGroup;
- groupIndex: number;
- onDeleteGroup: (groupId: number) => void;
- form: UseFormReturn<FormValues>;
- monitors: Monitor[];
-}
-
-function MonitorGroup({
- group,
- groupIndex,
- onDeleteGroup,
- form,
- monitors,
-}: MonitorGroupProps) {
- const watchGroup = form.watch(`groups.${groupIndex}`);
- const watchMonitors = form.watch("monitors");
- const watchGroups = form.watch("groups");
- const [data, setData] = useState<Monitor[]>(group.monitors);
-
- // Calculate taken monitors (in main list or other groups)
- const takenMonitorIds = new Set([
- ...watchMonitors.map((m) => m.id),
- ...watchGroups
- .filter((g) => g.id !== group.id)
- .flatMap((g) => g.monitors.map((m) => m.id)),
- ]);
-
- const onValueChange = useCallback(
- (newMonitors: Monitor[]) => {
- setData(newMonitors);
- // Update the form with the new monitor order
- form.setValue(
- `groups.${groupIndex}.monitors`,
- newMonitors.map((m, index) => ({
- id: m.id,
- order: index,
- active: m.active,
- })),
- );
- },
- [form, groupIndex],
- );
-
- useEffect(() => {
- setData(getSortedMonitors(monitors, watchGroup.monitors));
- }, [watchGroup.monitors, monitors]);
-
- const getItemValue = useCallback((item: Monitor) => item.id, []);
-
- const renderOverlay = useCallback(
- ({ value }: { value: UniqueIdentifier }) => {
- const monitor = data.find((item) => item.id === value);
- if (!monitor) return null;
-
- return <MonitorRow monitor={monitor} form={form} />;
- },
- [data, form],
- );
-
- return (
- <SortableItem value={group.id} className="bg-muted rounded-md border">
- <div className="grid grid-cols-3 gap-2 px-2 pt-2">
- <div className="flex flex-row items-center gap-1 self-center">
- <SortableItemHandle>
- <DragHandle
- size={16}
- aria-hidden="true"
- className="text-muted-foreground"
- />
- </SortableItemHandle>
- <FormField
- key={`${group.id}-name-${groupIndex}`}
- control={form.control}
- name={`groups.${groupIndex}.name` as const}
- render={({ field }) => (
- <FormItem className="w-full">
- <FormLabel className="sr-only">Group name</FormLabel>
- <FormControl>
- <Input
- placeholder="Group Name"
- className="bg-background w-full"
- {...field}
- />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- </div>
- <FormField
- key={`${group.id}-monitors-${groupIndex}`}
- control={form.control}
- name={`groups.${groupIndex}.monitors` as const}
- render={({ field }) => (
- <FormItem className="flex w-full flex-col">
- <FormLabel className="sr-only">Monitors</FormLabel>
- <Popover>
- <PopoverTrigger asChild>
- <FormControl>
- <Button
- variant="outline"
- role="combobox"
- className={cn(
- "w-full justify-between",
- !field.value && "text-muted-foreground",
- )}
- >
- {Array.isArray(field.value) && field.value.length > 0
- ? `${field.value.length} monitors selected`
- : "Select monitors"}
- <Expand className="opacity-50" />
- </Button>
- </FormControl>
- </PopoverTrigger>
- <PopoverContent className="p-0">
- <Command>
- <CommandInput
- placeholder="Search monitors..."
- className="h-9"
- />
- <CommandList>
- <CommandEmpty>No monitors found.</CommandEmpty>
- <CommandGroup>
- {monitors.map((monitor) => {
- const current = field.value ?? [];
- const isSelected = current.some(
- (m) => m.id === monitor.id,
- );
- const isTaken = takenMonitorIds.has(monitor.id);
- return (
- <CommandItem
- value={monitor.name}
- key={monitor.id}
- disabled={isTaken}
- onSelect={() => {
- if (isSelected) {
- form.setValue(
- `groups.${groupIndex}.monitors`,
- current.filter((m) => m.id !== monitor.id),
- );
- } else {
- form.setValue(
- `groups.${groupIndex}.monitors`,
- [
- ...current,
- {
- id: monitor.id,
- order: 0,
- active: monitor.active,
- },
- ],
- );
- }
- }}
- >
- {monitor.name}
- <Check
- className={cn(
- "ml-auto",
- isSelected ? "opacity-100" : "opacity-0",
- )}
- />
- </CommandItem>
- );
- })}
- </CommandGroup>
- </CommandList>
- </Command>
- </PopoverContent>
- </Popover>
- <FormMessage />
- </FormItem>
- )}
- />
- <div className="flex justify-end">
- <AlertDialog>
- <AlertDialogTrigger asChild>
- <Button
- type="button"
- variant="ghost"
- size="icon"
- className="text-destructive hover:bg-destructive/10 hover:text-destructive dark:hover:bg-destructive/20 [&_svg]:text-destructive [&_svg]:size-4"
- // NOTE: delete directly if no monitors are in the group
- {...(data.length === 0
- ? { onClick: () => onDeleteGroup(group.id) }
- : {})}
- >
- <Delete />
- </Button>
- </AlertDialogTrigger>
- <AlertDialogContent>
- <AlertDialogHeader>
- <AlertDialogTitle>Are you sure?</AlertDialogTitle>
- <AlertDialogDescription>
- You are about to delete this group and all its monitors.
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancel>Cancel</AlertDialogCancel>
- <AlertDialogAction
- className="bg-destructive hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40 text-white shadow-xs"
- onClick={() => onDeleteGroup(group.id)}
- >
- Delete
- </AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- </div>
- </div>
- <div className="mt-2 border-t px-2 pt-2 pb-2">
- <Sortable
- value={data}
- onValueChange={onValueChange}
- getItemValue={getItemValue}
- orientation="vertical"
- >
- {data.length ? (
- <SortableContent className="grid gap-2">
- {data.map((item) => {
- return (
- <MonitorRow
- key={`${item.id}-monitor`}
- monitor={item}
- form={form}
- />
- );
- })}
- <SortableOverlay>{renderOverlay}</SortableOverlay>
- </SortableContent>
- ) : (
- <EmptyStateContainer>
- <EmptyStateTitle>No monitors selected</EmptyStateTitle>
- </EmptyStateContainer>
- )}
- </Sortable>
- </div>
- </SortableItem>
- );
-}
diff --git a/apps/dashboard/src/components/nav/nav-main.tsx b/apps/dashboard/src/components/nav/nav-main.tsx
deleted file mode 100644
index f0a8ea4db..000000000
--- a/apps/dashboard/src/components/nav/nav-main.tsx
+++ /dev/null
@@ -1,77 +0,0 @@
-"use client";
-
-import { ChevronRight, type IconType } from "@openstatus/icons";
-import {
- Collapsible,
- CollapsibleContent,
- CollapsibleTrigger,
-} from "@openstatus/ui/components/ui/collapsible";
-import {
- SidebarGroup,
- SidebarGroupLabel,
- SidebarMenu,
- SidebarMenuButton,
- SidebarMenuItem,
- SidebarMenuSub,
- SidebarMenuSubButton,
- SidebarMenuSubItem,
- useSidebar,
-} from "@openstatus/ui/components/ui/sidebar";
-import Link from "next/link";
-export function NavMain({
- items,
-}: {
- items: {
- title: string;
- url: string;
- icon?: IconType;
- isActive?: boolean;
- items?: {
- title: string;
- url: string;
- }[];
- }[];
-}) {
- const { setOpenMobile } = useSidebar();
- return (
- <SidebarGroup>
- <SidebarGroupLabel>Workspace Data</SidebarGroupLabel>
- <SidebarMenu>
- {items.map((item) => (
- <Collapsible
- key={item.title}
- asChild
- defaultOpen={item.isActive}
- className="group/collapsible"
- >
- <SidebarMenuItem>
- <CollapsibleTrigger asChild>
- <SidebarMenuButton tooltip={item.title}>
- {item.icon && <item.icon />}
- <span>{item.title}</span>
- <ChevronRight className="ml-auto transition-transform duration-200 group-data-[state=open]/collapsible:rotate-90" />
- </SidebarMenuButton>
- </CollapsibleTrigger>
- <CollapsibleContent>
- <SidebarMenuSub>
- {item.items?.map((subItem) => (
- <SidebarMenuSubItem key={subItem.title}>
- <SidebarMenuSubButton asChild>
- <Link
- href={subItem.url}
- onClick={() => setOpenMobile(false)}
- >
- <span>{subItem.title}</span>
- </Link>
- </SidebarMenuSubButton>
- </SidebarMenuSubItem>
- ))}
- </SidebarMenuSub>
- </CollapsibleContent>
- </SidebarMenuItem>
- </Collapsible>
- ))}
- </SidebarMenu>
- </SidebarGroup>
- );
-}
diff --git a/apps/dashboard/src/data/audit-logs.ts b/apps/dashboard/src/data/audit-logs.ts
deleted file mode 100644
index f77e2e505..000000000
--- a/apps/dashboard/src/data/audit-logs.ts
+++ /dev/null
@@ -1,90 +0,0 @@
-export const auditLogs = [
- {
- id: 3,
- timestamp: new Date("2025-05-05 12:00:00"),
- action: "incident.created" as const,
- },
- {
- id: 2,
- timestamp: new Date("2025-05-05 12:00:00"),
- action: "monitor.failed" as const,
- metadata: {
- region: "ams",
- status: 500,
- latency: 1400,
- } as const,
- },
- {
- id: 1,
- timestamp: new Date("2025-05-05 12:00:00"),
- action: "notification.sent" as const,
- metadata: {
- provider: "slack",
- } as const,
- },
- {
- id: 0,
- timestamp: new Date("2025-05-05 12:00:00"),
- action: "monitor.recovered" as const,
- metadata: {
- region: "ams",
- latency: 140,
- } as const,
- },
- {
- id: -1,
- timestamp: new Date("2025-05-05 12:00:00"),
- action: "monitor.degraded" as const,
- metadata: {
- region: "ams",
- latency: 30_000,
- } as const,
- },
- {
- id: -2,
- timestamp: new Date("2025-05-05 12:00:00"),
- action: "incident.resolved" as const,
- },
- {
- id: -3,
- timestamp: new Date("2025-05-05 12:00:00"),
- action: "incident.created" as const,
- },
- {
- id: -4,
- timestamp: new Date("2025-05-05 12:00:00"),
- action: "monitor.degraded" as const,
- metadata: {
- region: "ams",
- latency: 30_000,
- } as const,
- },
- {
- id: -5,
- timestamp: new Date("2025-05-05 12:00:00"),
- action: "monitor.degraded" as const,
- metadata: {
- region: "ams",
- latency: 32_000,
- } as const,
- },
- {
- id: -6,
- timestamp: new Date("2025-05-05 12:00:00"),
- action: "monitor.degraded" as const,
- metadata: {
- region: "ams",
- latency: 33_000,
- } as const,
- },
- {
- id: -7,
- timestamp: new Date("2025-05-05 12:00:00"),
- action: "monitor.degraded" as const,
- metadata: {
- region: "ams",
- latency: 34_000,
- } as const,
- },
-];
-export type AuditLog = (typeof auditLogs)[number];
diff --git a/apps/dashboard/src/data/icons.ts b/apps/dashboard/src/data/icons.ts
deleted file mode 100644
index 26724170a..000000000
--- a/apps/dashboard/src/data/icons.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-"use client";
-
-import { Monitor, Alert, Search, Resolved } from "@openstatus/icons";
-
-export const status = {
- resolved: Resolved,
- investigating: Alert,
- identified: Search,
- monitoring: Monitor,
-} as const;
-
-export const icons = {
- status,
-};
diff --git a/apps/dashboard/src/data/incidents.ts b/apps/dashboard/src/data/incidents.ts
deleted file mode 100644
index d4c242c45..000000000
--- a/apps/dashboard/src/data/incidents.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-export const incidents = [
- {
- id: 1,
- startedAt: new Date("2025-05-05 12:00:00"),
- acknowledged: null,
- resolvedAt: new Date("2025-05-05 14:00:00"),
- monitor: "OpenStatus API",
- },
-];
-
-export type Incident = (typeof incidents)[number];
diff --git a/apps/dashboard/src/data/invitations.ts b/apps/dashboard/src/data/invitations.ts
deleted file mode 100644
index 560d4d0c3..000000000
--- a/apps/dashboard/src/data/invitations.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-export const invitations = [
- {
- id: 1,
- email: "[email protected]",
- role: "member",
- createdAt: "2021-01-01",
- expiresAt: "2021-01-07",
- acceptedAt: "2021-01-02",
- },
-];
-
-export type Invitation = (typeof invitations)[number];
diff --git a/apps/dashboard/src/data/maintenances.ts b/apps/dashboard/src/data/maintenances.ts
deleted file mode 100644
index f8fce1470..000000000
--- a/apps/dashboard/src/data/maintenances.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-export const maintenances = [
- {
- id: 1,
- title: "DB Migration",
- message:
- "We are currently performing a db migration on our system and will be down for a few hours.",
- startDate: new Date("2025-04-01"),
- endDate: new Date("2025-04-02"),
- affected: ["OpenStatus API"],
- },
-];
-
-export type Maintenance = (typeof maintenances)[number];
diff --git a/apps/dashboard/src/data/members.ts b/apps/dashboard/src/data/members.ts
deleted file mode 100644
index 389ce7996..000000000
--- a/apps/dashboard/src/data/members.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-export const members = [
- {
- id: 1,
- name: "Maximilian Kaske",
- email: "[email protected]",
- role: "admin",
- createdAt: "2021-01-01",
- },
-];
-
-export type Member = (typeof members)[number];
diff --git a/apps/dashboard/src/data/monitor-tags.ts b/apps/dashboard/src/data/monitor-tags.ts
deleted file mode 100644
index ad2886162..000000000
--- a/apps/dashboard/src/data/monitor-tags.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-export const monitorTags = [
- {
- value: "production",
- label: "Production",
- color: "bg-green-500",
- },
- {
- value: "development",
- label: "Development",
- color: "bg-blue-500",
- },
- {
- value: "staging",
- label: "Staging",
- color: "bg-yellow-500",
- },
- {
- value: "testing",
- label: "Testing",
- color: "bg-purple-500",
- },
- {
- value: "api",
- label: "API",
- color: "bg-red-500",
- },
- {
- value: "database",
- label: "Database",
- color: "bg-orange-500",
- },
-];
-
-export type MonitorTag = (typeof monitorTags)[number];
diff --git a/apps/dashboard/src/data/monitors.ts b/apps/dashboard/src/data/monitors.ts
deleted file mode 100644
index 11a76c982..000000000
--- a/apps/dashboard/src/data/monitors.ts
+++ /dev/null
@@ -1,88 +0,0 @@
-export const monitors = [
- {
- id: 1,
- name: "OpenStatus Marketing",
- description: "Marketing website for OpenStatus",
- public: false,
- active: true,
- status: "Normal" as const,
- url: "https://openstatus.dev",
- tags: ["Production"],
- lastIncident: undefined,
- p50: 110,
- p90: 200,
- p99: 250,
- },
- {
- id: 2,
- name: "OpenStatus API",
- description: "API for OpenStatus",
- public: false,
- active: true,
- status: "Normal" as const,
- url: "https://api.openstatus.dev/v1/ping",
- tags: ["Production", "API"],
- lastIncident: undefined,
- p50: 34,
- p90: 201,
- p99: 530,
- },
- {
- id: 3,
- name: "OpenStatus App",
- description: "Dashboard for OpenStatus",
- public: false,
- active: true,
- status: "Failing" as const,
- url: "https://openstatus.dev/app",
- tags: ["Production"],
- lastIncident: "10 minutes ago",
- p50: 130,
- p90: 200,
- p99: 250,
- },
- {
- id: 4,
- name: "Lightweight OS",
- description: "Lightweight Operations System",
- public: false,
- active: false,
- status: "Inactive" as const,
- url: "https://data-table.openstatus.dev/light",
- tags: ["Development"],
- lastIncident: undefined,
- p50: undefined,
- p90: undefined,
- p99: undefined,
- },
- {
- id: 5,
- name: "Astro Status Page",
- description: "Status page for Astro",
- public: false,
- active: true,
- status: "Degraded" as const,
- url: "https://status.openstat.us",
- tags: ["Development"],
- lastIncident: undefined,
- p50: 130,
- p90: 201,
- p99: 250,
- },
- {
- id: 6,
- name: "Vercel Edge Ping",
- description: "Ping for Vercel Edge",
- public: false,
- active: true,
- status: "Normal" as const,
- url: "https://light.openstatus.dev",
- tags: ["Staging"],
- lastIncident: "15 days ago",
- p50: 30,
- p90: 240,
- p99: 400,
- },
-];
-
-export type Monitor = (typeof monitors)[number];
diff --git a/apps/dashboard/src/data/notifications.ts b/apps/dashboard/src/data/notifications.ts
deleted file mode 100644
index b03d57810..000000000
--- a/apps/dashboard/src/data/notifications.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-export const notifications = [
- {
- id: 1,
- name: "Email",
- provider: "email",
- value: "[email protected]",
- },
-];
-
-export type Notification = (typeof notifications)[number];
diff --git a/apps/dashboard/src/data/regions.ts b/apps/dashboard/src/data/regions.ts
deleted file mode 100644
index b2e0886bc..000000000
--- a/apps/dashboard/src/data/regions.ts
+++ /dev/null
@@ -1,385 +0,0 @@
-export const regions = [
- {
- code: "ams",
- location: "Amsterdam, Netherlands",
- flag: "🇳🇱",
- continent: "Europe",
- provider: "Fly",
- },
- {
- code: "arn",
- location: "Stockholm, Sweden",
- flag: "🇸🇪",
- continent: "Europe",
- provider: "Fly",
- },
- {
- code: "atl",
- location: "Atlanta, Georgia, USA",
- flag: "🇺🇸",
- continent: "North America",
- provider: "Fly",
- },
- {
- code: "bog",
- location: "Bogotá, Colombia",
- flag: "🇨🇴",
- continent: "South America",
- provider: "Fly",
- },
- {
- code: "bom",
- location: "Mumbai, India",
- flag: "🇮🇳",
- continent: "Asia",
- provider: "Fly",
- },
- {
- code: "bos",
- location: "Boston, Massachusetts, USA",
- flag: "🇺🇸",
- continent: "North America",
- provider: "Fly",
- },
- {
- code: "cdg",
- location: "Paris, France",
- flag: "🇫🇷",
- continent: "Europe",
- provider: "Fly",
- },
- {
- code: "den",
- location: "Denver, Colorado, USA",
- flag: "🇺🇸",
- continent: "North America",
- provider: "Fly",
- },
- {
- code: "dfw",
- location: "Dallas, Texas, USA",
- flag: "🇺🇸",
- continent: "North America",
- provider: "Fly",
- },
- {
- code: "ewr",
- location: "Secaucus, New Jersey, USA",
- flag: "🇺🇸",
- continent: "North America",
- provider: "Fly",
- },
- {
- code: "eze",
- location: "Ezeiza, Argentina",
- flag: "🇦🇷",
- continent: "South America",
- provider: "Fly",
- },
- {
- code: "fra",
- location: "Frankfurt, Germany",
- flag: "🇩🇪",
- continent: "Europe",
- provider: "Fly",
- },
- {
- code: "gdl",
- location: "Guadalajara, Mexico",
- flag: "🇲🇽",
- continent: "North America",
- provider: "Fly",
- },
- {
- code: "gig",
- location: "Rio de Janeiro, Brazil",
- flag: "🇧🇷",
- continent: "South America",
- provider: "Fly",
- },
- {
- code: "gru",
- location: "Sao Paulo, Brazil",
- flag: "🇧🇷",
- continent: "South America",
- provider: "Fly",
- },
- {
- code: "hkg",
- location: "Hong Kong, Hong Kong",
- flag: "🇭🇰",
- continent: "Asia",
- provider: "Fly",
- },
- {
- code: "iad",
- location: "Ashburn, Virginia, USA",
- flag: "🇺🇸",
- continent: "North America",
- provider: "Fly",
- },
- {
- code: "jnb",
- location: "Johannesburg, South Africa",
- flag: "🇿🇦",
- continent: "Africa",
- },
- {
- code: "lax",
- location: "Los Angeles, California, USA",
- flag: "🇺🇸",
- continent: "North America",
- provider: "Fly",
- },
- {
- code: "lhr",
- location: "London, United Kingdom",
- flag: "🇬🇧",
- continent: "Europe",
- provider: "Fly",
- },
- {
- code: "mad",
- location: "Madrid, Spain",
- flag: "🇪🇸",
- continent: "Europe",
- },
- {
- code: "mia",
- location: "Miami, Florida, USA",
- flag: "🇺🇸",
- continent: "North America",
- provider: "Fly",
- },
- {
- code: "nrt",
- location: "Tokyo, Japan",
- flag: "🇯🇵",
- continent: "Asia",
- provider: "Fly",
- },
- {
- code: "ord",
- location: "Chicago, Illinois, USA",
- flag: "🇺🇸",
- continent: "North America",
- },
- {
- code: "otp",
- location: "Bucharest, Romania",
- flag: "🇷🇴",
- continent: "Europe",
- provider: "Fly",
- },
- {
- code: "phx",
- location: "Phoenix, Arizona, USA",
- flag: "🇺🇸",
- continent: "North America",
- provider: "Fly",
- },
- {
- code: "qro",
- location: "Querétaro, Mexico",
- flag: "🇲🇽",
- continent: "North America",
- provider: "Fly",
- },
- {
- code: "scl",
- location: "Santiago, Chile",
- flag: "🇨🇱",
- continent: "South America",
- provider: "Fly",
- },
- {
- code: "sjc",
- location: "San Jose, California, USA",
- flag: "🇺🇸",
- continent: "North America",
- provider: "Fly",
- },
- {
- code: "sea",
- location: "Seattle, Washington, USA",
- flag: "🇺🇸",
- continent: "North America",
- provider: "Fly",
- },
- {
- code: "sin",
- location: "Singapore, Singapore",
- flag: "🇸🇬",
- continent: "Asia",
- provider: "Fly",
- },
- {
- code: "syd",
- location: "Sydney, Australia",
- flag: "🇦🇺",
- continent: "Oceania",
- provider: "Fly",
- },
- {
- code: "waw",
- location: "Warsaw, Poland",
- flag: "🇵🇱",
- continent: "Europe",
- provider: "Fly",
- },
- {
- code: "yul",
- location: "Montreal, Canada",
- flag: "🇨🇦",
- continent: "North America",
- provider: "Fly",
- },
- {
- code: "yyz",
- location: "Toronto, Canada",
- flag: "🇨🇦",
- continent: "North America",
- provider: "Fly",
- },
- {
- code: "koyeb_fra",
- location: "Frankfurt, Germany",
- flag: "🇩🇪",
- continent: "Europe",
- provider: "koyeb",
- },
- {
- code: "koyeb_par",
- location: "Paris, France",
- flag: "🇫🇷",
- continent: "Europe",
- provider: "koyeb",
- },
- {
- code: "koyeb_sfo",
- location: "San Francisco, USA",
- flag: "🇺🇸",
- continent: "North America",
- provider: "koyeb",
- },
- {
- code: "koyeb_sin",
- location: "Singapore, Singapore",
- flag: "🇸🇬",
- continent: "Asia",
- provider: "koyeb",
- },
- {
- code: "koyeb_tyo",
- location: "Tokyo, Japan",
- flag: "🇯🇵",
- continent: "Asia",
- provider: "koyeb",
- },
- {
- code: "koyeb_was",
- location: "Washington, USA",
- flag: "🇺🇸",
- continent: "North America",
- provider: "koyeb",
- },
- {
- code: "railway_us-west2",
- location: "California, USA",
- flag: "🇺🇸",
- continent: "North America",
- provider: "railway",
- },
- {
- code: "railway_us-east4-eqdc4a",
- location: "Virginia, USA",
- flag: "🇺🇸",
- continent: "North America",
- provider: "railway",
- },
- {
- code: "railway_europe-west4-drams3a",
- location: "Amsterdam, Netherlands",
- flag: "🇳🇱",
- continent: "Europe",
- provider: "railway",
- },
- {
- code: "railway_asia-southeast1-eqsg3a",
- location: "Singapore, Singapore",
- flag: "🇸🇬",
- continent: "Asia",
- provider: "railway",
- },
-] as const;
-
-export type Region = (typeof regions)[number]["code"];
-
-export const groupedRegions = regions.reduce(
- (acc, region) => {
- const continent = region.continent;
- if (!acc[continent]) {
- acc[continent] = [];
- }
- acc[continent].push(region.code);
- return acc;
- },
- {} as Record<string, Region[]>,
-);
-
-export const regionColors = {
- ams: "hsl(217.2 91.2% 59.8%)",
- arn: "hsl(238.7 83.5% 66.7%)",
- atl: "hsl(258.3 89.5% 66.3%)",
- bog: "hsl(270.7 91% 65.1%)",
- bom: "hsl(292.2 84.1% 60.6%)",
- bos: "hsl(330.4 81.2% 60.4%)",
- cdg: "hsl(349.7 89.2% 60.2%)",
- den: "hsl(215.4 16.3% 46.9%)",
- dfw: "hsl(220 8.9% 46.1%)",
- ewr: "hsl(240 3.8% 46.1%)",
- eze: "hsl(0 0% 45.1%)",
- fra: "hsl(25 5.3% 44.7%)",
- gdl: "hsl(0 84.2% 60.2%)",
- gig: "hsl(24.6 95% 53.1%)",
- gru: "hsl(37.7 92.1% 50.2%)",
- hkg: "hsl(45.4 93.4% 47.5%)",
- iad: "hsl(83.7 80.5% 44.3%)",
- jnb: "hsl(142.1 70.6% 45.3%)",
- lax: "hsl(160.1 84.1% 39.4%)",
- lhr: "hsl(173.4 80.4% 40%)",
- mad: "hsl(188.7 94.5% 42.7%)",
- mia: "hsl(198.6 88.7% 48.4%)",
- nrt: "hsl(217.2 91.2% 59.8%)",
- ord: "hsl(238.7 83.5% 66.7%)",
- otp: "hsl(258.3 89.5% 66.3%)",
- phx: "hsl(270.7 91% 65.1%)",
- qro: "hsl(292.2 84.1% 60.6%)",
- scl: "hsl(330.4 81.2% 60.4%)",
- sjc: "hsl(349.7 89.2% 60.2%)",
- sea: "hsl(215.4 16.3% 46.9%)",
- sin: "hsl(220 8.9% 46.1%)",
- syd: "hsl(240 3.8% 46.1%)",
- waw: "hsl(0 0% 45.1%)",
- yul: "hsl(25 5.3% 44.7%)",
- yyz: "hsl(0 84.2% 60.2%)",
-
- koyeb_fra: "hsl(25 5.3% 44.7%)",
- koyeb_par: "hsl(25 5.3% 44.7%)",
- koyeb_sin: "hsl(25 5.3% 44.7%)",
- koyeb_sfo: "hsl(0 0% 45.1%)",
- koyeb_tyo: "hsl(0 0% 45.1%)",
- koyeb_was: "hsl(0 0% 45.1%)",
-
- "railway_asia-southeast1-eqsg3a": "hsl(0 0% 45.1%)",
- "railway_europe-west4-drams3a": "hsl(0 0% 45.1%)",
- "railway_us-east4-eqdc4a": "hsl(0 0% 45.1%)",
- "railway_us-west2": "hsl(0 0% 45.1%)",
-} satisfies Record<Region, string>;
-
-export function getRegionColor(region: string) {
- if (region in regionColors) {
- return regionColors[region as keyof typeof regionColors];
- }
- return "hsl(0 0% 45.1%)";
-}
diff --git a/apps/dashboard/src/data/status-pages.ts b/apps/dashboard/src/data/status-pages.ts
deleted file mode 100644
index ef5a7bd1f..000000000
--- a/apps/dashboard/src/data/status-pages.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-export const statusPages = [
- {
- id: 1,
- name: "OpenStatus Status",
- description: "See our uptime history and status reports.",
- slug: "status",
- favicon: "https://openstatus.dev/favicon.ico",
- domain: "status.openstatus.dev",
- protected: true,
- showValues: false,
- // NOTE: the worst status of a report
- status: "degraded" as const,
- monitors: [],
- },
-];
-
-export type StatusPage = (typeof statusPages)[number];
diff --git a/apps/dashboard/src/data/status-reports.ts b/apps/dashboard/src/data/status-reports.ts
deleted file mode 100644
index f4575f107..000000000
--- a/apps/dashboard/src/data/status-reports.ts
+++ /dev/null
@@ -1,60 +0,0 @@
-export const statusReports = [
- {
- id: 1,
- name: "Downtime API",
- startedAt: new Date("2025-06-07 12:00:00"),
- updatedAt: new Date("2025-06-07 12:30:00"),
- status: "operational",
- updates: [
- {
- id: 2,
- status: "operational" as const,
- message:
- "Everything is under control, we continue to monitor the situation.",
- date: new Date("2025-06-07 12:30:00"),
- updatedAt: new Date("2025-06-07 12:30:00"),
- monitors: [1],
- },
- {
- id: 1,
- status: "investigating" as const,
- message:
- "Our hosting provider is having an increase of 400 errors. We are aware of the dependency and will be working on a solution to reduce the risk.",
- date: new Date("2025-06-07 12:00:00"),
- updatedAt: new Date("2025-06-07 12:00:00"),
- monitors: [1],
- },
- ],
- affected: ["OpenStatus API"],
- },
- {
- id: 2,
- name: "Downtime API",
- startedAt: new Date("2025-06-04 12:10:00"),
- updatedAt: new Date("2025-06-04 12:30:00"),
- status: "operational",
- updates: [
- {
- id: 2,
- status: "operational" as const,
- message:
- "Everything is under control, we continue to monitor the situation.",
- date: new Date("2025-06-04 12:30:00"),
- updatedAt: new Date("2025-06-04 12:30:00"),
- monitors: [1],
- },
- {
- id: 1,
- status: "investigating" as const,
- message:
- "Our hosting provider is having an increase of 400 errors. We are working on a solution to reduce the risk.",
- date: new Date("2025-06-04 12:00:00"),
- updatedAt: new Date("2025-06-04 12:00:00"),
- monitors: [1],
- },
- ],
- affected: ["OpenStatus API"],
- },
-];
-
-export type StatusReport = (typeof statusReports)[number];
diff --git a/apps/dashboard/src/data/subscribers.ts b/apps/dashboard/src/data/subscribers.ts
deleted file mode 100644
index 40c5584c1..000000000
--- a/apps/dashboard/src/data/subscribers.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-export const subscribers = [
- {
- id: "1",
- email: "[email protected]",
- createdAt: "2025-05-20",
- validatedAt: "2025-05-20",
- },
- {
- id: "2",
- email: "[email protected]",
- createdAt: "2025-05-20",
- validatedAt: "2025-05-20",
- },
-];
-
-export type Subscriber = (typeof subscribers)[number];
diff --git a/apps/dashboard/src/hooks/use-feature.ts b/apps/dashboard/src/hooks/use-feature.ts
deleted file mode 100644
index bb620ea4b..000000000
--- a/apps/dashboard/src/hooks/use-feature.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-import type { Feature } from "@openstatus/services";
-import { useQuery } from "@tanstack/react-query";
-
-import { useTRPC } from "@/lib/trpc/client";
-
-export function useFeature(feature: Feature) {
- const trpc = useTRPC();
- const { data: workspace } = useQuery(trpc.workspace.get.queryOptions());
-
- return workspace?.features.includes(feature) ?? false;
-}
diff --git a/apps/dashboard/src/lib/middleware/with-invitation.ts b/apps/dashboard/src/lib/middleware/with-invitation.ts
deleted file mode 100644
index e69de29bb..000000000
diff --git a/apps/server/src/libs/checker/utils.test.ts b/apps/server/src/libs/checker/utils.test.ts
index 683b66191..db21670db 100644
--- a/apps/server/src/libs/checker/utils.test.ts
+++ b/apps/server/src/libs/checker/utils.test.ts
@@ -52,7 +52,7 @@ test("getCheckerUrl rejects an unsupported job type", () => {
).toThrow(OpenStatusApiError);
});
-test("getCheckerPayload builds an ICMP payload without assertions", () => {
+test("getCheckerPayload marks the run as api-triggered", () => {
const payload = getCheckerPayload(
buildMonitor({
jobType: "icmp",
@@ -77,78 +77,14 @@ test("getCheckerPayload builds an ICMP payload without assertions", () => {
expect("url" in payload).toBe(false);
});
-test("getCheckerPayload builds a gRPC payload with its target configuration", () => {
- const payload = getCheckerPayload(
- buildMonitor({
- jobType: "grpc",
- url: "api.example.com:443",
- grpcService: "checkout.v1.CheckoutService",
- grpcTls: "tls_insecure",
- headers: [{ key: "authorization", value: "Bearer token" }],
- assertions:
- '[{"version":"v1","type":"status","compare":"eq","target":200}]',
- }),
- "active",
- );
-
- expect(payload).toMatchObject({
- uri: "api.example.com:443",
- service: "checkout.v1.CheckoutService",
- tls: "tls_insecure",
- headers: { authorization: "Bearer token" },
- trigger: "api",
- });
- expect("assertions" in payload).toBe(false);
-});
-
-// The column is nullable and only defaults on insert, so a row that predates
-// the default must still dial with verification on.
-test("getCheckerPayload defaults a gRPC monitor with no TLS mode to tls", () => {
- const payload = getCheckerPayload(
- buildMonitor({ jobType: "grpc", url: "api.example.com:443" }),
- "active",
- );
-
- expect(payload).toMatchObject({ tls: "tls" });
-});
-
-test("getCheckerPayload builds a DNS payload with assertions", () => {
- const payload = getCheckerPayload(
- buildMonitor({
- jobType: "dns",
- url: "openstatus.dev",
- assertions:
- '[{"version":"v1","type":"dnsRecord","record":"A","compare":"eq","target":"1.2.3.4"}]',
- }),
- "active",
- );
-
- expect(payload).toMatchObject({ uri: "openstatus.dev", trigger: "api" });
- expect("assertions" in payload).toBe(true);
-});
-
-test("getCheckerPayload forwards the OTel config when configured", () => {
- const payload = getCheckerPayload(
- buildMonitor({
- jobType: "icmp",
- url: "1.1.1.1",
- otelEndpoint: "https://otel.example.com:4318",
- otelHeaders: [{ key: "Authorization", value: "Basic dGVzdA==" }],
- }),
- "active",
- );
-
- expect(payload.otelConfig).toEqual({
- endpoint: "https://otel.example.com:4318",
- headers: { Authorization: "Basic dGVzdA==" },
- });
-});
+test("getCheckerPayload rejects an unsupported job type as a bad request", () => {
+ let error: unknown;
+ try {
+ getCheckerPayload(buildMonitor({ jobType: "udp" }), "active");
+ } catch (err) {
+ error = err;
+ }
-test("getCheckerPayload rejects an unsupported job type", () => {
- expect(() =>
- getCheckerPayload(
- buildMonitor({ jobType: "unknown" as Monitor["jobType"] }),
- "active",
- ),
- ).toThrow(OpenStatusApiError);
+ expect(error).toBeInstanceOf(OpenStatusApiError);
+ expect(error).toMatchObject({ code: "BAD_REQUEST", status: 400 });
});
diff --git a/apps/server/src/libs/checker/utils.ts b/apps/server/src/libs/checker/utils.ts
index 32194e8b2..c6eac5eb3 100644
--- a/apps/server/src/libs/checker/utils.ts
+++ b/apps/server/src/libs/checker/utils.ts
@@ -1,12 +1,9 @@
import type { z } from "@hono/zod-openapi";
import type { selectMonitorSchema } from "@openstatus/db/src/schema";
import {
- type DNSPayloadSchema,
- type httpPayloadSchema,
- type grpcPayloadSchema,
- type icmpPayloadSchema,
- type tpcPayloadSchema,
- transformHeaders,
+ type CheckerPayload,
+ buildCheckerPayload,
+ isCheckerJobType,
} from "@openstatus/utils";
import { OpenStatusApiError } from "@/libs/errors";
@@ -14,123 +11,20 @@ import { OpenStatusApiError } from "@/libs/errors";
export function getCheckerPayload(
monitor: z.infer<typeof selectMonitorSchema>,
status: z.infer<typeof selectMonitorSchema>["status"],
-):
- | z.infer<typeof httpPayloadSchema>
- | z.infer<typeof tpcPayloadSchema>
- | z.infer<typeof DNSPayloadSchema>
- | z.infer<typeof icmpPayloadSchema>
- | z.infer<typeof grpcPayloadSchema> {
- const timestamp = new Date().getTime();
- switch (monitor.jobType) {
- case "http":
- return {
- workspaceId: String(monitor.workspaceId),
- monitorId: String(monitor.id),
- url: monitor.url,
- method: monitor.method || "GET",
- cronTimestamp: timestamp,
- body: monitor.body,
- headers: monitor.headers,
- status: status,
- assertions: monitor.assertions ? JSON.parse(monitor.assertions) : null,
- degradedAfter: monitor.degradedAfter,
- timeout: monitor.timeout,
- trigger: "api",
- otelConfig: monitor.otelEndpoint
- ? {
- endpoint: monitor.otelEndpoint,
- headers: transformHeaders(monitor.otelHeaders),
- }
- : undefined,
- retry: monitor.retry ?? 0,
- followRedirects: monitor.followRedirects ?? false,
- };
- case "tcp":
- return {
- workspaceId: String(monitor.workspaceId),
- monitorId: String(monitor.id),
- uri: monitor.url,
- status: status,
- assertions: monitor.assertions ? JSON.parse(monitor.assertions) : null,
- cronTimestamp: timestamp,
- degradedAfter: monitor.degradedAfter,
- timeout: monitor.timeout,
- trigger: "api",
- otelConfig: monitor.otelEndpoint
- ? {
- endpoint: monitor.otelEndpoint,
- headers: transformHeaders(monitor.otelHeaders),
- }
- : undefined,
- retry: monitor.retry ?? 0,
- followRedirects: monitor.followRedirects ?? false,
- };
- case "dns":
- return {
- workspaceId: String(monitor.workspaceId),
- monitorId: String(monitor.id),
- uri: monitor.url,
- status: status,
- assertions: monitor.assertions ? JSON.parse(monitor.assertions) : null,
- cronTimestamp: timestamp,
- degradedAfter: monitor.degradedAfter,
- timeout: monitor.timeout,
- trigger: "api",
- otelConfig: monitor.otelEndpoint
- ? {
- endpoint: monitor.otelEndpoint,
- headers: transformHeaders(monitor.otelHeaders),
- }
- : undefined,
- retry: monitor.retry ?? 0,
- };
- case "icmp":
- // No assertions: an ICMP check only reports reachability and latency.
- return {
- workspaceId: String(monitor.workspaceId),
- monitorId: String(monitor.id),
- uri: monitor.url,
- status: status,
- cronTimestamp: timestamp,
- degradedAfter: monitor.degradedAfter,
- timeout: monitor.timeout,
- trigger: "api",
- otelConfig: monitor.otelEndpoint
- ? {
- endpoint: monitor.otelEndpoint,
- headers: transformHeaders(monitor.otelHeaders),
- }
- : undefined,
- retry: monitor.retry ?? 0,
- };
- case "grpc":
- // No assertions: a gRPC health check only reports the serving status.
- return {
- workspaceId: String(monitor.workspaceId),
- monitorId: String(monitor.id),
- uri: monitor.url,
- service: monitor.grpcService ?? undefined,
- tls: monitor.grpcTls ?? "tls",
- headers: transformHeaders(monitor.headers),
- status: status,
- cronTimestamp: timestamp,
- degradedAfter: monitor.degradedAfter,
- timeout: monitor.timeout,
- trigger: "api",
- otelConfig: monitor.otelEndpoint
- ? {
- endpoint: monitor.otelEndpoint,
- headers: transformHeaders(monitor.otelHeaders),
- }
- : undefined,
- retry: monitor.retry ?? 0,
- };
- default:
- throw new OpenStatusApiError({
- code: "BAD_REQUEST",
- message: `Invalid jobType '${monitor.jobType}'`,
- });
+): CheckerPayload {
+ // The v1 routes build the payload before the URL, so reject here to keep a 400.
+ if (!isCheckerJobType(monitor.jobType)) {
+ throw new OpenStatusApiError({
+ code: "BAD_REQUEST",
+ message: `Invalid jobType '${monitor.jobType}'`,
+ });
}
+ return buildCheckerPayload({
+ monitor,
+ status,
+ trigger: "api",
+ timestamp: Date.now(),
+ });
}
// Bounds outbound checker fetches so a slow check can't pin API requests open
diff --git a/apps/server/src/routes/rpc/handlers/status-page/converters.ts b/apps/server/src/routes/rpc/handlers/status-page/converters.ts
index 978759f8b..1fbc5544f 100644
--- a/apps/server/src/routes/rpc/handlers/status-page/converters.ts
+++ b/apps/server/src/routes/rpc/handlers/status-page/converters.ts
@@ -14,7 +14,6 @@ import {
ComponentDayStatus,
ComponentEventStatus,
ComponentEventType,
- OverallStatus,
PageAccessType,
PageBarType,
PageComponentType,
@@ -515,14 +514,3 @@ export function dbSubscriberToProto(
componentIds: (subscriber.componentIds ?? []).map(String),
};
}
-
-/**
- * Get overall status based on component statuses.
- * This is a placeholder - the actual implementation would look at
- * monitor statuses, active incidents, and maintenance windows.
- */
-export function getOverallStatusValue(): OverallStatus {
- // Default to operational - in a real implementation this would
- // aggregate status from monitors and incidents
- return OverallStatus.OPERATIONAL;
-}
diff --git a/apps/status-page/src/components/chart/chart-line-region.tsx b/apps/status-page/src/components/chart/chart-line-region.tsx
deleted file mode 100644
index f8ab945db..000000000
--- a/apps/status-page/src/components/chart/chart-line-region.tsx
+++ /dev/null
@@ -1,93 +0,0 @@
-"use client";
-
-import {
- type ChartConfig,
- ChartContainer,
- ChartTooltip,
- ChartTooltipContent,
-} from "@openstatus/ui/components/ui/chart";
-import { cn } from "@openstatus/ui/lib/utils";
-import { CartesianGrid, Line, LineChart, XAxis, YAxis } from "recharts";
-
-import { ChartTooltipNumber } from "./chart-tooltip-number";
-
-const chartConfig = {
- latency: {
- label: "Latency",
- color: "var(--success)",
- },
-} satisfies ChartConfig;
-
-export type TrendPoint = {
- timestamp: number; // unix millis
- latency: number; // milliseconds
-};
-
-export function ChartLineRegion({
- className,
- data,
-}: {
- className?: string;
- data: TrendPoint[];
-}) {
- const trendData = data ?? [];
-
- const chartData = trendData.map((d) => ({
- timestamp: new Date(d.timestamp).toLocaleString("default", {
- hour: "numeric",
- minute: "numeric",
- day: "numeric",
- month: "short",
- }),
- latency: d.latency,
- }));
-
- return (
- <ChartContainer
- config={chartConfig}
- className={cn("h-[100px] w-full", className)}
- >
- <LineChart
- accessibilityLayer
- data={chartData}
- margin={{
- left: 12,
- right: 12,
- }}
- >
- <CartesianGrid vertical={false} />
- <XAxis dataKey="timestamp" hide />
- <ChartTooltip
- cursor={false}
- content={
- <ChartTooltipContent
- className="w-[180px]"
- formatter={(value, name) => (
- <ChartTooltipNumber
- chartConfig={chartConfig}
- value={value}
- name={name}
- />
- )}
- />
- }
- />
- <Line
- dataKey="latency"
- type="monotone"
- stroke="var(--color-latency)"
- strokeWidth={2}
- dot={false}
- />
- <YAxis
- domain={["dataMin", "dataMax"]}
- tickLine={false}
- axisLine={false}
- tickMargin={8}
- orientation="right"
- tickFormatter={(value) => `${value}ms`}
- />
- </LineChart>
- </ChartContainer>
- );
-}
diff --git a/apps/status-page/src/components/icons/discord.tsx b/apps/status-page/src/components/icons/discord.tsx
deleted file mode 100644
index 440d493fe..000000000
--- a/apps/status-page/src/components/icons/discord.tsx
+++ /dev/null
@@ -1,15 +0,0 @@
-export function DiscordIcon(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>Discord</title>
- <path d="M20.317 4.3698a19.7913 19.7913 0 00-4.8851-1.5152.0741.0741 0 00-.0785.0371c-.211.3753-.4447.8648-.6083 1.2495-1.8447-.2762-3.68-.2762-5.4868 0-.1636-.3933-.4058-.8742-.6177-1.2495a.077.077 0 00-.0785-.037 19.7363 19.7363 0 00-4.8852 1.515.0699.0699 0 00-.0321.0277C.5334 9.0458-.319 13.5799.0992 18.0578a.0824.0824 0 00.0312.0561c2.0528 1.5076 4.0413 2.4228 5.9929 3.0294a.0777.0777 0 00.0842-.0276c.4616-.6304.8731-1.2952 1.226-1.9942a.076.076 0 00-.0416-.1057c-.6528-.2476-1.2743-.5495-1.8722-.8923a.077.077 0 01-.0076-.1277c.1258-.0943.2517-.1923.3718-.2914a.0743.0743 0 01.0776-.0105c3.9278 1.7933 8.18 1.7933 12.0614 0a.0739.0739 0 01.0785.0095c.1202.099.246.1981.3728.2924a.077.077 0 01-.0066.1276 12.2986 12.2986 0 01-1.873.8914.0766.0766 0 00-.0407.1067c.3604.698.7719 1.3628 1.225 1.9932a.076.076 0 00.0842.0286c1.961-.6067 3.9495-1.5219 6.0023-3.0294a.077.077 0 00.0313-.0552c.5004-5.177-.8382-9.6739-3.5485-13.6604a.061.061 0 00-.0312-.0286zM8.02 15.3312c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9555-2.4189 2.157-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.9555 2.4189-2.1569 2.4189zm7.9748 0c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9554-2.4189 2.1569-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.946 2.4189-2.1568 2.4189Z" />
- </svg>
- );
-}
diff --git a/apps/status-page/src/components/icons/github.tsx b/apps/status-page/src/components/icons/github.tsx
deleted file mode 100644
index 93fb97670..000000000
--- a/apps/status-page/src/components/icons/github.tsx
+++ /dev/null
@@ -1,15 +0,0 @@
-export function GitHubIcon(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>GitHub</title>
- <path d="M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12" />
- </svg>
- );
-}
diff --git a/apps/status-page/src/components/icons/google.tsx b/apps/status-page/src/components/icons/google.tsx
deleted file mode 100644
index 93a9b9b3c..000000000
--- a/apps/status-page/src/components/icons/google.tsx
+++ /dev/null
@@ -1,15 +0,0 @@
-export function GoogleIcon(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>Google</title>
- <path d="M12.48 10.92v3.28h7.84c-.24 1.84-.853 3.187-1.787 4.133-1.147 1.147-2.933 2.4-6.053 2.4-4.827 0-8.6-3.893-8.6-8.72s3.773-8.72 8.6-8.72c2.6 0 4.507 1.027 5.907 2.347l2.307-2.307C18.747 1.44 16.133 0 12.48 0 5.867 0 .307 5.387.307 12s5.56 12 12.173 12c3.573 0 6.267-1.173 8.373-3.36 2.16-2.16 2.84-5.213 2.84-7.667 0-.76-.053-1.467-.173-2.053H12.48z" />
- </svg>
- );
-}
diff --git a/apps/status-page/src/components/icons/opsgenie.tsx b/apps/status-page/src/components/icons/opsgenie.tsx
deleted file mode 100644
index 6bc29e1dc..000000000
--- a/apps/status-page/src/components/icons/opsgenie.tsx
+++ /dev/null
@@ -1,15 +0,0 @@
-export function OpsGenieIcon(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>Opsgenie</title>
- <path d="M12.002 0a5.988 5.988 0 1 1 0 11.975 5.988 5.988 0 0 1 0-11.975zm9.723 13.026h-.03l-4.527-2.242a.671.671 0 0 0-.876.268 22.408 22.408 0 0 1-4.306 5.217 22.407 22.407 0 0 1-4.286-5.2.671.671 0 0 0-.876-.269l-4.535 2.226h-.03a.671.671 0 0 0-.248.902 28.85 28.85 0 0 0 4.55 5.933l-.002.001c.024.025.05.048.075.072.335.335.676.664 1.027.981.081.074.165.144.247.217.315.278.632.555.96.82.144.117.295.227.441.341.277.216.552.434.837.639.44.318.888.625 1.346.917a.963.963 0 0 0 1.007.017c.487-.312.962-.64 1.428-.98.068-.05.132-.103.2-.153.358-.266.713-.537 1.06-.82.234-.19.46-.39.688-.588.17-.147.34-.291.506-.442.295-.268.58-.545.864-.825.061-.06.127-.118.188-.179l-.004-.002a28.852 28.852 0 0 0 4.565-5.949.671.671 0 0 0-.269-.902z" />
- </svg>
- );
-}
diff --git a/apps/status-page/src/components/icons/pagerduty.tsx b/apps/status-page/src/components/icons/pagerduty.tsx
deleted file mode 100644
index 4681b18ae..000000000
--- a/apps/status-page/src/components/icons/pagerduty.tsx
+++ /dev/null
@@ -1,15 +0,0 @@
-export function PagerDutyIcon(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>PagerDuty</title>
- <path d="M16.965 1.18C15.085.164 13.769 0 10.683 0H3.73v14.55h6.926c2.743 0 4.8-.164 6.61-1.37 1.975-1.303 3.004-3.484 3.004-6.007 0-2.716-1.262-4.896-3.305-5.994zm-5.5 10.326h-4.21V3.113l3.977-.027c3.62-.028 5.43 1.234 5.43 4.128 0 3.113-2.248 4.292-5.197 4.292zM3.73 17.61h3.525V24H3.73Z" />
- </svg>
- );
-}
diff --git a/apps/status-page/src/components/icons/slack.tsx b/apps/status-page/src/components/icons/slack.tsx
deleted file mode 100644
index c5f2683c6..000000000
--- a/apps/status-page/src/components/icons/slack.tsx
+++ /dev/null
@@ -1,15 +0,0 @@
-export function SlackIcon(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>Slack</title>
- <path d="M5.042 15.165a2.528 2.528 0 0 1-2.52 2.523A2.528 2.528 0 0 1 0 15.165a2.527 2.527 0 0 1 2.522-2.52h2.52v2.52zM6.313 15.165a2.527 2.527 0 0 1 2.521-2.52 2.527 2.527 0 0 1 2.521 2.52v6.313A2.528 2.528 0 0 1 8.834 24a2.528 2.528 0 0 1-2.521-2.522v-6.313zM8.834 5.042a2.528 2.528 0 0 1-2.521-2.52A2.528 2.528 0 0 1 8.834 0a2.528 2.528 0 0 1 2.521 2.522v2.52H8.834zM8.834 6.313a2.528 2.528 0 0 1 2.521 2.521 2.528 2.528 0 0 1-2.521 2.521H2.522A2.528 2.528 0 0 1 0 8.834a2.528 2.528 0 0 1 2.522-2.521h6.312zM18.956 8.834a2.528 2.528 0 0 1 2.522-2.521A2.528 2.528 0 0 1 24 8.834a2.528 2.528 0 0 1-2.522 2.521h-2.522V8.834zM17.688 8.834a2.528 2.528 0 0 1-2.523 2.521 2.527 2.527 0 0 1-2.52-2.521V2.522A2.527 2.527 0 0 1 15.165 0a2.528 2.528 0 0 1 2.523 2.522v6.312zM15.165 18.956a2.528 2.528 0 0 1 2.523 2.522A2.528 2.528 0 0 1 15.165 24a2.527 2.527 0 0 1-2.52-2.522v-2.522h2.52zM15.165 17.688a2.527 2.527 0 0 1-2.52-2.523 2.526 2.526 0 0 1 2.52-2.52h6.313A2.527 2.527 0 0 1 24 15.165a2.528 2.528 0 0 1-2.522 2.523h-6.313z" />
- </svg>
- );
-}
diff --git a/apps/status-page/src/components/status-page/status-calendar.tsx b/apps/status-page/src/components/status-page/status-calendar.tsx
deleted file mode 100644
index c2c76eae1..000000000
--- a/apps/status-page/src/components/status-page/status-calendar.tsx
+++ /dev/null
@@ -1,189 +0,0 @@
-"use client";
-
-import type { RouterOutputs } from "@openstatus/api";
-import { dateFnsLocales } from "@openstatus/locales";
-import { StatusBarEvent } from "@openstatus/ui/components/blocks/status-bar";
-import {
- StatusCalendar as BlockStatusCalendar,
- StatusCalendarSkeleton as BlockStatusCalendarSkeleton,
- type StatusCalendarMarker,
- type StatusCalendarProps,
- type StatusCalendarSkeletonProps,
-} from "@openstatus/ui/components/blocks/status-calendar";
-import { useStatusBlocksLabels } from "@openstatus/ui/components/blocks/status-i18n";
-import {
- eachDayOfInterval,
- max as maxDate,
- min as minDate,
- startOfDay,
-} from "date-fns";
-import { useLocale } from "next-intl";
-import { useCallback, useMemo } from "react";
-
-import { usePathnamePrefix } from "../../hooks/use-pathname-prefix";
-import type { Locale as AppLocale } from "../../i18n/config";
-import { Link } from "../common/link";
-
-type Page = NonNullable<RouterOutputs["statusPage"]["get"]>;
-type ReportInput = Page["statusReports"][number];
-type MaintenanceInput = Page["maintenances"][number];
-type PageComponentInput = Page["pageComponents"][number];
-
-type Props = Omit<StatusCalendarProps, "markers" | "renderMarkerRow"> & {
- statusReports?: ReportInput[];
- maintenances?: MaintenanceInput[];
- pageComponents?: PageComponentInput[];
- /**
- * Mirrors the bar's loading pattern (`status-bar.tsx` consumer): when true,
- * the wrapper renders `<StatusCalendarSkeleton>` instead of the calendar.
- * Wire this to the parent's data-fetch loading state.
- */
- isLoading?: boolean;
-};
-
-// Marker color is keyed by event TYPE (not status) so resolved historical
-// outages still show as red/yellow rather than green. Mirrors StatusBarEvent.
-
-export function StatusCalendar({
- statusReports = [],
- maintenances = [],
- pageComponents = [],
- isLoading,
- ...rest
-}: Props) {
- const labels = useStatusBlocksLabels();
- const locale = useLocale() as AppLocale;
- const dateFnsLocale = dateFnsLocales[locale];
- const prefix = usePathnamePrefix();
- const base = prefix ? `/${prefix}` : "";
- const downtimeLabel = labels.systemStatus.error.short;
- const calendarTitle = labels.calendarTitle;
-
- const markers = useMemo<StatusCalendarMarker[]>(() => {
- const out: StatusCalendarMarker[] = [];
-
- for (const report of statusReports) {
- const updates = report.statusReportUpdates
- .slice()
- .sort((a, b) => a.date.getTime() - b.date.getTime());
- const firstUpdate = updates[0];
- const lastUpdate = updates[updates.length - 1];
- const startedAt = firstUpdate?.date ?? report.createdAt;
- if (!startedAt) continue;
- // Null (ongoing) unless a resolved update gives a real end date.
- const resolvedAt =
- report.status === "resolved" && lastUpdate?.status === "resolved"
- ? lastUpdate.date
- : null;
-
- out.push({
- id: `report-${report.id}`,
- date: startOfDay(startedAt),
- status: "degraded",
- type: "report",
- name: report.title,
- from: startedAt,
- to: resolvedAt,
- href: `${base}/events/report/${report.id}`,
- });
- }
-
- for (const m of maintenances) {
- const start = startOfDay(minDate([m.from, m.to]));
- const end = startOfDay(maxDate([m.from, m.to]));
- const href = `${base}/events/maintenance/${m.id}`;
- for (const day of eachDayOfInterval({ start, end })) {
- out.push({
- id: `maintenance-${m.id}-${day.toISOString()}`,
- date: day,
- status: "info",
- type: "maintenance",
- name: m.title,
- from: m.from,
- to: m.to,
- href,
- });
- }
- }
-
- const seenIncidents = new Set<number>();
- for (const c of pageComponents) {
- const incidents = c.monitor?.monitorIncidents ?? [];
- for (const inc of incidents) {
- if (seenIncidents.has(inc.id)) continue;
- seenIncidents.add(inc.id);
- const startedAt = inc.startedAt;
- const end = startOfDay(inc.resolvedAt ?? new Date());
- const start = startOfDay(startedAt);
- for (const day of eachDayOfInterval({ start, end })) {
- out.push({
- id: `incident-${inc.id}-${day.toISOString()}`,
- date: day,
- status: "error",
- type: "incident",
- // `incident.title` is empty string on the DB row by default; use
- // the localized "Downtime" label as a sensible fallback.
- name: inc.title?.trim() ? inc.title : downtimeLabel,
- from: startedAt,
- to: inc.resolvedAt,
- });
- }
- }
- }
-
- return out;
- }, [statusReports, maintenances, pageComponents, downtimeLabel, base]);
-
- const renderMarkerRow = useCallback((marker: StatusCalendarMarker) => {
- const event = (
- <StatusBarEvent
- type={marker.type}
- name={marker.name}
- from={marker.from}
- to={marker.to}
- isAggregated={marker.isAggregated}
- />
- );
- if (marker.href) {
- return (
- <Link
- variant="unstyled"
- href={marker.href}
- className="hover:bg-accent/50 block cursor-pointer rounded-sm"
- >
- {event}
- </Link>
- );
- }
- return event;
- }, []);
-
- if (isLoading) {
- return <BlockStatusCalendarSkeleton title={calendarTitle} />;
- }
-
- return (
- <BlockStatusCalendar
- title={calendarTitle}
- locale={dateFnsLocale}
- markers={markers}
- renderMarkerRow={renderMarkerRow}
- eventTypes={["report", "maintenance"]}
- disableFuture
- {...rest}
- />
- );
-}
-
-/**
- * App-side skeleton wrapper that injects the localized "Calendar" title.
- * Use while the status-page data is in flight.
- */
-export function StatusCalendarSkeleton(
- props: Omit<StatusCalendarSkeletonProps, "title">,
-) {
- const labels = useStatusBlocksLabels();
- return (
- <BlockStatusCalendarSkeleton title={labels.calendarTitle} {...props} />
- );
-}
diff --git a/apps/status-page/src/components/status-page/utils.test.ts b/apps/status-page/src/components/status-page/utils.test.ts
deleted file mode 100644
index 1e776f375..000000000
--- a/apps/status-page/src/components/status-page/utils.test.ts
+++ /dev/null
@@ -1,87 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import {
- type ChartData,
- getHighestPriorityStatus,
- getHighestStatus,
- getPercentagePriorityStatus,
-} from "./utils";
-
-function day(
- counts: Partial<Pick<ChartData, "success" | "degraded" | "error" | "info">>,
-): ChartData {
- return {
- timestamp: 0,
- success: 0,
- degraded: 0,
- error: 0,
- info: 0,
- ...counts,
- };
-}
-
-describe("getHighestPriorityStatus", () => {
- it("returns empty for a day without data", () => {
- expect(getHighestPriorityStatus(day({}))).toBe("empty");
- });
-
- it("ranks error over degraded over info over success", () => {
- expect(
- getHighestPriorityStatus(
- day({ success: 1, info: 1, degraded: 1, error: 1 }),
- ),
- ).toBe("error");
- expect(
- getHighestPriorityStatus(day({ success: 1, info: 1, degraded: 1 })),
- ).toBe("degraded");
- expect(getHighestPriorityStatus(day({ success: 1, info: 1 }))).toBe("info");
- expect(getHighestPriorityStatus(day({ success: 1 }))).toBe("success");
- });
-
- it("lets a single error minute outrank a full day of success", () => {
- expect(getHighestPriorityStatus(day({ success: 1439, error: 1 }))).toBe(
- "error",
- );
- });
-});
-
-describe("getPercentagePriorityStatus", () => {
- it("returns empty for a day without data", () => {
- expect(getPercentagePriorityStatus(day({}))).toBe("empty");
- });
-
- it("applies the 95% and 75% success thresholds", () => {
- expect(getPercentagePriorityStatus(day({ success: 95, error: 5 }))).toBe(
- "success",
- );
- expect(getPercentagePriorityStatus(day({ success: 94, error: 6 }))).toBe(
- "degraded",
- );
- expect(getPercentagePriorityStatus(day({ success: 75, error: 25 }))).toBe(
- "degraded",
- );
- expect(getPercentagePriorityStatus(day({ success: 74, error: 26 }))).toBe(
- "error",
- );
- });
-
- it("treats a day with no successful checks as error", () => {
- expect(getPercentagePriorityStatus(day({ error: 10 }))).toBe("error");
- expect(getPercentagePriorityStatus(day({ info: 10 }))).toBe("error");
- });
-});
-
-describe("getHighestStatus", () => {
- it("picks the most severe status", () => {
- expect(getHighestStatus(["success", "info", "degraded", "error"])).toBe(
- "error",
- );
- expect(getHighestStatus(["success", "info", "degraded"])).toBe("degraded");
- expect(getHighestStatus(["success", "info"])).toBe("info");
- expect(getHighestStatus(["success"])).toBe("success");
- });
-
- it("defaults to success for an empty list", () => {
- expect(getHighestStatus([])).toBe("success");
- });
-});
diff --git a/apps/status-page/src/components/status-page/utils.ts b/apps/status-page/src/components/status-page/utils.ts
deleted file mode 100644
index 1cd9ff749..000000000
--- a/apps/status-page/src/components/status-page/utils.ts
+++ /dev/null
@@ -1,117 +0,0 @@
-import type { ChartConfig } from "@openstatus/ui/components/ui/chart";
-
-import { VARIANT, type VariantType } from "./floating-button";
-
-export const chartData = Array.from({ length: 45 }, (_, i) => {
- const date = new Date();
- date.setDate(date.getDate() - i);
-
- // Simulate realistic daily status distribution that sums to 1440 minutes
- let error = 0;
- let degraded = 0;
- let success = 1440; // Start with all minutes as ok
- let info = 0;
-
- // Simulate some incidents on certain days
- if (i === 3) {
- // Day 3: Major incident for 2 hours (120 minutes)
- error = 120;
- success -= error;
- } else if (i === 16) {
- // Day 16: Degraded performance for 4 hours (240 minutes)
- degraded = 240;
- success -= degraded;
- } else if (i === 8) {
- // Day 8: Brief outage (30 minutes) + some degraded performance (60 minutes)
- error = 30;
- degraded = 60;
- success -= error + degraded;
- } else if (i === 13) {
- info = 120;
- success -= info;
- } else if (i === 22) {
- // Day 22: Extended degraded performance (6 hours = 360 minutes)
- degraded = 360;
- success -= degraded;
- } else if (Math.random() > 0.85) {
- // Random minor issues on some days (5-15 minutes of degraded performance)
- degraded = Math.floor(Math.random() * 10) + 5;
- success -= degraded;
- }
-
- return {
- timestamp: date.getTime(),
- info,
- degraded,
- error,
- success,
- };
-}).reverse();
-
-export type ChartData = (typeof chartData)[number];
-
-export const chartConfig = {
- success: {
- label: "success",
- color: "var(--success)",
- },
- degraded: {
- label: "degraded",
- color: "var(--warning)",
- },
- error: {
- label: "error",
- color: "var(--destructive)",
- },
- info: {
- label: "info",
- color: "var(--info)",
- },
- empty: {
- label: "empty",
- color: "var(--muted)",
- },
-} satisfies ChartConfig;
-
-export const PRIORITY = {
- error: 3,
- degraded: 2,
- info: 1,
- success: 0,
-} as const; // satisfies Record<XXX, number>;
-
-export function getHighestPriorityStatus(item: ChartData) {
- const total = item.success + item.degraded + item.info + item.error;
- if (total === 0) return "empty";
- return (
- VARIANT.filter((status) => item[status] > 0).sort(
- (a, b) => PRIORITY[b] - PRIORITY[a],
- )[0] || "empty"
- );
-}
-
-export const PERCENTAGE_PRIORITY = {
- info: -1,
- error: 0,
- degraded: 0.75,
- success: 0.95,
-} as const;
-
-export function getPercentagePriorityStatus(item: ChartData) {
- const total = item.success + item.degraded + item.info + item.error;
- if (total === 0) return "empty";
-
- const percentage = item.success / total;
- if (percentage >= PERCENTAGE_PRIORITY.success) return "success";
- if (percentage >= PERCENTAGE_PRIORITY.degraded) return "degraded";
- if (percentage >= PERCENTAGE_PRIORITY.error) return "error";
- if (percentage >= PERCENTAGE_PRIORITY.info) return "info";
- return "info";
-}
-
-export function getHighestStatus(items: VariantType[]) {
- if (items.some((item) => item === "error")) return "error";
- if (items.some((item) => item === "degraded")) return "degraded";
- if (items.some((item) => item === "info")) return "info";
- return "success";
-}
diff --git a/apps/status-page/src/components/ui/data-table/data-table-action-bar.tsx b/apps/status-page/src/components/ui/data-table/data-table-action-bar.tsx
deleted file mode 100644
index 7fc78b9d6..000000000
--- a/apps/status-page/src/components/ui/data-table/data-table-action-bar.tsx
+++ /dev/null
@@ -1,175 +0,0 @@
-"use client";
-
-import { Button } from "@openstatus/ui/components/ui/button";
-import { Separator } from "@openstatus/ui/components/ui/separator";
-import {
- Tooltip,
- TooltipContent,
- TooltipTrigger,
-} from "@openstatus/ui/components/ui/tooltip";
-import { cn } from "@openstatus/ui/lib/utils";
-import type { Table } from "@tanstack/react-table";
-import { Loader, X } from "lucide-react";
-import * as React from "react";
-import * as ReactDOM from "react-dom";
-
-export interface DataTableActionBarProps<
- TData,
-> extends React.ComponentProps<"div"> {
- table: Table<TData>;
- visible?: boolean;
- container?: Element | DocumentFragment | null;
-}
-
-function DataTableActionBar<TData>({
- table,
- visible: visibleProp,
- container: containerProp,
- children,
- className,
- ...props
-}: DataTableActionBarProps<TData>) {
- const [mounted, setMounted] = React.useState(false);
-
- React.useLayoutEffect(() => {
- setMounted(true);
- }, []);
-
- React.useEffect(() => {
- function onKeyDown(event: KeyboardEvent) {
- if (event.key === "Escape") {
- table.toggleAllRowsSelected(false);
- }
- }
-
- window.addEventListener("keydown", onKeyDown);
- return () => window.removeEventListener("keydown", onKeyDown);
- }, [table]);
-
- const container =
- containerProp ?? (mounted ? globalThis.document?.body : null);
-
- if (!container) return null;
-
- const visible =
- visibleProp ?? table.getFilteredSelectedRowModel().rows.length > 0;
-
- return ReactDOM.createPortal(
- <div>
- {visible && (
- <div
- role="toolbar"
- aria-orientation="horizontal"
- className={cn(
- "bg-background text-foreground fixed inset-x-0 bottom-6 z-50 mx-auto flex w-fit flex-wrap items-center justify-center gap-2 rounded-md border p-2 shadow-sm",
- className,
- )}
- {...props}
- >
- {children}
- </div>
- )}
- </div>,
- container,
- );
-}
-
-interface DataTableActionBarActionProps extends React.ComponentProps<
- typeof Button
-> {
- tooltip?: string;
- isPending?: boolean;
-}
-
-function DataTableActionBarAction({
- size = "sm",
- tooltip,
- isPending,
- disabled,
- className,
- children,
- ...props
-}: DataTableActionBarActionProps) {
- const trigger = (
- <Button
- variant="secondary"
- size={size}
- className={cn(
- "border-secondary bg-secondary/50 hover:bg-secondary/70 gap-1.5 border [&>svg]:size-3.5",
- size === "icon" ? "size-7" : "h-7",
- className,
- )}
- disabled={disabled || isPending}
- {...props}
- >
- {isPending ? <Loader className="animate-spin" /> : children}
- </Button>
- );
-
- if (!tooltip) return trigger;
-
- return (
- <Tooltip>
- <TooltipTrigger asChild>{trigger}</TooltipTrigger>
- <TooltipContent
- sideOffset={6}
- className="bg-accent text-foreground border font-semibold dark:bg-zinc-900 [&>span]:hidden"
- >
- <p>{tooltip}</p>
- </TooltipContent>
- </Tooltip>
- );
-}
-
-interface DataTableActionBarSelectionProps<TData> {
- table: Table<TData>;
-}
-
-function DataTableActionBarSelection<TData>({
- table,
-}: DataTableActionBarSelectionProps<TData>) {
- const onClearSelection = React.useCallback(() => {
- table.toggleAllRowsSelected(false);
- }, [table]);
-
- return (
- <div className="flex h-7 items-center rounded-md border pr-1 pl-2.5">
- <span className="text-xs whitespace-nowrap">
- {table.getFilteredSelectedRowModel().rows.length} selected
- </span>
- <Separator
- orientation="vertical"
- className="mr-1 ml-2 data-[orientation=vertical]:h-4"
- />
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- variant="ghost"
- size="icon"
- className="size-5"
- onClick={onClearSelection}
- >
- <X className="size-3.5" />
- </Button>
- </TooltipTrigger>
- <TooltipContent
- sideOffset={10}
- className="bg-accent text-foreground flex items-center gap-2 border px-2 py-1 font-semibold dark:bg-zinc-900 [&>span]:hidden"
- >
- <p>Clear selection</p>
- <kbd className="bg-background text-foreground rounded border px-1.5 py-px font-mono text-[0.7rem] font-normal shadow-xs select-none">
- <abbr title="Escape" className="no-underline">
- Esc
- </abbr>
- </kbd>
- </TooltipContent>
- </Tooltip>
- </div>
- );
-}
-
-export {
- DataTableActionBar,
- DataTableActionBarAction,
- DataTableActionBarSelection,
-};
diff --git a/apps/status-page/src/components/ui/data-table/data-table-faceted-filter.tsx b/apps/status-page/src/components/ui/data-table/data-table-faceted-filter.tsx
deleted file mode 100644
index 8c4863d3c..000000000
--- a/apps/status-page/src/components/ui/data-table/data-table-faceted-filter.tsx
+++ /dev/null
@@ -1,159 +0,0 @@
-import { Badge } from "@openstatus/ui/components/ui/badge";
-import { Button } from "@openstatus/ui/components/ui/button";
-import {
- Command,
- CommandEmpty,
- CommandGroup,
- CommandInput,
- CommandItem,
- CommandList,
- CommandSeparator,
-} from "@openstatus/ui/components/ui/command";
-import {
- Popover,
- PopoverContent,
- PopoverTrigger,
-} from "@openstatus/ui/components/ui/popover";
-import { cn } from "@openstatus/ui/lib/utils";
-import type { Column } from "@tanstack/react-table";
-import { Check, PlusCircle } from "lucide-react";
-import type * as React from "react";
-
-interface DataTableFacetedFilterProps<TData, TValue> {
- column?: Column<TData, TValue>;
- title?: string;
- icon?: React.ComponentType<{ className?: string }>;
- options: {
- label: string;
- value: string | number;
- icon?: React.ComponentType<{ className?: string }>;
- }[];
-}
-
-export function DataTableFacetedFilter<TData, TValue>({
- column,
- title,
- icon: Icon,
- options,
-}: DataTableFacetedFilterProps<TData, TValue>) {
- const facets = column?.getFacetedUniqueValues();
- const selectedValues = new Set(
- column?.getFilterValue() as (string | number)[],
- );
-
- return (
- <Popover>
- <PopoverTrigger asChild>
- <Button
- variant="outline"
- size="sm"
- className={cn(
- "h-8 border-dashed",
- selectedValues?.size > 0 && "border-solid",
- )}
- >
- {Icon ? <Icon /> : <PlusCircle />}
- {title}
- {selectedValues?.size > 0 && (
- <>
- <Badge
- variant="secondary"
- className="rounded-sm px-1 font-normal lg:hidden"
- >
- {selectedValues.size}
- </Badge>
- <div className="hidden space-x-1 lg:flex">
- {selectedValues.size > 2 ? (
- <Badge
- variant="secondary"
- className="rounded-sm px-1 font-normal"
- >
- {selectedValues.size} selected
- </Badge>
- ) : (
- options
- .filter((option) => selectedValues.has(option.value))
- .map((option) => (
- <Badge
- variant="secondary"
- key={option.value}
- className="rounded-sm px-1 font-normal"
- >
- {option.label}
- </Badge>
- ))
- )}
- </div>
- </>
- )}
- </Button>
- </PopoverTrigger>
- <PopoverContent className="w-[200px] p-0" align="start">
- <Command>
- <CommandInput placeholder={title} />
- <CommandList>
- <CommandEmpty>No results found.</CommandEmpty>
- <CommandGroup>
- {options.map((option) => {
- const isSelected = selectedValues.has(option.value);
- return (
- <CommandItem
- key={option.value}
- onSelect={() => {
- if (isSelected) {
- selectedValues.delete(option.value);
- } else {
- selectedValues.add(option.value);
- }
- const filterValues = Array.from(selectedValues);
- column?.setFilterValue(
- filterValues.length ? filterValues : undefined,
- );
- }}
- >
- <div
- className={cn(
- "border-primary mr-2 flex h-4 w-4 items-center justify-center rounded-sm border",
- isSelected
- ? "bg-primary text-primary-foreground"
- : "opacity-50 [&_svg]:invisible",
- )}
- >
- <Check
- className={cn(
- isSelected ? "text-primary-foreground" : undefined,
- )}
- />
- </div>
- {option.icon && (
- <option.icon className="text-muted-foreground mr-2 h-4 w-4" />
- )}
- <span className="truncate">{option.label}</span>
- {facets?.get(option.value) && (
- <span className="ml-auto flex h-4 w-4 items-center justify-center font-mono text-xs">
- {facets.get(option.value)}
- </span>
- )}
- </CommandItem>
- );
- })}
- </CommandGroup>
- {selectedValues.size > 0 && (
- <>
- <CommandSeparator />
- <CommandGroup>
- <CommandItem
- onSelect={() => column?.setFilterValue(undefined)}
- className="justify-center text-center"
- >
- Clear filters
- </CommandItem>
- </CommandGroup>
- </>
- )}
- </CommandList>
- </Command>
- </PopoverContent>
- </Popover>
- );
-}
diff --git a/apps/status-page/src/components/ui/data-table/data-table-skeleton.tsx b/apps/status-page/src/components/ui/data-table/data-table-skeleton.tsx
deleted file mode 100644
index 7298f07de..000000000
--- a/apps/status-page/src/components/ui/data-table/data-table-skeleton.tsx
+++ /dev/null
@@ -1,62 +0,0 @@
-import { Skeleton } from "@openstatus/ui/components/ui/skeleton";
-import {
- Table,
- TableBody,
- TableCell,
- TableHead,
- TableHeader,
- TableRow,
-} from "@openstatus/ui/components/ui/table";
-
-interface DataTableSkeletonProps {
- /**
- * Number of rows to render
- * @default 10
- */
- rows?: number;
-}
-
-export function DataTableSkeleton({ rows = 3 }: DataTableSkeletonProps) {
- return (
- <Table>
- <TableHeader className="bg-muted/50">
- <TableRow className="hover:bg-transparent">
- <TableHead>
- <Skeleton className="my-1.5 h-4 w-24" />
- </TableHead>
- <TableHead className="hidden sm:table-cell">
- <Skeleton className="my-1.5 h-4 w-32" />
- </TableHead>
- <TableHead className="hidden md:table-cell">
- <Skeleton className="my-1.5 h-4 w-16" />
- </TableHead>
- <TableHead>
- <Skeleton className="my-1.5 h-4 w-20" />
- </TableHead>
- <TableHead className="flex items-center justify-end" />
- </TableRow>
- </TableHeader>
- <TableBody>
- {Array.from({ length: rows }).map((_, i) => (
- <TableRow key={i} className="hover:bg-transparent">
- <TableCell>
- <Skeleton className="my-1.5 h-4 w-full max-w-40" />
- </TableCell>
- <TableCell className="hidden sm:table-cell">
- <Skeleton className="my-1.5 h-4 w-full max-w-52" />
- </TableCell>
- <TableCell className="hidden md:table-cell">
- <Skeleton className="my-1.5 h-4 w-24" />
- </TableCell>
- <TableCell>
- <Skeleton className="my-1.5 h-4 w-full max-w-40" />
- </TableCell>
- <TableCell className="flex justify-end">
- <Skeleton className="my-1.5 h-5 w-5" />
- </TableCell>
- </TableRow>
- ))}
- </TableBody>
- </Table>
- );
-}
diff --git a/apps/status-page/src/components/ui/data-table/data-table-toolbar.tsx b/apps/status-page/src/components/ui/data-table/data-table-toolbar.tsx
deleted file mode 100644
index e945965bf..000000000
--- a/apps/status-page/src/components/ui/data-table/data-table-toolbar.tsx
+++ /dev/null
@@ -1,59 +0,0 @@
-"use client";
-
-import { Button } from "@openstatus/ui/components/ui/button";
-import { Input } from "@openstatus/ui/components/ui/input";
-import type { Table } from "@tanstack/react-table";
-import { X } from "lucide-react";
-
-import { DataTableFacetedFilter } from "./data-table-faceted-filter";
-import { DataTableViewOptions } from "./data-table-view-options";
-
-export interface DataTableToolbarProps<TData> {
- table: Table<TData>;
-}
-
-export function DataTableToolbar<TData>({
- table,
-}: DataTableToolbarProps<TData>) {
- const isFiltered = table.getState().columnFilters.length > 0;
-
- return (
- <div className="flex items-center justify-between">
- <div className="flex flex-1 items-center space-x-2">
- <Input
- placeholder="Filter entries..."
- value={(table.getColumn("title")?.getFilterValue() as string) ?? ""}
- onChange={(event) =>
- table.getColumn("title")?.setFilterValue(event.target.value)
- }
- className="h-8 w-[150px] lg:w-[250px]"
- />
- {table.getColumn("status") && (
- <DataTableFacetedFilter
- column={table.getColumn("status")}
- title="Status"
- options={[]}
- />
- )}
- {table.getColumn("tags") && (
- <DataTableFacetedFilter
- column={table.getColumn("tags")}
- title="Tags"
- options={[]}
- />
- )}
- {isFiltered && (
- <Button
- variant="ghost"
- onClick={() => table.resetColumnFilters()}
- className="h-8 px-2 lg:px-3"
- >
- Reset
- <X />
- </Button>
- )}
- </div>
- <DataTableViewOptions table={table} />
- </div>
- );
-}
diff --git a/apps/status-page/src/components/ui/data-table/data-table-view-options.tsx b/apps/status-page/src/components/ui/data-table/data-table-view-options.tsx
deleted file mode 100644
index 9331814d3..000000000
--- a/apps/status-page/src/components/ui/data-table/data-table-view-options.tsx
+++ /dev/null
@@ -1,58 +0,0 @@
-"use client";
-
-import { Button } from "@openstatus/ui/components/ui/button";
-import {
- DropdownMenu,
- DropdownMenuCheckboxItem,
- DropdownMenuContent,
- DropdownMenuLabel,
- DropdownMenuSeparator,
-} from "@openstatus/ui/components/ui/dropdown-menu";
-import { DropdownMenuTrigger } from "@radix-ui/react-dropdown-menu";
-import type { Table } from "@tanstack/react-table";
-import { Settings2 } from "lucide-react";
-
-interface DataTableViewOptionsProps<TData> {
- table: Table<TData>;
-}
-
-export function DataTableViewOptions<TData>({
- table,
-}: DataTableViewOptionsProps<TData>) {
- return (
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button
- variant="outline"
- size="sm"
- className="ml-auto hidden h-8 lg:flex"
- >
- <Settings2 />
- View
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end" className="w-[150px]">
- <DropdownMenuLabel>Toggle columns</DropdownMenuLabel>
- <DropdownMenuSeparator />
- {table
- .getAllColumns()
- .filter(
- (column) =>
- typeof column.accessorFn !== "undefined" && column.getCanHide(),
- )
- .map((column) => {
- return (
- <DropdownMenuCheckboxItem
- key={column.id}
- className="capitalize"
- checked={column.getIsVisible()}
- onCheckedChange={(value) => column.toggleVisibility(!!value)}
- >
- {column.id}
- </DropdownMenuCheckboxItem>
- );
- })}
- </DropdownMenuContent>
- </DropdownMenu>
- );
-}
diff --git a/apps/status-page/src/components/ui/data-table/data-table.tsx b/apps/status-page/src/components/ui/data-table/data-table.tsx
deleted file mode 100644
index 5e7ef1ef2..000000000
--- a/apps/status-page/src/components/ui/data-table/data-table.tsx
+++ /dev/null
@@ -1,208 +0,0 @@
-"use client";
-
-import {
- Table,
- TableBody,
- TableCell,
- TableHead,
- TableHeader,
- TableRow,
-} from "@openstatus/ui/components/ui/table";
-import {
- type ColumnDef,
- type ColumnFiltersState,
- type PaginationState,
- type Row,
- type SortingState,
- type VisibilityState,
- flexRender,
- getCoreRowModel,
- getExpandedRowModel,
- getFacetedRowModel,
- getFacetedUniqueValues,
- getFilteredRowModel,
- getPaginationRowModel,
- getSortedRowModel,
- useReactTable,
-} from "@tanstack/react-table";
-import * as React from "react";
-import { Fragment } from "react";
-
-import type { DataTableActionBarProps } from "./data-table-action-bar";
-import type { DataTablePaginationProps } from "./data-table-pagination";
-import type { DataTableToolbarProps } from "./data-table-toolbar";
-
-export interface DataTableProps<TData, TValue> {
- columns: ColumnDef<TData, TValue>[];
- data: TData[];
- rowComponent?: React.ComponentType<{ row: Row<TData> }>;
- toolbarComponent?: React.ComponentType<DataTableToolbarProps<TData>>;
- actionBar?: React.ComponentType<DataTableActionBarProps<TData>>;
- paginationComponent?: React.ComponentType<DataTablePaginationProps<TData>>;
- onRowClick?: (row: Row<TData>) => void;
- defaultSorting?: SortingState;
- defaultColumnVisibility?: VisibilityState;
- defaultColumnFilters?: ColumnFiltersState;
- defaultPagination?: PaginationState;
- autoResetPageIndex?: boolean;
-
- /** access the state from the parent component */
- columnFilters?: ColumnFiltersState;
- setColumnFilters?: React.Dispatch<React.SetStateAction<ColumnFiltersState>>;
- sorting?: SortingState;
- setSorting?: React.Dispatch<React.SetStateAction<SortingState>>;
- pagination?: PaginationState;
- setPagination?: React.Dispatch<React.SetStateAction<PaginationState>>;
-}
-
-export function DataTable<TData, TValue>({
- columns,
- data,
- rowComponent,
- toolbarComponent,
- actionBar,
- paginationComponent,
- onRowClick,
- defaultSorting = [],
- defaultColumnVisibility = {},
- defaultColumnFilters = [],
- defaultPagination = { pageIndex: 0, pageSize: 10 },
- autoResetPageIndex = true,
- columnFilters,
- setColumnFilters,
- sorting,
- setSorting,
- pagination,
- setPagination,
-}: DataTableProps<TData, TValue>) {
- // oxlint-disable-next-line typescript/no-explicit-any
- const [globalFilter, setGlobalFilter] = React.useState<any>();
- const [rowSelection, setRowSelection] = React.useState({});
- const [columnVisibility, setColumnVisibility] =
- React.useState<VisibilityState>(defaultColumnVisibility);
- const [internalPagination, setInternalPagination] =
- React.useState<PaginationState>(defaultPagination);
- const [internalColumnFilters, setInternalColumnFilters] =
- React.useState<ColumnFiltersState>(defaultColumnFilters);
- const [internalSorting, setInternalSorting] =
- React.useState<SortingState>(defaultSorting);
-
- // Use controlled or uncontrolled column filters
- const columnFiltersState = columnFilters ?? internalColumnFilters;
- const setColumnFiltersState = setColumnFilters ?? setInternalColumnFilters;
- const sortingState = sorting ?? internalSorting;
- const setSortingState = setSorting ?? setInternalSorting;
- const paginationState = pagination ?? internalPagination;
- const setPaginationState = setPagination ?? setInternalPagination;
-
- const table = useReactTable({
- data,
- columns,
- state: {
- sorting: sortingState,
- columnVisibility,
- rowSelection,
- pagination: paginationState,
- columnFilters: columnFiltersState,
- globalFilter,
- },
- enableRowSelection: true,
- onRowSelectionChange: setRowSelection,
- onSortingChange: setSortingState,
- onColumnFiltersChange: setColumnFiltersState,
- onColumnVisibilityChange: setColumnVisibility,
- onPaginationChange: setPaginationState,
- onGlobalFilterChange: setGlobalFilter,
- getCoreRowModel: getCoreRowModel(),
- getFilteredRowModel: getFilteredRowModel(),
- getPaginationRowModel: getPaginationRowModel(),
- getSortedRowModel: getSortedRowModel(),
- getFacetedRowModel: getFacetedRowModel(),
- getFacetedUniqueValues: getFacetedUniqueValues(),
- getExpandedRowModel: getExpandedRowModel(),
- autoResetPageIndex,
- // @ts-expect-error as we have an id in the data
- getRowCanExpand: (row) => Boolean(row.original.id),
- });
-
- return (
- <div className="grid gap-2">
- {toolbarComponent
- ? React.createElement(toolbarComponent, { table })
- : null}
- <Table>
- <TableHeader>
- {table.getHeaderGroups().map((headerGroup) => (
- <TableRow key={headerGroup.id}>
- {headerGroup.headers.map((header) => {
- return (
- <TableHead
- key={header.id}
- colSpan={header.colSpan}
- className={header.column.columnDef.meta?.headerClassName}
- >
- {header.isPlaceholder
- ? null
- : flexRender(
- header.column.columnDef.header,
- header.getContext(),
- )}
- </TableHead>
- );
- })}
- </TableRow>
- ))}
- </TableHeader>
- <TableBody>
- {table.getRowModel().rows?.length ? (
- table.getRowModel().rows.map((row) => (
- <Fragment key={row.id}>
- <TableRow
- data-state={
- (row.getIsSelected() || row.getIsExpanded()) && "selected"
- }
- onClick={() => onRowClick?.(row)}
- className="data-[state=selected]:bg-muted/50"
- >
- {row.getVisibleCells().map((cell) => (
- <TableCell
- key={cell.id}
- className={cell.column.columnDef.meta?.cellClassName}
- >
- {flexRender(
- cell.column.columnDef.cell,
- cell.getContext(),
- )}
- </TableCell>
- ))}
- </TableRow>
- {row.getIsExpanded() && (
- <TableRow className="hover:bg-background">
- <TableCell
- className="p-0"
- colSpan={row.getVisibleCells().length}
- >
- {rowComponent
- ? React.createElement(rowComponent, { row })
- : null}
- </TableCell>
- </TableRow>
- )}
- </Fragment>
- ))
- ) : (
- <TableRow>
- <TableCell colSpan={columns.length} className="h-24 text-center">
- No results.
- </TableCell>
- </TableRow>
- )}
- </TableBody>
- {actionBar ? React.createElement(actionBar, { table }) : null}
- </Table>
- {paginationComponent
- ? React.createElement(paginationComponent, { table })
- : null}
- </div>
- );
-}
diff --git a/apps/status-page/src/data/icons.ts b/apps/status-page/src/data/icons.ts
deleted file mode 100644
index 92a382f5b..000000000
--- a/apps/status-page/src/data/icons.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-"use client";
-
-import { Monitor, Alert, Resolved } from "@openstatus/icons";
-
-export const status = {
- operational: Resolved,
- investigating: Alert,
- identified: Alert,
- monitoring: Monitor,
-} as const;
-
-export const icons = {
- status,
-};
diff --git a/apps/status-page/src/data/incidents.ts b/apps/status-page/src/data/incidents.ts
deleted file mode 100644
index d4c242c45..000000000
--- a/apps/status-page/src/data/incidents.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-export const incidents = [
- {
- id: 1,
- startedAt: new Date("2025-05-05 12:00:00"),
- acknowledged: null,
- resolvedAt: new Date("2025-05-05 14:00:00"),
- monitor: "OpenStatus API",
- },
-];
-
-export type Incident = (typeof incidents)[number];
diff --git a/apps/status-page/src/data/invitations.ts b/apps/status-page/src/data/invitations.ts
deleted file mode 100644
index 560d4d0c3..000000000
--- a/apps/status-page/src/data/invitations.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-export const invitations = [
- {
- id: 1,
- email: "[email protected]",
- role: "member",
- createdAt: "2021-01-01",
- expiresAt: "2021-01-07",
- acceptedAt: "2021-01-02",
- },
-];
-
-export type Invitation = (typeof invitations)[number];
diff --git a/apps/status-page/src/data/maintenances.ts b/apps/status-page/src/data/maintenances.ts
deleted file mode 100644
index ecd06dd9f..000000000
--- a/apps/status-page/src/data/maintenances.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-const today = new Date();
-const week = new Date(today);
-week.setDate(week.getDate() + 7);
-const hour = new Date(week);
-hour.setHours(hour.getHours() + 1);
-
-export const maintenances = [
- {
- id: 1,
- title: "DB Migration",
- message:
- "We are performing a db migration on our system and will be down for a an hour.",
- startDate: week,
- endDate: hour,
- affected: ["OpenStatus API"],
- },
- {
- id: 2,
- title: "System Upgrade",
- message:
- "We will be upgrading our core infrastructure to improve performance and reliability. Service interruptions may occur.",
- startDate: new Date("2025-03-01 11:00:00"),
- endDate: new Date("2025-03-01 15:30:00"),
- affected: ["OpenStatus API", "OpenStatus Web"],
- },
-];
-
-export type Maintenance = (typeof maintenances)[number];
diff --git a/apps/status-page/src/data/members.ts b/apps/status-page/src/data/members.ts
deleted file mode 100644
index 389ce7996..000000000
--- a/apps/status-page/src/data/members.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-export const members = [
- {
- id: 1,
- name: "Maximilian Kaske",
- email: "[email protected]",
- role: "admin",
- createdAt: "2021-01-01",
- },
-];
-
-export type Member = (typeof members)[number];
diff --git a/apps/status-page/src/data/monitor-tags.ts b/apps/status-page/src/data/monitor-tags.ts
deleted file mode 100644
index ad2886162..000000000
--- a/apps/status-page/src/data/monitor-tags.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-export const monitorTags = [
- {
- value: "production",
- label: "Production",
- color: "bg-green-500",
- },
- {
- value: "development",
- label: "Development",
- color: "bg-blue-500",
- },
- {
- value: "staging",
- label: "Staging",
- color: "bg-yellow-500",
- },
- {
- value: "testing",
- label: "Testing",
- color: "bg-purple-500",
- },
- {
- value: "api",
- label: "API",
- color: "bg-red-500",
- },
- {
- value: "database",
- label: "Database",
- color: "bg-orange-500",
- },
-];
-
-export type MonitorTag = (typeof monitorTags)[number];
diff --git a/apps/status-page/src/data/plans.ts b/apps/status-page/src/data/plans.ts
deleted file mode 100644
index f1fb26480..000000000
--- a/apps/status-page/src/data/plans.ts
+++ /dev/null
@@ -1,74 +0,0 @@
-export const plans = [
- {
- title: "Hobby",
- id: "hobby",
- description: "Perfect for personal projects",
- price: 0,
- limits: {
- monitors: 1,
- regions: 35,
- periodicity: "10m",
- "status-pages": 1,
- members: 1,
- "notification-channels": 1,
- "custom-domain": false,
- "password-protection": false,
- "status-subscribers": false,
- "audit-log": false,
- },
- },
- {
- title: "Starter",
- id: "starter",
- description: "Perfect for uptime monitoring",
- price: 30,
- limits: {
- monitors: 20,
- regions: 35,
- periodicity: "1m",
- "status-pages": 1,
- members: Number.POSITIVE_INFINITY,
- "notification-channels": 10,
- "custom-domain": true,
- "password-protection": true,
- "status-subscribers": true,
- "audit-log": false,
- },
- },
- {
- title: "Pro",
- id: "team",
- description: "Perfect for global synthetic monitoring",
- price: 100,
- limits: {
- monitors: 50,
- regions: 35,
- periodicity: "30s",
- "status-pages": 5,
- members: Number.POSITIVE_INFINITY,
- "notification-channels": 20,
- "custom-domain": true,
- "password-protection": true,
- "status-subscribers": true,
- "audit-log": true,
- },
- },
- {
- title: "Scale",
- id: "scale",
- description: "For teams running serious infrastructure at scale",
- price: 500,
- limits: {
- monitors: 50,
- regions: 35,
- periodicity: "30s",
- "status-pages": 10,
- members: Number.POSITIVE_INFINITY,
- "notification-channels": 20,
- "custom-domain": true,
- "password-protection": true,
- "status-subscribers": true,
- "audit-log": true,
- },
- },
-];
diff --git a/apps/status-page/src/data/region-percentile.ts b/apps/status-page/src/data/region-percentile.ts
deleted file mode 100644
index 763a62cef..000000000
--- a/apps/status-page/src/data/region-percentile.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-const randomizer = Math.random() * 10;
-
-export const regionPercentile = Array.from({ length: 30 }, (_, i) => ({
- timestamp: new Date(
- new Date().setMinutes(new Date().getMinutes() - i),
- ).toLocaleString("default", {
- hour: "numeric",
- minute: "numeric",
- }),
- latency: Math.floor(Math.random() * randomizer + 1) * 100,
-})).map((item, i) => {
- const baseLatency = item.latency;
- const randomFactor = () => 0.85 + Math.random() * 0.3; // Random factor between 0.85-1.15
-
- return {
- ...item,
- // More realistic percentile distribution with randomness
- p50: Math.round(baseLatency * 0.7 * randomFactor()),
- p75: Math.round(baseLatency * 0.85 * randomFactor()),
- p90: Math.round(baseLatency * 1.1 * randomFactor()),
- p95: Math.round(baseLatency * 1.3 * randomFactor()),
- p99: Math.round(baseLatency * 1.8 * randomFactor()),
- // REMINDER: for error bars
- error: [4, 5, 6].includes(i) ? 1 : undefined,
- };
-});
-
-export type RegionPercentile = (typeof regionPercentile)[number];
diff --git a/apps/status-page/src/data/response-logs.ts b/apps/status-page/src/data/response-logs.ts
deleted file mode 100644
index cf0e5fb78..000000000
--- a/apps/status-page/src/data/response-logs.ts
+++ /dev/null
@@ -1,60 +0,0 @@
-export const responseLogs = [
- {
- id: 1,
- url: "https://api.openstatus.dev",
- method: "GET",
- status: 200 as const,
- latency: 150,
- timing: {
- dns: 10,
- connect: 20,
- tls: 30,
- ttfb: 40,
- transfer: 50,
- },
- assertions: [],
- region: "ams" as const,
- error: false,
- timestamp: new Date().getTime(),
- headers: {
- "Cache-Control":
- "private, no-cache, no-store, max-age=0, must-revalidate",
- "Content-Type": "text/html; charset=utf-8",
- Date: "Sun, 28 Jan 2024 08:50:13 GMT",
- Server: "Vercel",
- },
- type: "scheduled" as const satisfies "scheduled" | "on-demand",
- },
- {
- id: 2,
- url: "https://api.openstatus.dev",
- method: "GET",
- status: 500 as const,
- latency: 150,
- timing: {
- dns: 4,
- connect: 120,
- tls: 12,
- ttfb: 20,
- transfer: 40,
- },
- assertions: [],
- region: "ams" as const,
- error: true,
- timestamp: new Date().getTime(),
- headers: {
- "Cache-Control":
- "private, no-cache, no-store, max-age=0, must-revalidate",
- "Content-Type": "text/html; charset=utf-8",
- Date: "Sun, 28 Jan 2024 08:50:13 GMT",
- Server: "Vercel",
- },
- type: "scheduled" as const satisfies "scheduled" | "on-demand",
- // error message
- message:
- "Environment variable 'NEXT_PUBLIC_TEST_KEY' is missing. Please add and redeploy your project.",
- },
-];
-
-export type ResponseLog = (typeof responseLogs)[number];
-export type Timing = ResponseLog["timing"];
diff --git a/apps/status-page/src/data/status-codes.ts b/apps/status-page/src/data/status-codes.ts
deleted file mode 100644
index 1d4fc2f11..000000000
--- a/apps/status-page/src/data/status-codes.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-export const statusCodes = [
- {
- code: 200 as const,
- bg: "bg-success",
- text: "text-success",
- name: "OK",
- },
- {
- code: 500 as const,
- bg: "bg-destructive",
- text: "text-destructive",
- name: "Internal Server Error",
- },
-];
-
-export type StatusCode = (typeof statusCodes)[number]["code"];
diff --git a/apps/status-page/src/data/status-pages.ts b/apps/status-page/src/data/status-pages.ts
deleted file mode 100644
index ef5a7bd1f..000000000
--- a/apps/status-page/src/data/status-pages.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-export const statusPages = [
- {
- id: 1,
- name: "OpenStatus Status",
- description: "See our uptime history and status reports.",
- slug: "status",
- favicon: "https://openstatus.dev/favicon.ico",
- domain: "status.openstatus.dev",
- protected: true,
- showValues: false,
- // NOTE: the worst status of a report
- status: "degraded" as const,
- monitors: [],
- },
-];
-
-export type StatusPage = (typeof statusPages)[number];
diff --git a/apps/status-page/src/data/status-reports.ts b/apps/status-page/src/data/status-reports.ts
deleted file mode 100644
index 189b4a966..000000000
--- a/apps/status-page/src/data/status-reports.ts
+++ /dev/null
@@ -1,84 +0,0 @@
-const today = new Date();
-const lastHour = new Date(new Date().setHours(new Date().getHours() - 1));
-const yesterday = new Date(new Date().setDate(new Date().getDate() - 1));
-
-console.log({ today, lastHour, yesterday });
-
-export const statusReports = [
- {
- id: 1,
- name: "Downtime API due to hosting provider with 400 errors",
- startedAt: yesterday,
- updatedAt: today,
- status: "operational",
- updates: [
- {
- id: 2,
- status: "operational" as const,
- message:
- "Everything is under control, we continue to monitor the situation.",
- date: today,
- updatedAt: today,
- monitors: [1],
- },
- {
- id: 1,
- status: "investigating" as const,
- message:
- "Our hosting provider is having an increase of 400 errors. We are aware of the dependency and will be working on a solution to reduce the risk.",
- date: lastHour,
- updatedAt: lastHour,
- monitors: [1],
- },
- ],
- affected: ["OpenStatus API"],
- },
- {
- id: 3,
- name: "Downtime API due to hosting provider with 400 errors",
- startedAt: new Date("2025-08-05 12:10:00"),
- updatedAt: new Date("2025-08-05 12:30:00"),
- status: "operational",
- updates: [
- {
- id: 4,
- status: "operational" as const,
- message:
- "Everything is under control, we continue to monitor the situation.",
- date: new Date("2025-08-06 03:30:00"),
- updatedAt: new Date("2025-08-06 03:30:00"),
- monitors: [1],
- },
- {
- id: 3,
- status: "monitoring" as const,
- message:
- "We are continuing to monitor the situation to ensure that the issue is resolved.",
- date: new Date("2025-08-05 16:00:00"),
- updatedAt: new Date("2025-08-05 16:00:00"),
- monitors: [1],
- },
- {
- id: 2,
- status: "identified" as const,
- message:
- "We have identified the root cause of the issue. It is due to a configuration error on our part.",
- date: new Date("2025-08-05 14:00:00"),
- updatedAt: new Date("2025-08-05 14:00:00"),
- monitors: [1],
- },
- {
- id: 1,
- status: "investigating" as const,
- message:
- "Our hosting provider is having an increase of 400 errors. We are working on a solution to reduce the risk.",
- date: new Date("2025-08-05 12:00:00"),
- updatedAt: new Date("2025-08-05 12:00:00"),
- monitors: [1],
- },
- ],
- affected: ["OpenStatus API"],
- },
-];
-
-export type StatusReport = (typeof statusReports)[number];
diff --git a/apps/status-page/src/lib/composition.test.ts b/apps/status-page/src/lib/composition.test.ts
deleted file mode 100644
index f4bfea304..000000000
--- a/apps/status-page/src/lib/composition.test.ts
+++ /dev/null
@@ -1,68 +0,0 @@
-import { describe, expect, test } from "vitest";
-
-import { composeEventHandlers, composeRefs } from "./composition";
-
-describe("composeEventHandlers", () => {
- test("runs the original handler before ours", () => {
- const calls: string[] = [];
- const handler = composeEventHandlers(
- () => calls.push("original"),
- () => calls.push("ours"),
- );
- handler({ defaultPrevented: false });
- expect(calls).toEqual(["original", "ours"]);
- });
-
- test("skips ours when the original prevents default", () => {
- const calls: string[] = [];
- const handler = composeEventHandlers<{ defaultPrevented: boolean }>(
- (e) => {
- e.defaultPrevented = true;
- },
- () => calls.push("ours"),
- );
- handler({ defaultPrevented: false });
- expect(calls).toEqual([]);
- });
-
- test("runs ours anyway when the check is disabled", () => {
- const calls: string[] = [];
- const handler = composeEventHandlers(undefined, () => calls.push("ours"), {
- checkForDefaultPrevented: false,
- });
- handler({ defaultPrevented: true });
- expect(calls).toEqual(["ours"]);
- });
-});
-
-describe("composeRefs", () => {
- test("sets object refs and calls callback refs", () => {
- const objectRef = { current: null as string | null };
- let callbackValue: string | null = null;
- composeRefs<string>(
- objectRef,
- (v) => {
- callbackValue = v;
- },
- undefined,
- )("node");
- expect(objectRef.current).toBe("node");
- expect(callbackValue).toBe("node");
- });
-
- test("returns no cleanup when no ref returns one", () => {
- expect(composeRefs<string>({ current: null })("node")).toBeUndefined();
- });
-
- test("runs cleanups and nulls refs without one", () => {
- const objectRef = { current: null as string | null };
- let cleaned = false;
- const cleanup = composeRefs<string>(objectRef, () => () => {
- cleaned = true;
- })("node");
- expect(typeof cleanup).toBe("function");
- (cleanup as () => void)();
- expect(cleaned).toBe(true);
- expect(objectRef.current).toBeNull();
- });
-});
diff --git a/apps/status-page/src/lib/composition.ts b/apps/status-page/src/lib/composition.ts
deleted file mode 100644
index b65a7008a..000000000
--- a/apps/status-page/src/lib/composition.ts
+++ /dev/null
@@ -1,87 +0,0 @@
-import * as React from "react";
-
-/**
- * A utility to compose multiple event handlers into a single event handler.
- * Run originalEventHandler first, then ourEventHandler unless prevented.
- */
-function composeEventHandlers<E>(
- originalEventHandler?: (event: E) => void,
- ourEventHandler?: (event: E) => void,
- { checkForDefaultPrevented = true } = {},
-) {
- return function handleEvent(event: E) {
- originalEventHandler?.(event);
-
- if (
- checkForDefaultPrevented === false ||
- !(event as unknown as Event).defaultPrevented
- ) {
- return ourEventHandler?.(event);
- }
- };
-}
-
-/**
- * @see https://github.com/radix-ui/primitives/blob/main/packages/react/compose-refs/src/compose-refs.tsx
- */
-
-type PossibleRef<T> = React.Ref<T> | undefined;
-
-/**
- * Set a given ref to a given value.
- * This utility takes care of different types of refs: callback refs and RefObject(s).
- */
-function setRef<T>(ref: PossibleRef<T>, value: T) {
- if (typeof ref === "function") {
- return ref(value);
- }
-
- if (ref !== null && ref !== undefined) {
- ref.current = value;
- }
-}
-
-/**
- * A utility to compose multiple refs together.
- * Accepts callback refs and RefObject(s).
- */
-function composeRefs<T>(...refs: PossibleRef<T>[]): React.RefCallback<T> {
- return (node) => {
- let hasCleanup = false;
- const cleanups = refs.map((ref) => {
- const cleanup = setRef(ref, node);
- if (!hasCleanup && typeof cleanup === "function") {
- hasCleanup = true;
- }
- return cleanup;
- });
-
- // React <19 will log an error to the console if a callback ref returns a
- // value. We don't use ref cleanups internally so this will only happen if a
- // user's ref callback returns a value, which we only expect if they are
- // using the cleanup functionality added in React 19.
- if (hasCleanup) {
- return () => {
- for (let i = 0; i < cleanups.length; i++) {
- const cleanup = cleanups[i];
- if (typeof cleanup === "function") {
- cleanup();
- } else {
- setRef(refs[i], null);
- }
- }
- };
- }
- };
-}
-
-/**
- * A custom hook that composes multiple refs.
- * Accepts callback refs and RefObject(s).
- */
-function useComposedRefs<T>(...refs: PossibleRef<T>[]): React.RefCallback<T> {
- // eslint-disable-next-line react-hooks/exhaustive-deps
- return React.useCallback(composeRefs(...refs), refs);
-}
-
-export { composeEventHandlers, composeRefs, useComposedRefs };
diff --git a/apps/status-page/src/lib/utils.ts b/apps/status-page/src/lib/utils.ts
deleted file mode 100644
index 365058ceb..000000000
--- a/apps/status-page/src/lib/utils.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-import { type ClassValue, clsx } from "clsx";
-import { twMerge } from "tailwind-merge";
-
-export function cn(...inputs: ClassValue[]) {
- return twMerge(clsx(inputs));
-}
diff --git a/apps/web/src/app/layout.tsx b/apps/web/src/app/layout.tsx
index 6dba7a499..783fdcbfe 100644
--- a/apps/web/src/app/layout.tsx
+++ b/apps/web/src/app/layout.tsx
@@ -9,6 +9,7 @@ import Script from "next/script";
import { NuqsAdapter } from "nuqs/adapters/next/app";
import { Attribution } from "../components/attribution";
+import { TailwindIndicator } from "../components/tailwind-indicator";
import { ThemeProvider } from "../components/theme-provider";
import { WebMcpProvider } from "../components/webmcp-provider";
import { env } from "../env";
@@ -78,6 +79,7 @@ export default function RootLayout({
<ThemeProvider attribute="class" defaultTheme="light" enableSystem>
<NuqsAdapter>
<TRPCReactQueryProvider>{children}</TRPCReactQueryProvider>
+ <TailwindIndicator />
<WebMcpProvider />
<Attribution />
</NuqsAdapter>
diff --git a/apps/web/src/components/dev-mode-container.tsx b/apps/web/src/components/dev-mode-container.tsx
deleted file mode 100644
index 410427671..000000000
--- a/apps/web/src/components/dev-mode-container.tsx
+++ /dev/null
@@ -1,23 +0,0 @@
-import { cn } from "../lib/utils";
-
-export default function DevModeContainer({
- children,
- className,
-}: {
- children: React.ReactNode;
- className?: string;
-}) {
- return (
- <div
- className={cn(
- "border-destructive/80 relative -m-2 rounded-lg border-2 p-2",
- className,
- )}
- >
- <p className="bg-background text-destructive absolute -top-2 left-3 px-1 text-xs font-medium uppercase">
- dev mode
- </p>
- {children}
- </div>
- );
-}
diff --git a/apps/web/src/components/icons.tsx b/apps/web/src/components/icons.tsx
deleted file mode 100644
index 6db64d849..000000000
--- a/apps/web/src/components/icons.tsx
+++ /dev/null
@@ -1,66 +0,0 @@
-import {
- Monitor,
- Compare,
- Clock,
- Settings,
- Command,
- Copy,
- Fingerprint,
- Globe,
- Maintenance,
- Image,
- Info,
- ApiKey,
- Link,
- Network,
- Play,
- Search,
- Resolved,
- Server,
- Table,
- Account,
- Webhook,
- Speed,
-} from "@openstatus/icons";
-import type { IconType, IconProps } from "@openstatus/icons";
-import {
- BlueskyIcon,
- DiscordIcon,
- GitHubIcon,
- LinkedInIcon,
- XIcon,
-} from "@openstatus/icons/brand";
-
-export type Icon = IconType;
-export type { IconProps };
-export type ValidIcon = keyof typeof Icons;
-
-export const Icons = {
- activity: Monitor,
- clock: Clock,
- cog: Settings,
- command: Command,
- compare: Compare,
- copy: Copy,
- fingerprint: Fingerprint,
- globe: Globe,
- hammer: Maintenance,
- image: Image,
- info: Info,
- key: ApiKey,
- link: Link,
- network: Network,
- play: Play,
- search: Search,
- "search-check": Resolved,
- server: Server,
- table: Table,
- user: Account,
- webhook: Webhook,
- zap: Speed,
- bluesky: BlueskyIcon,
- discord: DiscordIcon,
- github: GitHubIcon,
- linkedin: LinkedInIcon,
- twitter: XIcon,
-} as const;
diff --git a/apps/web/src/components/loading-animation.tsx b/apps/web/src/components/loading-animation.tsx
deleted file mode 100644
index f3fdc9e63..000000000
--- a/apps/web/src/components/loading-animation.tsx
+++ /dev/null
@@ -1,46 +0,0 @@
-import { cva } from "class-variance-authority";
-import type { VariantProps } from "class-variance-authority";
-
-import { cn } from "../lib/utils";
-
-const loadingVariants = cva(
- "direction-alternate animate-pulse rounded-full duration-700",
- {
- variants: {
- variant: {
- // we might want to inverse both styles
- default: "bg-primary-foreground",
- inverse: "bg-primary",
- },
- size: {
- default: "h-1 w-1",
- lg: "h-1.5 w-1.5",
- },
- },
- defaultVariants: {
- variant: "default",
- size: "default",
- },
- },
-);
-
-interface Props
- extends React.ComponentProps<"div">, VariantProps<typeof loadingVariants> {}
-
-export function LoadingAnimation({
- className,
- variant,
- size,
- ...props
-}: Props) {
- return (
- <div
- className={cn("flex items-center justify-center gap-1", className)}
- {...props}
- >
- <div className={cn(loadingVariants({ variant, size }))} />
- <div className={cn(loadingVariants({ variant, size }), "delay-150")} />
- <div className={cn(loadingVariants({ variant, size }), "delay-300")} />
- </div>
- );
-}
diff --git a/apps/web/src/components/ui/data-table/data-table-column-header.tsx b/apps/web/src/components/ui/data-table/data-table-column-header.tsx
deleted file mode 100644
index 0d63e1030..000000000
--- a/apps/web/src/components/ui/data-table/data-table-column-header.tsx
+++ /dev/null
@@ -1,60 +0,0 @@
-import { Button } from "@openstatus/ui/components/ui/button";
-import { cn } from "@openstatus/ui/lib/utils";
-import type { Column } from "@tanstack/react-table";
-import { ChevronDown, ChevronUp } from "lucide-react";
-
-interface DataTableColumnHeaderProps<
- TData,
- TValue,
-> extends React.ComponentProps<"button"> {
- column: Column<TData, TValue>;
- title: string;
-}
-
-export function DataTableColumnHeader<TData, TValue>({
- column,
- title,
- className,
- onClick,
- ...props
-}: DataTableColumnHeaderProps<TData, TValue>) {
- if (!column.getCanSort()) {
- return <div className={cn(className)}>{title}</div>;
- }
-
- return (
- <Button
- variant="ghost"
- size="sm"
- className={cn(
- "flex h-7 w-full items-center justify-between gap-2 px-0 py-0 hover:bg-transparent dark:hover:bg-transparent",
- className,
- )}
- {...props}
- onClick={(event) => {
- column.toggleSorting(undefined);
- onClick?.(event);
- }}
- >
- <span>{title}</span>
- <span className="flex flex-col">
- <ChevronUp
- className={cn(
- "-mb-0.5 size-3",
- column.getIsSorted() === "asc"
- ? "text-accent-foreground"
- : "text-muted-foreground",
- )}
- />
- <ChevronDown
- className={cn(
- "-mt-0.5 size-3",
- column.getIsSorted() === "desc"
- ? "text-accent-foreground"
- : "text-muted-foreground",
- )}
- />
- </span>
- </Button>
- );
-}
diff --git a/apps/web/src/components/ui/data-table/data-table.tsx b/apps/web/src/components/ui/data-table/data-table.tsx
deleted file mode 100644
index 926eee6ab..000000000
--- a/apps/web/src/components/ui/data-table/data-table.tsx
+++ /dev/null
@@ -1,158 +0,0 @@
-"use client";
-
-import {
- Table,
- TableBody,
- TableCell,
- TableHead,
- TableHeader,
- TableRow,
-} from "@openstatus/ui/components/ui/table";
-import {
- type ColumnDef,
- type ColumnFiltersState,
- type Row,
- type SortingState,
- type VisibilityState,
- flexRender,
- getCoreRowModel,
- getExpandedRowModel,
- getFacetedRowModel,
- getFacetedUniqueValues,
- getFilteredRowModel,
- getSortedRowModel,
- useReactTable,
-} from "@tanstack/react-table";
-import * as React from "react";
-import { Fragment } from "react";
-
-interface DataTableToolbarProps<TData> {
- table: import("@tanstack/react-table").Table<TData>;
-}
-
-// trimmed port of apps/dashboard data-table: no pagination/action bar —
-// play tools render a fixed, small set of rows
-interface DataTableProps<TData, TValue> {
- columns: ColumnDef<TData, TValue>[];
- data: TData[];
- rowComponent?: React.ComponentType<{ row: Row<TData> }>;
- toolbarComponent?: React.ComponentType<DataTableToolbarProps<TData>>;
- onRowClick?: (row: Row<TData>) => void;
- defaultSorting?: SortingState;
- defaultColumnVisibility?: VisibilityState;
- defaultColumnFilters?: ColumnFiltersState;
- emptyState?: React.ReactNode;
-}
-
-export function DataTable<TData, TValue>({
- columns,
- data,
- rowComponent,
- toolbarComponent,
- onRowClick,
- defaultSorting = [],
- defaultColumnVisibility = {},
- defaultColumnFilters = [],
- emptyState = "No results.",
-}: DataTableProps<TData, TValue>) {
- const [columnVisibility, setColumnVisibility] =
- React.useState<VisibilityState>(defaultColumnVisibility);
- const [columnFilters, setColumnFilters] =
- React.useState<ColumnFiltersState>(defaultColumnFilters);
- const [sorting, setSorting] = React.useState<SortingState>(defaultSorting);
-
- const table = useReactTable({
- data,
- columns,
- state: {
- sorting,
- columnVisibility,
- columnFilters,
- },
- onSortingChange: setSorting,
- onColumnFiltersChange: setColumnFilters,
- onColumnVisibilityChange: setColumnVisibility,
- getCoreRowModel: getCoreRowModel(),
- getFilteredRowModel: getFilteredRowModel(),
- getSortedRowModel: getSortedRowModel(),
- getFacetedRowModel: getFacetedRowModel(),
- getFacetedUniqueValues: getFacetedUniqueValues(),
- getExpandedRowModel: getExpandedRowModel(),
- getRowCanExpand: () => Boolean(rowComponent),
- });
-
- return (
- <div className="grid gap-2">
- {toolbarComponent
- ? React.createElement(toolbarComponent, { table })
- : null}
- <Table>
- <TableHeader>
- {table.getHeaderGroups().map((headerGroup) => (
- <TableRow key={headerGroup.id}>
- {headerGroup.headers.map((header) => {
- return (
- <TableHead
- key={header.id}
- colSpan={header.colSpan}
- className={header.column.columnDef.meta?.headerClassName}
- >
- {header.isPlaceholder
- ? null
- : flexRender(
- header.column.columnDef.header,
- header.getContext(),
- )}
- </TableHead>
- );
- })}
- </TableRow>
- ))}
- </TableHeader>
- <TableBody>
- {table.getRowModel().rows?.length ? (
- table.getRowModel().rows.map((row) => (
- <Fragment key={row.id}>
- <TableRow
- data-state={row.getIsExpanded() && "selected"}
- onClick={() => onRowClick?.(row)}
- className="data-[state=selected]:bg-muted/50"
- >
- {row.getVisibleCells().map((cell) => (
- <TableCell
- key={cell.id}
- className={cell.column.columnDef.meta?.cellClassName}
- >
- {flexRender(
- cell.column.columnDef.cell,
- cell.getContext(),
- )}
- </TableCell>
- ))}
- </TableRow>
- {row.getIsExpanded() && (
- <TableRow className="hover:bg-background">
- <TableCell
- className="p-0"
- colSpan={row.getVisibleCells().length}
- >
- {rowComponent
- ? React.createElement(rowComponent, { row })
- : null}
- </TableCell>
- </TableRow>
- )}
- </Fragment>
- ))
- ) : (
- <TableRow>
- <TableCell colSpan={columns.length} className="h-24 text-center">
- {emptyState}
- </TableCell>
- </TableRow>
- )}
- </TableBody>
- </Table>
- </div>
- );
-}
diff --git a/apps/web/src/config/socials.ts b/apps/web/src/config/socials.ts
deleted file mode 100644
index 0287bde64..000000000
--- a/apps/web/src/config/socials.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-import type { ValidIcon } from "../components/icons";
-
-export type Social = {
- title: string;
- href: string;
- icon: ValidIcon;
-};
-
-export const socialsConfig: Social[] = [
- {
- title: "Discord",
- href: "/discord",
- icon: "discord",
- },
- {
- title: "GitHub",
- href: "/github",
- icon: "github",
- },
- {
- title: "Bluesky",
- href: "https://bsky.app/profile/openstatus.dev",
- icon: "bluesky",
- },
- {
- title: "Twitter",
- href: "/twitter",
- icon: "twitter",
- },
- {
- title: "LinkedIn",
- href: "/linkedin",
- icon: "linkedin",
- },
-];
diff --git a/apps/web/src/content/nav.tsx b/apps/web/src/content/nav.tsx
deleted file mode 100644
index e69de29bb..000000000
diff --git a/apps/web/src/data/code-dictionary.ts b/apps/web/src/data/code-dictionary.ts
deleted file mode 100644
index 7967e2760..000000000
--- a/apps/web/src/data/code-dictionary.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-export const codesDict = {
- "1xx": {
- prefix: 1,
- label: "1xx",
- name: "Informational",
- },
- "2xx": {
- prefix: 2,
- label: "2xx",
- name: "Successful",
- },
- "3xx": {
- prefix: 3,
- label: "3xx",
- name: "Redirection",
- },
- "4xx": {
- prefix: 4,
- label: "4xx",
- name: "Client Error",
- },
- "5xx": {
- prefix: 5,
- label: "5xx",
- name: "Server Error",
- },
-} as const;
diff --git a/apps/web/src/data/incidents-dictionary.ts b/apps/web/src/data/incidents-dictionary.ts
deleted file mode 100644
index d51ef8e25..000000000
--- a/apps/web/src/data/incidents-dictionary.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-export const statusDict = {
- investigating: {
- value: "investigating",
- label: "Investigating",
- icon: "search",
- color: "border-status-down/20 bg-status-down/10 text-status-down",
- order: 1,
- },
- identified: {
- value: "identified",
- label: "Identified",
- icon: "fingerprint",
- color:
- "border-status-degraded/20 bg-status-degraded/10 text-status-degraded",
- order: 2,
- },
- monitoring: {
- value: "monitoring",
- label: "Monitoring",
- icon: "activity",
- color:
- "border-status-monitoring/20 bg-status-monitoring/10 text-status-monitoring",
- order: 3,
- },
- resolved: {
- value: "resolved",
- label: "Resolved",
- icon: "search-check",
- color:
- "border-status-operational/20 bg-status-operational/10 text-status-operational",
- order: 4,
- },
- // FIXME: check source of thruth
- maintenance: {
- value: "maintenance",
- label: "Maintenance",
- icon: "hammer",
- color:
- "border-status-monitoring/20 bg-status-monitoring/10 text-status-monitoring",
- order: 0,
- },
-} as const;
diff --git a/apps/web/src/data/trigger-dictionary.ts b/apps/web/src/data/trigger-dictionary.ts
deleted file mode 100644
index 06cbc4f50..000000000
--- a/apps/web/src/data/trigger-dictionary.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import type { ValidIcon } from "../components/icons";
-import type { Trigger } from "../lib/monitor/utils";
-
-export const triggerDict = {
- cron: {
- value: "cron",
- label: "Scheduled",
- icon: "clock",
- },
- api: {
- value: "api",
- label: "On-Demand",
- icon: "network",
- },
- unknown: {
- value: "unknown",
- label: "Unknown",
- icon: "cog",
- },
-} satisfies Record<
- string,
- {
- icon: ValidIcon;
- label: string;
- value: Trigger | "unknown";
- }
->;
diff --git a/apps/web/src/lib/domains.ts b/apps/web/src/lib/domains.ts
deleted file mode 100644
index 07a6b9796..000000000
--- a/apps/web/src/lib/domains.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-export const getSubdomain = (name: string, apexName: string) => {
- if (name === apexName) return null;
- return name.slice(0, name.length - apexName.length - 1);
-};
-
-export const getApexDomain = (url: string) => {
- let domain: string;
- try {
- domain = new URL(url).hostname;
- } catch (_e) {
- return "";
- }
- const parts = domain.split(".");
- if (parts.length > 2) {
- // if it's a subdomain (e.g. dub.vercel.app), return the last 2 parts
- return parts.slice(-2).join(".");
- }
- // if it's a normal domain (e.g. dub.sh), we return the domain
- return domain;
-};
diff --git a/apps/web/src/lib/github.ts b/apps/web/src/lib/github.ts
deleted file mode 100644
index c78e01748..000000000
--- a/apps/web/src/lib/github.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import * as z from "zod";
-
-const schema = z.object({
- stargazers_count: z.number(),
-});
-
-export async function getGitHubStars() {
- const res = await fetch(
- "https://api.github.com/repos/openstatusHQ/openstatus",
- { next: { revalidate: 600 } }, // 10min
- );
- const json = await res.json();
- const github = schema.safeParse(json);
-
- if (!github.success) return 0;
- return github.data.stargazers_count;
-}
diff --git a/apps/web/src/lib/maintenances/utils.ts b/apps/web/src/lib/maintenances/utils.ts
deleted file mode 100644
index 9d0f77929..000000000
--- a/apps/web/src/lib/maintenances/utils.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-import type { Maintenance } from "@openstatus/db/src/schema";
-
-export function isActiveMaintenance(maintenances?: Maintenance[]) {
- if (!maintenances) return false;
- return maintenances.some((maintenance) => {
- return maintenance.from <= new Date() && maintenance.to >= new Date();
- });
-}
diff --git a/apps/web/src/lib/preferred-settings/client.ts b/apps/web/src/lib/preferred-settings/client.ts
deleted file mode 100644
index ea8281a1b..000000000
--- a/apps/web/src/lib/preferred-settings/client.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-import { useState } from "react";
-
-import { COOKIE_NAME } from "./shared";
-import type { PreferredSettings } from "./validation";
-import { preferencesSchema } from "./validation";
-
-function getPreferredSettingsCookie() {
- const cookie = document.cookie
- .split(";")
- .find((cookie) => cookie.trim().startsWith(`${COOKIE_NAME}=`));
- if (!cookie) return {};
- const settings = preferencesSchema.safeParse(
- JSON.parse(cookie.split("=")[1]),
- );
- if (!settings.success) return {};
- return settings.data;
-}
-
-function setPreferredSettingsCookie(value: Record<string, unknown>) {
- const month = 30 * 24 * 60 * 60 * 1000;
- const expires = new Date(Date.now() + month).toUTCString();
- document.cookie = `${COOKIE_NAME}=${JSON.stringify(
- value,
- )}; path=/; expires=${expires}`;
-}
-
-/**
- * Update user preferences and store them in a cookie accessible on the client and server
- */
-export function usePreferredSettings(defaultValue: PreferredSettings) {
- const [settings, setSettings] = useState<PreferredSettings>(defaultValue);
-
- const handleChange = (value: Record<string, unknown>) => {
- const settings = preferencesSchema.safeParse(value);
-
- if (!settings.success) return;
-
- const currentSettings = getPreferredSettingsCookie();
- const newSettings = { ...currentSettings, ...settings.data };
-
- setPreferredSettingsCookie(newSettings);
- setSettings(newSettings);
- };
-
- return [settings, handleChange] as const;
-}
diff --git a/apps/web/src/lib/preferred-settings/server.ts b/apps/web/src/lib/preferred-settings/server.ts
deleted file mode 100644
index 6374044de..000000000
--- a/apps/web/src/lib/preferred-settings/server.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import { cookies } from "next/headers";
-
-import { COOKIE_NAME } from "./shared";
-import { preferencesSchema } from "./validation";
-
-export async function getPreferredSettings() {
- const cookieStore = await cookies();
- const cookie = cookieStore.get(COOKIE_NAME);
- const parsed = cookie ? JSON.parse(cookie.value) : {};
- const settings = preferencesSchema.safeParse(parsed);
- if (!settings.success) return undefined;
- return settings.data;
-}
-
-export type PreferredSettings = Awaited<
- ReturnType<typeof getPreferredSettings>
->;
diff --git a/apps/web/src/lib/preferred-settings/shared.ts b/apps/web/src/lib/preferred-settings/shared.ts
deleted file mode 100644
index cd847d59b..000000000
--- a/apps/web/src/lib/preferred-settings/shared.ts
+++ /dev/null
@@ -1 +0,0 @@
-export const COOKIE_NAME = "preferred-settings";
diff --git a/apps/web/src/lib/preferred-settings/validation.ts b/apps/web/src/lib/preferred-settings/validation.ts
deleted file mode 100644
index 899f073ce..000000000
--- a/apps/web/src/lib/preferred-settings/validation.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-import { z } from "zod";
-
-export const preferencesSchema = z
- .object({
- combinedRegions: z.boolean().nullable().prefault(false).optional(),
- // ... other settings to store user preferences
- // accessible via document.cookie in the client and cookies() on the server
- })
- .optional();
-
-export type PreferredSettings = z.infer<typeof preferencesSchema>;
diff --git a/apps/web/src/lib/timezone.ts b/apps/web/src/lib/timezone.ts
deleted file mode 100644
index e6643c599..000000000
--- a/apps/web/src/lib/timezone.ts
+++ /dev/null
@@ -1,108 +0,0 @@
-import { format, getTimezoneOffset, utcToZonedTime } from "date-fns-tz";
-import { headers } from "next/headers";
-
-export async function getRequestHeaderTimezone() {
- const headersList = await headers();
-
- /**
- * Vercel includes ip timezone to request header
- */
- const requestTimezone = headersList.get("x-vercel-ip-timezone");
-
- return requestTimezone;
-}
-
-export async function convertTimezoneToGMT(defaultTimezone?: string) {
- const requestTimezone = await getRequestHeaderTimezone();
-
- /**
- * Server region timezone as fallback
- */
- const clientTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
-
- const timezone = defaultTimezone || requestTimezone || clientTimezone;
-
- if (!supportedTimezones.includes(timezone)) return "Etc/UTC";
-
- const msOffset = getTimezoneOffset(timezone);
-
- if (Number.isNaN(msOffset)) return "Etc/UTC";
-
- const hrOffset = Math.round(msOffset / (1000 * 60 * 60)); // avoid weird 30min timezones
- const offset = hrOffset >= 0 ? `-${hrOffset}` : `+${Math.abs(hrOffset)}`;
-
- return `Etc/GMT${offset}` as const;
-}
-
-export function getServerTimezoneUTCFormat() {
- const now = new Date();
- const now_utc = new Date(now.toUTCString().slice(0, -4)); // remove the GMT end
-
- return format(now_utc, "LLL dd, y HH:mm:ss (z)", { timeZone: "UTC" });
-}
-
-export function getServerTimezoneFormat() {
- return format(new Date(), "LLL dd, y HH:mm:ss (z)");
-}
-
-export function formatDate(date: Date) {
- return format(date, "LLL dd, y", { timeZone: "UTC" });
-}
-
-export function formatDateTime(date: Date) {
- return format(date, "LLL dd, y HH:mm:ss zzz", { timeZone: "UTC" });
-}
-
-export function formatTime(date: Date) {
- return format(date, "HH:mm:ss zzz", { timeZone: "UTC" });
-}
-
-/**
- * All supported browser / node timezones
- */
-export const supportedTimezones = Intl.supportedValuesOf("timeZone");
-
-export async function getClosestTimezone(defaultTimezone?: string) {
- const requestTimezone = await getRequestHeaderTimezone();
-
- /**
- * Server region timezone as fallback
- */
- const clientTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
-
- const timezone = defaultTimezone || requestTimezone || clientTimezone;
-
- if (!supportedTimezones.includes(timezone)) return "CET";
-
- const now = new Date();
-
- const estTime = utcToZonedTime(now, "America/New_York");
- const pstTime = utcToZonedTime(now, "America/Los_Angeles");
- const cetTime = utcToZonedTime(now, "Europe/Paris");
- const utcTime = utcToZonedTime(now, "UTC");
-
- const timeDifferences = {
- EST: Math.abs(now.getTime() - estTime.getTime()),
- PST: Math.abs(now.getTime() - pstTime.getTime()),
- CET: Math.abs(now.getTime() - cetTime.getTime()),
- UTC: Math.abs(now.getTime() - utcTime.getTime()),
- };
-
- const closestTimezone = Object.keys(timeDifferences).reduce(
- (prev, curr) => {
- if (
- timeDifferences[curr as keyof typeof timeDifferences] <
- prev.minDifference
- ) {
- return {
- timezone: curr,
- minDifference: timeDifferences[curr as keyof typeof timeDifferences],
- };
- }
- return prev;
- },
- { timezone: "UTC", minDifference: Number.POSITIVE_INFINITY },
- );
-
- return closestTimezone.timezone as keyof typeof timeDifferences;
-}
diff --git a/apps/web/src/trpc/client.ts b/apps/web/src/trpc/client.ts
deleted file mode 100644
index 9fe37e96c..000000000
--- a/apps/web/src/trpc/client.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import type { AppRouter } from "@openstatus/api";
-import { createTRPCClient } from "@trpc/client";
-
-import { endingLink, sentryLoggerLink } from "./shared";
-
-export const api = createTRPCClient<AppRouter>({
- links: [
- sentryLoggerLink(),
- endingLink({
- headers: {
- "x-trpc-source": "client",
- },
- }),
- ],
-});
-
-export { type RouterInputs, type RouterOutputs } from "@openstatus/api";
diff --git a/apps/web/src/types/utils.ts b/apps/web/src/types/utils.ts
deleted file mode 100644
index 2f45b1129..000000000
--- a/apps/web/src/types/utils.ts
+++ /dev/null
@@ -1 +0,0 @@
-export type Writeable<T> = { -readonly [P in keyof T]: T[P] };
diff --git a/apps/workflows/src/cron/checker-payload.test.ts b/apps/workflows/src/cron/checker-payload.test.ts
index 15c897114..87b06dde2 100644
--- a/apps/workflows/src/cron/checker-payload.test.ts
+++ b/apps/workflows/src/cron/checker-payload.test.ts
@@ -8,7 +8,7 @@ import { z } from "zod";
import {
type CheckerPublisher,
type TaskInput,
- buildCheckerPayload,
+ buildCronCheckerPayload,
checkerTopic,
publishCheckerTasks,
} from "./checker-payload";
@@ -58,7 +58,7 @@ const input = (
type Published = {
topic: string;
- payload: ReturnType<typeof buildCheckerPayload>;
+ payload: ReturnType<typeof buildCronCheckerPayload>;
attributes: Record<string, string>;
};
@@ -80,9 +80,9 @@ const recordingPublisher = (failTopics: string[] = []) => {
return { published, publisher };
};
-describe("buildCheckerPayload", () => {
+describe("buildCronCheckerPayload", () => {
test("http keeps the request shape the checker binds", () => {
- const payload = buildCheckerPayload(
+ const payload = buildCronCheckerPayload(
input({
row: monitorRow({
assertions:
@@ -112,7 +112,7 @@ describe("buildCheckerPayload", () => {
test.each(["tcp", "dns", "icmp"] as const)(
"%s sends the url as uri",
(jobType) => {
- const payload = buildCheckerPayload(
+ const payload = buildCronCheckerPayload(
input({ row: monitorRow({ jobType, url: "example.com:443" }) }),
);
@@ -126,7 +126,7 @@ describe("buildCheckerPayload", () => {
);
test("grpc sends headers as a map and defaults tls", () => {
- const payload = buildCheckerPayload(
+ const payload = buildCronCheckerPayload(
input({
row: monitorRow({
jobType: "grpc",
@@ -168,7 +168,7 @@ describe("publishCheckerTasks", () => {
expect(published).toEqual([
{
topic: "checker-iad",
- payload: buildCheckerPayload(input({ row, region: "iad" })),
+ payload: buildCronCheckerPayload(input({ row, region: "iad" })),
attributes: {
jobType: "tcp",
periodicity: "5m",
diff --git a/apps/workflows/src/cron/checker-payload.ts b/apps/workflows/src/cron/checker-payload.ts
index 700f8968a..8d4205d6a 100644
--- a/apps/workflows/src/cron/checker-payload.ts
+++ b/apps/workflows/src/cron/checker-payload.ts
@@ -4,14 +4,7 @@ import type {
Region,
monitorPeriodicitySchema,
} from "@openstatus/db/src/schema/constants";
-import {
- type DNSPayloadSchema,
- type grpcPayloadSchema,
- type httpPayloadSchema,
- type icmpPayloadSchema,
- type tpcPayloadSchema,
- transformHeaders,
-} from "@openstatus/utils";
+import { type CheckerPayload, buildCheckerPayload } from "@openstatus/utils";
import { Effect, Result } from "effect";
import type { z } from "zod";
@@ -24,106 +17,18 @@ export type TaskInput = {
region: Region;
};
-export type CheckerPayload =
- | z.infer<typeof httpPayloadSchema>
- | z.infer<typeof tpcPayloadSchema>
- | z.infer<typeof DNSPayloadSchema>
- | z.infer<typeof icmpPayloadSchema>
- | z.infer<typeof grpcPayloadSchema>;
-
// timestamp needs to be in ms
-export function buildCheckerPayload({
+export function buildCronCheckerPayload({
row,
timestamp,
status,
}: Omit<TaskInput, "region">): CheckerPayload {
- const otelConfig = row.otelEndpoint
- ? {
- endpoint: row.otelEndpoint,
- headers: transformHeaders(row.otelHeaders),
- }
- : undefined;
-
- switch (row.jobType) {
- case "http":
- return {
- workspaceId: String(row.workspaceId),
- monitorId: String(row.id),
- url: row.url,
- method: row.method || "GET",
- cronTimestamp: timestamp,
- body: row.body,
- headers: row.headers,
- status: status,
- assertions: row.assertions ? JSON.parse(row.assertions) : null,
- degradedAfter: row.degradedAfter,
- timeout: row.timeout,
- trigger: "cron",
- otelConfig,
- retry: row.retry || 3,
- followRedirects:
- row.followRedirects === null ? true : row.followRedirects,
- };
- case "tcp":
- return {
- workspaceId: String(row.workspaceId),
- monitorId: String(row.id),
- uri: row.url,
- status: status,
- assertions: row.assertions ? JSON.parse(row.assertions) : null,
- cronTimestamp: timestamp,
- degradedAfter: row.degradedAfter,
- timeout: row.timeout,
- trigger: "cron",
- retry: row.retry || 3,
- otelConfig,
- };
- case "dns":
- return {
- workspaceId: String(row.workspaceId),
- monitorId: String(row.id),
- uri: row.url,
- cronTimestamp: timestamp,
- status: status,
- assertions: row.assertions ? JSON.parse(row.assertions) : null,
- degradedAfter: row.degradedAfter,
- timeout: row.timeout,
- trigger: "cron",
- otelConfig,
- retry: row.retry || 3,
- };
- case "icmp":
- return {
- workspaceId: String(row.workspaceId),
- monitorId: String(row.id),
- uri: row.url,
- cronTimestamp: timestamp,
- status: status,
- degradedAfter: row.degradedAfter,
- timeout: row.timeout,
- trigger: "cron",
- otelConfig,
- retry: row.retry || 3,
- };
- case "grpc":
- return {
- workspaceId: String(row.workspaceId),
- monitorId: String(row.id),
- uri: row.url,
- service: row.grpcService ?? undefined,
- tls: row.grpcTls ?? "tls",
- headers: transformHeaders(row.headers),
- cronTimestamp: timestamp,
- status: status,
- degradedAfter: row.degradedAfter,
- timeout: row.timeout,
- trigger: "cron",
- otelConfig,
- retry: row.retry || 3,
- };
- default:
- throw new Error("Invalid jobType");
- }
+ return buildCheckerPayload({
+ monitor: row,
+ status,
+ trigger: "cron",
+ timestamp,
+ });
}
export function checkerTopic(region: Region, periodicity: Periodicity) {
@@ -158,7 +63,7 @@ export async function publishCheckerTasks(
try: () =>
publisher.publish(
checkerTopic(input.region, periodicity),
- Buffer.from(JSON.stringify(buildCheckerPayload(input))),
+ Buffer.from(JSON.stringify(buildCronCheckerPayload(input))),
{
jobType: input.row.jobType,
periodicity,
diff --git a/apps/workflows/src/cron/checker.ts b/apps/workflows/src/cron/checker.ts
index 9ed195be1..5d3f9914b 100644
--- a/apps/workflows/src/cron/checker.ts
+++ b/apps/workflows/src/cron/checker.ts
@@ -33,7 +33,7 @@ import {
type CheckerPublisher,
type Periodicity,
type TaskInput,
- buildCheckerPayload,
+ buildCronCheckerPayload,
publishCheckerTasks,
} from "./checker-payload";
@@ -320,7 +320,7 @@ const createCronTask = async (
parent: string,
client: CloudTasksClient,
) => {
- const payload = buildCheckerPayload({ row, timestamp, status });
+ const payload = buildCronCheckerPayload({ row, timestamp, status });
const regionInfo = regionDict[region];
let regionHeader = {};
if (regionInfo.provider === "fly") {
diff --git a/packages/api/src/router/checker.ts b/packages/api/src/router/checker.ts
index 60deba8ef..e7fe33eb4 100644
--- a/packages/api/src/router/checker.ts
+++ b/packages/api/src/router/checker.ts
@@ -12,13 +12,10 @@ import { and, db, eq } from "@openstatus/db";
import { monitor, selectMonitorSchema } from "@openstatus/db/src/schema";
import { monitorRegionSchema } from "@openstatus/db/src/schema/constants";
import {
- type httpPayloadSchema,
- type grpcPayloadSchema,
- type icmpPayloadSchema,
GRPC_TLS_MODES,
+ buildCheckerPayload,
headerPairSchema,
safeUrlSchema,
- type tpcPayloadSchema,
transformHeaders,
} from "@openstatus/utils";
import { TRPCError } from "@trpc/server";
@@ -578,126 +575,16 @@ export async function testGrpc(input: z.infer<typeof grpcTestInput>) {
export async function triggerChecker(
input: z.infer<typeof selectMonitorSchema>,
) {
- let payload:
- | z.infer<typeof httpPayloadSchema>
- | z.infer<typeof tpcPayloadSchema>
- | z.infer<typeof icmpPayloadSchema>
- | z.infer<typeof grpcPayloadSchema>
- | null = null;
-
if (process.env.NODE_ENV !== "production") {
return;
}
- const timestamp = Date.now();
-
- if (input.jobType === "http") {
- payload = {
- workspaceId: String(input.workspaceId),
- monitorId: String(input.id),
- url: input.url,
- method: input.method || "GET",
- cronTimestamp: timestamp,
- body: input.body,
- headers: input.headers,
- status: "active",
- assertions: input.assertions ? JSON.parse(input.assertions) : null,
- degradedAfter: input.degradedAfter,
- timeout: input.timeout,
- trigger: "cron",
- otelConfig: input.otelEndpoint
- ? {
- endpoint: input.otelEndpoint,
- headers: transformHeaders(input.otelHeaders),
- }
- : undefined,
- retry: input.retry || 3,
- followRedirects: input.followRedirects || true,
- };
- }
- if (input.jobType === "tcp") {
- payload = {
- workspaceId: String(input.workspaceId),
- monitorId: String(input.id),
- uri: input.url,
- status: "active",
- assertions: input.assertions ? JSON.parse(input.assertions) : null,
- cronTimestamp: timestamp,
- degradedAfter: input.degradedAfter,
- timeout: input.timeout,
- trigger: "cron",
- retry: input.retry || 3,
- otelConfig: input.otelEndpoint
- ? {
- endpoint: input.otelEndpoint,
- headers: transformHeaders(input.otelHeaders),
- }
- : undefined,
- followRedirects: input.followRedirects || true,
- };
- }
- if (input.jobType === "dns") {
- payload = {
- workspaceId: String(input.workspaceId),
- monitorId: String(input.id),
- uri: input.url,
- status: "active",
- assertions: input.assertions ? JSON.parse(input.assertions) : null,
- cronTimestamp: timestamp,
- degradedAfter: input.degradedAfter,
- timeout: input.timeout,
- trigger: "cron",
- retry: input.retry || 3,
- otelConfig: input.otelEndpoint
- ? {
- endpoint: input.otelEndpoint,
- headers: transformHeaders(input.otelHeaders),
- }
- : undefined,
- followRedirects: input.followRedirects || true,
- };
- }
- if (input.jobType === "icmp") {
- payload = {
- workspaceId: String(input.workspaceId),
- monitorId: String(input.id),
- uri: input.url,
- status: "active",
- cronTimestamp: timestamp,
- degradedAfter: input.degradedAfter,
- timeout: input.timeout,
- trigger: "cron",
- retry: input.retry || 3,
- otelConfig: input.otelEndpoint
- ? {
- endpoint: input.otelEndpoint,
- headers: transformHeaders(input.otelHeaders),
- }
- : undefined,
- };
- }
- if (input.jobType === "grpc") {
- payload = {
- workspaceId: String(input.workspaceId),
- monitorId: String(input.id),
- uri: input.url,
- service: input.grpcService ?? undefined,
- tls: input.grpcTls ?? "tls",
- headers: transformHeaders(input.headers),
- status: "active",
- cronTimestamp: timestamp,
- degradedAfter: input.degradedAfter,
- timeout: input.timeout,
- trigger: "cron",
- retry: input.retry || 3,
- otelConfig: input.otelEndpoint
- ? {
- endpoint: input.otelEndpoint,
- headers: transformHeaders(input.otelHeaders),
- }
- : undefined,
- };
- }
+ const payload = buildCheckerPayload({
+ monitor: input,
+ status: "active",
+ trigger: "cron",
+ timestamp: Date.now(),
+ });
const allResult = [];
for (const region of input.regions) {
diff --git a/packages/api/src/router/statusPage.lookup.test.ts b/packages/api/src/router/statusPage.lookup.test.ts
new file mode 100644
index 000000000..cf1d53acc
--- /dev/null
+++ b/packages/api/src/router/statusPage.lookup.test.ts
@@ -0,0 +1,65 @@
+import { db, eq } from "@openstatus/db";
+import { page } from "@openstatus/db/src/schema";
+import {
+ createPage,
+ createTestWorkspace,
+} from "@openstatus/db/src/test/factories";
+import { NextRequest } from "next/server.js";
+import { afterAll, beforeAll, describe, expect, test } from "vitest";
+
+import { appRouter } from "../root";
+import { createInnerTRPCContext } from "../trpc";
+
+let workspaceId: number;
+let pageId: number;
+let slug: string;
+const customDomain = `status-${Date.now()}.lookup-test.dev`;
+
+const caller = () =>
+ appRouter.createCaller(
+ createInnerTRPCContext({
+ req: new NextRequest("http://rsc.internal"),
+ session: null,
+ }),
+ );
+
+beforeAll(async () => {
+ const fixture = await createTestWorkspace();
+ workspaceId = fixture.workspace.id;
+ const _page = await createPage(workspaceId, { customDomain });
+ pageId = _page.id;
+ slug = _page.slug;
+});
+
+afterAll(async () => {
+ await db.delete(page).where(eq(page.workspaceId, workspaceId));
+});
+
+describe("statusPage lookup by slug or custom domain", () => {
+ test("resolves a page by its slug", async () => {
+ const result = await caller().statusPage.get({ slug });
+ expect(result?.id).toBe(pageId);
+ });
+
+ test("resolves the same page by its custom domain", async () => {
+ const result = await caller().statusPage.get({ slug: customDomain });
+ expect(result?.id).toBe(pageId);
+ });
+
+ test("returns null for an unknown host", async () => {
+ const result = await caller().statusPage.get({
+ slug: `missing-${customDomain}`,
+ });
+ expect(result).toBeNull();
+ });
+
+ test("getLight and getUptime use the same matching", async () => {
+ const light = await caller().statusPage.getLight({ slug: customDomain });
+ expect(light).not.toBeNull();
+ const uptime = await caller().statusPage.getUptime({
+ slug: customDomain,
+ pageComponentIds: [],
+ });
+ expect(uptime).toEqual([]);
+ });
+});
diff --git a/packages/api/src/router/statusPage.ts b/packages/api/src/router/statusPage.ts
index 684ae756f..fa5e7aa69 100644
--- a/packages/api/src/router/statusPage.ts
+++ b/packages/api/src/router/statusPage.ts
@@ -40,6 +40,7 @@ import { createTRPCRouter, publicProcedure } from "../trpc";
import {
type StatusData,
activeReportStatus,
+ fetchByJobType,
fillStatusDataFor45Days,
fillStatusDataFor45DaysNoop,
getEvents,
@@ -80,6 +81,10 @@ const gateFieldsSchema = selectPageSchema.pick({
// Password for cookie-less server callers (feeds, `?pw=` links).
const queryPasswordSchema = z.string().nullish();
+// A host reaches its page through either the slug or the custom domain.
+const bySlugOrDomain = (slug: string) =>
+ sql`lower(${page.slug}) = ${slug} OR lower(${page.customDomain}) = ${slug}`;
+
export const statusPageRouter = createTRPCRouter({
get: publicProcedure
.input(
@@ -98,7 +103,7 @@ export const statusPageRouter = createTRPCRouter({
if (!opts.input.slug) return null;
const _page = await opts.ctx.db.query.page.findFirst({
- where: sql`lower(${page.slug}) = ${opts.input.slug} OR lower(${page.customDomain}) = ${opts.input.slug}`,
+ where: bySlugOrDomain(opts.input.slug),
with: {
workspace: true,
statusReports: {
@@ -550,7 +555,7 @@ export const statusPageRouter = createTRPCRouter({
// Single query with all relations
const _page = await opts.ctx.db.query.page.findFirst({
- where: sql`lower(${page.slug}) = ${opts.input.slug} OR lower(${page.customDomain}) = ${opts.input.slug}`,
+ where: bySlugOrDomain(opts.input.slug),
with: {
workspace: true,
statusReports: {
@@ -657,7 +662,7 @@ export const statusPageRouter = createTRPCRouter({
if (!opts.input.slug) return null;
const _page = await opts.ctx.db.query.page.findFirst({
- where: sql`lower(${page.slug}) = ${opts.input.slug} OR lower(${page.customDomain}) = ${opts.input.slug}`,
+ where: bySlugOrDomain(opts.input.slug),
columns: {
slug: true,
customDomain: true,
@@ -694,9 +699,7 @@ export const statusPageRouter = createTRPCRouter({
const _page = await opts.ctx.db
.select()
.from(page)
- .where(
- sql`lower(${page.slug}) = ${opts.input.slug} OR lower(${page.customDomain}) = ${opts.input.slug}`,
- )
+ .where(bySlugOrDomain(opts.input.slug))
.get();
if (!_page) return null;
@@ -749,7 +752,7 @@ export const statusPageRouter = createTRPCRouter({
if (!input.slug) return null;
const _page = await opts.ctx.db.query.page.findFirst({
- where: sql`lower(${page.slug}) = ${input.slug} OR lower(${page.customDomain}) = ${input.slug}`,
+ where: bySlugOrDomain(input.slug),
with: {
maintenances: {
with: {
@@ -793,70 +796,17 @@ export const statusPageRouter = createTRPCRouter({
const monitors = pageComponents.filter(isMonitorComponent);
- const monitorsByType = {
- http: monitors.filter((c) => c.monitor.jobType === "http"),
- tcp: monitors.filter((c) => c.monitor.jobType === "tcp"),
- dns: monitors.filter((c) => c.monitor.jobType === "dns"),
- icmp: monitors.filter((c) => c.monitor.jobType === "icmp"),
- grpc: monitors.filter((c) => c.monitor.jobType === "grpc"),
- };
-
- const proceduresByType = {
- http: getStatusProcedure("45d", "http"),
- tcp: getStatusProcedure("45d", "tcp"),
- dns: getStatusProcedure("45d", "dns"),
- icmp: getStatusProcedure("45d", "icmp"),
- grpc: getStatusProcedure("45d", "grpc"),
- };
-
// Manual mode never touches Tinybird. Otherwise race the reads against
// the fallback budget: a slow (>5s) or erroring Tinybird degrades the
// whole page to manual mode so bars still render from DB events.
const tinybird = await withTinybirdFallback(() =>
input.barType === "manual"
- ? Promise.resolve([null, null, null, null, null])
- : Promise.all(
- Object.entries(proceduresByType).map(([type, procedure]) => {
- const monitorIds = monitorsByType[
- type as keyof typeof proceduresByType
- ].map((c) => c.monitor.id.toString());
- if (monitorIds.length === 0) return null;
- return procedure({ monitorIds });
- }),
- ),
+ ? Promise.resolve(null)
+ : fetchByJobType(monitors, (type) => getStatusProcedure("45d", type)),
);
const tinybirdUnhealthy = !tinybird.ok;
- const [statusHttp, statusTcp, statusDns, statusIcmp, statusGrpc] =
- tinybird.data ?? [null, null, null, null, null];
-
- const statusDataByMonitorId = new Map<
- string,
- | Awaited<ReturnType<(typeof proceduresByType)["http"]>>["data"]
- | Awaited<ReturnType<(typeof proceduresByType)["tcp"]>>["data"]
- | Awaited<ReturnType<(typeof proceduresByType)["dns"]>>["data"]
- | Awaited<ReturnType<(typeof proceduresByType)["icmp"]>>["data"]
- | Awaited<ReturnType<(typeof proceduresByType)["grpc"]>>["data"]
- >();
-
- // Consolidate status data from all monitor types into the map
- for (const statusResult of [
- statusHttp,
- statusTcp,
- statusDns,
- statusIcmp,
- statusGrpc,
- ]) {
- if (statusResult?.data) {
- statusResult.data.forEach((status) => {
- const monitorId = status.monitorId;
- if (!statusDataByMonitorId.has(monitorId)) {
- statusDataByMonitorId.set(monitorId, []);
- }
- statusDataByMonitorId.get(monitorId)?.push(status);
- });
- }
- }
+ const statusDataByMonitorId = tinybird.data ?? new Map<string, never[]>();
const parsedConfiguration = pageConfigurationSchema.safeParse(
_page.configuration ?? {},
@@ -999,9 +949,7 @@ export const statusPageRouter = createTRPCRouter({
const _page = await opts.ctx.db
.select()
.from(page)
- .where(
- sql`lower(${page.slug}) = ${opts.input.slug} OR lower(${page.customDomain}) = ${opts.input.slug}`,
- )
+ .where(bySlugOrDomain(opts.input.slug))
.get();
if (!_page) return null;
@@ -1121,7 +1069,7 @@ export const statusPageRouter = createTRPCRouter({
// NOTE: revalidate the public monitors first
const _page = await opts.ctx.db.query.page.findFirst({
- where: sql`lower(${page.slug}) = ${opts.input.slug} OR lower(${page.customDomain}) = ${opts.input.slug}`,
+ where: bySlugOrDomain(opts.input.slug),
with: {
pageComponents: {
with: {
@@ -1143,101 +1091,13 @@ export const statusPageRouter = createTRPCRouter({
.filter(isMonitorComponent)
.filter((c) => c.monitor?.public);
- const monitorsByType = {
- http: publicMonitors.filter((c) => c.monitor.jobType === "http"),
- tcp: publicMonitors.filter((c) => c.monitor.jobType === "tcp"),
- dns: publicMonitors.filter((c) => c.monitor.jobType === "dns"),
- icmp: publicMonitors.filter((c) => c.monitor.jobType === "icmp"),
- grpc: publicMonitors.filter((c) => c.monitor.jobType === "grpc"),
- };
-
- const proceduresByType = {
- http: getMetricsLatencyMultiProcedure("1d", "http"),
- tcp: getMetricsLatencyMultiProcedure("1d", "tcp"),
- dns: getMetricsLatencyMultiProcedure("1d", "dns"),
- icmp: getMetricsLatencyMultiProcedure("1d", "icmp"),
- grpc: getMetricsLatencyMultiProcedure("1d", "grpc"),
- };
-
// Slow/erroring Tinybird → empty latency data so the page still renders.
const metrics = await withTinybirdFallback(() =>
- Promise.all(
- Object.entries(proceduresByType).map(([type, procedure]) => {
- const monitorIds = monitorsByType[
- type as keyof typeof proceduresByType
- ].map((c) => c.monitor.id.toString());
- if (monitorIds.length === 0) return null;
- return procedure({ monitorIds });
- }),
+ fetchByJobType(publicMonitors, (type) =>
+ getMetricsLatencyMultiProcedure("1d", type),
),
);
-
- const [
- metricsLatencyMultiHttp,
- metricsLatencyMultiTcp,
- metricsLatencyMultiDns,
- metricsLatencyMultiIcmp,
- metricsLatencyMultiGrpc,
- ] = metrics.data ?? [null, null, null, null, null];
-
- const metricsDataByMonitorId = new Map<
- string,
- | Awaited<ReturnType<(typeof proceduresByType)["http"]>>["data"]
- | Awaited<ReturnType<(typeof proceduresByType)["tcp"]>>["data"]
- | Awaited<ReturnType<(typeof proceduresByType)["dns"]>>["data"]
- | Awaited<ReturnType<(typeof proceduresByType)["icmp"]>>["data"]
- | Awaited<ReturnType<(typeof proceduresByType)["grpc"]>>["data"]
- >();
-
- if (metricsLatencyMultiHttp?.data) {
- metricsLatencyMultiHttp.data.forEach((metric) => {
- const monitorId = metric.monitorId;
- if (!metricsDataByMonitorId.has(monitorId)) {
- metricsDataByMonitorId.set(monitorId, []);
- }
- metricsDataByMonitorId.get(monitorId)?.push(metric);
- });
- }
-
- if (metricsLatencyMultiTcp?.data) {
- metricsLatencyMultiTcp.data.forEach((metric) => {
- const monitorId = metric.monitorId;
- if (!metricsDataByMonitorId.has(monitorId)) {
- metricsDataByMonitorId.set(monitorId, []);
- }
- metricsDataByMonitorId.get(monitorId)?.push(metric);
- });
- }
-
- if (metricsLatencyMultiDns?.data) {
- metricsLatencyMultiDns.data.forEach((metric) => {
- const monitorId = metric.monitorId;
- if (!metricsDataByMonitorId.has(monitorId)) {
- metricsDataByMonitorId.set(monitorId, []);
- }
- metricsDataByMonitorId.get(monitorId)?.push(metric);
- });
- }
-
- if (metricsLatencyMultiIcmp?.data) {
- metricsLatencyMultiIcmp.data.forEach((metric) => {
- const monitorId = metric.monitorId;
- if (!metricsDataByMonitorId.has(monitorId)) {
- metricsDataByMonitorId.set(monitorId, []);
- }
- metricsDataByMonitorId.get(monitorId)?.push(metric);
- });
- }
-
- if (metricsLatencyMultiGrpc?.data) {
- metricsLatencyMultiGrpc.data.forEach((metric) => {
- const monitorId = metric.monitorId;
- if (!metricsDataByMonitorId.has(monitorId)) {
- metricsDataByMonitorId.set(monitorId, []);
- }
- metricsDataByMonitorId.get(monitorId)?.push(metric);
- });
- }
+ const metricsDataByMonitorId = metrics.data ?? new Map<string, never[]>();
return publicMonitors.map((c) => {
const monitorId = c.monitor.id.toString();
@@ -1262,7 +1122,7 @@ export const statusPageRouter = createTRPCRouter({
if (!opts.input.slug) return null;
const _page = await opts.ctx.db.query.page.findFirst({
- where: sql`lower(${page.slug}) = ${opts.input.slug} OR lower(${page.customDomain}) = ${opts.input.slug}`,
+ where: bySlugOrDomain(opts.input.slug),
with: {
pageComponents: {
where: eq(pageComponent.monitorId, opts.input.id),
@@ -1384,7 +1244,7 @@ export const statusPageRouter = createTRPCRouter({
if (!opts.input.slug) return null;
const _page = await opts.ctx.db.query.page.findFirst({
- where: sql`lower(${page.slug}) = ${opts.input.slug} OR lower(${page.customDomain}) = ${opts.input.slug}`,
+ where: bySlugOrDomain(opts.input.slug),
with: {
workspace: true,
},
@@ -1514,7 +1374,7 @@ export const statusPageRouter = createTRPCRouter({
if (!opts.input.slug) return null;
const _page = await opts.ctx.db.query.page.findFirst({
- where: sql`lower(${page.slug}) = ${opts.input.slug} OR lower(${page.customDomain}) = ${opts.input.slug}`,
+ where: bySlugOrDomain(opts.input.slug),
});
if (!_page) {
@@ -1583,7 +1443,7 @@ export const statusPageRouter = createTRPCRouter({
if (!opts.input.slug) return null;
const _page = await opts.ctx.db.query.page.findFirst({
- where: sql`lower(${page.slug}) = ${opts.input.slug} OR lower(${page.customDomain}) = ${opts.input.slug}`,
+ where: bySlugOrDomain(opts.input.slug),
});
if (!_page) {
@@ -1622,7 +1482,7 @@ export const statusPageRouter = createTRPCRouter({
)
.query(async (opts) => {
const _page = await opts.ctx.db.query.page.findFirst({
- where: sql`lower(${page.slug}) = ${opts.input.slug} OR lower(${page.customDomain}) = ${opts.input.slug}`,
+ where: bySlugOrDomain(opts.input.slug),
columns: { password: true, accessType: true },
});
if (!_page || _page.accessType !== "password") return false;
diff --git a/packages/api/src/router/statusPage.utils.test.ts b/packages/api/src/router/statusPage.utils.test.ts
index f3e0e7f05..219399752 100644
--- a/packages/api/src/router/statusPage.utils.test.ts
+++ b/packages/api/src/router/statusPage.utils.test.ts
@@ -9,6 +9,7 @@ import { describe, expect, it } from "vitest";
import {
currentImpactByComponent,
+ fetchByJobType,
fillStatusDataFor45Days,
getEvents,
getUptime,
@@ -2263,3 +2264,63 @@ describe("withTinybirdFallback", () => {
expect(result).toEqual({ ok: false, data: null });
});
});
+
+describe("fetchByJobType", () => {
+ const component = (id: number, jobType: string) => ({
+ monitor: { id, jobType },
+ });
+
+ it("queries each job type once, only with its own monitors", async () => {
+ const calls: { type: string; monitorIds: string[] }[] = [];
+ await fetchByJobType(
+ [component(1, "http"), component(2, "tcp"), component(3, "http")],
+ (type) =>
+ async ({ monitorIds }) => {
+ calls.push({ type, monitorIds });
+ return { data: [] };
+ },
+ );
+
+ expect(calls).toEqual([
+ { type: "http", monitorIds: ["1", "3"] },
+ { type: "tcp", monitorIds: ["2"] },
+ ]);
+ });
+
+ it("skips job types the pipes don't cover", async () => {
+ const types: string[] = [];
+ await fetchByJobType([component(1, "udp")], (type) => async () => {
+ types.push(type);
+ return { data: [] };
+ });
+ expect(types).toEqual([]);
+ });
+
+ it("groups rows from every pipe by monitor id, keeping order", async () => {
+ const rows: Record<string, { monitorId: string; day: string }[]> = {
+ http: [
+ { monitorId: "1", day: "a" },
+ { monitorId: "3", day: "a" },
+ { monitorId: "1", day: "b" },
+ ],
+ dns: [{ monitorId: "2", day: "a" }],
+ };
+ const result = await fetchByJobType(
+ [component(1, "http"), component(2, "dns"), component(3, "http")],
+ (type) => async () => ({ data: rows[type] ?? [] }),
+ );
+
+ expect(result.get("1")?.map((r) => r.day)).toEqual(["a", "b"]);
+ expect(result.get("2")).toEqual([{ monitorId: "2", day: "a" }]);
+ expect(result.get("3")).toHaveLength(1);
+ expect(result.has("4")).toBe(false);
+ });
+
+ it("propagates a pipe failure so withTinybirdFallback can catch it", async () => {
+ await expect(
+ fetchByJobType([component(1, "http")], () => async () => {
+ throw new Error("tinybird down");
+ }),
+ ).rejects.toThrow("tinybird down");
+ });
+});
diff --git a/packages/api/src/router/statusPage.utils.ts b/packages/api/src/router/statusPage.utils.ts
index dc709bb10..265e234e5 100644
--- a/packages/api/src/router/statusPage.utils.ts
+++ b/packages/api/src/router/statusPage.utils.ts
@@ -717,3 +717,34 @@ export function getUptime({
if (total === 0) return "100%";
return `${floorPct(up / total)}%`;
}
+
+const JOB_TYPES = ["http", "tcp", "dns", "icmp", "grpc"] as const;
+
+// Tinybird pipes are split per job type: query every type that has monitors
+// in parallel, then key the rows by monitor id.
+export async function fetchByJobType<Row extends { monitorId: string }>(
+ components: { monitor: { id: number; jobType: string } }[],
+ procedureFor: (
+ type: (typeof JOB_TYPES)[number],
+ ) => (args: { monitorIds: string[] }) => Promise<{ data: Row[] }>,
+): Promise<Map<string, Row[]>> {
+ const results = await Promise.all(
+ JOB_TYPES.map((type) => {
+ const monitorIds = components
+ .filter((c) => c.monitor.jobType === type)
+ .map((c) => c.monitor.id.toString());
+ if (monitorIds.length === 0) return null;
+ return procedureFor(type)({ monitorIds });
+ }),
+ );
+
+ const byMonitorId = new Map<string, Row[]>();
+ for (const result of results) {
+ for (const row of result?.data ?? []) {
+ const rows = byMonitorId.get(row.monitorId);
+ if (rows) rows.push(row);
+ else byMonitorId.set(row.monitorId, [row]);
+ }
+ }
+ return byMonitorId;
+}
diff --git a/packages/api/src/router/tinybird/index.ts b/packages/api/src/router/tinybird/index.ts
index 7d5ccc1fb..df88b0f86 100644
--- a/packages/api/src/router/tinybird/index.ts
+++ b/packages/api/src/router/tinybird/index.ts
@@ -18,6 +18,17 @@ const types = ["http", "tcp", "dns", "icmp", "grpc"] as const;
type Period = (typeof periods)[number];
type Type = (typeof types)[number];
+// Read-only ownership check before querying Tinybird by monitor id.
+async function getMonitorOrThrow(workspaceId: number, monitorId: number) {
+ const row = await db.query.monitor.findFirst({
+ where: and(eq(monitor.id, monitorId), eq(monitor.workspaceId, workspaceId)),
+ });
+ if (!row) {
+ throw new TRPCError({ code: "NOT_FOUND", message: "Monitor not found" });
+ }
+ return row;
+}
+
// Free workspaces only get up to 7d; longer windows are blocked server-side.
function assertPaidPeriod(plan: string, period: Period) {
if (plan === "free" && period !== "1d" && period !== "7d") {
@@ -380,21 +391,10 @@ export const tinybirdRouter = createTRPCRouter({
}),
)
.query(async (opts) => {
- const whereConditions: SQL[] = [
- eq(monitor.id, Number.parseInt(opts.input.monitorId)),
- eq(monitor.workspaceId, opts.ctx.workspace.id),
- ];
-
- const _monitor = await db.query.monitor.findFirst({
- where: and(...whereConditions),
- });
-
- if (!_monitor) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "Monitor not found",
- });
- }
+ await getMonitorOrThrow(
+ opts.ctx.workspace.id,
+ Number.parseInt(opts.input.monitorId),
+ );
// only 90d is gated here; 30d is the default uptime MV used by all windows
if (opts.ctx.workspace.plan === "free" && opts.input.period === "90d") {
@@ -416,21 +416,10 @@ export const tinybirdRouter = createTRPCRouter({
}),
)
.query(async (opts) => {
- const whereConditions: SQL[] = [
- eq(monitor.id, Number.parseInt(opts.input.monitorId)),
- eq(monitor.workspaceId, opts.ctx.workspace.id),
- ];
-
- const _monitor = await db.query.monitor.findFirst({
- where: and(...whereConditions),
- });
-
- if (!_monitor) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "Monitor not found",
- });
- }
+ await getMonitorOrThrow(
+ opts.ctx.workspace.id,
+ Number.parseInt(opts.input.monitorId),
+ );
return await tb.getAuditLog({
monitorId: `monitor:${opts.input.monitorId}`,
@@ -449,26 +438,15 @@ export const tinybirdRouter = createTRPCRouter({
}),
)
.query(async (opts) => {
- const whereConditions: SQL[] = [
- eq(monitor.id, Number.parseInt(opts.input.monitorId)),
- eq(monitor.workspaceId, opts.ctx.workspace.id),
- ];
-
- const _monitor = await db.query.monitor.findFirst({
- where: and(...whereConditions),
- });
+ await getMonitorOrThrow(
+ opts.ctx.workspace.id,
+ Number.parseInt(opts.input.monitorId),
+ );
if (opts.ctx.workspace.plan === "free") {
opts.input.regions = undefined;
}
- if (!_monitor) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "Monitor not found",
- });
- }
-
assertPaidPeriod(opts.ctx.workspace.plan, opts.input.period);
const procedure = getMetricsProcedure(opts.input.period, opts.input.type);
@@ -490,21 +468,10 @@ export const tinybirdRouter = createTRPCRouter({
}),
)
.query(async (opts) => {
- const whereConditions: SQL[] = [
- eq(monitor.id, Number.parseInt(opts.input.monitorId)),
- eq(monitor.workspaceId, opts.ctx.workspace.id),
- ];
-
- const _monitor = await db.query.monitor.findFirst({
- where: and(...whereConditions),
- });
-
- if (!_monitor) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "Monitor not found",
- });
- }
+ await getMonitorOrThrow(
+ opts.ctx.workspace.id,
+ Number.parseInt(opts.input.monitorId),
+ );
if (opts.ctx.workspace.plan === "free") {
opts.input.regions = undefined;
@@ -533,21 +500,10 @@ export const tinybirdRouter = createTRPCRouter({
}),
)
.query(async (opts) => {
- const whereConditions: SQL[] = [
- eq(monitor.id, Number.parseInt(opts.input.monitorId)),
- eq(monitor.workspaceId, opts.ctx.workspace.id),
- ];
-
- const _monitor = await db.query.monitor.findFirst({
- where: and(...whereConditions),
- });
-
- if (!_monitor) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "Monitor not found",
- });
- }
+ const _monitor = await getMonitorOrThrow(
+ opts.ctx.workspace.id,
+ Number.parseInt(opts.input.monitorId),
+ );
const procedure = getGetProcedure(
opts.input.period,
@@ -597,21 +553,10 @@ export const tinybirdRouter = createTRPCRouter({
}),
)
.query(async (opts) => {
- const whereConditions: SQL[] = [
- eq(monitor.id, Number.parseInt(opts.input.monitorId)),
- eq(monitor.workspaceId, opts.ctx.workspace.id),
- ];
-
- const _monitor = await db.query.monitor.findFirst({
- where: and(...whereConditions),
- });
-
- if (!_monitor) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "Monitor not found",
- });
- }
+ await getMonitorOrThrow(
+ opts.ctx.workspace.id,
+ Number.parseInt(opts.input.monitorId),
+ );
if (opts.ctx.workspace.plan === "free") {
opts.input.regions = undefined;
@@ -648,21 +593,10 @@ export const tinybirdRouter = createTRPCRouter({
}),
)
.query(async (opts) => {
- const whereConditions: SQL[] = [
- eq(monitor.id, Number.parseInt(opts.input.monitorId)),
- eq(monitor.workspaceId, opts.ctx.workspace.id),
- ];
-
- const _monitor = await db.query.monitor.findFirst({
- where: and(...whereConditions),
- });
-
- if (!_monitor) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "Monitor not found",
- });
- }
+ await getMonitorOrThrow(
+ opts.ctx.workspace.id,
+ Number.parseInt(opts.input.monitorId),
+ );
if (opts.ctx.workspace.plan === "free") {
opts.input.regions = undefined;
diff --git a/packages/utils/src/checker-payload.test.ts b/packages/utils/src/checker-payload.test.ts
new file mode 100644
index 000000000..300ef4f0b
--- /dev/null
+++ b/packages/utils/src/checker-payload.test.ts
@@ -0,0 +1,148 @@
+import { describe, expect, test } from "vitest";
+
+import { type CheckerMonitor, buildCheckerPayload } from "./checker-payload";
+
+const monitor = (overrides: Partial<CheckerMonitor> = {}): CheckerMonitor => ({
+ id: 42,
+ workspaceId: 7,
+ jobType: "http",
+ url: "https://example.com",
+ method: "GET",
+ body: "",
+ headers: [{ key: "x-api-key", value: "secret" }],
+ assertions: null,
+ degradedAfter: null,
+ timeout: 45_000,
+ retry: 3,
+ followRedirects: true,
+ otelEndpoint: null,
+ otelHeaders: [],
+ grpcService: null,
+ grpcTls: null,
+ ...overrides,
+});
+
+const build = (m: CheckerMonitor, trigger: "cron" | "api" = "cron") =>
+ buildCheckerPayload({
+ monitor: m,
+ status: "active",
+ trigger,
+ timestamp: 1_700_000_000_000,
+ });
+
+describe("buildCheckerPayload", () => {
+ test("http keeps the request shape the checker binds", () => {
+ expect(
+ build(
+ monitor({
+ assertions:
+ '[{"version":"v1","type":"status","compare":"eq","target":200}]',
+ }),
+ "api",
+ ),
+ ).toMatchObject({
+ workspaceId: "7",
+ monitorId: "42",
+ url: "https://example.com",
+ method: "GET",
+ cronTimestamp: 1_700_000_000_000,
+ headers: [{ key: "x-api-key", value: "secret" }],
+ assertions: [
+ { version: "v1", type: "status", compare: "eq", target: 200 },
+ ],
+ trigger: "api",
+ retry: 3,
+ followRedirects: true,
+ });
+ });
+
+ test("http honours a disabled followRedirects", () => {
+ expect(build(monitor({ followRedirects: false }))).toMatchObject({
+ followRedirects: false,
+ });
+ });
+
+ test("defaults a missing retry to the checker default", () => {
+ expect(build(monitor({ retry: null }))).toMatchObject({ retry: 3 });
+ });
+
+ test.each(["tcp", "dns"] as const)(
+ "%s sends uri and assertions",
+ (jobType) => {
+ const payload = build(
+ monitor({
+ jobType,
+ url: "example.com:443",
+ assertions:
+ '[{"version":"v1","type":"status","compare":"eq","target":200}]',
+ }),
+ );
+ expect(payload).toMatchObject({ uri: "example.com:443" });
+ expect("assertions" in payload).toBe(true);
+ expect("url" in payload).toBe(false);
+ expect("followRedirects" in payload).toBe(false);
+ },
+ );
+
+ test("icmp drops assertions a previous job type left on the row", () => {
+ const payload = build(
+ monitor({
+ jobType: "icmp",
+ url: "1.1.1.1",
+ assertions:
+ '[{"version":"v1","type":"status","compare":"eq","target":200}]',
+ }),
+ );
+ expect(payload).toMatchObject({ uri: "1.1.1.1" });
+ expect("assertions" in payload).toBe(false);
+ });
+
+ test("grpc sends headers as a map and defaults tls", () => {
+ expect(
+ build(
+ monitor({
+ jobType: "grpc",
+ url: "grpc.example.com:443",
+ grpcService: "health",
+ }),
+ ),
+ ).toMatchObject({
+ uri: "grpc.example.com:443",
+ service: "health",
+ tls: "tls",
+ headers: { "x-api-key": "secret" },
+ });
+ });
+
+ test("forwards the OTel config when configured", () => {
+ const payload = build(
+ monitor({
+ otelEndpoint: "https://otel.example.com:4318",
+ otelHeaders: [{ key: "Authorization", value: "Basic dGVzdA==" }],
+ }),
+ );
+ expect(payload.otelConfig).toEqual({
+ endpoint: "https://otel.example.com:4318",
+ headers: { Authorization: "Basic dGVzdA==" },
+ });
+ });
+
+ test.each(["icmp", "grpc"] as const)(
+ "%s ignores a malformed assertions string",
+ (jobType) => {
+ expect(() =>
+ build(monitor({ jobType, assertions: "{not json" })),
+ ).not.toThrow();
+ },
+ );
+
+ test("http still rejects a malformed assertions string", () => {
+ expect(() => build(monitor({ assertions: "{not json" }))).toThrow(
+ SyntaxError,
+ );
+ });
+
+ test("rejects an unsupported job type", () => {
+ expect(() => build(monitor({ jobType: "udp" }))).toThrow("Invalid jobType");
+ });
+});
diff --git a/packages/utils/src/checker-payload.ts b/packages/utils/src/checker-payload.ts
new file mode 100644
index 000000000..709d4edf3
--- /dev/null
+++ b/packages/utils/src/checker-payload.ts
@@ -0,0 +1,115 @@
+import type {
+ MONITOR_JOB_TYPES,
+ MONITOR_METHODS,
+ MONITOR_STATUSES,
+} from "./constants";
+import { transformHeaders } from "./headers";
+import type {
+ DNSPayload,
+ GRPC_TLS_MODES,
+ GrpcPayload,
+ HttpPayload,
+ IcmpPayload,
+ TcpPayload,
+} from "./payloads";
+
+type KeyValue = { key: string; value: string };
+
+/** Job types the Go checker can run; anything else is rejected by `buildCheckerPayload`. */
+const CHECKER_JOB_TYPES = ["http", "tcp", "dns", "icmp", "grpc"] as const;
+
+export function isCheckerJobType(
+ jobType: string,
+): jobType is (typeof CHECKER_JOB_TYPES)[number] {
+ return (CHECKER_JOB_TYPES as readonly string[]).includes(jobType);
+}
+
+/** The monitor fields the checker needs; a parsed `selectMonitorSchema` row satisfies it. */
+export type CheckerMonitor = {
+ id: number;
+ workspaceId: number | null;
+ jobType: (typeof MONITOR_JOB_TYPES)[number];
+ url: string;
+ method: (typeof MONITOR_METHODS)[number] | null;
+ body: string | null;
+ headers: KeyValue[];
+ assertions: string | null;
+ degradedAfter: number | null;
+ timeout: number;
+ retry: number | null;
+ followRedirects: boolean | null;
+ otelEndpoint: string | null;
+ otelHeaders: KeyValue[];
+ grpcService?: string | null;
+ grpcTls?: (typeof GRPC_TLS_MODES)[number] | null;
+};
+
+export type CheckerPayload =
+ | HttpPayload
+ | TcpPayload
+ | DNSPayload
+ | IcmpPayload
+ | GrpcPayload;
+
+/** Builds the body the Go checker expects for one run of `monitor`. `timestamp` is in ms. */
+export function buildCheckerPayload({
+ monitor,
+ status,
+ trigger,
+ timestamp,
+}: {
+ monitor: CheckerMonitor;
+ status: (typeof MONITOR_STATUSES)[number];
+ trigger: "cron" | "api";
+ timestamp: number;
+}): CheckerPayload {
+ const common = {
+ workspaceId: String(monitor.workspaceId),
+ monitorId: String(monitor.id),
+ status,
+ cronTimestamp: timestamp,
+ degradedAfter: monitor.degradedAfter,
+ timeout: monitor.timeout,
+ trigger,
+ otelConfig: monitor.otelEndpoint
+ ? {
+ endpoint: monitor.otelEndpoint,
+ headers: transformHeaders(monitor.otelHeaders),
+ }
+ : undefined,
+ // The checker treats 0 as its own default of 3, so `??` and `||` agree on the wire.
+ retry: monitor.retry ?? 3,
+ };
+ // Lazy: ICMP and gRPC ignore assertions, so a stale string must not fail their run.
+ const assertions = () =>
+ monitor.assertions ? JSON.parse(monitor.assertions) : null;
+
+ switch (monitor.jobType) {
+ case "http":
+ return {
+ ...common,
+ url: monitor.url,
+ method: monitor.method || "GET",
+ body: monitor.body ?? undefined,
+ headers: monitor.headers,
+ assertions: assertions(),
+ followRedirects: monitor.followRedirects ?? true,
+ };
+ case "tcp":
+ case "dns":
+ return { ...common, uri: monitor.url, assertions: assertions() };
+ // ICMP and gRPC only report reachability / serving status: no assertions.
+ case "icmp":
+ return { ...common, uri: monitor.url };
+ case "grpc":
+ return {
+ ...common,
+ uri: monitor.url,
+ service: monitor.grpcService ?? undefined,
+ tls: monitor.grpcTls ?? "tls",
+ headers: transformHeaders(monitor.headers),
+ };
+ default:
+ throw new Error(`Invalid jobType '${monitor.jobType}'`);
+ }
+}
diff --git a/packages/utils/src/headers.ts b/packages/utils/src/headers.ts
index 05931de1b..a34f01f02 100644
--- a/packages/utils/src/headers.ts
+++ b/packages/utils/src/headers.ts
@@ -18,3 +18,9 @@ export const headerPairSchema = z.object({
});
export type HeaderPair = z.infer<typeof headerPairSchema>;
+
+export function transformHeaders(
+ headers: { key: string; value: string }[],
+): Record<string, string> {
+ return Object.fromEntries(headers.map(({ key, value }) => [key, value]));
+}
diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.ts
index dd4161fb6..4cec9f557 100644
--- a/packages/utils/src/index.ts
+++ b/packages/utils/src/index.ts
@@ -23,13 +23,13 @@ export {
MONITOR_STATUSES,
} from "./constants";
export { buildCurlCommand, type CurlRequest } from "./curl";
-export { type HeaderPair, headerPairSchema } from "./headers";
+export { type HeaderPair, headerPairSchema, transformHeaders } from "./headers";
+export {
+ buildCheckerPayload,
+ isCheckerJobType,
+ type CheckerMonitor,
+ type CheckerPayload,
+} from "./checker-payload";
export { personName } from "./person-name";
export { iteratorToStream, yieldMany } from "./stream";
export { type PageUpdateStatus, statusLabel } from "./status";
-
-export function transformHeaders(
- headers: { key: string; value: string }[],
-): Record<string, string> {
- return Object.fromEntries(headers.map(({ key, value }) => [key, value]));
-}