@supercheck/cli 0.1.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +79 -0
- package/dist/bin/supercheck.js +3750 -0
- package/dist/bin/supercheck.js.map +1 -0
- package/dist/index.d.ts +1140 -0
- package/dist/index.js +8 -0
- package/dist/index.js.map +1 -0
- package/package.json +56 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/bin/supercheck.ts","../../src/commands/login.ts","../../src/auth/store.ts","../../src/utils/errors.ts","../../src/utils/logger.ts","../../src/version.ts","../../src/api/client.ts","../../src/utils/discovery.ts","../../src/utils/resources.ts","../../src/commands/health.ts","../../src/config/loader.ts","../../src/config/schema.ts","../../src/output/formatter.ts","../../src/commands/config.ts","../../src/commands/init.ts","../../src/utils/spinner.ts","../../src/commands/jobs.ts","../../src/api/authenticated-client.ts","../../src/utils/validation.ts","../../src/commands/runs.ts","../../src/commands/tests.ts","../../src/commands/monitors.ts","../../src/commands/variables.ts","../../src/commands/tags.ts","../../src/commands/diff.ts","../../src/utils/reconcile.ts","../../src/commands/deploy.ts","../../src/commands/destroy.ts","../../src/commands/pull.ts","../../src/commands/notifications.ts","../../src/commands/alerts.ts","../../src/commands/audit.ts"],"sourcesContent":["import { Command } from 'commander'\nimport pc from 'picocolors'\nimport { loginCommand, logoutCommand, whoamiCommand } from '../commands/login.js'\nimport { healthCommand, locationsCommand } from '../commands/health.js'\nimport { configCommand } from '../commands/config.js'\nimport { initCommand } from '../commands/init.js'\nimport { jobCommand } from '../commands/jobs.js'\nimport { runCommand } from '../commands/runs.js'\nimport { testCommand } from '../commands/tests.js'\nimport { monitorCommand } from '../commands/monitors.js'\nimport { varCommand } from '../commands/variables.js'\nimport { tagCommand } from '../commands/tags.js'\nimport { diffCommand } from '../commands/diff.js'\nimport { deployCommand } from '../commands/deploy.js'\nimport { destroyCommand } from '../commands/destroy.js'\nimport { pullCommand } from '../commands/pull.js'\nimport { notificationCommand } from '../commands/notifications.js'\nimport { alertCommand } from '../commands/alerts.js'\nimport { auditCommand } from '../commands/audit.js'\nimport { setOutputFormat, type OutputFormat } from '../output/formatter.js'\nimport { setQuietMode, setLogLevel } from '../utils/logger.js'\nimport { CLIError, ExitCode } from '../utils/errors.js'\nimport { CLI_VERSION } from '../version.js'\n\nconst program = new Command()\n .name('supercheck')\n .description('Open-source testing, monitoring, and reliability — as code')\n .version(CLI_VERSION, '-v, --version')\n .option('--json', 'Output in JSON format')\n .option('--quiet', 'Suppress non-essential output')\n .option('--debug', 'Enable debug logging')\n .hook('preAction', (_thisCommand, actionCommand) => {\n const opts = program.opts()\n\n if (opts.json) {\n setOutputFormat('json' as OutputFormat)\n }\n\n if (opts.quiet) {\n setQuietMode(true)\n setOutputFormat('quiet' as OutputFormat)\n }\n\n if (opts.debug) {\n setLogLevel('debug')\n }\n\n // Validate that actionCommand exists (just for type safety)\n void actionCommand\n })\n\n// Register commands — auth\nprogram.addCommand(loginCommand)\nprogram.addCommand(logoutCommand)\nprogram.addCommand(whoamiCommand)\n\n// Register commands — project\nprogram.addCommand(initCommand)\nprogram.addCommand(configCommand)\n\n// Register commands — resources\nprogram.addCommand(jobCommand)\nprogram.addCommand(runCommand)\nprogram.addCommand(testCommand)\nprogram.addCommand(monitorCommand)\nprogram.addCommand(varCommand)\nprogram.addCommand(tagCommand)\n\n// Register commands — monitoring-as-code\nprogram.addCommand(diffCommand)\nprogram.addCommand(deployCommand)\nprogram.addCommand(destroyCommand)\nprogram.addCommand(pullCommand)\n\n// Register commands — notifications & alerts\nprogram.addCommand(notificationCommand)\nprogram.addCommand(alertCommand)\nprogram.addCommand(auditCommand)\n\n// Register commands — utilities\nprogram.addCommand(healthCommand)\nprogram.addCommand(locationsCommand)\n\n// Global error handler\nprogram.exitOverride()\n\nasync function main(): Promise<void> {\n try {\n await program.parseAsync(process.argv)\n } catch (err) {\n if (err instanceof CLIError) {\n if (err.exitCode !== ExitCode.Success) {\n console.error(pc.red(`\\n✗ ${err.message}\\n`))\n }\n process.exit(err.exitCode)\n }\n\n // Commander.js exit override throws CommanderError for --help, --version, etc.\n // Check for exitCode property (Commander sets exitCode: 0 for successful exits)\n if (err && typeof err === 'object' && 'exitCode' in err && typeof err.exitCode === 'number') {\n process.exit(err.exitCode)\n }\n\n // Unknown error\n console.error(pc.red(`\\n✗ Unexpected error: ${err instanceof Error ? err.message : String(err)}\\n`))\n process.exit(ExitCode.GeneralError)\n }\n}\n\nmain()\n","import { Command } from 'commander'\nimport {\n setToken,\n setBaseUrl,\n clearAuth,\n getToken,\n getStoredBaseUrl,\n validateTokenFormat,\n} from '../auth/store.js'\nimport { getApiClient } from '../api/client.js'\nimport { logger } from '../utils/logger.js'\nimport { CLIError, ExitCode } from '../utils/errors.js'\nimport { safeTokenPreview } from '../utils/resources.js'\n\nexport const loginCommand = new Command('login')\n .description('Authenticate with Supercheck')\n .option('--token <token>', 'Provide a CLI token directly (for CI/CD)')\n .option('--url <url>', 'Supercheck API URL (for self-hosted instances)')\n .action(async (options: { token?: string; url?: string }) => {\n if (options.token) {\n const token = options.token.trim()\n if (!validateTokenFormat(token)) {\n throw new CLIError(\n 'Invalid token. `supercheck login` requires a CLI token (sck_live_* or sck_test_*). Trigger keys (sck_trigger_* / job_*) are only for `supercheck job trigger` via SUPERCHECK_TRIGGER_KEY.',\n ExitCode.AuthError,\n )\n }\n\n // Build client with provided options (don't persist until verified)\n const client = getApiClient({\n baseUrl: options.url,\n token,\n })\n\n try {\n // Verify token using a Bearer-auth-compatible endpoint\n await client.get('/api/cli-tokens')\n } catch {\n throw new CLIError(\n 'Token verification failed. Please check your token and try again.',\n ExitCode.AuthError,\n )\n }\n\n // Token verified — now persist credentials\n setToken(token)\n if (options.url) {\n setBaseUrl(options.url)\n }\n\n const tokenPreview = safeTokenPreview(token)\n logger.success('Authentication successful')\n logger.info(` Token: ${tokenPreview}`)\n if (options.url) {\n logger.info(` API URL: ${options.url}`)\n }\n return\n }\n\n // Interactive login — not yet implemented\n logger.newline()\n logger.info('To authenticate, create a CLI token in the Dashboard:')\n logger.info(' Dashboard → Project Settings → CLI Tokens → Create Token')\n logger.newline()\n if (options.url) {\n logger.info(`Then run: supercheck login --token <your-token> --url ${options.url}`)\n } else {\n logger.info('Then run: supercheck login --token <your-token>')\n }\n logger.newline()\n logger.warn('Browser-based OAuth login is not yet implemented.')\n })\n\nexport const logoutCommand = new Command('logout')\n .description('Remove stored authentication credentials')\n .action(() => {\n clearAuth()\n logger.success('Logged out successfully. Stored credentials removed.')\n })\n\nexport const whoamiCommand = new Command('whoami')\n .description('Show current authentication context')\n .action(async () => {\n const token = getToken()\n if (!token) {\n throw new CLIError(\n 'Not authenticated. Run `supercheck login` to authenticate.',\n ExitCode.AuthError,\n )\n }\n\n const baseUrl = getStoredBaseUrl()\n const client = getApiClient({ token, baseUrl: baseUrl ?? undefined })\n\n try {\n // Use cli-tokens endpoint which supports Bearer auth via requireAuthContext()\n const { data } = await client.get<{\n success: boolean\n tokens: Array<{\n id: string\n name: string\n start: string\n enabled: boolean\n createdByName: string\n expiresAt: string | null\n lastRequest: string | null\n }>\n }>('/api/cli-tokens')\n\n const tokenPreview = safeTokenPreview(token)\n\n // Match the current token against the server's token list by prefix\n const activeToken = data.tokens?.find((t) => t.start && token.startsWith(t.start.replace(/\\.+$/, '')))\n\n logger.newline()\n logger.header('Current Context')\n logger.newline()\n if (activeToken?.createdByName && activeToken.createdByName !== '-') {\n logger.info(` User: ${activeToken.createdByName}`)\n }\n if (activeToken?.name) {\n logger.info(` Token: ${activeToken.name} (${tokenPreview})`)\n } else {\n logger.info(` Token: ${tokenPreview}`)\n }\n logger.info(` API URL: ${baseUrl ?? 'https://app.supercheck.io'}`)\n if (activeToken?.expiresAt) {\n logger.info(` Expires: ${activeToken.expiresAt}`)\n }\n if (activeToken?.lastRequest) {\n logger.info(` Last used: ${activeToken.lastRequest}`)\n }\n logger.newline()\n } catch {\n throw new CLIError(\n 'Failed to verify authentication. Your token may be expired or invalid.',\n ExitCode.AuthError,\n )\n }\n })\n","import Conf from 'conf'\nimport { AuthenticationError } from '../utils/errors.js'\nimport { logger } from '../utils/logger.js'\n\nconst TOKEN_PREFIX_LIVE = 'sck_live_'\nconst TOKEN_PREFIX_TEST = 'sck_test_'\nconst TOKEN_PREFIX_TRIGGER = 'sck_trigger_'\nconst TOKEN_PREFIX_TRIGGER_LEGACY = 'job_'\n\nconst VALID_CLI_PREFIXES = [TOKEN_PREFIX_LIVE, TOKEN_PREFIX_TEST]\nconst VALID_TRIGGER_PREFIXES = [TOKEN_PREFIX_TRIGGER, TOKEN_PREFIX_TRIGGER_LEGACY]\n\ninterface AuthData {\n token?: string\n baseUrl?: string\n organization?: string\n project?: string\n}\n\n/**\n * Local credential store using `conf`.\n *\n * SECURITY NOTE: The key below is a static obfuscation key — it prevents\n * casual inspection of the JSON file on disk but does NOT provide real\n * encryption against a determined attacker with file access.\n * For CI/CD and production use, prefer the SUPERCHECK_TOKEN environment\n * variable which bypasses the local store entirely.\n *\n * The `conf` library requires the parameter name `encryptionKey` — it is\n * NOT true encryption in this usage because the key is static and public.\n */\nconst store = new Conf<AuthData>({\n projectName: 'supercheck-cli',\n schema: {\n token: { type: 'string' },\n baseUrl: { type: 'string' },\n organization: { type: 'string' },\n project: { type: 'string' },\n },\n // Static obfuscation key — see SECURITY NOTE above.\n encryptionKey: 'supercheck-cli-v1',\n})\n\n/**\n * Validate that a token has a recognized prefix.\n */\nexport function validateTokenFormat(token: string): boolean {\n return VALID_CLI_PREFIXES.some((prefix) => token.startsWith(prefix))\n}\n\nexport function validateTriggerKeyFormat(token: string): boolean {\n return VALID_TRIGGER_PREFIXES.some((prefix) => token.startsWith(prefix))\n}\n\n/**\n * Get the current authentication token.\n * Priority: env var > stored token\n */\nexport function getToken(): string | null {\n const envToken = process.env.SUPERCHECK_TOKEN\n if (envToken) {\n const trimmed = envToken.trim()\n if (!validateTokenFormat(trimmed)) {\n logger.warn('SUPERCHECK_TOKEN must be a CLI token (sck_live_* or sck_test_*).')\n return null\n }\n return trimmed\n }\n\n const stored = store.get('token')\n if (!stored) return null\n return validateTokenFormat(stored) ? stored : null\n}\n\nexport function getTriggerKey(): string | null {\n const envKey = process.env.SUPERCHECK_TRIGGER_KEY\n if (envKey) {\n const trimmed = envKey.trim()\n if (!validateTriggerKeyFormat(trimmed)) {\n logger.warn('SUPERCHECK_TRIGGER_KEY must start with sck_trigger_ or job_.')\n return null\n }\n return trimmed\n }\n\n // Backward-compatible fallback: allow using SUPERCHECK_TOKEN as a trigger key\n // only if it matches a trigger key prefix.\n const token = process.env.SUPERCHECK_TOKEN\n if (token && validateTriggerKeyFormat(token.trim())) {\n logger.warn('Using SUPERCHECK_TOKEN as a trigger key. Prefer setting SUPERCHECK_TRIGGER_KEY instead.')\n return token.trim()\n }\n\n return null\n}\n\n/**\n * Store a token after validation.\n */\nexport function setToken(token: string): void {\n if (!validateTokenFormat(token)) {\n throw new AuthenticationError(\n `Invalid token format. Token must start with one of: ${VALID_CLI_PREFIXES.join(', ')}`,\n )\n }\n store.set('token', token)\n}\n\n/**\n * Remove stored credentials.\n */\nexport function clearAuth(): void {\n store.delete('token')\n store.delete('baseUrl')\n store.delete('organization')\n store.delete('project')\n}\n\n/**\n * Get the stored base URL override.\n */\nexport function getStoredBaseUrl(): string | null {\n return process.env.SUPERCHECK_URL ?? store.get('baseUrl') ?? null\n}\n\n/**\n * Store a base URL for self-hosted instances.\n */\nexport function setBaseUrl(url: string): void {\n store.set('baseUrl', url)\n}\n\n/**\n * Get the stored organization context.\n */\nexport function getStoredOrganization(): string | null {\n return process.env.SUPERCHECK_ORG ?? store.get('organization') ?? null\n}\n\n/**\n * Store the active organization.\n */\nexport function setOrganization(org: string): void {\n store.set('organization', org)\n}\n\n/**\n * Get the stored project context.\n */\nexport function getStoredProject(): string | null {\n return process.env.SUPERCHECK_PROJECT ?? store.get('project') ?? null\n}\n\n/**\n * Store the active project.\n */\nexport function setProject(project: string): void {\n store.set('project', project)\n}\n\n/**\n * Check if authenticated (token is available).\n */\nexport function isAuthenticated(): boolean {\n return getToken() !== null\n}\n\n/**\n * Require authentication — throw if no token available.\n */\nexport function requireAuth(): string {\n const token = getToken()\n if (!token) {\n throw new AuthenticationError(\n 'Not authenticated. Run `supercheck login` or set SUPERCHECK_TOKEN environment variable.',\n )\n }\n return token\n}\n\nexport function requireTriggerKey(): string {\n const key = getTriggerKey()\n if (!key) {\n throw new AuthenticationError(\n 'Missing trigger key. Set SUPERCHECK_TRIGGER_KEY (sck_trigger_* or job_*) to use `supercheck job trigger`.',\n )\n }\n return key\n}\n","/**\n * Standard CLI exit codes.\n *\n * 0 — Success\n * 1 — General error\n * 2 — Authentication error\n * 3 — Configuration error\n * 4 — Network / API error\n * 5 — Timeout\n */\nexport enum ExitCode {\n Success = 0,\n GeneralError = 1,\n AuthError = 2,\n ConfigError = 3,\n ApiError = 4,\n Timeout = 5,\n}\n\nexport class CLIError extends Error {\n public readonly exitCode: ExitCode\n\n constructor(message: string, exitCode: ExitCode = ExitCode.GeneralError) {\n super(message)\n this.name = 'CLIError'\n this.exitCode = exitCode\n }\n}\n\nexport class AuthenticationError extends CLIError {\n constructor(message: string) {\n super(message, ExitCode.AuthError)\n this.name = 'AuthenticationError'\n }\n}\n\nexport class ConfigurationError extends CLIError {\n constructor(message: string) {\n super(message, ExitCode.ConfigError)\n this.name = 'ConfigurationError'\n }\n}\n\nexport class ApiRequestError extends CLIError {\n public readonly statusCode?: number\n public readonly responseBody?: unknown\n\n constructor(message: string, statusCode?: number, responseBody?: unknown) {\n super(message, ExitCode.ApiError)\n this.name = 'ApiRequestError'\n this.statusCode = statusCode\n this.responseBody = responseBody\n }\n}\n\nexport class TimeoutError extends CLIError {\n constructor(message: string) {\n super(message, ExitCode.Timeout)\n this.name = 'TimeoutError'\n }\n}\n","import pc from 'picocolors'\n\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'silent'\n\nconst LOG_LEVELS: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n silent: 4,\n}\n\nlet currentLevel: LogLevel = 'info'\nlet quietMode = false\n\nexport function setLogLevel(level: LogLevel): void {\n currentLevel = level\n}\n\nexport function setQuietMode(quiet: boolean): void {\n quietMode = quiet\n if (quiet) currentLevel = 'error'\n}\n\nfunction shouldLog(level: LogLevel): boolean {\n return LOG_LEVELS[level] >= LOG_LEVELS[currentLevel]\n}\n\nexport const logger = {\n debug(message: string, ...args: unknown[]): void {\n if (shouldLog('debug')) {\n console.error(pc.gray(`[debug] ${message}`), ...args)\n }\n },\n\n info(message: string, ...args: unknown[]): void {\n if (shouldLog('info') && !quietMode) {\n console.error(message, ...args)\n }\n },\n\n success(message: string, ...args: unknown[]): void {\n if (shouldLog('info') && !quietMode) {\n console.error(pc.green(`✓ ${message}`), ...args)\n }\n },\n\n warn(message: string, ...args: unknown[]): void {\n if (shouldLog('warn')) {\n console.error(pc.yellow(`⚠ ${message}`), ...args)\n }\n },\n\n error(message: string, ...args: unknown[]): void {\n if (shouldLog('error')) {\n console.error(pc.red(`✗ ${message}`), ...args)\n }\n },\n\n /**\n * Output data to stdout (not stderr).\n * This is for machine-readable output (JSON, tables).\n */\n output(data: string): void {\n console.log(data)\n },\n\n newline(): void {\n if (!quietMode) console.error('')\n },\n\n /**\n * Print a styled header.\n */\n header(text: string): void {\n if (!quietMode) {\n console.error(pc.bold(pc.cyan(text)))\n }\n },\n}\n","// Version is injected at build time by tsup via define\ndeclare const __CLI_VERSION__: string\n\nexport const CLI_VERSION: string = typeof __CLI_VERSION__ !== 'undefined' ? __CLI_VERSION__ : '0.0.0-dev'\n","import { ApiRequestError, TimeoutError } from '../utils/errors.js'\nimport { logger } from '../utils/logger.js'\nimport { CLI_VERSION } from '../version.js'\nimport { ProxyAgent } from 'undici'\n\nconst DEFAULT_BASE_URL = 'https://app.supercheck.io'\nconst DEFAULT_TIMEOUT_MS = 30_000\nconst MAX_RETRIES = 3\nconst RETRY_BACKOFF_MS = 1_000\n\nexport interface ApiClientOptions {\n baseUrl?: string\n token?: string\n timeout?: number\n proxy?: string\n}\n\n/**\n * ProxyAgent cache.\n *\n * In a CLI context the process is short-lived, so accumulating entries is\n * not a practical concern. The cache exists to avoid creating duplicate\n * agents for the same proxy URL within a single run.\n */\nconst proxyAgents = new Map<string, ProxyAgent>()\n\nfunction getProxyAgent(proxyUrl: string): ProxyAgent {\n const existing = proxyAgents.get(proxyUrl)\n if (existing) return existing\n const created = new ProxyAgent(proxyUrl)\n proxyAgents.set(proxyUrl, created)\n return created\n}\n\n/**\n * Clear all cached ProxyAgent instances (useful for testing).\n */\nexport function clearProxyAgents(): void {\n proxyAgents.clear()\n}\n\nexport interface ApiResponse<T = unknown> {\n data: T\n status: number\n headers: Headers\n}\n\nexport interface PaginatedResponse<T = unknown> {\n data: T[]\n pagination: {\n total: number\n page: number\n limit: number\n totalPages: number\n hasNextPage: boolean\n hasPrevPage: boolean\n }\n}\n\nexport class ApiClient {\n private baseUrl: string\n private token: string | null\n private timeout: number\n private proxy: string | null\n\n constructor(options: ApiClientOptions = {}) {\n this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/$/, '')\n this.token = options.token ?? null\n this.timeout = options.timeout ?? DEFAULT_TIMEOUT_MS\n this.proxy = options.proxy ?? null\n }\n\n setToken(token: string): void {\n this.token = token\n }\n\n setBaseUrl(url: string): void {\n this.baseUrl = url.replace(/\\/$/, '')\n }\n\n setTimeout(timeout: number): void {\n this.timeout = timeout\n }\n\n setProxy(proxy: string | null): void {\n this.proxy = proxy\n }\n\n private buildHeaders(extraHeaders?: Record<string, string>): Headers {\n const headers = new Headers({\n 'Content-Type': 'application/json',\n 'User-Agent': `supercheck-cli/${CLI_VERSION}`,\n ...extraHeaders,\n })\n\n if (this.token) {\n headers.set('Authorization', `Bearer ${this.token}`)\n }\n\n return headers\n }\n\n private buildUrl(path: string, params?: Record<string, string | number | boolean | undefined>): string {\n const url = new URL(`${this.baseUrl}${path}`)\n if (params) {\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined) {\n url.searchParams.set(key, String(value))\n }\n }\n }\n return url.toString()\n }\n\n private getProxyEnv(url: URL): string | null {\n if (this.proxy) return this.proxy\n\n const noProxyRaw = process.env.NO_PROXY ?? process.env.no_proxy\n if (noProxyRaw && this.isNoProxyMatch(url, noProxyRaw)) {\n return null\n }\n\n if (url.protocol === 'https:') {\n return (\n process.env.HTTPS_PROXY ??\n process.env.https_proxy ??\n process.env.HTTP_PROXY ??\n process.env.http_proxy ??\n null\n )\n }\n\n if (url.protocol === 'http:') {\n return process.env.HTTP_PROXY ?? process.env.http_proxy ?? null\n }\n\n return null\n }\n\n private isNoProxyMatch(url: URL, noProxyRaw: string): boolean {\n const hostname = url.hostname\n const port = url.port || (url.protocol === 'https:' ? '443' : '80')\n const entries = noProxyRaw\n .split(',')\n .map((entry) => entry.trim())\n .filter(Boolean)\n\n if (entries.includes('*')) return true\n\n for (const entry of entries) {\n const [hostPart, portPart] = entry.split(':')\n const host = hostPart.trim()\n const entryPort = portPart?.trim()\n\n if (!host) continue\n if (entryPort && entryPort !== port) continue\n\n if (host.startsWith('.')) {\n if (hostname.endsWith(host)) return true\n continue\n }\n\n if (hostname === host) return true\n if (hostname.endsWith(`.${host}`)) return true\n }\n\n return false\n }\n\n /**\n * Execute an HTTP request with retries, timeout, and rate limit handling.\n */\n async request<T = unknown>(\n method: string,\n path: string,\n options?: {\n body?: unknown\n params?: Record<string, string | number | boolean | undefined>\n headers?: Record<string, string>\n retries?: number\n },\n ): Promise<ApiResponse<T>> {\n const url = this.buildUrl(path, options?.params)\n const parsedUrl = new URL(url)\n const headers = this.buildHeaders(options?.headers)\n const maxRetries = options?.retries ?? MAX_RETRIES\n\n let lastError: Error | null = null\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n let timeoutId: ReturnType<typeof setTimeout> | null = null\n try {\n const controller = new AbortController()\n timeoutId = setTimeout(() => controller.abort(), this.timeout)\n\n const proxy = this.getProxyEnv(parsedUrl)\n const fetchOptions: RequestInit & { dispatcher?: unknown } = {\n method,\n headers,\n body: options?.body ? JSON.stringify(options.body) : undefined,\n signal: controller.signal,\n }\n\n if (proxy) {\n fetchOptions.dispatcher = getProxyAgent(proxy)\n }\n\n const response = await fetch(url, fetchOptions)\n\n clearTimeout(timeoutId)\n timeoutId = null\n\n // Rate limit handling\n if (response.status === 429) {\n if (attempt >= maxRetries) {\n throw new ApiRequestError(\n `Rate limited after ${maxRetries + 1} attempts: ${method} ${path}`,\n 429,\n )\n }\n\n const retryAfter = response.headers.get('Retry-After')\n const parsedSeconds = retryAfter ? Number(retryAfter) : NaN\n const waitMs = Number.isFinite(parsedSeconds) && parsedSeconds > 0\n ? parsedSeconds * 1000\n : RETRY_BACKOFF_MS * Math.pow(2, attempt)\n\n logger.warn(`Rate limited. Retrying in ${Math.round(waitMs / 1000)}s...`)\n await this.sleep(waitMs)\n continue\n }\n\n // Server error — retry\n if (response.status >= 500 && attempt < maxRetries) {\n const waitMs = RETRY_BACKOFF_MS * Math.pow(2, attempt)\n logger.debug(`Server error ${response.status}. Retrying in ${waitMs}ms...`)\n await this.sleep(waitMs)\n continue\n }\n\n // Read response body as text first to safely handle empty/non-JSON responses (e.g. 204 No Content)\n const text = await response.text()\n\n // Client error — don't retry\n if (!response.ok) {\n let responseBody: unknown\n try {\n responseBody = JSON.parse(text)\n } catch {\n responseBody = text\n }\n\n throw new ApiRequestError(\n `API request failed: ${method} ${path} → ${response.status}`,\n response.status,\n responseBody,\n )\n }\n\n const data = text ? (JSON.parse(text) as T) : ({} as T)\n\n return {\n data,\n status: response.status,\n headers: response.headers,\n }\n } catch (err) {\n if (err instanceof ApiRequestError) throw err\n\n if (err instanceof DOMException && err.name === 'AbortError') {\n throw new TimeoutError(`Request timed out after ${this.timeout}ms: ${method} ${path}`)\n }\n\n lastError = err as Error\n\n if (attempt < maxRetries) {\n const waitMs = RETRY_BACKOFF_MS * Math.pow(2, attempt)\n logger.debug(`Network error: ${(err as Error).message}. Retrying in ${waitMs}ms...`)\n await this.sleep(waitMs)\n }\n } finally {\n if (timeoutId !== null) clearTimeout(timeoutId)\n }\n }\n\n throw new ApiRequestError(\n `Request failed after ${maxRetries + 1} attempts: ${lastError?.message ?? 'Unknown error'}`,\n )\n }\n\n async get<T = unknown>(\n path: string,\n params?: Record<string, string | number | boolean | undefined>,\n ): Promise<ApiResponse<T>> {\n return this.request<T>('GET', path, { params })\n }\n\n async post<T = unknown>(path: string, body?: unknown): Promise<ApiResponse<T>> {\n return this.request<T>('POST', path, { body })\n }\n\n async put<T = unknown>(path: string, body?: unknown): Promise<ApiResponse<T>> {\n return this.request<T>('PUT', path, { body })\n }\n\n async patch<T = unknown>(path: string, body?: unknown): Promise<ApiResponse<T>> {\n return this.request<T>('PATCH', path, { body })\n }\n\n async delete<T = unknown>(path: string): Promise<ApiResponse<T>> {\n return this.request<T>('DELETE', path)\n }\n\n private sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n }\n}\n\nlet defaultClient: ApiClient | null = null\n\n/**\n * Get or create the default API client singleton.\n * If options are provided and a client already exists, the token and baseUrl\n * are updated to reflect the caller's intent (e.g., after login).\n */\nexport function getApiClient(options?: ApiClientOptions): ApiClient {\n if (!defaultClient) {\n defaultClient = new ApiClient(options)\n } else if (options) {\n if (options.token !== undefined) defaultClient.setToken(options.token)\n if (options.baseUrl !== undefined) defaultClient.setBaseUrl(options.baseUrl)\n if (options.timeout !== undefined) defaultClient.setTimeout(options.timeout)\n if (options.proxy !== undefined) defaultClient.setProxy(options.proxy)\n }\n return defaultClient\n}\n\n/**\n * Reset the default API client (useful for testing).\n */\nexport function resetApiClient(): void {\n defaultClient = null\n}\n","import { readdirSync, statSync, readFileSync } from 'node:fs'\nimport { resolve, relative, basename } from 'node:path'\nimport { logger } from './logger.js'\n\nexport interface DiscoveredFile {\n absolutePath: string\n relativePath: string\n filename: string\n type: 'playwright' | 'k6'\n}\n\n/**\n * Match files against a simple glob pattern.\n * Supports: ** (any depth), * (any chars in segment)\n */\nfunction matchGlob(filePath: string, pattern: string): boolean {\n // First, replace glob wildcards with placeholders to protect them during escaping\n const withPlaceholders = pattern\n .replace(/\\*\\*/g, '{{GLOBSTAR}}')\n .replace(/\\*/g, '{{STAR}}')\n\n // Escape all regex-special characters in the remaining literal text\n const escaped = withPlaceholders.replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&')\n\n // Restore glob wildcards as regex equivalents\n const regexStr = escaped\n .replace(/\\{\\{GLOBSTAR\\}\\}/g, '.*')\n .replace(/\\{\\{STAR\\}\\}/g, '[^/]*')\n\n return new RegExp(`^${regexStr}$`).test(filePath)\n}\n\nconst SKIP_DIRS = new Set([\n 'node_modules', '.git', '.next', '.nuxt', 'dist', 'build',\n 'out', 'coverage', '.turbo', '.cache', '.vercel', 'vendor',\n])\n\n/**\n * Recursively walk a directory, returning all files.\n */\nfunction walkDir(dir: string): string[] {\n const results: string[] = []\n\n try {\n const entries = readdirSync(dir, { withFileTypes: true })\n for (const entry of entries) {\n const fullPath = resolve(dir, entry.name)\n if (entry.isDirectory()) {\n if (SKIP_DIRS.has(entry.name)) continue\n results.push(...walkDir(fullPath))\n } else if (entry.isFile()) {\n results.push(fullPath)\n }\n }\n } catch {\n // Directory doesn't exist or isn't readable\n }\n\n return results\n}\n\n/**\n * Extract the static directory prefix from a glob pattern.\n * e.g. '_supercheck_/tests/**\\/*.pw.ts' -> '_supercheck_/tests'\n */\nfunction getGlobStaticPrefix(pattern: string): string | null {\n const parts = pattern.split('/')\n const staticParts: string[] = []\n for (const part of parts) {\n if (part.includes('*') || part.includes('?') || part.includes('{') || part.includes('[')) break\n staticParts.push(part)\n }\n return staticParts.length > 0 ? staticParts.join('/') : null\n}\n\n/**\n * Discover test files matching glob patterns from the config.\n */\nexport function discoverFiles(\n cwd: string,\n patterns: { playwright?: string; k6?: string },\n): DiscoveredFile[] {\n // Collect unique root directories to walk based on glob static prefixes\n const walkRoots = new Set<string>()\n for (const pattern of [patterns.playwright, patterns.k6]) {\n if (!pattern) continue\n const prefix = getGlobStaticPrefix(pattern)\n if (prefix) {\n walkRoots.add(resolve(cwd, prefix))\n } else {\n // Fallback: no static prefix means we must walk cwd\n walkRoots.add(cwd)\n }\n }\n\n // Deduplicate: if cwd is in the set, it subsumes everything else\n if (walkRoots.has(cwd) && walkRoots.size > 1) {\n walkRoots.clear()\n walkRoots.add(cwd)\n }\n\n const allFiles: string[] = []\n for (const root of walkRoots) {\n allFiles.push(...walkDir(root))\n }\n\n const discovered: DiscoveredFile[] = []\n\n for (const absPath of allFiles) {\n const relPath = relative(cwd, absPath)\n const name = basename(absPath)\n\n if (patterns.playwright && matchGlob(relPath, patterns.playwright)) {\n discovered.push({\n absolutePath: absPath,\n relativePath: relPath,\n filename: name,\n type: 'playwright',\n })\n } else if (patterns.k6 && matchGlob(relPath, patterns.k6)) {\n discovered.push({\n absolutePath: absPath,\n relativePath: relPath,\n filename: name,\n type: 'k6',\n })\n }\n }\n\n logger.debug(`Discovered ${discovered.length} test files`)\n return discovered\n}\n\n/**\n * Read a file's content as a UTF-8 string, or return null on error.\n */\nexport function readFileContent(filePath: string): string | null {\n try {\n return readFileSync(filePath, 'utf-8')\n } catch {\n logger.warn(`Cannot read file: ${filePath}`)\n return null\n }\n}\n\n/**\n * Get file size in bytes.\n */\nexport function getFileSize(filePath: string): number {\n try {\n return statSync(filePath).size\n } catch {\n return 0\n }\n}\n","import { getApiClient } from '../api/client.js'\nimport { discoverFiles, readFileContent } from './discovery.js'\nimport { logger } from './logger.js'\nimport { ApiRequestError } from './errors.js'\nimport type { LocalResource, RemoteResource } from './reconcile.js'\nimport type { SupercheckConfig } from '../config/schema.js'\nimport type { PaginatedResponse } from '../api/client.js'\n\n/**\n * Regex for a valid UUID (v1–v7, any variant).\n * Used to parse UUID-based test filenames (e.g. `019a1234-abcd-7000-8000-000000000001.pw.ts`).\n */\nconst UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i\n\n/**\n * Build local resource list from the loaded config + discovered files.\n */\nexport function buildLocalResources(config: SupercheckConfig, cwd: string): LocalResource[] {\n const resources: LocalResource[] = []\n\n if (config.jobs) {\n for (const job of config.jobs) {\n resources.push({\n id: job.id,\n type: 'job',\n name: job.name,\n definition: { ...job },\n })\n }\n }\n\n if (config.variables) {\n for (const v of config.variables) {\n resources.push({\n id: v.id,\n type: 'variable',\n name: v.key,\n definition: { key: v.key, value: v.value, isSecret: v.isSecret, description: v.description },\n })\n }\n }\n\n if (config.tags) {\n for (const t of config.tags) {\n resources.push({\n id: t.id,\n type: 'tag',\n name: t.name,\n definition: { name: t.name, color: t.color },\n })\n }\n }\n\n if (Array.isArray(config.monitors)) {\n for (const m of config.monitors) {\n resources.push({\n id: m.id,\n type: 'monitor',\n name: m.name,\n definition: { ...m },\n })\n }\n } else if (typeof config.monitors === 'string') {\n logger.warn(\n `monitors is set to a glob pattern (\"${config.monitors}\") but glob-based monitor discovery is not yet implemented. ` +\n 'Define monitors as an inline array in your config, or remove the monitors field.',\n )\n }\n\n if (Array.isArray(config.statusPages)) {\n for (const sp of config.statusPages) {\n resources.push({\n id: sp.id,\n type: 'statusPage',\n name: sp.name,\n definition: { ...sp },\n })\n }\n } else if (typeof config.statusPages === 'string') {\n logger.warn(\n `statusPages is set to a glob pattern (\"${config.statusPages}\") but glob-based status page discovery is not yet implemented. ` +\n 'Define status pages as an inline array in your config, or remove the statusPages field.',\n )\n }\n\n const patterns = {\n playwright: config.tests?.playwright?.testMatch,\n k6: config.tests?.k6?.testMatch,\n }\n const files = discoverFiles(cwd, patterns)\n for (const file of files) {\n const script = readFileContent(file.absolutePath)\n if (script) {\n // Parse UUID from filename (e.g. `019a1234-abcd-7000-8000-000000000001.pw.ts`)\n const stem = file.filename.replace(/\\.(pw|k6)\\.ts$/, '')\n const testId = UUID_REGEX.test(stem) ? stem : undefined\n\n if (!testId) {\n logger.debug(`Test file \"${file.filename}\" does not have a UUID-based filename — will be treated as a new resource`)\n }\n\n resources.push({\n id: testId,\n type: 'test',\n name: file.filename,\n definition: {\n id: testId,\n title: stem,\n testType: file.type === 'playwright' ? 'playwright' : 'k6',\n script,\n },\n })\n }\n }\n\n return resources\n}\n\n/** Maximum items per page when fetching paginated resources. */\nconst PAGE_LIMIT = 200\n\n/**\n * Fetch all pages of a paginated API endpoint.\n *\n * Iterates through every page so that reconciliation and destroy commands\n * see the complete set of remote resources, regardless of how many exist.\n */\nexport async function fetchAllPages<T = Record<string, unknown>>(\n client: ReturnType<typeof getApiClient>,\n endpoint: string,\n label: string,\n): Promise<T[]> {\n const items: T[] = []\n let page = 1\n let totalPages = 1\n\n do {\n const { data } = await client.get<PaginatedResponse<T>>(endpoint, {\n limit: String(PAGE_LIMIT),\n page: String(page),\n })\n items.push(...data.data)\n\n if (data.pagination) {\n totalPages = data.pagination.totalPages\n }\n\n page++\n } while (page <= totalPages)\n\n if (totalPages > 1) {\n logger.debug(`Fetched ${totalPages} pages of ${label} (${items.length} total)`)\n }\n\n return items\n}\n\n/**\n * Safely extract a string `id` from a raw resource record.\n * Returns `undefined` if the value is missing or not a usable identifier.\n */\nfunction safeId(value: unknown): string | undefined {\n if (value === undefined || value === null) return undefined\n const str = String(value)\n if (str === 'undefined' || str === 'null' || str === '') return undefined\n return str\n}\n\n/**\n * Fetch remote resources from the Supercheck API.\n */\nexport async function fetchRemoteResources(client: ReturnType<typeof getApiClient>): Promise<RemoteResource[]> {\n const resources: RemoteResource[] = []\n\n try {\n const jobs = await fetchAllPages<Record<string, unknown>>(client, '/api/jobs', 'jobs')\n for (const job of jobs) {\n const id = safeId(job.id)\n if (!id) { logger.debug('Skipping job with missing id'); continue }\n resources.push({ id, type: 'job', name: String(job.name ?? ''), raw: job })\n }\n } catch (err) { logFetchError('jobs', err) }\n\n try {\n const tests = await fetchAllPages<Record<string, unknown>>(client, '/api/tests', 'tests')\n for (const test of tests) {\n const id = safeId(test.id)\n if (!id) { logger.debug('Skipping test with missing id'); continue }\n resources.push({ id, type: 'test', name: String(test.title ?? ''), raw: test })\n }\n } catch (err) { logFetchError('tests', err) }\n\n try {\n const monitors = await fetchAllPages<Record<string, unknown>>(client, '/api/monitors', 'monitors')\n for (const monitor of monitors) {\n const id = safeId(monitor.id)\n if (!id) { logger.debug('Skipping monitor with missing id'); continue }\n resources.push({ id, type: 'monitor', name: String(monitor.name ?? ''), raw: monitor })\n }\n } catch (err) { logFetchError('monitors', err) }\n\n try {\n const { data } = await client.get<Array<Record<string, unknown>>>('/api/variables')\n for (const v of data) {\n const id = safeId(v.id)\n if (!id) { logger.debug('Skipping variable with missing id'); continue }\n resources.push({ id, type: 'variable', name: String(v.key ?? ''), raw: v })\n }\n } catch (err) { logFetchError('variables', err) }\n\n try {\n const { data } = await client.get<Array<Record<string, unknown>>>('/api/tags')\n for (const t of data) {\n const id = safeId(t.id)\n if (!id) { logger.debug('Skipping tag with missing id'); continue }\n resources.push({ id, type: 'tag', name: String(t.name ?? ''), raw: t })\n }\n } catch (err) { logFetchError('tags', err) }\n\n try {\n const statusPages = await fetchAllPages<Record<string, unknown>>(client, '/api/status-pages', 'status-pages')\n for (const sp of statusPages) {\n const id = safeId(sp.id)\n if (!id) { logger.debug('Skipping status page with missing id'); continue }\n resources.push({ id, type: 'statusPage', name: String(sp.name ?? ''), raw: sp })\n }\n } catch (err) { logFetchError('status-pages', err) }\n\n return resources\n}\n\n/**\n * Log fetch errors with appropriate severity.\n * 404s are debug-level (resource type may not be enabled), other errors are warnings.\n */\nfunction logFetchError(resourceType: string, err: unknown): void {\n if (err instanceof ApiRequestError && err.statusCode === 404) {\n logger.debug(`Could not fetch ${resourceType} (not found)`)\n } else {\n const msg = err instanceof Error ? err.message : String(err)\n logger.warn(`Could not fetch ${resourceType}: ${msg}`)\n }\n}\n\n/**\n * Map resource type to the correct API endpoint.\n */\nexport function getApiEndpoint(type: string): string {\n switch (type) {\n case 'job': return '/api/jobs'\n case 'test': return '/api/tests'\n case 'monitor': return '/api/monitors'\n case 'variable': return '/api/variables'\n case 'tag': return '/api/tags'\n case 'statusPage': return '/api/status-pages'\n default: throw new Error(`Unknown resource type: ${type}`)\n }\n}\n\n/**\n * Safe token preview that handles short tokens gracefully.\n * Returns a masked version suitable for user-facing log output.\n */\nexport function safeTokenPreview(token: string): string {\n if (!token || token.length === 0) return '(empty)'\n if (token.length <= 4) return `${token.substring(0, 1)}***`\n if (token.length <= 8) {\n return `${token.substring(0, 4)}...`\n }\n if (token.length <= 20) {\n // Show only the prefix (e.g. sck_live_) + a few chars\n return `${token.substring(0, Math.min(token.length - 4, 12))}...`\n }\n return `${token.substring(0, 12)}...${token.substring(token.length - 4)}`\n}\n","import { Command } from 'commander'\nimport { getApiClient } from '../api/client.js'\nimport { getStoredBaseUrl } from '../auth/store.js'\nimport { tryLoadConfig } from '../config/loader.js'\nimport { logger } from '../utils/logger.js'\nimport { output } from '../output/formatter.js'\nimport { CLIError, ExitCode } from '../utils/errors.js'\n\nexport const healthCommand = new Command('health')\n .description('Check Supercheck API health')\n .option('--url <url>', 'Supercheck API URL')\n .action(async (options: { url?: string }) => {\n const configResult = await tryLoadConfig()\n const baseUrl = options.url\n ?? getStoredBaseUrl()\n ?? configResult?.config.api?.baseUrl\n ?? 'https://app.supercheck.io'\n\n const client = getApiClient({ baseUrl })\n\n try {\n const { data } = await client.get<{\n status: string\n timestamp?: string\n latencyMs?: number\n checks?: Record<string, { status: string; latencyMs?: number; error?: string }>\n }>('/api/health')\n\n // Build a flat view for display\n const checks = data.checks ?? {}\n const displayData: Record<string, unknown> = {\n status: data.status,\n database: checks.database?.status ?? 'n/a',\n redis: checks.redis?.status ?? 'n/a',\n s3: checks.s3?.status ?? 'n/a',\n latencyMs: data.latencyMs,\n }\n\n output(displayData as Record<string, unknown>, {\n columns: [\n { key: 'status', header: 'Status' },\n { key: 'database', header: 'Database' },\n { key: 'redis', header: 'Redis' },\n { key: 's3', header: 'S3' },\n { key: 'latencyMs', header: 'Latency (ms)' },\n ],\n })\n\n if (data.status === 'ok') {\n logger.success(`API is healthy at ${baseUrl}`)\n } else {\n throw new CLIError(`API reports degraded status at ${baseUrl}`, ExitCode.ApiError)\n }\n } catch (err) {\n if (err instanceof CLIError) throw err\n logger.error(`Cannot reach API at ${baseUrl}`)\n if (err instanceof Error) {\n logger.debug(err.message)\n }\n throw new CLIError(`Cannot reach API at ${baseUrl}`, ExitCode.ApiError)\n }\n })\n\nexport const locationsCommand = new Command('locations')\n .description('List available execution locations')\n .action(async () => {\n const configResult = await tryLoadConfig()\n const baseUrl = getStoredBaseUrl()\n ?? configResult?.config.api?.baseUrl\n ?? 'https://app.supercheck.io'\n\n const client = getApiClient({ baseUrl })\n\n const { data } = await client.get<\n | { locations: Array<{ id?: string; code?: string; name: string; region: string }> }\n | { success: boolean; data: Array<{ code: string; name: string; region: string }> }\n >('/api/locations')\n\n const locations =\n 'locations' in data\n ? data.locations\n : (data.data ?? [])\n\n output(locations as unknown as Record<string, unknown>[], {\n columns: [\n { key: 'code', header: 'Code' },\n { key: 'name', header: 'Name' },\n { key: 'region', header: 'Region' },\n ],\n })\n })\n","import { createJiti } from 'jiti'\nimport { deepmerge } from 'deepmerge-ts'\nimport { existsSync } from 'node:fs'\nimport { resolve, dirname } from 'node:path'\nimport { supercheckConfigSchema, type SupercheckConfig } from './schema.js'\nimport { CLIError, ExitCode } from '../utils/errors.js'\n\nconst CONFIG_FILES = [\n 'supercheck.config.ts',\n 'supercheck.config.js',\n 'supercheck.config.mjs',\n]\n\nconst LOCAL_CONFIG_FILES = [\n 'supercheck.config.local.ts',\n 'supercheck.config.local.js',\n 'supercheck.config.local.mjs',\n]\n\n/**\n * Resolve the config file path. Search order:\n * 1. Explicit --config flag\n * 2. supercheck.config.{ts,js,mjs} in cwd\n */\nfunction resolveConfigPath(cwd: string, explicitPath?: string): string | null {\n if (explicitPath) {\n const abs = resolve(cwd, explicitPath)\n if (!existsSync(abs)) {\n throw new CLIError(\n `Config file not found: ${abs}`,\n ExitCode.ConfigError,\n )\n }\n return abs\n }\n\n for (const file of CONFIG_FILES) {\n const abs = resolve(cwd, file)\n if (existsSync(abs)) return abs\n }\n\n return null\n}\n\n/**\n * Resolve local override config file path.\n */\nfunction resolveLocalConfigPath(cwd: string): string | null {\n for (const file of LOCAL_CONFIG_FILES) {\n const abs = resolve(cwd, file)\n if (existsSync(abs)) return abs\n }\n return null\n}\n\n/**\n * Load a TS/JS config file using jiti (zero-config TS execution).\n */\nasync function loadConfigFile(filePath: string): Promise<unknown> {\n const jiti = createJiti(dirname(filePath), {\n interopDefault: true,\n })\n\n const mod = await jiti.import(filePath) as Record<string, unknown>\n return mod.default ?? mod\n}\n\n/**\n * Apply environment variable overrides to the config.\n */\nfunction applyEnvOverrides(config: SupercheckConfig): SupercheckConfig {\n const result = { ...config }\n\n if (process.env.SUPERCHECK_URL) {\n result.api = {\n ...result.api,\n baseUrl: process.env.SUPERCHECK_URL,\n }\n }\n\n if (process.env.SUPERCHECK_ORG) {\n result.project = {\n ...result.project,\n organization: process.env.SUPERCHECK_ORG,\n }\n }\n\n if (process.env.SUPERCHECK_PROJECT) {\n result.project = {\n ...result.project,\n project: process.env.SUPERCHECK_PROJECT,\n }\n }\n\n return result\n}\n\n/**\n * Detect secrets in config values that should never be stored in config files.\n */\nfunction validateNoSecrets(config: SupercheckConfig): void {\n const configStr = JSON.stringify(config)\n const secretPatterns = [\n /sck_live_[a-zA-Z0-9]+/,\n /sck_trigger_[a-zA-Z0-9]+/,\n /sck_test_[a-zA-Z0-9]+/,\n ]\n\n for (const pattern of secretPatterns) {\n if (pattern.test(configStr)) {\n throw new CLIError(\n 'Config file contains what appears to be an API token. ' +\n 'Tokens must be stored in environment variables (SUPERCHECK_TOKEN) or the OS keychain, never in config files.',\n ExitCode.ConfigError,\n )\n }\n }\n}\n\nexport interface LoadConfigOptions {\n cwd?: string\n configPath?: string\n}\n\nexport interface LoadConfigResult {\n config: SupercheckConfig\n configPath: string | null\n}\n\n/**\n * Load, merge, validate, and return the Supercheck configuration.\n *\n * Priority (highest to lowest):\n * 1. Environment variables\n * 2. supercheck.config.local.{ts,js,mjs}\n * 3. supercheck.config.{ts,js,mjs}\n */\nexport async function loadConfig(options: LoadConfigOptions = {}): Promise<LoadConfigResult> {\n const cwd = options.cwd ?? process.cwd()\n\n const configPath = resolveConfigPath(cwd, options.configPath)\n if (!configPath) {\n throw new CLIError(\n 'No supercheck.config.ts found. Run `supercheck init` to create one.',\n ExitCode.ConfigError,\n )\n }\n\n let config = await loadConfigFile(configPath) as SupercheckConfig\n\n const localConfigPath = resolveLocalConfigPath(cwd)\n if (localConfigPath) {\n const localConfig = await loadConfigFile(localConfigPath) as Partial<SupercheckConfig>\n config = deepmerge(config, localConfig) as SupercheckConfig\n }\n\n config = applyEnvOverrides(config)\n\n validateNoSecrets(config)\n\n const parsed = supercheckConfigSchema.safeParse(config)\n if (!parsed.success) {\n const issues = parsed.error.issues\n .map((i) => ` - ${i.path.join('.')}: ${i.message}`)\n .join('\\n')\n throw new CLIError(\n `Invalid configuration:\\n${issues}`,\n ExitCode.ConfigError,\n )\n }\n\n return {\n config: parsed.data,\n configPath,\n }\n}\n\n/**\n * Try to load config, but return null if no config file exists.\n * Used by commands that don't strictly require a config (e.g., login, health).\n */\nexport async function tryLoadConfig(options: LoadConfigOptions = {}): Promise<LoadConfigResult | null> {\n try {\n return await loadConfig(options)\n } catch (err) {\n if (err instanceof CLIError && err.message.includes('No supercheck.config.ts found')) {\n return null\n }\n throw err\n }\n}\n","import { z } from 'zod'\n\n// --- Leaf schemas ---\n\nexport const tagDefinitionSchema = z.object({\n /** Database UUID. Present for existing resources, omitted for new ones. */\n id: z.string().uuid().optional(),\n name: z.string().min(1),\n color: z.string().optional(),\n})\n\nexport const variableDefinitionSchema = z.object({\n /** Database UUID. Present for existing resources, omitted for new ones. */\n id: z.string().uuid().optional(),\n key: z.string().min(1),\n value: z.string(),\n isSecret: z.boolean().default(false),\n description: z.string().optional(),\n})\n\nexport const notificationProviderDefinitionSchema = z.object({\n /** Database UUID. Present for existing resources, omitted for new ones. */\n id: z.string().uuid().optional(),\n name: z.string().min(1),\n type: z.enum(['email', 'slack', 'webhook', 'telegram', 'discord', 'teams']),\n config: z.record(z.unknown()),\n})\n\n// --- Alert Config ---\n\n/** Base alert configuration shared by monitors and jobs. */\nexport const alertConfigSchema = z.object({\n enabled: z.boolean().optional(),\n notificationProviders: z.array(z.string()).optional(),\n alertOnFailure: z.boolean().optional(),\n alertOnSuccess: z.boolean().optional(),\n alertOnTimeout: z.boolean().optional(),\n alertOnRecovery: z.boolean().optional(),\n alertOnSslExpiration: z.boolean().optional(),\n failureThreshold: z.number().int().positive().optional(),\n recoveryThreshold: z.number().int().positive().optional(),\n customMessage: z.string().optional(),\n}).passthrough()\n\n// --- Playwright & k6 ---\n\nexport const playwrightTestConfigSchema = z.object({\n testMatch: z.string().default('_supercheck_/tests/**/*.pw.ts'),\n browser: z.enum(['chromium', 'firefox', 'webkit']).default('chromium'),\n})\n\nexport const k6TestConfigSchema = z.object({\n testMatch: z.string().default('_supercheck_/tests/**/*.k6.ts'),\n})\n\nexport const testsConfigSchema = z.object({\n playwright: playwrightTestConfigSchema.optional(),\n k6: k6TestConfigSchema.optional(),\n})\n\n// --- Monitors ---\n\nexport const monitorDefinitionSchema = z.object({\n /** Database UUID. Present for existing resources, omitted for new ones. */\n id: z.string().uuid().optional(),\n name: z.string().min(1),\n description: z.string().optional(),\n type: z.enum(['http_request', 'website', 'ping_host', 'port_check', 'synthetic_test']),\n target: z.string().optional(),\n frequencyMinutes: z.number().int().positive().optional(),\n enabled: z.boolean().optional(),\n config: z.record(z.unknown()).optional(),\n alertConfig: alertConfigSchema.optional(),\n tags: z.array(z.string()).optional(),\n})\n\n// --- Jobs ---\n\nexport const jobDefinitionSchema = z.object({\n /** Database UUID. Present for existing resources, omitted for new ones. */\n id: z.string().uuid().optional(),\n name: z.string().min(1),\n description: z.string().optional(),\n jobType: z.enum(['playwright', 'k6']).optional(),\n tests: z.array(z.string()).min(1),\n cronSchedule: z.string().optional(),\n status: z.string().optional(),\n alertConfig: alertConfigSchema.optional(),\n tags: z.array(z.string()).optional(),\n})\n\n// --- Status Pages ---\n\nexport const statusPageComponentDefinitionSchema = z.object({\n /** Database UUID. Present for existing resources, omitted for new ones. */\n id: z.string().uuid().optional(),\n name: z.string().min(1),\n description: z.string().optional(),\n monitors: z.array(z.string()).optional(),\n position: z.number().int().min(0).optional(),\n})\n\nexport const statusPageDefinitionSchema = z.object({\n /** Database UUID. Present for existing resources, omitted for new ones. */\n id: z.string().uuid().optional(),\n name: z.string().min(1),\n subdomain: z.string().optional(),\n status: z.enum(['draft', 'published', 'archived']).optional(),\n description: z.string().optional(),\n headline: z.string().optional(),\n supportUrl: z.string().optional(),\n components: z.array(statusPageComponentDefinitionSchema).optional(),\n branding: z.object({\n bodyBackgroundColor: z.string().optional(),\n fontColor: z.string().optional(),\n greens: z.string().optional(),\n reds: z.string().optional(),\n }).optional(),\n notifications: z.object({\n allowEmailSubscribers: z.boolean().default(true),\n allowWebhookSubscribers: z.boolean().default(false),\n allowRssFeed: z.boolean().default(true),\n }).optional(),\n})\n\n// --- Project, API, Defaults ---\n\nexport const projectConfigSchema = z.object({\n organization: z.string().min(1),\n project: z.string().min(1),\n})\n\nexport const apiConfigSchema = z.object({\n baseUrl: z.string().url().default('https://app.supercheck.io'),\n})\n\nexport const defaultsConfigSchema = z.object({\n runLocation: z.string().optional(),\n timeout: z.number().int().positive().optional(),\n})\n\n// --- Root config ---\n\nexport const supercheckConfigSchema = z.object({\n schemaVersion: z.literal('1.0'),\n project: projectConfigSchema,\n api: apiConfigSchema.optional(),\n defaults: defaultsConfigSchema.optional(),\n tests: testsConfigSchema.optional(),\n monitors: z.union([\n z.string(),\n z.array(monitorDefinitionSchema),\n ]).optional(),\n statusPages: z.union([\n z.string(),\n z.array(statusPageDefinitionSchema),\n ]).optional(),\n jobs: z.array(jobDefinitionSchema).optional(),\n notificationProviders: z.array(notificationProviderDefinitionSchema).optional(),\n variables: z.array(variableDefinitionSchema).optional(),\n tags: z.array(tagDefinitionSchema).optional(),\n})\n\n// --- Inferred types ---\n\nexport type AlertConfig = z.infer<typeof alertConfigSchema>\nexport type SupercheckConfig = z.infer<typeof supercheckConfigSchema>\nexport type ProjectConfig = z.infer<typeof projectConfigSchema>\nexport type ApiConfig = z.infer<typeof apiConfigSchema>\nexport type DefaultsConfig = z.infer<typeof defaultsConfigSchema>\nexport type TestsConfig = z.infer<typeof testsConfigSchema>\nexport type PlaywrightTestConfig = z.infer<typeof playwrightTestConfigSchema>\nexport type K6TestConfig = z.infer<typeof k6TestConfigSchema>\nexport type MonitorDefinition = z.infer<typeof monitorDefinitionSchema>\nexport type JobDefinition = z.infer<typeof jobDefinitionSchema>\nexport type StatusPageDefinition = z.infer<typeof statusPageDefinitionSchema>\nexport type StatusPageComponentDefinition = z.infer<typeof statusPageComponentDefinitionSchema>\nexport type NotificationProviderDefinition = z.infer<typeof notificationProviderDefinitionSchema>\nexport type VariableDefinition = z.infer<typeof variableDefinitionSchema>\nexport type TagDefinition = z.infer<typeof tagDefinitionSchema>\n","import Table from 'cli-table3'\nimport pc from 'picocolors'\nimport { logger } from '../utils/logger.js'\n\nexport type OutputFormat = 'table' | 'json' | 'quiet'\n\nexport type OutputColumn = {\n key: string\n header: string\n width?: number\n format?: (value: unknown, row: Record<string, unknown>) => string\n}\n\nlet currentFormat: OutputFormat = 'table'\n\nexport function setOutputFormat(format: OutputFormat): void {\n currentFormat = format\n}\n\nexport function getOutputFormat(): OutputFormat {\n return currentFormat\n}\n\n/**\n * Format and output data based on the current output format.\n */\nexport function output<T extends Record<string, unknown>>(\n data: T | T[],\n options?: {\n columns?: OutputColumn[]\n },\n): void {\n switch (currentFormat) {\n case 'json':\n logger.output(JSON.stringify(data, null, 2))\n break\n\n case 'quiet':\n // In quiet mode, only output IDs or minimal info\n if (Array.isArray(data)) {\n for (const item of data) {\n if ('id' in item) logger.output(String(item.id))\n }\n } else if ('id' in data) {\n logger.output(String(data.id))\n }\n break\n\n case 'table':\n default:\n outputTable(data, options?.columns)\n break\n }\n}\n\nfunction outputTable<T extends Record<string, unknown>>(\n data: T | T[] | undefined | null,\n columns?: OutputColumn[],\n): void {\n // Handle undefined/null data\n if (data === undefined || data === null) {\n logger.info('No results found.')\n return\n }\n\n // Convert to array and filter out undefined/null items\n const rawItems = Array.isArray(data) ? data : [data]\n const items = rawItems.filter((item): item is T => item !== undefined && item !== null)\n\n if (items.length === 0) {\n logger.info('No results found.')\n return\n }\n\n // Use provided columns or infer from first item\n const cols: OutputColumn[] = columns ?? Object.keys(items[0]).map((key) => ({\n key,\n header: key.charAt(0).toUpperCase() + key.slice(1),\n }))\n\n const table = new Table({\n head: cols.map((c) => c.header),\n style: {\n head: ['cyan'],\n border: ['gray'],\n },\n })\n\n for (const item of items) {\n // Safely access each column value\n table.push(cols.map((c) => formatValue(item?.[c.key], c, item)))\n }\n\n logger.output(table.toString())\n}\n\n/**\n * Status values that should be colorized\n */\nconst STATUS_COLORS: Record<string, 'success' | 'error' | 'warning'> = {\n // Success states (green)\n up: 'success',\n ok: 'success',\n success: 'success',\n passed: 'success',\n active: 'success',\n sent: 'success',\n enabled: 'success',\n healthy: 'success',\n running: 'success',\n completed: 'success',\n\n // Error states (red)\n down: 'error',\n failed: 'error',\n error: 'error',\n blocked: 'error',\n unhealthy: 'error',\n cancelled: 'error',\n canceled: 'error',\n\n // Warning states (yellow)\n paused: 'warning',\n pending: 'warning',\n disabled: 'warning',\n degraded: 'warning',\n unknown: 'warning',\n queued: 'warning',\n warning: 'warning',\n skipped: 'warning',\n inactive: 'warning',\n}\n\n/**\n * Format a status value with color and indicator\n */\nfunction formatStatus(status: string): string {\n const normalizedStatus = status.toLowerCase()\n const colorType = STATUS_COLORS[normalizedStatus]\n\n if (!colorType) {\n return status\n }\n\n switch (colorType) {\n case 'success':\n return pc.green(`● ${status}`)\n case 'error':\n return pc.red(`● ${status}`)\n case 'warning':\n return pc.yellow(`● ${status}`)\n default:\n return status\n }\n}\n\nfunction formatValue(value: unknown, column?: OutputColumn, row?: Record<string, unknown>): string {\n if (column?.format && row) {\n return column.format(value, row)\n }\n\n if (value === null || value === undefined) return pc.dim('-')\n\n if (typeof value === 'boolean') {\n return value ? pc.green('✓') : pc.red('✗')\n }\n\n if (value instanceof Date) return formatDate(value)\n\n if (Array.isArray(value)) return value.join(', ')\n\n if (typeof value === 'number') {\n const dateForNumber = maybeFormatDate(value, column?.key)\n if (dateForNumber) return dateForNumber\n return String(value)\n }\n\n if (typeof value === 'object') return JSON.stringify(value)\n\n const strValue = String(value)\n\n const dateForString = maybeFormatDate(strValue, column?.key)\n if (dateForString) return dateForString\n\n // Check if this looks like a status value\n if (STATUS_COLORS[strValue.toLowerCase()]) {\n return formatStatus(strValue)\n }\n\n return strValue\n}\n\nconst DATE_KEY_PATTERN = /(At|Date|Time|Timestamp)$/i\n\nfunction maybeFormatDate(value: string | number, key?: string): string | null {\n if (!key && typeof value !== 'string') return null\n\n if (key && !DATE_KEY_PATTERN.test(key) && typeof value !== 'string') return null\n\n const date = new Date(value)\n if (Number.isNaN(date.getTime())) return null\n\n if (typeof value === 'string') {\n const isIsoLike = value.includes('T') || value.endsWith('Z') || /[+-]\\d{2}:?\\d{2}$/.test(value)\n if (!isIsoLike) return null\n return formatDate(date)\n }\n\n return formatDate(date)\n}\n\nfunction formatDate(date: Date): string {\n return date.toISOString().replace('T', ' ').replace('Z', '')\n}\n\n/**\n * Output a single key-value pair detail view.\n */\nexport function outputDetail(data: Record<string, unknown>): void {\n if (currentFormat === 'json') {\n logger.output(JSON.stringify(data, null, 2))\n return\n }\n\n if (currentFormat === 'quiet') {\n if ('id' in data) logger.output(String(data.id))\n return\n }\n\n const keys = Object.keys(data)\n if (keys.length === 0) {\n logger.info('No details available.')\n return\n }\n\n const maxKeyLen = Math.max(...keys.map((k) => k.length))\n for (const [key, value] of Object.entries(data)) {\n const label = key.padEnd(maxKeyLen + 2)\n logger.output(` ${label}${formatValue(value, { key, header: key }, data)}`)\n }\n}\n","import { Command } from 'commander'\nimport { loadConfig } from '../config/loader.js'\nimport { logger } from '../utils/logger.js'\nimport { output } from '../output/formatter.js'\n\nexport const configCommand = new Command('config')\n .description('Configuration management')\n\nconfigCommand\n .command('validate')\n .description('Validate supercheck.config.ts')\n .action(async () => {\n const { config, configPath } = await loadConfig()\n logger.success(`Valid configuration loaded from ${configPath}`)\n logger.info(` Organization: ${config.project.organization}`)\n logger.info(` Project: ${config.project.project}`)\n })\n\nconfigCommand\n .command('print')\n .description('Print the resolved configuration')\n .action(async () => {\n const { config } = await loadConfig()\n output(config as unknown as Record<string, unknown>)\n })\n","import { Command } from 'commander'\nimport { existsSync, mkdirSync, writeFileSync, readFileSync, appendFileSync } from 'node:fs'\nimport { resolve, basename } from 'node:path'\nimport { logger } from '../utils/logger.js'\nimport { CLIError, ExitCode } from '../utils/errors.js'\nimport { withSpinner } from '../utils/spinner.js'\n\nconst CONFIG_TEMPLATE = `import { defineConfig } from '@supercheck/cli'\n\nexport default defineConfig({\n schemaVersion: '1.0',\n project: {\n organization: 'my-org',\n project: 'my-project',\n },\n api: {\n baseUrl: process.env.SUPERCHECK_URL ?? 'https://app.supercheck.io',\n },\n tests: {\n playwright: {\n testMatch: '_supercheck_/tests/**/*.pw.ts',\n browser: 'chromium',\n },\n k6: {\n testMatch: '_supercheck_/tests/**/*.k6.ts',\n },\n },\n})\n`\n\nconst EXAMPLE_PW_TEST = `import { test, expect } from '@playwright/test'\n\ntest('homepage loads successfully', async ({ page }) => {\n await page.goto('https://example.com')\n await expect(page).toHaveTitle(/Example/)\n})\n`\n\nconst EXAMPLE_K6_TEST = `import http from 'k6/http'\nimport { check, sleep } from 'k6'\n\nexport const options = {\n vus: 10,\n duration: '30s',\n}\n\nexport default function () {\n const res = http.get('https://example.com')\n check(res, {\n 'status is 200': (r) => r.status === 200,\n 'response time < 500ms': (r) => r.timings.duration < 500,\n })\n sleep(1)\n}\n`\n\nconst SUPERCHECK_TSCONFIG = `{\n \"compilerOptions\": {\n \"target\": \"ES2022\",\n \"module\": \"ESNext\",\n \"moduleResolution\": \"bundler\",\n \"esModuleInterop\": true,\n \"strict\": true,\n \"skipLibCheck\": true,\n \"resolveJsonModule\": true,\n \"isolatedModules\": true,\n \"noEmit\": true,\n \"types\": [\"node\"]\n },\n \"include\": [\n \"supercheck.config.ts\",\n \"supercheck.config.local.ts\",\n \"_supercheck_/**/*.ts\"\n ]\n}\n`\n\nconst GITIGNORE_ADDITIONS = `\n# Supercheck CLI\nsupercheck.config.local.ts\nsupercheck.config.local.js\nsupercheck.config.local.mjs\n`\n\n/**\n * Detect the package manager used in the project.\n * Checks for lock files in order of priority.\n */\nfunction detectPackageManager(cwd: string): 'npm' | 'yarn' | 'pnpm' | 'bun' {\n if (existsSync(resolve(cwd, 'bun.lockb')) || existsSync(resolve(cwd, 'bun.lock'))) return 'bun'\n if (existsSync(resolve(cwd, 'pnpm-lock.yaml'))) return 'pnpm'\n if (existsSync(resolve(cwd, 'yarn.lock'))) return 'yarn'\n return 'npm'\n}\n\n/**\n * Get the install command for dev dependencies based on the detected package manager.\n */\nfunction getInstallCommand(pm: 'npm' | 'yarn' | 'pnpm' | 'bun', packages: string[]): string {\n const pkgs = packages.join(' ')\n switch (pm) {\n case 'bun': return `bun add -d ${pkgs}`\n case 'pnpm': return `pnpm add -D ${pkgs}`\n case 'yarn': return `yarn add -D ${pkgs}`\n case 'npm': return `npm install --save-dev ${pkgs}`\n }\n}\n\n/**\n * Ensure a package.json exists. If not, create a minimal one.\n */\nfunction ensurePackageJson(cwd: string): boolean {\n const pkgPath = resolve(cwd, 'package.json')\n if (existsSync(pkgPath)) return false\n\n const projectName = basename(cwd).toLowerCase().replace(/[^a-z0-9-]/g, '-')\n\n const minimalPkg = {\n name: projectName,\n private: true,\n type: 'module',\n scripts: {\n 'supercheck:deploy': 'supercheck deploy',\n 'supercheck:diff': 'supercheck diff',\n 'supercheck:pull': 'supercheck pull',\n },\n }\n\n writeFileSync(pkgPath, JSON.stringify(minimalPkg, null, 2) + '\\n', 'utf-8')\n return true\n}\n\n/**\n * Install dev dependencies required for Supercheck tests.\n */\nasync function installDependencies(\n cwd: string,\n pm: 'npm' | 'yarn' | 'pnpm' | 'bun',\n opts: { playwright: boolean; skipInstall: boolean },\n): Promise<void> {\n if (opts.skipInstall) {\n logger.info('Skipping dependency installation (--skip-install)')\n return\n }\n\n const devDeps: string[] = ['@supercheck/cli', 'typescript', '@types/node']\n\n if (opts.playwright) {\n devDeps.push('@playwright/test')\n }\n\n // Note: k6 is a standalone binary, not an npm package.\n // Users must install k6 separately: https://grafana.com/docs/k6/latest/set-up/install-k6/\n\n const cmd = getInstallCommand(pm, devDeps)\n\n logger.info(`Installing dependencies with ${pm}...`)\n logger.debug(`Running: ${cmd}`)\n\n await withSpinner(\n `Installing ${devDeps.length} packages...`,\n async () => {\n const { execSync } = await import('node:child_process')\n try {\n execSync(cmd, {\n cwd,\n stdio: 'pipe',\n timeout: 120_000, // 2 minute timeout\n env: { ...process.env, NODE_ENV: 'development' },\n })\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n throw new CLIError(\n `Failed to install dependencies. Run manually:\\n ${cmd}\\n\\nError: ${message}`,\n ExitCode.GeneralError,\n )\n }\n },\n { successText: 'Dependencies installed' },\n )\n}\n\nexport const initCommand = new Command('init')\n .description('Initialize a new Supercheck project with config and example tests')\n .option('--force', 'Overwrite existing config file')\n .option('--skip-install', 'Skip automatic dependency installation')\n .option('--skip-examples', 'Skip creating example test files')\n .option('--pm <manager>', 'Package manager to use (npm, yarn, pnpm, bun)')\n .action(async (options: { force?: boolean; skipInstall?: boolean; skipExamples?: boolean; pm?: string }) => {\n const cwd = process.cwd()\n\n const configPath = resolve(cwd, 'supercheck.config.ts')\n if (existsSync(configPath) && !options.force) {\n throw new CLIError(\n 'supercheck.config.ts already exists. Use --force to overwrite.',\n ExitCode.ConfigError,\n )\n }\n\n logger.newline()\n logger.header('Initializing Supercheck project...')\n logger.newline()\n\n // 1. Write supercheck.config.ts\n writeFileSync(configPath, CONFIG_TEMPLATE, 'utf-8')\n logger.success('Created supercheck.config.ts')\n\n // 2. Write tsconfig.supercheck.json for IDE IntelliSense\n const tsconfigPath = resolve(cwd, 'tsconfig.supercheck.json')\n if (!existsSync(tsconfigPath) || options.force) {\n writeFileSync(tsconfigPath, SUPERCHECK_TSCONFIG, 'utf-8')\n logger.success('Created tsconfig.supercheck.json (IDE IntelliSense)')\n }\n\n // 3. Create directory structure with .gitkeep for empty dirs\n const dirs = [\n '_supercheck_/tests',\n '_supercheck_/monitors',\n '_supercheck_/status-pages',\n ]\n\n for (const dir of dirs) {\n const dirPath = resolve(cwd, dir)\n if (!existsSync(dirPath)) {\n mkdirSync(dirPath, { recursive: true })\n }\n\n // Add .gitkeep to directories that will be empty (monitors, status-pages)\n if (dir !== '_supercheck_/tests') {\n const gitkeepPath = resolve(dirPath, '.gitkeep')\n if (!existsSync(gitkeepPath)) {\n writeFileSync(gitkeepPath, '', 'utf-8')\n }\n }\n }\n logger.success('Created _supercheck_/ directory structure')\n\n // 4. Create example test files (unless --skip-examples)\n if (!options.skipExamples) {\n const pwTestPath = resolve(cwd, '_supercheck_/tests/homepage.pw.ts')\n if (!existsSync(pwTestPath)) {\n writeFileSync(pwTestPath, EXAMPLE_PW_TEST, 'utf-8')\n logger.success('Created _supercheck_/tests/homepage.pw.ts (Playwright example)')\n }\n\n const k6TestPath = resolve(cwd, '_supercheck_/tests/load-test.k6.ts')\n if (!existsSync(k6TestPath)) {\n writeFileSync(k6TestPath, EXAMPLE_K6_TEST, 'utf-8')\n logger.success('Created _supercheck_/tests/load-test.k6.ts (k6 example)')\n }\n }\n\n // 5. Update .gitignore\n const gitignorePath = resolve(cwd, '.gitignore')\n if (existsSync(gitignorePath)) {\n const content = readFileSync(gitignorePath, 'utf-8')\n if (!content.includes('supercheck.config.local')) {\n appendFileSync(gitignorePath, GITIGNORE_ADDITIONS, 'utf-8')\n logger.success('Updated .gitignore with Supercheck entries')\n }\n }\n\n // 6. Detect package manager\n const pm = (options.pm as 'npm' | 'yarn' | 'pnpm' | 'bun') ?? detectPackageManager(cwd)\n logger.debug(`Detected package manager: ${pm}`)\n\n // 7. Ensure package.json exists\n const createdPkg = ensurePackageJson(cwd)\n if (createdPkg) {\n logger.success('Created package.json')\n }\n\n // 8. Install dependencies\n await installDependencies(cwd, pm, {\n playwright: !options.skipExamples,\n skipInstall: options.skipInstall ?? false,\n })\n\n logger.newline()\n logger.header('Supercheck project initialized!')\n logger.newline()\n logger.info('Next steps:')\n logger.info(' 1. Edit supercheck.config.ts with your org/project details')\n logger.info(' 2. Run `supercheck login --token <your-token>` to authenticate')\n logger.info(' 3. Write tests in _supercheck_/tests/ (*.pw.ts for Playwright, *.k6.ts for k6)')\n logger.info(' 4. Run `supercheck diff` to preview changes against the cloud')\n logger.info(' 5. Run `supercheck deploy` to push to Supercheck')\n logger.info(' 6. Run `supercheck pull` to sync cloud resources locally')\n logger.newline()\n logger.info('Useful commands:')\n logger.info(' supercheck pull Pull tests & config from the cloud')\n logger.info(' supercheck diff Preview local vs remote differences')\n logger.info(' supercheck deploy Push local config to Supercheck')\n logger.info(' supercheck whoami Check authentication status')\n logger.newline()\n })\n","import ora, { type Ora } from 'ora'\nimport { getOutputFormat } from '../output/formatter.js'\nimport { logger } from './logger.js'\n\n/**\n * Create a spinner for long-running operations.\n * Spinners are disabled in JSON/quiet mode for clean output.\n */\nexport function createSpinner(text: string): Ora {\n const format = getOutputFormat()\n const isInteractive = format === 'table'\n\n const spinner = ora({\n text,\n // Disable spinner in non-interactive modes\n isSilent: !isInteractive,\n // Use dots style for a clean look\n spinner: 'dots',\n })\n\n return spinner\n}\n\n/**\n * Run an async operation with a spinner.\n * Shows success/failure automatically.\n */\nexport async function withSpinner<T>(\n text: string,\n fn: () => Promise<T>,\n options?: {\n successText?: string | ((result: T) => string)\n failText?: string\n },\n): Promise<T> {\n const spinner = createSpinner(text)\n spinner.start()\n\n try {\n const result = await fn()\n const successMessage =\n typeof options?.successText === 'function'\n ? options.successText(result)\n : options?.successText ?? text.replace(/\\.\\.\\.?$/, '')\n\n spinner.succeed(successMessage)\n return result\n } catch (error) {\n const failMessage = options?.failText ?? text.replace(/\\.\\.\\.?$/, ' failed')\n spinner.fail(failMessage)\n throw error\n }\n}\n\n/**\n * Simple spinner for manual control.\n */\nexport function startSpinner(text: string): {\n succeed: (text?: string) => void\n fail: (text?: string) => void\n update: (text: string) => void\n stop: () => void\n} {\n const format = getOutputFormat()\n const isInteractive = format === 'table'\n\n if (!isInteractive) {\n // In non-interactive mode, just log and return no-ops\n logger.info(text)\n return {\n succeed: (msg) => msg && logger.success(msg),\n fail: (msg) => msg && logger.error(msg),\n update: () => {},\n stop: () => {},\n }\n }\n\n const spinner = ora({ text, spinner: 'dots' }).start()\n\n return {\n succeed: (msg) => spinner.succeed(msg),\n fail: (msg) => spinner.fail(msg),\n update: (msg) => {\n spinner.text = msg\n },\n stop: () => spinner.stop(),\n }\n}\n","import { Command } from 'commander'\nimport { createAuthenticatedClient } from '../api/authenticated-client.js'\nimport { ApiClient } from '../api/client.js'\nimport { logger } from '../utils/logger.js'\nimport { output, outputDetail } from '../output/formatter.js'\nimport { CLIError, ExitCode } from '../utils/errors.js'\nimport { parseIntStrict } from '../utils/validation.js'\nimport type { PaginatedResponse } from '../api/client.js'\nimport { getStoredBaseUrl, requireTriggerKey } from '../auth/store.js'\n\nexport const jobCommand = new Command('job')\n .description('Manage jobs')\n\njobCommand\n .command('list')\n .description('List all jobs')\n .option('--page <page>', 'Page number', '1')\n .option('--limit <limit>', 'Items per page', '50')\n .action(async (options: { page: string; limit: string }) => {\n const client = createAuthenticatedClient()\n\n const { data } = await client.get<PaginatedResponse<Record<string, unknown>>>(\n '/api/jobs',\n { page: options.page, limit: options.limit },\n )\n\n output(data.data, {\n columns: [\n { key: 'id', header: 'ID' },\n { key: 'name', header: 'Name' },\n { key: 'status', header: 'Status' },\n { key: 'cronSchedule', header: 'Schedule' },\n { key: 'createdAt', header: 'Created' },\n ],\n })\n\n if (data.pagination) {\n logger.info(\n `\\nPage ${data.pagination.page}/${data.pagination.totalPages} (${data.pagination.total} total)`,\n )\n }\n })\n\nconst keysCommand = jobCommand\n .command('keys')\n .description('Manage job trigger keys')\n\nkeysCommand\n .argument('<jobId>', 'Job ID')\n .action(async (jobId: string) => {\n const client = createAuthenticatedClient()\n const { data } = await client.get<{ success: boolean; apiKeys: Array<Record<string, unknown>> }>(\n `/api/jobs/${jobId}/api-keys`,\n )\n\n output(data.apiKeys ?? [], {\n columns: [\n { key: 'id', header: 'ID' },\n { key: 'name', header: 'Name' },\n { key: 'start', header: 'Prefix' },\n { key: 'enabled', header: 'Enabled' },\n { key: 'expiresAt', header: 'Expires' },\n { key: 'lastRequest', header: 'Last used' },\n ],\n })\n })\n\nkeysCommand\n .command('create')\n .description('Create a new trigger key for a job')\n .argument('<jobId>', 'Job ID')\n .requiredOption('--name <name>', 'Key name')\n .option('--expires-in <seconds>', 'Expiry in seconds (min 60)')\n .action(async (jobId: string, options: { name: string; expiresIn?: string }) => {\n const client = createAuthenticatedClient()\n\n const body: Record<string, unknown> = { name: options.name }\n if (options.expiresIn !== undefined) {\n body.expiresIn = parseIntStrict(options.expiresIn, '--expires-in', { min: 60 })\n }\n\n const { data } = await client.post<{ success: boolean; apiKey: Record<string, unknown> }>(\n `/api/jobs/${jobId}/api-keys`,\n body,\n )\n\n logger.success('Trigger key created')\n logger.warn('Save the `key` value now. It will only be shown once.')\n outputDetail(data.apiKey)\n })\n\nkeysCommand\n .command('delete')\n .description('Revoke a trigger key')\n .argument('<jobId>', 'Job ID')\n .argument('<keyId>', 'Key ID')\n .action(async (jobId: string, keyId: string) => {\n const client = createAuthenticatedClient()\n await client.delete(`/api/jobs/${jobId}/api-keys/${keyId}`)\n logger.success(`Trigger key ${keyId} revoked`)\n })\n\njobCommand\n .command('get <id>')\n .description('Get job details')\n .action(async (id: string) => {\n const client = createAuthenticatedClient()\n const { data } = await client.get<Record<string, unknown>>(`/api/jobs/${id}`)\n outputDetail(data)\n })\n\njobCommand\n .command('create')\n .description('Create a new job')\n .requiredOption('--name <name>', 'Job name')\n .option('--description <description>', 'Job description', '')\n .option('--schedule <cron>', 'Cron schedule expression')\n .option('--timeout <seconds>', 'Timeout in seconds', '300')\n .option('--retries <count>', 'Retry count on failure', '0')\n .action(async (options: { name: string; description: string; schedule?: string; timeout: string; retries: string }) => {\n const client = createAuthenticatedClient()\n\n const body: Record<string, unknown> = {\n name: options.name,\n description: options.description,\n timeoutSeconds: parseIntStrict(options.timeout, '--timeout', { min: 1 }),\n retryCount: parseIntStrict(options.retries, '--retries', { min: 0 }),\n config: {},\n tests: [],\n }\n if (options.schedule) body.cronSchedule = options.schedule\n\n const { data } = await client.post<Record<string, unknown>>('/api/jobs', body)\n logger.success(`Job \"${options.name}\" created (${data.id})`)\n outputDetail(data)\n })\n\njobCommand\n .command('update <id>')\n .description('Update job configuration')\n .option('--name <name>', 'Job name')\n .option('--description <description>', 'Job description')\n .option('--schedule <cron>', 'Cron schedule expression')\n .option('--timeout <seconds>', 'Timeout in seconds')\n .option('--retries <count>', 'Retry count on failure')\n .option('--status <status>', 'Job status (active, paused)')\n .action(async (id: string, options: { name?: string; description?: string; schedule?: string; timeout?: string; retries?: string; status?: string }) => {\n const client = createAuthenticatedClient()\n\n const body: Record<string, unknown> = {}\n if (options.name !== undefined) body.name = options.name\n if (options.description !== undefined) body.description = options.description\n if (options.schedule !== undefined) body.cronSchedule = options.schedule\n if (options.timeout !== undefined) body.timeoutSeconds = parseIntStrict(options.timeout, '--timeout', { min: 1 })\n if (options.retries !== undefined) body.retryCount = parseIntStrict(options.retries, '--retries', { min: 0 })\n if (options.status !== undefined) body.status = options.status\n\n if (Object.keys(body).length === 0) {\n logger.warn('No fields to update. Use --name, --description, --schedule, --timeout, --retries, or --status.')\n return\n }\n\n const { data } = await client.patch<Record<string, unknown>>(`/api/jobs/${id}`, body)\n logger.success(`Job ${id} updated`)\n outputDetail(data)\n })\n\njobCommand\n .command('delete <id>')\n .description('Delete a job')\n .option('--force', 'Skip confirmation')\n .action(async (id: string, options: { force?: boolean }) => {\n if (!options.force) {\n const { createInterface } = await import('node:readline')\n const rl = createInterface({ input: process.stdin, output: process.stdout })\n const answer = await new Promise<string>((resolve) => {\n rl.question(`Are you sure you want to delete job ${id}? (y/N) `, resolve)\n })\n rl.close()\n if (answer.toLowerCase() !== 'y') {\n logger.info('Aborted')\n return\n }\n }\n\n const client = createAuthenticatedClient()\n await client.delete(`/api/jobs/${id}`)\n logger.success(`Job ${id} deleted`)\n })\n\njobCommand\n .command('run')\n .description('Run a job immediately')\n .requiredOption('--id <id>', 'Job ID to run')\n .action(async (options: { id: string }) => {\n const client = createAuthenticatedClient()\n\n const { data: jobData } = await client.get<{ tests?: Array<{ id: string; name?: string; title?: string }> }>(\n `/api/jobs/${options.id}`,\n )\n\n const tests = Array.isArray(jobData.tests) ? jobData.tests : []\n if (tests.length === 0) {\n throw new CLIError(\n `Job ${options.id} has no tests. Add tests to the job before running it.`,\n ExitCode.GeneralError,\n )\n }\n\n const payloadTests = tests.map((test) => ({\n id: test.id,\n name: test.name ?? test.title ?? '',\n }))\n\n logger.info(`Running job ${options.id}...`)\n const { data } = await client.post<{ runId: string; message: string }>(\n '/api/jobs/run',\n { jobId: options.id, tests: payloadTests, trigger: 'manual' },\n )\n\n logger.success(`Job started. Run ID: ${data.runId}`)\n outputDetail(data as Record<string, unknown>)\n })\n\njobCommand\n .command('trigger <id>')\n .description('Trigger a job run')\n .option('--wait', 'Wait for the run to complete')\n .option('--timeout <seconds>', 'Maximum wait time in seconds', '300')\n .action(async (id: string, options: { wait?: boolean; timeout: string }) => {\n const triggerClient = new ApiClient({\n token: requireTriggerKey(),\n baseUrl: getStoredBaseUrl() ?? undefined,\n })\n\n logger.info(`Triggering job ${id}...`)\n\n const { data } = await triggerClient.post<{ runId: string; message: string }>(\n `/api/jobs/${id}/trigger`,\n )\n\n logger.success(`Job triggered. Run ID: ${data.runId}`)\n\n if (options.wait) {\n let statusClient: ReturnType<typeof createAuthenticatedClient>\n try {\n statusClient = createAuthenticatedClient()\n } catch {\n throw new CLIError(\n 'Waiting for completion requires a CLI token. Set SUPERCHECK_TOKEN (sck_live_* or sck_test_).',\n ExitCode.AuthError,\n )\n }\n\n logger.info('Waiting for run to complete...')\n const timeoutMs = parseIntStrict(options.timeout, '--timeout', { min: 1 }) * 1000\n const startTime = Date.now()\n\n while (Date.now() - startTime < timeoutMs) {\n await new Promise((resolve) => setTimeout(resolve, 3000))\n\n const { data: runData } = await statusClient.get<{ status: string }>(\n `/api/runs/${data.runId}`,\n )\n\n const status = typeof runData.status === 'string' ? runData.status.toLowerCase() : ''\n\n if (['passed', 'failed', 'error', 'blocked'].includes(status)) {\n if (status === 'passed') {\n logger.success(`Run ${data.runId} passed`)\n } else if (status === 'blocked') {\n logger.error(`Run ${data.runId} blocked`)\n throw new CLIError(`Run ${data.runId} blocked`, ExitCode.GeneralError)\n } else {\n logger.error(`Run ${data.runId} ${status}`)\n throw new CLIError(`Run ${data.runId} ${status}`, ExitCode.GeneralError)\n }\n outputDetail(runData as Record<string, unknown>)\n return\n }\n\n logger.debug(`Run status: ${status || '(unknown)'}`)\n }\n\n throw new CLIError(\n `Timed out waiting for run to complete after ${options.timeout}s`,\n ExitCode.Timeout,\n )\n }\n })\n","import { getApiClient } from './client.js'\nimport { requireAuth, getStoredBaseUrl } from '../auth/store.js'\nimport type { ApiClient } from './client.js'\n\n/**\n * Create an API client pre-configured with the stored auth token and base URL.\n * Shared across all command modules to avoid repeating this pattern.\n */\nexport function createAuthenticatedClient(): ApiClient {\n const token = requireAuth()\n const baseUrl = getStoredBaseUrl()\n return getApiClient({ token, baseUrl: baseUrl ?? undefined })\n}\n","import { CLIError, ExitCode } from './errors.js'\n\n/**\n * Parse a string to an integer with strict validation.\n *\n * Unlike bare `parseInt`, this function rejects NaN and non-finite values,\n * producing a clear CLI error message instead of sending invalid data to the API.\n *\n * @param value - The string value to parse.\n * @param name - A human-readable name for the option (used in error messages).\n * @param opts - Optional constraints.\n * @returns The parsed integer.\n * @throws {CLIError} If the value is not a valid integer or violates constraints.\n */\nexport function parseIntStrict(\n value: string,\n name: string,\n opts?: { min?: number; max?: number },\n): number {\n const parsed = parseInt(value, 10)\n if (!Number.isFinite(parsed)) {\n throw new CLIError(\n `Invalid value for ${name}: \"${value}\" is not a valid integer.`,\n ExitCode.ConfigError,\n )\n }\n if (opts?.min !== undefined && parsed < opts.min) {\n throw new CLIError(\n `Invalid value for ${name}: ${parsed} is below the minimum of ${opts.min}.`,\n ExitCode.ConfigError,\n )\n }\n if (opts?.max !== undefined && parsed > opts.max) {\n throw new CLIError(\n `Invalid value for ${name}: ${parsed} exceeds the maximum of ${opts.max}.`,\n ExitCode.ConfigError,\n )\n }\n return parsed\n}\n","import { Command } from 'commander'\nimport { createAuthenticatedClient } from '../api/authenticated-client.js'\nimport { requireAuth, getStoredBaseUrl } from '../auth/store.js'\nimport { logger } from '../utils/logger.js'\nimport { output, outputDetail } from '../output/formatter.js'\nimport { CLIError, ExitCode } from '../utils/errors.js'\nimport type { PaginatedResponse } from '../api/client.js'\nimport { CLI_VERSION } from '../version.js'\nimport { ProxyAgent } from 'undici'\n\nconst proxyAgents = new Map<string, ProxyAgent>()\n\nfunction getProxyAgent(proxyUrl: string): ProxyAgent {\n const existing = proxyAgents.get(proxyUrl)\n if (existing) return existing\n const created = new ProxyAgent(proxyUrl)\n proxyAgents.set(proxyUrl, created)\n return created\n}\n\nfunction isNoProxyMatch(url: URL, noProxyRaw: string): boolean {\n const hostname = url.hostname\n const port = url.port || (url.protocol === 'https:' ? '443' : '80')\n const entries = noProxyRaw\n .split(',')\n .map((entry) => entry.trim())\n .filter(Boolean)\n\n if (entries.includes('*')) return true\n\n for (const entry of entries) {\n const [hostPart, portPart] = entry.split(':')\n const host = hostPart.trim()\n const entryPort = portPart?.trim()\n\n if (!host) continue\n if (entryPort && entryPort !== port) continue\n\n if (host.startsWith('.')) {\n if (hostname.endsWith(host)) return true\n continue\n }\n\n if (hostname === host) return true\n if (hostname.endsWith(`.${host}`)) return true\n }\n\n return false\n}\n\nfunction getProxyEnv(url: URL): string | null {\n const noProxyRaw = process.env.NO_PROXY ?? process.env.no_proxy\n if (noProxyRaw && isNoProxyMatch(url, noProxyRaw)) {\n return null\n }\n\n if (url.protocol === 'https:') {\n return (\n process.env.HTTPS_PROXY ??\n process.env.https_proxy ??\n process.env.HTTP_PROXY ??\n process.env.http_proxy ??\n null\n )\n }\n\n if (url.protocol === 'http:') {\n return process.env.HTTP_PROXY ?? process.env.http_proxy ?? null\n }\n\n return null\n}\n\nexport const runCommand = new Command('run')\n .description('Manage runs')\n\nrunCommand\n .command('list')\n .description('List runs')\n .option('--page <page>', 'Page number', '1')\n .option('--limit <limit>', 'Items per page', '50')\n .option('--job <jobId>', 'Filter by job ID')\n .option('--status <status>', 'Filter by status (queued, running, passed, failed, error, blocked)')\n .action(async (options: { page: string; limit: string; job?: string; status?: string }) => {\n const client = createAuthenticatedClient()\n\n const params: Record<string, string> = {\n page: options.page,\n limit: options.limit,\n }\n if (options.job) params.jobId = options.job\n if (options.status) params.status = options.status\n\n const { data } = await client.get<PaginatedResponse<Record<string, unknown>>>(\n '/api/runs',\n params,\n )\n\n output(data.data, {\n columns: [\n { key: 'id', header: 'ID' },\n { key: 'jobName', header: 'Job' },\n { key: 'status', header: 'Status' },\n { key: 'trigger', header: 'Trigger' },\n { key: 'duration', header: 'Duration' },\n { key: 'startedAt', header: 'Started' },\n ],\n })\n\n if (data.pagination) {\n logger.info(\n `\\nPage ${data.pagination.page}/${data.pagination.totalPages} (${data.pagination.total} total)`,\n )\n }\n })\n\nrunCommand\n .command('get <id>')\n .description('Get run details')\n .action(async (id: string) => {\n const client = createAuthenticatedClient()\n const { data } = await client.get<Record<string, unknown>>(`/api/runs/${id}`)\n outputDetail(data)\n })\n\nrunCommand\n .command('permissions <id>')\n .description('Get run access permissions')\n .action(async (id: string) => {\n const client = createAuthenticatedClient()\n const { data } = await client.get<Record<string, unknown>>(`/api/runs/${id}/permissions`)\n outputDetail(data)\n })\n\nrunCommand\n .command('cancel <id>')\n .description('Cancel a running execution')\n .action(async (id: string) => {\n const client = createAuthenticatedClient()\n await client.post(`/api/runs/${id}/cancel`)\n logger.success(`Run ${id} cancelled`)\n })\n\nrunCommand\n .command('status <id>')\n .description('Get run status')\n .action(async (id: string) => {\n const client = createAuthenticatedClient()\n const { data } = await client.get<Record<string, unknown>>(`/api/runs/${id}/status`)\n outputDetail(data)\n })\n\nrunCommand\n .command('stream <id>')\n .description('Stream live console output from a run')\n .option('--idle-timeout <seconds>', 'Abort if no data received within this period', '60')\n .action(async (id: string, options: { idleTimeout: string }) => {\n const token = requireAuth()\n const baseUrl = getStoredBaseUrl() ?? 'https://app.supercheck.io'\n const idleTimeoutMs = Math.max(Number(options.idleTimeout) || 60, 10) * 1000\n\n const url = `${baseUrl}/api/runs/${id}/stream`\n const parsedUrl = new URL(url)\n\n logger.info(`Streaming output for run ${id}...`)\n logger.newline()\n\n // Connection timeout for initial SSE handshake (30s)\n const controller = new AbortController()\n const connectTimeout = setTimeout(() => controller.abort(), 30_000)\n\n try {\n const proxy = getProxyEnv(parsedUrl)\n const response = await fetch(url, {\n headers: {\n 'Authorization': `Bearer ${token}`,\n 'Accept': 'text/event-stream',\n 'User-Agent': `supercheck-cli/${CLI_VERSION}`,\n },\n ...(proxy ? { dispatcher: getProxyAgent(proxy) } : {}),\n signal: controller.signal,\n })\n\n clearTimeout(connectTimeout)\n\n if (!response.ok) {\n throw new CLIError(`Failed to connect to stream: ${response.status}`, ExitCode.ApiError)\n }\n\n const reader = response.body?.getReader()\n if (!reader) {\n throw new CLIError('No response body for SSE stream', ExitCode.ApiError)\n }\n\n const decoder = new TextDecoder()\n let buffer = ''\n let currentEvent = ''\n\n // Idle timeout: abort if no data received within the configured period\n let idleTimer: ReturnType<typeof setTimeout> | undefined\n const resetIdleTimer = () => {\n if (idleTimer) clearTimeout(idleTimer)\n idleTimer = setTimeout(() => controller.abort(), idleTimeoutMs)\n }\n resetIdleTimer()\n\n while (true) {\n const { done, value } = await reader.read()\n if (done) break\n\n resetIdleTimer()\n\n buffer += decoder.decode(value, { stream: true })\n const lines = buffer.split('\\n')\n buffer = lines.pop() ?? ''\n\n for (const line of lines) {\n // SSE comment (keepalive) — ignore\n if (line.startsWith(':')) continue\n\n // SSE event type\n if (line.startsWith('event: ')) {\n currentEvent = line.slice(7).trim()\n continue\n }\n\n // SSE retry directive — ignore\n if (line.startsWith('retry:')) continue\n\n // SSE data payload\n if (line.startsWith('data: ')) {\n const data = line.slice(6)\n try {\n const parsed = JSON.parse(data)\n switch (currentEvent) {\n case 'console':\n // Server sends { line: \"...\" } for console output\n if (parsed.line !== undefined) {\n process.stdout.write(parsed.line + '\\n')\n }\n break\n case 'complete':\n // Server sends { status: \"completed\" | \"error\" | ... }\n logger.newline()\n if (parsed.status === 'completed' || parsed.status === 'success') {\n logger.success(`Run ${id} ${parsed.status}`)\n } else {\n logger.warn(`Run ${id} finished with status: ${parsed.status}`)\n }\n if (idleTimer) clearTimeout(idleTimer)\n return\n case 'ready':\n logger.debug(`Stream ready for run ${parsed.runId ?? id}`)\n break\n case 'error':\n logger.error(`Stream error: ${parsed.message ?? JSON.stringify(parsed)}`)\n break\n case 'heartbeat':\n // Server keepalive — no action needed\n break\n default:\n // Unknown or unnamed event — show status/output if present\n if (parsed.output) {\n process.stdout.write(parsed.output)\n } else if (parsed.status) {\n logger.info(`Status: ${parsed.status}`)\n }\n break\n }\n } catch {\n // Raw text output\n process.stdout.write(data)\n }\n // Reset event type after processing data\n currentEvent = ''\n continue\n }\n\n // Empty line marks end of SSE event block — reset event type\n if (line.trim() === '') {\n currentEvent = ''\n }\n }\n }\n\n if (idleTimer) clearTimeout(idleTimer)\n } catch (err) {\n if (err instanceof CLIError) throw err\n if (err instanceof Error && err.name === 'AbortError') {\n throw new CLIError(\n `Stream timed out (no data received for ${Math.round(idleTimeoutMs / 1000)}s)`,\n ExitCode.Timeout,\n )\n }\n throw new CLIError(\n `Stream error: ${err instanceof Error ? err.message : String(err)}`,\n ExitCode.ApiError,\n )\n }\n })\n","import { Command } from 'commander'\nimport { createAuthenticatedClient } from '../api/authenticated-client.js'\nimport { logger } from '../utils/logger.js'\nimport { output, outputDetail } from '../output/formatter.js'\nimport { CLIError, ExitCode } from '../utils/errors.js'\nimport type { PaginatedResponse } from '../api/client.js'\nimport { requireAuth, getStoredBaseUrl } from '../auth/store.js'\nimport { CLI_VERSION } from '../version.js'\nimport { ProxyAgent } from 'undici'\nimport { Buffer } from 'node:buffer'\n\nconst proxyAgents = new Map<string, ProxyAgent>()\n\nfunction getProxyAgent(proxyUrl: string): ProxyAgent {\n const existing = proxyAgents.get(proxyUrl)\n if (existing) return existing\n const created = new ProxyAgent(proxyUrl)\n proxyAgents.set(proxyUrl, created)\n return created\n}\n\nfunction isNoProxyMatch(url: URL, noProxyRaw: string): boolean {\n const hostname = url.hostname\n const port = url.port || (url.protocol === 'https:' ? '443' : '80')\n const entries = noProxyRaw\n .split(',')\n .map((entry) => entry.trim())\n .filter(Boolean)\n\n if (entries.includes('*')) return true\n\n for (const entry of entries) {\n const [hostPart, portPart] = entry.split(':')\n const host = hostPart.trim()\n const entryPort = portPart?.trim()\n\n if (!host) continue\n if (entryPort && entryPort !== port) continue\n\n if (host.startsWith('.')) {\n if (hostname.endsWith(host)) return true\n continue\n }\n\n if (hostname === host) return true\n if (hostname.endsWith(`.${host}`)) return true\n }\n\n return false\n}\n\nfunction getProxyEnv(url: URL): string | null {\n const noProxyRaw = process.env.NO_PROXY ?? process.env.no_proxy\n if (noProxyRaw && isNoProxyMatch(url, noProxyRaw)) {\n return null\n }\n\n if (url.protocol === 'https:') {\n return (\n process.env.HTTPS_PROXY ??\n process.env.https_proxy ??\n process.env.HTTP_PROXY ??\n process.env.http_proxy ??\n null\n )\n }\n\n if (url.protocol === 'http:') {\n return process.env.HTTP_PROXY ?? process.env.http_proxy ?? null\n }\n\n return null\n}\n\nfunction normalizeTestType(input: string): string {\n const normalized = input.trim().toLowerCase()\n if (normalized === 'k6') return 'performance'\n if (normalized === 'performance') return 'performance'\n if (normalized === 'playwright') return 'browser'\n if (normalized === 'browser') return 'browser'\n return normalized\n}\n\nexport const testCommand = new Command('test')\n .description('Manage tests')\n\ntestCommand\n .command('list')\n .description('List all tests')\n .option('--page <page>', 'Page number', '1')\n .option('--limit <limit>', 'Items per page', '50')\n .option('--search <query>', 'Search by title')\n .option('--type <type>', 'Filter by type (playwright, k6)')\n .action(async (options: { page: string; limit: string; search?: string; type?: string }) => {\n const client = createAuthenticatedClient()\n\n const params: Record<string, string> = {\n page: options.page,\n limit: options.limit,\n }\n if (options.search) params.search = options.search\n if (options.type) params.type = normalizeTestType(options.type)\n\n const { data } = await client.get<PaginatedResponse<Record<string, unknown>>>(\n '/api/tests',\n params,\n )\n\n output(data.data, {\n columns: [\n { key: 'id', header: 'ID' },\n { key: 'title', header: 'Title' },\n { key: 'type', header: 'Type' },\n { key: 'createdAt', header: 'Created' },\n ],\n })\n\n if (data.pagination) {\n logger.info(\n `\\nPage ${data.pagination.page}/${data.pagination.totalPages} (${data.pagination.total} total)`,\n )\n }\n })\n\ntestCommand\n .command('get <id>')\n .description('Get test details')\n .option('--include-script', 'Include the test script content')\n .action(async (id: string, options: { includeScript?: boolean }) => {\n const client = createAuthenticatedClient()\n const params: Record<string, string> = {}\n if (options.includeScript) params.includeScript = 'true'\n\n const { data } = await client.get<Record<string, unknown>>(`/api/tests/${id}`, params)\n outputDetail(data)\n })\n\ntestCommand\n .command('create')\n .description('Create a new test')\n .requiredOption('--title <title>', 'Test title')\n .requiredOption('--file <path>', 'Path to the test script file')\n .option('--type <type>', 'Test type (playwright, k6)', 'playwright')\n .option('--description <description>', 'Test description')\n .action(async (options: { title: string; file: string; type: string; description?: string }) => {\n const { readFileSync } = await import('node:fs')\n const { resolve } = await import('node:path')\n\n const filePath = resolve(process.cwd(), options.file)\n let script: string\n\n try {\n script = readFileSync(filePath, 'utf-8')\n } catch {\n throw new CLIError(`Cannot read file: ${filePath}`, ExitCode.GeneralError)\n }\n\n const client = createAuthenticatedClient()\n\n const encodedScript = Buffer.from(script, 'utf-8').toString('base64')\n\n const body: Record<string, unknown> = {\n title: options.title,\n script: encodedScript,\n type: normalizeTestType(options.type),\n }\n if (options.description) body.description = options.description\n\n const { data } = await client.post<Record<string, unknown>>('/api/tests', body)\n const createdId =\n (data as { test?: { id?: string } }).test?.id ??\n (data as { id?: string }).id\n logger.success(`Test \"${options.title}\" created${createdId ? ` (${createdId})` : ''}`)\n outputDetail(data)\n })\n\ntestCommand\n .command('update <id>')\n .description('Update a test')\n .option('--title <title>', 'Test title')\n .option('--file <path>', 'Path to updated test script')\n .option('--description <description>', 'Test description')\n .action(async (id: string, options: { title?: string; file?: string; description?: string }) => {\n const client = createAuthenticatedClient()\n\n const body: Record<string, unknown> = {}\n if (options.title !== undefined) body.title = options.title\n if (options.description !== undefined) body.description = options.description\n\n if (options.file) {\n const { readFileSync } = await import('node:fs')\n const { resolve } = await import('node:path')\n const filePath = resolve(process.cwd(), options.file)\n try {\n const raw = readFileSync(filePath, 'utf-8')\n body.script = Buffer.from(raw, 'utf-8').toString('base64')\n } catch {\n throw new CLIError(`Cannot read file: ${filePath}`, ExitCode.GeneralError)\n }\n }\n\n if (Object.keys(body).length === 0) {\n logger.warn('No fields to update. Use --title, --file, or --description.')\n return\n }\n\n const { data } = await client.patch<Record<string, unknown>>(`/api/tests/${id}`, body)\n logger.success(`Test ${id} updated`)\n outputDetail(data)\n })\n\ntestCommand\n .command('delete <id>')\n .description('Delete a test')\n .option('--force', 'Skip confirmation')\n .action(async (id: string, options: { force?: boolean }) => {\n if (!options.force) {\n const { createInterface } = await import('node:readline')\n const rl = createInterface({ input: process.stdin, output: process.stdout })\n const answer = await new Promise<string>((resolve) => {\n rl.question(`Are you sure you want to delete test ${id}? (y/N) `, resolve)\n })\n rl.close()\n if (answer.toLowerCase() !== 'y') {\n logger.info('Aborted')\n return\n }\n }\n\n const client = createAuthenticatedClient()\n await client.delete(`/api/tests/${id}`)\n logger.success(`Test ${id} deleted`)\n })\n\ntestCommand\n .command('execute <id>')\n .description('Execute a test immediately')\n .option('--location <location>', 'Execution location (k6 only)')\n .action(async (id: string, options: { location?: string }) => {\n const client = createAuthenticatedClient()\n const body: Record<string, unknown> = {}\n if (options.location) body.location = options.location\n const { data } = await client.post<Record<string, unknown>>(`/api/tests/${id}/execute`, body)\n outputDetail(data)\n })\n\ntestCommand\n .command('tags <id>')\n .description('Get test tags')\n .action(async (id: string) => {\n const client = createAuthenticatedClient()\n const { data } = await client.get<Record<string, unknown>[]>(`/api/tests/${id}/tags`)\n output(data, {\n columns: [\n { key: 'id', header: 'ID' },\n { key: 'name', header: 'Name' },\n { key: 'color', header: 'Color' },\n ],\n })\n })\n\ntestCommand\n .command('validate')\n .description('Validate a test script')\n .requiredOption('--file <path>', 'Path to the test script file')\n .option('--type <type>', 'Test type (playwright, k6)', 'playwright')\n .action(async (options: { file: string; type: string }) => {\n const { readFileSync } = await import('node:fs')\n const { resolve } = await import('node:path')\n\n const filePath = resolve(process.cwd(), options.file)\n let script: string\n\n try {\n script = readFileSync(filePath, 'utf-8')\n } catch {\n throw new CLIError(`Cannot read file: ${filePath}`, ExitCode.GeneralError)\n }\n\n const client = createAuthenticatedClient()\n\n const { data } = await client.post<{ valid: boolean; errors?: string[] }>(\n '/api/validate-script',\n { script, testType: normalizeTestType(options.type) },\n )\n\n if (data.valid) {\n logger.success(`Script is valid (${options.type})`)\n } else {\n logger.error('Script validation failed:')\n if (data.errors) {\n for (const err of data.errors) {\n logger.error(` - ${err}`)\n }\n }\n throw new CLIError('Script validation failed', ExitCode.GeneralError)\n }\n })\n\ntestCommand\n .command('status <id>')\n .description('Stream live status events for a test')\n .option('--idle-timeout <seconds>', 'Abort if no data received within this period', '60')\n .action(async (id: string, options: { idleTimeout: string }) => {\n const token = requireAuth()\n const baseUrl = getStoredBaseUrl() ?? 'https://app.supercheck.io'\n const idleTimeoutMs = Math.max(Number(options.idleTimeout) || 60, 10) * 1000\n\n const url = `${baseUrl}/api/test-status/events/${id}`\n const parsedUrl = new URL(url)\n\n logger.info(`Streaming status for test ${id}...`)\n logger.newline()\n\n const controller = new AbortController()\n const connectTimeout = setTimeout(() => controller.abort(), 30_000)\n\n try {\n const proxy = getProxyEnv(parsedUrl)\n const response = await fetch(url, {\n headers: {\n 'Authorization': `Bearer ${token}`,\n 'Accept': 'text/event-stream',\n 'User-Agent': `supercheck-cli/${CLI_VERSION}`,\n },\n ...(proxy ? { dispatcher: getProxyAgent(proxy) } : {}),\n signal: controller.signal,\n })\n\n clearTimeout(connectTimeout)\n\n if (!response.ok) {\n throw new CLIError(`Failed to connect to status stream: ${response.status}`, ExitCode.ApiError)\n }\n\n const reader = response.body?.getReader()\n if (!reader) {\n throw new CLIError('No response body for SSE stream', ExitCode.ApiError)\n }\n\n const decoder = new TextDecoder()\n let buffer = ''\n\n let idleTimer: ReturnType<typeof setTimeout> | undefined\n const resetIdleTimer = () => {\n if (idleTimer) clearTimeout(idleTimer)\n idleTimer = setTimeout(() => controller.abort(), idleTimeoutMs)\n }\n resetIdleTimer()\n\n while (true) {\n const { done, value } = await reader.read()\n if (done) break\n\n resetIdleTimer()\n\n buffer += decoder.decode(value, { stream: true })\n const lines = buffer.split('\\n')\n buffer = lines.pop() ?? ''\n\n for (const line of lines) {\n if (line.startsWith(':')) continue\n if (line.startsWith('data: ')) {\n const payload = line.slice(6)\n try {\n const parsed = JSON.parse(payload) as Record<string, unknown>\n outputDetail(parsed)\n } catch {\n process.stdout.write(payload + '\\n')\n }\n }\n }\n }\n\n if (idleTimer) clearTimeout(idleTimer)\n } catch (err) {\n if (err instanceof CLIError) throw err\n if (err instanceof Error && err.name === 'AbortError') {\n throw new CLIError(\n `Stream timed out (no data received for ${Math.round(idleTimeoutMs / 1000)}s)`,\n ExitCode.Timeout,\n )\n }\n throw new CLIError(\n `Stream error: ${err instanceof Error ? err.message : String(err)}`,\n ExitCode.ApiError,\n )\n }\n })\n","import { Command } from 'commander'\nimport { createAuthenticatedClient } from '../api/authenticated-client.js'\nimport { logger } from '../utils/logger.js'\nimport { output, outputDetail } from '../output/formatter.js'\nimport type { PaginatedResponse } from '../api/client.js'\n\nexport const monitorCommand = new Command('monitor')\n .description('Manage monitors')\n\nmonitorCommand\n .command('list')\n .description('List all monitors')\n .option('--page <page>', 'Page number', '1')\n .option('--limit <limit>', 'Items per page', '50')\n .action(async (options: { page: string; limit: string }) => {\n const client = createAuthenticatedClient()\n\n const { data } = await client.get<PaginatedResponse<Record<string, unknown>>>(\n '/api/monitors',\n { page: options.page, limit: options.limit },\n )\n\n output(data.data, {\n columns: [\n { key: 'id', header: 'ID' },\n { key: 'name', header: 'Name' },\n { key: 'type', header: 'Type' },\n { key: 'status', header: 'Status' },\n { key: 'frequencyMinutes', header: 'Freq (min)' },\n ],\n })\n\n if (data.pagination) {\n logger.info(\n `\\nPage ${data.pagination.page}/${data.pagination.totalPages} (${data.pagination.total} total)`,\n )\n }\n })\n\nmonitorCommand\n .command('get <id>')\n .description('Get monitor details')\n .action(async (id: string) => {\n const client = createAuthenticatedClient()\n const { data } = await client.get<Record<string, unknown>>(`/api/monitors/${id}`)\n outputDetail(data)\n })\n\nmonitorCommand\n .command('results <id>')\n .description('Get monitor check results')\n .option('--limit <limit>', 'Number of results', '20')\n .action(async (id: string, options: { limit: string }) => {\n const client = createAuthenticatedClient()\n const { data } = await client.get<{ results: Record<string, unknown>[] }>(\n `/api/monitors/${id}/results`,\n { limit: options.limit },\n )\n\n output(data.results, {\n columns: [\n { key: 'timestamp', header: 'Time' },\n { key: 'status', header: 'Status' },\n { key: 'responseTime', header: 'Response (ms)' },\n { key: 'location', header: 'Location' },\n ],\n })\n })\n\nmonitorCommand\n .command('stats <id>')\n .description('Get monitor performance statistics')\n .action(async (id: string) => {\n const client = createAuthenticatedClient()\n const { data } = await client.get<Record<string, unknown>>(`/api/monitors/${id}/stats`)\n outputDetail(data)\n })\n\nmonitorCommand\n .command('status <id>')\n .description('Get current monitor status')\n .action(async (id: string) => {\n const client = createAuthenticatedClient()\n const { data } = await client.get<Record<string, unknown>>(`/api/monitors/${id}`)\n const statusInfo: Record<string, unknown> = {\n id: data.id,\n name: data.name,\n status: data.status,\n lastCheckAt: data.lastCheckAt,\n responseTime: data.responseTime,\n }\n outputDetail(statusInfo)\n })\n\nmonitorCommand\n .command('create')\n .description('Create a new monitor')\n .requiredOption('--name <name>', 'Monitor name')\n .requiredOption('--url <url>', 'URL to monitor')\n .option('--type <type>', 'Monitor type (http_request, website, ping_host, port_check, synthetic_test)', 'http_request')\n .option('--interval <seconds>', 'Check interval in seconds', '300')\n .option('--timeout <seconds>', 'Request timeout in seconds', '30')\n .option('--method <method>', 'HTTP method (GET, POST, HEAD)', 'GET')\n .action(async (options: { name: string; url: string; type: string; interval: string; timeout: string; method: string }) => {\n const client = createAuthenticatedClient()\n\n const intervalSeconds = parseInt(options.interval, 10)\n if (!Number.isFinite(intervalSeconds) || intervalSeconds <= 0) {\n logger.error('Invalid --interval value: must be a positive number of seconds')\n return\n }\n const frequencyMinutes = Math.max(1, Math.ceil(intervalSeconds / 60))\n\n const body: Record<string, unknown> = {\n name: options.name,\n target: options.url,\n type: options.type,\n frequencyMinutes,\n config: {\n timeout: parseInt(options.timeout, 10) * 1000, // API expects milliseconds\n method: options.method,\n },\n }\n\n const { data } = await client.post<Record<string, unknown>>('/api/monitors', body)\n logger.success(`Monitor \"${options.name}\" created (${data.id})`)\n outputDetail(data)\n })\n\nmonitorCommand\n .command('update <id>')\n .description('Update a monitor')\n .option('--name <name>', 'Monitor name')\n .option('--url <url>', 'URL to monitor')\n .option('--interval <seconds>', 'Check interval in seconds')\n .option('--timeout <seconds>', 'Request timeout in seconds')\n .option('--method <method>', 'HTTP method')\n .option('--active <boolean>', 'Enable or disable monitor (true/false)')\n .action(async (id: string, options: { name?: string; url?: string; interval?: string; timeout?: string; method?: string; active?: string }) => {\n const client = createAuthenticatedClient()\n\n const body: Record<string, unknown> = {}\n if (options.name !== undefined) body.name = options.name\n if (options.url !== undefined) body.target = options.url\n if (options.interval !== undefined) {\n const intervalSeconds = parseInt(options.interval, 10)\n if (!Number.isFinite(intervalSeconds) || intervalSeconds <= 0) {\n logger.error('Invalid --interval value: must be a positive number of seconds')\n return\n }\n body.frequencyMinutes = Math.max(1, Math.ceil(intervalSeconds / 60))\n }\n if (options.active !== undefined) body.enabled = options.active === 'true'\n\n // timeout and method go in config object\n const config: Record<string, unknown> = {}\n if (options.timeout !== undefined) config.timeout = parseInt(options.timeout, 10) * 1000\n if (options.method !== undefined) config.method = options.method\n if (Object.keys(config).length > 0) body.config = config\n\n if (Object.keys(body).length === 0) {\n logger.warn('No fields to update. Use --name, --url, --interval, --timeout, --method, or --active.')\n return\n }\n\n const { data } = await client.patch<Record<string, unknown>>(`/api/monitors/${id}`, body)\n logger.success(`Monitor ${id} updated`)\n outputDetail(data)\n })\n\nmonitorCommand\n .command('delete <id>')\n .description('Delete a monitor')\n .option('--force', 'Skip confirmation')\n .action(async (id: string, options: { force?: boolean }) => {\n if (!options.force) {\n const { createInterface } = await import('node:readline')\n const rl = createInterface({ input: process.stdin, output: process.stdout })\n const answer = await new Promise<string>((resolve) => {\n rl.question(`Are you sure you want to delete monitor ${id}? (y/N) `, resolve)\n })\n rl.close()\n if (answer.toLowerCase() !== 'y') {\n logger.info('Aborted')\n return\n }\n }\n\n const client = createAuthenticatedClient()\n await client.delete(`/api/monitors/${id}`)\n logger.success(`Monitor ${id} deleted`)\n })\n","import { Command } from 'commander'\nimport { createAuthenticatedClient } from '../api/authenticated-client.js'\nimport { logger } from '../utils/logger.js'\nimport { output, outputDetail } from '../output/formatter.js'\nimport { CLIError, ExitCode } from '../utils/errors.js'\n\ninterface Variable {\n id: string\n key: string\n value?: string\n isSecret: boolean\n description?: string | null\n createdAt?: string\n}\n\nexport const varCommand = new Command('var')\n .description('Manage project variables')\n\nvarCommand\n .command('list')\n .description('List all variables')\n .action(async () => {\n const client = createAuthenticatedClient()\n const { data } = await client.get<Variable[]>('/api/variables')\n\n output(data as unknown as Record<string, unknown>[], {\n columns: [\n { key: 'id', header: 'ID' },\n { key: 'key', header: 'Key' },\n { key: 'isSecret', header: 'Secret' },\n { key: 'createdAt', header: 'Created' },\n ],\n })\n })\n\nvarCommand\n .command('get <key>')\n .description('Get a variable by key name')\n .action(async (key: string) => {\n const client = createAuthenticatedClient()\n const { data: variables } = await client.get<Variable[]>('/api/variables')\n\n const variable = variables.find((v) => v.key === key)\n if (!variable) {\n throw new CLIError(`Variable \"${key}\" not found`, ExitCode.GeneralError)\n }\n\n outputDetail(variable as unknown as Record<string, unknown>)\n })\n\nvarCommand\n .command('set <key> <value>')\n .description('Create or update a variable')\n .option('--secret', 'Mark as secret (value will be encrypted)')\n .option('--description <description>', 'Variable description')\n .action(async (key: string, value: string, options: { secret?: boolean; description?: string }) => {\n const client = createAuthenticatedClient()\n\n // Check if variable exists\n const { data: variables } = await client.get<Variable[]>('/api/variables')\n const existing = variables.find((v) => v.key === key)\n\n if (existing) {\n await client.put(`/api/variables/${existing.id}`, {\n key,\n value,\n isSecret: options.secret ?? existing.isSecret,\n ...(options.description !== undefined && { description: options.description }),\n })\n logger.success(`Variable \"${key}\" updated`)\n } else {\n await client.post('/api/variables', {\n key,\n value,\n isSecret: options.secret ?? false,\n ...(options.description !== undefined && { description: options.description }),\n })\n logger.success(`Variable \"${key}\" created`)\n }\n })\n\nvarCommand\n .command('delete <key>')\n .description('Delete a variable')\n .action(async (key: string) => {\n const client = createAuthenticatedClient()\n\n const { data: variables } = await client.get<Variable[]>('/api/variables')\n const variable = variables.find((v) => v.key === key)\n\n if (!variable) {\n throw new CLIError(`Variable \"${key}\" not found`, ExitCode.GeneralError)\n }\n\n await client.delete(`/api/variables/${variable.id}`)\n logger.success(`Variable \"${key}\" deleted`)\n })\n","import { Command } from 'commander'\nimport { createAuthenticatedClient } from '../api/authenticated-client.js'\nimport { logger } from '../utils/logger.js'\nimport { output } from '../output/formatter.js'\n\nexport const tagCommand = new Command('tag')\n .description('Manage tags')\n\ntagCommand\n .command('list')\n .description('List all tags')\n .action(async () => {\n const client = createAuthenticatedClient()\n const { data } = await client.get<Record<string, unknown>[]>('/api/tags')\n\n output(data, {\n columns: [\n { key: 'id', header: 'ID' },\n { key: 'name', header: 'Name' },\n { key: 'color', header: 'Color' },\n ],\n })\n })\n\ntagCommand\n .command('create <name>')\n .description('Create a new tag')\n .option('--color <color>', 'Tag color (hex)')\n .action(async (name: string, options: { color?: string }) => {\n const client = createAuthenticatedClient()\n const { data } = await client.post<Record<string, unknown>>('/api/tags', {\n name,\n color: options.color,\n })\n\n logger.success(`Tag \"${name}\" created (${data.id})`)\n })\n\ntagCommand\n .command('delete <id>')\n .description('Delete a tag')\n .action(async (id: string) => {\n const client = createAuthenticatedClient()\n await client.delete(`/api/tags/${id}`)\n logger.success(`Tag ${id} deleted`)\n })\n","import { Command } from 'commander'\nimport { createAuthenticatedClient } from '../api/authenticated-client.js'\nimport { loadConfig } from '../config/loader.js'\nimport { logger } from '../utils/logger.js'\nimport {\n reconcile,\n formatChangePlan,\n} from '../utils/reconcile.js'\nimport { buildLocalResources, fetchRemoteResources } from '../utils/resources.js'\n\n\nexport const diffCommand = new Command('diff')\n .description('Preview changes between local config and the remote Supercheck project')\n .option('--config <path>', 'Path to config file')\n .action(async (options: { config?: string }) => {\n const cwd = process.cwd()\n const { config } = await loadConfig({ cwd, configPath: options.config })\n const client = createAuthenticatedClient()\n\n logger.info('Comparing local config with remote project...')\n logger.newline()\n\n const localResources = buildLocalResources(config, cwd)\n const remoteResources = await fetchRemoteResources(client)\n\n logger.debug(`Local: ${localResources.length} resources, Remote: ${remoteResources.length} resources`)\n\n const changes = reconcile(localResources, remoteResources)\n formatChangePlan(changes)\n })\n","import pc from 'picocolors'\nimport { logger } from './logger.js'\n\n/**\n * Represents a resource defined in the local config file.\n */\nexport interface LocalResource {\n /** Database UUID if this resource already exists on the server. Absent for new resources. */\n id?: string\n type: 'test' | 'monitor' | 'job' | 'variable' | 'tag' | 'statusPage'\n name: string\n definition: Record<string, unknown>\n}\n\n/**\n * Represents a resource fetched from the remote Supercheck API.\n */\nexport interface RemoteResource {\n id: string\n type: 'test' | 'monitor' | 'job' | 'variable' | 'tag' | 'statusPage'\n name: string\n raw: Record<string, unknown>\n}\n\nexport type ChangeAction = 'create' | 'update' | 'delete' | 'no-change'\n\nexport interface ResourceChange {\n action: ChangeAction\n type: LocalResource['type']\n id?: string\n name: string\n local?: LocalResource\n remote?: RemoteResource\n details?: string[]\n}\n\n/**\n * Compare local config resources against remote API resources\n * using id-based reconciliation.\n *\n * - Resources with an `id` in local config are matched against remote by `type:id`.\n * - Resources without an `id` in local config are treated as new (create).\n * - Remote resources whose `id` does not appear in any local resource are candidates for deletion.\n */\nexport function reconcile(\n local: LocalResource[],\n remote: RemoteResource[],\n): ResourceChange[] {\n const changes: ResourceChange[] = []\n\n // Build lookup maps by type + id\n const remoteByKey = new Map<string, RemoteResource>()\n for (const r of remote) {\n remoteByKey.set(`${r.type}:${r.id}`, r)\n }\n\n const localByKey = new Map<string, LocalResource>()\n for (const l of local) {\n if (l.id) {\n localByKey.set(`${l.type}:${l.id}`, l)\n }\n }\n\n // Detect creates and updates\n for (const l of local) {\n if (!l.id) {\n // No id = new resource to create\n changes.push({\n action: 'create',\n type: l.type,\n name: l.name,\n local: l,\n })\n continue\n }\n\n const key = `${l.type}:${l.id}`\n const r = remoteByKey.get(key)\n\n if (!r) {\n // Has id but not found on remote — treat as create (might have been deleted server-side)\n changes.push({\n action: 'create',\n type: l.type,\n id: l.id,\n name: l.name,\n local: l,\n })\n } else {\n const diffs = diffFields(l.definition, r.raw)\n if (diffs.length > 0) {\n changes.push({\n action: 'update',\n type: l.type,\n id: l.id,\n name: l.name,\n local: l,\n remote: r,\n details: diffs,\n })\n } else {\n changes.push({\n action: 'no-change',\n type: l.type,\n id: l.id,\n name: l.name,\n local: l,\n remote: r,\n })\n }\n }\n }\n\n // Detect deletes — remote resources NOT in local config\n for (const r of remote) {\n const key = `${r.type}:${r.id}`\n if (!localByKey.has(key)) {\n changes.push({\n action: 'delete',\n type: r.type,\n id: r.id,\n name: r.name,\n remote: r,\n })\n }\n }\n\n return changes\n}\n\n/**\n * Produce a stable JSON string with sorted keys to avoid false diffs\n * caused by different key insertion order in objects.\n */\nfunction stableStringify(value: unknown): string {\n return JSON.stringify(value, (_, v) => {\n if (v && typeof v === 'object' && !Array.isArray(v)) {\n return Object.keys(v).sort().reduce<Record<string, unknown>>((sorted, k) => {\n sorted[k] = (v as Record<string, unknown>)[k]\n return sorted\n }, {})\n }\n return v\n })\n}\n\n/**\n * Shallow diff between local definition fields and remote raw fields.\n * Returns a list of human-readable change descriptions.\n */\nfunction diffFields(local: Record<string, unknown>, remote: Record<string, unknown>): string[] {\n const diffs: string[] = []\n // Only compare fields present in the local definition\n for (const [key, localVal] of Object.entries(local)) {\n // Skip internal/metadata fields\n if (['id', 'createdAt', 'updatedAt', 'projectId', 'organizationId', 'createdByUserId'].includes(key)) continue\n\n const remoteVal = remote[key]\n if (stableStringify(localVal) !== stableStringify(remoteVal)) {\n diffs.push(`${key}: ${JSON.stringify(remoteVal)} -> ${JSON.stringify(localVal)}`)\n }\n }\n return diffs\n}\n\n/**\n * Format a change plan for display in the terminal.\n */\nexport function formatChangePlan(changes: ResourceChange[]): void {\n const creates = changes.filter((c) => c.action === 'create')\n const updates = changes.filter((c) => c.action === 'update')\n const deletes = changes.filter((c) => c.action === 'delete')\n const unchanged = changes.filter((c) => c.action === 'no-change')\n\n logger.newline()\n logger.header('Change Plan')\n logger.newline()\n\n if (creates.length > 0) {\n logger.info(pc.green(` + ${creates.length} to create`))\n for (const c of creates) {\n logger.info(pc.green(` + ${c.type}/${c.name}`))\n }\n }\n\n if (updates.length > 0) {\n logger.info(pc.yellow(` ~ ${updates.length} to update`))\n for (const c of updates) {\n logger.info(pc.yellow(` ~ ${c.type}/${c.name} (${c.id})`))\n if (c.details) {\n for (const d of c.details) {\n logger.info(pc.gray(` ${d}`))\n }\n }\n }\n }\n\n if (deletes.length > 0) {\n logger.info(pc.red(` - ${deletes.length} to delete`))\n for (const c of deletes) {\n logger.info(pc.red(` - ${c.type}/${c.name} (${c.id})`))\n }\n }\n\n if (unchanged.length > 0) {\n logger.info(pc.gray(` = ${unchanged.length} unchanged`))\n }\n\n logger.newline()\n\n const totalChanges = creates.length + updates.length + deletes.length\n if (totalChanges === 0) {\n logger.success('No changes detected. Everything is in sync.')\n } else {\n logger.info(`${pc.bold(String(totalChanges))} change(s) detected.`)\n }\n logger.newline()\n}\n","import { Command } from 'commander'\nimport { createAuthenticatedClient } from '../api/authenticated-client.js'\nimport { loadConfig } from '../config/loader.js'\nimport { logger } from '../utils/logger.js'\nimport {\n reconcile,\n formatChangePlan,\n type ResourceChange,\n} from '../utils/reconcile.js'\nimport { CLIError, ExitCode } from '../utils/errors.js'\nimport { buildLocalResources, fetchRemoteResources, getApiEndpoint } from '../utils/resources.js'\nimport pc from 'picocolors'\n\n\n/**\n * Apply a single resource change via the API.\n */\nasync function applyChange(\n client: import('../api/client.js').ApiClient,\n change: ResourceChange,\n): Promise<{ success: boolean; error?: string }> {\n try {\n const endpoint = getApiEndpoint(change.type)\n\n switch (change.action) {\n case 'create': {\n const body = { ...change.local!.definition }\n await client.post(endpoint, body)\n return { success: true }\n }\n case 'update': {\n const id = change.id ?? change.remote!.id\n // Destructure to exclude id — it's used for matching, not updating\n const { id: _id, ...body } = change.local!.definition\n await client.put(`${endpoint}/${id}`, body)\n return { success: true }\n }\n case 'delete': {\n const id = change.id ?? change.remote!.id\n await client.delete(`${endpoint}/${id}`)\n return { success: true }\n }\n default:\n return { success: true }\n }\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n return { success: false, error: message }\n }\n}\n\nexport const deployCommand = new Command('deploy')\n .description('Push local config resources to the Supercheck project')\n .option('--config <path>', 'Path to config file')\n .option('--dry-run', 'Show what would change without applying')\n .option('--force', 'Skip confirmation prompt')\n .option('--no-delete', 'Do not delete remote resources missing from config')\n .action(async (options: { config?: string; dryRun?: boolean; force?: boolean; delete?: boolean }) => {\n const cwd = process.cwd()\n const { config, configPath } = await loadConfig({ cwd, configPath: options.config })\n const client = createAuthenticatedClient()\n\n logger.info(`Deploying from ${configPath ?? 'config'}...`)\n logger.newline()\n\n const localResources = buildLocalResources(config, cwd)\n const remoteResources = await fetchRemoteResources(client)\n let changes = reconcile(localResources, remoteResources)\n\n // Filter out deletes if --no-delete\n if (options.delete === false) {\n changes = changes.filter((c) => c.action !== 'delete')\n }\n\n const actionable = changes.filter((c) => c.action !== 'no-change')\n\n if (actionable.length === 0) {\n logger.success('No changes to deploy. Everything is in sync.')\n return\n }\n\n formatChangePlan(changes)\n\n if (options.dryRun) {\n logger.info(pc.yellow('Dry run — no changes applied.'))\n return\n }\n\n if (!options.force) {\n const { createInterface } = await import('node:readline')\n const rl = createInterface({ input: process.stdin, output: process.stdout })\n const answer = await new Promise<string>((resolve) => {\n rl.question('Do you want to apply these changes? (y/N) ', resolve)\n })\n rl.close()\n if (!answer || answer.toLowerCase() !== 'y') {\n logger.info('Deploy aborted.')\n return\n }\n }\n\n // Apply changes\n logger.info('Applying changes...')\n logger.newline()\n\n let succeeded = 0\n let failed = 0\n\n // Apply creates first, then updates, then deletes\n const ordered = [\n ...actionable.filter((c) => c.action === 'create'),\n ...actionable.filter((c) => c.action === 'update'),\n ...actionable.filter((c) => c.action === 'delete'),\n ]\n\n for (const change of ordered) {\n const actionLabel = change.action === 'create' ? '+' : change.action === 'update' ? '~' : '-'\n const color = change.action === 'create' ? pc.green : change.action === 'update' ? pc.yellow : pc.red\n\n const result = await applyChange(client, change)\n\n if (result.success) {\n logger.info(color(` ${actionLabel} ${change.type}/${change.name} ✓`))\n succeeded++\n } else {\n logger.error(` ${actionLabel} ${change.type}/${change.name} ✗ ${result.error}`)\n failed++\n }\n }\n\n logger.newline()\n\n if (failed > 0) {\n throw new CLIError(\n `Deploy completed with errors: ${succeeded} succeeded, ${failed} failed`,\n ExitCode.GeneralError,\n )\n } else {\n logger.success(`Deploy complete: ${succeeded} change(s) applied successfully`)\n }\n })\n","import { Command } from 'commander'\nimport { createAuthenticatedClient } from '../api/authenticated-client.js'\nimport { loadConfig } from '../config/loader.js'\nimport { logger } from '../utils/logger.js'\nimport { discoverFiles } from '../utils/discovery.js'\nimport { CLIError, ExitCode, ApiRequestError } from '../utils/errors.js'\nimport { getApiEndpoint, fetchAllPages } from '../utils/resources.js'\nimport type { SupercheckConfig } from '../config/schema.js'\nimport pc from 'picocolors'\n\n\ninterface ManagedResource {\n id: string\n type: string\n name: string\n}\n\n/**\n * Fetch all managed resources (those whose id appears in the local config) from the API.\n * Resources without an `id` in the config are considered new (not yet deployed) and are skipped.\n */\nasync function fetchManagedResources(\n client: import('../api/client.js').ApiClient,\n config: SupercheckConfig,\n): Promise<ManagedResource[]> {\n const resources: ManagedResource[] = []\n\n // Collect ids from config to know what's managed\n const managedIds = new Set<string>()\n\n if (config.jobs) {\n for (const j of config.jobs) {\n if (j.id) managedIds.add(`job:${j.id}`)\n }\n }\n if (config.variables) {\n for (const v of config.variables) {\n if (v.id) managedIds.add(`variable:${v.id}`)\n }\n }\n if (config.tags) {\n for (const t of config.tags) {\n if (t.id) managedIds.add(`tag:${t.id}`)\n }\n }\n if (Array.isArray(config.monitors)) {\n for (const m of config.monitors) {\n if (m.id) managedIds.add(`monitor:${m.id}`)\n }\n }\n if (Array.isArray(config.statusPages)) {\n for (const sp of config.statusPages) {\n if (sp.id) managedIds.add(`statusPage:${sp.id}`)\n }\n }\n\n // Discover test files — extract UUIDs from filenames to match remote tests by id.\n // Files are named `{uuid}.pw.ts` / `{uuid}.k6.ts` after `supercheck pull`.\n const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i\n const patterns = {\n playwright: config.tests?.playwright?.testMatch,\n k6: config.tests?.k6?.testMatch,\n }\n const cwd = process.cwd()\n const files = discoverFiles(cwd, patterns)\n const testIds = new Set<string>()\n for (const f of files) {\n const stem = f.filename.replace(/\\.(pw|k6)\\.ts$/, '')\n if (UUID_RE.test(stem)) {\n testIds.add(stem)\n }\n }\n\n // Fetch remote resources and filter to managed ones\n try {\n const jobs = await fetchAllPages<Record<string, unknown>>(client, '/api/jobs', 'jobs')\n for (const job of jobs) {\n if (job.id && managedIds.has(`job:${String(job.id)}`)) {\n resources.push({ id: String(job.id), type: 'job', name: String(job.name ?? '') })\n }\n }\n } catch (err) { logDestroyFetchError('jobs', err) }\n\n try {\n const tests = await fetchAllPages<Record<string, unknown>>(client, '/api/tests', 'tests')\n for (const test of tests) {\n // Match by database id — local test files are named `{uuid}.pw.ts`\n if (test.id && testIds.has(String(test.id))) {\n resources.push({ id: String(test.id), type: 'test', name: String(test.title ?? '') })\n }\n }\n } catch (err) { logDestroyFetchError('tests', err) }\n\n try {\n const monitors = await fetchAllPages<Record<string, unknown>>(client, '/api/monitors', 'monitors')\n for (const monitor of monitors) {\n if (monitor.id && managedIds.has(`monitor:${String(monitor.id)}`)) {\n resources.push({ id: String(monitor.id), type: 'monitor', name: String(monitor.name ?? '') })\n }\n }\n } catch (err) { logDestroyFetchError('monitors', err) }\n\n try {\n const { data } = await client.get<Array<Record<string, unknown>>>('/api/variables')\n for (const v of data) {\n if (v.id && managedIds.has(`variable:${String(v.id)}`)) {\n resources.push({ id: String(v.id), type: 'variable', name: String(v.key ?? '') })\n }\n }\n } catch (err) { logDestroyFetchError('variables', err) }\n\n try {\n const { data } = await client.get<Array<Record<string, unknown>>>('/api/tags')\n for (const t of data) {\n if (t.id && managedIds.has(`tag:${String(t.id)}`)) {\n resources.push({ id: String(t.id), type: 'tag', name: String(t.name ?? '') })\n }\n }\n } catch (err) { logDestroyFetchError('tags', err) }\n\n try {\n const statusPages = await fetchAllPages<Record<string, unknown>>(client, '/api/status-pages', 'status-pages')\n for (const sp of statusPages) {\n if (sp.id && managedIds.has(`statusPage:${String(sp.id)}`)) {\n resources.push({ id: String(sp.id), type: 'statusPage', name: String(sp.name ?? '') })\n }\n }\n } catch (err) { logDestroyFetchError('status-pages', err) }\n\n return resources\n}\n\n/**\n * Log fetch errors with appropriate severity for the destroy command.\n */\nfunction logDestroyFetchError(resourceType: string, err: unknown): void {\n if (err instanceof ApiRequestError && err.statusCode === 404) {\n logger.debug(`Could not fetch ${resourceType} (not found)`)\n } else {\n const msg = err instanceof Error ? err.message : String(err)\n logger.warn(`Could not fetch ${resourceType}: ${msg}`)\n }\n}\n\nexport const destroyCommand = new Command('destroy')\n .description('Tear down managed resources from the Supercheck project')\n .option('--config <path>', 'Path to config file')\n .option('--dry-run', 'Show what would be destroyed without applying')\n .option('--force', 'Skip confirmation prompt')\n .action(async (options: { config?: string; dryRun?: boolean; force?: boolean }) => {\n const cwd = process.cwd()\n const { config } = await loadConfig({ cwd, configPath: options.config })\n const client = createAuthenticatedClient()\n\n logger.info('Scanning for managed resources to destroy...')\n logger.newline()\n\n const managed = await fetchManagedResources(client, config)\n\n if (managed.length === 0) {\n logger.success('No managed resources found on the remote project.')\n return\n }\n\n logger.header('Resources to destroy:')\n logger.newline()\n for (const r of managed) {\n logger.info(pc.red(` - ${r.type}/${r.name} [${r.id}]`))\n }\n logger.newline()\n logger.warn(`This will permanently delete ${pc.bold(String(managed.length))} resource(s).`)\n logger.newline()\n\n if (options.dryRun) {\n logger.info(pc.yellow('Dry run — no resources destroyed.'))\n return\n }\n\n if (!options.force) {\n throw new CLIError(\n 'Use --force to confirm destruction, or --dry-run to preview.',\n ExitCode.GeneralError,\n )\n }\n\n logger.info('Destroying resources...')\n logger.newline()\n\n let succeeded = 0\n let failed = 0\n\n // Delete in reverse dependency order: tests/monitors first, then jobs, then vars/tags\n const deleteOrder = ['test', 'monitor', 'statusPage', 'job', 'variable', 'tag']\n const sorted = [...managed].sort((a, b) => deleteOrder.indexOf(a.type) - deleteOrder.indexOf(b.type))\n\n for (const resource of sorted) {\n try {\n const endpoint = getApiEndpoint(resource.type)\n await client.delete(`${endpoint}/${resource.id}`)\n logger.info(pc.red(` - ${resource.type}/${resource.name} ✓`))\n succeeded++\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n logger.error(` - ${resource.type}/${resource.name} ✗ ${msg}`)\n failed++\n }\n }\n\n logger.newline()\n\n if (failed > 0) {\n throw new CLIError(\n `Destroy completed with errors: ${succeeded} destroyed, ${failed} failed`,\n ExitCode.GeneralError,\n )\n } else {\n logger.success(`Destroy complete: ${succeeded} resource(s) removed`)\n }\n })\n","import { Command } from 'commander'\nimport { existsSync, mkdirSync, writeFileSync, readFileSync } from 'node:fs'\nimport { resolve, dirname } from 'node:path'\nimport { createAuthenticatedClient } from '../api/authenticated-client.js'\nimport { tryLoadConfig } from '../config/loader.js'\nimport { getStoredBaseUrl, getStoredOrganization, getStoredProject } from '../auth/store.js'\nimport { logger } from '../utils/logger.js'\nimport { withSpinner } from '../utils/spinner.js'\nimport { CLIError, ExitCode, ApiRequestError } from '../utils/errors.js'\nimport { fetchAllPages } from '../utils/resources.js'\nimport pc from 'picocolors'\nimport type { ApiClient } from '../api/client.js'\n\n// ────────────────────────────────────────────────────────────────\n// Types for fetched remote resources\n// ────────────────────────────────────────────────────────────────\n\ninterface RemoteTest {\n id: string\n title: string\n description?: string\n type: string // 'browser' | 'performance' | 'api' etc.\n priority?: string\n script?: string\n tags?: Array<{ id: string; name: string; color?: string }>\n createdAt?: string\n updatedAt?: string\n}\n\ninterface RemoteMonitor {\n id: string\n name: string\n description?: string\n type: string // 'http_request' | 'website' | 'ping_host' | 'port_check' | 'synthetic_test'\n target?: string\n frequencyMinutes?: number\n enabled?: boolean\n status?: string\n config?: Record<string, unknown>\n alertConfig?: Record<string, unknown>\n organizationId?: string\n projectId?: string\n createdAt?: string\n updatedAt?: string\n}\n\ninterface RemoteJob {\n id: string\n name: string\n description?: string\n jobType?: string\n cronSchedule?: string\n status?: string\n alertConfig?: Record<string, unknown>\n tests?: Array<{ id: string; title?: string; type?: string }>\n lastRunAt?: string\n nextRunAt?: string\n createdAt?: string\n updatedAt?: string\n}\n\ninterface RemoteVariable {\n id: string\n key: string\n value?: string\n isSecret: boolean\n description?: string | null\n}\n\ninterface RemoteTag {\n id: string\n name: string\n color?: string\n}\n\ninterface RemoteStatusPage {\n id: string\n name: string\n subdomain?: string\n status?: string\n pageDescription?: string\n headline?: string\n supportUrl?: string\n allowEmailSubscribers?: boolean\n allowWebhookSubscribers?: boolean\n allowRssFeed?: boolean\n cssBodyBackgroundColor?: string\n cssFontColor?: string\n cssGreens?: string\n cssReds?: string\n createdAt?: string\n updatedAt?: string\n}\n\ninterface RemoteContext {\n organization: { id: string; name: string | null; slug: string | null }\n project: { id: string; name: string; slug: string | null; isDefault: boolean }\n}\n\ninterface PullSummary {\n tests: number\n monitors: number\n jobs: number\n variables: number\n tags: number\n statusPages: number\n skipped: number\n errors: string[]\n}\n\n// ────────────────────────────────────────────────────────────────\n// Helpers\n// ────────────────────────────────────────────────────────────────\n\n/**\n * Map API test type back to user-facing type name.\n */\nfunction mapTestType(apiType: string): 'playwright' | 'k6' {\n if (apiType === 'performance' || apiType === 'k6') return 'k6'\n return 'playwright'\n}\n\n/**\n * Get the file extension for a test type.\n */\nfunction testFileExtension(testType: 'playwright' | 'k6'): string {\n return testType === 'k6' ? '.k6.ts' : '.pw.ts'\n}\n\n/**\n * Generate a test filename using the database UUID.\n * Uses UUID as filename for stable, deterministic file paths that\n * survive test renames. Format: {uuid}.pw.ts or {uuid}.k6.ts\n */\nfunction testFilename(testId: string, testType: 'playwright' | 'k6'): string {\n const ext = testFileExtension(testType)\n return `${testId}${ext}`\n}\n\n/**\n * Write a file only if the content has changed, avoiding unnecessary git diffs.\n * Returns true if the file was written (new or changed), false if unchanged.\n */\nfunction writeIfChanged(filePath: string, content: string): boolean {\n if (existsSync(filePath)) {\n const existing = readFileSync(filePath, 'utf-8')\n if (existing === content) return false\n }\n\n const dir = dirname(filePath)\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true })\n }\n\n writeFileSync(filePath, content, 'utf-8')\n return true\n}\n\n/**\n * Decode a base64-encoded script, with fallback to raw string.\n *\n * Uses a round-trip verification: decode from base64, then re-encode and compare\n * against the original (ignoring trailing whitespace/padding). This prevents\n * false positives where plain text that happens to be valid base64 is silently\n * corrupted.\n */\nfunction decodeScript(script: string | undefined): string | null {\n if (!script) return null\n\n // Try base64 first — scripts from the API are typically base64-encoded\n try {\n const trimmed = script.trim()\n const decoded = Buffer.from(trimmed, 'base64').toString('utf-8')\n\n // Round-trip check: re-encode and verify it matches the original.\n // This catches plain-text strings that Node's lenient base64 parser\n // would silently \"decode\" into garbage.\n const reEncoded = Buffer.from(decoded, 'utf-8').toString('base64')\n if (reEncoded !== trimmed) {\n // Not genuine base64 — return the original script as-is\n return script\n }\n\n // Validate that the decoded content looks like code (not garbled binary)\n if (/^[\\x09\\x0a\\x0d\\x20-\\x7e\\u00a0-\\uffff]*$/.test(decoded) && decoded.length > 0) {\n return decoded\n }\n } catch {\n // Not valid base64 — treat as raw\n }\n\n return script\n}\n\n// ────────────────────────────────────────────────────────────────\n// Fetch functions\n// ────────────────────────────────────────────────────────────────\n\nasync function fetchContext(client: ApiClient): Promise<RemoteContext | null> {\n try {\n const { data } = await client.get<{ success: boolean } & RemoteContext>('/api/context')\n // Validate that we got meaningful data\n if (data?.organization?.id && data?.project?.id) {\n return data\n }\n logger.debug('Context response missing organization or project ID')\n return null\n } catch (err) {\n logger.warn(`Could not fetch project context: ${err instanceof Error ? err.message : String(err)}`)\n logger.debug('Organization and project will be set to placeholder values. Re-run after fixing connectivity.')\n return null\n }\n}\n\nasync function fetchTests(client: ApiClient): Promise<RemoteTest[]> {\n try {\n return await fetchAllPages<RemoteTest>(client, '/api/tests', 'tests')\n } catch (err) {\n if (err instanceof ApiRequestError && err.statusCode === 404) return []\n throw err\n }\n}\n\nasync function fetchMonitors(client: ApiClient): Promise<RemoteMonitor[]> {\n try {\n return await fetchAllPages<RemoteMonitor>(client, '/api/monitors', 'monitors')\n } catch (err) {\n if (err instanceof ApiRequestError && err.statusCode === 404) return []\n throw err\n }\n}\n\nasync function fetchJobs(client: ApiClient): Promise<RemoteJob[]> {\n try {\n return await fetchAllPages<RemoteJob>(client, '/api/jobs', 'jobs')\n } catch (err) {\n if (err instanceof ApiRequestError && err.statusCode === 404) return []\n throw err\n }\n}\n\nasync function fetchVariables(client: ApiClient): Promise<RemoteVariable[]> {\n try {\n const { data } = await client.get<RemoteVariable[]>('/api/variables')\n return data\n } catch (err) {\n if (err instanceof ApiRequestError && err.statusCode === 404) return []\n throw err\n }\n}\n\nasync function fetchTags(client: ApiClient): Promise<RemoteTag[]> {\n try {\n const { data } = await client.get<RemoteTag[]>('/api/tags')\n return data\n } catch (err) {\n if (err instanceof ApiRequestError && err.statusCode === 404) return []\n throw err\n }\n}\n\nasync function fetchStatusPages(client: ApiClient): Promise<RemoteStatusPage[]> {\n try {\n return await fetchAllPages<RemoteStatusPage>(client, '/api/status-pages', 'status-pages')\n } catch (err) {\n if (err instanceof ApiRequestError && err.statusCode === 404) return []\n throw err\n }\n}\n\n// ────────────────────────────────────────────────────────────────\n// Writers — write remote resources to local files\n// ────────────────────────────────────────────────────────────────\n\n/**\n * Pull test scripts into _supercheck_/tests/ directory.\n * Each test is saved as a .pw.ts or .k6.ts file.\n */\nfunction pullTests(tests: RemoteTest[], cwd: string, summary: PullSummary): void {\n const testsDir = resolve(cwd, '_supercheck_/tests')\n if (!existsSync(testsDir)) {\n mkdirSync(testsDir, { recursive: true })\n }\n\n for (const test of tests) {\n try {\n const testType = mapTestType(test.type)\n const filename = testFilename(test.id, testType)\n const relPath = `_supercheck_/tests/${filename}`\n\n const script = decodeScript(test.script)\n if (!script) {\n logger.debug(`Skipping test \"${test.title}\" — no script content`)\n summary.skipped++\n continue\n }\n\n const filePath = resolve(cwd, relPath)\n const written = writeIfChanged(filePath, script)\n\n if (written) {\n logger.info(pc.green(` + ${relPath}`))\n summary.tests++\n } else {\n logger.debug(` = ${relPath} (unchanged)`)\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n summary.errors.push(`test \"${test.title}\": ${msg}`)\n }\n }\n}\n\n/**\n * Build monitor definitions from remote data.\n * Produces a clean config by removing defaults and runtime-only fields\n * while keeping field names compatible with the API for round-trip support.\n */\nfunction buildMonitorDefinitions(\n monitors: RemoteMonitor[],\n): Record<string, unknown>[] {\n return monitors.map((m) => {\n const def: Record<string, unknown> = {\n id: m.id,\n name: m.name,\n type: m.type,\n }\n\n if (m.description) def.description = m.description\n if (m.target) def.target = m.target\n if (m.frequencyMinutes !== undefined) def.frequencyMinutes = m.frequencyMinutes\n if (m.enabled !== undefined) def.enabled = m.enabled\n\n // Pass config through, stripping only runtime/default noise\n if (m.config && typeof m.config === 'object') {\n const config = { ...m.config } as Record<string, unknown>\n\n // Remove runtime-only fields\n delete config.sslLastCheckedAt\n\n // Clean up default playwrightOptions (retries:0, timeout:300000, headless:true)\n if (config.playwrightOptions && typeof config.playwrightOptions === 'object') {\n const opts = { ...(config.playwrightOptions as Record<string, unknown>) }\n if (opts.retries === 0) delete opts.retries\n if (opts.timeout === 300000) delete opts.timeout\n if (opts.headless === true) delete opts.headless\n config.playwrightOptions = Object.keys(opts).length > 0 ? opts : undefined\n if (!config.playwrightOptions) delete config.playwrightOptions\n }\n\n // Clean up locationConfig: remove defaults, drop if empty/disabled\n if (config.locationConfig && typeof config.locationConfig === 'object') {\n const loc = { ...(config.locationConfig as Record<string, unknown>) }\n const hasLocations = Array.isArray(loc.locations) && (loc.locations as string[]).length > 0\n if (!loc.enabled || !hasLocations) {\n // Disabled or no locations — remove entirely\n delete config.locationConfig\n } else {\n // Remove default values to reduce noise\n if (loc.enabled === true) delete loc.enabled\n if (loc.strategy === 'majority') delete loc.strategy\n if (loc.threshold === 50) delete loc.threshold\n config.locationConfig = Object.keys(loc).length > 0 ? loc : undefined\n if (!config.locationConfig) delete config.locationConfig\n }\n }\n\n if (Object.keys(config).length > 0) def.config = config\n }\n\n // Pass alertConfig through, stripping only defaults\n if (m.alertConfig && typeof m.alertConfig === 'object') {\n const alert = { ...m.alertConfig } as Record<string, unknown>\n\n // Remove empty/default values\n if (alert.customMessage === '' || alert.customMessage === null) delete alert.customMessage\n if (alert.failureThreshold === 1) delete alert.failureThreshold\n if (alert.recoveryThreshold === 1) delete alert.recoveryThreshold\n\n // Remove false boolean flags (they're defaults)\n for (const key of ['alertOnFailure', 'alertOnRecovery', 'alertOnSslExpiration', 'alertOnSuccess', 'alertOnTimeout']) {\n if (alert[key] === false) delete alert[key]\n }\n\n // Remove empty notificationProviders array\n if (Array.isArray(alert.notificationProviders) && (alert.notificationProviders as string[]).length === 0) {\n delete alert.notificationProviders\n }\n\n if (Object.keys(alert).length > 0) def.alertConfig = alert\n }\n\n return def\n })\n}\n\n/**\n * Build job definitions from remote data.\n * testMap resolves test UUIDs to file paths for human-readable references.\n * Omits runtime state (status) and cleans up alertConfig defaults.\n */\nfunction buildJobDefinitions(\n jobs: RemoteJob[],\n testMap: Map<string, string>,\n): Record<string, unknown>[] {\n return jobs.map((j) => {\n const def: Record<string, unknown> = {\n id: j.id,\n name: j.name,\n tests: (j.tests ?? []).map((t) => {\n // Resolve test UUID to file path if available, otherwise keep UUID\n return testMap.get(t.id) ?? t.id\n }),\n }\n\n if (j.description) def.description = j.description\n if (j.jobType) def.jobType = j.jobType\n if (j.cronSchedule) def.cronSchedule = j.cronSchedule\n // Note: `status` is intentionally omitted — it's runtime state, not config\n\n // Pass alertConfig through, stripping only defaults\n if (j.alertConfig && typeof j.alertConfig === 'object') {\n const alert = { ...j.alertConfig } as Record<string, unknown>\n\n // Remove empty/default values\n if (alert.customMessage === '' || alert.customMessage === null) delete alert.customMessage\n if (alert.failureThreshold === 1) delete alert.failureThreshold\n if (alert.recoveryThreshold === 1) delete alert.recoveryThreshold\n\n // Remove false boolean flags (they're defaults)\n for (const key of ['alertOnFailure', 'alertOnRecovery', 'alertOnSslExpiration', 'alertOnSuccess', 'alertOnTimeout']) {\n if (alert[key] === false) delete alert[key]\n }\n\n // Remove empty notificationProviders array\n if (Array.isArray(alert.notificationProviders) && (alert.notificationProviders as string[]).length === 0) {\n delete alert.notificationProviders\n }\n\n if (Object.keys(alert).length > 0) def.alertConfig = alert\n }\n\n return def\n })\n}\n\n/**\n * Build variable definitions from remote data.\n * Secret values are never written to config.\n */\nfunction buildVariableDefinitions(variables: RemoteVariable[]): Record<string, unknown>[] {\n return variables.map((v) => {\n const def: Record<string, unknown> = {\n id: v.id,\n key: v.key,\n isSecret: v.isSecret,\n }\n\n if (v.description) def.description = v.description\n\n if (v.isSecret) {\n // SECURITY: Never write secret values to config files.\n // Use environment variables or `supercheck var set` for secret values.\n const envVarName = v.key.toUpperCase()\n // Use bracket notation for names that aren't valid JS identifiers\n // (e.g. keys containing dashes, dots, spaces, or starting with digits)\n const isValidIdentifier = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(envVarName)\n def.value = isValidIdentifier\n ? `\\${${envVarName}}`\n : `\\${[${envVarName}]}`\n } else {\n def.value = v.value ?? ''\n }\n\n return def\n })\n}\n\n/**\n * Build tag definitions from remote data.\n */\nfunction buildTagDefinitions(tags: RemoteTag[]): Record<string, unknown>[] {\n return tags.map((t) => {\n const def: Record<string, unknown> = {\n id: t.id,\n name: t.name,\n }\n if (t.color) def.color = t.color\n return def\n })\n}\n\n/**\n * Build status page definitions from remote data.\n * Keeps essential config only — branding and styling are managed via the dashboard.\n */\nfunction buildStatusPageDefinitions(pages: RemoteStatusPage[]): Record<string, unknown>[] {\n return pages.map((p) => {\n const def: Record<string, unknown> = {\n id: p.id,\n name: p.name,\n }\n\n if (p.subdomain) def.subdomain = p.subdomain\n if (p.status) def.status = p.status\n if (p.pageDescription) def.description = p.pageDescription\n if (p.headline) def.headline = p.headline\n if (p.supportUrl) def.supportUrl = p.supportUrl\n\n // Note: branding (colors, fonts) is intentionally omitted —\n // visual customization is better managed via the dashboard.\n\n return def\n })\n}\n\n// ────────────────────────────────────────────────────────────────\n// Config generator\n// ────────────────────────────────────────────────────────────────\n\n/**\n * Generate a supercheck.config.ts file from pulled remote resources.\n */\nfunction generateConfigContent(opts: {\n orgId: string\n projectId: string\n baseUrl: string\n monitors: Record<string, unknown>[]\n jobs: Record<string, unknown>[]\n variables: Record<string, unknown>[]\n tags: Record<string, unknown>[]\n statusPages: Record<string, unknown>[]\n}): string {\n const parts: string[] = []\n\n parts.push(`import { defineConfig } from '@supercheck/cli'`)\n parts.push('')\n parts.push('export default defineConfig({')\n parts.push(` schemaVersion: '1.0',`)\n parts.push(' project: {')\n parts.push(` organization: '${opts.orgId}',`)\n parts.push(` project: '${opts.projectId}',`)\n parts.push(' },')\n parts.push(' api: {')\n parts.push(` baseUrl: process.env.SUPERCHECK_URL ?? '${opts.baseUrl}',`)\n parts.push(' },')\n parts.push(' tests: {')\n parts.push(' playwright: {')\n parts.push(` testMatch: '_supercheck_/tests/**/*.pw.ts',`)\n parts.push(' },')\n parts.push(' k6: {')\n parts.push(` testMatch: '_supercheck_/tests/**/*.k6.ts',`)\n parts.push(' },')\n parts.push(' },')\n\n // Monitors\n if (opts.monitors.length > 0) {\n parts.push(` monitors: ${formatArray(opts.monitors, 2)},`)\n }\n\n // Jobs\n if (opts.jobs.length > 0) {\n parts.push(` jobs: ${formatArray(opts.jobs, 2)},`)\n }\n\n // Variables\n if (opts.variables.length > 0) {\n parts.push(` variables: ${formatArray(opts.variables, 2)},`)\n }\n\n // Tags\n if (opts.tags.length > 0) {\n parts.push(` tags: ${formatArray(opts.tags, 2)},`)\n }\n\n // Status Pages\n if (opts.statusPages.length > 0) {\n parts.push(` statusPages: ${formatArray(opts.statusPages, 2)},`)\n }\n\n parts.push('})')\n parts.push('')\n\n return parts.join('\\n')\n}\n\n/**\n * Format an array of objects as indented TypeScript-like syntax.\n */\nfunction formatArray(arr: Record<string, unknown>[], baseIndent: number): string {\n const indent = ' '.repeat(baseIndent)\n const innerIndent = ' '.repeat(baseIndent + 1)\n\n if (arr.length === 0) return '[]'\n\n const items = arr.map((obj) => {\n const fields = Object.entries(obj)\n .map(([key, value]) => `${innerIndent} ${key}: ${formatValue(value, baseIndent + 2)},`)\n .join('\\n')\n return `${innerIndent}{\\n${fields}\\n${innerIndent}}`\n })\n\n return `[\\n${items.join(',\\n')}\\n${indent}]`\n}\n\n/**\n * Format a value for TypeScript source output.\n * Produces clean, readable TS syntax (not JSON.stringify).\n */\nfunction formatValue(value: unknown, indent = 0): string {\n if (typeof value === 'string') {\n // Check if it's an env var reference like ${VAR_NAME} or ${[VAR-NAME]}\n if (value.startsWith('${') && value.endsWith('}')) {\n const inner = value.slice(2, -1)\n // Bracket-notation reference: ${[VAR-NAME]} → process.env['VAR-NAME']\n if (inner.startsWith('[') && inner.endsWith(']')) {\n const varName = inner.slice(1, -1)\n return `process.env['${varName.replace(/'/g, \"\\\\'\")}'] ?? ''`\n }\n return `process.env.${inner} ?? ''`\n }\n return `'${value.replace(/'/g, \"\\\\'\")}'`\n }\n if (typeof value === 'number' || typeof value === 'boolean') return String(value)\n if (value === null || value === undefined) return 'undefined'\n if (Array.isArray(value)) {\n if (value.length === 0) return '[]'\n if (value.every((v) => typeof v === 'string')) {\n return `[${value.map((v) => `'${String(v).replace(/'/g, \"\\\\'\")}'`).join(', ')}]`\n }\n // Array of objects or mixed\n const innerIndent = ' '.repeat(indent + 1)\n const items = value.map((v) => `${innerIndent}${formatValue(v, indent + 1)}`)\n return `[\\n${items.join(',\\n')}\\n${' '.repeat(indent)}]`\n }\n if (typeof value === 'object') {\n const entries = Object.entries(value as Record<string, unknown>)\n if (entries.length === 0) return '{}'\n const innerIndent = ' '.repeat(indent + 1)\n const fields = entries\n .map(([key, v]) => `${innerIndent}${key}: ${formatValue(v, indent + 1)}`)\n .join(',\\n')\n return `{\\n${fields},\\n${' '.repeat(indent)}}`\n }\n return String(value)\n}\n\n// ────────────────────────────────────────────────────────────────\n// Pull Command\n// ────────────────────────────────────────────────────────────────\n\nexport const pullCommand = new Command('pull')\n .description('Pull tests, monitors, jobs, status pages, and config from the Supercheck cloud into the local project')\n .option('--config <path>', 'Path to config file')\n .option('--force', 'Overwrite existing local files without prompting')\n .option('--tests-only', 'Only pull test scripts')\n .option('--config-only', 'Only pull config (monitors, jobs, variables, tags, status pages)')\n .option('--dry-run', 'Show what would be pulled without writing files')\n .action(async (options: {\n config?: string\n force?: boolean\n testsOnly?: boolean\n configOnly?: boolean\n dryRun?: boolean\n }) => {\n // Validate mutually exclusive flags\n if (options.testsOnly && options.configOnly) {\n throw new CLIError(\n '--tests-only and --config-only are mutually exclusive. Use one or neither.',\n ExitCode.ConfigError,\n )\n }\n\n const cwd = process.cwd()\n const client = createAuthenticatedClient()\n\n // Try loading existing config for baseUrl context\n const existing = await tryLoadConfig({ cwd, configPath: options.config })\n\n logger.newline()\n logger.header('Pulling from Supercheck cloud...')\n logger.newline()\n\n // ── Fetch project/org context and all remote resources in parallel ──\n const [context, tests, monitors, jobs, variables, tags, statusPages] = await withSpinner(\n 'Fetching remote resources...',\n async () => {\n const results = await Promise.all([\n fetchContext(client),\n options.configOnly ? Promise.resolve([]) : fetchTests(client),\n options.testsOnly ? Promise.resolve([]) : fetchMonitors(client),\n options.testsOnly ? Promise.resolve([]) : fetchJobs(client),\n options.testsOnly ? Promise.resolve([]) : fetchVariables(client),\n options.testsOnly ? Promise.resolve([]) : fetchTags(client),\n options.testsOnly ? Promise.resolve([]) : fetchStatusPages(client),\n ])\n return results as [RemoteContext | null, RemoteTest[], RemoteMonitor[], RemoteJob[], RemoteVariable[], RemoteTag[], RemoteStatusPage[]]\n },\n { successText: 'Fetched remote resources' },\n )\n\n logger.debug(`Found: ${tests.length} tests, ${monitors.length} monitors, ${jobs.length} jobs, ${variables.length} variables, ${tags.length} tags, ${statusPages.length} status pages`)\n\n const totalResources = tests.length + monitors.length + jobs.length + variables.length + tags.length + statusPages.length\n if (totalResources === 0) {\n logger.warn('No resources found on the remote project.')\n logger.info('Hint: Create tests and monitors in the Supercheck dashboard, then run `supercheck pull` again.')\n return\n }\n\n // ── Dry run summary ──\n if (options.dryRun) {\n logger.newline()\n logger.header('Resources that would be pulled:')\n logger.newline()\n\n if (tests.length > 0) {\n logger.info(pc.cyan(` Tests (${tests.length}):`))\n for (const t of tests) {\n const testType = mapTestType(t.type)\n logger.info(` ${t.title} (${testType})`)\n }\n }\n if (monitors.length > 0) {\n logger.info(pc.cyan(` Monitors (${monitors.length}):`))\n for (const m of monitors) logger.info(` ${m.name} (${m.type}, every ${m.frequencyMinutes ?? '?'}min)`)\n }\n if (jobs.length > 0) {\n logger.info(pc.cyan(` Jobs (${jobs.length}):`))\n for (const j of jobs) logger.info(` ${j.name}${j.cronSchedule ? ` (${j.cronSchedule})` : ''}`)\n }\n if (variables.length > 0) {\n logger.info(pc.cyan(` Variables (${variables.length}):`))\n for (const v of variables) logger.info(` ${v.key}${v.isSecret ? ' (secret)' : ''}`)\n }\n if (tags.length > 0) {\n logger.info(pc.cyan(` Tags (${tags.length}):`))\n for (const t of tags) logger.info(` ${t.name}`)\n }\n if (statusPages.length > 0) {\n logger.info(pc.cyan(` Status Pages (${statusPages.length}):`))\n for (const sp of statusPages) logger.info(` ${sp.name} (${sp.status ?? 'draft'})`)\n }\n\n logger.newline()\n logger.info(pc.yellow('Dry run — no files written.'))\n logger.newline()\n return\n }\n\n // ── Confirm if not --force ──\n if (!options.force) {\n logger.info(`Found ${pc.bold(String(totalResources))} resources to pull.`)\n logger.info('This will write test scripts and update supercheck.config.ts.')\n logger.newline()\n\n const { createInterface } = await import('node:readline')\n const rl = createInterface({ input: process.stdin, output: process.stdout })\n const answer = await new Promise<string>((resolvePrompt) => {\n rl.question('Continue? (y/N) ', resolvePrompt)\n })\n rl.close()\n\n if (!answer || answer.toLowerCase() !== 'y') {\n logger.info('Pull aborted.')\n return\n }\n logger.newline()\n }\n\n const summary: PullSummary = {\n tests: 0,\n monitors: 0,\n jobs: 0,\n variables: 0,\n tags: 0,\n statusPages: 0,\n skipped: 0,\n errors: [],\n }\n\n // ── Pull test scripts ──\n if (!options.configOnly && tests.length > 0) {\n logger.header('Tests:')\n\n // For tests that need full script content, fetch individually\n // (list endpoint may not include script)\n const fullTests: RemoteTest[] = []\n for (const t of tests) {\n if (t.script) {\n fullTests.push(t)\n } else {\n // Fetch individual test to get the script\n try {\n const { data } = await client.get<RemoteTest>(\n `/api/tests/${t.id}`,\n { includeScript: 'true' },\n )\n fullTests.push(data)\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n logger.warn(` Could not fetch script for \"${t.title}\": ${msg}`)\n summary.errors.push(`test \"${t.title}\": ${msg}`)\n }\n }\n }\n\n pullTests(fullTests, cwd, summary)\n logger.newline()\n }\n\n // ── Build config from remote resources ──\n if (!options.testsOnly) {\n // Build a test ID -> file path map for job test references\n const testMap = new Map<string, string>()\n for (const t of tests) {\n const testType = mapTestType(t.type)\n const filePath = `_supercheck_/tests/${testFilename(t.id, testType)}`\n testMap.set(t.id, filePath)\n }\n\n const monitorDefs = buildMonitorDefinitions(monitors)\n const jobDefs = buildJobDefinitions(jobs, testMap)\n const variableDefs = buildVariableDefinitions(variables)\n const tagDefs = buildTagDefinitions(tags)\n const statusPageDefs = buildStatusPageDefinitions(statusPages)\n\n summary.monitors = monitors.length\n summary.jobs = jobs.length\n summary.variables = variables.length\n summary.tags = tags.length\n summary.statusPages = statusPages.length\n\n // Resolve org/project identity — prefer context API, fall back to resource data.\n // Skip 'unknown-*' from previous broken pulls to avoid self-reinforcing fallback.\n const existingOrg = existing?.config?.project?.organization\n const existingProject = existing?.config?.project?.project\n const firstMonitor = monitors[0]\n const orgId = context?.organization?.id\n ?? firstMonitor?.organizationId\n ?? getStoredOrganization()\n ?? (existingOrg && !existingOrg.startsWith('unknown') ? existingOrg : null)\n ?? 'unknown-org'\n const projectId = context?.project?.id\n ?? firstMonitor?.projectId\n ?? getStoredProject()\n ?? (existingProject && !existingProject.startsWith('unknown') ? existingProject : null)\n ?? 'unknown-project'\n const baseUrl = existing?.config?.api?.baseUrl\n ?? getStoredBaseUrl()\n ?? 'https://app.supercheck.io'\n\n const configContent = generateConfigContent({\n orgId,\n projectId,\n baseUrl,\n monitors: monitorDefs,\n jobs: jobDefs,\n variables: variableDefs,\n tags: tagDefs,\n statusPages: statusPageDefs,\n })\n\n const configPath = resolve(cwd, 'supercheck.config.ts')\n const configChanged = writeIfChanged(configPath, configContent)\n\n if (configChanged) {\n logger.header('Config:')\n if (monitorDefs.length > 0) logger.info(pc.green(` + ${monitorDefs.length} monitor(s)`))\n if (jobDefs.length > 0) logger.info(pc.green(` + ${jobDefs.length} job(s)`))\n if (variableDefs.length > 0) logger.info(pc.green(` + ${variableDefs.length} variable(s)`))\n if (tagDefs.length > 0) logger.info(pc.green(` + ${tagDefs.length} tag(s)`))\n if (statusPageDefs.length > 0) logger.info(pc.green(` + ${statusPageDefs.length} status page(s)`))\n logger.success('Updated supercheck.config.ts')\n } else {\n logger.info('supercheck.config.ts is already up to date')\n }\n }\n\n // ── Summary ──\n logger.newline()\n\n const totalWritten = summary.tests + summary.monitors + summary.jobs + summary.variables + summary.tags + summary.statusPages\n const totalErrors = summary.errors.length\n\n if (totalErrors > 0) {\n logger.header('Errors:')\n for (const err of summary.errors) {\n logger.error(` ${err}`)\n }\n logger.newline()\n }\n\n if (totalWritten === 0 && summary.skipped === 0 && totalErrors === 0) {\n logger.success('Everything is already in sync.')\n } else {\n const resultParts: string[] = []\n if (summary.tests > 0) resultParts.push(`${summary.tests} test(s)`)\n if (summary.monitors > 0) resultParts.push(`${summary.monitors} monitor(s)`)\n if (summary.jobs > 0) resultParts.push(`${summary.jobs} job(s)`)\n if (summary.variables > 0) resultParts.push(`${summary.variables} variable(s)`)\n if (summary.tags > 0) resultParts.push(`${summary.tags} tag(s)`)\n if (summary.statusPages > 0) resultParts.push(`${summary.statusPages} status page(s)`)\n if (summary.skipped > 0) resultParts.push(`${summary.skipped} skipped`)\n\n if (resultParts.length > 0) {\n logger.success(`Pull complete: ${resultParts.join(', ')}`)\n }\n\n if (totalErrors > 0) {\n throw new CLIError(\n `Pull completed with ${totalErrors} error(s)`,\n ExitCode.GeneralError,\n )\n }\n }\n\n logger.newline()\n logger.info('Tip: Review the changes, then commit to version control.')\n logger.info(' Run `supercheck diff` to compare local vs remote.')\n logger.newline()\n })\n","import { Command } from 'commander'\nimport { createAuthenticatedClient } from '../api/authenticated-client.js'\nimport { logger } from '../utils/logger.js'\nimport { output, outputDetail } from '../output/formatter.js'\nimport { CLIError, ExitCode } from '../utils/errors.js'\n\nexport const notificationCommand = new Command('notification')\n .alias('notifications')\n .description('Manage notification providers')\n\nnotificationCommand\n .command('list')\n .description('List notification providers')\n .action(async () => {\n const client = createAuthenticatedClient()\n const { data } = await client.get<Record<string, unknown>[]>('/api/notification-providers')\n\n output(data, {\n columns: [\n { key: 'id', header: 'ID' },\n { key: 'name', header: 'Name' },\n { key: 'type', header: 'Type' },\n { key: 'enabled', header: 'Enabled' },\n { key: 'lastUsed', header: 'Last Used' },\n ],\n })\n })\n\nnotificationCommand\n .command('get <id>')\n .description('Get notification provider details')\n .action(async (id: string) => {\n const client = createAuthenticatedClient()\n const { data } = await client.get<Record<string, unknown>>(`/api/notification-providers/${id}`)\n outputDetail(data)\n })\n\nnotificationCommand\n .command('create')\n .description('Create a notification provider')\n .requiredOption('--type <type>', 'Provider type (email, slack, webhook, telegram, discord, teams)')\n .requiredOption('--name <name>', 'Provider name')\n .option('--config <json>', 'Provider config as JSON string')\n .action(async (options: { type: string; name: string; config?: string }) => {\n const validTypes = ['email', 'slack', 'webhook', 'telegram', 'discord', 'teams']\n if (!validTypes.includes(options.type)) {\n throw new CLIError(\n `Invalid provider type. Must be one of: ${validTypes.join(', ')}`,\n ExitCode.GeneralError,\n )\n }\n\n let config: Record<string, unknown> = {}\n if (options.config) {\n try {\n config = JSON.parse(options.config)\n } catch {\n throw new CLIError('Invalid JSON in --config', ExitCode.GeneralError)\n }\n }\n\n const client = createAuthenticatedClient()\n const { data } = await client.post<Record<string, unknown>>('/api/notification-providers', {\n name: options.name,\n type: options.type,\n config: { name: options.name, ...config },\n })\n\n logger.success(`Notification provider \"${options.name}\" created (${data.id})`)\n outputDetail(data)\n })\n\nnotificationCommand\n .command('update <id>')\n .description('Update a notification provider')\n .option('--name <name>', 'Provider name')\n .option('--type <type>', 'Provider type')\n .option('--config <json>', 'Provider config as JSON string')\n .action(async (id: string, options: { name?: string; type?: string; config?: string }) => {\n const client = createAuthenticatedClient()\n\n if (!options.name && !options.type && !options.config) {\n logger.warn('No fields to update. Use --name, --type, or --config.')\n return\n }\n\n // Fetch existing provider to merge changes (server PUT expects full body)\n const { data: existing } = await client.get<Record<string, unknown>>(`/api/notification-providers/${id}`)\n\n let updatedConfig = (existing.config as Record<string, unknown>) ?? {}\n if (options.config) {\n try {\n updatedConfig = { ...updatedConfig, ...JSON.parse(options.config) }\n } catch {\n throw new CLIError('Invalid JSON in --config', ExitCode.GeneralError)\n }\n }\n\n const updatedName = options.name ?? String(existing.name ?? '')\n const updatedType = options.type ?? String(existing.type ?? '')\n\n // Ensure config.name stays in sync with top-level name\n updatedConfig.name = updatedName\n\n const body = {\n name: updatedName,\n type: updatedType,\n config: updatedConfig,\n }\n\n const { data } = await client.put<Record<string, unknown>>(`/api/notification-providers/${id}`, body)\n logger.success(`Notification provider ${id} updated`)\n outputDetail(data)\n })\n\nnotificationCommand\n .command('delete <id>')\n .description('Delete a notification provider')\n .option('--force', 'Skip confirmation')\n .action(async (id: string, options: { force?: boolean }) => {\n if (!options.force) {\n const { createInterface } = await import('node:readline')\n const rl = createInterface({ input: process.stdin, output: process.stdout })\n const answer = await new Promise<string>((resolve) => {\n rl.question(`Are you sure you want to delete notification provider ${id}? (y/N) `, resolve)\n })\n rl.close()\n if (answer.toLowerCase() !== 'y') {\n logger.info('Aborted')\n return\n }\n }\n\n const client = createAuthenticatedClient()\n await client.delete(`/api/notification-providers/${id}`)\n logger.success(`Notification provider ${id} deleted`)\n })\n\nnotificationCommand\n .command('test')\n .description('Send a test notification to verify provider configuration')\n .requiredOption('--type <type>', 'Provider type (email, slack, webhook, telegram, discord, teams)')\n .requiredOption('--config <json>', 'Provider config as JSON string')\n .action(async (options: { type: string; config: string }) => {\n const validTypes = ['email', 'slack', 'webhook', 'telegram', 'discord', 'teams']\n if (!validTypes.includes(options.type)) {\n throw new CLIError(\n `Invalid provider type. Must be one of: ${validTypes.join(', ')}`,\n ExitCode.GeneralError,\n )\n }\n\n let config: Record<string, unknown> = {}\n try {\n config = JSON.parse(options.config)\n } catch {\n throw new CLIError('Invalid JSON in --config', ExitCode.GeneralError)\n }\n\n const client = createAuthenticatedClient()\n const { data } = await client.post<{ success: boolean; message?: string; error?: string }>(\n '/api/notification-providers/test',\n { type: options.type, config },\n )\n\n if (data.success) {\n logger.success(data.message ?? 'Test notification sent successfully')\n } else {\n throw new CLIError(data.error ?? 'Test notification failed', ExitCode.GeneralError)\n }\n })\n","import { Command } from 'commander'\nimport { createAuthenticatedClient } from '../api/authenticated-client.js'\nimport { output } from '../output/formatter.js'\nimport { logger } from '../utils/logger.js'\nimport type { PaginatedResponse } from '../api/client.js'\n\nexport const alertCommand = new Command('alert')\n .alias('alerts')\n .description('View alert history')\n\nalertCommand\n .command('history')\n .description('Get alert history')\n .option('--page <page>', 'Page number', '1')\n .option('--limit <limit>', 'Number of results per page', '50')\n .action(async (options: { page: string; limit: string }) => {\n const client = createAuthenticatedClient()\n const { data } = await client.get<\n PaginatedResponse<Record<string, unknown>> | Record<string, unknown>[]\n >('/api/alerts/history', { page: options.page, limit: options.limit })\n\n // Handle both flat array and paginated response\n const items = Array.isArray(data) ? data : data.data\n const pagination = Array.isArray(data) ? null : data.pagination\n\n output(items, {\n columns: [\n { key: 'id', header: 'ID' },\n { key: 'targetType', header: 'Target Type' },\n { key: 'targetName', header: 'Target' },\n { key: 'type', header: 'Alert Type' },\n { key: 'status', header: 'Status' },\n { key: 'timestamp', header: 'Time' },\n ],\n })\n\n if (pagination) {\n logger.info(\n `\\nPage ${pagination.page}/${pagination.totalPages} (${pagination.total} total)`,\n )\n }\n })\n\n","import { Command } from 'commander'\nimport { createAuthenticatedClient } from '../api/authenticated-client.js'\nimport { logger } from '../utils/logger.js'\nimport { output } from '../output/formatter.js'\nimport { CLIError, ExitCode } from '../utils/errors.js'\n\ninterface AuditResponse {\n success: boolean\n data: {\n logs: Array<{\n id: string\n action: string\n details: unknown\n createdAt: string\n user: { id: string; name: string | null; email: string | null }\n }>\n pagination: {\n currentPage: number\n totalPages: number\n totalCount: number\n limit: number\n hasNext: boolean\n hasPrev: boolean\n }\n }\n}\n\nexport const auditCommand = new Command('audit')\n .description('View audit logs (admin)')\n .option('--page <page>', 'Page number', '1')\n .option('--limit <limit>', 'Items per page', '20')\n .option('--search <query>', 'Search by action')\n .option('--action <action>', 'Filter by action type')\n .action(async (options: { page: string; limit: string; search?: string; action?: string }) => {\n const client = createAuthenticatedClient()\n\n const params: Record<string, string> = {\n page: options.page,\n limit: options.limit,\n }\n if (options.search) params.search = options.search\n if (options.action) params.action = options.action\n\n const { data } = await client.get<AuditResponse>('/api/audit', params)\n\n if (!data.success) {\n throw new CLIError('Failed to fetch audit logs', ExitCode.ApiError)\n }\n\n const rows = data.data.logs.map((log) => ({\n id: log.id,\n action: log.action,\n user: log.user?.email ?? log.user?.name ?? '-',\n createdAt: log.createdAt,\n }))\n\n output(rows, {\n columns: [\n { key: 'id', header: 'ID' },\n { key: 'action', header: 'Action' },\n { key: 'user', header: 'User' },\n { key: 'createdAt', header: 'Date' },\n ],\n })\n\n const { pagination } = data.data\n if (pagination) {\n logger.info(\n `\\nPage ${pagination.currentPage}/${pagination.totalPages} (${pagination.totalCount} total)`,\n )\n }\n })\n"],"mappings":";;;AAAA,SAAS,WAAAA,iBAAe;AACxB,OAAOC,SAAQ;;;ACDf,SAAS,eAAe;;;ACAxB,OAAO,UAAU;;;ACmB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AAc;AACjC,QAAQ,WAAW,WAAW;AAG9B,QAAQ,WAAW,mBAAmB;AACtC,QAAQ,WAAW,YAAY;AAC/B,QAAQ,WAAW,YAAY;AAG/B,QAAQ,WAAW,aAAa;AAChC,QAAQ,WAAW,gBAAgB;AAGnC,QAAQ,aAAa;AAErB,eAAe,OAAsB;AACnC,MAAI;AACF,UAAM,QAAQ,WAAW,QAAQ,IAAI;AAAA,EACvC,SAAS,KAAK;AACZ,QAAI,eAAe,UAAU;AAC3B,UAAI,IAAI,8BAA+B;AACrC,gBAAQ,MAAMC,IAAG,IAAI;AAAA,SAAO,IAAI,OAAO;AAAA,CAAI,CAAC;AAAA,MAC9C;AACA,cAAQ,KAAK,IAAI,QAAQ;AAAA,IAC3B;AAIA,QAAI,OAAO,OAAO,QAAQ,YAAY,cAAc,OAAO,OAAO,IAAI,aAAa,UAAU;AAC3F,cAAQ,KAAK,IAAI,QAAQ;AAAA,IAC3B;AAGA,YAAQ,MAAMA,IAAG,IAAI;AAAA,2BAAyB,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;AAAA,CAAI,CAAC;AACnG,YAAQ,yBAA0B;AAAA,EACpC;AACF;AAEA,KAAK;","names":["Command","pc","resolve","Command","resolve","resolve","pc","pc","Command","Command","Command","Command","existsSync","readFileSync","resolve","basename","existsSync","resolve","basename","Command","readFileSync","Command","Command","resolve","Command","ProxyAgent","proxyAgents","getProxyAgent","Command","Command","ProxyAgent","Buffer","proxyAgents","getProxyAgent","isNoProxyMatch","getProxyEnv","Command","readFileSync","resolve","Command","Command","resolve","Command","Command","Command","Command","Command","pc","pc","Command","Command","pc","Command","resolve","Command","pc","Command","Command","existsSync","mkdirSync","writeFileSync","readFileSync","resolve","dirname","pc","existsSync","readFileSync","dirname","mkdirSync","writeFileSync","resolve","formatValue","Command","Command","Command","resolve","Command","Command","Command","Command","Command","pc"]}
|