Open-source status page, incident response and uptime monitoring
TypeScript alertingincident-managementmcpmcp-servermonitoringmonitoring-as-codeobservabilityon-callopen-sourcesrestatus-pagestatuspagesynthetic-monitoringterraformtinybirdtursouptimeuptime-checkeruptime-monitor
refactor(status-fetcher): replace fetch-utils with Effect-based fetchers (#2185)
Thibault Le Ouaycf57cde57622
diff --git a/apps/web/package.json b/apps/web/package.jsonindex c84b6765c..cd6cc6e92 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -36,7 +36,6 @@"@openstatus/react": "workspace:*","@openstatus/regions": "workspace:*","@openstatus/services": "workspace:*",- "@openstatus/status-fetcher": "workspace:*","@openstatus/theme-store": "workspace:*","@openstatus/tinybird": "workspace:*","@openstatus/tracker": "workspace:*",diff --git a/apps/workflows/src/cron/external-status.ts b/apps/workflows/src/cron/external-status.tsindex 92a73314f..158242fc5 100644--- a/apps/workflows/src/cron/external-status.ts+++ b/apps/workflows/src/cron/external-status.ts@@ -1,10 +1,10 @@import { getLogger } from "@logtape/logtape";import { listExternalServices } from "@openstatus/services/external-service";import type { ExternalServiceRow } from "@openstatus/services/external-service";-import { fetchers } from "@openstatus/status-fetcher";+import { FetchError, fetchers } from "@openstatus/status-fetcher";import type { StatusPageEntry, StatusResult } from "@openstatus/status-fetcher";import { OSTinybird } from "@openstatus/tinybird";-import { Effect, Schedule } from "effect";+import { Effect, Either } from "effect";import type { Context } from "hono";import { env } from "../env";@@ -65,22 +65,36 @@ export async function runExternalStatusTick(): Promise<{const entries = services.map(toStatusPageEntry);const fetchedAt = Date.now();- const settled = await Promise.allSettled(- entries.map(async (entry) => {- const fetcher = fetchers.find((f) => f.canHandle(entry));- if (!fetcher) {- throw new Error(`no fetcher matches entry slug=${entry.id}`);- }- const result = await fetcher.fetch(entry);- return buildSnapshot({ entry, result, fetchedAt });- }),+ const results = await Effect.runPromise(+ Effect.forEach(+ entries,+ (entry) => {+ const fetcher = fetchers.find((f) => f.canHandle(entry));+ if (!fetcher) {+ return Effect.either(+ Effect.fail(+ new FetchError({+ url: entry.status_page_url,+ entryId: entry.id,+ cause: new Error(`no fetcher matches entry slug=${entry.id}`),+ }),+ ),+ );+ }+ return fetcher.fetch(entry).pipe(+ Effect.map((result) => buildSnapshot({ entry, result, fetchedAt })),+ Effect.either,+ );+ },+ { concurrency: 25 },+ ),);const snapshots: Snapshot[] = [];let failureCount = 0;- for (const [i, r] of settled.entries()) {- if (r.status === "fulfilled") {- snapshots.push(r.value);+ for (const [i, r] of results.entries()) {+ if (Either.isRight(r)) {+ snapshots.push(r.right);} else {failureCount++;const slug = entries[i]?.id ?? "<unknown>";@@ -88,8 +102,7 @@ export async function runExternalStatusTick(): Promise<{"external-status tick: fetcher failed for slug={slug}: {reason}",{slug,- reason:- r.reason instanceof Error ? r.reason.message : String(r.reason),+ reason: r.left.message,},);}@@ -121,10 +134,6 @@ export async function handleExternalStatusCron(c: Context) {`external-status tick failed: ${e instanceof Error ? e.message : String(e)}`,),}).pipe(- Effect.retry({- times: 3,- schedule: Schedule.exponential("1000 millis"),- }),Effect.tap((res) =>Effect.sync(() => {logger.info(diff --git a/packages/status-fetcher/README.md b/packages/status-fetcher/README.mdindex cb7c6119d..9823aea13 100644--- a/packages/status-fetcher/README.md+++ b/packages/status-fetcher/README.md@@ -1,479 +1,215 @@# @openstatus/status-fetcher-A production-ready, type-safe library for fetching real-time status from major tech companies and service providers, with support for 6 status page platforms.--## Features--- π **Curated Registry** - TypeScript-based list of verified status pages with runtime validation-- π **6 Provider Fetchers** - Support for Atlassian, Instatus, BetterStack, Incident.io, Custom APIs, and HTML scraping-- β **Type-safe** - Full TypeScript support with Zod runtime validation-- π **Automatic Retries** - Exponential backoff retry logic for transient failures-- β±οΈ **Smart Timeouts** - Configurable 30s timeout prevents hanging requests-- π― **Minimal Dependencies** - Only requires `zod` and `node-html-parser`-- π‘οΈ **Production Ready** - Comprehensive error handling and context-rich error messages--## Quick Start--```typescript-import { getStatusDirectory } from "@openstatus/status-fetcher";-import { fetchers } from "@openstatus/status-fetcher/fetchers";--const directory = getStatusDirectory();-const github = directory.find((e) => e.id === "github");--if (github) {- const fetcher = fetchers.find((f) => f.canHandle(github));- if (fetcher) {- const status = await fetcher.fetch(github);- console.log(`${github.name}: ${status.status} - ${status.description}`);- // Output: GitHub: operational - All Systems Operational- }-}-```--## Usage--### Get Directory Entries--```typescript-import { getStatusDirectory } from "@openstatus/status-fetcher";--const directory = getStatusDirectory();-console.log(`Found ${directory.length} status pages`);--// Filter by industry-const saasCompanies = directory.filter((e) =>- e.industry.includes("saas"),-);+Effect-based fetchers for third-party status pages. Each fetcher returns an+`Effect.Effect<StatusResult, FetchError>` so failures propagate through the+typed error channel and successful results carry a normalized shape across+providers.++## Quick start++```ts+import { Effect } from "effect";+import { FetchError, fetchers } from "@openstatus/status-fetcher";+import type { StatusPageEntry } from "@openstatus/status-fetcher";++const entry: StatusPageEntry = {+ id: "github",+ name: "GitHub",+ url: "https://github.com",+ status_page_url: "https://www.githubstatus.com",+ provider: "atlassian-statuspage",+ industry: ["development-tools"],+ api_config: { type: "atlassian" },+};-// Filter by provider-const atlassianPages = directory.filter((e) =>- e.provider === "atlassian-statuspage",+const fetcher = fetchers.find((f) => f.canHandle(entry));+if (!fetcher) throw new Error("no fetcher matches entry");++const result = await Effect.runPromise(fetcher.fetch(entry));+console.log(result.severity, result.status, result.description);+```++For batch fan-out with per-item success/failure, use `Effect.forEach` ++`Effect.either`:++```ts+import { Effect, Either } from "effect";++const results = await Effect.runPromise(+ Effect.forEach(+ entries,+ (entry) => {+ const fetcher = fetchers.find((f) => f.canHandle(entry));+ if (!fetcher) {+ return Effect.either(+ Effect.fail(+ new FetchError({ url: entry.status_page_url, entryId: entry.id }),+ ),+ );+ }+ return fetcher.fetch(entry).pipe(Effect.either);+ },+ { concurrency: "unbounded" },+ ),);-```--### Fetch Status with Error Handling--```typescript-import { getStatusDirectory } from "@openstatus/status-fetcher";-import { fetchers, FetchError } from "@openstatus/status-fetcher/fetchers";--const directory = getStatusDirectory();-for (const entry of directory) {- const fetcher = fetchers.find((f) => f.canHandle(entry));- if (!fetcher) {- console.log(`No fetcher for ${entry.name}`);- continue;- }-- try {- const status = await fetcher.fetch(entry);- console.log(- `β ${entry.name}: ${status.status} (${status.severity}) - ${status.description}`,- );- } catch (error) {- if (error instanceof FetchError) {- console.error(- `β ${error.entryId}: ${error.message}`,- );- } else {- console.error(`Failed to fetch ${entry.name}:`, error);- }+for (const r of results) {+ if (Either.isRight(r)) {+ /* r.right is the StatusResult */+ } else {+ /* r.left is a FetchError */}}```-### Using Fetch Utilities Directly--```typescript-import {- fetchWithRetry,- fetchWithTimeout,- fetchWithDeduplication,-} from "@openstatus/status-fetcher";--// Fetch with automatic retry (3 attempts, exponential backoff)-const response = await fetchWithRetry("https://api.example.com/status", {- timeout: 30000,- maxRetries: 3,- headers: { "User-Agent": "MyApp/1.0" },-});--// Fetch with timeout only-const response2 = await fetchWithTimeout("https://api.example.com/health", {- timeout: 10000,-});--// Fetch with request deduplication (concurrent requests to same URL are deduplicated)-const [r1, r2, r3] = await Promise.all([- fetchWithDeduplication("https://api.example.com/status"),- fetchWithDeduplication("https://api.example.com/status"), // Reuses first request- fetchWithDeduplication("https://api.example.com/status"), // Reuses first request-]);-```--## Supported Providers--| Provider | Coverage | Features | Authentication |-|----------|----------|----------|----------------|-| Atlassian Statuspage | ~60% of status pages | Full API support, rich metadata | None required |-| Instatus | Growing adoption | Real-time updates, maintenance windows | None required |-| BetterStack (Better Uptime) | Popular in startups | Aggregate state, timezone support | None required |-| Incident.io | Enterprise | Incident workflow states | None required |-| Custom APIs | Slack, etc. | Configurable parsers | None required |-| HTML Scraper | Universal fallback | Pattern-based extraction | None required |--## Architecture+## Types-### Type System+### `StatusPageEntry`-All types are derived from single-source-of-truth arrays:--```typescript-// Source of truth-export const STATUS_PAGE_PROVIDERS = [- "atlassian-statuspage",- "instatus",- // ...-] as const;--// TypeScript type (automatically inferred)-export type StatusPageProvider = (typeof STATUS_PAGE_PROVIDERS)[number];--// Zod schema (automatically derived)-export const statusPageProviderSchema = z.enum(STATUS_PAGE_PROVIDERS);-```--This eliminates duplication and ensures TypeScript types and runtime validation are always in sync.--### Severity vs Status--The package provides two complementary fields:--- **Severity**: Impact level (`none`, `minor`, `major`, `critical`)-- **Status**: Actual state (`operational`, `degraded`, `investigating`, `major_outage`, etc.)--This allows for nuanced status reporting:--```typescript-{- severity: "none",- status: "under_maintenance" // Scheduled, not impactful-}--{- severity: "major",- status: "investigating" // Active incident being investigated-}-```--### Retry & Timeout Logic--All fetchers use intelligent retry logic:--- **Automatic retries**: 3 attempts with exponential backoff (100ms β 200ms β 400ms)-- **Smart retry**: Only retries network errors and 5xx responses, not 4xx client errors-- **Timeout**: 30s default timeout prevents hanging requests-- **Context-rich errors**: Errors include fetcher name, entry ID, and URL for debugging--```typescript-// Retry logic (simplified)-for (let attempt = 0; attempt <= maxRetries; attempt++) {- try {- const response = await fetchWithTimeout(url, { timeout: 30000 });- if (response.ok || response.status < 500) return response;- } catch (error) {- if (attempt < maxRetries && shouldRetry(error)) {- await sleep(delay);- delay *= 2; // Exponential backoff- }- }-}-```--## Data Structures--### StatusPageEntry--```typescript+```tsinterface StatusPageEntry {- id: string; // Unique slug (e.g., "github")- name: string; // Display name- url: string; // Main company website- status_page_url: string; // Status page URL- provider: StatusPageProvider; // Platform used- industry: Industry[]; // Categorization (e.g., ["saas", "development-tools"])- description?: string; // Short description- api_config?: ApiConfig; // Fetcher configuration+ id: string;+ name: string;+ url: string;+ status_page_url: string;+ provider: StatusPageProvider;+ industry: Industry[];+ description?: string;+ api_config?: ApiConfig;}```-### StatusResult+### `StatusResult`-```typescript+```tsinterface StatusResult {- severity: SeverityLevel; // Impact: "none" | "minor" | "major" | "critical"- status: StatusType; // State: "operational" | "degraded" | "partial_outage" |- // "major_outage" | "under_maintenance" | "investigating" |- // "identified" | "monitoring" | "resolved"- description: string; // Human-readable status message- updated_at: number; // Timestamp (ms since epoch)- timezone?: string; // Timezone (e.g., "UTC", "America/New_York")-}-```--### ApiConfig--```typescript-interface ApiConfig {- type: "atlassian" | "instatus" | "betterstack" | "incidentio" | "custom" | "html-scraper";- endpoint?: string; // Custom API endpoint (overrides default)- parser?: string; // Custom parser name (for custom type)+ severity: SeverityLevel; // "none" | "minor" | "major" | "critical"+ status: StatusType; // "operational" | "degraded" | "partial_outage" |+ // "major_outage" | "under_maintenance" |+ // "investigating" | "identified" |+ // "monitoring" | "resolved"+ description: string;+ updated_at: number; // ms since epoch+ timezone?: string;}```-## Testing+### `FetchError`-Run the test suite:+Thrown via `Effect.fail` on any fetch failure. Always carries `url`; carries+`fetcherName` / `entryId` / `httpStatus` / `cause` when available.-```bash-bun test-# or-npm test-```--Test all fetchers manually:--```bash-tsx scripts/test-fetchers.ts-```--Example output:-```-π Testing 7 entries...--β GitHub: operational (none) - All Systems Operational (245ms)-β Vercel: operational (none) - All Systems Operational (198ms)-β Slack: operational (none) - All Systems Operational (312ms)-β Linear: operational (none) - All Systems Operational (156ms)-β OpenAI: operational (none) - All Systems Operational (223ms)-β Stripe: operational (none) - All Systems Operational (189ms)-β Cloudflare: operational (none) - All Systems Operational (267ms)--β¨ Testing complete! 7/7 passed-```--## Adding New Entries--### 1. Add to Directory--Edit `src/data/directory.ts`:--```typescript-{- id: "stripe",- name: "Stripe",- url: "https://stripe.com",- status_page_url: "https://status.stripe.com",- provider: "atlassian-statuspage",- industry: ["fintech"],- description: "Online payment processing platform",- api_config: {- type: "atlassian",- },+```ts+class FetchError extends Error {+ readonly url: string;+ readonly fetcherName?: string;+ readonly entryId?: string;+ readonly httpStatus?: number;+ // `.cause: unknown` (inherited from Error)}```-The directory is validated at startup using Zod, so invalid entries will fail immediately.--### 2. Test the Entry--```bash-bun test-```--### 3. Verify Manually--```typescript-import { getStatusDirectory } from "@openstatus/status-fetcher";-import { fetchers } from "@openstatus/status-fetcher/fetchers";--const stripe = getStatusDirectory().find((e) => e.id === "stripe");-const fetcher = fetchers.find((f) => f.canHandle(stripe!));-const status = await fetcher!.fetch(stripe!);-console.log(status);-```--## Implementing a Custom Parser--For companies with proprietary APIs (like Slack), add a parser to `CustomApiFetcher`:+The computed `.message` is `[<fetcherName> (<entryId>)] HTTP <status>: <url>`+or `[<fetcherName> (<entryId>)] fetch failed: <url>` when no HTTP status is+available.-```typescript-// In src/fetchers/custom.ts-private parseMyCompany(json: unknown): StatusResult {- const schema = z.object({- status: z.string(),- lastUpdate: z.number(),- });+## Retry & timeout- const data = schema.parse(json);+Each `fetchJson` / `fetchText` call:- return {- severity: data.status === "ok" ? "none" : "major",- status: data.status === "ok" ? "operational" : "major_outage",- description: data.status === "ok" ? "All Systems Operational" : "Service Disruption",- updated_at: data.lastUpdate,- timezone: "UTC",- };-}+- 30s timeout per attempt (via `Effect.timeoutFail`)+- Up to 3 retries on transient errors with exponential backoff+ (`Schedule.exponential("100 millis").pipe(Schedule.jittered)`)+- **4xx responses skip retry** (predicate fails fast)+- 5xx, network errors, and timeouts retry-private parseResponse(json: unknown, parser: string): StatusResult {- switch (parser) {- case "slack":- return this.parseSlack(json);- case "aws":- return this.parseAws(json);- case "mycompany": // Add your parser- return this.parseMyCompany(json);- default:- return this.parseGeneric(json);- }-}-```+## Supported providers-Then use it in your directory entry:--```typescript-{- id: "mycompany",- name: "My Company",- url: "https://mycompany.com",- status_page_url: "https://status.mycompany.com",- provider: "custom",- industry: ["saas"],- api_config: {- type: "custom",- endpoint: "https://status.mycompany.com/api/current",- parser: "mycompany",- },-}-```+| Provider | `api_config.type` | Notes |+| -------------------- | ----------------- | --------------------------------------------------------- |+| Atlassian Statuspage | `atlassian` | `<status_page_url>/api/v2/summary.json` |+| Instatus | `instatus` | `<status_page_url>/summary.json` |+| BetterStack | `betterstack` | `<status_page_url>/index.json` |+| Incident.io | `incidentio` | `<origin>/api/widget` (Widget API must be enabled) |+| UptimeRobot | `uptimerobot` | endpoint required β `<page>/api/getMonitorList/<u>-<p>` |+| Custom JSON | `custom` | `parser: "slack" \| "aws" \| "generic"` |+| HTML scraper | `html-scraper` | universal fallback, opt-in only |-## Error Handling+Fetcher selection is `fetchers.find((f) => f.canHandle(entry))`. Each+fetcher's `canHandle` ORs three signals: `api_config.type`, `provider`, and+hostname (`urlHostnameEndsWith`, which checks the URL hostname strictly to+avoid substring spoofing). The registry order in `src/fetchers/index.ts` is+deliberate: `Atlassian β Instatus β BetterStack β Incident.io β UptimeRobot β+Custom β HtmlScraper`. `Custom` and `HtmlScraper` only match when explicitly+configured.-The package provides rich error context through the `FetchError` class:+## Adding a new fetcher-```typescript-import { FetchError } from "@openstatus/status-fetcher";+1. Subclass `StatusFetcher`:-try {- const status = await fetcher.fetch(entry);-} catch (error) {- if (error instanceof FetchError) {- console.error({- message: error.message, // "HTTP 500: Internal Server Error"- url: error.url, // "https://api.example.com/status"- fetcherName: error.fetcherName, // "atlassian"- entryId: error.entryId, // "github"- cause: error.cause, // Original error- });- }-}-```--## API Reference+ ```ts+ import { Effect } from "effect";+ import { z } from "zod";+ import { FetchError, fetchJson } from "../fetch";+ import type { StatusFetcher, StatusPageEntry, StatusResult } from "../types";-### Exported Types+ const responseSchema = z.object({ /* ... */ });-```typescript-// Core types-export type { StatusPageEntry, StatusResult, ApiConfig, StatusFetcher };--// Type unions-export type { StatusPageProvider, Industry, SeverityLevel, StatusType };--// Arrays (source of truth)-export {- STATUS_PAGE_PROVIDERS,- INDUSTRIES,- SEVERITY_LEVELS,- STATUS_TYPES,- API_CONFIG_TYPES,-};+ export class MyFetcher implements StatusFetcher {+ name = "myprovider";-// Zod schemas-export {- statusPageEntrySchema,- statusPageProviderSchema,- industrySchema,- apiConfigSchema,-};+ canHandle(entry: StatusPageEntry): boolean {+ return entry.api_config?.type === "myprovider";+ }-// Utilities-export { fetchWithTimeout, fetchWithRetry, FetchError };-export { inferStatus };-```+ fetch(entry: StatusPageEntry): Effect.Effect<StatusResult, FetchError> {+ return fetchJson({+ url: entry.api_config?.endpoint ?? "/* default */",+ schema: responseSchema,+ fetcherName: this.name,+ entryId: entry.id,+ }).pipe(+ Effect.map((data) => ({ /* StatusResult */ })),+ );+ }+ }+ ```-### Functions+2. Register the class in `src/fetchers/index.ts` (before `Custom` /+ `HtmlScraper`).-```typescript-// Get the full directory-getStatusDirectory(): StatusPageEntry[]+3. Add `myprovider` to `API_CONFIG_TYPES` in `src/types.ts` if it's a new+ `api_config.type`, and to `STATUS_PAGE_PROVIDERS` if it's a new+ `provider`.-// Infer status from description and severity-inferStatus(description: string, severity: SeverityLevel): StatusType+4. Write `__tests__/fetchers/myprovider.test.ts` using the helpers in+ `__tests__/helpers.ts` (`installMockFetch`, `runFetcher`,+ `runFetcherExit`, `expectFetchError`).-// Fetch with timeout-fetchWithTimeout(url: string, options?: FetchWithTimeoutOptions): Promise<Response>+## Testing-// Fetch with retry-fetchWithRetry(url: string, options?: FetchWithTimeoutOptions & RetryOptions): Promise<Response>+```sh+bun test```-## Performance Considerations+Live smoke check against real status pages (GitHub, Linear, Slack,+Bluesky):-- **Validation overhead**: Directory validation happens once at module load (~1ms for 100 entries)-- **Retry timing**: Default retry strategy adds ~700ms max (100ms + 200ms + 400ms) for failures-- **Timeout**: 30s timeout per request prevents indefinite hanging-- **Parallel fetching**: Fetchers are stateless and can be called concurrently--```typescript-// Fetch multiple statuses in parallel-const statuses = await Promise.allSettled(- directory.map(async (entry) => {- const fetcher = fetchers.find((f) => f.canHandle(entry));- return fetcher ? fetcher.fetch(entry) : null;- }),-);+```sh+tsx scripts/test-fetchers.ts```-## Contributing--Contributions are welcome! Please:--1. Add tests for new features-2. Ensure all tests pass (`bun test`)-3. Follow existing code style-4. Update documentation--## Roadmap--- [ ] Database storage for status history-- [ ] Cron job for automated status updates-- [ ] Web UI displaying the directory-- [ ] Public REST API endpoint-- [ ] Community submission form-- [ ] Webhook notifications-- [ ] GraphQL API-- [ ] Status page analytics--## License--MIT+## Internals-## Support+- `src/fetch.ts` β `fetchJson` / `fetchText` / `FetchError`. Defaults:+ `User-Agent: OpenStatus-Directory/1.0` and `Accept: application/json` for+ `fetchJson`; `User-Agent: Mozilla/5.0 (compatible; OpenStatus-Bot/1.0)` for+ `fetchText`. Caller's `init.headers` override via spread merge.+- `src/utils.ts` β `inferStatus(description, severity)` keyword classifier+ and `urlHostnameEndsWith(url, domain)` strict hostname matcher.+- `src/types.ts` β single-source-of-truth `as const` arrays drive both+ TypeScript types and Zod schemas.-- π [Documentation](https://github.com/openstatusHQ/openstatus)-- π [Report Issues](https://github.com/openstatusHQ/openstatus/issues)-- π¬ [Discord Community](https://openstatus.dev/discord)+`fetchJson` / `fetchText` stay package-internal; only `FetchError`, the+fetcher registry, and the type surface are re-exported from the package+entry.diff --git a/packages/status-fetcher/__tests__/fetch-utils.test.ts b/packages/status-fetcher/__tests__/fetch-utils.test.tsdeleted file mode 100644index 5759d3898..000000000--- a/packages/status-fetcher/__tests__/fetch-utils.test.ts+++ /dev/null@@ -1,517 +0,0 @@-import { describe, expect, it, mock } from "bun:test";-import {- FetchError,- fetchWithDeduplication,- fetchWithRetry,- fetchWithTimeout,-} from "../src/fetch-utils";--describe("fetchWithTimeout", () => {- it("should successfully fetch with timeout", async () => {- global.fetch = mock(() =>- Promise.resolve({- ok: true,- status: 200,- json: async () => ({ data: "test" }),- } as Response),- );-- const response = await fetchWithTimeout("https://api.example.com", {- timeout: 5000,- });-- expect(response.ok).toBe(true);- expect(response.status).toBe(200);- });-- it.skip("should timeout after specified duration", async () => {- // Note: This test is skipped because testing AbortController timeout- // behavior with mocked fetch is unreliable in test environments- global.fetch = mock(- () =>- new Promise((resolve) => {- // Never resolve - let timeout trigger- setTimeout(() => resolve({} as Response), 10000);- }),- );-- await expect(- fetchWithTimeout("https://api.example.com", { timeout: 50 }),- ).rejects.toThrow("Request timeout after 50ms");- });-- it("should use default timeout of 30000ms", async () => {- let _timeoutDuration = 0;-- global.fetch = mock(- () =>- new Promise((resolve) => {- setTimeout(() => {- _timeoutDuration = Date.now();- resolve({ ok: true } as Response);- }, 10);- }),- );-- const start = Date.now();- await fetchWithTimeout("https://api.example.com");- const duration = Date.now() - start;-- // Should not timeout on quick response- expect(duration).toBeLessThan(100);- });-- it("should clear timeout on successful response", async () => {- global.fetch = mock(() => Promise.resolve({ ok: true } as Response));-- // Should not throw or cause memory leak- await fetchWithTimeout("https://api.example.com", { timeout: 1000 });-- // Wait a bit to ensure timeout is cleared- await new Promise((resolve) => setTimeout(resolve, 50));- });-- it("should pass through fetch options", async () => {- let capturedOptions: RequestInit | undefined;-- global.fetch = mock((_url: string, options?: RequestInit) => {- capturedOptions = options;- return Promise.resolve({ ok: true } as Response);- });-- await fetchWithTimeout("https://api.example.com", {- timeout: 5000,- headers: { "X-Custom": "header" },- method: "POST",- });-- expect(capturedOptions?.headers).toEqual({ "X-Custom": "header" });- expect(capturedOptions?.method).toBe("POST");- expect(capturedOptions?.signal).toBeDefined();- });-});--describe("fetchWithRetry", () => {- it("should succeed on first attempt", async () => {- global.fetch = mock(() =>- Promise.resolve({- ok: true,- status: 200,- json: async () => ({ data: "test" }),- } as Response),- );-- const response = await fetchWithRetry("https://api.example.com");-- expect(response.ok).toBe(true);- expect(response.status).toBe(200);- });-- it("should retry on 5xx errors", async () => {- let attempts = 0;-- global.fetch = mock(() => {- attempts++;- if (attempts < 3) {- return Promise.resolve({- ok: false,- status: 503,- statusText: "Service Unavailable",- } as Response);- }- return Promise.resolve({- ok: true,- status: 200,- } as Response);- });-- const response = await fetchWithRetry("https://api.example.com", {- maxRetries: 3,- initialDelay: 10,- });-- expect(attempts).toBe(3);- expect(response.ok).toBe(true);- });-- it("should not retry on 4xx errors", async () => {- let attempts = 0;-- global.fetch = mock(() => {- attempts++;- return Promise.resolve({- ok: false,- status: 404,- statusText: "Not Found",- } as Response);- });-- const response = await fetchWithRetry("https://api.example.com", {- maxRetries: 3,- });-- expect(attempts).toBe(1); // Should not retry- expect(response.status).toBe(404);- });-- it("should throw after max retries", async () => {- global.fetch = mock(() =>- Promise.resolve({- ok: false,- status: 500,- statusText: "Internal Server Error",- } as Response),- );-- await expect(- fetchWithRetry("https://api.example.com", {- maxRetries: 2,- initialDelay: 10,- }),- ).rejects.toThrow("HTTP 500: Internal Server Error");- });-- it("should use exponential backoff", async () => {- const attemptTimes: number[] = [];-- global.fetch = mock(() => {- attemptTimes.push(Date.now());- return Promise.resolve({- ok: false,- status: 503,- statusText: "Service Unavailable",- } as Response);- });-- try {- await fetchWithRetry("https://api.example.com", {- maxRetries: 3,- initialDelay: 50,- maxDelay: 1000,- });- } catch {- // Expected to throw- }-- // Should have 4 attempts (1 initial + 3 retries)- expect(attemptTimes.length).toBe(4);-- // Calculate delays between attempts- const delays = [- attemptTimes[1] - attemptTimes[0],- attemptTimes[2] - attemptTimes[1],- attemptTimes[3] - attemptTimes[2],- ];-- // First delay should be ~50ms (with jitter Β±12.5ms)- expect(delays[0]).toBeGreaterThanOrEqual(35);- expect(delays[0]).toBeLessThanOrEqual(75);-- // Second delay should be ~100ms (with jitter Β±25ms)- expect(delays[1]).toBeGreaterThanOrEqual(70);- expect(delays[1]).toBeLessThanOrEqual(150);-- // Third delay should be ~200ms (with jitter Β±50ms)- expect(delays[2]).toBeGreaterThanOrEqual(140);- expect(delays[2]).toBeLessThanOrEqual(300);- });-- it("should respect maxDelay cap", async () => {- const delays: number[] = [];- let lastTime = Date.now();-- global.fetch = mock(() => {- const now = Date.now();- if (delays.length > 0) {- delays.push(now - lastTime);- }- lastTime = now;-- return Promise.resolve({- ok: false,- status: 503,- statusText: "Service Unavailable",- } as Response);- });-- try {- await fetchWithRetry("https://api.example.com", {- maxRetries: 5,- initialDelay: 100,- maxDelay: 150, // Cap at 150ms- });- } catch {- // Expected to throw- }-- // All delays should be capped at ~150ms (with jitter)- delays.forEach((delay) => {- expect(delay).toBeLessThanOrEqual(200); // 150ms + max jitter- });- });-- it("should add jitter to prevent thundering herd", async () => {- const delays: number[] = [];-- global.fetch = mock(() =>- Promise.resolve({- ok: false,- status: 500,- statusText: "Error",- } as Response),- );-- // Run multiple retry sequences- const _results = await Promise.allSettled(- Array.from({ length: 5 }, async (_, i) => {- const startTime = Date.now();- try {- await fetchWithRetry(`https://api.example.com/${i}`, {- maxRetries: 1,- initialDelay: 100,- });- } catch {- delays.push(Date.now() - startTime);- }- }),- );-- // Delays should vary due to jitter (not all exactly the same)- const uniqueDelays = new Set(delays);- expect(uniqueDelays.size).toBeGreaterThan(1);- });-- it("should allow custom shouldRetry function", async () => {- let attempts = 0;-- global.fetch = mock(() => {- attempts++;- return Promise.resolve({- ok: false,- status: 503, // Service Unavailable- statusText: "Service Unavailable",- } as Response);- });-- // Custom retry logic: never retry- const shouldRetry = () => false;-- try {- await fetchWithRetry("https://api.example.com", {- maxRetries: 2,- initialDelay: 10,- shouldRetry,- });- } catch {- // Expected to throw- }-- expect(attempts).toBe(1); // Should not retry due to custom function- });-- it("should handle network errors with retry", async () => {- let attempts = 0;-- global.fetch = mock(() => {- attempts++;- if (attempts < 2) {- return Promise.reject(new Error("fetch failed"));- }- return Promise.resolve({ ok: true } as Response);- });-- const response = await fetchWithRetry("https://api.example.com", {- maxRetries: 3,- initialDelay: 10,- });-- expect(attempts).toBe(2);- expect(response.ok).toBe(true);- });-});--describe("FetchError", () => {- it("should create error with all context", () => {- const originalError = new Error("Network timeout");- const fetchError = new FetchError(- "Request failed",- "https://api.example.com",- "atlassian",- "github",- originalError,- );-- expect(fetchError.message).toBe("Request failed");- expect(fetchError.url).toBe("https://api.example.com");- expect(fetchError.fetcherName).toBe("atlassian");- expect(fetchError.entryId).toBe("github");- expect(fetchError.cause).toBe(originalError);- expect(fetchError.name).toBe("FetchError");- });-- it("should format toString with all context", () => {- const originalError = new Error("Connection reset");- const fetchError = new FetchError(- "HTTP 500",- "https://api.example.com",- "atlassian",- "github",- originalError,- );-- const str = fetchError.toString();-- expect(str).toContain("[FetchError]");- expect(str).toContain("atlassian");- expect(str).toContain("(github)");- expect(str).toContain("HTTP 500");- expect(str).toContain("Connection reset");- });-- it("should format toString without optional fields", () => {- const fetchError = new FetchError(- "Request failed",- "https://api.example.com",- );-- const str = fetchError.toString();-- expect(str).toBe("[FetchError]: Request failed");- });-- it("should support Error.cause standard property", () => {- const originalError = new Error("Original error");- const fetchError = new FetchError(- "Wrapper error",- "https://api.example.com",- undefined,- undefined,- originalError,- );-- expect(fetchError.cause).toBe(originalError);- });-});--describe("fetchWithDeduplication", () => {- it("should deduplicate concurrent requests to same URL", async () => {- let fetchCount = 0;-- global.fetch = mock(() => {- fetchCount++;- return new Promise((resolve) =>- setTimeout(() => resolve({ ok: true, status: 200 } as Response), 50),- );- });-- // Make 5 concurrent requests to the same URL- const promises = Array.from({ length: 5 }, () =>- fetchWithDeduplication("https://api.example.com"),- );-- const responses = await Promise.all(promises);-- // Should only make 1 actual fetch- expect(fetchCount).toBe(1);-- // All responses should be the same- responses.forEach((response) => {- expect(response.ok).toBe(true);- expect(response.status).toBe(200);- });- });-- it("should not deduplicate requests to different URLs", async () => {- let fetchCount = 0;-- global.fetch = mock(() => {- fetchCount++;- return Promise.resolve({ ok: true } as Response);- });-- await Promise.all([- fetchWithDeduplication("https://api.example.com/1"),- fetchWithDeduplication("https://api.example.com/2"),- fetchWithDeduplication("https://api.example.com/3"),- ]);-- // Should make 3 separate fetches- expect(fetchCount).toBe(3);- });-- it("should not deduplicate requests with different methods", async () => {- let fetchCount = 0;-- global.fetch = mock(() => {- fetchCount++;- return Promise.resolve({ ok: true } as Response);- });-- await Promise.all([- fetchWithDeduplication("https://api.example.com", { method: "GET" }),- fetchWithDeduplication("https://api.example.com", { method: "POST" }),- ]);-- // Should make 2 separate fetches- expect(fetchCount).toBe(2);- });-- it("should clean up cache after request completes", async () => {- let fetchCount = 0;-- global.fetch = mock(() => {- fetchCount++;- return Promise.resolve({ ok: true } as Response);- });-- // First request- await fetchWithDeduplication("https://api.example.com");-- // Wait a bit for cleanup- await new Promise((resolve) => setTimeout(resolve, 10));-- // Second request after first completes- await fetchWithDeduplication("https://api.example.com");-- // Should make 2 separate fetches (no deduplication after completion)- expect(fetchCount).toBe(2);- });-- it("should handle errors in deduplicated requests", async () => {- global.fetch = mock(() =>- Promise.resolve({- ok: false,- status: 500,- statusText: "Error",- } as Response),- );-- const promises = Array.from({ length: 3 }, () =>- fetchWithDeduplication("https://api.example.com", { maxRetries: 0 }),- );-- // All should receive the same error- await expect(Promise.all(promises)).rejects.toThrow();- });-- it("should deduplicate requests with same headers", async () => {- let fetchCount = 0;-- global.fetch = mock(() => {- fetchCount++;- return Promise.resolve({ ok: true } as Response);- });-- await Promise.all([- fetchWithDeduplication("https://api.example.com", {- headers: { "X-Test": "value" },- }),- fetchWithDeduplication("https://api.example.com", {- headers: { "X-Test": "value" },- }),- ]);-- // Should only make 1 fetch- expect(fetchCount).toBe(1);- });-});diff --git a/packages/status-fetcher/__tests__/fetch.test.ts b/packages/status-fetcher/__tests__/fetch.test.tsnew file mode 100644index 000000000..97ac65ea0--- /dev/null+++ b/packages/status-fetcher/__tests__/fetch.test.ts@@ -0,0 +1,230 @@+import { beforeEach, describe, expect, it, mock } from "bun:test";+import { Cause, Effect, Exit, Option } from "effect";+import { z } from "zod";+import { FetchError, fetchJson, fetchText } from "../src/fetch";++const TEST_URL = "https://api.example.com/status";++type FetchImpl = (url: string, init?: RequestInit) => Promise<Response>;++const installMockFetch = (impl: FetchImpl) => {+ const fn = mock(impl);+ global.fetch = fn as unknown as typeof fetch;+ return fn;+};++const okJson = (body: Record<string, string>): Response =>+ ({+ ok: true,+ status: 200,+ statusText: "OK",+ json: async () => body,+ text: async () => JSON.stringify(body),+ }) as Response;++const errorResponse = (status: number, statusText: string): Response =>+ ({+ ok: false,+ status,+ statusText,+ json: async () => ({}),+ text: async () => "",+ }) as Response;++const okText = (body: string): Response =>+ ({+ ok: true,+ status: 200,+ statusText: "OK",+ text: async () => body,+ json: async () => JSON.parse(body),+ }) as Response;++const expectFailure = <A>(exit: Exit.Exit<A, FetchError>): FetchError => {+ if (!Exit.isFailure(exit)) {+ throw new Error("expected Exit.Failure");+ }+ const failure = Cause.failureOption(exit.cause);+ if (Option.isNone(failure)) {+ throw new Error("expected Cause.Fail");+ }+ return failure.value;+};++describe("fetchJson", () => {+ beforeEach(() => {+ installMockFetch(() => Promise.resolve(okJson({ ok: "yes" })));+ });++ it("returns parsed body on 200", async () => {+ installMockFetch(() => Promise.resolve(okJson({ name: "OpenStatus" })));+ const schema = z.object({ name: z.string() });+ const result = await Effect.runPromise(+ fetchJson({ url: TEST_URL, schema }),+ );+ expect(result.name).toBe("OpenStatus");+ });++ it("fails with FetchError carrying httpStatus on 4xx and does not retry", async () => {+ const fetchMock = installMockFetch(() =>+ Promise.resolve(errorResponse(404, "Not Found")),+ );+ const schema = z.object({ name: z.string() });+ const exit = await Effect.runPromiseExit(+ fetchJson({ url: TEST_URL, schema, fetcherName: "test", entryId: "x" }),+ );+ const err = expectFailure(exit);+ expect(err.httpStatus).toBe(404);+ expect(err.fetcherName).toBe("test");+ expect(err.entryId).toBe("x");+ expect(fetchMock.mock.calls.length).toBe(1);+ });++ it("retries up to 3 times on 5xx then fails", async () => {+ const fetchMock = installMockFetch(() =>+ Promise.resolve(errorResponse(503, "Service Unavailable")),+ );+ const schema = z.object({ name: z.string() });+ const exit = await Effect.runPromiseExit(+ fetchJson({ url: TEST_URL, schema }),+ );+ const err = expectFailure(exit);+ expect(err.httpStatus).toBe(503);+ expect(fetchMock.mock.calls.length).toBe(4);+ });++ it("retries up to 3 times on network error then fails", async () => {+ const fetchMock = installMockFetch(() =>+ Promise.reject(new Error("ECONNRESET")),+ );+ const schema = z.object({ name: z.string() });+ const exit = await Effect.runPromiseExit(+ fetchJson({ url: TEST_URL, schema }),+ );+ const err = expectFailure(exit);+ expect(err.httpStatus).toBeUndefined();+ expect(fetchMock.mock.calls.length).toBe(4);+ });++ it("fails with FetchError on schema mismatch without retrying", async () => {+ const fetchMock = installMockFetch(() =>+ Promise.resolve(okJson({ unexpected: "shape" })),+ );+ const schema = z.object({ name: z.string() });+ const exit = await Effect.runPromiseExit(+ fetchJson({ url: TEST_URL, schema }),+ );+ const err = expectFailure(exit);+ expect(err.cause).toBeInstanceOf(Error);+ expect(fetchMock.mock.calls.length).toBe(1);+ });++ it("applies default User-Agent and Accept headers", async () => {+ let capturedInit: RequestInit | undefined;+ installMockFetch((_url, init) => {+ capturedInit = init;+ return Promise.resolve(okJson({ ok: "yes" }));+ });+ const schema = z.object({ ok: z.string() });+ await Effect.runPromise(fetchJson({ url: TEST_URL, schema }));+ const headers = capturedInit?.headers as Record<string, string>;+ expect(headers["User-Agent"]).toBe("OpenStatus-Directory/1.0");+ expect(headers.Accept).toBe("application/json");+ });++ it("merges caller headers over defaults", async () => {+ let capturedInit: RequestInit | undefined;+ installMockFetch((_url, init) => {+ capturedInit = init;+ return Promise.resolve(okJson({ ok: "yes" }));+ });+ const schema = z.object({ ok: z.string() });+ await Effect.runPromise(+ fetchJson({+ url: TEST_URL,+ schema,+ init: { headers: { "User-Agent": "Custom/1.0", "X-Trace": "abc" } },+ }),+ );+ const headers = capturedInit?.headers as Record<string, string>;+ expect(headers["User-Agent"]).toBe("Custom/1.0");+ expect(headers.Accept).toBe("application/json");+ expect(headers["X-Trace"]).toBe("abc");+ });++ it("passes through method and body from init", async () => {+ let capturedInit: RequestInit | undefined;+ installMockFetch((_url, init) => {+ capturedInit = init;+ return Promise.resolve(okJson({ ok: "yes" }));+ });+ const schema = z.object({ ok: z.string() });+ await Effect.runPromise(+ fetchJson({+ url: TEST_URL,+ schema,+ init: { method: "POST", body: '{"k":"v"}' },+ }),+ );+ expect(capturedInit?.method).toBe("POST");+ expect(capturedInit?.body).toBe('{"k":"v"}');+ });+});++describe("fetchText", () => {+ it("returns response.text() verbatim", async () => {+ installMockFetch(() => Promise.resolve(okText("<html>ok</html>")));+ const result = await Effect.runPromise(fetchText({ url: TEST_URL }));+ expect(result).toBe("<html>ok</html>");+ });++ it("applies browser-ish default User-Agent", async () => {+ let capturedInit: RequestInit | undefined;+ installMockFetch((_url, init) => {+ capturedInit = init;+ return Promise.resolve(okText("body"));+ });+ await Effect.runPromise(fetchText({ url: TEST_URL }));+ const headers = capturedInit?.headers as Record<string, string>;+ expect(headers["User-Agent"]).toBe(+ "Mozilla/5.0 (compatible; OpenStatus-Bot/1.0)",+ );+ });++ it("retries on 5xx then fails", async () => {+ const fetchMock = installMockFetch(() =>+ Promise.resolve(errorResponse(500, "Server Error")),+ );+ const exit = await Effect.runPromiseExit(fetchText({ url: TEST_URL }));+ const err = expectFailure(exit);+ expect(err.httpStatus).toBe(500);+ expect(fetchMock.mock.calls.length).toBe(4);+ });+});++describe("FetchError", () => {+ it("formats message with fetcherName and entryId", () => {+ const err = new FetchError({+ url: "https://example.com",+ fetcherName: "atlassian",+ entryId: "github",+ httpStatus: 503,+ });+ expect(err.message).toBe(+ "[atlassian (github)] HTTP 503: https://example.com",+ );+ expect(err.name).toBe("FetchError");+ expect(err.url).toBe("https://example.com");+ });++ it("uses 'fetch failed' when no httpStatus", () => {+ const err = new FetchError({ url: "https://x.com" });+ expect(err.message).toBe("[FetchError] fetch failed: https://x.com");+ });++ it("preserves cause", () => {+ const cause = new Error("boom");+ const err = new FetchError({ url: "https://x.com", cause });+ expect(err.cause).toBe(cause);+ });+});diff --git a/packages/status-fetcher/__tests__/fetchers/atlassian.test.ts b/packages/status-fetcher/__tests__/fetchers/atlassian.test.tsindex c95dfc14f..65e49528e 100644--- a/packages/status-fetcher/__tests__/fetchers/atlassian.test.ts+++ b/packages/status-fetcher/__tests__/fetchers/atlassian.test.ts@@ -1,6 +1,12 @@-import { beforeEach, describe, expect, it, mock } from "bun:test";+import { beforeEach, describe, expect, it } from "bun:test";import { AtlassianFetcher } from "../../src/fetchers/atlassian";import type { StatusPageEntry } from "../../src/types";+import {+ expectFetchError,+ installMockFetch,+ runFetcher,+ runFetcherExit,+} from "../helpers";describe("AtlassianFetcher", () => {let fetcher: AtlassianFetcher;@@ -90,20 +96,20 @@ describe("AtlassianFetcher", () => {},};- global.fetch = mock(() =>+ const fetchMock = installMockFetch(() =>Promise.resolve({ok: true,json: async () => mockResponse,} as Response),);- const result = await fetcher.fetch(entry);+ const result = await runFetcher(fetcher, entry);expect(result.severity).toBe("none");expect(result.description).toBe("All Systems Operational");expect(result.timezone).toBe("Etc/UTC");expect(typeof result.updated_at).toBe("number");- expect(global.fetch).toHaveBeenCalledWith(+ expect(fetchMock).toHaveBeenCalledWith("https://www.githubstatus.com/api/v2/summary.json",expect.objectContaining({headers: expect.objectContaining({@@ -136,14 +142,14 @@ describe("AtlassianFetcher", () => {},};- global.fetch = mock(() =>+ installMockFetch(() =>Promise.resolve({ok: true,json: async () => mockResponse,} as Response),);- const result = await fetcher.fetch(entry);+ const result = await runFetcher(fetcher, entry);expect(result.severity).toBe("minor");expect(result.description).toBe("Elevated Error Rates");@@ -174,14 +180,14 @@ describe("AtlassianFetcher", () => {},};- global.fetch = mock(() =>+ installMockFetch(() =>Promise.resolve({ok: true,json: async () => mockResponse,} as Response),);- const result = await fetcher.fetch(entry);+ const result = await runFetcher(fetcher, entry);expect(result.severity).toBe("major");expect(result.description).toBe("Major Service Outage");@@ -215,22 +221,22 @@ describe("AtlassianFetcher", () => {},};- global.fetch = mock(() =>+ const fetchMock = installMockFetch(() =>Promise.resolve({ok: true,json: async () => mockResponse,} as Response),);- await fetcher.fetch(entry);+ await runFetcher(fetcher, entry);- expect(global.fetch).toHaveBeenCalledWith(+ expect(fetchMock).toHaveBeenCalledWith("https://custom.endpoint.com/status.json",expect.any(Object),);});- it("should throw error on non-200 response", async () => {+ it("should fail with FetchError on non-200 response", async () => {const entry: StatusPageEntry = {id: "test",name: "Test",@@ -240,7 +246,7 @@ describe("AtlassianFetcher", () => {industry: ["saas"],};- global.fetch = mock(() =>+ installMockFetch(() =>Promise.resolve({ok: false,status: 404,@@ -248,10 +254,14 @@ describe("AtlassianFetcher", () => {} as Response),);- await expect(fetcher.fetch(entry)).rejects.toThrow("HTTP 404: Not Found");+ const exit = await runFetcherExit(fetcher, entry);+ const err = expectFetchError(exit);+ expect(err.httpStatus).toBe(404);+ expect(err.fetcherName).toBe("atlassian");+ expect(err.entryId).toBe("test");});- it("should throw error on invalid JSON schema", async () => {+ it("should fail with FetchError on invalid JSON schema", async () => {const entry: StatusPageEntry = {id: "test",name: "Test",@@ -261,14 +271,16 @@ describe("AtlassianFetcher", () => {industry: ["saas"],};- global.fetch = mock(() =>+ installMockFetch(() =>Promise.resolve({ok: true,json: async () => ({ invalid: "data" }),} as Response),);- await expect(fetcher.fetch(entry)).rejects.toThrow();+ const exit = await runFetcherExit(fetcher, entry);+ const err = expectFetchError(exit);+ expect(err.cause).toBeInstanceOf(Error);});});});diff --git a/packages/status-fetcher/__tests__/fetchers/betterstack.test.ts b/packages/status-fetcher/__tests__/fetchers/betterstack.test.tsindex 10a0be0af..e596c9de6 100644--- a/packages/status-fetcher/__tests__/fetchers/betterstack.test.ts+++ b/packages/status-fetcher/__tests__/fetchers/betterstack.test.ts@@ -1,6 +1,12 @@-import { beforeEach, describe, expect, it, mock } from "bun:test";+import { beforeEach, describe, expect, it } from "bun:test";import { BetterStackFetcher } from "../../src/fetchers/betterstack";import type { StatusPageEntry } from "../../src/types";+import {+ expectFetchError,+ installMockFetch,+ runFetcher,+ runFetcherExit,+} from "../helpers";describe("BetterStackFetcher", () => {let fetcher: BetterStackFetcher;@@ -101,20 +107,20 @@ describe("BetterStackFetcher", () => {},};- global.fetch = mock(() =>+ const fetchMock = installMockFetch(() =>Promise.resolve({ok: true,json: async () => mockResponse,} as Response),);- const result = await fetcher.fetch(entry);+ const result = await runFetcher(fetcher, entry);expect(result.severity).toBe("none");expect(result.description).toBe("All Systems Operational");expect(result.timezone).toBe("America/New_York");expect(typeof result.updated_at).toBe("number");- expect(global.fetch).toHaveBeenCalledWith(+ expect(fetchMock).toHaveBeenCalledWith("https://status.test.com/index.json",expect.objectContaining({headers: expect.objectContaining({@@ -148,14 +154,14 @@ describe("BetterStackFetcher", () => {},};- global.fetch = mock(() =>+ installMockFetch(() =>Promise.resolve({ok: true,json: async () => mockResponse,} as Response),);- const result = await fetcher.fetch(entry);+ const result = await runFetcher(fetcher, entry);expect(result.severity).toBe("minor");expect(result.description).toBe("Degraded Service");@@ -184,14 +190,14 @@ describe("BetterStackFetcher", () => {},};- global.fetch = mock(() =>+ installMockFetch(() =>Promise.resolve({ok: true,json: async () => mockResponse,} as Response),);- const result = await fetcher.fetch(entry);+ const result = await runFetcher(fetcher, entry);expect(result.severity).toBe("major");expect(result.description).toBe("Service Outage");@@ -224,22 +230,22 @@ describe("BetterStackFetcher", () => {},};- global.fetch = mock(() =>+ const fetchMock = installMockFetch(() =>Promise.resolve({ok: true,json: async () => mockResponse,} as Response),);- await fetcher.fetch(entry);+ await runFetcher(fetcher, entry);- expect(global.fetch).toHaveBeenCalledWith(+ expect(fetchMock).toHaveBeenCalledWith("https://custom.endpoint.com/status.json",expect.any(Object),);});- it("should throw error on non-200 response", async () => {+ it("should fail with FetchError on 4xx response", async () => {const entry: StatusPageEntry = {id: "test",name: "Test",@@ -249,7 +255,7 @@ describe("BetterStackFetcher", () => {industry: ["saas"],};- global.fetch = mock(() =>+ installMockFetch(() =>Promise.resolve({ok: false,status: 403,@@ -257,10 +263,12 @@ describe("BetterStackFetcher", () => {} as Response),);- await expect(fetcher.fetch(entry)).rejects.toThrow("HTTP 403: Forbidden");+ const exit = await runFetcherExit(fetcher, entry);+ const err = expectFetchError(exit);+ expect(err.httpStatus).toBe(403);});- it("should throw error on invalid JSON schema", async () => {+ it("should fail with FetchError on invalid JSON schema", async () => {const entry: StatusPageEntry = {id: "test",name: "Test",@@ -270,14 +278,16 @@ describe("BetterStackFetcher", () => {industry: ["saas"],};- global.fetch = mock(() =>+ installMockFetch(() =>Promise.resolve({ok: true,json: async () => ({ invalid: "data" }),} as Response),);- await expect(fetcher.fetch(entry)).rejects.toThrow();+ const exit = await runFetcherExit(fetcher, entry);+ const err = expectFetchError(exit);+ expect(err.cause).toBeInstanceOf(Error);});});});diff --git a/packages/status-fetcher/__tests__/fetchers/custom.test.ts b/packages/status-fetcher/__tests__/fetchers/custom.test.tsindex cecb6d8c8..272ce40a3 100644--- a/packages/status-fetcher/__tests__/fetchers/custom.test.ts+++ b/packages/status-fetcher/__tests__/fetchers/custom.test.ts@@ -1,6 +1,12 @@-import { beforeEach, describe, expect, it, mock } from "bun:test";+import { beforeEach, describe, expect, it } from "bun:test";import { CustomApiFetcher } from "../../src/fetchers/custom";import type { StatusPageEntry } from "../../src/types";+import {+ expectFetchError,+ installMockFetch,+ runFetcher,+ runFetcherExit,+} from "../helpers";describe("CustomApiFetcher", () => {let fetcher: CustomApiFetcher;@@ -53,7 +59,7 @@ describe("CustomApiFetcher", () => {});describe("fetch", () => {- it("should throw error if endpoint is not provided", async () => {+ it("should fail with FetchError if endpoint is not provided", async () => {const entry: StatusPageEntry = {id: "test",name: "Test",@@ -64,7 +70,12 @@ describe("CustomApiFetcher", () => {api_config: { type: "custom" },};- await expect(fetcher.fetch(entry)).rejects.toThrow(+ const exit = await runFetcherExit(fetcher, entry);+ const err = expectFetchError(exit);+ if (!(err.cause instanceof Error)) {+ throw new Error("expected Error cause");+ }+ expect(err.cause.message).toContain("Custom API requires explicit endpoint configuration",);});@@ -92,14 +103,14 @@ describe("CustomApiFetcher", () => {active_incidents: [],};- global.fetch = mock(() =>+ installMockFetch(() =>Promise.resolve({ok: true,json: async () => mockResponse,} as Response),);- const result = await fetcher.fetch(entry);+ const result = await runFetcher(fetcher, entry);expect(result.severity).toBe("none");expect(result.description).toBe("All Systems Operational");@@ -129,14 +140,14 @@ describe("CustomApiFetcher", () => {active_incidents: [],};- global.fetch = mock(() =>+ installMockFetch(() =>Promise.resolve({ok: true,json: async () => mockResponse,} as Response),);- const result = await fetcher.fetch(entry);+ const result = await runFetcher(fetcher, entry);expect(result.severity).toBe("none");expect(result.updated_at).toBe(1708091234000);@@ -172,14 +183,14 @@ describe("CustomApiFetcher", () => {],};- global.fetch = mock(() =>+ installMockFetch(() =>Promise.resolve({ok: true,json: async () => mockResponse,} as Response),);- const result = await fetcher.fetch(entry);+ const result = await runFetcher(fetcher, entry);expect(result.severity).toBe("minor");expect(result.description).toBe("Login Issues");@@ -215,14 +226,14 @@ describe("CustomApiFetcher", () => {],};- global.fetch = mock(() =>+ installMockFetch(() =>Promise.resolve({ok: true,json: async () => mockResponse,} as Response),);- const result = await fetcher.fetch(entry);+ const result = await runFetcher(fetcher, entry);expect(result.severity).toBe("major");expect(result.description).toBe("Service Unavailable");@@ -249,14 +260,14 @@ describe("CustomApiFetcher", () => {message: "All systems running smoothly",};- global.fetch = mock(() =>+ installMockFetch(() =>Promise.resolve({ok: true,json: async () => mockResponse,} as Response),);- const result = await fetcher.fetch(entry);+ const result = await runFetcher(fetcher, entry);expect(result.severity).toBe("none");expect(result.description).toBe("All systems running smoothly");@@ -281,14 +292,14 @@ describe("CustomApiFetcher", () => {message: "System is down",};- global.fetch = mock(() =>+ installMockFetch(() =>Promise.resolve({ok: true,json: async () => mockResponse,} as Response),);- const result = await fetcher.fetch(entry);+ const result = await runFetcher(fetcher, entry);expect(result.severity).toBe("major");expect(result.description).toBe("System is down");@@ -313,14 +324,14 @@ describe("CustomApiFetcher", () => {description: "Performance issues",};- global.fetch = mock(() =>+ installMockFetch(() =>Promise.resolve({ok: true,json: async () => mockResponse,} as Response),);- const result = await fetcher.fetch(entry);+ const result = await runFetcher(fetcher, entry);expect(result.severity).toBe("minor");expect(result.description).toBe("Performance issues");@@ -344,14 +355,14 @@ describe("CustomApiFetcher", () => {health: "healthy",};- global.fetch = mock(() =>+ installMockFetch(() =>Promise.resolve({ok: true,json: async () => mockResponse,} as Response),);- const result = await fetcher.fetch(entry);+ const result = await runFetcher(fetcher, entry);expect(result.severity).toBe("none");expect(result.description).toBe("healthy");@@ -359,7 +370,7 @@ describe("CustomApiFetcher", () => {});describe("AWS parser", () => {- it("should throw error for unimplemented AWS parser", async () => {+ it("should fail with FetchError for unimplemented AWS parser", async () => {const entry: StatusPageEntry = {id: "aws",name: "AWS",@@ -374,20 +385,25 @@ describe("CustomApiFetcher", () => {},};- global.fetch = mock(() =>+ installMockFetch(() =>Promise.resolve({ok: true,json: async () => ({}),} as Response),);- await expect(fetcher.fetch(entry)).rejects.toThrow(+ const exit = await runFetcherExit(fetcher, entry);+ const err = expectFetchError(exit);+ if (!(err.cause instanceof Error)) {+ throw new Error("expected Error cause");+ }+ expect(err.cause.message).toContain("AWS parser not implemented - uses RSS feeds",);});});- it("should throw error on non-200 response", async () => {+ it("should fail with FetchError on 4xx response", async () => {const entry: StatusPageEntry = {id: "test",name: "Test",@@ -401,7 +417,7 @@ describe("CustomApiFetcher", () => {},};- global.fetch = mock(() =>+ installMockFetch(() =>Promise.resolve({ok: false,status: 401,@@ -409,9 +425,9 @@ describe("CustomApiFetcher", () => {} as Response),);- await expect(fetcher.fetch(entry)).rejects.toThrow(- "HTTP 401: Unauthorized",- );+ const exit = await runFetcherExit(fetcher, entry);+ const err = expectFetchError(exit);+ expect(err.httpStatus).toBe(401);});});});diff --git a/packages/status-fetcher/__tests__/fetchers/edge-cases.test.ts b/packages/status-fetcher/__tests__/fetchers/edge-cases.test.tsindex feb07c1e2..d46c873f4 100644--- a/packages/status-fetcher/__tests__/fetchers/edge-cases.test.ts+++ b/packages/status-fetcher/__tests__/fetchers/edge-cases.test.ts@@ -1,10 +1,17 @@-import { describe, expect, it, mock } from "bun:test";+import { describe, expect, it } from "bun:test";+import { Exit } from "effect";import { AtlassianFetcher } from "../../src/fetchers/atlassian";import { BetterStackFetcher } from "../../src/fetchers/betterstack";import { CustomApiFetcher } from "../../src/fetchers/custom";import { HtmlScraperFetcher } from "../../src/fetchers/html";import { InstatusFetcher } from "../../src/fetchers/instatus";import type { StatusPageEntry } from "../../src/types";+import {+ expectFetchError,+ installMockFetch,+ runFetcher,+ runFetcherExit,+} from "../helpers";describe("Fetcher Edge Cases", () => {describe("Network Errors", () => {@@ -19,9 +26,14 @@ describe("Fetcher Edge Cases", () => {industry: ["saas"],};- global.fetch = mock(() => Promise.reject(new Error("Network error")));+ installMockFetch(() => Promise.reject(new Error("Network error")));- await expect(fetcher.fetch(entry)).rejects.toThrow("Network error");+ const exit = await runFetcherExit(fetcher, entry);+ const err = expectFetchError(exit);+ if (!(err.cause instanceof Error)) {+ throw new Error("expected Error cause");+ }+ expect(err.cause.message).toContain("Network error");});it("should handle timeout errors", async () => {@@ -35,9 +47,10 @@ describe("Fetcher Edge Cases", () => {industry: ["saas"],};- global.fetch = mock(() => Promise.reject(new Error("Request timeout")));+ installMockFetch(() => Promise.reject(new Error("Request timeout")));- await expect(fetcher.fetch(entry)).rejects.toThrow("Request timeout");+ const exit = await runFetcherExit(fetcher, entry);+ expect(Exit.isFailure(exit)).toBe(true);});});@@ -53,7 +66,7 @@ describe("Fetcher Edge Cases", () => {industry: ["saas"],};- global.fetch = mock(() =>+ installMockFetch(() =>Promise.resolve({ok: true,json: async () => {@@ -62,7 +75,12 @@ describe("Fetcher Edge Cases", () => {} as unknown as Response),);- await expect(fetcher.fetch(entry)).rejects.toThrow("Invalid JSON");+ const exit = await runFetcherExit(fetcher, entry);+ const err = expectFetchError(exit);+ if (!(err.cause instanceof Error)) {+ throw new Error("expected Error cause");+ }+ expect(err.cause.message).toContain("Invalid JSON");});it("should handle missing required fields in BetterStack response", async () => {@@ -76,7 +94,6 @@ describe("Fetcher Edge Cases", () => {industry: ["saas"],};- // Missing data.attributesconst malformedResponse = {data: {id: "123",@@ -84,14 +101,15 @@ describe("Fetcher Edge Cases", () => {},};- global.fetch = mock(() =>+ installMockFetch(() =>Promise.resolve({ok: true,json: async () => malformedResponse,} as Response),);- await expect(fetcher.fetch(entry)).rejects.toThrow();+ const exit = await runFetcherExit(fetcher, entry);+ expect(Exit.isFailure(exit)).toBe(true);});it("should handle empty response", async () => {@@ -105,14 +123,15 @@ describe("Fetcher Edge Cases", () => {industry: ["saas"],};- global.fetch = mock(() =>+ installMockFetch(() =>Promise.resolve({ok: true,json: async () => ({}),} as Response),);- await expect(fetcher.fetch(entry)).rejects.toThrow();+ const exit = await runFetcherExit(fetcher, entry);+ expect(Exit.isFailure(exit)).toBe(true);});});@@ -137,19 +156,20 @@ describe("Fetcher Edge Cases", () => {updated_at: "2024-02-16T12:00:00.000Z",},status: {- indicator: "unknown", // Invalid value+ indicator: "unknown",description: "Unknown Status",},};- global.fetch = mock(() =>+ installMockFetch(() =>Promise.resolve({ok: true,json: async () => mockResponse,} as Response),);- await expect(fetcher.fetch(entry)).rejects.toThrow();+ const exit = await runFetcherExit(fetcher, entry);+ expect(Exit.isFailure(exit)).toBe(true);});it("should handle unknown status type in Instatus", async () => {@@ -168,7 +188,7 @@ describe("Fetcher Edge Cases", () => {activeMaintenances: [],status: {text: "Unknown",- type: "UNKNOWN", // Invalid type+ type: "UNKNOWN",},page: {name: "Test",@@ -177,14 +197,15 @@ describe("Fetcher Edge Cases", () => {},};- global.fetch = mock(() =>+ installMockFetch(() =>Promise.resolve({ok: true,json: async () => mockResponse,} as Response),);- await expect(fetcher.fetch(entry)).rejects.toThrow();+ const exit = await runFetcherExit(fetcher, entry);+ expect(Exit.isFailure(exit)).toBe(true);});});@@ -203,15 +224,14 @@ describe("Fetcher Edge Cases", () => {const malformedHtml = "<html><body><div class='status'>Unclosed div";- global.fetch = mock(() =>+ installMockFetch(() =>Promise.resolve({ok: true,text: async () => malformedHtml,} as Response),);- // Should not throw, but return Unknown- const result = await fetcher.fetch(entry);+ const result = await runFetcher(fetcher, entry);expect(result.description).toBe("Unknown");expect(result.severity).toBe("none");expect(result.status).toBe("operational");@@ -229,14 +249,14 @@ describe("Fetcher Edge Cases", () => {api_config: { type: "html-scraper" },};- global.fetch = mock(() =>+ installMockFetch(() =>Promise.resolve({ok: true,text: async () => "",} as Response),);- const result = await fetcher.fetch(entry);+ const result = await runFetcher(fetcher, entry);expect(result.description).toBe("Unknown");expect(result.severity).toBe("none");});@@ -262,14 +282,14 @@ describe("Fetcher Edge Cases", () => {</html>`;- global.fetch = mock(() =>+ installMockFetch(() =>Promise.resolve({ok: true,text: async () => htmlWithNoStatus,} as Response),);- const result = await fetcher.fetch(entry);+ const result = await runFetcher(fetcher, entry);expect(result.description).toBe("Unknown");});});@@ -284,10 +304,15 @@ describe("Fetcher Edge Cases", () => {status_page_url: "https://status.test.com",provider: "custom",industry: ["saas"],- api_config: { type: "custom" }, // Missing endpoint+ api_config: { type: "custom" },};- await expect(fetcher.fetch(entry)).rejects.toThrow(+ const exit = await runFetcherExit(fetcher, entry);+ const err = expectFetchError(exit);+ if (!(err.cause instanceof Error)) {+ throw new Error("expected Error cause");+ }+ expect(err.cause.message).toContain("Custom API requires explicit endpoint configuration",);});@@ -308,14 +333,19 @@ describe("Fetcher Edge Cases", () => {},};- global.fetch = mock(() =>+ installMockFetch(() =>Promise.resolve({ok: true,json: async () => ({}),} as Response),);- await expect(fetcher.fetch(entry)).rejects.toThrow(+ const exit = await runFetcherExit(fetcher, entry);+ const err = expectFetchError(exit);+ if (!(err.cause instanceof Error)) {+ throw new Error("expected Error cause");+ }+ expect(err.cause.message).toContain("AWS parser not implemented - uses RSS feeds",);});@@ -337,14 +367,14 @@ describe("Fetcher Edge Cases", () => {const minimalResponse = { status: "ok" };- global.fetch = mock(() =>+ installMockFetch(() =>Promise.resolve({ok: true,json: async () => minimalResponse,} as Response),);- const result = await fetcher.fetch(entry);+ const result = await runFetcher(fetcher, entry);expect(result.severity).toBe("none");expect(result.status).toBe("operational");});@@ -362,7 +392,7 @@ describe("Fetcher Edge Cases", () => {{ code: 503, text: "Service Unavailable" },];- testCases.forEach(({ code, text }) => {+ for (const { code, text } of testCases) {it(`should handle ${code} ${text}`, async () => {const fetcher = new AtlassianFetcher();const entry: StatusPageEntry = {@@ -374,7 +404,7 @@ describe("Fetcher Edge Cases", () => {industry: ["saas"],};- global.fetch = mock(() =>+ installMockFetch(() =>Promise.resolve({ok: false,status: code,@@ -382,9 +412,11 @@ describe("Fetcher Edge Cases", () => {} as Response),);- await expect(fetcher.fetch(entry)).rejects.toThrow(`${code}`);+ const exit = await runFetcherExit(fetcher, entry);+ const err = expectFetchError(exit);+ expect(err.httpStatus).toBe(code);});- });+ }});describe("Date/Timestamp Edge Cases", () => {@@ -405,7 +437,7 @@ describe("Fetcher Edge Cases", () => {name: "Test",url: "https://status.test.com",timezone: "UTC",- updated_at: "not-a-date", // Invalid date+ updated_at: "not-a-date",},status: {indicator: "none",@@ -413,14 +445,15 @@ describe("Fetcher Edge Cases", () => {},};- global.fetch = mock(() =>+ installMockFetch(() =>Promise.resolve({ok: true,json: async () => mockResponse,} as Response),);- await expect(fetcher.fetch(entry)).rejects.toThrow();+ const exit = await runFetcherExit(fetcher, entry);+ expect(Exit.isFailure(exit)).toBe(true);});it("should handle Slack API with string timestamp", async () => {@@ -446,15 +479,14 @@ describe("Fetcher Edge Cases", () => {active_incidents: [],};- global.fetch = mock(() =>+ installMockFetch(() =>Promise.resolve({ok: true,json: async () => mockResponse,} as Response),);- // Should handle string timestamps by parsing them- const result = await fetcher.fetch(entry);+ const result = await runFetcher(fetcher, entry);expect(result.severity).toBe("none");expect(result.status).toBe("operational");expect(typeof result.updated_at).toBe("number");diff --git a/packages/status-fetcher/__tests__/fetchers/html.test.ts b/packages/status-fetcher/__tests__/fetchers/html.test.tsindex 643aca752..7e35de2dc 100644--- a/packages/status-fetcher/__tests__/fetchers/html.test.ts+++ b/packages/status-fetcher/__tests__/fetchers/html.test.ts@@ -1,6 +1,12 @@-import { beforeEach, describe, expect, it, mock } from "bun:test";+import { beforeEach, describe, expect, it } from "bun:test";import { HtmlScraperFetcher } from "../../src/fetchers/html";import type { StatusPageEntry } from "../../src/types";+import {+ expectFetchError,+ installMockFetch,+ runFetcher,+ runFetcherExit,+} from "../helpers";describe("HtmlScraperFetcher", () => {let fetcher: HtmlScraperFetcher;@@ -72,20 +78,20 @@ describe("HtmlScraperFetcher", () => {</html>`;- global.fetch = mock(() =>+ const fetchMock = installMockFetch(() =>Promise.resolve({ok: true,text: async () => mockHtml,} as Response),);- const result = await fetcher.fetch(entry);+ const result = await runFetcher(fetcher, entry);expect(result.severity).toBe("none");expect(result.description).toBe("All Systems Operational");expect(result.timezone).toBe("UTC");expect(typeof result.updated_at).toBe("number");- expect(global.fetch).toHaveBeenCalledWith(+ expect(fetchMock).toHaveBeenCalledWith("https://status.test.com",expect.objectContaining({headers: expect.objectContaining({@@ -114,14 +120,14 @@ describe("HtmlScraperFetcher", () => {</html>`;- global.fetch = mock(() =>+ installMockFetch(() =>Promise.resolve({ok: true,text: async () => mockHtml,} as Response),);- const result = await fetcher.fetch(entry);+ const result = await runFetcher(fetcher, entry);expect(result.severity).toBe("none");expect(result.description).toBe("operational");@@ -147,14 +153,14 @@ describe("HtmlScraperFetcher", () => {</html>`;- global.fetch = mock(() =>+ installMockFetch(() =>Promise.resolve({ok: true,text: async () => mockHtml,} as Response),);- const result = await fetcher.fetch(entry);+ const result = await runFetcher(fetcher, entry);expect(result.severity).toBe("none");expect(result.description).toBe("All systems operational");@@ -179,14 +185,14 @@ describe("HtmlScraperFetcher", () => {</html>`;- global.fetch = mock(() =>+ installMockFetch(() =>Promise.resolve({ok: true,text: async () => mockHtml,} as Response),);- const result = await fetcher.fetch(entry);+ const result = await runFetcher(fetcher, entry);expect(result.severity).toBe("minor");expect(result.description).toBe("Service Degraded");@@ -211,14 +217,14 @@ describe("HtmlScraperFetcher", () => {</html>`;- global.fetch = mock(() =>+ installMockFetch(() =>Promise.resolve({ok: true,text: async () => mockHtml,} as Response),);- const result = await fetcher.fetch(entry);+ const result = await runFetcher(fetcher, entry);expect(result.severity).toBe("minor");expect(result.description).toBe("Partial Service Outage");@@ -243,14 +249,14 @@ describe("HtmlScraperFetcher", () => {</html>`;- global.fetch = mock(() =>+ installMockFetch(() =>Promise.resolve({ok: true,text: async () => mockHtml,} as Response),);- const result = await fetcher.fetch(entry);+ const result = await runFetcher(fetcher, entry);expect(result.severity).toBe("major");expect(result.description).toBe("Major Outage in Progress");@@ -275,14 +281,14 @@ describe("HtmlScraperFetcher", () => {</html>`;- global.fetch = mock(() =>+ installMockFetch(() =>Promise.resolve({ok: true,text: async () => mockHtml,} as Response),);- const result = await fetcher.fetch(entry);+ const result = await runFetcher(fetcher, entry);expect(result.severity).toBe("major");expect(result.description).toBe("System Down");@@ -307,20 +313,20 @@ describe("HtmlScraperFetcher", () => {</html>`;- global.fetch = mock(() =>+ installMockFetch(() =>Promise.resolve({ok: true,text: async () => mockHtml,} as Response),);- const result = await fetcher.fetch(entry);+ const result = await runFetcher(fetcher, entry);expect(result.severity).toBe("none");expect(result.description).toBe("Unknown");});- it("should throw error on non-200 response", async () => {+ it("should fail with FetchError on non-200 response", async () => {const entry: StatusPageEntry = {id: "test",name: "Test",@@ -331,14 +337,16 @@ describe("HtmlScraperFetcher", () => {api_config: { type: "html-scraper" },};- global.fetch = mock(() =>+ installMockFetch(() =>Promise.resolve({ok: false,status: 404,} as Response),);- await expect(fetcher.fetch(entry)).rejects.toThrow("HTTP 404:");+ const exit = await runFetcherExit(fetcher, entry);+ const err = expectFetchError(exit);+ expect(err.httpStatus).toBe(404);});it("should trim whitespace from description", async () => {@@ -364,14 +372,14 @@ describe("HtmlScraperFetcher", () => {</html>`;- global.fetch = mock(() =>+ installMockFetch(() =>Promise.resolve({ok: true,text: async () => mockHtml,} as Response),);- const result = await fetcher.fetch(entry);+ const result = await runFetcher(fetcher, entry);expect(result.description).toBe("All Systems Operational");});diff --git a/packages/status-fetcher/__tests__/fetchers/incidentio.test.ts b/packages/status-fetcher/__tests__/fetchers/incidentio.test.tsindex 8bac98654..032984885 100644--- a/packages/status-fetcher/__tests__/fetchers/incidentio.test.ts+++ b/packages/status-fetcher/__tests__/fetchers/incidentio.test.ts@@ -1,6 +1,12 @@-import { beforeEach, describe, expect, it, mock } from "bun:test";+import { beforeEach, describe, expect, it } from "bun:test";import { IncidentioFetcher } from "../../src/fetchers/incidentio";import type { StatusPageEntry } from "../../src/types";+import {+ expectFetchError,+ installMockFetch,+ runFetcher,+ runFetcherExit,+} from "../helpers";describe("IncidentioFetcher", () => {let fetcher: IncidentioFetcher;@@ -81,19 +87,19 @@ describe("IncidentioFetcher", () => {scheduled_maintenances: [],};- global.fetch = mock(() =>+ const fetchMock = installMockFetch(() =>Promise.resolve({ok: true,json: async () => mockResponse,} as Response),);- const result = await fetcher.fetch(entry);+ const result = await runFetcher(fetcher, entry);expect(result.severity).toBe("none");expect(result.description).toBe("All Systems Operational");expect(result.timezone).toBe("UTC");- expect(global.fetch).toHaveBeenCalledWith(+ expect(fetchMock).toHaveBeenCalledWith("https://status.test.com/api/widget",expect.objectContaining({headers: expect.objectContaining({@@ -130,14 +136,14 @@ describe("IncidentioFetcher", () => {scheduled_maintenances: [],};- global.fetch = mock(() =>+ installMockFetch(() =>Promise.resolve({ok: true,json: async () => mockResponse,} as Response),);- const result = await fetcher.fetch(entry);+ const result = await runFetcher(fetcher, entry);expect(result.severity).toBe("major");expect(result.description).toBe("Incident: API Errors");@@ -169,14 +175,14 @@ describe("IncidentioFetcher", () => {scheduled_maintenances: [],};- global.fetch = mock(() =>+ installMockFetch(() =>Promise.resolve({ok: true,json: async () => mockResponse,} as Response),);- const result = await fetcher.fetch(entry);+ const result = await runFetcher(fetcher, entry);expect(result.severity).toBe("minor");expect(result.description).toBe("Monitoring: Database Slowness");@@ -208,14 +214,14 @@ describe("IncidentioFetcher", () => {scheduled_maintenances: [],};- global.fetch = mock(() =>+ installMockFetch(() =>Promise.resolve({ok: true,json: async () => mockResponse,} as Response),);- const result = await fetcher.fetch(entry);+ const result = await runFetcher(fetcher, entry);expect(result.severity).toBe("none");expect(result.description).toBe("Maintenance: Database Upgrade");@@ -247,14 +253,14 @@ describe("IncidentioFetcher", () => {],};- global.fetch = mock(() =>+ installMockFetch(() =>Promise.resolve({ok: true,json: async () => mockResponse,} as Response),);- const result = await fetcher.fetch(entry);+ const result = await runFetcher(fetcher, entry);expect(result.severity).toBe("none");expect(result.description).toBe(@@ -298,14 +304,14 @@ describe("IncidentioFetcher", () => {scheduled_maintenances: [],};- global.fetch = mock(() =>+ installMockFetch(() =>Promise.resolve({ok: true,json: async () => mockResponse,} as Response),);- const result = await fetcher.fetch(entry);+ const result = await runFetcher(fetcher, entry);expect(result.severity).toBe("major");expect(result.description).toBe("Incident: Critical Issue");@@ -331,22 +337,22 @@ describe("IncidentioFetcher", () => {scheduled_maintenances: [],};- global.fetch = mock(() =>+ const fetchMock = installMockFetch(() =>Promise.resolve({ok: true,json: async () => mockResponse,} as Response),);- await fetcher.fetch(entry);+ await runFetcher(fetcher, entry);- expect(global.fetch).toHaveBeenCalledWith(+ expect(fetchMock).toHaveBeenCalledWith("https://custom.endpoint.com/widget",expect.any(Object),);});- it("should throw error on non-200 response", async () => {+ it("should fail with FetchError on 5xx response", async () => {const entry: StatusPageEntry = {id: "test",name: "Test",@@ -356,7 +362,7 @@ describe("IncidentioFetcher", () => {industry: ["saas"],};- global.fetch = mock(() =>+ installMockFetch(() =>Promise.resolve({ok: false,status: 503,@@ -364,9 +370,9 @@ describe("IncidentioFetcher", () => {} as Response),);- await expect(fetcher.fetch(entry)).rejects.toThrow(- "HTTP 503: Service Unavailable",- );+ const exit = await runFetcherExit(fetcher, entry);+ const err = expectFetchError(exit);+ expect(err.httpStatus).toBe(503);});});});diff --git a/packages/status-fetcher/__tests__/fetchers/instatus.test.ts b/packages/status-fetcher/__tests__/fetchers/instatus.test.tsindex 89f69626b..65660c943 100644--- a/packages/status-fetcher/__tests__/fetchers/instatus.test.ts+++ b/packages/status-fetcher/__tests__/fetchers/instatus.test.ts@@ -1,6 +1,12 @@-import { beforeEach, describe, expect, it, mock } from "bun:test";+import { beforeEach, describe, expect, it } from "bun:test";import { InstatusFetcher } from "../../src/fetchers/instatus";import type { StatusPageEntry } from "../../src/types";+import {+ expectFetchError,+ installMockFetch,+ runFetcher,+ runFetcherExit,+} from "../helpers";describe("InstatusFetcher", () => {let fetcher: InstatusFetcher;@@ -89,20 +95,20 @@ describe("InstatusFetcher", () => {},};- global.fetch = mock(() =>+ const fetchMock = installMockFetch(() =>Promise.resolve({ok: true,json: async () => mockResponse,} as Response),);- const result = await fetcher.fetch(entry);+ const result = await runFetcher(fetcher, entry);expect(result.severity).toBe("none");expect(result.description).toBe("All Systems Operational");expect(result.timezone).toBe("UTC");expect(typeof result.updated_at).toBe("number");- expect(global.fetch).toHaveBeenCalledWith(+ expect(fetchMock).toHaveBeenCalledWith("https://test.instatus.com/summary.json",expect.objectContaining({headers: expect.objectContaining({@@ -136,14 +142,14 @@ describe("InstatusFetcher", () => {},};- global.fetch = mock(() =>+ installMockFetch(() =>Promise.resolve({ok: true,json: async () => mockResponse,} as Response),);- const result = await fetcher.fetch(entry);+ const result = await runFetcher(fetcher, entry);expect(result.severity).toBe("major");expect(result.description).toBe("Service Degraded");@@ -173,14 +179,14 @@ describe("InstatusFetcher", () => {},};- global.fetch = mock(() =>+ installMockFetch(() =>Promise.resolve({ok: true,json: async () => mockResponse,} as Response),);- const result = await fetcher.fetch(entry);+ const result = await runFetcher(fetcher, entry);expect(result.severity).toBe("none");expect(result.description).toBe("Under Maintenance");@@ -214,22 +220,22 @@ describe("InstatusFetcher", () => {},};- global.fetch = mock(() =>+ const fetchMock = installMockFetch(() =>Promise.resolve({ok: true,json: async () => mockResponse,} as Response),);- await fetcher.fetch(entry);+ await runFetcher(fetcher, entry);- expect(global.fetch).toHaveBeenCalledWith(+ expect(fetchMock).toHaveBeenCalledWith("https://custom.endpoint.com/status.json",expect.any(Object),);});- it("should throw error on non-200 response", async () => {+ it("should fail with FetchError on non-200 response (after retries)", async () => {const entry: StatusPageEntry = {id: "test",name: "Test",@@ -239,7 +245,7 @@ describe("InstatusFetcher", () => {industry: ["saas"],};- global.fetch = mock(() =>+ installMockFetch(() =>Promise.resolve({ok: false,status: 500,@@ -247,12 +253,12 @@ describe("InstatusFetcher", () => {} as Response),);- await expect(fetcher.fetch(entry)).rejects.toThrow(- "HTTP 500: Internal Server Error",- );+ const exit = await runFetcherExit(fetcher, entry);+ const err = expectFetchError(exit);+ expect(err.httpStatus).toBe(500);});- it("should throw error on invalid JSON schema", async () => {+ it("should fail with FetchError on invalid JSON schema", async () => {const entry: StatusPageEntry = {id: "test",name: "Test",@@ -262,14 +268,16 @@ describe("InstatusFetcher", () => {industry: ["saas"],};- global.fetch = mock(() =>+ installMockFetch(() =>Promise.resolve({ok: true,json: async () => ({ invalid: "data" }),} as Response),);- await expect(fetcher.fetch(entry)).rejects.toThrow();+ const exit = await runFetcherExit(fetcher, entry);+ const err = expectFetchError(exit);+ expect(err.cause).toBeInstanceOf(Error);});});});diff --git a/packages/status-fetcher/__tests__/fetchers/uptimerobot.test.ts b/packages/status-fetcher/__tests__/fetchers/uptimerobot.test.tsindex 7a0228998..cacfeff33 100644--- a/packages/status-fetcher/__tests__/fetchers/uptimerobot.test.ts+++ b/packages/status-fetcher/__tests__/fetchers/uptimerobot.test.ts@@ -1,9 +1,28 @@import { afterEach, beforeEach, describe, expect, it, mock } from "bun:test";import { UptimeRobotFetcher } from "../../src/fetchers/uptimerobot";import type { StatusPageEntry } from "../../src/types";+import {+ expectFetchError,+ installMockFetch,+ runFetcher,+ runFetcherExit,+} from "../helpers";const ENDPOINT = "https://status.example.com/api/getMonitorList/1234567-789012";+type MonitorFixture = {+ monitorId: number;+ name: string;+ statusClass: string;+ url: string | null;+ type: string;+ ratio: { ratio: string; label: string; color: string };+ "30dRatio": { ratio: string; label: string; color: string };+ "90dRatio": { ratio: string; label: string; color: string };+ hasIncidentComments: boolean;+ lastDowntime: null;+};+function makeEntry(overrides: Partial<StatusPageEntry> = {}): StatusPageEntry {return {id: "test",@@ -17,8 +36,8 @@ function makeEntry(overrides: Partial<StatusPageEntry> = {}): StatusPageEntry {};}-function mockResponse(monitors: Array<Record<string, unknown>>) {- global.fetch = mock(() =>+function mockResponseWith(monitors: MonitorFixture[]) {+ return installMockFetch(() =>Promise.resolve({ok: true,json: async () => ({ status: "ok", data: monitors }),@@ -30,7 +49,7 @@ let monitorIdCounter = 0;function monitor(statusClass: string,name = `monitor-${statusClass}`,-): Record<string, unknown> {+): MonitorFixture {monitorIdCounter++;return {monitorId: monitorIdCounter,@@ -105,20 +124,20 @@ describe("UptimeRobotFetcher", () => {describe("fetch", () => {it("aggregates all success β operational", async () => {- mockResponse([+ const fetchMock = mockResponseWith([monitor("success"),monitor("success"),monitor("success"),]);- const result = await fetcher.fetch(makeEntry());+ const result = await runFetcher(fetcher, makeEntry());expect(result.severity).toBe("none");expect(result.status).toBe("operational");expect(result.description).toBe("0 monitors down (3 total)");expect(result.timezone).toBe("UTC");expect(typeof result.updated_at).toBe("number");- expect(global.fetch).toHaveBeenCalledWith(+ expect(fetchMock).toHaveBeenCalledWith(ENDPOINT,expect.objectContaining({headers: expect.objectContaining({@@ -129,13 +148,13 @@ describe("UptimeRobotFetcher", () => {});it("aggregates one warning among success β degraded", async () => {- mockResponse([+ mockResponseWith([monitor("success"),monitor("warning"),monitor("success"),]);- const result = await fetcher.fetch(makeEntry());+ const result = await runFetcher(fetcher, makeEntry());expect(result.severity).toBe("minor");expect(result.status).toBe("degraded");@@ -143,23 +162,27 @@ describe("UptimeRobotFetcher", () => {});it("aggregates two warnings among success β degraded (plural)", async () => {- mockResponse([+ mockResponseWith([monitor("success"),monitor("warning"),monitor("warning"),monitor("success"),]);- const result = await fetcher.fetch(makeEntry());+ const result = await runFetcher(fetcher, makeEntry());expect(result.status).toBe("degraded");expect(result.description).toBe("2 monitors degraded (4 total)");});it("aggregates one danger among success β partial_outage", async () => {- mockResponse([monitor("success"), monitor("danger"), monitor("success")]);+ mockResponseWith([+ monitor("success"),+ monitor("danger"),+ monitor("success"),+ ]);- const result = await fetcher.fetch(makeEntry());+ const result = await runFetcher(fetcher, makeEntry());expect(result.severity).toBe("major");expect(result.status).toBe("partial_outage");@@ -167,14 +190,14 @@ describe("UptimeRobotFetcher", () => {});it("aggregates danger + warning mix β partial_outage with separated counts", async () => {- mockResponse([+ mockResponseWith([monitor("success"),monitor("danger"),monitor("warning"),monitor("success"),]);- const result = await fetcher.fetch(makeEntry());+ const result = await runFetcher(fetcher, makeEntry());expect(result.severity).toBe("major");expect(result.status).toBe("partial_outage");@@ -182,9 +205,13 @@ describe("UptimeRobotFetcher", () => {});it("aggregates all danger β major_outage", async () => {- mockResponse([monitor("danger"), monitor("danger"), monitor("danger")]);+ mockResponseWith([+ monitor("danger"),+ monitor("danger"),+ monitor("danger"),+ ]);- const result = await fetcher.fetch(makeEntry());+ const result = await runFetcher(fetcher, makeEntry());expect(result.severity).toBe("major");expect(result.status).toBe("major_outage");@@ -192,18 +219,22 @@ describe("UptimeRobotFetcher", () => {});it("single monitor all down β major_outage with singular wording", async () => {- mockResponse([monitor("danger")]);+ mockResponseWith([monitor("danger")]);- const result = await fetcher.fetch(makeEntry());+ const result = await runFetcher(fetcher, makeEntry());expect(result.status).toBe("major_outage");expect(result.description).toBe("1 monitor down (1 total)");});it("single paused alongside healthy stays operational", async () => {- mockResponse([monitor("success"), monitor("paused"), monitor("success")]);+ mockResponseWith([+ monitor("success"),+ monitor("paused"),+ monitor("success"),+ ]);- const result = await fetcher.fetch(makeEntry());+ const result = await runFetcher(fetcher, makeEntry());expect(result.severity).toBe("none");expect(result.status).toBe("operational");@@ -211,9 +242,9 @@ describe("UptimeRobotFetcher", () => {});it("all paused β under_maintenance", async () => {- mockResponse([monitor("paused"), monitor("paused")]);+ mockResponseWith([monitor("paused"), monitor("paused")]);- const result = await fetcher.fetch(makeEntry());+ const result = await runFetcher(fetcher, makeEntry());expect(result.severity).toBe("none");expect(result.status).toBe("under_maintenance");@@ -221,18 +252,18 @@ describe("UptimeRobotFetcher", () => {});it("info treated as maintenance", async () => {- mockResponse([monitor("info"), monitor("info")]);+ mockResponseWith([monitor("info"), monitor("info")]);- const result = await fetcher.fetch(makeEntry());+ const result = await runFetcher(fetcher, makeEntry());expect(result.severity).toBe("none");expect(result.status).toBe("under_maintenance");});it("empty data array β operational", async () => {- mockResponse([]);+ mockResponseWith([]);- const result = await fetcher.fetch(makeEntry());+ const result = await runFetcher(fetcher, makeEntry());expect(result.severity).toBe("none");expect(result.status).toBe("operational");@@ -244,14 +275,14 @@ describe("UptimeRobotFetcher", () => {const originalWarn = console.warn;console.warn = warnSpy;- mockResponse([+ mockResponseWith([monitor("success"),monitor("frobnicate"),monitor("success"),]);try {- const result = await fetcher.fetch(makeEntry());+ const result = await runFetcher(fetcher, makeEntry());expect(result.severity).toBe("none");expect(result.status).toBe("operational");@@ -261,18 +292,23 @@ describe("UptimeRobotFetcher", () => {}});- it("throws when api_config.endpoint is missing", async () => {+ it("fails with FetchError when api_config.endpoint is missing", async () => {const entry = makeEntry({api_config: { type: "uptimerobot" },});- await expect(fetcher.fetch(entry)).rejects.toThrow(+ const exit = await runFetcherExit(fetcher, entry);+ const err = expectFetchError(exit);+ if (!(err.cause instanceof Error)) {+ throw new Error("expected Error cause");+ }+ expect(err.cause.message).toContain("UptimeRobot fetcher requires api_config.endpoint",);});- it("throws on HTTP 500", async () => {- global.fetch = mock(() =>+ it("fails with FetchError on HTTP 500", async () => {+ installMockFetch(() =>Promise.resolve({ok: false,status: 500,@@ -280,31 +316,35 @@ describe("UptimeRobotFetcher", () => {} as Response),);- await expect(fetcher.fetch(makeEntry())).rejects.toThrow(- "HTTP 500: Internal Server Error",- );+ const exit = await runFetcherExit(fetcher, makeEntry());+ const err = expectFetchError(exit);+ expect(err.httpStatus).toBe(500);});- it("throws on malformed JSON (missing data array)", async () => {- global.fetch = mock(() =>+ it("fails with FetchError on malformed JSON (missing data array)", async () => {+ installMockFetch(() =>Promise.resolve({ok: true,json: async () => ({ status: "ok" }),} as Response),);- await expect(fetcher.fetch(makeEntry())).rejects.toThrow();+ const exit = await runFetcherExit(fetcher, makeEntry());+ const err = expectFetchError(exit);+ expect(err.cause).toBeInstanceOf(Error);});- it("throws on wrong status field", async () => {- global.fetch = mock(() =>+ it("fails with FetchError on wrong status field", async () => {+ installMockFetch(() =>Promise.resolve({ok: true,json: async () => ({ status: "error", data: [] }),} as Response),);- await expect(fetcher.fetch(makeEntry())).rejects.toThrow();+ const exit = await runFetcherExit(fetcher, makeEntry());+ const err = expectFetchError(exit);+ expect(err.cause).toBeInstanceOf(Error);});});});diff --git a/packages/status-fetcher/__tests__/helpers.ts b/packages/status-fetcher/__tests__/helpers.tsnew file mode 100644index 000000000..8b067767e--- /dev/null+++ b/packages/status-fetcher/__tests__/helpers.ts@@ -0,0 +1,39 @@+import { mock } from "bun:test";+import { Cause, Effect, Exit, Option } from "effect";+import type { FetchError } from "../src/fetch";+import type {+ StatusFetcher,+ StatusPageEntry,+ StatusResult,+} from "../src/types";++type FetchImpl = (url: string, init?: RequestInit) => Promise<Response>;++export const installMockFetch = (impl: FetchImpl) => {+ const fn = mock(impl);+ global.fetch = fn as unknown as typeof fetch;+ return fn;+};++export const runFetcher = (+ fetcher: StatusFetcher,+ entry: StatusPageEntry,+): Promise<StatusResult> => Effect.runPromise(fetcher.fetch(entry));++export const runFetcherExit = (+ fetcher: StatusFetcher,+ entry: StatusPageEntry,+) => Effect.runPromiseExit(fetcher.fetch(entry));++export const expectFetchError = (+ exit: Exit.Exit<StatusResult, FetchError>,+): FetchError => {+ if (!Exit.isFailure(exit)) {+ throw new Error("expected Exit.Failure, got Success");+ }+ const failure = Cause.failureOption(exit.cause);+ if (Option.isNone(failure)) {+ throw new Error("expected Cause.Fail, got defect");+ }+ return failure.value;+};diff --git a/packages/status-fetcher/__tests__/integration.test.ts b/packages/status-fetcher/__tests__/integration.test.tsindex fa02cfac0..dd2cb9db7 100644--- a/packages/status-fetcher/__tests__/integration.test.ts+++ b/packages/status-fetcher/__tests__/integration.test.ts@@ -1,6 +1,8 @@-import { describe, expect, it, mock } from "bun:test";+import { describe, expect, it } from "bun:test";+import { Effect } from "effect";import { fetchers as allFetchers } from "../src/fetchers";import type { StatusPageEntry, StatusPageProvider } from "../src/types";+import { installMockFetch } from "./helpers";describe("Integration Tests", () => {describe("Fetcher Selection", () => {@@ -14,7 +16,6 @@ describe("Integration Tests", () => {industry: ["saas"],};- // Use allFetchers imported aboveconst selectedFetcher = allFetchers.find((f) => f.canHandle(entry));expect(selectedFetcher?.name).toBe("atlassian");@@ -30,7 +31,6 @@ describe("Integration Tests", () => {industry: ["saas"],};- // Use allFetchers imported aboveconst selectedFetcher = allFetchers.find((f) => f.canHandle(entry));expect(selectedFetcher?.name).toBe("instatus");@@ -46,7 +46,6 @@ describe("Integration Tests", () => {industry: ["saas"],};- // Use allFetchers imported aboveconst selectedFetcher = allFetchers.find((f) => f.canHandle(entry));expect(selectedFetcher?.name).toBe("betterstack");@@ -62,7 +61,6 @@ describe("Integration Tests", () => {industry: ["saas"],};- // Use allFetchers imported aboveconst selectedFetcher = allFetchers.find((f) => f.canHandle(entry));expect(selectedFetcher?.name).toBe("incidentio");@@ -82,7 +80,6 @@ describe("Integration Tests", () => {},};- // Use allFetchers imported aboveconst selectedFetcher = allFetchers.find((f) => f.canHandle(entry));expect(selectedFetcher?.name).toBe("custom");@@ -99,7 +96,6 @@ describe("Integration Tests", () => {api_config: { type: "html-scraper" },};- // Use allFetchers imported aboveconst selectedFetcher = allFetchers.find((f) => f.canHandle(entry));expect(selectedFetcher?.name).toBe("html-scraper");@@ -110,13 +106,12 @@ describe("Integration Tests", () => {id: "test",name: "Test",url: "https://test.com",- status_page_url: "https://customstatus.com", // Generic URL+ status_page_url: "https://customstatus.com",provider: "unknown",industry: ["saas"],- api_config: { type: "html-scraper" }, // Explicit HTML scraper config+ api_config: { type: "html-scraper" },};- // Use allFetchers imported aboveconst selectedFetcher = allFetchers.find((f) => f.canHandle(entry));expect(selectedFetcher?.name).toBe("html-scraper");@@ -128,11 +123,10 @@ describe("Integration Tests", () => {name: "Test",url: "https://test.com",status_page_url: "https://customdomain.com",- provider: "instatus", // Explicitly set provider+ provider: "instatus",industry: ["saas"],};- // Use allFetchers imported aboveconst selectedFetcher = allFetchers.find((f) => f.canHandle(entry));expect(selectedFetcher?.name).toBe("instatus");@@ -151,10 +145,8 @@ describe("Integration Tests", () => {api_config: { type: "atlassian" },};- // Use allFetchers imported aboveconst matchingFetchers = allFetchers.filter((f) => f.canHandle(entry));- // Atlassian fetcher should match via provider, api_config, and URLexpect(matchingFetchers.length).toBeGreaterThanOrEqual(1);expect(matchingFetchers[0].name).toBe("atlassian");});@@ -171,11 +163,8 @@ describe("Integration Tests", () => {industry: ["saas"],};- // Use allFetchers imported aboveconst selectedFetcher = allFetchers.find((f) => f.canHandle(entry));- // Should find no matching fetcher (html-scraper would match if it has no restrictions)- // Actually, html-scraper only matches if api_config.type === "html-scraper"expect(selectedFetcher).toBeUndefined();});});@@ -191,7 +180,7 @@ describe("Integration Tests", () => {industry: ["saas"],};- global.fetch = mock(() =>+ installMockFetch(() =>Promise.resolve({ok: true,json: async () => ({@@ -210,21 +199,17 @@ describe("Integration Tests", () => {} as Response),);- // Use allFetchers imported aboveconst atlassianFetcher = allFetchers.find((f) => f.name === "atlassian");- const result = await atlassianFetcher?.fetch(atlassianEntry);+ if (!atlassianFetcher) throw new Error("atlassian fetcher missing");+ const result = await Effect.runPromise(+ atlassianFetcher.fetch(atlassianEntry),+ );- // Verify all required fields existexpect(result).toHaveProperty("severity");expect(result).toHaveProperty("status");expect(result).toHaveProperty("description");expect(result).toHaveProperty("updated_at");- if (!result) {- throw new Error("Result is undefined");- }-- // Verify typesexpect(typeof result.severity).toBe("string");expect(typeof result.status).toBe("string");expect(typeof result.description).toBe("string");@@ -251,15 +236,15 @@ describe("Integration Tests", () => {];for (const testCase of testCases) {- global.fetch = mock(() =>+ installMockFetch(() =>Promise.resolve({ok: true,json: async () => testCase.mockResponse,} as Response),);- // Use allFetchers imported aboveconst fetcher = allFetchers.find((f) => f.name === testCase.fetcher);+ if (!fetcher) throw new Error(`${testCase.fetcher} fetcher missing`);const entry: StatusPageEntry = {id: "test",@@ -270,11 +255,7 @@ describe("Integration Tests", () => {industry: ["saas"],};- const result = await fetcher?.fetch(entry);-- if (!result) {- throw new Error("Result is undefined");- }+ const result = await Effect.runPromise(fetcher.fetch(entry));expect(result.severity).toBe("none");expect(result.status).toBe("operational");@@ -282,7 +263,7 @@ describe("Integration Tests", () => {});it("should map degraded states to severity 'minor'", async () => {- global.fetch = mock(() =>+ installMockFetch(() =>Promise.resolve({ok: true,json: async () => ({@@ -300,8 +281,8 @@ describe("Integration Tests", () => {} as Response),);- // Use allFetchers imported aboveconst fetcher = allFetchers.find((f) => f.name === "betterstack");+ if (!fetcher) throw new Error("betterstack fetcher missing");const entry: StatusPageEntry = {id: "test",@@ -312,11 +293,7 @@ describe("Integration Tests", () => {industry: ["saas"],};- const result = await fetcher?.fetch(entry);-- if (!result) {- throw new Error("Result is undefined");- }+ const result = await Effect.runPromise(fetcher.fetch(entry));expect(result.severity).toBe("minor");expect(result.status).toBe("degraded");@@ -341,7 +318,7 @@ describe("Integration Tests", () => {};let fetchedUrl = "";- global.fetch = mock((url) => {+ installMockFetch((url) => {fetchedUrl = url;return Promise.resolve({ok: true,@@ -361,9 +338,9 @@ describe("Integration Tests", () => {} as Response);});- // Use allFetchers imported aboveconst fetcher = allFetchers.find((f) => f.name === "atlassian");- await fetcher?.fetch(entry);+ if (!fetcher) throw new Error("atlassian fetcher missing");+ await Effect.runPromise(fetcher.fetch(entry));expect(fetchedUrl).toBe(customEndpoint);});diff --git a/packages/status-fetcher/package.json b/packages/status-fetcher/package.jsonindex 6f1c49f90..12f3784d2 100644--- a/packages/status-fetcher/package.json+++ b/packages/status-fetcher/package.json@@ -16,6 +16,7 @@"tsc": "tsc --noEmit"},"dependencies": {+ "effect": "3.19.12","zod": "4.1.13","node-html-parser": "6.1.12"},diff --git a/packages/status-fetcher/scripts/test-fetchers.ts b/packages/status-fetcher/scripts/test-fetchers.tsindex 900f51584..9bb72ef9c 100644--- a/packages/status-fetcher/scripts/test-fetchers.ts+++ b/packages/status-fetcher/scripts/test-fetchers.ts@@ -1,3 +1,4 @@+import { Effect } from "effect";import { fetchers } from "../src/fetchers";import type { SeverityLevel, StatusPageEntry } from "../src/types";@@ -73,7 +74,7 @@ async function testFetchers() {try {const startTime = Date.now();- const status = await fetcher.fetch(entry);+ const status = await Effect.runPromise(fetcher.fetch(entry));const duration = Date.now() - startTime;const statusEmoji = getStatusEmoji(status.severity);diff --git a/packages/status-fetcher/src/fetch-utils.ts b/packages/status-fetcher/src/fetch-utils.tsdeleted file mode 100644index 27a69fe76..000000000--- a/packages/status-fetcher/src/fetch-utils.ts+++ /dev/null@@ -1,309 +0,0 @@-/**- * Fetch utilities with timeout and retry logic- *- * @module fetch-utils- * @description Provides robust HTTP fetching with timeout and automatic retry capabilities- */--/**- * Options for fetch operations with timeout support- * Extends standard RequestInit but excludes 'signal' since we manage it internally- */-export type FetchWithTimeoutOptions = Omit<RequestInit, "signal"> & {- /** Timeout in milliseconds (default: 30000ms / 30s) */- timeout?: number;-};--/**- * Options for retry behavior- */-export type RetryOptions = {- /** Maximum number of retry attempts (default: 3) */- maxRetries?: number;- /** Initial delay between retries in milliseconds (default: 100ms) */- initialDelay?: number;- /** Maximum delay cap in milliseconds (default: 5000ms) */- maxDelay?: number;- /**- * Custom function to determine if a request should be retried- * @param error - The error that occurred- * @param attempt - The current attempt number (0-indexed)- * @returns true to retry, false to stop- */- shouldRetry?: (error: Error, attempt: number) => boolean;-};--/**- * Fetch with timeout support using AbortController- *- * @param url - The URL to fetch- * @param options - Fetch options including timeout- * @returns Promise resolving to the Response- * @throws {Error} If request times out or fetch fails- *- * @example- * ```typescript- * const response = await fetchWithTimeout('https://api.example.com', {- * timeout: 5000,- * headers: { 'Authorization': 'Bearer token' }- * });- * ```- */-export async function fetchWithTimeout(- url: string,- options: FetchWithTimeoutOptions = {},-): Promise<Response> {- const { timeout = 30000, ...fetchOptions } = options;-- const controller = new AbortController();- const timeoutId = setTimeout(() => controller.abort(), timeout);-- try {- const response = await fetch(url, {- ...fetchOptions,- signal: controller.signal,- });- clearTimeout(timeoutId);- return response;- } catch (error) {- clearTimeout(timeoutId);- if (error instanceof Error && error.name === "AbortError") {- throw new Error(`Request timeout after ${timeout}ms: ${url}`);- }- throw error;- }-}--/**- * Fetch with automatic retry on transient failures- *- * Features:- * - Exponential backoff with jitter (Β±25%) to prevent thundering herd- * - Smart retry: only retries on network errors and 5xx server errors- * - No retry on 4xx client errors- * - Respects maxDelay cap to prevent excessively long waits- *- * @param url - The URL to fetch- * @param options - Combined fetch and retry options- * @returns Promise resolving to the Response- * @throws {Error} If all retry attempts fail- *- * @example- * ```typescript- * // Basic usage with defaults (3 retries, 30s timeout)- * const response = await fetchWithRetry('https://api.example.com');- *- * // Custom retry configuration- * const response = await fetchWithRetry('https://api.example.com', {- * maxRetries: 5,- * initialDelay: 200,- * timeout: 10000,- * shouldRetry: (error, attempt) => {- * // Custom retry logic- * return attempt < 3 && error.message.includes('ECONNRESET');- * }- * });- * ```- */-export async function fetchWithRetry(- url: string,- options: FetchWithTimeoutOptions & RetryOptions = {},-): Promise<Response> {- const {- maxRetries = 3,- initialDelay = 100,- maxDelay = 5000,- shouldRetry = defaultShouldRetry,- ...fetchOptions- } = options;-- let lastError: Error | undefined;- let delay = initialDelay;-- for (let attempt = 0; attempt <= maxRetries; attempt++) {- try {- const response = await fetchWithTimeout(url, fetchOptions);-- // Don't retry on successful responses or 4xx client errors- if (response.ok || (response.status >= 400 && response.status < 500)) {- return response;- }-- // 5xx server errors - retry- lastError = new Error(`HTTP ${response.status}: ${response.statusText}`);- } catch (error) {- lastError = error instanceof Error ? error : new Error(String(error));- }-- // Check if we should retry- if (attempt < maxRetries && shouldRetry(lastError, attempt)) {- // Add jitter (Β±25%) to prevent thundering herd- const jitter = delay * 0.25 * (Math.random() * 2 - 1);- await sleep(delay + jitter);- delay = Math.min(delay * 2, maxDelay); // Exponential backoff with cap- } else {- break;- }- }-- throw lastError || new Error("Unknown error during fetch with retry");-}--/**- * Default retry logic: retry on network errors and 5xx responses- *- * Retry conditions:- * - Network errors (fetch failed, network issues)- * - 5xx server errors (503 Service Unavailable, 500 Internal Server Error, etc.)- * - Timeout errors only on first attempt- *- * Does NOT retry:- * - 4xx client errors (400 Bad Request, 404 Not Found, etc.)- * - Timeout errors after first attempt (likely not transient)- *- * @param error - The error that occurred- * @param attempt - The current attempt number (0-indexed)- * @returns true if request should be retried- */-function defaultShouldRetry(error: Error, attempt: number): boolean {- // Don't retry on timeout errors after first attempt- if (error.message.includes("timeout") && attempt > 0) {- return false;- }-- // Retry on network errors- if (- error.message.includes("fetch failed") ||- error.message.includes("network")- ) {- return true;- }-- // Retry on 5xx errors- if (error.message.match(/HTTP 5\d{2}/)) {- return true;- }-- return false;-}--/**- * Sleep utility for retry delays- */-function sleep(ms: number): Promise<void> {- return new Promise((resolve) => setTimeout(resolve, ms));-}--/**- * In-flight request cache for deduplication- * Prevents multiple concurrent requests to the same URL- */-const inflightRequests = new Map<string, Promise<Response>>();--/**- * Fetch with request deduplication- *- * If multiple requests to the same URL are made concurrently, only one actual- * fetch is performed and all callers receive the same promise. This prevents- * thundering herd to the same endpoint.- *- * @param url - The URL to fetch- * @param options - Fetch options with timeout and retry- * @returns Promise resolving to the Response- *- * @example- * ```typescript- * // These three concurrent calls will result in only ONE actual fetch- * const [r1, r2, r3] = await Promise.all([- * fetchWithDeduplication('https://api.example.com'),- * fetchWithDeduplication('https://api.example.com'),- * fetchWithDeduplication('https://api.example.com'),- * ]);- * ```- */-export async function fetchWithDeduplication(- url: string,- options: FetchWithTimeoutOptions & RetryOptions = {},-): Promise<Response> {- // Create cache key from URL and relevant options- const cacheKey = `${url}:${JSON.stringify({- method: options.method || "GET",- headers: options.headers,- })}`;-- // Check if request is already in flight- const existing = inflightRequests.get(cacheKey);- if (existing) {- return existing;- }-- // Start new request and cache the promise- const promise = fetchWithRetry(url, options).finally(() => {- // Clean up when request completes- inflightRequests.delete(cacheKey);- });-- inflightRequests.set(cacheKey, promise);- return promise;-}--/**- * Custom error class for fetch operations with rich context- *- * Provides detailed information about fetch failures including:- * - The URL that was being fetched- * - Which fetcher was making the request- * - Which directory entry was being processed- * - The underlying cause (via standard Error.cause)- *- * @example- * ```typescript- * try {- * await fetcher.fetch(entry);- * } catch (error) {- * if (error instanceof FetchError) {- * console.error({- * message: error.message, // "HTTP 503: Service Unavailable"- * url: error.url, // "https://api.github.com/status"- * fetcher: error.fetcherName, // "atlassian"- * entry: error.entryId, // "github"- * cause: error.cause // Original error- * });- * }- * }- * ```- */-export class FetchError extends Error {- /**- * Creates a new FetchError- *- * @param message - Human-readable error message- * @param url - The URL that failed- * @param fetcherName - Name of the fetcher (e.g., "atlassian", "instatus")- * @param entryId - Directory entry ID (e.g., "github", "slack")- * @param cause - Original error that caused this failure- */- constructor(- message: string,- public readonly url: string,- public readonly fetcherName?: string,- public readonly entryId?: string,- cause?: Error,- ) {- super(message, { cause }); // Use standard Error.cause- this.name = "FetchError";- }-- /**- * Formats error with full context for logging- * @returns Formatted error string- */- toString(): string {- let msg = `[${this.name}]`;- if (this.fetcherName) msg += ` ${this.fetcherName}`;- if (this.entryId) msg += ` (${this.entryId})`;- msg += `: ${this.message}`;- if (this.cause) msg += ` - Caused by: ${(this.cause as Error).message}`;- return msg;- }-}diff --git a/packages/status-fetcher/src/fetch.ts b/packages/status-fetcher/src/fetch.tsnew file mode 100644index 000000000..c2f599dcc--- /dev/null+++ b/packages/status-fetcher/src/fetch.ts@@ -0,0 +1,147 @@+import { type Duration, Effect, Schedule } from "effect";+import type { z } from "zod";++type FetchErrorInit = {+ url: string;+ fetcherName?: string;+ entryId?: string;+ httpStatus?: number;+ cause?: Error;+};++export class FetchError extends Error {+ readonly url: string;+ readonly fetcherName?: string;+ readonly entryId?: string;+ readonly httpStatus?: number;++ constructor(init: FetchErrorInit) {+ const ctx =+ [init.fetcherName, init.entryId && `(${init.entryId})`]+ .filter(Boolean)+ .join(" ") || "FetchError";+ const status = init.httpStatus ? `HTTP ${init.httpStatus}` : "fetch failed";+ super(`[${ctx}] ${status}: ${init.url}`, { cause: init.cause });+ this.name = "FetchError";+ this.url = init.url;+ this.fetcherName = init.fetcherName;+ this.entryId = init.entryId;+ this.httpStatus = init.httpStatus;+ }+}++const DEFAULT_TIMEOUT: Duration.DurationInput = "30000 millis";++export type FetchBaseOptions = {+ url: string;+ init?: Omit<RequestInit, "signal" | "headers"> & {+ headers?: Record<string, string>;+ };+ timeout?: Duration.DurationInput;+ fetcherName?: string;+ entryId?: string;+};++const isRetryable = (err: FetchError): boolean =>+ !(+ err.httpStatus !== undefined &&+ err.httpStatus >= 400 &&+ err.httpStatus < 500+ );++const retryPolicy = {+ schedule: Schedule.exponential("100 millis").pipe(Schedule.jittered),+ times: 3,+ while: isRetryable,+};++const buildFetchError = (+ opts: FetchBaseOptions,+ extras: { httpStatus?: number; cause?: Error },+): FetchError =>+ new FetchError({+ url: opts.url,+ fetcherName: opts.fetcherName,+ entryId: opts.entryId,+ ...extras,+ });++const failWith =+ (opts: FetchBaseOptions) =>+ (cause: unknown): FetchError =>+ buildFetchError(opts, {+ cause: cause instanceof Error ? cause : new Error(String(cause)),+ });++const doFetch = (+ opts: FetchBaseOptions,+ defaultHeaders: Record<string, string>,+): Effect.Effect<Response, FetchError> =>+ Effect.tryPromise({+ try: (signal) =>+ fetch(opts.url, {+ ...opts.init,+ headers: { ...defaultHeaders, ...opts.init?.headers },+ signal,+ }),+ catch: failWith(opts),+ }).pipe(+ Effect.timeoutFail({+ duration: opts.timeout ?? DEFAULT_TIMEOUT,+ onTimeout: () =>+ buildFetchError(opts, {+ cause: new Error(+ `timeout after ${String(opts.timeout ?? DEFAULT_TIMEOUT)}`,+ ),+ }),+ }),+ Effect.flatMap((response) =>+ response.ok+ ? Effect.succeed(response)+ : Effect.fail(buildFetchError(opts, { httpStatus: response.status })),+ ),+ );++const fetchBody = <T>(+ opts: FetchBaseOptions,+ defaultHeaders: Record<string, string>,+ read: (response: Response) => Effect.Effect<T, FetchError>,+): Effect.Effect<T, FetchError> =>+ doFetch(opts, defaultHeaders).pipe(+ Effect.retry(retryPolicy),+ Effect.flatMap(read),+ );++const JSON_HEADERS = {+ "User-Agent": "OpenStatus-Directory/1.0",+ Accept: "application/json",+};++// browser-like UA: some status pages reject non-browser User-Agents+const TEXT_HEADERS = {+ "User-Agent": "Mozilla/5.0 (compatible; OpenStatus-Bot/1.0)",+};++export const fetchJson = <T>(+ opts: FetchBaseOptions & { schema: z.ZodType<T> },+): Effect.Effect<T, FetchError> =>+ fetchBody(opts, JSON_HEADERS, (response) =>+ Effect.tryPromise({+ try: () => response.json(),+ catch: failWith(opts),+ }).pipe(+ Effect.flatMap((json) =>+ Effect.try({+ try: () => opts.schema.parse(json),+ catch: failWith(opts),+ }),+ ),+ ),+ );++export const fetchText = (+ opts: FetchBaseOptions,+): Effect.Effect<string, FetchError> =>+ fetchBody(opts, TEXT_HEADERS, (response) =>+ Effect.tryPromise({ try: () => response.text(), catch: failWith(opts) }),+ );diff --git a/packages/status-fetcher/src/fetchers/atlassian.ts b/packages/status-fetcher/src/fetchers/atlassian.tsindex 05ef18a9b..b01879df5 100644--- a/packages/status-fetcher/src/fetchers/atlassian.ts+++ b/packages/status-fetcher/src/fetchers/atlassian.ts@@ -1,11 +1,10 @@+import { Effect } from "effect";import { z } from "zod";-import { FetchError, fetchWithRetry } from "../fetch-utils";+import { type FetchError, fetchJson } from "../fetch";import type { StatusFetcher, StatusPageEntry, StatusResult } from "../types";import { SEVERITY_LEVELS } from "../types";import { inferStatus, urlHostnameEndsWith } from "../utils";-// DOCS: https://status.atlassian.com/api-const atlassianResponseSchema = z.object({page: z.object({id: z.string(),@@ -31,54 +30,28 @@ export class AtlassianFetcher implements StatusFetcher {);}- async fetch(entry: StatusPageEntry): Promise<StatusResult> {- // Construct API URL- // Format: https://[id].statuspage.io/api/v2/summary.json+ fetch(entry: StatusPageEntry): Effect.Effect<StatusResult, FetchError> {const apiUrl =entry.api_config?.endpoint ||`${entry.status_page_url}/api/v2/summary.json`;- try {- const response = await fetchWithRetry(apiUrl, {- headers: {- "User-Agent": "OpenStatus-Directory/1.0",- },- timeout: 30000,- });-- if (!response.ok) {- throw new FetchError(- `HTTP ${response.status}: ${response.statusText}`,- apiUrl,- this.name,- entry.id,- );- }-- const json = await response.json();- const data = atlassianResponseSchema.parse(json);-- const severity = data.status.indicator;- const description = data.status.description;-- return {- severity,- status: inferStatus(description, severity),- description,- updated_at: new Date(data.page.updated_at).getTime(),- timezone: data.page.timezone,- };- } catch (error) {- if (error instanceof FetchError) {- throw error;- }- throw new FetchError(- error instanceof Error ? error.message : "Unknown error",- apiUrl,- this.name,- entry.id,- error instanceof Error ? error : undefined,- );- }+ return fetchJson({+ url: apiUrl,+ schema: atlassianResponseSchema,+ fetcherName: this.name,+ entryId: entry.id,+ }).pipe(+ Effect.map((data) => {+ const severity = data.status.indicator;+ const description = data.status.description;+ return {+ severity,+ status: inferStatus(description, severity),+ description,+ updated_at: new Date(data.page.updated_at).getTime(),+ timezone: data.page.timezone,+ };+ }),+ );}}diff --git a/packages/status-fetcher/src/fetchers/betterstack.ts b/packages/status-fetcher/src/fetchers/betterstack.tsindex e945bf536..bb2742716 100644--- a/packages/status-fetcher/src/fetchers/betterstack.ts+++ b/packages/status-fetcher/src/fetchers/betterstack.ts@@ -1,10 +1,9 @@+import { Effect } from "effect";import { z } from "zod";-import { FetchError, fetchWithRetry } from "../fetch-utils";+import { type FetchError, fetchJson } from "../fetch";import type { StatusFetcher, StatusPageEntry, StatusResult } from "../types";import { urlHostnameEndsWith } from "../utils";-// DOCS: https://betterstack.com/docs/uptime/status-pages/subscribing-to-status-updates/subscribing-to-api/#access-the-json-endpoint-const betterStackResponseSchema = z.object({data: z.object({id: z.string(),@@ -36,54 +35,29 @@ export class BetterStackFetcher implements StatusFetcher {);}- async fetch(entry: StatusPageEntry): Promise<StatusResult> {+ fetch(entry: StatusPageEntry): Effect.Effect<StatusResult, FetchError> {const apiUrl =entry.api_config?.endpoint || `${entry.status_page_url}/index.json`;- try {- const response = await fetchWithRetry(apiUrl, {- headers: {- "User-Agent": "OpenStatus-Directory/1.0",- Accept: "application/json",- },- timeout: 30000,- });-- if (!response.ok) {- throw new FetchError(- `HTTP ${response.status}: ${response.statusText}`,- apiUrl,- this.name,- entry.id,- );- }-- const json = await response.json();- const data = betterStackResponseSchema.parse(json);-- const { aggregate_state, updated_at, timezone } = data.data.attributes;- const { severity, status, description } =- this.mapAggregateState(aggregate_state);-- return {- severity,- status,- description,- updated_at: new Date(updated_at).getTime(),- timezone: timezone,- };- } catch (error) {- if (error instanceof FetchError) {- throw error;- }- throw new FetchError(- error instanceof Error ? error.message : "Unknown error",- apiUrl,- this.name,- entry.id,- error instanceof Error ? error : undefined,- );- }+ return fetchJson({+ url: apiUrl,+ schema: betterStackResponseSchema,+ fetcherName: this.name,+ entryId: entry.id,+ }).pipe(+ Effect.map((data) => {+ const { aggregate_state, updated_at, timezone } = data.data.attributes;+ const { severity, status, description } =+ this.mapAggregateState(aggregate_state);+ return {+ severity,+ status,+ description,+ updated_at: new Date(updated_at).getTime(),+ timezone,+ };+ }),+ );}private mapAggregateState(diff --git a/packages/status-fetcher/src/fetchers/custom.ts b/packages/status-fetcher/src/fetchers/custom.tsindex 4869ca6e5..9405cae64 100644--- a/packages/status-fetcher/src/fetchers/custom.ts+++ b/packages/status-fetcher/src/fetchers/custom.ts@@ -1,8 +1,38 @@+import { Effect } from "effect";import { z } from "zod";-import { FetchError, fetchWithRetry } from "../fetch-utils";+import { FetchError, fetchJson } from "../fetch";import type { StatusFetcher, StatusPageEntry, StatusResult } from "../types";import { inferStatus } from "../utils";+const slackSchema = z.object({+ status: z.enum(["ok", "active", "resolved"]),+ date_created: z.union([z.number(), z.string()]),+ date_updated: z.union([z.number(), z.string()]),+ active_incidents: z.array(+ z.object({+ id: z.number(),+ title: z.string(),+ type: z.enum(["incident", "notice", "outage"]),+ status: z.string(),+ services: z.array(z.string()),+ }),+ ),+});++const genericShape = z.object({+ status: z.string().optional(),+ state: z.string().optional(),+ health: z.string().optional(),+ description: z.string().optional(),+ message: z.string().optional(),+});++type SlackData = z.infer<typeof slackSchema>;+type GenericData = z.infer<typeof genericShape>;++const toError = (cause: unknown): Error =>+ cause instanceof Error ? cause : new Error(String(cause));+export class CustomApiFetcher implements StatusFetcher {name = "custom";@@ -10,86 +40,54 @@ export class CustomApiFetcher implements StatusFetcher {return entry.api_config?.type === "custom";}- async fetch(entry: StatusPageEntry): Promise<StatusResult> {- if (!entry.api_config?.endpoint) {- throw new FetchError(- "Custom API requires explicit endpoint configuration",- "",- this.name,- entry.id,+ fetch(entry: StatusPageEntry): Effect.Effect<StatusResult, FetchError> {+ const apiUrl = entry.api_config?.endpoint;+ if (!apiUrl) {+ return Effect.fail(+ new FetchError({+ url: entry.status_page_url,+ fetcherName: this.name,+ entryId: entry.id,+ cause: new Error(+ "Custom API requires explicit endpoint configuration",+ ),+ }),);}- const apiUrl = entry.api_config.endpoint;-- try {- const response = await fetchWithRetry(apiUrl, {- headers: {- "User-Agent": "OpenStatus-Directory/1.0",- Accept: "application/json",- },- timeout: 30000,- });-- if (!response.ok) {- throw new FetchError(- `HTTP ${response.status}: ${response.statusText}`,- apiUrl,- this.name,- entry.id,- );- }-- const json = await response.json();- const parser = entry.api_config.parser || "generic";- return this.parseResponse(json, parser);- } catch (error) {- if (error instanceof FetchError) {- throw error;- }- throw new FetchError(- error instanceof Error ? error.message : "Unknown error",- apiUrl,- this.name,- entry.id,- error instanceof Error ? error : undefined,- );- }- }+ const parser = entry.api_config?.parser || "generic";+ const errorCtx = { url: apiUrl, fetcherName: this.name, entryId: entry.id };- private parseResponse(json: unknown, parser: string): StatusResult {switch (parser) {case "slack":- return this.parseSlack(json);+ return fetchJson({+ ...errorCtx,+ schema: slackSchema,+ }).pipe(Effect.map((data) => this.parseSlack(data)));case "aws":- return this.parseAws(json);+ return Effect.fail(+ new FetchError({+ ...errorCtx,+ cause: new Error("AWS parser not implemented - uses RSS feeds"),+ }),+ );default:- return this.parseGeneric(json);+ return fetchJson({+ ...errorCtx,+ schema: genericShape,+ }).pipe(+ Effect.flatMap((data) =>+ Effect.try({+ try: () => this.parseGeneric(data),+ catch: (cause) =>+ new FetchError({ ...errorCtx, cause: toError(cause) }),+ }),+ ),+ );}}- /**- * Slack Status API v2.0.0 parser- * API: https://slack-status.com/api/v2.0.0/current- * Docs: https://docs.slack.dev/reference/slack-status-api/- */- private parseSlack(json: unknown): StatusResult {- const schema = z.object({- status: z.enum(["ok", "active", "resolved"]),- date_created: z.union([z.number(), z.string()]),- date_updated: z.union([z.number(), z.string()]),- active_incidents: z.array(- z.object({- id: z.number(),- title: z.string(),- type: z.enum(["incident", "notice", "outage"]),- status: z.string(),- services: z.array(z.string()),- }),- ),- });-- const data = schema.parse(json);+ private parseSlack(data: SlackData): StatusResult {const hasActiveIncidents = data.active_incidents.length > 0;const hasOutage = data.active_incidents.some((i) => i.type === "outage");@@ -111,7 +109,6 @@ export class CustomApiFetcher implements StatusFetcher {description = data.active_incidents[0].title;}- // Handle both number (seconds) and string (ISO) timestampsconst dateUpdated =typeof data.date_updated === "number"? data.date_updated * 1000@@ -126,28 +123,11 @@ export class CustomApiFetcher implements StatusFetcher {};}- /**- * AWS Health Dashboard parser (placeholder)- */- private parseAws(_json: unknown): StatusResult {- throw new Error("AWS parser not implemented - uses RSS feeds");- }-- /**- * Generic parser for unknown custom APIs- */- private parseGeneric(json: unknown): StatusResult {- const jsonObject = json as {- status?: string;- state?: string;- health?: string;- description?: string;- message?: string;- };+ private parseGeneric(parsed: GenericData): StatusResult {const statusField =- jsonObject.status || jsonObject.state || jsonObject.health || "unknown";+ parsed.status || parsed.state || parsed.health || "unknown";const descriptionField =- jsonObject.description || jsonObject.message || String(statusField);+ parsed.description || parsed.message || String(statusField);const statusLower = String(statusField).toLowerCase();let severity: "none" | "minor" | "major" = "none";diff --git a/packages/status-fetcher/src/fetchers/html.ts b/packages/status-fetcher/src/fetchers/html.tsindex 6f0db6e0f..c922ffcde 100644--- a/packages/status-fetcher/src/fetchers/html.ts+++ b/packages/status-fetcher/src/fetchers/html.ts@@ -1,5 +1,6 @@+import { Effect } from "effect";import { parse } from "node-html-parser";-import { FetchError, fetchWithRetry } from "../fetch-utils";+import { type FetchError, fetchText } from "../fetch";import type { StatusFetcher, StatusPageEntry, StatusResult } from "../types";import { inferStatus } from "../utils";@@ -7,77 +8,52 @@ export class HtmlScraperFetcher implements StatusFetcher {name = "html-scraper";canHandle(entry: StatusPageEntry): boolean {- // Fallback fetcher - only use if explicitly enabledreturn entry.api_config?.type === "html-scraper";}- async fetch(entry: StatusPageEntry): Promise<StatusResult> {- const apiUrl = entry.status_page_url;+ fetch(entry: StatusPageEntry): Effect.Effect<StatusResult, FetchError> {+ return fetchText({+ url: entry.status_page_url,+ fetcherName: this.name,+ entryId: entry.id,+ }).pipe(+ Effect.map((html) => {+ const root = parse(html);- try {- const response = await fetchWithRetry(apiUrl, {- headers: {- "User-Agent": "Mozilla/5.0 (compatible; OpenStatus-Bot/1.0)",- },- timeout: 30000,- });+ const patterns = [+ { selector: '[class*="status"]', attr: "textContent" },+ { selector: "[data-status]", attr: "data-status" },+ { selector: 'meta[name="status"]', attr: "content" },+ ];- if (!response.ok) {- throw new FetchError(- `HTTP ${response.status}: ${response.statusText}`,- apiUrl,- this.name,- entry.id,- );- }+ let description = "Unknown";+ let severity: "none" | "minor" | "major" = "none";- const html = await response.text();- const root = parse(html);+ for (const pattern of patterns) {+ const element = root.querySelector(pattern.selector);+ if (element) {+ const text =+ pattern.attr === "textContent"+ ? element.textContent+ : element.getAttribute(pattern.attr);- const patterns = [- { selector: '[class*="status"]', attr: "textContent" },- { selector: "[data-status]", attr: "data-status" },- { selector: 'meta[name="status"]', attr: "content" },- ];-- let description = "Unknown";- let severity: "none" | "minor" | "major" = "none";-- for (const pattern of patterns) {- const element = root.querySelector(pattern.selector);- if (element) {- const text =- pattern.attr === "textContent"- ? element.textContent- : element.getAttribute(pattern.attr);-- if (text) {- description = text.trim();- severity = this.inferSeverity(description);- break;+ if (text) {+ description = text.trim();+ severity = this.inferSeverity(description);+ break;+ }}}- }- return {- severity,- status: inferStatus(description, severity),- description,- updated_at: Date.now(),- timezone: "UTC",- };- } catch (error) {- if (error instanceof FetchError) {- throw error;- }- throw new FetchError(- error instanceof Error ? error.message : "Unknown error",- apiUrl,- this.name,- entry.id,- error instanceof Error ? error : undefined,- );- }+ return {+ severity,+ status: inferStatus(description, severity),+ description,+ updated_at: Date.now(),+ timezone: "UTC",+ };+ }),+ );}private inferSeverity(text: string): "none" | "minor" | "major" {diff --git a/packages/status-fetcher/src/fetchers/incidentio.ts b/packages/status-fetcher/src/fetchers/incidentio.tsindex 21dda1ccd..40336ef9a 100644--- a/packages/status-fetcher/src/fetchers/incidentio.ts+++ b/packages/status-fetcher/src/fetchers/incidentio.ts@@ -1,11 +1,9 @@+import { Effect } from "effect";import { z } from "zod";-import { FetchError, fetchWithRetry } from "../fetch-utils";+import { type FetchError, fetchJson } from "../fetch";import type { StatusFetcher, StatusPageEntry, StatusResult } from "../types";import { urlHostnameEndsWith } from "../utils";-// DOCS: https://help.incident.io/articles/7434055319-embed-your-status-page%27s-data-into-your-own-product-// NOTE: this only works if Widget API is enabled-const incidentSchema = z.object({id: z.string(),name: z.string(),@@ -25,6 +23,8 @@ const incidentioResponseSchema = z.object({scheduled_maintenances: z.array(incidentSchema),});+type IncidentioData = z.infer<typeof incidentioResponseSchema>;+export class IncidentioFetcher implements StatusFetcher {name = "incidentio";@@ -37,52 +37,26 @@ export class IncidentioFetcher implements StatusFetcher {);}- async fetch(entry: StatusPageEntry): Promise<StatusResult> {+ fetch(entry: StatusPageEntry): Effect.Effect<StatusResult, FetchError> {const apiUrl = entry.api_config?.endpoint || this.constructApiUrl(entry);- try {- const response = await fetchWithRetry(apiUrl, {- headers: {- "User-Agent": "OpenStatus-Directory/1.0",- Accept: "application/json",- },- timeout: 30000,- });-- if (!response.ok) {- throw new FetchError(- `HTTP ${response.status}: ${response.statusText}`,- apiUrl,- this.name,- entry.id,- );- }-- const json = await response.json();- const data = incidentioResponseSchema.parse(json);-- const { severity, status, description } = this.analyzeIncidents(data);- const latestUpdate = this.getLatestUpdateTime(data);-- return {- severity,- status,- description,- updated_at: latestUpdate,- timezone: "UTC",- };- } catch (error) {- if (error instanceof FetchError) {- throw error;- }- throw new FetchError(- error instanceof Error ? error.message : "Unknown error",- apiUrl,- this.name,- entry.id,- error instanceof Error ? error : undefined,- );- }+ return fetchJson({+ url: apiUrl,+ schema: incidentioResponseSchema,+ fetcherName: this.name,+ entryId: entry.id,+ }).pipe(+ Effect.map((data) => {+ const { severity, status, description } = this.analyzeIncidents(data);+ return {+ severity,+ status,+ description,+ updated_at: this.getLatestUpdateTime(data),+ timezone: "UTC",+ };+ }),+ );}private constructApiUrl(entry: StatusPageEntry): string {@@ -90,7 +64,7 @@ export class IncidentioFetcher implements StatusFetcher {return `${url.origin}/api/widget`;}- private analyzeIncidents(data: z.infer<typeof incidentioResponseSchema>): {+ private analyzeIncidents(data: IncidentioData): {severity: "none" | "minor" | "major";status:| "operational"@@ -164,20 +138,20 @@ export class IncidentioFetcher implements StatusFetcher {};}- private getLatestUpdateTime(- data: z.infer<typeof incidentioResponseSchema>,- ): number {+ private getLatestUpdateTime(data: IncidentioData): number {const allItems = [...data.ongoing_incidents,...data.in_progress_maintenances,...data.scheduled_maintenances,];- if (allItems.length === 0) return Date.now();-- const timestamps = allItems- .filter((item) => item.last_update?.updated_at)- .map((item) => new Date(item.last_update?.updated_at).getTime());+ const timestamps: number[] = [];+ for (const item of allItems) {+ const updatedAt = item.last_update?.updated_at;+ if (updatedAt) {+ timestamps.push(new Date(updatedAt).getTime());+ }+ }return timestamps.length > 0 ? Math.max(...timestamps) : Date.now();}diff --git a/packages/status-fetcher/src/fetchers/instatus.ts b/packages/status-fetcher/src/fetchers/instatus.tsindex ddcac37e9..ec0990ba1 100644--- a/packages/status-fetcher/src/fetchers/instatus.ts+++ b/packages/status-fetcher/src/fetchers/instatus.ts@@ -1,10 +1,9 @@+import { Effect } from "effect";import { z } from "zod";-import { FetchError, fetchWithRetry } from "../fetch-utils";+import { type FetchError, fetchJson } from "../fetch";import type { StatusFetcher, StatusPageEntry, StatusResult } from "../types";import { urlHostnameEndsWith } from "../utils";-// DOCS: https://instatus.com/help/status-page/widgets-const instatusResponseSchema = z.object({activeIncidents: z.array(z.unknown()),activeMaintenances: z.array(z.unknown()),@@ -30,49 +29,27 @@ export class InstatusFetcher implements StatusFetcher {);}- async fetch(entry: StatusPageEntry): Promise<StatusResult> {+ fetch(entry: StatusPageEntry): Effect.Effect<StatusResult, FetchError> {const apiUrl =entry.api_config?.endpoint || `${entry.status_page_url}/summary.json`;- try {- const response = await fetchWithRetry(apiUrl, {- headers: { "User-Agent": "OpenStatus-Directory/1.0" },- timeout: 30000,- });-- if (!response.ok) {- throw new FetchError(- `HTTP ${response.status}: ${response.statusText}`,- apiUrl,- this.name,- entry.id,- );- }-- const json = await response.json();- const data = instatusResponseSchema.parse(json);-- const mapping = this.mapInstatusType(data.status.type);-- return {- severity: mapping.severity,- status: mapping.status,- description: data.status.text,- updated_at: new Date(data.page.updated).getTime(),- timezone: "UTC",- };- } catch (error) {- if (error instanceof FetchError) {- throw error;- }- throw new FetchError(- error instanceof Error ? error.message : "Unknown error",- apiUrl,- this.name,- entry.id,- error instanceof Error ? error : undefined,- );- }+ return fetchJson({+ url: apiUrl,+ schema: instatusResponseSchema,+ fetcherName: this.name,+ entryId: entry.id,+ }).pipe(+ Effect.map((data) => {+ const mapping = this.mapInstatusType(data.status.type);+ return {+ severity: mapping.severity,+ status: mapping.status,+ description: data.status.text,+ updated_at: new Date(data.page.updated).getTime(),+ timezone: "UTC",+ };+ }),+ );}private mapInstatusType(type: "UP" | "HASISSUES" | "UNDERMAINTENANCE"): {diff --git a/packages/status-fetcher/src/fetchers/uptimerobot.ts b/packages/status-fetcher/src/fetchers/uptimerobot.tsindex 0c5780607..988428445 100644--- a/packages/status-fetcher/src/fetchers/uptimerobot.ts+++ b/packages/status-fetcher/src/fetchers/uptimerobot.ts@@ -1,5 +1,6 @@+import { Effect } from "effect";import { z } from "zod";-import { FetchError, fetchWithRetry } from "../fetch-utils";+import { FetchError, fetchJson } from "../fetch";import type {SeverityLevel,StatusFetcher,@@ -8,10 +9,6 @@ import type {StatusType,} from "../types";-// UptimeRobot public status pages: no official docs.-// Endpoint observed in the wild: `<status_page_url>/api/getMonitorList/<userId>-<pspId>`.-// The page-id is unguessable, so operators must set it via api_config.endpoint.-const monitorRatioSchema = z.object({ratio: z.string(),label: z.string(),@@ -43,6 +40,8 @@ const uptimeRobotResponseSchema = z.object({data: z.array(monitorSchema),});+type Monitor = z.infer<typeof monitorSchema>;+export class UptimeRobotFetcher implements StatusFetcher {name = "uptimerobot";@@ -53,59 +52,41 @@ export class UptimeRobotFetcher implements StatusFetcher {);}- async fetch(entry: StatusPageEntry): Promise<StatusResult> {+ fetch(entry: StatusPageEntry): Effect.Effect<StatusResult, FetchError> {const apiUrl = entry.api_config?.endpoint;if (!apiUrl) {- throw new FetchError(- "UptimeRobot fetcher requires api_config.endpoint pointing at /api/getMonitorList/<userId>-<pspId>",- entry.status_page_url,- this.name,- entry.id,+ return Effect.fail(+ new FetchError({+ url: entry.status_page_url,+ fetcherName: this.name,+ entryId: entry.id,+ cause: new Error(+ "UptimeRobot fetcher requires api_config.endpoint pointing at /api/getMonitorList/<userId>-<pspId>",+ ),+ }),);}- try {- const response = await fetchWithRetry(apiUrl, {- headers: { "User-Agent": "OpenStatus-Directory/1.0" },- timeout: 30000,- });-- if (!response.ok) {- throw new FetchError(- `HTTP ${response.status}: ${response.statusText}`,- apiUrl,- this.name,- entry.id,- );- }-- const json = await response.json();- const data = uptimeRobotResponseSchema.parse(json);-- const { severity, status, description } = this.aggregate(data.data);-- return {- severity,- status,- description,- updated_at: Date.now(),- timezone: "UTC",- };- } catch (error) {- if (error instanceof FetchError) {- throw error;- }- throw new FetchError(- error instanceof Error ? error.message : "Unknown error",- apiUrl,- this.name,- entry.id,- error instanceof Error ? error : undefined,- );- }+ return fetchJson({+ url: apiUrl,+ schema: uptimeRobotResponseSchema,+ fetcherName: this.name,+ entryId: entry.id,+ }).pipe(+ Effect.map((data) => {+ const { severity, status, description } = this.aggregate(data.data);+ return {+ severity,+ status,+ description,+ updated_at: Date.now(),+ timezone: "UTC",+ };+ }),+ );}- private aggregate(monitors: z.infer<typeof monitorSchema>[]): {+ private aggregate(monitors: Monitor[]): {severity: SeverityLevel;status: StatusType;description: string;diff --git a/packages/status-fetcher/src/index.ts b/packages/status-fetcher/src/index.tsindex e73f50150..e21e68199 100644--- a/packages/status-fetcher/src/index.ts+++ b/packages/status-fetcher/src/index.ts@@ -1,12 +1,5 @@export * from "./types";export * from "./utils";-export {- fetchWithTimeout,- fetchWithRetry,- fetchWithDeduplication,- FetchError,- type FetchWithTimeoutOptions,- type RetryOptions,-} from "./fetch-utils";+export { FetchError } from "./fetch";export { fetchers } from "./fetchers";export type { DirectoryEntry } from "./data/index";diff --git a/packages/status-fetcher/src/types.ts b/packages/status-fetcher/src/types.tsindex f95283311..afdf0f85a 100644--- a/packages/status-fetcher/src/types.ts+++ b/packages/status-fetcher/src/types.ts@@ -1,4 +1,6 @@+import type { Effect } from "effect";import { z } from "zod";+import type { FetchError } from "./fetch";// Define arrays as source of truthexport const API_CONFIG_TYPES = [@@ -108,5 +110,5 @@ export interface StatusResult {export interface StatusFetcher {name: string;canHandle(entry: StatusPageEntry): boolean;- fetch(entry: StatusPageEntry): Promise<StatusResult>;+ fetch(entry: StatusPageEntry): Effect.Effect<StatusResult, FetchError>;}diff --git a/packages/status-fetcher/tsconfig.json b/packages/status-fetcher/tsconfig.jsonindex 0e12c2cb2..9d6eaf3f5 100644--- a/packages/status-fetcher/tsconfig.json+++ b/packages/status-fetcher/tsconfig.json@@ -11,7 +11,7 @@"esModuleInterop": true,"resolveJsonModule": true,"isolatedModules": true,- "types": ["bun-types"]+ "types": ["bun"]},"include": ["src/**/*", "__tests__/**/*"]}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex bcd3c727d..f8e30c167 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -907,9 +907,6 @@ importers:'@openstatus/services':specifier: workspace:*version: link:../../packages/services- '@openstatus/status-fetcher':- specifier: workspace:*- version: link:../../packages/status-fetcher'@openstatus/theme-store':specifier: workspace:*version: link:../../packages/theme-store@@ -2136,6 +2133,9 @@ importers:packages/status-fetcher:dependencies:+ effect:+ specifier: 3.19.12+ version: 3.19.12node-html-parser:specifier: 6.1.12version: 6.1.12@@ -4052,14 +4052,6 @@ packages:'@types/node':optional: true- '@isaacs/[email protected]':- resolution: {integrity: sha512-yzMTt9lEb8Gv7zRioUilSglI0c0smZ9k5D65677DLWLtWJaXIS3CqcGyUFByYKlnUj6TkjLVs54fBl6+TiGQDQ==}- engines: {node: 20 || >=22}-- '@isaacs/[email protected]':- resolution: {integrity: sha512-ZT55BDLV0yv0RBm2czMiZ+SqCGO7AvmOM3G/w2xhVPH+te0aKgFjmBvGlL1dH+ql2tgGO3MVrbb3jCKyvpgnxA==}- engines: {node: 20 || >=22}-'@isaacs/[email protected]':resolution: {integrity: sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==}engines: {node: '>=12'}@@ -4177,16 +4169,6 @@ packages:'@types/react': '>=16'react: '>=16'- '@modelcontextprotocol/[email protected]':- resolution: {integrity: sha512-Y5RmPncpiDtTXDbLKswIJzTqu2hyBKxTNsgKqKclDbhIgg1wgtf1fRuvxgTnRfcnxtvvgbIEcqUOzZrJ6iSReg==}- engines: {node: '>=18'}- peerDependencies:- '@cfworker/json-schema': ^4.1.1- zod: ^3.25 || ^4.0- peerDependenciesMeta:- '@cfworker/json-schema':- optional: true-'@modelcontextprotocol/[email protected]':resolution: {integrity: sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ==}engines: {node: '>=18'}@@ -8013,10 +7995,6 @@ packages:engines: {node: '>=6.0.0'}hasBin: true- resolution: {integrity: sha512-V8fbOCSeOFvlDj7LLChUcqbZrdKD9RU/VR260piF1790vT0mfLSwGc/Qzxv3IqiTukOpNtItePa0HBpMAj7MDg==}- hasBin: true-resolution: {integrity: sha512-4Bcg1P8xhUuqcii/S0Z9wiHIrQVPMermM1any+MX5GeGD7faD3/msQUDGLol9wOcz4/jbg/WJnGqoJF6LiBdtg==}engines: {node: '>=10.0.0'}@@ -8424,10 +8402,6 @@ packages:resolution: {integrity: sha512-OA0mILzGc1kCOCSJerOeqDxDQ4HOh+G8NbOJFOTgOCzpw7fCBubk0fEyxp8AgOL/jvLgYA/uV0cMbe43ElF1JA==}engines: {node: ^10 || ^12.20.0 || ^14.13.0 || >=15.0.0, npm: '>=7.0.0'}- resolution: {integrity: sha512-0eW44TGN5SQXU1mWSkKwFstI/22X2bG1nYzZTYMAWjylYURhse752YgbE4Cx46AC+bAvI+/dYTPRk1LqSUnu6w==}- engines: {node: ^10 || ^12.20.0 || ^14.13.0 || >=15.0.0}-resolution: {integrity: sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==}engines: {node: ^10 || ^12.20.0 || ^14.13.0 || >=15.0.0}@@ -10080,10 +10054,6 @@ packages:resolution: {integrity: sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==}- resolution: {integrity: sha512-F9ODfyqML2coTIsQpSkRHnLSZMtkU8Q+mSfcaIyKwy58u+8k5nvAYeiNhsyMARvzNcXJ9QfWVrcPsC9e9rAxtg==}- engines: {node: 20 || >=22}-resolution: {integrity: sha512-aY/R+aEsRelme17KGQa/1ZSIpLpNYYrhcrepKTZgE+W3WM16YMCaPwOHLHsmopZHELU0Ojin1lPVxKR0MihncA==}engines: {node: 20 || >=22}@@ -10190,9 +10160,6 @@ packages:resolution: {integrity: sha512-aylIc7Z9y4yzHYAJNuESG3hfhC+0Ibp/MAMiaOZgNv4pmEdFyfZhhhny4MNiAfWdBQ1RQ2mfDWmM1x8SvGyp8g==}- resolution: {integrity: sha512-IEn+pegP1aManZuckezWCO+XZQDplx1366JoVhTpMpBB1sPey/SbveZQUosKiKiGYjg1wH4pMlNgXbCiYgihQA==}-resolution: {integrity: sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==}@@ -10347,10 +10314,6 @@ packages:resolution: {integrity: sha512-VP79XUPxV2CigYP3jWwAUFSku2aKqBH7uTAapFWCBqutsbmDo96KY5o8uh6U+/YSIn5OxJnXp73beVkpqMIGhA==}engines: {node: '>=18'}- resolution: {integrity: sha512-enIvLvRAFZYXJzkCYG5RKmPfrFArdLv+R+lbQ53BmIMLIry74bjKzX6iHAm8WYamJkhSSEabrWN5D97XnKObjQ==}- engines: {node: 20 || >=22}-resolution: {integrity: sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==}engines: {node: 18 || 20 || >=22}@@ -11997,10 +11960,6 @@ packages:resolution: {integrity: sha512-GTPwEaCRN8IbYe5/VeGiwxYvMO0dKaC16fTeLbF+QGswjkLZ9JUqAfDhLMyH2SWukYhmetH+uxWa1Bhluv/evQ==}- resolution: {integrity: sha512-kXuRi1mtaKMrsLUxz3sQYvVl37B0Ns6MzfrtV5DvJceE9bPyspOqk9xxv7XbZWcfLWbFmm997vl83qUWVJA64w==}- engines: {node: '>=16'}-resolution: {integrity: sha512-LktZQb3IeoUWB9lqR5EWTHgW/VTITCXg4D21M+lvybRVdylLrRMnqaIONLVb5mav8vM19m44HIcGq4qASeu2Qw==}engines: {node: '>=16'}@@ -14801,12 +14760,6 @@ snapshots:optionalDependencies:'@types/node': 24.0.8- '@isaacs/[email protected]': {}-- '@isaacs/[email protected]':- dependencies:- '@isaacs/balanced-match': 4.0.1-'@isaacs/[email protected]':dependencies:string-width: 5.1.2@@ -14918,14 +14871,14 @@ snapshots:'@logtape/[email protected](@logtape/[email protected])':dependencies:'@logtape/logtape': 2.0.1- '@opentelemetry/api': 1.9.0+ '@opentelemetry/api': 1.9.1'@opentelemetry/api-logs': 0.208.0- '@opentelemetry/exporter-logs-otlp-grpc': 0.208.0(@opentelemetry/[email protected])- '@opentelemetry/exporter-logs-otlp-http': 0.208.0(@opentelemetry/[email protected])- '@opentelemetry/exporter-logs-otlp-proto': 0.208.0(@opentelemetry/[email protected])- '@opentelemetry/otlp-exporter-base': 0.208.0(@opentelemetry/[email protected])- '@opentelemetry/resources': 2.2.0(@opentelemetry/[email protected])- '@opentelemetry/sdk-logs': 0.208.0(@opentelemetry/[email protected])+ '@opentelemetry/exporter-logs-otlp-grpc': 0.208.0(@opentelemetry/[email protected])+ '@opentelemetry/exporter-logs-otlp-http': 0.208.0(@opentelemetry/[email protected])+ '@opentelemetry/exporter-logs-otlp-proto': 0.208.0(@opentelemetry/[email protected])+ '@opentelemetry/otlp-exporter-base': 0.208.0(@opentelemetry/[email protected])+ '@opentelemetry/resources': 2.2.0(@opentelemetry/[email protected])+ '@opentelemetry/sdk-logs': 0.208.0(@opentelemetry/[email protected])'@opentelemetry/semantic-conventions': 1.38.0@@ -14969,7 +14922,7 @@ snapshots:'@types/react': 19.2.2react: 19.2.3- '@modelcontextprotocol/[email protected]([email protected])':+ '@modelcontextprotocol/[email protected]([email protected])':dependencies:'@hono/node-server': 1.19.9([email protected])ajv: 8.17.1@@ -15142,7 +15095,7 @@ snapshots:'@opentelemetry/[email protected]':dependencies:- '@opentelemetry/api': 1.9.0+ '@opentelemetry/api': 1.9.1'@opentelemetry/[email protected]':dependencies:@@ -15156,11 +15109,6 @@ snapshots:dependencies:'@opentelemetry/api': 1.9.1- '@opentelemetry/[email protected](@opentelemetry/[email protected])':- dependencies:- '@opentelemetry/api': 1.9.0- '@opentelemetry/semantic-conventions': 1.38.0-'@opentelemetry/[email protected](@opentelemetry/[email protected])':dependencies:'@opentelemetry/api': 1.9.1@@ -15171,35 +15119,35 @@ snapshots:'@opentelemetry/api': 1.9.1'@opentelemetry/semantic-conventions': 1.38.0- '@opentelemetry/[email protected](@opentelemetry/[email protected])':+ '@opentelemetry/[email protected](@opentelemetry/[email protected])':dependencies:'@grpc/grpc-js': 1.14.1- '@opentelemetry/api': 1.9.0- '@opentelemetry/core': 2.2.0(@opentelemetry/[email protected])- '@opentelemetry/otlp-exporter-base': 0.208.0(@opentelemetry/[email protected])- '@opentelemetry/otlp-grpc-exporter-base': 0.208.0(@opentelemetry/[email protected])- '@opentelemetry/otlp-transformer': 0.208.0(@opentelemetry/[email protected])- '@opentelemetry/sdk-logs': 0.208.0(@opentelemetry/[email protected])+ '@opentelemetry/api': 1.9.1+ '@opentelemetry/core': 2.2.0(@opentelemetry/[email protected])+ '@opentelemetry/otlp-exporter-base': 0.208.0(@opentelemetry/[email protected])+ '@opentelemetry/otlp-grpc-exporter-base': 0.208.0(@opentelemetry/[email protected])+ '@opentelemetry/otlp-transformer': 0.208.0(@opentelemetry/[email protected])+ '@opentelemetry/sdk-logs': 0.208.0(@opentelemetry/[email protected])- '@opentelemetry/[email protected](@opentelemetry/[email protected])':+ '@opentelemetry/[email protected](@opentelemetry/[email protected])':dependencies:- '@opentelemetry/api': 1.9.0+ '@opentelemetry/api': 1.9.1'@opentelemetry/api-logs': 0.208.0- '@opentelemetry/core': 2.2.0(@opentelemetry/[email protected])- '@opentelemetry/otlp-exporter-base': 0.208.0(@opentelemetry/[email protected])- '@opentelemetry/otlp-transformer': 0.208.0(@opentelemetry/[email protected])- '@opentelemetry/sdk-logs': 0.208.0(@opentelemetry/[email protected])+ '@opentelemetry/core': 2.2.0(@opentelemetry/[email protected])+ '@opentelemetry/otlp-exporter-base': 0.208.0(@opentelemetry/[email protected])+ '@opentelemetry/otlp-transformer': 0.208.0(@opentelemetry/[email protected])+ '@opentelemetry/sdk-logs': 0.208.0(@opentelemetry/[email protected])- '@opentelemetry/[email protected](@opentelemetry/[email protected])':+ '@opentelemetry/[email protected](@opentelemetry/[email protected])':dependencies:- '@opentelemetry/api': 1.9.0+ '@opentelemetry/api': 1.9.1'@opentelemetry/api-logs': 0.208.0- '@opentelemetry/core': 2.2.0(@opentelemetry/[email protected])- '@opentelemetry/otlp-exporter-base': 0.208.0(@opentelemetry/[email protected])- '@opentelemetry/otlp-transformer': 0.208.0(@opentelemetry/[email protected])- '@opentelemetry/resources': 2.2.0(@opentelemetry/[email protected])- '@opentelemetry/sdk-logs': 0.208.0(@opentelemetry/[email protected])- '@opentelemetry/sdk-trace-base': 2.2.0(@opentelemetry/[email protected])+ '@opentelemetry/core': 2.2.0(@opentelemetry/[email protected])+ '@opentelemetry/otlp-exporter-base': 0.208.0(@opentelemetry/[email protected])+ '@opentelemetry/otlp-transformer': 0.208.0(@opentelemetry/[email protected])+ '@opentelemetry/resources': 2.2.0(@opentelemetry/[email protected])+ '@opentelemetry/sdk-logs': 0.208.0(@opentelemetry/[email protected])+ '@opentelemetry/sdk-trace-base': 2.2.0(@opentelemetry/[email protected])'@opentelemetry/[email protected](@opentelemetry/[email protected])':dependencies:@@ -15404,39 +15352,33 @@ snapshots:transitivePeerDependencies:- supports-color- '@opentelemetry/[email protected](@opentelemetry/[email protected])':+ '@opentelemetry/[email protected](@opentelemetry/[email protected])':dependencies:- '@opentelemetry/api': 1.9.0- '@opentelemetry/core': 2.2.0(@opentelemetry/[email protected])- '@opentelemetry/otlp-transformer': 0.208.0(@opentelemetry/[email protected])+ '@opentelemetry/api': 1.9.1+ '@opentelemetry/core': 2.2.0(@opentelemetry/[email protected])+ '@opentelemetry/otlp-transformer': 0.208.0(@opentelemetry/[email protected])- '@opentelemetry/[email protected](@opentelemetry/[email protected])':+ '@opentelemetry/[email protected](@opentelemetry/[email protected])':dependencies:'@grpc/grpc-js': 1.14.1- '@opentelemetry/api': 1.9.0- '@opentelemetry/core': 2.2.0(@opentelemetry/[email protected])- '@opentelemetry/otlp-exporter-base': 0.208.0(@opentelemetry/[email protected])- '@opentelemetry/otlp-transformer': 0.208.0(@opentelemetry/[email protected])+ '@opentelemetry/api': 1.9.1+ '@opentelemetry/core': 2.2.0(@opentelemetry/[email protected])+ '@opentelemetry/otlp-exporter-base': 0.208.0(@opentelemetry/[email protected])+ '@opentelemetry/otlp-transformer': 0.208.0(@opentelemetry/[email protected])- '@opentelemetry/[email protected](@opentelemetry/[email protected])':+ '@opentelemetry/[email protected](@opentelemetry/[email protected])':dependencies:- '@opentelemetry/api': 1.9.0+ '@opentelemetry/api': 1.9.1'@opentelemetry/api-logs': 0.208.0- '@opentelemetry/core': 2.2.0(@opentelemetry/[email protected])- '@opentelemetry/resources': 2.2.0(@opentelemetry/[email protected])- '@opentelemetry/sdk-logs': 0.208.0(@opentelemetry/[email protected])- '@opentelemetry/sdk-metrics': 2.2.0(@opentelemetry/[email protected])- '@opentelemetry/sdk-trace-base': 2.2.0(@opentelemetry/[email protected])+ '@opentelemetry/core': 2.2.0(@opentelemetry/[email protected])+ '@opentelemetry/resources': 2.2.0(@opentelemetry/[email protected])+ '@opentelemetry/sdk-logs': 0.208.0(@opentelemetry/[email protected])+ '@opentelemetry/sdk-metrics': 2.2.0(@opentelemetry/[email protected])+ '@opentelemetry/sdk-trace-base': 2.2.0(@opentelemetry/[email protected])protobufjs: 7.5.4'@opentelemetry/[email protected]': {}- '@opentelemetry/[email protected](@opentelemetry/[email protected])':- dependencies:- '@opentelemetry/api': 1.9.0- '@opentelemetry/core': 2.2.0(@opentelemetry/[email protected])- '@opentelemetry/semantic-conventions': 1.38.0-'@opentelemetry/[email protected](@opentelemetry/[email protected])':dependencies:'@opentelemetry/api': 1.9.1@@ -15449,24 +15391,24 @@ snapshots:'@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])'@opentelemetry/semantic-conventions': 1.38.0- '@opentelemetry/[email protected](@opentelemetry/[email protected])':+ '@opentelemetry/[email protected](@opentelemetry/[email protected])':dependencies:- '@opentelemetry/api': 1.9.0+ '@opentelemetry/api': 1.9.1'@opentelemetry/api-logs': 0.208.0- '@opentelemetry/core': 2.2.0(@opentelemetry/[email protected])- '@opentelemetry/resources': 2.2.0(@opentelemetry/[email protected])+ '@opentelemetry/core': 2.2.0(@opentelemetry/[email protected])+ '@opentelemetry/resources': 2.2.0(@opentelemetry/[email protected])- '@opentelemetry/[email protected](@opentelemetry/[email protected])':+ '@opentelemetry/[email protected](@opentelemetry/[email protected])':dependencies:- '@opentelemetry/api': 1.9.0- '@opentelemetry/core': 2.2.0(@opentelemetry/[email protected])- '@opentelemetry/resources': 2.2.0(@opentelemetry/[email protected])+ '@opentelemetry/api': 1.9.1+ '@opentelemetry/core': 2.2.0(@opentelemetry/[email protected])+ '@opentelemetry/resources': 2.2.0(@opentelemetry/[email protected])- '@opentelemetry/[email protected](@opentelemetry/[email protected])':+ '@opentelemetry/[email protected](@opentelemetry/[email protected])':dependencies:- '@opentelemetry/api': 1.9.0- '@opentelemetry/core': 2.2.0(@opentelemetry/[email protected])- '@opentelemetry/resources': 2.2.0(@opentelemetry/[email protected])+ '@opentelemetry/api': 1.9.1+ '@opentelemetry/core': 2.2.0(@opentelemetry/[email protected])+ '@opentelemetry/resources': 2.2.0(@opentelemetry/[email protected])'@opentelemetry/semantic-conventions': 1.38.0'@opentelemetry/[email protected](@opentelemetry/[email protected])':@@ -17509,14 +17451,14 @@ snapshots:'@sentry/[email protected](@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected](@swc/[email protected](@swc/[email protected])))':dependencies:- '@opentelemetry/api': 1.9.0+ '@opentelemetry/api': 1.9.1'@opentelemetry/semantic-conventions': 1.38.0'@rollup/plugin-commonjs': 28.0.1([email protected])'@sentry-internal/browser-utils': 10.31.0'@sentry/bundler-plugin-core': 4.6.1'@sentry/core': 10.31.0'@sentry/node': 10.31.0- '@sentry/opentelemetry': 10.31.0(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected])+ '@sentry/opentelemetry': 10.31.0(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected])'@sentry/react': 10.31.0([email protected])'@sentry/vercel-edge': 10.31.0@@ -17589,15 +17531,6 @@ snapshots:transitivePeerDependencies:- supports-color- '@sentry/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected])':- dependencies:- '@opentelemetry/api': 1.9.0- '@opentelemetry/context-async-hooks': 2.2.0(@opentelemetry/[email protected])- '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])- '@opentelemetry/sdk-trace-base': 2.7.1(@opentelemetry/[email protected])- '@opentelemetry/semantic-conventions': 1.38.0- '@sentry/core': 10.31.0-'@sentry/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected])':dependencies:'@opentelemetry/api': 1.9.1@@ -17622,8 +17555,8 @@ snapshots:'@sentry/[email protected]':dependencies:- '@opentelemetry/api': 1.9.0- '@opentelemetry/resources': 2.2.0(@opentelemetry/[email protected])+ '@opentelemetry/api': 1.9.1+ '@opentelemetry/resources': 2.2.0(@opentelemetry/[email protected])'@sentry/core': 10.31.0@@ -18333,7 +18266,7 @@ snapshots:'@ts-morph/[email protected]':dependencies:fast-glob: 3.3.3- minimatch: 10.1.1+ minimatch: 10.2.5path-browserify: 1.0.1'@tsconfig/[email protected]': {}@@ -19097,8 +19030,6 @@ snapshots:- [email protected]: {}-@@ -19177,7 +19108,7 @@ snapshots:dependencies:- baseline-browser-mapping: 2.9.9+ baseline-browser-mapping: 2.10.29caniuse-lite: 1.0.30001760electron-to-chromium: 1.5.267node-releases: 2.0.27@@ -19516,11 +19447,6 @@ snapshots:mdn-data: 2.0.28source-map-js: 1.2.1- dependencies:- mdn-data: 2.12.2- source-map-js: 1.2.1-dependencies:mdn-data: 2.27.1@@ -20360,7 +20286,7 @@ snapshots:dependencies:foreground-child: 3.3.1jackspeak: 4.1.1- minimatch: 10.1.1+ minimatch: 10.2.5minipass: 7.1.2package-json-from-dist: 1.0.1path-scurry: 2.0.1@@ -21327,8 +21253,6 @@ snapshots:- [email protected]: {}-@@ -21552,8 +21476,6 @@ snapshots:- [email protected]: {}-@@ -21859,10 +21781,6 @@ snapshots:- dependencies:- '@isaacs/brace-expansion': 5.0.0-dependencies:brace-expansion: 5.0.6@@ -21920,7 +21838,7 @@ snapshots:rettime: 0.7.0statuses: 2.0.2strict-event-emitter: 0.5.1- tough-cookie: 6.0.0+ tough-cookie: 6.0.1type-fest: 5.2.0until-async: 3.0.2yargs: 17.7.2@@ -21945,7 +21863,7 @@ snapshots:rettime: 0.7.0statuses: 2.0.2strict-event-emitter: 0.5.1- tough-cookie: 6.0.0+ tough-cookie: 6.0.1type-fest: 5.2.0until-async: 3.0.2yargs: 17.7.2@@ -22464,7 +22382,7 @@ snapshots:dependencies:- lru-cache: 11.2.2+ lru-cache: 11.2.7minipass: 7.1.2@@ -23385,7 +23303,7 @@ snapshots:'@babel/plugin-transform-typescript': 7.28.5(@babel/[email protected])'@babel/preset-typescript': 7.28.5(@babel/[email protected])'@dotenvx/dotenvx': 1.52.0- '@modelcontextprotocol/sdk': 1.26.0([email protected])+ '@modelcontextprotocol/sdk': 1.29.0([email protected])'@types/validate-npm-package-name': 4.0.2browserslist: 4.28.1commander: 14.0.3@@ -23429,7 +23347,7 @@ snapshots:'@babel/plugin-transform-typescript': 7.28.5(@babel/[email protected])'@babel/preset-typescript': 7.28.5(@babel/[email protected])'@dotenvx/dotenvx': 1.52.0- '@modelcontextprotocol/sdk': 1.26.0([email protected])+ '@modelcontextprotocol/sdk': 1.29.0([email protected])'@types/validate-npm-package-name': 4.0.2browserslist: 4.28.1commander: 14.0.3@@ -23874,7 +23792,7 @@ snapshots:dependencies:commander: 11.1.0css-select: 5.2.2- css-tree: 3.1.0+ css-tree: 3.2.1css-what: 6.2.2csso: 5.0.5picocolors: 1.1.1@@ -24025,10 +23943,6 @@ snapshots:'@sentry/types': 8.9.2'@sentry/utils': 8.9.2- dependencies:- tldts: 7.0.19-dependencies:tldts: 7.0.19@@ -24297,7 +24211,7 @@ snapshots:dependencies:- css-tree: 3.1.0+ css-tree: 3.2.1ofetch: 1.5.1ohash: 2.0.11