@viberaven/cli 0.1.0-beta.0 → 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/dist/cli.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/cli.ts", "../src/config.ts", "../../../src/station/fetchUtils.ts", "../../../src/station/backendClient.ts", "../src/account.ts", "../src/auth.ts", "../../../src/station/fileScanner.ts", "../../../src/station/orchestrator.ts", "../../../src/station/engines.ts", "../../../src/station/sifgTemplates.ts", "../../../src/station/providerRegistry.ts", "../../../src/station/missionGraph.ts", "../../../src/station/promptBuilder.ts", "../../../src/station/productionConnections.ts", "../../../src/station/envEvidence.ts", "../../../src/station/repositoryEvidence.ts", "../../../src/station/scanContext.ts", "../../../src/station/sifgExtractors.ts", "../../../src/station/sifgEngine.ts", "../../../src/station/sifgPrompt.ts", "../../../src/station/promptRouting.ts", "../../../src/station/stackAutomation.ts", "../../../src/station/supabaseWiring.ts", "../../../src/station/stackWiring.ts", "../../../src/station/verification.ts", "../src/runScan.ts", "../src/artifacts.ts", "../src/report/agentSummary.ts", "../src/report/reportStyles.ts", "../src/report/reportHtml.ts", "../src/openBrowser.ts", "../src/terminalSummary.ts"],
4
- "sourcesContent": ["import { readFile } from 'node:fs/promises';\r\nimport { join } from 'node:path';\r\nimport {\r\n clearCredentials,\r\n getProjectArtifactsDir,\r\n loadCredentials,\r\n loadStackChoicesFile,\r\n resolveApiBaseUrl,\r\n saveStackChoicesFile\r\n} from './config';\r\nimport { requireCredentials, runDeviceLogin } from './auth';\r\nimport { fetchAccountMe, formatScanLimitMessage, formatUsageLine, syncCredentialsFromAccount } from './account';\r\nimport { runProjectScan } from './runScan';\r\nimport { writeScanArtifacts } from './artifacts';\r\nimport { openPathInBrowser } from './openBrowser';\r\nimport { printScanSummary } from './terminalSummary';\r\nimport type { CliScanArtifact } from './types';\r\nimport type { Gap } from '../../../src/station/types';\r\n\r\nconst VERSION = '0.1.0-beta.0';\r\n\r\nfunction printHelp(): void {\r\n console.log(`viberaven ${VERSION} \u2014 launch readiness for AI-built apps\r\n\r\nUsage:\r\n viberaven login [--api-url <url>]\r\n viberaven logout\r\n viberaven status\r\n viberaven scan [--open] [--json] [--api-url <url>] [path]\r\n viberaven prompt [--gap <id>] [--provider <key>] [--area <key>]\r\n viberaven stack set <area> <provider>\r\n viberaven stack clear <area>\r\n viberaven stack list\r\n\r\nAgent workflow (Claude Code / Codex):\r\n npx -y @viberaven/cli@beta scan --open\r\n Read .viberaven/agent-summary.md and fix the top gap, then scan again.\r\n\r\nEnvironment:\r\n VIBERAVEN_API_URL Managed API base URL (same server as the VS Code extension)\r\n`);\r\n}\r\n\r\nfunction parseArgs(argv: string[]): {\r\n command: string;\r\n flags: Record<string, string | boolean>;\r\n positional: string[];\r\n} {\r\n const flags: Record<string, string | boolean> = {};\r\n const positional: string[] = [];\r\n let command = '';\r\n\r\n for (let i = 0; i < argv.length; i += 1) {\r\n const arg = argv[i];\r\n if (arg === '--help' || arg === '-h') {\r\n flags.help = true;\r\n continue;\r\n }\r\n if (arg.startsWith('--')) {\r\n const key = arg.slice(2);\r\n const next = argv[i + 1];\r\n if (next && !next.startsWith('-')) {\r\n flags[key] = next;\r\n i += 1;\r\n } else {\r\n flags[key] = true;\r\n }\r\n continue;\r\n }\r\n if (!command) {\r\n command = arg;\r\n } else {\r\n positional.push(arg);\r\n }\r\n }\r\n\r\n return { command, flags, positional };\r\n}\r\n\r\nasync function loadLastArtifact(cwd: string): Promise<CliScanArtifact> {\r\n const path = join(getProjectArtifactsDir(cwd), 'last-scan.json');\r\n const raw = await readFile(path, 'utf-8');\r\n return JSON.parse(raw) as CliScanArtifact;\r\n}\r\n\r\nfunction pickGap(\r\n artifact: CliScanArtifact,\r\n options: { gapId?: string; provider?: string; area?: string }\r\n): Gap | undefined {\r\n if (options.gapId) {\r\n return artifact.gaps.find((g) => g.id === options.gapId);\r\n }\r\n if (options.provider) {\r\n const key = options.provider.toLowerCase();\r\n return artifact.gaps.find(\r\n (g) =>\r\n g.primaryMapCategory === key ||\r\n g.title.toLowerCase().includes(key) ||\r\n g.id.toLowerCase().includes(key)\r\n );\r\n }\r\n if (options.area) {\r\n return artifact.gaps.find((g) => g.primaryMapCategory === options.area);\r\n }\r\n const rank = { critical: 0, warning: 1, info: 2 };\r\n return [...artifact.gaps].sort(\r\n (a, b) => rank[a.severity] - rank[b.severity] || a.title.localeCompare(b.title)\r\n )[0];\r\n}\r\n\r\nasync function cmdLogin(flags: Record<string, string | boolean>): Promise<void> {\r\n const apiBaseUrl = resolveApiBaseUrl(typeof flags['api-url'] === 'string' ? flags['api-url'] : undefined);\r\n await runDeviceLogin(apiBaseUrl);\r\n}\r\n\r\nasync function cmdLogout(): Promise<void> {\r\n await clearCredentials();\r\n console.log('Signed out.');\r\n}\r\n\r\nasync function cmdStatus(): Promise<number> {\r\n const creds = await loadCredentials();\r\n if (!creds?.accessToken) {\r\n console.log('Not signed in. Run: viberaven login');\r\n return 1;\r\n }\r\n try {\r\n const synced = await syncCredentialsFromAccount(creds);\r\n console.log(`Signed in: ${synced.email ?? '(email unknown)'}`);\r\n console.log(`Plan: ${synced.plan ?? 'unknown'}`);\r\n console.log(formatUsageLine(synced.account.usage));\r\n console.log(`API: ${synced.apiBaseUrl}`);\r\n return 0;\r\n } catch (error) {\r\n console.log(`Signed in (cached): ${creds.email ?? '(email unknown)'}`);\r\n console.log(`Plan: ${creds.plan ?? 'unknown'}`);\r\n console.log(`API: ${creds.apiBaseUrl}`);\r\n console.warn(error instanceof Error ? error.message : String(error));\r\n return 1;\r\n }\r\n}\r\n\r\nasync function cmdScan(\r\n flags: Record<string, string | boolean>,\r\n positional: string[]\r\n): Promise<number> {\r\n const workspacePath = positional[0] ? join(process.cwd(), positional[0]) : process.cwd();\r\n const apiBaseUrl = resolveApiBaseUrl(typeof flags['api-url'] === 'string' ? flags['api-url'] : undefined);\r\n\r\n let accessToken: string;\r\n try {\r\n ({ accessToken } = await requireCredentials(apiBaseUrl));\r\n } catch (error) {\r\n console.error(error instanceof Error ? error.message : String(error));\r\n return 1;\r\n }\r\n\r\n console.log(`Scanning ${workspacePath}\u2026`);\r\n const result = await runProjectScan({ workspacePath, accessToken, apiBaseUrl });\r\n\r\n if (!result.ok) {\r\n if (result.kind === 'scan_limit') {\r\n console.error(formatScanLimitMessage(result.upgradeUrl));\r\n try {\r\n const account = await fetchAccountMe(apiBaseUrl, accessToken);\r\n console.error(formatUsageLine(account.usage));\r\n } catch {\r\n // usage refresh is best-effort when blocked\r\n }\r\n return 2;\r\n }\r\n console.error(result.message);\r\n return 1;\r\n }\r\n\r\n const paths = await writeScanArtifacts({ artifact: result.artifact, cwd: workspacePath });\r\n\r\n if (flags.json) {\r\n console.log(JSON.stringify(result.artifact, null, 2));\r\n return 0;\r\n }\r\n\r\n printScanSummary(result.artifact, paths);\r\n if (result.artifact.usage) {\r\n console.log(formatUsageLine(result.artifact.usage));\r\n }\r\n\r\n if (flags.open) {\r\n try {\r\n await openPathInBrowser(paths.reportPath);\r\n } catch (error) {\r\n console.warn(error instanceof Error ? error.message : String(error));\r\n }\r\n }\r\n\r\n return 0;\r\n}\r\n\r\nasync function cmdPrompt(\r\n flags: Record<string, string | boolean>,\r\n positional: string[]\r\n): Promise<number> {\r\n const cwd = positional[0] ? join(process.cwd(), positional[0]) : process.cwd();\r\n let artifact: CliScanArtifact;\r\n try {\r\n artifact = await loadLastArtifact(cwd);\r\n } catch {\r\n console.error('No scan found. Run: viberaven scan');\r\n return 1;\r\n }\r\n\r\n const gap = pickGap(artifact, {\r\n gapId: typeof flags.gap === 'string' ? flags.gap : undefined,\r\n provider: typeof flags.provider === 'string' ? flags.provider : undefined,\r\n area: typeof flags.area === 'string' ? flags.area : undefined\r\n });\r\n\r\n if (!gap) {\r\n console.error('No matching gap. Run `viberaven scan` or pass --gap <id>.');\r\n return 1;\r\n }\r\n\r\n console.log(gap.copyPrompt);\r\n return 0;\r\n}\r\n\r\nconst STACK_AREAS = new Set(['database', 'auth', 'payments', 'deployment', 'monitoring', 'security']);\r\n\r\nasync function cmdStack(positional: string[]): Promise<number> {\r\n const cwd = process.cwd();\r\n const sub = positional[0];\r\n\r\n if (sub === 'list' || !sub) {\r\n const file = await loadStackChoicesFile(cwd);\r\n const entries = Object.entries(file.choices);\r\n if (entries.length === 0) {\r\n console.log('No provider overrides. Detection runs from repo evidence.');\r\n return 0;\r\n }\r\n for (const [area, choice] of entries) {\r\n console.log(`${area}: ${choice.provider}`);\r\n }\r\n return 0;\r\n }\r\n\r\n if (sub === 'set') {\r\n const area = positional[1];\r\n const provider = positional[2];\r\n if (!area || !provider) {\r\n console.error('Usage: viberaven stack set <area> <provider>');\r\n return 1;\r\n }\r\n if (!STACK_AREAS.has(area)) {\r\n console.error(`Unknown area \"${area}\". Valid: ${[...STACK_AREAS].join(', ')}`);\r\n return 1;\r\n }\r\n const file = await loadStackChoicesFile(cwd);\r\n file.choices[area] = { provider, selectedAt: new Date().toISOString() };\r\n await saveStackChoicesFile(cwd, file);\r\n console.log(`Set ${area} \u2192 ${provider}. Run \\`viberaven scan\\` to re-map.`);\r\n return 0;\r\n }\r\n\r\n if (sub === 'clear') {\r\n const area = positional[1];\r\n const file = await loadStackChoicesFile(cwd);\r\n if (area) {\r\n delete file.choices[area];\r\n } else {\r\n file.choices = {};\r\n }\r\n await saveStackChoicesFile(cwd, file);\r\n console.log(area ? `Cleared ${area}.` : 'Cleared all provider overrides.');\r\n return 0;\r\n }\r\n\r\n console.error(`Unknown stack subcommand \"${sub}\". Use set, clear, or list.`);\r\n return 1;\r\n}\r\n\r\nasync function main(): Promise<number> {\r\n const { command, flags, positional } = parseArgs(process.argv.slice(2));\r\n\r\n if (flags.help) {\r\n printHelp();\r\n return 0;\r\n }\r\n if (!command) {\r\n printHelp();\r\n return 1;\r\n }\r\n\r\n switch (command) {\r\n case 'login':\r\n await cmdLogin(flags);\r\n return 0;\r\n case 'logout':\r\n await cmdLogout();\r\n return 0;\r\n case 'status':\r\n return cmdStatus();\r\n case 'scan':\r\n return cmdScan(flags, positional);\r\n case 'prompt':\r\n return cmdPrompt(flags, positional);\r\n case 'stack':\r\n return cmdStack(positional);\r\n case '--version':\r\n case '-v':\r\n case 'version':\r\n console.log(VERSION);\r\n return 0;\r\n default:\r\n console.error(`Unknown command: ${command}`);\r\n printHelp();\r\n return 1;\r\n }\r\n}\r\n\r\nmain()\r\n .then((code) => {\r\n if (code !== 0) {\r\n process.exitCode = code;\r\n }\r\n })\r\n .catch((error) => {\r\n console.error(error instanceof Error ? error.message : String(error));\r\n process.exitCode = 1;\r\n });\r\n", "import { homedir } from 'node:os';\r\nimport { join } from 'node:path';\r\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\r\nimport { constants } from 'node:fs';\r\nimport { access } from 'node:fs/promises';\r\n\r\n/** Same default as the shipped VS Code extension (`getBackendBaseUrl`). */\r\nexport const DEFAULT_API_BASE_URL =\r\n 'https://jaohiwzjhtwljyqligpu.supabase.co/functions/v1/viberice-api';\r\n\r\nexport interface CliCredentials {\r\n accessToken: string;\r\n apiBaseUrl: string;\r\n email?: string;\r\n plan?: string;\r\n}\r\n\r\nexport interface CliStackChoice {\r\n provider: string;\r\n selectedAt: string;\r\n}\r\n\r\nexport interface CliStackChoicesFile {\r\n version: 1;\r\n choices: Record<string, CliStackChoice>;\r\n}\r\n\r\nexport function getStackChoicesPath(cwd: string = process.cwd()): string {\r\n return join(getProjectArtifactsDir(cwd), 'stack.json');\r\n}\r\n\r\nexport function getConfigDir(): string {\r\n const override = process.env.VIBERAVEN_CONFIG_DIR?.trim();\r\n if (override) {\r\n return override;\r\n }\r\n if (process.platform === 'win32') {\r\n const appData = process.env.APPDATA?.trim();\r\n if (appData) {\r\n return join(appData, 'viberaven');\r\n }\r\n }\r\n return join(homedir(), '.config', 'viberaven');\r\n}\r\n\r\nexport function getCredentialsPath(): string {\r\n return join(getConfigDir(), 'credentials.json');\r\n}\r\n\r\nexport function getProjectArtifactsDir(cwd: string = process.cwd()): string {\r\n return join(cwd, '.viberaven');\r\n}\r\n\r\nexport async function ensureConfigDir(): Promise<string> {\r\n const dir = getConfigDir();\r\n await mkdir(dir, { recursive: true });\r\n return dir;\r\n}\r\n\r\nexport async function loadCredentials(): Promise<CliCredentials | undefined> {\r\n try {\r\n const raw = await readFile(getCredentialsPath(), 'utf-8');\r\n const parsed = JSON.parse(raw) as Partial<CliCredentials>;\r\n if (typeof parsed.accessToken !== 'string' || !parsed.accessToken.trim()) {\r\n return undefined;\r\n }\r\n return {\r\n accessToken: parsed.accessToken.trim(),\r\n apiBaseUrl: (parsed.apiBaseUrl?.trim() || DEFAULT_API_BASE_URL).replace(/\\/+$/, ''),\r\n email: typeof parsed.email === 'string' ? parsed.email : undefined,\r\n plan: typeof parsed.plan === 'string' ? parsed.plan : undefined\r\n };\r\n } catch {\r\n return undefined;\r\n }\r\n}\r\n\r\nexport async function saveCredentials(credentials: CliCredentials): Promise<void> {\r\n await ensureConfigDir();\r\n await writeFile(getCredentialsPath(), `${JSON.stringify(credentials, null, 2)}\\n`, {\r\n mode: constants.S_IRUSR | constants.S_IWUSR\r\n });\r\n}\r\n\r\nexport async function clearCredentials(): Promise<void> {\r\n try {\r\n await access(getCredentialsPath());\r\n await writeFile(getCredentialsPath(), '{}\\n');\r\n } catch {\r\n // no credentials file\r\n }\r\n}\r\n\r\nexport function resolveApiBaseUrl(flag?: string): string {\r\n const fromFlag = flag?.trim();\r\n if (fromFlag) {\r\n return fromFlag.replace(/\\/+$/, '');\r\n }\r\n const fromEnv = process.env.VIBERAVEN_API_URL?.trim() || process.env.VRAVEN_API_URL?.trim();\r\n if (fromEnv) {\r\n return fromEnv.replace(/\\/+$/, '');\r\n }\r\n return DEFAULT_API_BASE_URL;\r\n}\r\n\r\nexport async function loadStackChoicesFile(cwd: string): Promise<CliStackChoicesFile> {\r\n try {\r\n const raw = await readFile(getStackChoicesPath(cwd), 'utf-8');\r\n const parsed = JSON.parse(raw) as Partial<CliStackChoicesFile>;\r\n if (parsed && parsed.version === 1 && parsed.choices && typeof parsed.choices === 'object') {\r\n return { version: 1, choices: parsed.choices };\r\n }\r\n } catch {\r\n // optional file\r\n }\r\n return { version: 1, choices: {} };\r\n}\r\n\r\nexport async function saveStackChoicesFile(cwd: string, file: CliStackChoicesFile): Promise<void> {\r\n await mkdir(getProjectArtifactsDir(cwd), { recursive: true });\r\n await writeFile(getStackChoicesPath(cwd), `${JSON.stringify(file, null, 2)}\\n`, 'utf-8');\r\n}\r\n", "/**\r\n * True when the failure is a low-level network/transport error (no HTTP response),\r\n * e.g. ECONNREFUSED to localhost, DNS failure, or offline.\r\n */\r\nexport function isNetworkFetchFailure(error: unknown): boolean {\r\n if (error == null) {\r\n return false;\r\n }\r\n\r\n if (error instanceof TypeError) {\r\n const m = error.message;\r\n if (m === 'fetch failed' || m.toLowerCase().includes('fetch failed') || m.includes('Failed to fetch')) {\r\n return true;\r\n }\r\n }\r\n\r\n if (error instanceof AggregateError) {\r\n return error.errors.some((e) => isNetworkFetchFailure(e));\r\n }\r\n\r\n if (error instanceof Error && 'cause' in error && (error as Error & { cause?: unknown }).cause != null) {\r\n return isNetworkFetchFailure((error as Error & { cause?: unknown }).cause);\r\n }\r\n\r\n const e = error as NodeJS.ErrnoException;\r\n if (typeof e.code === 'string') {\r\n if (\r\n ['ECONNREFUSED', 'ECONNRESET', 'ENOTFOUND', 'EAI_AGAIN', 'ETIMEDOUT', 'ENETUNREACH', 'EHOSTUNREACH'].includes(\r\n e.code\r\n )\r\n ) {\r\n return true;\r\n }\r\n }\r\n\r\n return false;\r\n}\r\n", "import type { DevicePollResponse, DeviceStartResponse } from '../../shared/auth';\nimport { isNetworkFetchFailure } from './fetchUtils';\nimport type {\n ManagedStationRequest,\n ManagedStationResponse,\n ManagedStationUsage\n} from '../../shared/station';\n\nexport const MANAGED_ACCESS_TOKEN_SECRET_KEY = 'viberice.managedAccessToken';\nexport const MANAGED_SESSION_STATE_KEY = 'viberice.managedSession';\n\nexport interface ManagedAccount {\n email?: string;\n plan?: string;\n trialEndsAt?: string | null;\n}\n\nexport interface ManagedSession {\n account?: ManagedAccount;\n usage?: ManagedUsage;\n}\n\nexport type ManagedUsage = ManagedStationUsage;\n\nexport type ManagedSignInStart = DeviceStartResponse;\n\nexport type ManagedSignInPoll =\n | DevicePollResponse\n | { status: 'expired' | 'denied' };\n\nexport async function startManagedSignIn(baseUrl: string): Promise<ManagedSignInStart> {\n const payload = await postJson(`${normalizeBaseUrl(baseUrl)}/v1/auth/device/start`, undefined, {\n failurePrefix: 'Managed sign-in start'\n });\n\n if (!isManagedSignInStart(payload)) {\n throw new Error('Managed sign-in start response was invalid.');\n }\n\n return payload;\n}\n\nexport async function pollManagedSignIn(\n baseUrl: string,\n deviceCode: string\n): Promise<ManagedSignInPoll> {\n let payload: unknown;\n try {\n payload = await postJson(\n `${normalizeBaseUrl(baseUrl)}/v1/auth/device/poll`,\n { deviceCode },\n { failurePrefix: 'Managed sign-in poll' }\n );\n } catch (error) {\n if (error instanceof BackendHttpError && error.status === 410) {\n return { status: 'expired' };\n }\n\n throw error;\n }\n\n if (!isManagedSignInPoll(payload)) {\n throw new Error('Managed sign-in poll response was invalid.');\n }\n\n return payload;\n}\n\nexport async function runManagedStation(\n baseUrl: string,\n accessToken: string,\n payload: ManagedStationRequest\n): Promise<ManagedStationResponse> {\n const responsePayload = await postJson(`${normalizeBaseUrl(baseUrl)}/v1/station/run`, payload, {\n accessToken,\n failurePrefix: 'Managed station run'\n });\n\n if (!isManagedStationResponse(responsePayload)) {\n throw new Error('Managed station run response was invalid.');\n }\n\n return responsePayload;\n}\n\nasync function postJson(\n url: string,\n payload: unknown,\n options: { accessToken?: string; failurePrefix: string }\n): Promise<unknown> {\n let response: Response;\n try {\n response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...(options.accessToken ? { Authorization: `Bearer ${options.accessToken}` } : {})\n },\n // Fastify rejects `Content-Type: application/json` with an empty body (FST_ERR_CTP_EMPTY_JSON_BODY).\n body: JSON.stringify(payload === undefined ? {} : payload)\n });\n } catch (error) {\n if (isNetworkFetchFailure(error)) {\n throw new Error(\n `Could not reach the VibeRaven backend at ${url}. Check your network, then sign in again if needed.`,\n { cause: error }\n );\n }\n throw error;\n }\n\n if (!response.ok) {\n const bodyText = await readError(response);\n let upgradeUrl: string | undefined;\n try {\n const parsed = JSON.parse(bodyText) as Record<string, unknown>;\n if (typeof parsed.upgrade_url === 'string' && parsed.upgrade_url.length > 0) {\n upgradeUrl = parsed.upgrade_url;\n }\n } catch {\n /* body may not be JSON */\n }\n throw new BackendHttpError(\n `${options.failurePrefix} failed with ${response.status}: ${bodyText}`,\n response.status,\n upgradeUrl\n );\n }\n\n return response.json();\n}\n\nasync function readError(response: Response): Promise<string> {\n try {\n const body = await response.text();\n return body.trim() || response.statusText || 'Unknown error';\n } catch {\n return response.statusText || 'Unknown error';\n }\n}\n\nexport function normalizeBaseUrl(baseUrl: string): string {\n return baseUrl.replace(/\\/+$/, '');\n}\n\nfunction isManagedSignInStart(value: unknown): value is ManagedSignInStart {\n return (\n isRecord(value) &&\n isNonEmptyString(value.deviceCode) &&\n isNonEmptyString(value.verificationUrl) &&\n typeof value.pollIntervalSeconds === 'number' &&\n value.pollIntervalSeconds > 0 &&\n isNonEmptyString(value.expiresAt)\n );\n}\n\nfunction isManagedSignInPoll(value: unknown): value is ManagedSignInPoll {\n if (!isRecord(value) || !isNonEmptyString(value.status)) {\n return false;\n }\n\n if (value.status === 'pending' || value.status === 'expired' || value.status === 'denied') {\n return true;\n }\n\n return (\n value.status === 'approved' &&\n isNonEmptyString(value.accessToken) &&\n isManagedAccount(value.account)\n );\n}\n\nfunction isManagedStationResponse(value: unknown): value is ManagedStationResponse {\n return (\n isRecord(value) &&\n (value.status === 'stable' || value.status === 'drifting' || value.status === 'chaos') &&\n isNonEmptyString(value.reason) &&\n isNonEmptyString(value.impact) &&\n (value.confidence === 'low' || value.confidence === 'medium' || value.confidence === 'high') &&\n typeof value.output === 'string' &&\n isManagedUsage(value.usage)\n );\n}\n\nfunction isManagedAccount(value: unknown): value is ManagedAccount {\n return (\n isRecord(value) &&\n isNonEmptyString(value.email) &&\n (value.plan === 'free' || value.plan === 'pro') &&\n (value.trialEndsAt === null || isNonEmptyString(value.trialEndsAt))\n );\n}\n\nfunction isManagedUsage(value: unknown): value is ManagedUsage {\n if (!isRecord(value) || (value.plan !== 'free' && value.plan !== 'pro')) {\n return false;\n }\n if (value.remainingPrompts !== null && typeof value.remainingPrompts !== 'number') {\n return false;\n }\n if (typeof value.used !== 'number' || typeof value.limit !== 'number') {\n return false;\n }\n if (value.period !== 'lifetime' && value.period !== 'monthly') {\n return false;\n }\n if (!Array.isArray(value.unlockedMapCategoryKeys)) {\n return false;\n }\n return value.unlockedMapCategoryKeys.every((k) => typeof k === 'string');\n}\n\nexport class BackendHttpError extends Error {\n constructor(\n message: string,\n public readonly status: number,\n public readonly upgradeUrl?: string\n ) {\n super(message);\n }\n}\n\nfunction isOptionalString(value: unknown): boolean {\n return value === undefined || typeof value === 'string';\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === 'string' && value.trim().length > 0;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n", "import { normalizeBaseUrl } from '../../../src/station/backendClient';\r\nimport type { ManagedStationUsage } from '../../../shared/station';\r\nimport { saveCredentials, type CliCredentials } from './config';\r\n\r\nexport interface AccountMeResponse {\r\n email: string;\r\n plan: 'free' | 'pro';\r\n trialEndsAt?: string | null;\r\n usage: ManagedStationUsage;\r\n billing?: {\r\n status?: string | null;\r\n renewsAt?: string | null;\r\n endsAt?: string | null;\r\n currentPeriodStart?: string | null;\r\n };\r\n}\r\n\r\nexport async function fetchAccountMe(\r\n apiBaseUrl: string,\r\n accessToken: string\r\n): Promise<AccountMeResponse> {\r\n const url = `${normalizeBaseUrl(apiBaseUrl)}/v1/account/me`;\r\n let response: Response;\r\n try {\r\n response = await fetch(url, {\r\n headers: { Authorization: `Bearer ${accessToken}` }\r\n });\r\n } catch (error) {\r\n const cause = error instanceof Error ? error.message : String(error);\r\n throw new Error(`Could not reach VibeRaven API at ${url}: ${cause}`);\r\n }\r\n\r\n if (response.status === 401) {\r\n throw new Error('Session expired. Run `viberaven login` again.');\r\n }\r\n\r\n const bodyText = await response.text();\r\n if (!response.ok) {\r\n throw new Error(`Account lookup failed (${response.status}): ${bodyText.trim() || response.statusText}`);\r\n }\r\n\r\n const data = JSON.parse(bodyText) as AccountMeResponse;\r\n if (!data.usage || (data.plan !== 'free' && data.plan !== 'pro')) {\r\n throw new Error('Account response was missing usage or plan.');\r\n }\r\n return data;\r\n}\r\n\r\nexport async function syncCredentialsFromAccount(\r\n credentials: CliCredentials\r\n): Promise<CliCredentialsWithAccount> {\r\n const account = await fetchAccountMe(credentials.apiBaseUrl, credentials.accessToken);\r\n const updated: CliCredentials = {\r\n ...credentials,\r\n email: account.email,\r\n plan: account.plan\r\n };\r\n await saveCredentials(updated);\r\n return { ...updated, account };\r\n}\r\n\r\nexport type CliCredentialsWithAccount = CliCredentials & { account: AccountMeResponse };\r\n\r\nexport function formatUsageLine(usage: ManagedStationUsage): string {\r\n const periodLabel = usage.period === 'monthly' ? 'this month' : 'lifetime';\r\n return `Scans: ${usage.used}/${usage.limit} (${periodLabel}, ${usage.plan}) \u00B7 ${usage.remainingPrompts} remaining`;\r\n}\r\n\r\nexport function formatScanLimitMessage(upgradeUrl: string): string {\r\n return [\r\n '',\r\n 'Free scan limit reached. Upgrade to Pro to continue.',\r\n 'Your last scan artifacts are unchanged if you already ran a scan in this repo.',\r\n '',\r\n `Upgrade & account: ${upgradeUrl}`,\r\n ''\r\n ].join('\\n');\r\n}\r\n", "import { pollManagedSignIn, startManagedSignIn } from '../../../src/station/backendClient';\r\nimport { formatUsageLine, syncCredentialsFromAccount } from './account';\r\nimport { loadCredentials, resolveApiBaseUrl, saveCredentials } from './config';\r\n\r\nfunction sleep(ms: number): Promise<void> {\r\n return new Promise((resolve) => setTimeout(resolve, ms));\r\n}\r\n\r\nexport async function runDeviceLogin(apiBaseUrl: string): Promise<void> {\r\n const signIn = await startManagedSignIn(apiBaseUrl);\r\n const verificationUrl = buildVerificationUrl(signIn.verificationUrl, signIn.deviceCode);\r\n\r\n console.log('\\nVibeRaven sign-in\\n');\r\n console.log(`Open: ${verificationUrl}`);\r\n console.log(`Code: ${signIn.deviceCode}\\n`);\r\n console.log('Waiting for approval in the browser\u2026\\n');\r\n\r\n const expiresAt = Date.parse(signIn.expiresAt);\r\n const pollMs = Math.max(2, signIn.pollIntervalSeconds) * 1000;\r\n\r\n while (Date.now() < expiresAt) {\r\n const result = await pollManagedSignIn(apiBaseUrl, signIn.deviceCode);\r\n if (result.status === 'pending') {\r\n await sleep(pollMs);\r\n continue;\r\n }\r\n if (result.status === 'expired') {\r\n throw new Error('Sign-in expired. Run `viberaven login` again.');\r\n }\r\n if (result.status === 'denied') {\r\n throw new Error('Sign-in was denied.');\r\n }\r\n if (result.status === 'approved') {\r\n const baseCreds = {\r\n accessToken: result.accessToken,\r\n apiBaseUrl,\r\n email: result.account?.email,\r\n plan: result.account?.plan\r\n };\r\n await saveCredentials(baseCreds);\r\n try {\r\n const synced = await syncCredentialsFromAccount(baseCreds);\r\n const email = synced.email ?? 'your account';\r\n const usage = synced.account?.usage;\r\n console.log(`Signed in as ${email} (${synced.plan ?? 'unknown'}).`);\r\n if (usage) {\r\n console.log(formatUsageLine(usage));\r\n }\r\n } catch (error) {\r\n const email = result.account?.email ?? 'your account';\r\n console.log(`Signed in as ${email}.`);\r\n console.warn(\r\n error instanceof Error\r\n ? `Could not refresh account usage: ${error.message}`\r\n : 'Could not refresh account usage.'\r\n );\r\n }\r\n return;\r\n }\r\n }\r\n\r\n throw new Error('Sign-in timed out. Run `viberaven login` again.');\r\n}\r\n\r\nfunction buildVerificationUrl(verificationUrl: string, deviceCode: string): string {\r\n try {\r\n const url = new URL(verificationUrl);\r\n url.searchParams.set('device_code', deviceCode);\r\n return url.toString();\r\n } catch {\r\n const separator = verificationUrl.includes('?') ? '&' : '?';\r\n return `${verificationUrl}${separator}device_code=${encodeURIComponent(deviceCode)}`;\r\n }\r\n}\r\n\r\nexport async function requireCredentials(apiBaseUrl?: string): Promise<{\r\n accessToken: string;\r\n apiBaseUrl: string;\r\n}> {\r\n const creds = await loadCredentials();\r\n const base = apiBaseUrl ?? creds?.apiBaseUrl ?? resolveApiBaseUrl();\r\n if (!creds?.accessToken) {\r\n throw new Error('Not signed in. Run `viberaven login` first (or set credentials via device flow).');\r\n }\r\n return { accessToken: creds.accessToken, apiBaseUrl: base };\r\n}\r\n", "import { promises as fs } from 'node:fs';\r\nimport { join, relative, basename, sep } from 'node:path';\r\nimport type { ScanResult, ScannedFile, StackSignalKey } from './types';\r\n\r\nconst ALWAYS_SKIP = new Set([\r\n 'node_modules', '.git', '.next', 'dist', 'build', 'out',\r\n '.cache', 'coverage', '.nyc_output', 'storybook-static',\r\n 'public', 'static', '.turbo', '.vercel'\r\n]);\r\n\r\nconst SECRET_PATTERNS = [\r\n /\\.env$/, /\\.env\\..+/, /\\.pem$/, /\\.key$/,\r\n /\\.p8$/, /\\.p12$/, /\\.pfx$/, /\\.ppk$/,\r\n /secrets?\\./i, /credentials?\\./i, /\\.secret\\./i,\r\n /service[-_]?account/i, /private[-_]?key/i\r\n];\r\n\r\nconst SECRET_FILE_NAMES = new Set([\r\n '.npmrc',\r\n '.netrc',\r\n '.pypirc',\r\n 'id_rsa',\r\n 'id_dsa',\r\n 'id_ecdsa',\r\n 'id_ed25519',\r\n 'npmrc',\r\n 'kubeconfig',\r\n 'dockerconfigjson'\r\n]);\r\n\r\nconst HIGH_SIGNAL_FILES = [\r\n 'package.json', 'tsconfig.json', 'SPEC.md', 'README.md',\r\n '.env.example', 'middleware.ts', 'middleware.js',\r\n 'vite.config.ts', 'vite.config.js',\r\n 'next.config.ts', 'next.config.js',\r\n 'tailwind.config.ts', 'tailwind.config.js',\r\n 'vercel.json', 'sentry.client.config.ts', 'sentry.server.config.ts',\r\n 'playwright.config.ts', 'playwright.config.js',\r\n 'drizzle.config.ts', 'drizzle.config.js',\r\n 'prisma/schema.prisma', 'supabase/config.toml',\r\n 'src/middleware.ts', 'app/middleware.ts',\r\n];\r\n\r\nconst STACK_SIGNAL_PATHS: Record<StackSignalKey, string[]> = {\r\n hasSupabase: ['supabase/config.toml', 'src/utils/supabase.ts', 'lib/supabase.ts'],\r\n hasPrisma: ['prisma/schema.prisma'],\r\n hasDrizzle: ['drizzle.config.ts', 'drizzle.config.js'],\r\n hasMongoose: [],\r\n hasNextJs: ['next.config.ts', 'next.config.js', 'app/layout.tsx'],\r\n hasVite: ['vite.config.ts', 'vite.config.js'],\r\n hasAuth: [\r\n 'middleware.ts', 'src/middleware.ts', 'app/middleware.ts',\r\n 'src/lib/auth.ts', 'lib/auth.ts', 'auth.config.ts'\r\n ],\r\n hasTests: ['jest.config.ts', 'vitest.config.ts'],\r\n hasDocker: ['Dockerfile', 'docker-compose.yml', 'docker-compose.yaml'],\r\n hasCI: ['.github/workflows', '.gitlab-ci.yml', 'circle.yml'],\r\n hasStripe: [],\r\n hasClerk: [],\r\n hasAuthJs: [],\r\n hasPaddle: [],\r\n hasVercel: ['vercel.json'],\r\n hasSentry: ['sentry.client.config.ts', 'sentry.server.config.ts', 'instrumentation.ts'],\r\n hasPostHog: [],\r\n hasPlaywright: ['playwright.config.ts', 'playwright.config.js'],\r\n hasUpstash: [],\r\n hasTurnstile: [],\r\n hasNeon: [],\r\n hasMongoDb: [],\r\n hasPlanetScale: [],\r\n hasTurso: ['turso/config.toml'],\r\n hasLanding: ['landing', 'pages/index.tsx', 'app/page.tsx', 'index.html'],\r\n hasRateLimit: [],\r\n hasEnvExample: ['.env.example'],\r\n hasRobots: ['public/robots.txt', 'robots.txt'],\r\n hasSitemap: ['public/sitemap.xml', 'sitemap.xml'],\r\n hasErrorBoundary: [],\r\n hasLoadingStates: [],\r\n};\r\n\r\nexport interface DeepScanOptions {\r\n maxFiles: number;\r\n maxBytesPerFile: number;\r\n maxTotalBytes: number;\r\n maxDepth: number;\r\n}\r\n\r\nconst DEFAULT_OPTIONS: DeepScanOptions = {\r\n maxFiles: 80,\r\n maxBytesPerFile: 6000,\r\n maxTotalBytes: 120000,\r\n maxDepth: 8,\r\n};\r\n\r\nexport async function deepScanWorkspace(\r\n workspaceRoot: string,\r\n options: Partial<DeepScanOptions> = {}\r\n): Promise<ScanResult> {\r\n const opts = { ...DEFAULT_OPTIONS, ...options };\r\n let ignoredByGitignore: (relPath: string) => boolean = () => false;\r\n\r\n try {\r\n const gitignoreContent = await fs.readFile(join(workspaceRoot, '.gitignore'), 'utf-8');\r\n ignoredByGitignore = createGitignoreMatcher(gitignoreContent);\r\n } catch {\r\n // No .gitignore is fine\r\n }\r\n\r\n const allFiles: string[] = [];\r\n const secretsFound: string[] = [];\r\n\r\n async function walk(dir: string, depth: number): Promise<void> {\r\n if (depth > opts.maxDepth) return;\r\n let entries: import('node:fs').Dirent<string>[];\r\n try {\r\n entries = await fs.readdir(dir, { withFileTypes: true });\r\n } catch {\r\n return;\r\n }\r\n entries.sort((a, b) => a.name.localeCompare(b.name));\r\n\r\n for (const entry of entries) {\r\n const fullPath = join(dir, entry.name);\r\n const relPath = relative(workspaceRoot, fullPath);\r\n\r\n if (entry.isDirectory()) {\r\n if (ALWAYS_SKIP.has(entry.name)) {\r\n if (entry.name === 'public' || entry.name === 'static') {\r\n await collectPublicMetadataFiles(fullPath, relPath, depth + 1);\r\n }\r\n continue;\r\n }\r\n if (relPath && ignoredByGitignore(relPath)) continue;\r\n await walk(fullPath, depth + 1);\r\n } else {\r\n if (relPath && ignoredByGitignore(relPath)) continue;\r\n if (isSecretFileName(entry.name)) {\r\n secretsFound.push(relPath);\r\n continue;\r\n }\r\n allFiles.push(relPath);\r\n }\r\n }\r\n }\r\n\r\n async function collectPublicMetadataFiles(dir: string, relDir: string, depth: number): Promise<void> {\r\n if (depth > opts.maxDepth) return;\r\n let entries: import('node:fs').Dirent<string>[];\r\n try {\r\n entries = await fs.readdir(dir, { withFileTypes: true });\r\n } catch {\r\n return;\r\n }\r\n entries.sort((a, b) => a.name.localeCompare(b.name));\r\n\r\n for (const entry of entries) {\r\n const fullPath = join(dir, entry.name);\r\n const relPath = join(relDir, entry.name);\r\n if (entry.isDirectory()) {\r\n await collectPublicMetadataFiles(fullPath, relPath, depth + 1);\r\n continue;\r\n }\r\n if (/^(robots\\.txt|sitemap\\.xml)$/i.test(entry.name)) {\r\n allFiles.push(relPath);\r\n }\r\n }\r\n }\r\n\r\n await walk(workspaceRoot, 0);\r\n\r\n const scored = allFiles\r\n .map((f) => ({ path: f, score: scoreFile(f) }))\r\n .sort((a, b) => b.score - a.score || a.path.localeCompare(b.path))\r\n .slice(0, opts.maxFiles);\r\n\r\n let totalBytes = 0;\r\n const scannedFiles: ScannedFile[] = [];\r\n\r\n for (const { path: relPath, score } of scored) {\r\n if (totalBytes >= opts.maxTotalBytes) break;\r\n const fullPath = join(workspaceRoot, relPath);\r\n let content: string | null = null;\r\n let sizeBytes = 0;\r\n\r\n try {\r\n const raw = await fs.readFile(fullPath);\r\n if (isLikelyBinary(raw)) {\r\n scannedFiles.push({ path: relPath, content: null, isSecret: false, sizeBytes: raw.length, heat: Math.round(score) });\r\n continue;\r\n }\r\n const text = raw.toString('utf-8');\r\n const safeText = redactSecretValues(text);\r\n sizeBytes = Buffer.byteLength(text, 'utf-8');\r\n const budget = Math.min(opts.maxBytesPerFile, opts.maxTotalBytes - totalBytes);\r\n content = safeText.slice(0, budget);\r\n totalBytes += Math.min(sizeBytes, budget);\r\n } catch {\r\n // Unreadable file \u2014 still record path\r\n }\r\n\r\n scannedFiles.push({ path: relPath, content, isSecret: false, sizeBytes, heat: Math.round(score) });\r\n }\r\n\r\n // Stack signals from file paths\r\n const allPathsSet = new Set(allFiles);\r\n const stackSignals: Partial<Record<StackSignalKey, boolean>> = {};\r\n\r\n for (const [signal, paths] of Object.entries(STACK_SIGNAL_PATHS) as Array<[StackSignalKey, string[]]>) {\r\n if (paths.length > 0) {\r\n stackSignals[signal] = paths.some(\r\n (p) => allPathsSet.has(p) || [...allPathsSet].some((ap) => ap.replace(/\\\\/g, '/').includes(p))\r\n );\r\n }\r\n }\r\n\r\n // Stack signals from package.json files across monorepos/sub-apps.\r\n const packageDeps = await readPackageDependencies(workspaceRoot, allFiles);\r\n const packageDepsLower = packageDeps.map((dep) => dep.toLowerCase());\r\n const pathBlob = allFiles.map((file) => file.replace(/\\\\/g, '/').toLowerCase()).join('\\n');\r\n const contentBlob = scannedFiles\r\n .filter((file) => !file.isSecret && typeof file.content === 'string')\r\n .map((file) => file.content as string)\r\n .join('\\n')\r\n .toLowerCase();\r\n const repoBlob = `${packageDepsLower.join('\\n')}\\n${pathBlob}\\n${contentBlob}`;\r\n\r\n stackSignals.hasSupabase = Boolean(stackSignals.hasSupabase) || hasPackage(packageDepsLower, ['@supabase/']) || /\\bsupabase\\b/.test(repoBlob);\r\n stackSignals.hasStripe = hasPackage(packageDepsLower, ['stripe']) || /\\bstripe_(secret_key|webhook_secret)\\b/.test(repoBlob) || /stripe/.test(pathBlob);\r\n stackSignals.hasClerk = hasPackage(packageDepsLower, ['@clerk/']) || /\\bclerk_(secret_key|publishable_key)\\b|\\bnext_public_clerk_/.test(repoBlob);\r\n stackSignals.hasAuthJs = hasPackage(packageDepsLower, ['next-auth', '@auth/']) || /\\b(auth_secret|nextauth_secret)\\b|\\bauth\\.js\\b/.test(repoBlob);\r\n stackSignals.hasAuth = Boolean(stackSignals.hasAuth) || Boolean(stackSignals.hasClerk) || Boolean(stackSignals.hasAuthJs) || /\\bauthmiddleware\\b|\\bclerkmiddleware\\b/.test(repoBlob);\r\n stackSignals.hasPaddle = hasPackage(packageDepsLower, ['@paddle/', 'paddle']) || /\\bpaddle_(api_key|webhook_secret|client_token)\\b/.test(repoBlob);\r\n stackSignals.hasVercel = Boolean(stackSignals.hasVercel) || hasPackage(packageDepsLower, ['@vercel/']) || /\\bvercel\\.json\\b|\\bvercel\\b/.test(repoBlob);\r\n stackSignals.hasSentry = Boolean(stackSignals.hasSentry) || hasPackage(packageDepsLower, ['@sentry/']) || /\\bsentry_dsn\\b|\\bsentry\\.init\\b|\\bsentry\\b/.test(repoBlob);\r\n stackSignals.hasPostHog = hasPackage(packageDepsLower, ['posthog-js', 'posthog-node']) || /\\b(next_public_)?posthog_key\\b|\\bposthog\\.init\\b|\\bposthog\\b/.test(repoBlob);\r\n stackSignals.hasPlaywright = Boolean(stackSignals.hasPlaywright) || hasPackage(packageDepsLower, ['@playwright/test']) || /(^|\\/)playwright\\.config\\.[jt]s\\b|\\.spec\\.[jt]sx?\\b/.test(pathBlob);\r\n stackSignals.hasUpstash = hasPackage(packageDepsLower, ['@upstash/']) || /\\bupstash_redis_rest_(url|token)\\b|\\bupstash\\b/.test(repoBlob);\r\n stackSignals.hasTurnstile = hasPackage(packageDepsLower, ['turnstile']) || /\\bturnstile_(secret_key|site_key)\\b|\\bnext_public_turnstile_site_key\\b|\\bcloudflare turnstile\\b/.test(repoBlob);\r\n stackSignals.hasNeon = hasPackage(packageDepsLower, ['@neondatabase/']) || /\\bneon_database_url\\b|\\bneon\\b/.test(repoBlob);\r\n stackSignals.hasMongoDb = hasPackage(packageDepsLower, ['mongodb', 'mongoose']) || /\\bmongodb_(uri|url)\\b|\\bmongodb\\b/.test(repoBlob);\r\n stackSignals.hasPlanetScale = hasPackage(packageDepsLower, ['@planetscale/database']) || /\\bplanetscale_database_url\\b|\\bplanetscale\\b/.test(repoBlob);\r\n stackSignals.hasTurso = hasPackage(packageDepsLower, ['@libsql/client']) || /\\bturso_(database_url|auth_token)\\b|\\bturso\\b/.test(repoBlob);\r\n stackSignals.hasMongoose = packageDepsLower.includes('mongoose');\r\n stackSignals.hasTests = Boolean(stackSignals.hasTests) || hasPackage(packageDepsLower, ['vitest', 'jest', '@playwright/test', 'cypress']) || /\\.test\\.[jt]sx?\\b|\\.spec\\.[jt]sx?\\b/.test(pathBlob);\r\n stackSignals.hasRateLimit = packageDeps.some((d) =>\r\n ['express-rate-limit', 'rate-limiter-flexible', '@fastify/rate-limit', 'upstash'].some((r) => d.includes(r))\r\n ) || scanContainsRateLimit(scannedFiles);\r\n stackSignals.hasCI = Boolean(stackSignals.hasCI) || /(^|\\n)\\.github\\/workflows\\/[^/\\n]+\\.ya?ml(\\n|$)|(^|\\n)(\\.gitlab-ci\\.yml|circle\\.yml)(\\n|$)/i.test(pathBlob);\r\n stackSignals.hasRobots = Boolean(stackSignals.hasRobots) || /(^|\\n|\\/)robots\\.txt(\\n|$)/i.test(pathBlob);\r\n stackSignals.hasSitemap = Boolean(stackSignals.hasSitemap) || /(^|\\n|\\/)sitemap\\.xml(\\n|$)/i.test(pathBlob);\r\n stackSignals.hasErrorBoundary = Boolean(stackSignals.hasErrorBoundary) ||\r\n /(^|\\n|\\/)(error|error-boundary|errorboundary)\\.[jt]sx?(\\n|$)|(^|\\n).*errorboundary\\.[jt]sx?(\\n|$)/i.test(pathBlob) ||\r\n /\\b(componentdidcatch|errorboundary|react\\.component<.*error)/i.test(contentBlob);\r\n stackSignals.hasLoadingStates = Boolean(stackSignals.hasLoadingStates) ||\r\n /(^|\\n|\\/)(loading|skeleton|spinner)\\.[jt]sx?(\\n|$)|(^|\\n).*skeleton\\.[jt]sx?(\\n|$)/i.test(pathBlob) ||\r\n /\\b(isloading|loading state|suspense fallback|<skeleton|<spinner)/i.test(contentBlob);\r\n\r\n return {\r\n files: scannedFiles,\r\n stackSignals,\r\n packageDeps,\r\n fileTree: allFiles.slice(0, 200).join('\\n'),\r\n secretsFound,\r\n totalFilesScanned: allFiles.length,\r\n };\r\n}\r\n\r\nfunction hasPackage(packageDepsLower: string[], needles: string[]): boolean {\r\n return needles.some((needle) => packageDepsLower.some((dep) => dep === needle || dep.includes(needle)));\r\n}\r\n\r\nfunction scoreFile(relPath: string): number {\r\n const name = basename(relPath);\r\n const parts = relPath.split(sep);\r\n let score = 0;\r\n\r\n if (HIGH_SIGNAL_FILES.some((f) => relPath === f || relPath.replace(/\\\\/g, '/').endsWith(f))) score += 10;\r\n if (/config|Config/.test(name)) score += 6;\r\n if (/auth|middleware|guard|permission|role|policy/i.test(relPath)) score += 7;\r\n if (/schema|migration|seed|\\.prisma/i.test(relPath)) score += 6;\r\n if (/\\.github[/\\\\]workflows[/\\\\].+\\.ya?ml$|\\.gitlab-ci\\.yml$|circle\\.yml$/i.test(relPath)) score += 9;\r\n if (/(^|[/\\\\])robots\\.txt$|(^|[/\\\\])sitemap\\.xml$/i.test(relPath)) score += 9;\r\n if (/sentry\\.(client|server)\\.config\\.[jt]s$|instrumentation\\.[jt]s$/i.test(relPath)) score += 9;\r\n if (/error[-_]?boundary|errorboundary|(^|[/\\\\])error\\.[jt]sx?$/i.test(relPath)) score += 8;\r\n if (/(^|[/\\\\])loading\\.[jt]sx?$|skeleton|spinner/i.test(relPath)) score += 7;\r\n if (/webhook|checkout|billing|rate-?limit|validation|validator/i.test(relPath)) score += 7;\r\n if (parts.includes('api') || parts.includes('routes')) score += 5;\r\n if (['main.ts', 'main.tsx', 'index.ts', 'index.tsx', 'App.tsx', 'App.ts',\r\n 'layout.tsx', 'page.tsx', 'server.ts', 'app.ts'].includes(name)) score += 5;\r\n if (/types?|\\.d\\.ts/.test(name)) score += 3;\r\n if (parts.some((p) => ['hooks', 'store', 'stores', 'context'].includes(p))) score += 4;\r\n if (/db|database/i.test(relPath)) score += 5;\r\n score -= Math.max(0, parts.length - 3) * 0.5;\r\n\r\n return score;\r\n}\r\n\r\nasync function readPackageDependencies(workspaceRoot: string, allFiles: string[]): Promise<string[]> {\r\n const deps = new Set<string>();\r\n const packagePaths = allFiles.filter((file) => basename(file) === 'package.json');\r\n\r\n for (const relPath of packagePaths) {\r\n try {\r\n const raw = await fs.readFile(join(workspaceRoot, relPath), 'utf-8');\r\n const pkg = JSON.parse(raw) as Record<string, unknown>;\r\n for (const key of ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies']) {\r\n const group = pkg[key];\r\n if (!group || typeof group !== 'object' || Array.isArray(group)) {\r\n continue;\r\n }\r\n for (const name of Object.keys(group)) {\r\n deps.add(name);\r\n }\r\n }\r\n } catch {\r\n // Invalid or unreadable package.json files should not fail the scan.\r\n }\r\n }\r\n\r\n return [...deps].sort();\r\n}\r\n\r\nfunction scanContainsRateLimit(files: ScannedFile[]): boolean {\r\n const haystack = files\r\n .filter((file) => typeof file.content === 'string' && /[/\\\\](api|routes|server|src)[/\\\\]|app\\.(ts|js)$/i.test(file.path))\r\n .map((file) => file.content as string)\r\n .join('\\n');\r\n\r\n return /\\b(rateLimit|rateLimiter|rate-limiter|rateLimitBuckets|Too many requests)\\b/i.test(haystack);\r\n}\r\n\r\nfunction redactSecretValues(text: string): string {\r\n return text\r\n .replace(/\\b(sk_(?:live|test)_[A-Za-z0-9]{12,}|sk-proj-[A-Za-z0-9_-]{16,}|sk-[A-Za-z0-9_-]{20,}|whsec_[A-Za-z0-9]{12,}|rk_(?:live|test)_[A-Za-z0-9]{12,})\\b/g, '[REDACTED_SECRET]')\r\n .replace(\r\n /\\b([A-Z0-9_]*(?:SECRET|TOKEN|API_KEY|PRIVATE_KEY|SERVICE_ROLE|PASSWORD|WEBHOOK_SECRET)[A-Z0-9_]*)[ \\t]*=[ \\t]*(['\"]?)([^\\s'\"`#]+)\\2/g,\r\n (_match, key: string, quote: string, value: string) => value.length > 0 ? `${key}=${quote}[REDACTED_SECRET]${quote}` : `${key}=`\r\n );\r\n}\r\n\r\nfunction isSecretFileName(fileName: string): boolean {\r\n if (fileName === '.env.example') {\r\n return false;\r\n }\r\n\r\n if (SECRET_FILE_NAMES.has(fileName.toLowerCase())) {\r\n return true;\r\n }\r\n\r\n return SECRET_PATTERNS.some((pattern) => pattern.test(fileName));\r\n}\r\n\r\nfunction isLikelyBinary(buffer: Buffer): boolean {\r\n return buffer.includes(0);\r\n}\r\n\r\ntype GitignoreRule = {\r\n directoryOnly: boolean;\r\n anchored: boolean;\r\n hasSlash: boolean;\r\n pattern: string;\r\n regex: RegExp;\r\n};\r\n\r\nfunction createGitignoreMatcher(gitignoreContent: string): (relPath: string) => boolean {\r\n const rules = gitignoreContent\r\n .split(/\\r?\\n/)\r\n .map((line) => line.trim())\r\n .filter((line) => line.length > 0 && !line.startsWith('#') && !line.startsWith('!'))\r\n .map(parseGitignoreRule);\r\n\r\n return (relPath: string) => {\r\n const normalized = relPath.replace(/\\\\/g, '/').replace(/^\\/+/, '');\r\n return rules.some((rule) => ruleMatchesPath(rule, normalized));\r\n };\r\n}\r\n\r\nfunction parseGitignoreRule(raw: string): GitignoreRule {\r\n const anchored = raw.startsWith('/');\r\n let pattern = raw.replace(/^\\/+/, '');\r\n const directoryOnly = pattern.endsWith('/');\r\n pattern = pattern.replace(/\\/+$/, '');\r\n const hasSlash = pattern.includes('/');\r\n\r\n return {\r\n directoryOnly,\r\n anchored,\r\n hasSlash,\r\n pattern,\r\n regex: new RegExp(`^${gitignoreGlobToRegex(pattern)}$`)\r\n };\r\n}\r\n\r\nfunction ruleMatchesPath(rule: GitignoreRule, relPath: string): boolean {\r\n const candidates = rule.anchored || rule.hasSlash ? [relPath] : relPath.split('/');\r\n const directMatch = candidates.some((candidate) => rule.regex.test(candidate));\r\n if (directMatch && !rule.directoryOnly) {\r\n return true;\r\n }\r\n if (directMatch && rule.directoryOnly) {\r\n return true;\r\n }\r\n\r\n if (!rule.directoryOnly) {\r\n return false;\r\n }\r\n\r\n if (rule.anchored || rule.hasSlash) {\r\n return relPath === rule.pattern || relPath.startsWith(`${rule.pattern}/`);\r\n }\r\n\r\n return relPath.split('/').includes(rule.pattern);\r\n}\r\n\r\nfunction gitignoreGlobToRegex(pattern: string): string {\r\n let out = '';\r\n for (let i = 0; i < pattern.length; i += 1) {\r\n const ch = pattern[i];\r\n if (ch === '*') {\r\n out += '[^/]*';\r\n continue;\r\n }\r\n if (ch === '?') {\r\n out += '[^/]';\r\n continue;\r\n }\r\n out += escapeRegex(ch);\r\n }\r\n return out;\r\n}\r\n\r\nfunction escapeRegex(value: string): string {\r\n return value.replace(/[|\\\\{}()[\\]^$+?.]/g, '\\\\$&');\r\n}\r\n", "import { promises as fs } from 'node:fs';\r\nimport { join } from 'node:path';\r\nimport { BackendHttpError } from './backendClient';\r\nimport { adaptManagedStationResponse, normalizeModelOutput } from './engines';\r\nimport { isNetworkFetchFailure } from './fetchUtils';\r\nimport { buildMissionGraph } from './missionGraph';\r\nimport { buildProviderRegistrySnapshot } from './providerRegistry';\r\nimport { buildAnalysisPrompt } from './promptBuilder';\r\nimport {\r\n buildProductionConnectionContext,\r\n detectProductionConnectionEvidence,\r\n normalizeProductionChoice,\r\n summarizeProductionConnections\r\n} from './productionConnections';\r\nimport { analyzeRepositoryEvidence } from './repositoryEvidence';\r\nimport { computeStationScanContext } from './scanContext';\r\nimport { buildStaticInfrastructureFlowGraph } from './sifgEngine';\r\nimport { buildStackAutomationContext, buildStackAutomationSummary } from './stackAutomation';\r\nimport { analyzeStackWiring, buildStackWiringContext } from './stackWiring';\r\nimport { buildVerificationEvidenceContext, buildVerificationSummary } from './verification';\r\nimport type { ManagedStationRequest, ManagedStationResponse } from '../../shared/station';\r\nimport type { ProductionConnectionChoices } from './productionConnections';\r\nimport type { SifgGraph } from './sifgTypes';\r\nimport type {\r\n MissionGraph,\r\n ModelStationOutput,\r\n RepositoryEvidenceSummary,\r\n ScanResult,\r\n ScannedFile,\r\n StackAutomationSummary,\r\n StackWiringSummary,\r\n StationScanContext,\r\n VerificationSummary\r\n} from './types';\r\n\r\ninterface StationOrchestratorDeps {\r\n scanWorkspace: (root: string) => Promise<ScanResult>;\r\n fetchStationOutput: (prompt: string, configuration?: unknown) => Promise<Partial<ModelStationOutput>>;\r\n getManagedAccessToken?: () => Promise<string | undefined>;\r\n runManagedStation?: (\r\n accessToken: string,\r\n payload: ManagedStationRequest\r\n ) => Promise<ManagedStationResponse>;\r\n /**\r\n * When false (default for shipped builds), Station never falls back to BYOK/local OpenAI \u2014\r\n * users must be signed in and reach the managed API.\r\n */\r\n isLocalStationFallbackAllowed?: () => boolean | Promise<boolean>;\r\n getProductionConnectionChoices?: () => Promise<ProductionConnectionChoices | undefined>;\r\n}\r\n\r\ninterface StationOrchestratorInput {\r\n workspaceRoot: string;\r\n prompt: string;\r\n configuration?: unknown;\r\n}\r\n\r\nexport interface StationRunResult extends ModelStationOutput {\r\n scannedFiles: ScannedFile[];\r\n scanContext: StationScanContext;\r\n providerRegistry: ReturnType<typeof buildProviderRegistrySnapshot>;\r\n productionConnections: ReturnType<typeof summarizeProductionConnections>;\r\n verificationSummary: VerificationSummary;\r\n stackWiring: StackWiringSummary;\r\n stackAutomation: StackAutomationSummary;\r\n repositoryEvidence: RepositoryEvidenceSummary;\r\n missionGraph: MissionGraph;\r\n staticInfrastructureFlowGraph: SifgGraph;\r\n usage?: ManagedStationResponse['usage'];\r\n}\r\n\r\nexport interface ScanLimitResult {\r\n kind: 'scan_limit_reached';\r\n upgradeUrl: string;\r\n}\r\n\r\nexport interface ManagedRequiredResult {\r\n kind: 'managed_required';\r\n message: string;\r\n}\r\n\r\n/** Managed API rejected the stored access token (wrong server or rotated API secret). */\r\nexport interface ManagedSessionInvalidResult {\r\n kind: 'managed_session_invalid';\r\n message: string;\r\n}\r\n\r\nexport type OrchestratorResult =\r\n | StationRunResult\r\n | ScanLimitResult\r\n | ManagedRequiredResult\r\n | ManagedSessionInvalidResult;\r\n\r\nexport function isScanLimitResult(value: OrchestratorResult): value is ScanLimitResult {\r\n return (value as ScanLimitResult).kind === 'scan_limit_reached';\r\n}\r\n\r\nexport function isManagedRequiredResult(value: OrchestratorResult): value is ManagedRequiredResult {\r\n return (value as ManagedRequiredResult).kind === 'managed_required';\r\n}\r\n\r\nexport function isManagedSessionInvalidResult(\r\n value: OrchestratorResult\r\n): value is ManagedSessionInvalidResult {\r\n return (value as ManagedSessionInvalidResult).kind === 'managed_session_invalid';\r\n}\r\n\r\nexport function createStationOrchestrator(deps: StationOrchestratorDeps) {\r\n return {\r\n async run(input: StationOrchestratorInput): Promise<OrchestratorResult> {\r\n const allowLocal = Boolean(await deps.isLocalStationFallbackAllowed?.());\r\n\r\n const scan = await deps.scanWorkspace(input.workspaceRoot);\r\n const productionConnectionChoices = await loadProductionConnectionChoices(deps);\r\n const productionConnectionEvidence = detectProductionConnectionEvidence(scan);\r\n const productionConnections = summarizeProductionConnections(\r\n productionConnectionChoices,\r\n productionConnectionEvidence\r\n );\r\n const productionConnectionContext = buildProductionConnectionContext(\r\n productionConnectionChoices,\r\n productionConnectionEvidence\r\n );\r\n const verificationSummary = buildVerificationSummary(scan, productionConnections);\r\n const verificationEvidenceContext = buildVerificationEvidenceContext(verificationSummary);\r\n const stackWiring: StackWiringSummary = analyzeStackWiring(scan);\r\n const stackWiringContext = buildStackWiringContext(stackWiring);\r\n const repositoryEvidence = analyzeRepositoryEvidence(scan);\r\n const providerRegistry = buildProviderRegistrySnapshot();\r\n const staticInfrastructureFlowGraph = buildStaticInfrastructureFlowGraph(scan);\r\n const stackAutomation = buildStackAutomationSummary(stackWiring, { staticInfrastructureFlowGraph });\r\n const stackAutomationContext = buildStackAutomationContext(stackAutomation);\r\n const missionGraph = buildMissionGraph({\r\n stackWiring,\r\n repositoryEvidence,\r\n staticInfrastructureFlowGraph\r\n });\r\n const specContent = await readSpec(input.workspaceRoot);\r\n const modelPrompt = buildAnalysisPrompt(\r\n scan,\r\n specContent,\r\n productionConnectionContext,\r\n verificationEvidenceContext,\r\n stackWiringContext,\r\n stackAutomationContext\r\n );\r\n\r\n const managedToken = await deps.getManagedAccessToken?.();\r\n let managedResponse: ManagedStationResponse | undefined;\r\n\r\n if (managedToken && deps.runManagedStation) {\r\n try {\r\n managedResponse = await deps.runManagedStation(managedToken, {\r\n prompt: modelPrompt,\r\n workspacePath: input.workspaceRoot,\r\n specMarkdown: specContent.trim().length > 0 ? specContent : null,\r\n files: scan.files\r\n .filter((f) => !f.isSecret && f.content !== null)\r\n .slice(0, 20)\r\n .map((f) => ({\r\n path: f.path,\r\n summary: f.content!.slice(0, 200),\r\n heat: f.heat >= 7 ? 'hot' : f.heat >= 4 ? 'warm' : 'cool',\r\n })),\r\n });\r\n } catch (error) {\r\n if (error instanceof BackendHttpError && error.status === 402) {\r\n return {\r\n kind: 'scan_limit_reached',\r\n upgradeUrl: error.upgradeUrl ?? 'https://viberice.com/account'\r\n };\r\n }\r\n if (error instanceof BackendHttpError && error.status === 401) {\r\n return {\r\n kind: 'managed_session_invalid',\r\n message:\r\n 'VibeRaven returned 401 Unauthorized for this scan. Your saved sign-in no longer matches the managed API. Use VibeRaven: Sign Out, then VibeRaven: Sign In again.'\r\n };\r\n }\r\n if (isNetworkFetchFailure(error)) {\r\n if (!allowLocal) {\r\n return {\r\n kind: 'managed_required',\r\n message:\r\n 'Could not reach the VibeRaven managed API. This is not a Pro-only restriction \u2014 Free accounts include two managed scans once the server is reachable. Check your connection, then retry.'\r\n };\r\n }\r\n // fall through to BYOK below\r\n } else {\r\n throw error;\r\n }\r\n }\r\n }\r\n\r\n if (managedResponse !== undefined) {\r\n const raw: Partial<ModelStationOutput> = adaptManagedStationResponse(managedResponse);\r\n const normalized = normalizeModelOutput(raw);\r\n const scanContext = computeStationScanContext(scan);\r\n return {\r\n ...normalized,\r\n scannedFiles: scan.files,\r\n scanContext,\r\n providerRegistry,\r\n productionConnections,\r\n verificationSummary,\r\n stackWiring,\r\n stackAutomation,\r\n repositoryEvidence,\r\n missionGraph,\r\n staticInfrastructureFlowGraph,\r\n usage: managedResponse.usage\r\n };\r\n }\r\n\r\n if (!allowLocal) {\r\n return {\r\n kind: 'managed_required',\r\n message:\r\n managedToken && deps.runManagedStation\r\n ? 'Managed scan could not complete. Sign in again or check your VibeRaven backend URL.'\r\n : 'Sign in to VibeRaven (VibeRaven: Sign In) to run managed scans. Local-only API keys are disabled in this build unless you turn on \u201CAllow local Station without managed account\u201D in settings.'\r\n };\r\n }\r\n\r\n const raw: Partial<ModelStationOutput> = await deps.fetchStationOutput(modelPrompt, input.configuration);\r\n const normalized = normalizeModelOutput(raw);\r\n const scanContext = computeStationScanContext(scan);\r\n\r\n return {\r\n ...normalized,\r\n scannedFiles: scan.files,\r\n scanContext,\r\n providerRegistry,\r\n productionConnections,\r\n verificationSummary,\r\n stackWiring,\r\n stackAutomation,\r\n repositoryEvidence,\r\n missionGraph,\r\n staticInfrastructureFlowGraph\r\n };\r\n },\r\n };\r\n}\r\n\r\nasync function readSpec(workspaceRoot: string): Promise<string> {\r\n try {\r\n return await fs.readFile(join(workspaceRoot, 'SPEC.md'), 'utf-8');\r\n } catch {\r\n return '';\r\n }\r\n}\r\n\r\nasync function loadProductionConnectionChoices(\r\n deps: StationOrchestratorDeps\r\n): Promise<ProductionConnectionChoices> {\r\n try {\r\n return normalizeProductionChoice(await deps.getProductionConnectionChoices?.());\r\n } catch {\r\n return normalizeProductionChoice(undefined);\r\n }\r\n}\r\n", "import type {\r\n Gap,\r\n GapCategory,\r\n GapSeverity,\r\n ModelStationOutput,\r\n ProductionMapCategoryKey,\r\n ProductionChecklist,\r\n ToolSuggestion,\r\n} from './types';\r\nimport type { ManagedStationResponse } from '../../shared/station';\r\n\r\nconst VALID_SEVERITY: GapSeverity[] = ['critical', 'warning', 'info'];\r\nconst VALID_CATEGORIES: GapCategory[] = [\r\n 'SECURITY & AUTH', 'DATABASE & DATA', 'ERROR HANDLING', 'DEPLOYMENT',\r\n 'PERFORMANCE', 'MISSING FEATURES', 'EDGE CASES & RISKS', 'LANDING & MARKETING'\r\n];\r\nconst VALID_MAP_CATEGORIES: ProductionMapCategoryKey[] = [\r\n 'appFlow',\r\n 'frontend',\r\n 'backend',\r\n 'auth',\r\n 'database',\r\n 'payments',\r\n 'deployment',\r\n 'monitoring',\r\n 'security',\r\n 'testing',\r\n 'landing',\r\n 'errorHandling',\r\n];\r\nconst MAP_CATEGORY_RULES: Array<{ key: ProductionMapCategoryKey; match: RegExp }> = [\r\n { key: 'monitoring', match: /\\b(monitor|monitoring|observability|sentry|logrocket|posthog|analytics|telemetry|logs?)\\b/i },\r\n { key: 'errorHandling', match: /\\b(error handling|error boundary|exception|unhandled|crash|fallback|failure|failures|rejected promise)\\b/i },\r\n { key: 'auth', match: /\\b(auth|login|logout|session|jwt|oauth|supabase auth|protected route|role|roles|permission|permissions)\\b/i },\r\n { key: 'payments', match: /\\b(payment|payments|billing|checkout|stripe|polar|paddle|subscription|webhook|lemon squeezy|lemonsqueezy|invoice)\\b/i },\r\n { key: 'backend', match: /\\b(backend|api|server|route|handler|endpoint|station run|station runs|fastify|express)\\b/i },\r\n { key: 'security', match: /\\b(security|secret|secrets|rate limit|ratelimit|csrf|xss|bot|abuse|signature)\\b/i },\r\n { key: 'database', match: /\\b(database|data|postgres|mysql|mongo|schema|migration|storage|rls|supabase|repository)\\b/i },\r\n { key: 'deployment', match: /\\b(deploy|deployment|hosting|vercel|netlify|docker|ci|pipeline|environment|env|release)\\b/i },\r\n { key: 'testing', match: /\\b(test|testing|spec|coverage|vitest|jest|playwright|cypress|qa)\\b/i },\r\n { key: 'landing', match: /\\b(landing|marketing|homepage|hero|cta|pricing|seo|sitemap|robots|onboarding|funnel)\\b/i },\r\n { key: 'frontend', match: /\\b(frontend|react|ui|component|layout|state|loading|client)\\b/i },\r\n { key: 'appFlow', match: /\\b(app flow|ux|user flow|journey|activation|empty state)\\b/i },\r\n];\r\nconst SEVERITY_RANK: Record<GapSeverity, number> = { info: 0, warning: 1, critical: 2 };\r\n\r\nfunction isRecord(v: unknown): v is Record<string, unknown> {\r\n return typeof v === 'object' && v !== null && !Array.isArray(v);\r\n}\r\n\r\nfunction clampScore(v: unknown, fallback = 50): number {\r\n if (typeof v !== 'number' || Number.isNaN(v)) return fallback;\r\n return Math.max(0, Math.min(100, Math.round(v)));\r\n}\r\n\r\nfunction stableVisibleScore(v: unknown, fallback = 50): number {\r\n const clamped = clampScore(v, fallback);\r\n return Math.max(0, Math.min(100, Math.round(clamped / 5) * 5));\r\n}\r\n\r\nfunction toStringArray(v: unknown): string[] {\r\n if (!Array.isArray(v)) return [];\r\n return v.filter((item): item is string => typeof item === 'string');\r\n}\r\n\r\nfunction isProductionMapCategoryKey(value: unknown): value is ProductionMapCategoryKey {\r\n return typeof value === 'string' && VALID_MAP_CATEGORIES.includes(value as ProductionMapCategoryKey);\r\n}\r\n\r\nfunction uniqueMapCategories(values: ProductionMapCategoryKey[]): ProductionMapCategoryKey[] {\r\n const seen = new Set<ProductionMapCategoryKey>();\r\n const out: ProductionMapCategoryKey[] = [];\r\n for (const value of values) {\r\n if (!seen.has(value)) {\r\n seen.add(value);\r\n out.push(value);\r\n }\r\n }\r\n return out;\r\n}\r\n\r\nfunction fallbackMapCategoryForGap(category: GapCategory, text: string): ProductionMapCategoryKey {\r\n switch (category) {\r\n case 'SECURITY & AUTH':\r\n return /\\b(auth|login|session|oauth|jwt|role|permission|protected route)\\b/i.test(text) ? 'auth' : 'security';\r\n case 'DATABASE & DATA':\r\n return 'database';\r\n case 'ERROR HANDLING':\r\n return 'errorHandling';\r\n case 'DEPLOYMENT':\r\n return 'deployment';\r\n case 'PERFORMANCE':\r\n return 'frontend';\r\n case 'LANDING & MARKETING':\r\n return 'landing';\r\n case 'EDGE CASES & RISKS':\r\n return 'testing';\r\n case 'MISSING FEATURES':\r\n default:\r\n return 'appFlow';\r\n }\r\n}\r\n\r\nfunction inferMapCategories(\r\n category: GapCategory,\r\n title: string,\r\n detail: string,\r\n copyPrompt: string,\r\n explicitPrimary: unknown,\r\n explicitAffected: unknown\r\n): ProductionMapCategoryKey[] {\r\n const text = [category, title, detail, copyPrompt].filter(Boolean).join(' ');\r\n const fallback = fallbackMapCategoryForGap(category, text);\r\n const matched = MAP_CATEGORY_RULES.filter((rule) => rule.match.test(text)).map((rule) => rule.key);\r\n const explicit = isProductionMapCategoryKey(explicitPrimary) ? [explicitPrimary] : [];\r\n const affected = Array.isArray(explicitAffected)\r\n ? explicitAffected.filter(isProductionMapCategoryKey)\r\n : [];\r\n\r\n const primarySeed = matched[0] ? [matched[0], fallback] : [fallback];\r\n return uniqueMapCategories([...explicit, ...primarySeed, ...matched, ...affected]);\r\n}\r\n\r\nfunction slugify(value: string): string {\r\n return value\r\n .trim()\r\n .toLowerCase()\r\n .replace(/&/g, 'and')\r\n .replace(/[^a-z0-9]+/g, '-')\r\n .replace(/^-+|-+$/g, '')\r\n .slice(0, 52);\r\n}\r\n\r\nfunction normalizeToolSuggestion(v: unknown): ToolSuggestion | null {\r\n if (!isRecord(v)) return null;\r\n const name = typeof v.name === 'string' ? v.name.trim() : '';\r\n const url = typeof v.url === 'string' ? v.url.trim() : '';\r\n if (!name || !url) return null;\r\n return { name, url, reason: typeof v.reason === 'string' ? v.reason : '' };\r\n}\r\n\r\nexport function normalizeGap(v: unknown): Gap | null {\r\n if (!isRecord(v)) return null;\r\n const title = typeof v.title === 'string' ? v.title.trim() : '';\r\n const copyPrompt = typeof v.copyPrompt === 'string' ? v.copyPrompt.trim() : '';\r\n if (!title || !copyPrompt) return null;\r\n\r\n const severity = VALID_SEVERITY.includes(v.severity as GapSeverity)\r\n ? (v.severity as GapSeverity)\r\n : 'warning';\r\n\r\n const category = VALID_CATEGORIES.includes(v.category as GapCategory)\r\n ? (v.category as GapCategory)\r\n : 'MISSING FEATURES';\r\n\r\n const toolSuggestions = Array.isArray(v.toolSuggestions)\r\n ? v.toolSuggestions.map(normalizeToolSuggestion).filter((t): t is ToolSuggestion => t !== null)\r\n : [];\r\n\r\n const affectedMapCategories = inferMapCategories(\r\n category,\r\n title,\r\n typeof v.detail === 'string' ? v.detail : '',\r\n copyPrompt,\r\n v.primaryMapCategory,\r\n v.affectedMapCategories\r\n );\r\n\r\n return {\r\n id: typeof v.id === 'string' && v.id.trim() ? v.id.trim() : `gap-${slugify(title) || 'root'}`,\r\n category,\r\n severity,\r\n title,\r\n detail: typeof v.detail === 'string' ? v.detail : '',\r\n copyPrompt,\r\n toolSuggestions,\r\n mcpSuggestion: typeof v.mcpSuggestion === 'string' ? v.mcpSuggestion : null,\r\n primaryMapCategory: affectedMapCategories[0],\r\n affectedMapCategories,\r\n };\r\n}\r\n\r\nfunction rootGapKey(gap: Gap): string {\r\n const titleKey = slugify(gap.title);\r\n if (titleKey) {\r\n return titleKey;\r\n }\r\n return slugify([gap.category, gap.copyPrompt].join(' ')) || gap.id;\r\n}\r\n\r\nfunction mergeToolSuggestions(a: ToolSuggestion[], b: ToolSuggestion[]): ToolSuggestion[] {\r\n const seen = new Set<string>();\r\n const out: ToolSuggestion[] = [];\r\n for (const tool of [...a, ...b]) {\r\n const key = `${tool.name.trim().toLowerCase()}|${tool.url.trim().toLowerCase()}`;\r\n if (!seen.has(key)) {\r\n seen.add(key);\r\n out.push(tool);\r\n }\r\n }\r\n return out;\r\n}\r\n\r\nfunction mergeRootGaps(a: Gap, b: Gap): Gap {\r\n const severity = SEVERITY_RANK[b.severity] > SEVERITY_RANK[a.severity] ? b.severity : a.severity;\r\n return {\r\n ...a,\r\n severity,\r\n detail: b.detail.length > a.detail.length ? b.detail : a.detail,\r\n copyPrompt: b.copyPrompt.length > a.copyPrompt.length ? b.copyPrompt : a.copyPrompt,\r\n toolSuggestions: mergeToolSuggestions(a.toolSuggestions, b.toolSuggestions),\r\n mcpSuggestion: a.mcpSuggestion ?? b.mcpSuggestion,\r\n primaryMapCategory: a.primaryMapCategory,\r\n affectedMapCategories: a.affectedMapCategories,\r\n };\r\n}\r\n\r\nfunction dedupeRootGaps(gaps: Gap[]): Gap[] {\r\n const byKey = new Map<string, Gap>();\r\n const order: string[] = [];\r\n for (const gap of gaps) {\r\n const key = rootGapKey(gap);\r\n const existing = byKey.get(key);\r\n if (!existing) {\r\n byKey.set(key, gap);\r\n order.push(key);\r\n continue;\r\n }\r\n byKey.set(key, mergeRootGaps(existing, gap));\r\n }\r\n return order.map((key) => byKey.get(key)).filter((gap): gap is Gap => Boolean(gap));\r\n}\r\n\r\nfunction normalizeChecklist(v: unknown): ProductionChecklist {\r\n const defaults: ProductionChecklist = {\r\n security: 50, database: 50, auth: 50, errorHandling: 50,\r\n deployment: 50, testing: 50, landing: 50, monitoring: 50\r\n };\r\n if (!isRecord(v)) return defaults;\r\n return {\r\n security: clampScore(v.security),\r\n database: clampScore(v.database),\r\n auth: clampScore(v.auth),\r\n errorHandling: clampScore(v.errorHandling),\r\n deployment: clampScore(v.deployment),\r\n testing: clampScore(v.testing),\r\n landing: clampScore(v.landing),\r\n monitoring: clampScore(v.monitoring),\r\n };\r\n}\r\n\r\nexport function normalizeModelOutput(raw: Partial<ModelStationOutput>): ModelStationOutput {\r\n const gaps = Array.isArray(raw.gaps)\r\n ? raw.gaps.map(normalizeGap).filter((g): g is Gap => g !== null)\r\n : [];\r\n const uniqueGaps = dedupeRootGaps(gaps);\r\n\r\n return {\r\n score: stableVisibleScore(raw.score),\r\n scoreLabel: typeof raw.scoreLabel === 'string' && raw.scoreLabel.trim() ? raw.scoreLabel : 'Drifting',\r\n summary: typeof raw.summary === 'string' && raw.summary.trim() ? raw.summary : 'Scan complete.',\r\n archetype: typeof raw.archetype === 'string' && raw.archetype.trim() ? raw.archetype : 'unknown',\r\n gaps: uniqueGaps,\r\n stackDetected: toStringArray(raw.stackDetected),\r\n missingLayers: toStringArray(raw.missingLayers),\r\n quickWins: toStringArray(raw.quickWins),\r\n productionChecklist: normalizeChecklist(raw.productionChecklist),\r\n };\r\n}\r\n\r\nexport function adaptManagedStationResponse(response: ManagedStationResponse): ModelStationOutput {\r\n const structured = parseManagedStructuredOutput(response.output);\r\n if (structured) {\r\n return structured;\r\n }\r\n\r\n const scoreMap: Record<string, number> = { stable: 75, drifting: 50, chaos: 25 };\r\n const labelMap: Record<string, string> = { stable: 'Stable', drifting: 'Drifting', chaos: 'Chaos' };\r\n const score = scoreMap[response.status] ?? 50;\r\n\r\n const gaps: Gap[] = [];\r\n if (response.output && response.output.trim()) {\r\n gaps.push({\r\n id: 'managed-output',\r\n category: 'MISSING FEATURES',\r\n severity: 'warning',\r\n title: 'Station recommendation',\r\n detail: response.reason,\r\n copyPrompt: response.output,\r\n toolSuggestions: [],\r\n mcpSuggestion: null,\r\n primaryMapCategory: 'appFlow',\r\n affectedMapCategories: ['appFlow'],\r\n });\r\n }\r\n\r\n const checklist: ProductionChecklist = {\r\n security: score, database: score, auth: score, errorHandling: score,\r\n deployment: score, testing: score, landing: score, monitoring: score,\r\n };\r\n\r\n return {\r\n score,\r\n scoreLabel: labelMap[response.status] ?? 'Drifting',\r\n summary: response.reason,\r\n archetype: 'unknown',\r\n gaps,\r\n stackDetected: [],\r\n missingLayers: [],\r\n quickWins: [],\r\n productionChecklist: checklist,\r\n };\r\n}\r\n\r\nfunction parseManagedStructuredOutput(output: string): ModelStationOutput | null {\r\n try {\r\n const parsed = JSON.parse(output) as Partial<ModelStationOutput>;\r\n if (!Array.isArray(parsed.gaps) || !isRecord(parsed.productionChecklist)) {\r\n return null;\r\n }\r\n return normalizeModelOutput(parsed);\r\n } catch {\r\n return null;\r\n }\r\n}\r\n", "import type {\r\n ProductionConnectionProvider,\r\n StackWiringArea,\r\n StackWiringKey,\r\n StackWiringProvider\r\n} from './types';\r\n\r\ntype SifgTemplateRegistryProvider =\r\n | StackWiringProvider\r\n | ProductionConnectionProvider\r\n | 'netlify'\r\n | 'aws'\r\n | 'playwright';\r\n\r\nexport interface SifgTemplate {\r\n id: string;\r\n label: string;\r\n registryProvider: SifgTemplateRegistryProvider;\r\n providerKey: StackWiringKey;\r\n area: StackWiringArea;\r\n sourceMatchers: Array<Record<string, string>>;\r\n requiredGuards: Array<{\r\n kind: string;\r\n symbols: string[];\r\n requiresEnvNames?: string[];\r\n mustPrecede: string[];\r\n }>;\r\n forbiddenFlows: Array<Record<string, string>>;\r\n repoFixPolicy: {\r\n allowedFileGlobs: string[];\r\n blockedFileGlobs: string[];\r\n requiresApproval: true;\r\n };\r\n}\r\n\r\nconst BLOCKED_PRODUCT_GLOBS = ['landing/**', 'services/api/**', 'marketing/**'];\r\n\r\nconst TEMPLATES: SifgTemplate[] = [\r\n {\r\n id: 'template:payments:stripe:webhook-ingress',\r\n label: 'Stripe webhook ingress',\r\n registryProvider: 'stripe',\r\n providerKey: 'stripe-payments',\r\n area: 'payments',\r\n sourceMatchers: [\r\n { kind: 'route-handler', framework: 'nextjs-app-router', routePattern: '/api/**/stripe/**', method: 'POST' },\r\n { kind: 'sdk-symbol', importName: 'stripe', member: 'webhooks.constructEvent' }\r\n ],\r\n requiredGuards: [\r\n {\r\n kind: 'signature-verifier',\r\n symbols: ['stripe.webhooks.constructEvent'],\r\n requiresEnvNames: ['STRIPE_WEBHOOK_SECRET'],\r\n mustPrecede: ['database-write', 'entitlement-update', 'provider-mutation']\r\n },\r\n {\r\n kind: 'idempotency-guard',\r\n symbols: ['event.id', 'idempotencyKey', 'processed_events'],\r\n mustPrecede: ['entitlement-update']\r\n }\r\n ],\r\n forbiddenFlows: [\r\n { from: 'request-body', to: 'database-write', unlessGuardedBy: 'signature-verifier' },\r\n { from: 'env:STRIPE_SECRET_KEY', to: 'client-bundle', severity: 'critical' }\r\n ],\r\n repoFixPolicy: {\r\n allowedFileGlobs: ['app/**/route.ts', 'src/server/**', 'lib/server/**'],\r\n blockedFileGlobs: BLOCKED_PRODUCT_GLOBS,\r\n requiresApproval: true\r\n }\r\n },\r\n {\r\n id: 'template:auth:protected-data-access',\r\n label: 'Protected data access',\r\n registryProvider: 'clerk',\r\n providerKey: 'clerk-auth',\r\n area: 'auth',\r\n sourceMatchers: [{ kind: 'route-handler', routePattern: '/api/**', method: 'ANY' }],\r\n requiredGuards: [{ kind: 'auth-guard', symbols: ['auth', 'getServerSession', 'currentUser'], mustPrecede: ['database-read', 'database-write'] }],\r\n forbiddenFlows: [{ from: 'private-data', to: 'response', unlessGuardedBy: 'auth-guard' }],\r\n repoFixPolicy: {\r\n allowedFileGlobs: ['app/**/route.ts', 'src/server/**', 'lib/server/**', 'middleware.ts', 'src/middleware.ts'],\r\n blockedFileGlobs: BLOCKED_PRODUCT_GLOBS,\r\n requiresApproval: true\r\n }\r\n },\r\n {\r\n id: 'template:database:supabase:service-role-boundary',\r\n label: 'Supabase service role boundary',\r\n registryProvider: 'supabase',\r\n providerKey: 'supabase-database',\r\n area: 'database',\r\n sourceMatchers: [{ kind: 'env-read', envName: 'SUPABASE_SERVICE_ROLE_KEY' }],\r\n requiredGuards: [{ kind: 'server-only-boundary', symbols: ['server-only'], mustPrecede: ['database-read', 'database-write'] }],\r\n forbiddenFlows: [{ from: 'env:SUPABASE_SERVICE_ROLE_KEY', to: 'client-bundle', severity: 'critical' }],\r\n repoFixPolicy: {\r\n allowedFileGlobs: ['src/server/**', 'lib/server/**', 'app/**/route.ts', 'supabase/**'],\r\n blockedFileGlobs: BLOCKED_PRODUCT_GLOBS,\r\n requiresApproval: true\r\n }\r\n },\r\n {\r\n id: 'template:security:public-route-abuse-guard',\r\n label: 'Public route abuse guard',\r\n registryProvider: 'rate-limit',\r\n providerKey: 'rate-limit-security',\r\n area: 'security',\r\n sourceMatchers: [{ kind: 'route-handler', routePattern: '/api/**', method: 'ANY' }],\r\n requiredGuards: [{ kind: 'rate-limit-guard', symbols: ['ratelimit', 'rateLimit', 'upstash'], mustPrecede: ['provider-mutation', 'database-write'] }],\r\n forbiddenFlows: [{ from: 'public-request', to: 'expensive-sink', unlessGuardedBy: 'rate-limit-guard' }],\r\n repoFixPolicy: {\r\n allowedFileGlobs: ['app/**/route.ts', 'src/server/**', 'lib/server/**'],\r\n blockedFileGlobs: BLOCKED_PRODUCT_GLOBS,\r\n requiresApproval: true\r\n }\r\n },\r\n {\r\n id: 'template:security:secret-boundary',\r\n label: 'Secret boundary',\r\n registryProvider: 'secrets-hygiene',\r\n providerKey: 'secrets-hygiene-security',\r\n area: 'security',\r\n sourceMatchers: [{ kind: 'env-read', envName: '*' }],\r\n requiredGuards: [{ kind: 'server-only-boundary', symbols: ['server-only'], mustPrecede: ['client-bundle'] }],\r\n forbiddenFlows: [{ from: 'env:*', to: 'client-bundle', severity: 'critical' }],\r\n repoFixPolicy: {\r\n allowedFileGlobs: ['src/**', 'lib/**', 'app/**'],\r\n blockedFileGlobs: BLOCKED_PRODUCT_GLOBS,\r\n requiresApproval: true\r\n }\r\n },\r\n {\r\n id: 'template:errorHandling:safe-error-response',\r\n label: 'Safe error response',\r\n registryProvider: 'sentry',\r\n providerKey: 'sentry-error-handling',\r\n area: 'errorHandling',\r\n sourceMatchers: [{ kind: 'throw-or-catch', routePattern: '/api/**' }],\r\n requiredGuards: [{ kind: 'error-capture', symbols: ['Sentry.captureException', 'captureException'], mustPrecede: ['safe-response'] }],\r\n forbiddenFlows: [{ from: 'provider-error', to: 'client-response', unlessGuardedBy: 'safe-response' }],\r\n repoFixPolicy: {\r\n allowedFileGlobs: ['app/**/route.ts', 'src/server/**', 'lib/server/**'],\r\n blockedFileGlobs: BLOCKED_PRODUCT_GLOBS,\r\n requiresApproval: true\r\n }\r\n }\r\n];\r\n\r\nexport const SIFG_TEMPLATE_IDS = TEMPLATES.map((template) => template.id);\r\n\r\nexport function allSifgTemplates(): SifgTemplate[] {\r\n return TEMPLATES.map((template) => ({\r\n ...template,\r\n sourceMatchers: template.sourceMatchers.map((matcher) => ({ ...matcher })),\r\n requiredGuards: template.requiredGuards.map((guard) => ({\r\n ...guard,\r\n symbols: [...guard.symbols],\r\n requiresEnvNames: guard.requiresEnvNames ? [...guard.requiresEnvNames] : undefined,\r\n mustPrecede: [...guard.mustPrecede]\r\n })),\r\n forbiddenFlows: template.forbiddenFlows.map((flow) => ({ ...flow })),\r\n repoFixPolicy: {\r\n allowedFileGlobs: [...template.repoFixPolicy.allowedFileGlobs],\r\n blockedFileGlobs: [...template.repoFixPolicy.blockedFileGlobs],\r\n requiresApproval: true\r\n }\r\n }));\r\n}\r\n\r\nexport function sifgTemplatesForProviderKey(providerKey: StackWiringKey): SifgTemplate[] {\r\n return allSifgTemplates().filter((template) => template.providerKey === providerKey);\r\n}\r\n\r\nexport function sifgTemplatesForRegistryProviderArea(\r\n registryProvider: SifgTemplateRegistryProvider,\r\n area: StackWiringArea\r\n): SifgTemplate[] {\r\n return allSifgTemplates().filter((template) =>\r\n template.registryProvider === registryProvider && template.area === area\r\n );\r\n}\r\n", "import type {\r\n ProductionConnectionArea,\r\n ProductionConnectionProvider,\r\n ProviderMcpTemplate,\r\n ProviderRegistryEntry,\r\n ProviderRegistrySnapshot,\r\n ProviderRegistryStatus,\r\n StackWiringArea,\r\n StackWiringKey\r\n} from './types';\r\nimport { sifgTemplatesForRegistryProviderArea } from './sifgTemplates';\r\n\r\nexport const PROVIDER_REGISTRY_STALE_AFTER_DAYS = 45;\r\n\r\ntype RegistryProvider = ProviderRegistryEntry['provider'];\r\ntype NonProductionRegistryProvider = Exclude<RegistryProvider, ProductionConnectionProvider>;\r\ntype ProviderSeedBase = Omit<ProviderRegistryEntry, 'provider' | 'productionAreas' | 'status'>;\r\ntype ProductionProviderSeed = ProviderSeedBase & {\r\n provider: ProductionConnectionProvider;\r\n productionAreas: ProductionConnectionArea[];\r\n};\r\ntype NonProductionProviderSeed = ProviderSeedBase & {\r\n provider: NonProductionRegistryProvider;\r\n productionAreas: [];\r\n};\r\ntype ProviderSeed = ProductionProviderSeed | NonProductionProviderSeed;\r\n\r\nconst PROVIDERS: ProviderSeed[] = [\r\n provider('supabase', 'Supabase', ['supabase'], ['database', 'landing'], ['database', 'auth'], 'supabase', {\r\n docsUrl: 'https://supabase.com/docs',\r\n dashboardUrl: 'https://supabase.com/dashboard',\r\n mcp: {\r\n label: 'Supabase',\r\n serverName: 'supabase',\r\n vscodeServer: { type: 'http', url: 'https://mcp.supabase.com/mcp?read_only=true' },\r\n cursorServer: { url: 'https://mcp.supabase.com/mcp?read_only=true' },\r\n keyInstructions: 'For hosted Supabase MCP, no API key goes in this file. Your IDE opens browser OAuth after you add the server. A Supabase access token is only needed for CI/manual-header setups, where it is passed as Authorization: Bearer ${SUPABASE_ACCESS_TOKEN}.'\r\n },\r\n verification: { supportsReadOnly: true }\r\n }),\r\n provider('supabase-auth', 'Supabase Auth', ['supabaseauth'], ['auth'], [], 'supabase', {\r\n docsUrl: 'https://supabase.com/docs/guides/auth',\r\n dashboardUrl: 'https://supabase.com/dashboard'\r\n }),\r\n provider('clerk', 'Clerk', ['clerk'], ['auth'], ['auth'], 'clerk', {\r\n docsUrl: 'https://clerk.com/docs',\r\n dashboardUrl: 'https://dashboard.clerk.com',\r\n mcp: {\r\n label: 'Clerk',\r\n serverName: 'clerk',\r\n vscodeServer: { type: 'http', url: 'https://mcp.clerk.com/mcp' },\r\n cursorServer: { url: 'https://mcp.clerk.com/mcp' },\r\n keyInstructions: 'Clerk MCP uses your Clerk credentials. If your IDE asks for a token, create one from the Clerk Dashboard developer settings.'\r\n },\r\n verification: { supportsReadOnly: true }\r\n }),\r\n provider('authjs', 'Auth.js', ['authjs', 'auth', 'nextauth'], ['auth'], ['auth'], 'authjs', {\r\n docsUrl: 'https://authjs.dev'\r\n }),\r\n provider('neon', 'Neon', ['neon'], ['database'], ['database'], 'neon', {\r\n docsUrl: 'https://neon.tech/docs',\r\n dashboardUrl: 'https://console.neon.tech',\r\n mcp: {\r\n label: 'Neon',\r\n serverName: 'neon',\r\n vscodeServer: { type: 'http', url: 'https://mcp.neon.tech/mcp' },\r\n cursorServer: { url: 'https://mcp.neon.tech/mcp' },\r\n keyInstructions: 'Neon MCP normally opens browser OAuth. Use Neon project/database credentials only when your IDE asks for them.'\r\n },\r\n verification: { supportsReadOnly: true }\r\n }),\r\n provider('planetscale', 'PlanetScale', ['planetscale'], ['database'], ['database'], 'planetscale', {\r\n docsUrl: 'https://planetscale.com/docs',\r\n dashboardUrl: 'https://app.planetscale.com',\r\n mcp: {\r\n label: 'PlanetScale',\r\n serverName: 'planetscale',\r\n vscodeServer: { type: 'http', url: 'https://mcp.pscale.dev/mcp/planetscale' },\r\n cursorServer: { url: 'https://mcp.pscale.dev/mcp/planetscale' },\r\n keyInstructions: 'PlanetScale MCP normally opens browser OAuth. Use a PlanetScale service token only for local/manual fallback setups.'\r\n },\r\n verification: { supportsReadOnly: true }\r\n }),\r\n provider('mongodb', 'MongoDB Atlas', ['mongodb', 'mongodbatlas'], ['database'], ['database'], 'mongodb', {\r\n docsUrl: 'https://www.mongodb.com/docs',\r\n dashboardUrl: 'https://cloud.mongodb.com',\r\n mcp: {\r\n label: 'MongoDB',\r\n serverName: 'mongodb',\r\n vscodeServer: { type: 'stdio', command: 'npx', args: ['-y', 'mongodb-mcp-server', '--connectionString', 'mongodb://localhost:27017/myDatabase', '--readOnly'] },\r\n cursorServer: { command: 'npx', args: ['-y', 'mongodb-mcp-server', '--connectionString', 'mongodb://localhost:27017/myDatabase', '--readOnly'] },\r\n keyInstructions: 'MongoDB MCP runs locally. Replace the connection string placeholder with a local or Atlas connection string and keep readOnly until you trust the workflow.'\r\n },\r\n verification: { supportsReadOnly: false }\r\n }),\r\n provider('turso', 'Turso', ['turso'], ['database'], ['database'], 'turso', {\r\n docsUrl: 'https://docs.turso.tech',\r\n dashboardUrl: 'https://app.turso.tech'\r\n }),\r\n provider('stripe', 'Stripe', ['stripe'], ['payments'], ['payments'], 'stripe', {\r\n docsUrl: 'https://docs.stripe.com',\r\n dashboardUrl: 'https://dashboard.stripe.com',\r\n mcp: {\r\n label: 'Stripe',\r\n serverName: 'stripe',\r\n vscodeServer: { type: 'http', url: 'https://mcp.stripe.com' },\r\n cursorServer: { url: 'https://mcp.stripe.com' },\r\n keyInstructions: 'Stripe remote MCP normally authenticates with OAuth in the IDE. For local or custom bearer-token setups, use a restricted Stripe secret key from Developers > API keys.'\r\n },\r\n verification: { supportsReadOnly: true }\r\n }),\r\n provider('paddle', 'Paddle', ['paddle'], ['payments'], ['payments'], 'paddle', {\r\n docsUrl: 'https://developer.paddle.com',\r\n dashboardUrl: 'https://vendors.paddle.com',\r\n mcp: {\r\n label: 'Paddle',\r\n serverName: 'paddle',\r\n vscodeServer: { type: 'stdio', command: 'npx', args: ['-y', '@paddle/paddle-mcp', '--api-key=YOUR_API_KEY', '--environment=sandbox', '--tools=non-destructive'] },\r\n cursorServer: { command: 'npx', args: ['-y', '@paddle/paddle-mcp', '--api-key=YOUR_API_KEY', '--environment=sandbox', '--tools=non-destructive'] },\r\n keyInstructions: 'Paddle MCP needs your Paddle authentication. Replace YOUR_API_KEY with a sandbox or production API key before enabling write-capable tools.'\r\n },\r\n verification: { supportsReadOnly: false }\r\n }),\r\n provider('vercel', 'Vercel', ['vercel'], ['deployment'], ['deployment'], 'vercel', {\r\n docsUrl: 'https://vercel.com/docs',\r\n dashboardUrl: 'https://vercel.com/dashboard',\r\n mcp: {\r\n label: 'Vercel',\r\n serverName: 'vercel',\r\n vscodeServer: { type: 'http', url: 'https://mcp.vercel.com' },\r\n cursorServer: { url: 'https://mcp.vercel.com' },\r\n keyInstructions: 'Vercel MCP is a remote OAuth server. Finish the browser sign-in your IDE opens; only use a Vercel token for a separate CLI/local fallback.'\r\n },\r\n verification: { supportsReadOnly: true }\r\n }),\r\n provider('netlify', 'Netlify', ['netlify'], ['deployment'], [], 'netlify', {\r\n docsUrl: 'https://docs.netlify.com',\r\n dashboardUrl: 'https://app.netlify.com',\r\n mcp: {\r\n label: 'Netlify',\r\n serverName: 'netlify',\r\n vscodeServer: { type: 'stdio', command: 'npx', args: ['-y', '@netlify/mcp'] },\r\n cursorServer: { command: 'npx', args: ['-y', '@netlify/mcp'] },\r\n keyInstructions: 'Netlify MCP uses Netlify authentication from the IDE or CLI. Finish the browser sign-in or token prompt it opens.'\r\n },\r\n verification: { supportsReadOnly: false }\r\n }),\r\n provider('aws', 'AWS', ['aws'], ['deployment'], [], 'aws', {\r\n docsUrl: 'https://docs.aws.amazon.com',\r\n dashboardUrl: 'https://console.aws.amazon.com'\r\n }),\r\n provider('sentry', 'Sentry', ['sentry'], ['monitoring', 'errorHandling'], ['monitoring'], 'sentry', {\r\n docsUrl: 'https://docs.sentry.io',\r\n dashboardUrl: 'https://sentry.io',\r\n mcp: {\r\n label: 'Sentry',\r\n serverName: 'sentry',\r\n vscodeServer: { type: 'http', url: 'https://mcp.sentry.dev/mcp' },\r\n cursorServer: { url: 'https://mcp.sentry.dev/mcp' },\r\n keyInstructions: 'Sentry MCP is a remote MCP server. Finish the IDE/browser authentication flow; only use a Sentry auth token for separate local or CLI fallback setups.'\r\n },\r\n verification: { supportsReadOnly: true }\r\n }),\r\n provider('posthog', 'PostHog', ['posthog'], ['monitoring', 'errorHandling', 'landing'], ['monitoring'], 'posthog', {\r\n docsUrl: 'https://posthog.com/docs',\r\n dashboardUrl: 'https://app.posthog.com',\r\n mcp: {\r\n label: 'PostHog',\r\n serverName: 'posthog',\r\n vscodeServer: { type: 'http', url: 'https://mcp.posthog.com/mcp' },\r\n cursorServer: { url: 'https://mcp.posthog.com/mcp' },\r\n keyInstructions: 'PostHog MCP opens an authentication flow. Use a PostHog personal API key only if the IDE or local fallback asks for one.'\r\n },\r\n verification: { supportsReadOnly: true }\r\n }),\r\n provider('logrocket', 'LogRocket', ['logrocket'], ['monitoring'], ['monitoring'], 'logrocket', {\r\n docsUrl: 'https://docs.logrocket.com',\r\n dashboardUrl: 'https://app.logrocket.com'\r\n }),\r\n provider('playwright', 'Playwright', ['playwright', 'playwrighttest'], ['testing'], [], 'playwright', {\r\n docsUrl: 'https://playwright.dev/docs/intro',\r\n mcp: {\r\n label: 'Playwright',\r\n serverName: 'playwright',\r\n vscodeServer: { type: 'stdio', command: 'npx', args: ['-y', '@playwright/mcp@latest'] },\r\n cursorServer: { command: 'npx', args: ['-y', '@playwright/mcp@latest'] },\r\n keyInstructions: 'Playwright MCP runs locally through npx and normally does not need an API key.'\r\n },\r\n verification: { supportsReadOnly: false }\r\n }),\r\n provider('rate-limit', 'Rate limiting', ['upstash', 'upstashratelimit', 'ratelimit', 'ratelimiting', 'expressratelimit'], ['security'], ['security'], 'rate-limit', {\r\n docsUrl: 'https://upstash.com/docs/redis/sdks/ratelimit/overview',\r\n dashboardUrl: 'https://console.upstash.com',\r\n mcp: {\r\n label: 'Upstash',\r\n serverName: 'upstash',\r\n vscodeServer: { type: 'stdio', command: 'npx', args: ['-y', '@upstash/mcp-server@latest', '--email', '<UPSTASH_EMAIL>', '--api-key', '<UPSTASH_API_KEY>'] },\r\n cursorServer: { command: 'npx', args: ['-y', '@upstash/mcp-server@latest', '--email', '<UPSTASH_EMAIL>', '--api-key', '<UPSTASH_API_KEY>'] },\r\n keyInstructions: 'Upstash MCP needs your Upstash account email and API key. Replace the placeholders before enabling the server.'\r\n },\r\n verification: { supportsReadOnly: false }\r\n }),\r\n provider('bot-protection', 'Bot protection', ['botprotection', 'cloudflareturnstile', 'turnstile', 'cloudflare'], ['security'], ['security'], 'bot-protection', {\r\n docsUrl: 'https://developers.cloudflare.com/turnstile',\r\n dashboardUrl: 'https://dash.cloudflare.com',\r\n mcp: {\r\n label: 'Cloudflare',\r\n serverName: 'cloudflare-api',\r\n vscodeServer: { type: 'http', url: 'https://mcp.cloudflare.com/mcp' },\r\n cursorServer: { url: 'https://mcp.cloudflare.com/mcp' },\r\n keyInstructions: 'Cloudflare MCP uses Cloudflare account authentication. Finish browser sign-in or provide an API token only when prompted.'\r\n },\r\n verification: { supportsReadOnly: true }\r\n }),\r\n provider('secrets-hygiene', 'Secrets hygiene', ['secretshygiene', 'envhygiene'], ['security'], ['security'], 'secrets-hygiene'),\r\n provider('figma', 'Figma', ['figma'], ['appFlow'], [], 'figma', { docsUrl: 'https://help.figma.com' }),\r\n provider('storybook', 'Storybook', ['storybook'], ['appFlow'], [], 'storybook', { docsUrl: 'https://storybook.js.org/docs' }),\r\n provider('product-spec', 'Product Spec', ['productspec', 'prd'], ['appFlow'], [], 'product-spec'),\r\n provider('route-map', 'Route Map', ['routemap', 'routes'], ['appFlow'], [], 'route-map'),\r\n provider('react', 'React', ['react', 'reactjs'], ['frontend'], [], 'react', { docsUrl: 'https://react.dev' }),\r\n provider('vue', 'Vue', ['vue', 'vuejs'], ['frontend'], [], 'vue', { docsUrl: 'https://vuejs.org/guide' }),\r\n provider('svelte', 'Svelte', ['svelte', 'sveltekit'], ['frontend'], [], 'svelte', { docsUrl: 'https://svelte.dev/docs' }),\r\n provider('angular', 'Angular', ['angular'], ['frontend'], [], 'angular', { docsUrl: 'https://angular.dev' }),\r\n provider('node', 'Node.js', ['node', 'nodejs', 'node.js'], ['backend'], [], 'nodejs', { docsUrl: 'https://nodejs.org/docs/latest/api' }),\r\n provider('python', 'Python / FastAPI', ['python', 'pythonfastapi', 'fastapi'], ['backend'], [], 'python', { docsUrl: 'https://fastapi.tiangolo.com' }),\r\n provider('rails', 'Rails', ['rails', 'rubyonrails'], ['backend'], [], 'rails', { docsUrl: 'https://guides.rubyonrails.org' }),\r\n provider('go', 'Go', ['go', 'golang'], ['backend'], [], 'go', { docsUrl: 'https://go.dev/doc' }),\r\n provider('vitest', 'Vitest', ['vitest'], ['testing'], [], 'vitest', { docsUrl: 'https://vitest.dev' })\r\n];\r\n\r\nconst PROVIDERS_BY_KEY = new Map<string, ProviderSeed>(PROVIDERS.map((entry) => [entry.provider, entry]));\r\nconst PROVIDERS_BY_ALIAS = new Map<string, ProviderSeed>();\r\nfor (const entry of PROVIDERS) {\r\n PROVIDERS_BY_ALIAS.set(normalizeProviderToken(entry.provider), entry);\r\n for (const alias of entry.aliases) {\r\n PROVIDERS_BY_ALIAS.set(normalizeProviderToken(alias), entry);\r\n }\r\n}\r\n\r\nexport function getProviderRegistryEntry(provider: string): ProviderRegistryEntry | null {\r\n const entry = PROVIDERS_BY_ALIAS.get(normalizeProviderToken(provider)) ?? null;\r\n return entry ? withStatus(entry, new Date()) : null;\r\n}\r\n\r\nexport function normalizeProviderKey(provider: string): string {\r\n return PROVIDERS_BY_ALIAS.get(normalizeProviderToken(provider))?.provider ?? normalizeProviderToken(provider);\r\n}\r\n\r\nexport function providerLabel(provider: string): string {\r\n return getProviderRegistryEntry(provider)?.label ?? titleizeProvider(provider);\r\n}\r\n\r\nexport function productionProviders(): ProductionConnectionProvider[] {\r\n return PROVIDERS\r\n .filter(isProductionProviderSeed)\r\n .map((entry) => entry.provider);\r\n}\r\n\r\nexport function productionProvidersByArea(): Record<ProductionConnectionArea, readonly ProductionConnectionProvider[]> {\r\n return {\r\n database: providersForProductionArea('database'),\r\n auth: providersForProductionArea('auth'),\r\n payments: providersForProductionArea('payments'),\r\n deployment: providersForProductionArea('deployment'),\r\n monitoring: providersForProductionArea('monitoring'),\r\n security: providersForProductionArea('security')\r\n };\r\n}\r\n\r\nexport function mcpTemplateForProvider(provider: string): ProviderMcpTemplate | null {\r\n const normalized = normalizeProviderKey(provider);\r\n const entry = PROVIDERS_BY_KEY.get(normalized);\r\n if (entry?.mcp) {\r\n return cloneMcpTemplate(entry.mcp);\r\n }\r\n if (normalized === 'supabase-auth') {\r\n const supabaseMcp = PROVIDERS_BY_KEY.get('supabase')?.mcp;\r\n return supabaseMcp ? cloneMcpTemplate(supabaseMcp) : null;\r\n }\r\n return null;\r\n}\r\n\r\nexport function stackWiringKeyHasMcp(key: StackWiringKey): boolean {\r\n return Boolean(mcpTemplateForProvider(providerFromStackWiringKey(key)));\r\n}\r\n\r\nexport function mcpProviderIdForStackWiringKey(key: StackWiringKey): string | null {\r\n const provider = providerFromStackWiringKey(key);\r\n return mcpTemplateForProvider(provider) ? mcpServerProviderId(provider) : null;\r\n}\r\n\r\nexport function buildProviderRegistrySnapshot(now = new Date()): ProviderRegistrySnapshot {\r\n const providers = PROVIDERS.map((entry) => withStatus(entry, now));\r\n return {\r\n version: 1,\r\n source: 'bundled',\r\n generatedAt: now.toISOString(),\r\n staleAfterDays: PROVIDER_REGISTRY_STALE_AFTER_DAYS,\r\n status: providers.some((entry) => entry.status === 'stale') ? 'stale' : 'fresh',\r\n providers\r\n };\r\n}\r\n\r\nfunction provider(\r\n providerKey: ProductionConnectionProvider,\r\n label: string,\r\n aliases: string[],\r\n areas: StackWiringArea[],\r\n productionAreas: ProductionConnectionArea[],\r\n iconKey: string,\r\n extras?: Partial<Omit<ProviderSeedBase, 'label' | 'aliases' | 'areas' | 'iconKey' | 'verifiedAt'>>\r\n): ProductionProviderSeed;\r\nfunction provider(\r\n providerKey: NonProductionRegistryProvider,\r\n label: string,\r\n aliases: string[],\r\n areas: StackWiringArea[],\r\n productionAreas: [],\r\n iconKey: string,\r\n extras?: Partial<Omit<ProviderSeedBase, 'label' | 'aliases' | 'areas' | 'iconKey' | 'verifiedAt'>>\r\n): NonProductionProviderSeed;\r\nfunction provider(\r\n providerKey: RegistryProvider,\r\n label: string,\r\n aliases: string[],\r\n areas: StackWiringArea[],\r\n productionAreas: ProductionConnectionArea[],\r\n iconKey: string,\r\n extras: Partial<Omit<ProviderSeedBase, 'label' | 'aliases' | 'areas' | 'iconKey' | 'verifiedAt'>> = {}\r\n): ProviderSeed {\r\n const sifgTemplateIds = areas\r\n .flatMap((area) => sifgTemplatesForRegistryProviderArea(providerKey, area))\r\n .map((template) => template.id);\r\n\r\n return {\r\n provider: providerKey,\r\n label,\r\n aliases,\r\n areas,\r\n productionAreas,\r\n iconKey,\r\n verifiedAt: '2026-05-18',\r\n ...(sifgTemplateIds.length > 0 ? { sifgTemplateIds } : {}),\r\n ...extras\r\n } as ProviderSeed;\r\n}\r\n\r\nfunction providersForProductionArea(area: ProductionConnectionArea): ProductionConnectionProvider[] {\r\n return PROVIDERS\r\n .filter(isProductionProviderSeed)\r\n .filter((entry) => entry.productionAreas.includes(area))\r\n .map((entry) => entry.provider);\r\n}\r\n\r\nfunction isProductionProviderSeed(entry: ProviderSeed): entry is ProductionProviderSeed {\r\n return entry.productionAreas.length > 0;\r\n}\r\n\r\nfunction withStatus(entry: ProviderSeed, now: Date): ProviderRegistryEntry {\r\n const mcp = entry.mcp ? cloneMcpTemplate(entry.mcp) : undefined;\r\n const verification = entry.verification ? { ...entry.verification } : undefined;\r\n return {\r\n provider: entry.provider,\r\n label: entry.label,\r\n aliases: [...entry.aliases],\r\n areas: [...entry.areas],\r\n productionAreas: [...entry.productionAreas],\r\n iconKey: entry.iconKey,\r\n ...(entry.sifgTemplateIds ? { sifgTemplateIds: [...entry.sifgTemplateIds] } : {}),\r\n ...(entry.docsUrl ? { docsUrl: entry.docsUrl } : {}),\r\n ...(entry.dashboardUrl ? { dashboardUrl: entry.dashboardUrl } : {}),\r\n ...(mcp ? { mcp } : {}),\r\n ...(verification ? { verification } : {}),\r\n verifiedAt: entry.verifiedAt,\r\n status: registryStatus(entry.verifiedAt, now)\r\n };\r\n}\r\n\r\nfunction cloneMcpTemplate(template: ProviderMcpTemplate): ProviderMcpTemplate {\r\n return {\r\n label: template.label,\r\n serverName: template.serverName,\r\n vscodeServer: cloneRecord(template.vscodeServer),\r\n cursorServer: cloneRecord(template.cursorServer),\r\n keyInstructions: template.keyInstructions\r\n };\r\n}\r\n\r\nfunction cloneRecord(record: Record<string, unknown>): Record<string, unknown> {\r\n return Object.fromEntries(\r\n Object.entries(record).map(([key, value]) => [key, cloneUnknown(value)])\r\n );\r\n}\r\n\r\nfunction cloneUnknown(value: unknown): unknown {\r\n if (Array.isArray(value)) {\r\n return value.map(cloneUnknown);\r\n }\r\n if (value && typeof value === 'object') {\r\n return cloneRecord(value as Record<string, unknown>);\r\n }\r\n return value;\r\n}\r\n\r\nfunction registryStatus(verifiedAt: string, now: Date): ProviderRegistryStatus {\r\n const verifiedTime = Date.parse(`${verifiedAt}T00:00:00.000Z`);\r\n if (Number.isNaN(verifiedTime)) {\r\n return 'stale';\r\n }\r\n const ageMs = now.getTime() - verifiedTime;\r\n return ageMs > PROVIDER_REGISTRY_STALE_AFTER_DAYS * 24 * 60 * 60 * 1000 ? 'stale' : 'fresh';\r\n}\r\n\r\nfunction normalizeProviderToken(provider: string): string {\r\n return provider\r\n .toLowerCase()\r\n .replace(/&/g, 'and')\r\n .replace(/[^a-z0-9]+/g, '');\r\n}\r\n\r\nfunction providerFromStackWiringKey(key: StackWiringKey): string {\r\n return key\r\n .replace(/-(app-flow|frontend|backend|security|auth|database|payments|deployment|landing|monitoring|testing|error-handling)$/, '')\r\n .replace(/^supabase-database$/, 'supabase')\r\n .replace(/^supabase-landing$/, 'supabase')\r\n .replace(/^supabase-auth$/, 'supabase-auth');\r\n}\r\n\r\nfunction mcpServerProviderId(provider: string): string {\r\n if (provider === 'supabase-auth') {\r\n return 'supabase';\r\n }\r\n if (provider === 'rate-limit') {\r\n return 'upstash';\r\n }\r\n if (provider === 'bot-protection') {\r\n return 'cloudflare';\r\n }\r\n return provider;\r\n}\r\n\r\nfunction titleizeProvider(provider: string): string {\r\n return provider.replace(/(^|-)([a-z])/g, (_match, prefix: string, letter: string) =>\r\n `${prefix ? ' ' : ''}${letter.toUpperCase()}`\r\n );\r\n}\r\n", "import type {\r\n MissionArea,\r\n MissionCheck,\r\n MissionCheckStatus,\r\n MissionEvidenceClass,\r\n MissionGraph,\r\n ProviderMission,\r\n RepositoryEvidenceSummary,\r\n StackWiringArea,\r\n StackWiringItem,\r\n StackWiringProviderSummary,\r\n StackWiringSummary\r\n} from './types';\r\nimport { stackWiringKeyHasMcp } from './providerRegistry';\r\nimport type { SifgGraph, SifgLeak, SifgPipeline } from './sifgTypes';\r\n\r\ntype BuildMissionGraphInput = {\r\n stackWiring: StackWiringSummary;\r\n repositoryEvidence: RepositoryEvidenceSummary;\r\n staticInfrastructureFlowGraph?: SifgGraph;\r\n};\r\n\r\nconst AREA_LABELS: Record<StackWiringArea, string> = {\r\n appFlow: 'App Flow',\r\n frontend: 'Frontend',\r\n backend: 'Backend / API',\r\n database: 'Database',\r\n auth: 'Auth',\r\n payments: 'Payments',\r\n deployment: 'Deployment',\r\n monitoring: 'Monitoring',\r\n security: 'Security',\r\n testing: 'Testing',\r\n landing: 'Landing / Onboarding',\r\n errorHandling: 'Error Handling'\r\n};\r\n\r\nexport function buildMissionGraph(input: BuildMissionGraphInput): MissionGraph {\r\n const providerMissions = input.stackWiring.items.map(toProviderMission);\r\n if (input.staticInfrastructureFlowGraph) {\r\n overlaySifgLeaks(providerMissions, input.staticInfrastructureFlowGraph);\r\n }\r\n const byProvider = providerMissions.reduce<MissionGraph['byProvider']>((acc, mission) => {\r\n acc[mission.key] = mission;\r\n return acc;\r\n }, {});\r\n const areas = buildAreas(providerMissions);\r\n const byArea = areas.reduce<MissionGraph['byArea']>((acc, area) => {\r\n acc[area.key] = area;\r\n return acc;\r\n }, {});\r\n\r\n return {\r\n areas,\r\n byArea,\r\n byProvider,\r\n repositoryEvidence: input.repositoryEvidence,\r\n ...(input.staticInfrastructureFlowGraph\r\n ? { staticInfrastructureFlowGraph: input.staticInfrastructureFlowGraph }\r\n : {})\r\n };\r\n}\r\n\r\nfunction toProviderMission(summary: StackWiringProviderSummary): ProviderMission {\r\n const checks = summary.items.map((item) => toMissionCheck(summary, item));\r\n if (stackWiringKeyHasMcp(summary.key)) {\r\n checks.push({\r\n id: `${summary.key}-mcp-verifier`,\r\n label: `${summary.providerLabel} MCP verifier available`,\r\n providerKey: summary.key,\r\n providerLabel: summary.providerLabel,\r\n area: summary.area,\r\n evidenceClass: 'mcp-verifier',\r\n status: 'needs-connection',\r\n evidence: [],\r\n promptHint: `Connect the official ${summary.providerLabel} MCP/tool verifier before claiming external dashboard state.`\r\n });\r\n }\r\n\r\n return {\r\n key: summary.key,\r\n provider: summary.provider,\r\n providerLabel: summary.providerLabel,\r\n area: summary.area,\r\n promptSubject: summary.promptSubject,\r\n readinessPercent: summary.readinessPercent,\r\n checks\r\n };\r\n}\r\n\r\nfunction toMissionCheck(summary: StackWiringProviderSummary, item: StackWiringItem): MissionCheck {\r\n const evidenceClass = evidenceClassForStatus(item.status);\r\n return {\r\n id: item.id,\r\n label: item.label,\r\n providerKey: summary.key,\r\n providerLabel: summary.providerLabel,\r\n area: summary.area,\r\n evidenceClass,\r\n status: missionStatusForEvidenceClass(evidenceClass),\r\n evidence: item.evidence,\r\n promptHint: item.promptHint\r\n };\r\n}\r\n\r\nfunction evidenceClassForStatus(status: StackWiringItem['status']): MissionEvidenceClass {\r\n if (status === 'passed') {\r\n return 'repo-verified';\r\n }\r\n if (status === 'manual') {\r\n return 'manual-dashboard';\r\n }\r\n return 'missing-repo-fix';\r\n}\r\n\r\nfunction missionStatusForEvidenceClass(evidenceClass: MissionEvidenceClass): MissionCheckStatus {\r\n if (evidenceClass === 'repo-verified') {\r\n return 'passed';\r\n }\r\n if (evidenceClass === 'manual-dashboard') {\r\n return 'manual-required';\r\n }\r\n if (evidenceClass === 'mcp-verifier') {\r\n return 'needs-connection';\r\n }\r\n return 'missing';\r\n}\r\n\r\nfunction overlaySifgLeaks(providerMissions: ProviderMission[], graph: SifgGraph): void {\r\n const pipelinesById = new Map(graph.pipelines.map((pipeline) => [pipeline.id, pipeline]));\r\n const leaksByPipeline = new Map<string, SifgLeak[]>();\r\n const providerCheckIds = new Map(\r\n providerMissions.map((mission) => [\r\n mission.key,\r\n new Set(mission.checks.map((check) => check.id))\r\n ])\r\n );\r\n\r\n for (const leak of graph.leaks) {\r\n const leaks = leaksByPipeline.get(leak.pipelineId) ?? [];\r\n leaks.push(leak);\r\n leaksByPipeline.set(leak.pipelineId, leaks);\r\n }\r\n\r\n for (const [pipelineId, leaks] of leaksByPipeline.entries()) {\r\n const pipeline = pipelinesById.get(pipelineId);\r\n const providerKey = pipeline?.providerKey ?? leaks[0]?.providerKey;\r\n if (!providerKey) {\r\n continue;\r\n }\r\n\r\n const mission = providerMissions.find((candidate) => candidate.key === providerKey);\r\n if (!mission) {\r\n continue;\r\n }\r\n\r\n const usedCheckIds = providerCheckIds.get(mission.key) ?? new Set<string>();\r\n const check = toSifgMissionCheck(mission, pipeline, pipelineId, leaks, usedCheckIds);\r\n mission.checks.push(check);\r\n usedCheckIds.add(check.id);\r\n providerCheckIds.set(mission.key, usedCheckIds);\r\n }\r\n\r\n for (const mission of providerMissions) {\r\n mission.readinessPercent = readinessPercentForChecks(mission.checks);\r\n }\r\n}\r\n\r\nfunction toSifgMissionCheck(\r\n mission: ProviderMission,\r\n pipeline: SifgPipeline | undefined,\r\n pipelineId: string,\r\n leaks: SifgLeak[],\r\n usedCheckIds: Set<string>\r\n): MissionCheck {\r\n const firstLeak = leaks[0];\r\n const baseCheckId = pipeline?.missionCheckIds[0] ?? firstLeak?.id ?? pipelineId;\r\n const checkId = uniqueSifgCheckId(baseCheckId, pipelineId, firstLeak?.id, usedCheckIds);\r\n const evidence = leaks.flatMap((leak) =>\r\n leak.evidencePath.map((step) => `${step.file}:${step.range.startLine}-${step.range.endLine}`)\r\n );\r\n\r\n return {\r\n id: checkId,\r\n label: pipeline?.label ?? firstLeak?.summary ?? 'SIFG structural leak',\r\n providerKey: mission.key,\r\n providerLabel: mission.providerLabel,\r\n area: mission.area,\r\n evidenceClass: 'missing-repo-fix',\r\n status: 'missing',\r\n evidence,\r\n promptHint: firstLeak?.repoFix.requiredOutcome ?? 'Fix the SIFG structural leak in repository code.',\r\n sifg: {\r\n pipelineId,\r\n leakIds: leaks.map((leak) => leak.id),\r\n proofStatus: 'leak'\r\n }\r\n };\r\n}\r\n\r\nfunction uniqueSifgCheckId(\r\n baseCheckId: string,\r\n pipelineId: string,\r\n leakId: string | undefined,\r\n usedCheckIds: Set<string>\r\n): string {\r\n if (!usedCheckIds.has(baseCheckId)) {\r\n return baseCheckId;\r\n }\r\n\r\n const suffix = stableSifgSuffix(pipelineId) || (leakId ? stableSifgSuffix(leakId) : '') || 'sifg';\r\n const suffixed = `${baseCheckId}--${suffix}`;\r\n if (!usedCheckIds.has(suffixed)) {\r\n return suffixed;\r\n }\r\n\r\n let counter = 2;\r\n while (usedCheckIds.has(`${suffixed}-${counter}`)) {\r\n counter += 1;\r\n }\r\n return `${suffixed}-${counter}`;\r\n}\r\n\r\nfunction stableSifgSuffix(id: string): string {\r\n return id.split(':').filter(Boolean).at(-1)?.replace(/[^a-zA-Z0-9._-]/g, '-') ?? '';\r\n}\r\n\r\nfunction readinessPercentForChecks(checks: MissionCheck[]): number {\r\n const actionableChecks = checks.filter(isActionableCheck);\r\n const passed = actionableChecks.filter((check) => check.status === 'passed').length;\r\n return Math.round((passed / Math.max(actionableChecks.length, 1)) * 100);\r\n}\r\n\r\nfunction isActionableCheck(check: MissionCheck): boolean {\r\n return check.evidenceClass !== 'manual-dashboard' && check.evidenceClass !== 'mcp-verifier';\r\n}\r\n\r\nfunction buildAreas(providerMissions: ProviderMission[]): MissionArea[] {\r\n const byArea = new Map<StackWiringArea, ProviderMission[]>();\r\n for (const mission of providerMissions) {\r\n const current = byArea.get(mission.area) ?? [];\r\n current.push(mission);\r\n byArea.set(mission.area, current);\r\n }\r\n\r\n return [...byArea.entries()].map(([key, missions]) => {\r\n const actionableChecks = missions\r\n .flatMap((mission) => mission.checks)\r\n .filter(isActionableCheck);\r\n const passed = actionableChecks.filter((check) => check.status === 'passed').length;\r\n const missing = actionableChecks.filter((check) => check.status === 'missing' || check.status === 'failed').length;\r\n\r\n return {\r\n key,\r\n label: AREA_LABELS[key],\r\n readinessPercent: Math.round((passed / Math.max(actionableChecks.length, 1)) * 100),\r\n criticalCount: missing,\r\n providerMissions: missions\r\n };\r\n });\r\n}\r\n", "import type { ScanResult } from './types';\r\n\r\nexport function buildAnalysisPrompt(\r\n scan: ScanResult,\r\n specContent?: string,\r\n productionConnectionContext?: string,\r\n scannerEvidenceContext?: string,\r\n stackWiringContext?: string,\r\n stackAutomationContext?: string\r\n): string {\r\n const sections: string[] = [];\r\n\r\n const detectedStack = (Object.entries(scan.stackSignals) as Array<[string, boolean | undefined]>)\r\n .filter(([, v]) => v === true)\r\n .map(([k]) => k)\r\n .join(', ');\r\n\r\n sections.push(`## PROJECT CONTEXT\r\nTotal files in repo: ${scan.totalFilesScanned}\r\nFiles analyzed: ${scan.files.length}\r\nDetected stack signals: ${detectedStack || 'none detected'}\r\nAll dependencies: ${scan.packageDeps.join(', ') || 'none found'}\r\nSecret files found (contents not read): ${scan.secretsFound.join(', ') || 'none'}\r\n`);\r\n\r\n if (scan.fileTree) {\r\n sections.push(`## FILE TREE (compact)\r\n${scan.fileTree}\r\n`);\r\n }\r\n\r\n if (specContent && specContent.trim().length > 0) {\r\n sections.push(`## PROJECT SPEC (SPEC.md)\r\n${specContent.slice(0, 4000)}\r\n`);\r\n }\r\n\r\n const filesWithContent = scan.files.filter((f) => !f.isSecret && f.content !== null && f.content.trim().length > 0);\r\n if (filesWithContent.length > 0) {\r\n sections.push('## FILE CONTENTS (highest relevance first)');\r\n for (const file of filesWithContent) {\r\n const safePath = file.path.replace(/[\\r\\n]/g, ' ');\r\n const escapedContent = (file.content as string).replace(/`{3}/g, '\\\\`\\\\`\\\\`');\r\n sections.push(`### ${safePath} (heat: ${file.heat})\\n\\`\\`\\`\\n${escapedContent}\\n\\`\\`\\`\\n`);\r\n }\r\n }\r\n\r\n if (productionConnectionContext && productionConnectionContext.trim().length > 0) {\r\n sections.push(productionConnectionContext.trim());\r\n }\r\n\r\n if (scannerEvidenceContext && scannerEvidenceContext.trim().length > 0) {\r\n sections.push(`## LOCAL SCANNER EVIDENCE\r\n${scannerEvidenceContext.trim()}\r\n`);\r\n }\r\n\r\n if (stackWiringContext && stackWiringContext.trim().length > 0) {\r\n sections.push(stackWiringContext.trim());\r\n }\r\n\r\n if (stackAutomationContext && stackAutomationContext.trim().length > 0) {\r\n sections.push(stackAutomationContext.trim());\r\n }\r\n\r\n sections.push(`## YOUR TASK\r\n\r\nYou are a senior software engineer reviewing a vibe-coded project for production readiness.\r\nAnalyze everything above and return ONLY valid JSON with this exact structure:\r\n\r\n{\r\n \"score\": 75,\r\n \"scoreLabel\": \"Stable\",\r\n \"summary\": \"2 critical gaps before launch\",\r\n \"archetype\": \"saas-app\",\r\n \"gaps\": [\r\n {\r\n \"id\": \"unique-kebab-id\",\r\n \"category\": \"SECURITY & AUTH\",\r\n \"severity\": \"critical\",\r\n \"title\": \"No rate limiting on API routes\",\r\n \"detail\": \"Any user can spam your API endpoints causing cost and abuse.\",\r\n \"primaryMapCategory\": \"security\",\r\n \"affectedMapCategories\": [\"security\", \"backend\", \"auth\"],\r\n \"copyPrompt\": \"Harden API rate limiting. First inspect src, route handlers, middleware, and existing auth/session helpers. Identify every public or write-heavy endpoint that can be abused. Implement: 1. Add Upstash rate limiting to sensitive API routes. 2. Use conservative defaults such as 10 requests per minute per IP for auth/write endpoints. 3. Return clear 429 responses without leaking internals. Constraints: Preserve existing API contracts unless they are unsafe. Do not rely on client-side checks for server protection. Verification: Add or update tests/manual checks for allowed and rate-limited requests. Run the relevant test suite and TypeScript check. Summarize what changed and what scanner/rescan evidence should confirm.\",\r\n \"toolSuggestions\": [\r\n {\r\n \"name\": \"Upstash Rate Limit\",\r\n \"url\": \"https://upstash.com/docs/redis/sdks/ratelimit-ts/overview\",\r\n \"reason\": \"Best rate limiter for serverless/edge\"\r\n }\r\n ],\r\n \"mcpSuggestion\": null\r\n }\r\n ],\r\n \"stackDetected\": [\"nextjs\", \"supabase\", \"typescript\"],\r\n \"missingLayers\": [\"landing-page\", \"error-monitoring\"],\r\n \"quickWins\": [\"Add .env.example\", \"Add error boundary to root layout\"],\r\n \"productionChecklist\": {\r\n \"security\": 40,\r\n \"database\": 80,\r\n \"auth\": 60,\r\n \"errorHandling\": 30,\r\n \"deployment\": 70,\r\n \"testing\": 10,\r\n \"landing\": 50,\r\n \"monitoring\": 0\r\n }\r\n}\r\n\r\nGap categories must be one of:\r\nSECURITY & AUTH, DATABASE & DATA, ERROR HANDLING, DEPLOYMENT,\r\nPERFORMANCE, MISSING FEATURES, EDGE CASES & RISKS, LANDING & MARKETING\r\n\r\nMission Map category keys must be one of:\r\nappFlow, frontend, backend, auth, database, payments, deployment, monitoring, security, testing, landing, errorHandling\r\n\r\nSeverity: critical (blocks launch), warning (should fix soon), info (nice to have)\r\nScore: 0-100 overall production readiness. Be honest \u2014 most vibe-coded projects score 30-60.\r\nUse a stable scoring rubric: the same evidence should receive the same score on repeat scans. Do not move the score up or down for wording variety; only change it when the scanned evidence changes.\r\n\r\nReturn unique root gaps, not one copy of the same root problem for each affected section. For each gap:\r\n- Set primaryMapCategory to the single Mission Map section that should own/count the blocker.\r\n- Set affectedMapCategories to related sections that the blocker touches, but do not duplicate the gap for those sections.\r\n- Example: \"No production error monitoring is wired up\" should be one monitoring gap with affectedMapCategories such as [\"monitoring\", \"errorHandling\", \"auth\", \"payments\", \"backend\"], not separate auth, billing, backend, and error gaps.\r\n- Example: \"Auth enforcement is split across app layers\" should be one auth or security gap, depending on the strongest evidence, not repeated across every protected route.\r\n\r\nFor toolSuggestions: suggest real tools that solve this specific gap.\r\n- Database gaps: suggest Supabase, PlanetScale, Neon, Turso, or MongoDB Atlas based on detected stack.\r\n- Auth gaps: suggest Supabase Auth, Clerk, NextAuth, or Lucia based on detected stack.\r\n- Monitoring: suggest Sentry, LogRocket, or PostHog.\r\n- Deployment: suggest Vercel, Railway, Fly.io, or Render.\r\n\r\nEvery copyPrompt must be ready to paste into a coding agent. Use this VibeRaven execution structure inside the string:\r\n\r\n1. Start with the outcome in one sentence.\r\n2. Include a \"First inspect\" paragraph naming concrete files, directories, or helpers from the scanned project when possible.\r\n3. Include an \"Implement\" section with numbered steps.\r\n4. Include a \"Constraints\" section with safety rules and behavior that must not break.\r\n5. Include a \"Verification\" section with tests, commands, manual checks, or scanner evidence.\r\n6. End by asking the agent to \"Summarize what changed\" and what remains manual or external.\r\n\r\nMake each gap Raven-friendly: include a concrete copyPrompt, likely tool paths where relevant, and verification steps the user or scanner can check after implementation. Do not claim external dashboard setup is complete from repo evidence alone. If a step needs a provider dashboard, account, MCP connection, billing console, OAuth callback, RLS setting, alert route, or any other external system, say so explicitly and mark it as manual or MCP-verifiable instead of repo-verifiable.\r\n\r\nBe specific. A vibe coder needs to know EXACTLY what to do, not generic advice.\r\nReturn ONLY the JSON object \u2014 no markdown, no explanation.\r\n`);\r\n\r\n return sections.join('\\n');\r\n}\r\n", "import type {\r\n ProductionConnectionArea,\r\n ProductionConnectionChoice,\r\n ProductionConnectionChoices,\r\n ProductionConnectionEvidence,\r\n ProductionConnectionProvider,\r\n ProductionConnectionStatus,\r\n ProductionConnectionSummary,\r\n ScanResult\r\n} from './types';\r\nimport {\r\n normalizeProviderKey,\r\n productionProviders,\r\n productionProvidersByArea,\r\n providerLabel\r\n} from './providerRegistry';\r\n\r\nexport type {\r\n ProductionConnectionArea,\r\n ProductionConnectionChoice,\r\n ProductionConnectionChoices,\r\n ProductionConnectionEvidence,\r\n ProductionConnectionProvider,\r\n ProductionConnectionStatus,\r\n ProductionConnectionSummary\r\n} from './types';\r\n\r\nconst AREAS: ProductionConnectionArea[] = [\r\n 'database',\r\n 'auth',\r\n 'payments',\r\n 'deployment',\r\n 'monitoring',\r\n 'security'\r\n];\r\n\r\nconst PROVIDERS = productionProviders();\r\nconst PROVIDERS_BY_AREA = productionProvidersByArea();\r\n\r\ntype EvidenceMap = Partial<Record<ProductionConnectionArea, ProductionConnectionEvidence>>;\r\n\r\ntype ScannableFile = {\r\n path: string;\r\n displayPath: string;\r\n content: string;\r\n lowerContent: string;\r\n};\r\n\r\ntype ProviderDetectionRule = {\r\n area: ProductionConnectionArea;\r\n provider: ProductionConnectionProvider;\r\n label: string;\r\n packages?: RegExp[];\r\n env?: string[];\r\n paths?: RegExp[];\r\n imports?: string[];\r\n docs?: string[];\r\n content?: Array<{ pattern: RegExp; signal: string }>;\r\n};\r\n\r\ntype RawProductionConnectionChoice = {\r\n provider?: unknown;\r\n selectedAt?: unknown;\r\n};\r\n\r\ntype ChoiceInput =\r\n | ProductionConnectionChoices\r\n | Partial<Record<string, RawProductionConnectionChoice | undefined>>\r\n | null\r\n | undefined;\r\n\r\nconst PROVIDER_RULES: ProviderDetectionRule[] = [\r\n {\r\n area: 'database',\r\n provider: 'supabase',\r\n label: 'Supabase',\r\n packages: [/@supabase\\//],\r\n env: ['VITE_SUPABASE_URL', 'NEXT_PUBLIC_SUPABASE_URL', 'SUPABASE_URL', 'SUPABASE_SERVICE_ROLE_KEY'],\r\n paths: [/supabase\\/config\\.toml$/, /(^|\\/)(lib|utils)\\/supabase\\.[jt]s$/],\r\n imports: ['@supabase/supabase-js', '@supabase/ssr'],\r\n docs: ['supabase']\r\n },\r\n {\r\n area: 'database',\r\n provider: 'neon',\r\n label: 'Neon',\r\n packages: [/@neondatabase\\//],\r\n env: ['NEON_DATABASE_URL'],\r\n imports: ['@neondatabase/serverless'],\r\n docs: ['neon']\r\n },\r\n {\r\n area: 'database',\r\n provider: 'planetscale',\r\n label: 'PlanetScale',\r\n packages: [/@planetscale\\/database/],\r\n env: ['PLANETSCALE_DATABASE_URL'],\r\n imports: ['@planetscale/database'],\r\n docs: ['planetscale']\r\n },\r\n {\r\n area: 'database',\r\n provider: 'mongodb',\r\n label: 'MongoDB',\r\n packages: [/^mongodb$/, /^mongoose$/],\r\n env: ['MONGODB_URI', 'MONGODB_URL', 'MONGODB_ATLAS_URI'],\r\n imports: ['mongodb', 'mongoose'],\r\n docs: ['mongodb', 'mongo atlas']\r\n },\r\n {\r\n area: 'database',\r\n provider: 'turso',\r\n label: 'Turso',\r\n packages: [/@libsql\\/client/],\r\n env: ['TURSO_DATABASE_URL', 'TURSO_AUTH_TOKEN'],\r\n imports: ['@libsql/client'],\r\n docs: ['turso']\r\n },\r\n {\r\n area: 'auth',\r\n provider: 'clerk',\r\n label: 'Clerk',\r\n packages: [/@clerk\\//],\r\n env: ['CLERK_SECRET_KEY', 'NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY'],\r\n paths: [/middleware\\.[jt]sx?$/],\r\n imports: ['@clerk/nextjs', '@clerk/clerk-react', '@clerk/express'],\r\n docs: ['clerk']\r\n },\r\n {\r\n area: 'auth',\r\n provider: 'authjs',\r\n label: 'Auth.js',\r\n packages: [/^next-auth$/, /^@auth\\//],\r\n env: ['AUTH_SECRET', 'NEXTAUTH_SECRET', 'NEXTAUTH_URL'],\r\n paths: [/(^|\\/)auth\\.[jt]s$/, /api\\/auth\\//],\r\n imports: ['next-auth', '@auth/core', '@auth/nextjs'],\r\n docs: ['auth.js', 'nextauth', 'next-auth']\r\n },\r\n {\r\n area: 'payments',\r\n provider: 'stripe',\r\n label: 'Stripe',\r\n packages: [/^stripe$/, /@stripe\\//],\r\n env: ['STRIPE_SECRET_KEY', 'STRIPE_WEBHOOK_SECRET', 'NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY'],\r\n paths: [/stripe.*webhook/, /webhook.*stripe/, /stripe.*checkout/, /checkout.*stripe/],\r\n imports: ['stripe', '@stripe/stripe-js'],\r\n docs: ['stripe']\r\n },\r\n {\r\n area: 'payments',\r\n provider: 'paddle',\r\n label: 'Paddle',\r\n packages: [/@paddle\\//],\r\n env: ['PADDLE_API_KEY', 'PADDLE_WEBHOOK_SECRET', 'NEXT_PUBLIC_PADDLE_CLIENT_TOKEN'],\r\n paths: [/paddle.*webhook/, /webhook.*paddle/, /paddle.*checkout/, /checkout.*paddle/],\r\n imports: ['@paddle/paddle-js', '@paddle/paddle-node-sdk'],\r\n docs: ['paddle']\r\n },\r\n {\r\n area: 'deployment',\r\n provider: 'vercel',\r\n label: 'Vercel',\r\n packages: [/@vercel\\//],\r\n env: ['VERCEL_TOKEN', 'VERCEL_PROJECT_ID', 'VERCEL_ORG_ID'],\r\n paths: [/vercel\\.json$/],\r\n docs: ['vercel']\r\n },\r\n {\r\n area: 'monitoring',\r\n provider: 'sentry',\r\n label: 'Sentry',\r\n packages: [/@sentry\\//],\r\n env: ['SENTRY_DSN', 'NEXT_PUBLIC_SENTRY_DSN', 'SENTRY_AUTH_TOKEN'],\r\n paths: [/sentry\\.(client|server)\\.config\\.[jt]s$/, /instrumentation\\.[jt]s$/],\r\n imports: ['@sentry/nextjs', '@sentry/node', '@sentry/react'],\r\n content: [{ pattern: /sentry\\.init\\s*\\(/i, signal: 'init: Sentry.init' }],\r\n docs: ['sentry']\r\n },\r\n {\r\n area: 'monitoring',\r\n provider: 'posthog',\r\n label: 'PostHog',\r\n packages: [/^posthog-js$/, /^posthog-node$/],\r\n env: ['POSTHOG_KEY', 'NEXT_PUBLIC_POSTHOG_KEY', 'NEXT_PUBLIC_POSTHOG_HOST'],\r\n imports: ['posthog-js', 'posthog-node'],\r\n content: [{ pattern: /posthog\\.init\\s*\\(/i, signal: 'init: posthog.init' }],\r\n docs: ['posthog']\r\n },\r\n {\r\n area: 'monitoring',\r\n provider: 'logrocket',\r\n label: 'LogRocket',\r\n packages: [/^logrocket$/],\r\n env: ['LOGROCKET_APP_ID', 'NEXT_PUBLIC_LOGROCKET_APP_ID'],\r\n imports: ['logrocket'],\r\n content: [{ pattern: /logrocket\\.init\\s*\\(/i, signal: 'init: LogRocket.init' }],\r\n docs: ['logrocket']\r\n },\r\n {\r\n area: 'security',\r\n provider: 'rate-limit',\r\n label: 'Upstash rate limit',\r\n packages: [/@upstash\\/ratelimit/, /express-rate-limit/, /rate-limiter-flexible/, /@fastify\\/rate-limit/],\r\n env: ['UPSTASH_REDIS_REST_URL', 'UPSTASH_REDIS_REST_TOKEN'],\r\n paths: [/rate-?limit/, /ratelimit/],\r\n imports: ['@upstash/ratelimit', 'express-rate-limit', 'rate-limiter-flexible', '@fastify/rate-limit'],\r\n content: [{ pattern: /\\brateLimit\\b|\\bRatelimit\\b|\\bToo many requests\\b/i, signal: 'code: rate limit guard' }],\r\n docs: ['upstash', 'rate limit']\r\n },\r\n {\r\n area: 'security',\r\n provider: 'bot-protection',\r\n label: 'Cloudflare Turnstile',\r\n packages: [/turnstile/],\r\n env: ['NEXT_PUBLIC_TURNSTILE_SITE_KEY', 'TURNSTILE_SECRET_KEY', 'TURNSTILE_SITE_KEY'],\r\n paths: [/turnstile/, /bot.?protection/],\r\n imports: ['@marsidev/react-turnstile', 'react-turnstile'],\r\n content: [{ pattern: /\\bturnstile\\b|\\bcf-turnstile\\b|\\brecaptcha\\b|\\bhcaptcha\\b/i, signal: 'code: bot protection guard' }],\r\n docs: ['turnstile', 'cloudflare turnstile', 'bot protection']\r\n }\r\n];\r\n\r\nexport function normalizeProductionChoice(input: ChoiceInput): ProductionConnectionChoices {\r\n const source = isObject(input) && isObject(input.choices) ? input.choices : input;\r\n const choices: ProductionConnectionChoices['choices'] = {};\r\n\r\n if (!isObject(source)) {\r\n return { version: 1, choices };\r\n }\r\n\r\n for (const [areaKey, value] of Object.entries(source)) {\r\n const area = normalizeArea(areaKey);\r\n const provider = normalizeProviderForArea(area, isObject(value) ? value.provider : undefined);\r\n\r\n if (!area || !provider) {\r\n continue;\r\n }\r\n\r\n const selectedAt = isObject(value) ? normalizeSelectedAt(value.selectedAt) : null;\r\n if (!selectedAt) {\r\n continue;\r\n }\r\n\r\n choices[area] = { provider, selectedAt };\r\n }\r\n\r\n return { version: 1, choices };\r\n}\r\n\r\nexport function detectProductionConnectionEvidence(scan: ScanResult): EvidenceMap {\r\n const evidence: EvidenceMap = {};\r\n const deps = scan.packageDeps.map((dep) => dep.toLowerCase());\r\n const files = scan.files.map((file) => ({\r\n path: normalizePath(file.path),\r\n displayPath: file.path.replace(/\\\\/g, '/'),\r\n content: file.isSecret || typeof file.content !== 'string' ? '' : file.content,\r\n lowerContent: file.isSecret || typeof file.content !== 'string' ? '' : file.content.toLowerCase()\r\n }));\r\n const secretPathBlob = scan.secretsFound.map((path) => normalizePath(path)).join('\\n');\r\n const pathBlob = `${scan.fileTree}\\n${files.map((file) => file.path).join('\\n')}`.toLowerCase();\r\n const contentBlob = files.map((file) => file.lowerContent).join('\\n').slice(0, 120000);\r\n const secretsHygieneBlob = `${pathBlob}\\n${secretPathBlob}`;\r\n\r\n for (const rule of PROVIDER_RULES) {\r\n detectProvider(evidence, rule, deps, files, pathBlob);\r\n }\r\n\r\n detectSecretsHygiene(evidence, secretsHygieneBlob);\r\n\r\n for (const item of Object.values(evidence)) {\r\n if (!item) {\r\n continue;\r\n }\r\n applyVerificationStatus(item, pathBlob, contentBlob);\r\n }\r\n\r\n return evidence;\r\n}\r\n\r\nexport function summarizeProductionConnections(\r\n choices: ProductionConnectionChoices | null | undefined,\r\n evidence: EvidenceMap\r\n): {\r\n byArea: Partial<Record<ProductionConnectionArea, ProductionConnectionSummary>>;\r\n items: ProductionConnectionSummary[];\r\n stackRow: ProductionConnectionSummary[];\r\n} {\r\n const normalized = normalizeProductionChoice(choices);\r\n const byArea: Partial<Record<ProductionConnectionArea, ProductionConnectionSummary>> = {};\r\n const items: ProductionConnectionSummary[] = [];\r\n\r\n for (const area of AREAS) {\r\n const detected = evidence[area];\r\n const selected = normalized.choices[area];\r\n let summary: ProductionConnectionSummary | null = null;\r\n\r\n if (detected) {\r\n summary = {\r\n area,\r\n provider: detected.provider,\r\n source: 'detected',\r\n status: detected.status,\r\n label: `${providerLabel(detected.provider)} detected`,\r\n signals: detected.signals\r\n };\r\n } else if (selected) {\r\n summary = {\r\n area,\r\n provider: selected.provider,\r\n source: 'selected',\r\n status: ['selected', 'setup-not-verified'],\r\n label: `${providerLabel(selected.provider)} selected - setup not verified`,\r\n signals: [`Selected locally at ${selected.selectedAt}`]\r\n };\r\n }\r\n\r\n if (summary) {\r\n byArea[area] = summary;\r\n items.push(summary);\r\n }\r\n }\r\n\r\n const stackRow = items.filter((item) => item.provider !== null);\r\n\r\n return { byArea, items, stackRow };\r\n}\r\n\r\nexport function buildProductionConnectionContext(\r\n choices: ProductionConnectionChoices | null | undefined,\r\n evidence: EvidenceMap\r\n): string {\r\n const summary = summarizeProductionConnections(choices, evidence);\r\n const lines = summary.items.map((item) => `${item.area}: ${item.label}`);\r\n\r\n if (lines.some((line) => line.includes('selected - setup not verified'))) {\r\n lines.push('Do not treat selected as connected; only detected repo evidence can verify setup.');\r\n }\r\n\r\n return lines.length > 0 ? lines.join('\\n') : 'production connections: no selected or detected providers';\r\n}\r\n\r\nfunction detectProvider(\r\n evidence: EvidenceMap,\r\n rule: ProviderDetectionRule,\r\n deps: string[],\r\n files: ScannableFile[],\r\n pathBlob: string\r\n): void {\r\n if (evidence[rule.area]) {\r\n return;\r\n }\r\n\r\n const signals = collectSignals(rule, deps, files, pathBlob);\r\n if (signals.length === 0) {\r\n return;\r\n }\r\n\r\n evidence[rule.area] = {\r\n area: rule.area,\r\n provider: rule.provider,\r\n status: ['detected'],\r\n signals\r\n };\r\n}\r\n\r\nfunction collectSignals(\r\n rule: ProviderDetectionRule,\r\n deps: string[],\r\n files: ScannableFile[],\r\n pathBlob: string\r\n): string[] {\r\n const signals: string[] = [];\r\n\r\n for (const dep of deps) {\r\n if ((rule.packages ?? []).some((pattern) => pattern.test(dep))) {\r\n addSignal(signals, `package: ${dep}`);\r\n }\r\n }\r\n\r\n const upperContents = files.map((file) => file.content).join('\\n').toUpperCase();\r\n for (const envName of rule.env ?? []) {\r\n if (upperContents.includes(envName.toUpperCase())) {\r\n addSignal(signals, `env: ${envName}`);\r\n }\r\n }\r\n\r\n const pathLines = pathBlob.split(/\\r?\\n/).map((path) => path.trim()).filter(Boolean);\r\n for (const path of pathLines) {\r\n if ((rule.paths ?? []).some((pattern) => pattern.test(path))) {\r\n addSignal(signals, `${pathSignalPrefix(path)}: ${path}`);\r\n }\r\n }\r\n\r\n for (const file of files) {\r\n for (const importName of rule.imports ?? []) {\r\n if (containsImport(file.lowerContent, importName)) {\r\n addSignal(signals, `import: ${importName}`);\r\n }\r\n }\r\n\r\n for (const item of rule.content ?? []) {\r\n if (item.pattern.test(file.content)) {\r\n addSignal(signals, item.signal);\r\n }\r\n }\r\n\r\n if (isDocsPath(file.path)) {\r\n for (const docsTerm of rule.docs ?? []) {\r\n if (file.lowerContent.includes(docsTerm.toLowerCase())) {\r\n addSignal(signals, `docs: ${file.displayPath} mentions ${rule.label}`);\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n\r\n return signals;\r\n}\r\n\r\nfunction containsImport(content: string, importName: string): boolean {\r\n const escaped = importName.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&').toLowerCase();\r\n return new RegExp(`(?:from\\\\s+['\"]${escaped}['\"]|import\\\\s*\\\\(\\\\s*['\"]${escaped}['\"]|require\\\\s*\\\\(\\\\s*['\"]${escaped}['\"])`).test(content);\r\n}\r\n\r\nfunction isDocsPath(path: string): boolean {\r\n return /(^|\\/)(readme|product|spec)\\.md$/.test(path) || /(^|\\/)docs\\/.*\\.md$/.test(path);\r\n}\r\n\r\nfunction pathSignalPrefix(path: string): string {\r\n if (/webhook|checkout|billing|api\\/|route\\.[jt]s$/.test(path)) {\r\n return 'route';\r\n }\r\n if (/config|\\.json$|\\.toml$|\\.ya?ml$/.test(path)) {\r\n return 'config';\r\n }\r\n return 'file';\r\n}\r\n\r\nfunction addSignal(signals: string[], signal: string): void {\r\n if (!signals.includes(signal)) {\r\n signals.push(signal);\r\n }\r\n}\r\n\r\nfunction detectSecretsHygiene(evidence: EvidenceMap, secretsHygieneBlob: string): void {\r\n if (evidence.security) {\r\n return;\r\n }\r\n\r\n const signals: string[] = [];\r\n if (/(^|[/\\\\])\\.env\\.example\\b/m.test(secretsHygieneBlob)) {\r\n signals.push('file: .env.example');\r\n }\r\n if (/(^|[/\\\\])\\.env(\\.|$)/m.test(secretsHygieneBlob)) {\r\n signals.push('secret file excluded from scan');\r\n }\r\n if (signals.length === 0) {\r\n return;\r\n }\r\n\r\n evidence.security = {\r\n area: 'security',\r\n provider: 'secrets-hygiene',\r\n status: ['detected'],\r\n signals\r\n };\r\n}\r\n\r\nfunction applyVerificationStatus(\r\n evidence: ProductionConnectionEvidence,\r\n pathBlob: string,\r\n contentBlob: string\r\n): void {\r\n if (evidence.provider === 'secrets-hygiene') {\r\n addStatus(evidence.status, 'repo-verified');\r\n return;\r\n }\r\n\r\n const hasEnv = envPatternFor(evidence.provider).test(contentBlob);\r\n const hasWebhook = webhookPatternFor(evidence.provider).test(`${pathBlob}\\n${contentBlob}`);\r\n\r\n if (hasEnv || hasWebhook || evidence.area === 'deployment') {\r\n addStatus(evidence.status, 'repo-verified');\r\n }\r\n\r\n if (evidence.area === 'payments' && !hasWebhook) {\r\n addStatus(evidence.status, 'needs-webhook');\r\n }\r\n\r\n if (!hasEnv && evidence.area !== 'deployment') {\r\n addStatus(evidence.status, 'needs-env');\r\n }\r\n}\r\n\r\nfunction envPatternFor(provider: ProductionConnectionProvider): RegExp {\r\n switch (provider) {\r\n case 'supabase':\r\n return /\\b((vite|next_public)_)?supabase_(url|anon_key|service_role_key)\\b/i;\r\n case 'clerk':\r\n return /\\b(clerk_secret_key|next_public_clerk_)/i;\r\n case 'authjs':\r\n return /\\b(auth_secret|nextauth_secret)\\b/i;\r\n case 'neon':\r\n return /\\b(neon_database_url|database_url)\\b/i;\r\n case 'planetscale':\r\n return /\\b(planetscale_database_url|database_url)\\b/i;\r\n case 'mongodb':\r\n return /\\b(mongodb_uri|mongodb_url|database_url)\\b/i;\r\n case 'turso':\r\n return /\\b(turso_database_url|turso_auth_token|database_url)\\b/i;\r\n case 'stripe':\r\n return /\\bstripe_(secret_key|webhook_secret)\\b/i;\r\n case 'paddle':\r\n return /\\bpaddle_(api_key|webhook_secret|client_token)\\b/i;\r\n case 'sentry':\r\n return /\\bsentry_dsn\\b/i;\r\n case 'posthog':\r\n return /\\b(posthog_key|next_public_posthog_key)\\b/i;\r\n case 'logrocket':\r\n return /\\b(logrocket_app_id|next_public_logrocket_app_id)\\b/i;\r\n case 'rate-limit':\r\n return /\\b(upstash_redis_rest_url|upstash_redis_rest_token)\\b/i;\r\n case 'bot-protection':\r\n return /\\b(next_public_turnstile_site_key|turnstile_secret_key|turnstile_site_key)\\b/i;\r\n default:\r\n return /\\b[A-Z0-9_]+_(KEY|SECRET|TOKEN|URL)\\b/i;\r\n }\r\n}\r\n\r\nfunction webhookPatternFor(provider: ProductionConnectionProvider): RegExp {\r\n switch (provider) {\r\n case 'stripe':\r\n return /\\bstripe\\b.*\\bwebhook\\b|\\bwebhook\\b.*\\bstripe\\b/i;\r\n case 'paddle':\r\n return /\\bpaddle\\b.*\\bwebhook\\b|\\bwebhook\\b.*\\bpaddle\\b/i;\r\n default:\r\n return /\\bwebhook\\b/i;\r\n }\r\n}\r\n\r\nfunction addStatus(status: ProductionConnectionStatus[], value: ProductionConnectionStatus): void {\r\n if (!status.includes(value)) {\r\n status.push(value);\r\n }\r\n}\r\n\r\nfunction normalizeArea(value: unknown): ProductionConnectionArea | null {\r\n const normalized = String(value).toLowerCase();\r\n return AREAS.includes(normalized as ProductionConnectionArea) ? (normalized as ProductionConnectionArea) : null;\r\n}\r\n\r\nfunction normalizeProvider(value: unknown): ProductionConnectionProvider | null {\r\n const normalized = normalizeProviderKey(String(value));\r\n const productionProvider = normalized === 'supabase-auth' ? 'supabase' : normalized;\r\n return PROVIDERS.includes(productionProvider as ProductionConnectionProvider)\r\n ? (productionProvider as ProductionConnectionProvider)\r\n : null;\r\n}\r\n\r\nfunction normalizeProviderForArea(\r\n area: ProductionConnectionArea | null,\r\n value: unknown\r\n): ProductionConnectionProvider | null {\r\n if (!area) {\r\n return null;\r\n }\r\n\r\n const provider = normalizeProvider(value);\r\n if (!provider || !PROVIDERS_BY_AREA[area].includes(provider)) {\r\n return null;\r\n }\r\n\r\n return provider;\r\n}\r\n\r\nfunction normalizeSelectedAt(value: unknown): string | null {\r\n if (typeof value === 'string') {\r\n const date = new Date(value);\r\n if (!Number.isNaN(date.getTime())) {\r\n return date.toISOString();\r\n }\r\n }\r\n\r\n return null;\r\n}\r\n\r\nfunction normalizePath(path: string): string {\r\n return path.replace(/\\\\/g, '/').toLowerCase();\r\n}\r\n\r\nfunction isObject(value: unknown): value is Record<string, unknown> {\r\n return typeof value === 'object' && value !== null;\r\n}\r\n", "import type { EnvEvidenceMode, EnvVarEvidence, ScanResult } from './types';\r\n\r\nfunction normalizeEvidencePath(path: string): string {\r\n return path.replace(/\\\\/g, '/');\r\n}\r\n\r\nfunction uniquePaths(paths: string[]): string[] {\r\n return Array.from(new Set(paths.map(normalizeEvidencePath)));\r\n}\r\n\r\nfunction escapeRegExp(value: string): string {\r\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\r\n}\r\n\r\nfunction stripEnvValueQuotes(value: string): string {\r\n const trimmed = value.trim();\r\n const quote = trimmed[0];\r\n\r\n if ((quote === '\"' || quote === \"'\") && trimmed.endsWith(quote)) {\r\n return trimmed.slice(1, -1);\r\n }\r\n\r\n return trimmed;\r\n}\r\n\r\nexport function classifySafeEnvMode(value: string): EnvEvidenceMode {\r\n const normalized = stripEnvValueQuotes(value).toLowerCase();\r\n\r\n if (/^(?:sk|pk|rk)_test_/.test(normalized) || normalized.includes('_test_') || normalized.includes('test_example')) {\r\n return 'test';\r\n }\r\n\r\n if (/^(?:sk|pk|rk)_live_/.test(normalized) || normalized.includes('_live_') || normalized.includes('live_example')) {\r\n return 'live';\r\n }\r\n\r\n return 'unknown';\r\n}\r\n\r\nexport function collectEnvVarEvidence(scan: ScanResult, names: string[]): EnvVarEvidence[] {\r\n const nonSecretFiles = scan.files.filter((file) => !file.isSecret && typeof file.content === 'string');\r\n const secretEvidence = uniquePaths(scan.secretsFound);\r\n\r\n return names.map((name) => {\r\n const assignmentPattern = new RegExp(\r\n String.raw`^[ \\t]*(?:export[ \\t]+)?${escapeRegExp(name)}[ \\t]*=[ \\t]*([^\\r\\n#]*)`,\r\n 'm'\r\n );\r\n const namePattern = new RegExp(\r\n String.raw`^[ \\t]*(?:export[ \\t]+)?${escapeRegExp(name)}(?:[ \\t]*=|[ \\t]*(?:#|$))`,\r\n 'm'\r\n );\r\n const contentEvidence: string[] = [];\r\n const nameOnlyEvidence: string[] = [];\r\n const nonEmptyAssignmentEvidence: string[] = [];\r\n let mode: EnvEvidenceMode = 'unknown';\r\n\r\n for (const file of nonSecretFiles) {\r\n const content = file.content as string;\r\n const assignment = content.match(assignmentPattern);\r\n\r\n if (assignment) {\r\n const value = assignment[1] ?? '';\r\n const classifiedMode = classifySafeEnvMode(value);\r\n\r\n if (classifiedMode !== 'unknown') {\r\n contentEvidence.push(file.path);\r\n mode = classifiedMode;\r\n continue;\r\n }\r\n\r\n if (stripEnvValueQuotes(value).length > 0) {\r\n nonEmptyAssignmentEvidence.push(file.path);\r\n continue;\r\n }\r\n }\r\n\r\n if (namePattern.test(content)) {\r\n nameOnlyEvidence.push(file.path);\r\n }\r\n }\r\n\r\n if (contentEvidence.length > 0) {\r\n return {\r\n name,\r\n present: true,\r\n mode,\r\n source: 'non-secret-content',\r\n evidence: uniquePaths(contentEvidence).map((path) => `file: ${path}`)\r\n };\r\n }\r\n\r\n if (nonEmptyAssignmentEvidence.length > 0) {\r\n return {\r\n name,\r\n present: true,\r\n mode: 'unknown',\r\n source: 'non-secret-content',\r\n evidence: uniquePaths(nonEmptyAssignmentEvidence).map((path) => `file: ${path}`)\r\n };\r\n }\r\n\r\n if (nameOnlyEvidence.length > 0) {\r\n return {\r\n name,\r\n present: true,\r\n mode: 'unknown',\r\n source: 'variable-name-only',\r\n evidence: uniquePaths(nameOnlyEvidence).map((path) => `file: ${path}`)\r\n };\r\n }\r\n\r\n if (secretEvidence.length > 0) {\r\n return {\r\n name,\r\n present: false,\r\n mode: 'unknown',\r\n source: 'secret-file-path',\r\n evidence: secretEvidence.map((path) => `secret file: ${path}`)\r\n };\r\n }\r\n\r\n return {\r\n name,\r\n present: false,\r\n mode: 'unknown',\r\n source: 'variable-name-only',\r\n evidence: []\r\n };\r\n });\r\n}\r\n", "import { collectEnvVarEvidence } from './envEvidence';\r\nimport type {\r\n RepositoryEvidenceItem,\r\n RepositoryEvidenceSummary,\r\n ScanResult,\r\n ScannedFile\r\n} from './types';\r\n\r\nconst CORE_ENV_NAMES = [\r\n 'STRIPE_SECRET_KEY',\r\n 'STRIPE_WEBHOOK_SECRET',\r\n 'NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY',\r\n 'GOOGLE_CLIENT_ID',\r\n 'GOOGLE_CLIENT_SECRET',\r\n 'NEXT_PUBLIC_SUPABASE_URL',\r\n 'NEXT_PUBLIC_SUPABASE_ANON_KEY',\r\n 'SUPABASE_SERVICE_ROLE_KEY',\r\n 'NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY',\r\n 'CLERK_SECRET_KEY',\r\n 'AUTH_SECRET',\r\n 'NEXTAUTH_SECRET',\r\n 'VERCEL_PROJECT_ID',\r\n 'SENTRY_DSN',\r\n 'NEXT_PUBLIC_SENTRY_DSN',\r\n 'SENTRY_AUTH_TOKEN',\r\n 'NEXT_PUBLIC_POSTHOG_KEY',\r\n 'PADDLE_API_KEY',\r\n 'PADDLE_WEBHOOK_SECRET',\r\n 'UPSTASH_REDIS_REST_URL',\r\n 'UPSTASH_REDIS_REST_TOKEN',\r\n 'NEXT_PUBLIC_TURNSTILE_SITE_KEY',\r\n 'TURNSTILE_SECRET_KEY'\r\n];\r\n\r\nconst SECRET_ENV_REFERENCE = /\\b(?:STRIPE_SECRET_KEY|STRIPE_WEBHOOK_SECRET|GOOGLE_CLIENT_SECRET|SUPABASE_SERVICE_ROLE_KEY|CLERK_SECRET_KEY|AUTH_SECRET|NEXTAUTH_SECRET|SENTRY_AUTH_TOKEN|PADDLE_API_KEY|PADDLE_WEBHOOK_SECRET|UPSTASH_REDIS_REST_TOKEN|TURNSTILE_SECRET_KEY)\\b/i;\r\nconst RLS_POLICY = /enable\\s+row\\s+level\\s+security|create\\s+policy|alter\\s+policy/i;\r\nconst WEBHOOK_SIGNATURE = /webhooks\\.constructevent|stripe-signature|verify(?:signature|webhook)|svix\\.webhook|webhook\\.verify/i;\r\nconst RATE_LIMIT = /ratelimit|rate-limit|rate_limiter|too many requests|status\\s*:\\s*429/i;\r\nconst OAUTH_CALLBACK = /oauth|callback|redirect_uri|redirecturl|authorized redirect|allowed redirect/i;\r\nconst SECURITY_HEADERS = /content-security-policy|strict-transport-security|x-frame-options|x-content-type-options|referrer-policy|permissions-policy/i;\r\nconst SERVICE_ROLE = /\\bSUPABASE_SERVICE_ROLE_KEY\\b|service[-_]?role/i;\r\nconst SERVER_ONLY_HINT = /server-only|\\.server\\.|\\/server\\/|app\\/api\\/|pages\\/api\\/|\\/api\\/|route\\.[jt]s|actions?\\.[jt]s/i;\r\nconst ENV_OR_DOC_PATH = /(^|\\/)(\\.env\\.example|env\\.example|readme|docs?)|\\.md$/i;\r\n\r\nexport function analyzeRepositoryEvidence(scan: ScanResult): RepositoryEvidenceSummary {\r\n const files = visibleFiles(scan);\r\n const pathBlob = `${scan.fileTree}\\n${scan.files.map((file) => file.path).join('\\n')}`.replace(/\\\\/g, '/');\r\n const contentBlob = files.map((file) => file.content as string).join('\\n');\r\n\r\n return {\r\n env: collectEnvVarEvidence(scan, CORE_ENV_NAMES),\r\n security: [\r\n clientSecretReference(files),\r\n serviceRoleScope(files),\r\n foundOrMissing(\r\n 'supabase-rls-policy',\r\n 'Supabase RLS policy evidence',\r\n RLS_POLICY.test(contentBlob),\r\n evidenceFor(files, RLS_POLICY)\r\n ),\r\n foundOrMissing(\r\n 'webhook-signature-verification',\r\n 'Webhook signature verification evidence',\r\n WEBHOOK_SIGNATURE.test(contentBlob),\r\n evidenceFor(files, WEBHOOK_SIGNATURE)\r\n ),\r\n foundOrMissing(\r\n 'rate-limit-evidence',\r\n 'Rate limit evidence',\r\n Boolean(scan.stackSignals.hasRateLimit) || RATE_LIMIT.test(contentBlob),\r\n evidenceFor(files, RATE_LIMIT)\r\n ),\r\n foundOrMissing(\r\n 'oauth-callback-evidence',\r\n 'OAuth callback or redirect evidence',\r\n OAUTH_CALLBACK.test(`${contentBlob}\\n${pathBlob}`),\r\n evidenceFor(files, OAUTH_CALLBACK).concat(pathEvidence(scan, OAUTH_CALLBACK))\r\n ),\r\n foundOrMissing(\r\n 'security-headers',\r\n 'Security headers evidence',\r\n SECURITY_HEADERS.test(contentBlob),\r\n evidenceFor(files, SECURITY_HEADERS)\r\n )\r\n ]\r\n };\r\n}\r\n\r\nfunction visibleFiles(scan: ScanResult): ScannedFile[] {\r\n return scan.files.filter((file) => !file.isSecret && typeof file.content === 'string');\r\n}\r\n\r\nfunction foundOrMissing(id: string, label: string, found: boolean, evidence: string[]): RepositoryEvidenceItem {\r\n return {\r\n id,\r\n label,\r\n status: found ? 'found' : 'missing',\r\n evidence: unique(evidence).slice(0, 6)\r\n };\r\n}\r\n\r\nfunction clientSecretReference(files: ScannedFile[]): RepositoryEvidenceItem {\r\n const risky = files.filter((file) => isClientReachableFile(file) && SECRET_ENV_REFERENCE.test(file.content as string));\r\n return {\r\n id: 'client-secret-reference',\r\n label: 'No client-side secret references found',\r\n status: risky.length > 0 ? 'risk' : 'found',\r\n evidence: risky.map((file) => `file: ${normalizePath(file.path)}`).slice(0, 6)\r\n };\r\n}\r\n\r\nfunction serviceRoleScope(files: ScannedFile[]): RepositoryEvidenceItem {\r\n const references = files.filter((file) => SERVICE_ROLE.test(file.content as string));\r\n const risky = references.filter((file) => isClientReachableFile(file) && !SERVER_ONLY_HINT.test(normalizePath(file.path)));\r\n if (risky.length > 0) {\r\n return {\r\n id: 'service-role-scope',\r\n label: 'Supabase service role stays server-only',\r\n status: 'risk',\r\n evidence: risky.map((file) => `file: ${normalizePath(file.path)}`).slice(0, 6)\r\n };\r\n }\r\n\r\n const serverEvidence = references.filter((file) => isServerOnlyPath(file.path) && !isEnvOrDocPath(file.path));\r\n\r\n return {\r\n id: 'service-role-scope',\r\n label: 'Supabase service role stays server-only',\r\n status: serverEvidence.length > 0 ? 'found' : 'unknown',\r\n evidence: serverEvidence.map((file) => `file: ${normalizePath(file.path)}`).slice(0, 6)\r\n };\r\n}\r\n\r\nfunction evidenceFor(files: ScannedFile[], pattern: RegExp): string[] {\r\n return files\r\n .filter((file) => pattern.test(file.content as string))\r\n .map((file) => `file: ${normalizePath(file.path)}`)\r\n .slice(0, 6);\r\n}\r\n\r\nfunction pathEvidence(scan: ScanResult, pattern: RegExp): string[] {\r\n return scan.files\r\n .map((file) => normalizePath(file.path))\r\n .filter((path) => pattern.test(path))\r\n .map((path) => `file: ${path}`)\r\n .slice(0, 6);\r\n}\r\n\r\nfunction isClientReachableFile(file: ScannedFile): boolean {\r\n const content = file.content as string;\r\n const normalized = normalizePath(file.path).toLowerCase();\r\n if (hasUseClientDirective(content)) {\r\n return true;\r\n }\r\n if (/\\.client\\.[jt]sx?$|(^|\\/)(client|frontend|public)\\//.test(normalized)) {\r\n return true;\r\n }\r\n\r\n return isBrowserOnlyPath(file.path) && /\\b(window|document|localStorage|sessionStorage|navigator|useEffect|onClick)\\b/.test(content);\r\n}\r\n\r\nfunction hasUseClientDirective(content: string): boolean {\r\n return /^(?:\\s|;|\\/\\/[^\\n]*(?:\\n|$)|\\/\\*[\\s\\S]*?\\*\\/)*['\"]use client['\"]/.test(content);\r\n}\r\n\r\nfunction isBrowserOnlyPath(path: string): boolean {\r\n const normalized = normalizePath(path).toLowerCase();\r\n if (isServerOnlyPath(path)) {\r\n return false;\r\n }\r\n\r\n return (\r\n /(^|\\/)(components|hooks|contexts|providers)\\//.test(normalized) ||\r\n /\\.(jsx|tsx)$/.test(normalized)\r\n );\r\n}\r\n\r\nfunction isServerOnlyPath(path: string): boolean {\r\n const normalized = normalizePath(path).toLowerCase();\r\n return /\\/api\\/|app\\/api\\/|pages\\/api\\/|route\\.[jt]s$|\\.server\\.[jt]sx?$|\\/server\\//.test(normalized);\r\n}\r\n\r\nfunction isEnvOrDocPath(path: string): boolean {\r\n return ENV_OR_DOC_PATH.test(normalizePath(path).toLowerCase());\r\n}\r\n\r\nfunction normalizePath(path: string): string {\r\n return path.replace(/\\\\/g, '/');\r\n}\r\n\r\nfunction unique(values: string[]): string[] {\r\n return [...new Set(values)];\r\n}\r\n", "import type { ScanResult, StationScanContext } from './types';\n\nexport function computeStationScanContext(scan: ScanResult): StationScanContext {\n const s = scan.stackSignals;\n const hasDb = Boolean(s.hasSupabase || s.hasPrisma || s.hasDrizzle || s.hasMongoose);\n const pathBlob = `${scan.fileTree}\\n${scan.files.map((f) => f.path).join('\\n')}`;\n const apiHeavy = /[/\\\\]api[/\\\\]|[/\\\\]routes[/\\\\]|\\btrpc\\b|\\bserver\\.(ts|js|mjs)\\b/i.test(pathBlob);\n\n const sqlish = scan.files\n .filter((f) => /\\.sql$/i.test(f.path) && typeof f.content === 'string')\n .map((f) => f.content as string)\n .join('\\n')\n .slice(0, 80000);\n const rlsInSql = /create\\s+policy|enable\\s+row\\s+level\\s+security|alter\\s+table.*enable\\s+row\\s+level/i.test(\n sqlish\n );\n const rlsPaths = /supabase\\/migrations[/\\\\].*\\.sql|\\/policies\\/|_rls\\.sql|\\brls\\b/i.test(pathBlob);\n const rlsHint = rlsPaths || rlsInSql;\n\n return {\n suggestDatabaseLayer: !hasDb && apiHeavy,\n suggestSupabaseRlsReview: Boolean(s.hasSupabase && !rlsHint),\n suggestLandingPage: Boolean(!s.hasLanding && (s.hasNextJs || s.hasVite)),\n };\n}\n", "import type { SifgNodeKind, SifgRange } from './sifgTypes';\r\nimport type { ScanResult, StackWiringArea, StackWiringKey } from './types';\r\n\r\ntype CandidateBucket = 'sources' | 'guards' | 'sinks';\r\n\r\nexport interface SifgCandidate {\r\n kind: SifgNodeKind;\r\n area: StackWiringArea;\r\n providerKey: StackWiringKey;\r\n label: string;\r\n file: string;\r\n range: SifgRange;\r\n symbol: string;\r\n evidence: Record<string, string>;\r\n secretPolicy: 'no-values';\r\n}\r\n\r\nexport interface SifgUnknownCandidate {\r\n file: string;\r\n range: SifgRange;\r\n reason: 'Dynamic handler forwarding prevents deterministic flow proof.';\r\n}\r\n\r\nexport interface SifgCandidateSet {\r\n sources: SifgCandidate[];\r\n guards: SifgCandidate[];\r\n sinks: SifgCandidate[];\r\n unknowns: SifgUnknownCandidate[];\r\n}\r\n\r\nconst ROUTE_FILE_PATTERN = /^(?:src\\/)?app\\/api\\/(?:.*\\/)?route\\.(?:ts|js)$/;\r\nconst ROUTE_METHOD_PATTERN = /export\\s+async\\s+function\\s+(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\\b/;\r\nconst POST_METHOD_PATTERN = /export\\s+async\\s+function\\s+POST\\b/;\r\nconst STRIPE_SIGNATURE_PATTERN = /webhooks\\.constructEvent\\b/;\r\nconst PRISMA_WRITE_PATTERN = /\\bprisma\\.[A-Za-z0-9_]+\\.(?:create|update|delete)\\s*\\(/;\r\nconst SUPABASE_WRITE_PATTERN = /\\bsupabase\\.from\\s*\\([^)]*\\)\\s*\\.\\s*(?:insert|update|delete)\\s*\\(/;\r\nconst DB_WRITE_PATTERN = /\\bdb\\.(?:insert|update|delete)\\s*\\(/;\r\nconst DYNAMIC_FORWARD_PATTERN = /return\\s+handler\\s*\\(\\s*req\\s*\\)/;\r\n\r\nexport function extractSifgCandidates(scan: ScanResult): SifgCandidateSet {\r\n const candidates: SifgCandidateSet = {\r\n sources: [],\r\n guards: [],\r\n sinks: [],\r\n unknowns: []\r\n };\r\n\r\n for (const scannedFile of scan.files) {\r\n if (scannedFile.isSecret || typeof scannedFile.content !== 'string') {\r\n continue;\r\n }\r\n\r\n const file = scannedFile.path.replace(/\\\\/g, '/');\r\n const content = scannedFile.content;\r\n const isRouteFile = ROUTE_FILE_PATTERN.test(file);\r\n\r\n if (isRouteFile && ROUTE_METHOD_PATTERN.test(content)) {\r\n const symbol = POST_METHOD_PATTERN.test(content) ? 'POST' : 'ANY';\r\n const isStripePostRoute = /stripe/i.test(file) && symbol === 'POST';\r\n addCandidate(candidates, 'sources', {\r\n kind: 'entrypoint',\r\n area: isStripePostRoute ? 'payments' : 'security',\r\n providerKey: isStripePostRoute ? 'stripe-payments' : 'rate-limit-security',\r\n label: isStripePostRoute ? 'Stripe route handler' : 'API route handler',\r\n file,\r\n range: rangeForMatch(content, symbol === 'POST' ? POST_METHOD_PATTERN : ROUTE_METHOD_PATTERN),\r\n symbol,\r\n evidence: { detector: 'nextjs-route-handler', symbol },\r\n secretPolicy: 'no-values'\r\n });\r\n }\r\n\r\n if (/stripe/i.test(`${file}\\n${content}`) && STRIPE_SIGNATURE_PATTERN.test(content)) {\r\n addCandidate(candidates, 'guards', {\r\n kind: 'signature-verifier',\r\n area: 'payments',\r\n providerKey: 'stripe-payments',\r\n label: 'Stripe signature verifier',\r\n file,\r\n range: rangeForMatch(content, STRIPE_SIGNATURE_PATTERN),\r\n symbol: 'stripe.webhooks.constructEvent',\r\n evidence: {\r\n detector: 'stripe-signature-guard',\r\n proof: 'stripe.webhooks.constructEvent'\r\n },\r\n secretPolicy: 'no-values'\r\n });\r\n }\r\n\r\n const databaseWritePattern = firstMatchingPattern(content, [\r\n PRISMA_WRITE_PATTERN,\r\n SUPABASE_WRITE_PATTERN,\r\n DB_WRITE_PATTERN\r\n ]);\r\n if (databaseWritePattern) {\r\n addCandidate(candidates, 'sinks', {\r\n kind: 'database-write',\r\n area: 'database',\r\n providerKey: 'supabase-database',\r\n label: 'Database write',\r\n file,\r\n range: rangeForMatch(content, databaseWritePattern),\r\n symbol: 'database-write',\r\n evidence: { detector: 'database-write', symbol: 'database-write' },\r\n secretPolicy: 'no-values'\r\n });\r\n }\r\n\r\n if (isRouteFile && DYNAMIC_FORWARD_PATTERN.test(content)) {\r\n candidates.unknowns.push({\r\n file,\r\n range: rangeForMatch(content, DYNAMIC_FORWARD_PATTERN),\r\n reason: 'Dynamic handler forwarding prevents deterministic flow proof.'\r\n });\r\n }\r\n }\r\n\r\n return candidates;\r\n}\r\n\r\nfunction addCandidate(\r\n candidates: SifgCandidateSet,\r\n bucket: CandidateBucket,\r\n candidate: SifgCandidate\r\n): void {\r\n candidates[bucket].push(candidate);\r\n}\r\n\r\nfunction firstMatchingPattern(content: string, patterns: RegExp[]): RegExp | null {\r\n return patterns.find((pattern) => pattern.test(content)) ?? null;\r\n}\r\n\r\nfunction rangeForMatch(content: string, pattern: RegExp): SifgRange {\r\n const match = pattern.exec(content);\r\n if (!match || match.index < 0) {\r\n return { startLine: 1, endLine: 1 };\r\n }\r\n\r\n const startLine = lineNumberAtOffset(content, match.index);\r\n const endOffset = Math.max(match.index, match.index + match[0].length - 1);\r\n const endLine = lineNumberAtOffset(content, endOffset);\r\n return { startLine, endLine };\r\n}\r\n\r\nfunction lineNumberAtOffset(content: string, offset: number): number {\r\n let line = 1;\r\n for (let index = 0; index < offset; index += 1) {\r\n if (content[index] === '\\n') {\r\n line += 1;\r\n }\r\n }\r\n return line;\r\n}\r\n", "import { extractSifgCandidates, type SifgCandidate } from './sifgExtractors';\r\nimport { allSifgTemplates, type SifgTemplate } from './sifgTemplates';\r\nimport type { ScanResult } from './types';\r\nimport type {\r\n SifgEdge,\r\n SifgGraph,\r\n SifgGraphStatus,\r\n SifgLeak,\r\n SifgNode,\r\n SifgNodeKind,\r\n SifgPipeline,\r\n SifgSeverity\r\n} from './sifgTypes';\r\n\r\nconst STRIPE_PIPELINE_ID_PREFIX = 'pipeline:payments:stripe:webhook-ingress';\r\nconst STRIPE_LEAK_ID_PREFIX = 'leak:payments:stripe:missing-signature-before-db';\r\nconst STRIPE_MISSION_CHECK_ID = 'stripe-webhook-signature-verification';\r\n\r\nexport function buildStaticInfrastructureFlowGraph(scan: ScanResult, now = new Date()): SifgGraph {\r\n const candidates = extractSifgCandidates(scan);\r\n const templates = allSifgTemplates();\r\n const nodeIndex = new Map<SifgCandidate, SifgNode>();\r\n const usedNodeIds = new Set<string>();\r\n\r\n const nodes = [...candidates.sources, ...candidates.guards, ...candidates.sinks].map((candidate) => {\r\n const node = candidateToNode(candidate, usedNodeIds);\r\n nodeIndex.set(candidate, node);\r\n return node;\r\n });\r\n\r\n const edges: SifgEdge[] = [];\r\n const pipelines: SifgPipeline[] = [];\r\n const leaks: SifgLeak[] = [];\r\n const stripeTemplate = templates.find((template) => template.id === 'template:payments:stripe:webhook-ingress');\r\n\r\n if (stripeTemplate && scan.stackSignals.hasStripe) {\r\n evaluateStripeWebhookIngress({\r\n candidates,\r\n nodeIndex,\r\n edges,\r\n pipelines,\r\n leaks,\r\n stripeTemplate\r\n });\r\n }\r\n\r\n return sanitizeGraph({\r\n version: 1,\r\n graphId: `sifg:workspace:${now.toISOString()}`,\r\n generatedAt: now.toISOString(),\r\n registryVersion: 1,\r\n status: graphStatus(pipelines, leaks),\r\n nodes,\r\n edges,\r\n pipelines,\r\n leaks\r\n });\r\n}\r\n\r\ninterface StripeEvaluationInput {\r\n candidates: ReturnType<typeof extractSifgCandidates>;\r\n nodeIndex: Map<SifgCandidate, SifgNode>;\r\n edges: SifgEdge[];\r\n pipelines: SifgPipeline[];\r\n leaks: SifgLeak[];\r\n stripeTemplate: SifgTemplate;\r\n}\r\n\r\nfunction evaluateStripeWebhookIngress(input: StripeEvaluationInput): void {\r\n const stripeSources = input.candidates.sources\r\n .filter((candidate) =>\r\n candidate.kind === 'entrypoint' &&\r\n candidate.providerKey === 'stripe-payments' &&\r\n candidate.symbol === 'POST'\r\n )\r\n .sort(compareCandidatePosition);\r\n\r\n for (const sourceCandidate of stripeSources) {\r\n const source = input.nodeIndex.get(sourceCandidate);\r\n if (!source) {\r\n continue;\r\n }\r\n\r\n const sameFileGuards = input.candidates.guards\r\n .filter((candidate) => candidate.file === source.file && candidate.kind === 'signature-verifier')\r\n .sort(compareCandidatePosition);\r\n const sameFileSinks = input.candidates.sinks\r\n .filter((candidate) => candidate.file === source.file && candidate.kind === 'database-write')\r\n .sort(compareCandidatePosition);\r\n const guard = sameFileGuards.map((candidate) => input.nodeIndex.get(candidate)).find(isSifgNode);\r\n const sink = sameFileSinks.map((candidate) => input.nodeIndex.get(candidate)).find(isSifgNode);\r\n const hasUnknown = input.candidates.unknowns.some((unknown) => unknown.file === source.file);\r\n const requiredEdges: string[] = [];\r\n const forbiddenEdges: string[] = [];\r\n const sourceSuffix = sourceSlug(source);\r\n const pipelineId = `${STRIPE_PIPELINE_ID_PREFIX}:${sourceSuffix}`;\r\n\r\n let status: SifgGraphStatus = 'unknown';\r\n let severity: SifgSeverity = 'warning';\r\n\r\n if (guard && sink && guard.range.startLine < sink.range.startLine) {\r\n const edge = buildEdge(source, sink, 'guarded-flow', 'verified', guard);\r\n input.edges.push(edge);\r\n requiredEdges.push(edge.id);\r\n status = 'verified';\r\n severity = 'info';\r\n } else if (sink && (!guard || guard.range.startLine > sink.range.startLine)) {\r\n const edge = buildEdge(source, sink, 'forbidden-flow', 'leak');\r\n input.edges.push(edge);\r\n forbiddenEdges.push(edge.id);\r\n status = 'leak';\r\n severity = 'critical';\r\n input.leaks.push(buildStripeMissingSignatureLeak(\r\n source,\r\n sink,\r\n input.stripeTemplate,\r\n pipelineId,\r\n `${STRIPE_LEAK_ID_PREFIX}:${sourceSuffix}`\r\n ));\r\n } else if (hasUnknown) {\r\n const target = sink ?? guard ?? source;\r\n const edge = buildEdge(source, target, 'unknown-flow', 'unknown');\r\n input.edges.push(edge);\r\n requiredEdges.push(edge.id);\r\n }\r\n\r\n input.pipelines.push({\r\n id: pipelineId,\r\n area: 'payments',\r\n providerKey: 'stripe-payments',\r\n label: input.stripeTemplate.label,\r\n source: source.id,\r\n requiredEdges,\r\n forbiddenEdges,\r\n status,\r\n severity,\r\n missionCheckIds: [STRIPE_MISSION_CHECK_ID]\r\n });\r\n }\r\n}\r\n\r\nfunction candidateToNode(candidate: SifgCandidate, usedNodeIds: Set<string>): SifgNode {\r\n const baseId = sanitizeId(`node:${candidate.kind}:${candidate.file}:${candidate.range.startLine}`);\r\n const id = uniqueId(baseId, usedNodeIds);\r\n\r\n return {\r\n id,\r\n area: candidate.area,\r\n providerKey: candidate.providerKey,\r\n kind: candidate.kind,\r\n label: symbolicNodeLabel(candidate),\r\n file: candidate.file,\r\n range: { ...candidate.range },\r\n evidence: normalizeCandidateEvidence(candidate),\r\n secretPolicy: 'no-values'\r\n };\r\n}\r\n\r\nfunction buildEdge(\r\n source: SifgNode,\r\n target: SifgNode,\r\n kind: SifgEdge['kind'],\r\n status: SifgEdge['status'],\r\n guard?: SifgNode\r\n): SifgEdge {\r\n return {\r\n id: sanitizeId(`edge:${kind}:${source.id}:${target.id}`),\r\n from: source.id,\r\n to: target.id,\r\n kind,\r\n status,\r\n evidence: [{\r\n file: target.file,\r\n range: target.range,\r\n proof: guard ? `${guard.kind}: ${guard.evidence.symbol ?? guard.label}` : target.kind\r\n }]\r\n };\r\n}\r\n\r\nfunction buildStripeMissingSignatureLeak(\r\n source: SifgNode,\r\n sink: SifgNode,\r\n stripeTemplate: SifgTemplate,\r\n pipelineId: string,\r\n leakId: string\r\n): SifgLeak {\r\n const requiredGuard = stripeTemplate.requiredGuards.find((guard) => guard.kind === 'signature-verifier');\r\n const guardKind = normalizeTemplateGuardKind(requiredGuard?.kind);\r\n\r\n return {\r\n id: leakId,\r\n pipelineId,\r\n area: 'payments',\r\n providerKey: 'stripe-payments',\r\n kind: 'missing-mandatory-guard',\r\n severity: 'critical',\r\n summary: 'Stripe webhook request body reaches database code without proven signature verification.',\r\n evidencePath: [\r\n { nodeId: source.id, file: source.file, range: source.range, role: 'source' },\r\n { nodeId: sink.id, file: sink.file, range: sink.range, role: 'sink' }\r\n ],\r\n missingGuard: {\r\n expectedNodeKind: guardKind,\r\n expectedEvidence: buildExpectedGuardEvidence(requiredGuard, guardKind)\r\n },\r\n repoFix: {\r\n allowedFiles: [source.file],\r\n forbiddenFiles: [...stripeTemplate.repoFixPolicy.blockedFileGlobs],\r\n requiredOutcome: buildRequiredOutcome(requiredGuard, guardKind)\r\n }\r\n };\r\n}\r\n\r\nfunction graphStatus(pipelines: SifgPipeline[], leaks: SifgLeak[]): SifgGraphStatus {\r\n if (leaks.length > 0) {\r\n return 'leak';\r\n }\r\n\r\n if (pipelines.some((pipeline) => pipeline.status === 'unknown')) {\r\n return 'unknown';\r\n }\r\n\r\n if (pipelines.some((pipeline) => pipeline.status === 'verified')) {\r\n return 'verified';\r\n }\r\n\r\n return 'unknown';\r\n}\r\n\r\nfunction compareCandidatePosition(left: SifgCandidate, right: SifgCandidate): number {\r\n return left.file.localeCompare(right.file) || left.range.startLine - right.range.startLine;\r\n}\r\n\r\nfunction isSifgNode(value: SifgNode | undefined): value is SifgNode {\r\n return Boolean(value);\r\n}\r\n\r\nfunction symbolicNodeLabel(candidate: SifgCandidate): string {\r\n if (candidate.providerKey === 'stripe-payments' && candidate.kind === 'entrypoint') {\r\n return 'Stripe webhook entrypoint';\r\n }\r\n\r\n if (candidate.kind === 'signature-verifier') {\r\n return 'Stripe signature verifier';\r\n }\r\n\r\n if (candidate.kind === 'database-write') {\r\n return 'Database write sink';\r\n }\r\n\r\n return `${candidate.providerKey} ${candidate.kind}`;\r\n}\r\n\r\nfunction normalizeCandidateEvidence(candidate: SifgCandidate): Record<string, string> {\r\n return {\r\n detector: normalizeDetector(candidate.evidence.detector, candidate.kind),\r\n symbol: normalizeSymbol(candidate)\r\n };\r\n}\r\n\r\nfunction normalizeDetector(detector: string | undefined, kind: SifgCandidate['kind']): string {\r\n if (detector && /^[a-z0-9-]+$/i.test(detector)) {\r\n return detector;\r\n }\r\n\r\n return kind;\r\n}\r\n\r\nfunction normalizeSymbol(candidate: SifgCandidate): string {\r\n if (candidate.kind === 'entrypoint' && (candidate.symbol === 'POST' || candidate.symbol === 'ANY')) {\r\n return candidate.symbol;\r\n }\r\n\r\n if (\r\n candidate.kind === 'signature-verifier' &&\r\n (candidate.symbol.includes('stripe.webhooks.constructEvent') ||\r\n candidate.evidence.proof?.includes('stripe.webhooks.constructEvent'))\r\n ) {\r\n return 'stripe.webhooks.constructEvent';\r\n }\r\n\r\n if (candidate.kind === 'database-write') {\r\n return 'database-write';\r\n }\r\n\r\n return candidate.kind;\r\n}\r\n\r\nfunction normalizeTemplateGuardKind(kind: string | undefined): SifgNodeKind {\r\n return kind === 'signature-verifier' ? 'signature-verifier' : 'signature-verifier';\r\n}\r\n\r\nfunction buildExpectedGuardEvidence(\r\n guard: SifgTemplate['requiredGuards'][number] | undefined,\r\n guardKind: SifgNodeKind\r\n): string {\r\n const symbols = guard?.symbols.length ? guard.symbols.join(', ') : guardKind;\r\n const envNames = guard?.requiresEnvNames?.length ? ` using ${guard.requiresEnvNames.join(', ')}` : '';\r\n const targets = guard?.mustPrecede.length ? ` before ${formatList(guard.mustPrecede)}` : '';\r\n return `${guardKind}: ${symbols}${envNames}${targets}`;\r\n}\r\n\r\nfunction buildRequiredOutcome(\r\n guard: SifgTemplate['requiredGuards'][number] | undefined,\r\n guardKind: SifgNodeKind\r\n): string {\r\n const symbols = guard?.symbols.length ? guard.symbols.join(', ') : guardKind;\r\n const envNames = guard?.requiresEnvNames?.length ? ` using ${guard.requiresEnvNames.join(', ')}` : '';\r\n const targets = guard?.mustPrecede.length ? formatList(guard.mustPrecede) : 'database-write';\r\n return `Verify ${guardKind} (${symbols}${envNames}) before ${targets}.`;\r\n}\r\n\r\nfunction formatList(items: string[]): string {\r\n if (items.length <= 1) {\r\n return items.join('');\r\n }\r\n\r\n if (items.length === 2) {\r\n return `${items[0]} or ${items[1]}`;\r\n }\r\n\r\n return `${items.slice(0, -1).join(', ')}, or ${items[items.length - 1]}`;\r\n}\r\n\r\nfunction uniqueId(baseId: string, usedNodeIds: Set<string>): string {\r\n let id = baseId;\r\n let suffix = 2;\r\n while (usedNodeIds.has(id)) {\r\n id = `${baseId}.${suffix}`;\r\n suffix += 1;\r\n }\r\n usedNodeIds.add(id);\r\n return id;\r\n}\r\n\r\nfunction sanitizeId(value: string): string {\r\n return value.replace(/[^a-zA-Z0-9:._-]/g, '-');\r\n}\r\n\r\nfunction sourceSlug(source: SifgNode): string {\r\n return sanitizeId(source.id);\r\n}\r\n\r\nfunction sanitizeGraph(graph: SifgGraph): SifgGraph {\r\n return redactStructured(graph) as SifgGraph;\r\n}\r\n\r\nfunction redactStructured(value: unknown): unknown {\r\n if (typeof value === 'string') {\r\n return redactSecretLike(value);\r\n }\r\n\r\n if (Array.isArray(value)) {\r\n return value.map(redactStructured);\r\n }\r\n\r\n if (value && typeof value === 'object') {\r\n return Object.fromEntries(\r\n Object.entries(value).map(([key, child]) => [key, redactStructured(child)])\r\n );\r\n }\r\n\r\n return value;\r\n}\r\n\r\nfunction redactSecretLike(value: string): string {\r\n return value\r\n .replace(/\\bsk_(?:live|test)_[a-zA-Z0-9_]+\\b/g, '[redacted]')\r\n .replace(/\\bBearer\\s+[a-zA-Z0-9._~+/=-]+\\b/gi, 'Bearer [redacted]')\r\n .replace(/\\b(api[_-]?key|access[_-]?token|refresh[_-]?token|secret)\\s*[:=]\\s*[^\\s\"'`,;)}]+/gi, '$1=[redacted]');\r\n}\r\n", "import type { ContextualPromptSection } from './promptRouting';\r\nimport type { SifgLeak } from './sifgTypes';\r\n\r\nexport function buildSifgFixPromptSection(leak: SifgLeak): ContextualPromptSection {\r\n return {\r\n heading: 'SIFG leak context',\r\n lines: [\r\n `Leak ID: ${sanitizePromptValue(leak.id)}`,\r\n `Pipeline ID: ${sanitizePromptValue(leak.pipelineId)}`,\r\n `Severity: ${sanitizePromptValue(leak.severity)}`,\r\n `Summary: ${sanitizePromptValue(leak.summary)}`,\r\n `Evidence path: ${evidencePathLine(leak)}`,\r\n leak.missingGuard\r\n ? `Missing guard: ${sanitizePromptValue(leak.missingGuard.expectedNodeKind)} (${sanitizePromptValue(leak.missingGuard.expectedEvidence)})`\r\n : 'Missing guard: none',\r\n `Allowed files: ${sanitizeList(leak.repoFix.allowedFiles)}`,\r\n `Blocked files: ${sanitizeList(leak.repoFix.forbiddenFiles)}`,\r\n `Required outcome: ${sanitizePromptValue(leak.repoFix.requiredOutcome)}`,\r\n 'Manual dashboard and MCP checks remain separate.',\r\n 'Do not read, print, invent, or store real secret values.',\r\n 'After editing, rescan VibeRaven so SIFG can verify the structural flow.'\r\n ]\r\n };\r\n}\r\n\r\nfunction evidencePathLine(leak: SifgLeak): string {\r\n if (leak.evidencePath.length === 0) {\r\n return 'none';\r\n }\r\n return leak.evidencePath\r\n .map((step) => `${sanitizePromptValue(step.role)} ${sanitizePromptValue(step.file)}:${step.range.startLine}-${step.range.endLine}`)\r\n .join(' -> ');\r\n}\r\n\r\nfunction sanitizeList(values: string[]): string {\r\n return values.map(sanitizePromptValue).join(', ');\r\n}\r\n\r\nfunction sanitizePromptValue(value: string): string {\r\n return value\r\n .replace(/[\\r\\n\\t]+/g, ' ')\r\n .replace(/[\\u0000-\\u001f\\u007f]+/g, ' ')\r\n .replace(/\\s{2,}/g, ' ')\r\n .trim()\r\n .replace(/\\b(Authorization\\s*:\\s*Bearer)\\s+[A-Za-z0-9._~+/=-]{8,}/gi, '$1 [redacted]')\r\n .replace(\r\n /\\b(client_secret|secret|password|access_token|refresh_token|private_key)\\s*([:=])\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s,;]+)/gi,\r\n (_match, key: string, separator: string) => `${key}${separator === ':' ? ': ' : '='}[redacted]`\r\n )\r\n .replace(/\\b(apiKey|accessToken|refreshToken|serviceRoleKey)\\s*:\\s*(?:\"[^\"]+\"|'[^']+'|[^\\s,;]+)/g, '$1: [redacted]')\r\n .replace(/\\b(apiKey|accessToken|refreshToken|serviceRoleKey)\\s*=\\s*(?:\"[^\"]+\"|'[^']+'|[^\\s,;]+)/g, '$1=[redacted]')\r\n .replace(\r\n /\\b([A-Za-z_][A-Za-z0-9_.-]*(?:SECRET|TOKEN|PASSWORD|PRIVATE_KEY|SERVICE_ROLE_KEY|apiKey|ApiKey|apikey|api_key|accessToken|refreshToken|serviceRoleKey)[A-Za-z0-9_.-]*)\\s*([:=])\\s*(?:\"[^\"]+\"|'[^']+'|[^\\s,;]+)/g,\r\n '$1$2[redacted]'\r\n )\r\n .replace(/\\b(?:whsec|github_pat|ghp|gho|ghu|ghs|ghr|gh_pat)_[A-Za-z0-9_]{8,}\\b/g, '[redacted-secret]')\r\n .replace(/\\b(?:sk|pk)_(?:live|test)_[a-zA-Z0-9_]+\\b/g, '[redacted-secret]')\r\n .replace(/\\beyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]{2,}\\.[A-Za-z0-9_-]{2,}\\b/g, '[redacted-secret]');\r\n}\r\n", "import type {\r\n ContextualPrompt,\r\n ContextualPromptKind,\r\n StackAutomationAction\r\n} from './types';\r\nimport { buildSifgFixPromptSection } from './sifgPrompt';\r\nimport type { SifgLeak } from './sifgTypes';\r\n\r\nexport interface ContextualPromptSection {\r\n heading: string;\r\n lines: string[];\r\n}\r\n\r\nexport interface BuildContextualPromptInput {\r\n kind: ContextualPromptKind;\r\n promptSubject: string;\r\n providerLabel?: string;\r\n passedCount?: number;\r\n totalCount?: number;\r\n readinessPercent?: number;\r\n repoFixes?: StackAutomationAction[];\r\n manualChecks?: StackAutomationAction[];\r\n mcpProvider?: string | null;\r\n ravenGap?: {\r\n title: string;\r\n detail?: string;\r\n };\r\n sections?: ContextualPromptSection[];\r\n sifgLeaks?: SifgLeak[];\r\n afterEditing?: string[];\r\n emptyBody?: boolean;\r\n}\r\n\r\nexport function buildContextualPrompt(input: BuildContextualPromptInput): ContextualPrompt {\r\n switch (input.kind) {\r\n case 'repo-fix':\r\n return buildRepoFixPrompt(input);\r\n case 'manual-checklist':\r\n return buildManualChecklistPrompt(input);\r\n case 'mcp-verification':\r\n return buildMcpVerificationPrompt(input);\r\n case 'raven-gap':\r\n return buildRavenGapPrompt(input);\r\n }\r\n}\r\n\r\nfunction buildRepoFixPrompt(input: BuildContextualPromptInput): ContextualPrompt {\r\n const sifgSections = input.sifgLeaks?.map(buildSifgFixPromptSection) ?? [];\r\n return {\r\n kind: 'repo-fix',\r\n title: `Repo fix: ${input.promptSubject}`,\r\n body: input.emptyBody ? '' : compactLines([\r\n `Automate ${input.promptSubject} production fixes safely.`,\r\n readinessLine(input),\r\n '',\r\n ...sectionLines([...sifgSections, ...(input.sections ?? [])]),\r\n 'Repo fixes to make:',\r\n actionLines(input.repoFixes, '- No repo fixes are currently missing.'),\r\n '',\r\n 'Manual checks to preserve as manual:',\r\n actionLines(input.manualChecks, '- No manual dashboard checks are listed.'),\r\n '',\r\n 'Rules:',\r\n '- Work only inside the local repository.',\r\n '- Do not open external dashboards.',\r\n '- Do not claim provider dashboard checks are complete.',\r\n '- Do not claim dashboard checks are complete from repo edits.',\r\n '- Do not print, request, store, or invent provider secrets.',\r\n '- Use placeholder env names only.',\r\n '- Change only files needed for the listed repo fixes.',\r\n '- Treat SIFG leak IDs as the source of truth for repo-local structural gaps.',\r\n '- Do not edit outside SIFG allowed files when SIFG context is present.',\r\n '- Follow the existing framework, file structure, and naming style.',\r\n '- Keep secrets in server-only code and env examples.',\r\n ...prefixedLines(input.afterEditing, '', 'After editing:')\r\n ]),\r\n allowedActions: ['edit-repo', 'run-local-tests'],\r\n forbiddenActions: ['verify-dashboard', 'open-dashboard', 'request-secrets', 'store-secrets', 'invent-secrets']\r\n };\r\n}\r\n\r\nfunction buildManualChecklistPrompt(input: BuildContextualPromptInput): ContextualPrompt {\r\n return {\r\n kind: 'manual-checklist',\r\n title: `Manual checklist: ${input.promptSubject}`,\r\n body: compactLines([\r\n `Prepare manual setup checklist for ${input.promptSubject}.`,\r\n '',\r\n 'Rules:',\r\n '- Prepare a checklist for the developer.',\r\n '- Do not mark dashboard setup complete.',\r\n '- Do not request, print, store, or invent secrets.',\r\n '',\r\n 'Manual checks:',\r\n actionLines(input.manualChecks, '- No manual dashboard checks are listed.')\r\n ]),\r\n allowedActions: ['explain-manual-steps'],\r\n forbiddenActions: ['mark-dashboard-complete', 'request-secrets', 'store-secrets', 'invent-secrets']\r\n };\r\n}\r\n\r\nfunction buildMcpVerificationPrompt(input: BuildContextualPromptInput): ContextualPrompt {\r\n return {\r\n kind: 'mcp-verification',\r\n title: `MCP verification: ${input.promptSubject}`,\r\n body: compactLines([\r\n `Verify ${input.promptSubject} after VibeRaven automation.`,\r\n input.mcpProvider ? `MCP verifier: ${input.mcpProvider}.` : 'MCP verifier: none configured.',\r\n '',\r\n 'Rules:',\r\n '- Use only read-only MCP calls if already configured and authenticated by the IDE.',\r\n '- Never store OAuth tokens, API keys, or MCP credentials.',\r\n '- Report MCP evidence as verifier evidence, not manual dashboard completion.',\r\n '- If the verifier is unavailable, say that and stop.',\r\n '',\r\n 'Verification:',\r\n '- Rescan the repo and confirm missing checks moved to passed where repo evidence exists.',\r\n '- Report any remaining missing repo fixes separately from dashboard/manual checks.',\r\n '- If no repo fixes remain, keep the remaining dashboard/manual checks explicit instead of editing unrelated code.'\r\n ]),\r\n allowedActions: ['read-only-mcp', 'summarize-evidence'],\r\n forbiddenActions: ['write-mcp', 'mutate-provider', 'store-mcp-credentials', 'mark-dashboard-complete']\r\n };\r\n}\r\n\r\nfunction buildRavenGapPrompt(input: BuildContextualPromptInput): ContextualPrompt {\r\n const gapTitle = input.ravenGap?.title ?? input.promptSubject;\r\n return {\r\n kind: 'raven-gap',\r\n title: `Raven gap: ${gapTitle}`,\r\n body: compactLines([\r\n `Fix Raven product gap: ${gapTitle}.`,\r\n input.ravenGap?.detail ? `Gap detail: ${input.ravenGap.detail}` : '',\r\n '',\r\n 'Rules:',\r\n '- Fix only the Raven product gap described.',\r\n '- Work only in the repo.',\r\n '- Do not rewrite unrelated product areas.',\r\n '- Do not open dashboards or claim external setup.',\r\n '',\r\n 'After editing:',\r\n '- Run the closest relevant local tests, compile, or typecheck command.',\r\n '- Summarize changed files and verified commands.'\r\n ]),\r\n allowedActions: ['edit-repo', 'run-local-tests'],\r\n forbiddenActions: ['open-dashboard', 'claim-external-setup', 'rewrite-unrelated-product-areas']\r\n };\r\n}\r\n\r\nfunction readinessLine(input: BuildContextualPromptInput): string {\r\n if (input.passedCount === undefined || input.totalCount === undefined || input.readinessPercent === undefined) {\r\n return '';\r\n }\r\n return `Current readiness: ${input.passedCount}/${input.totalCount} repo checks passed (${input.readinessPercent}%).`;\r\n}\r\n\r\nfunction sectionLines(sections: ContextualPromptSection[] | undefined): string[] {\r\n if (!sections || sections.length === 0) {\r\n return [];\r\n }\r\n return sections.flatMap((section) => [\r\n section.heading,\r\n ...section.lines.map((line) => `- ${line}`),\r\n ''\r\n ]);\r\n}\r\n\r\nfunction actionLines(actions: StackAutomationAction[] | undefined, fallback: string): string {\r\n if (!actions || actions.length === 0) {\r\n return fallback;\r\n }\r\n return actions.map((action) => `- ${action.label}: ${action.promptHint}`).join('\\n');\r\n}\r\n\r\nfunction prefixedLines(lines: string[] | undefined, fallback: string, heading: string): string[] {\r\n if (!lines || lines.length === 0) {\r\n return fallback ? [heading, fallback] : [];\r\n }\r\n return ['', heading, ...lines.map((line) => `- ${line}`)];\r\n}\r\n\r\nfunction compactLines(lines: Array<string | string[]>): string {\r\n return lines.flat().join('\\n').replace(/\\n{3,}/g, '\\n\\n').trim();\r\n}\r\n", "import type {\r\n ContextualPrompt,\r\n ContextualPromptKind,\r\n StackAutomationAction,\r\n StackAutomationRecipe,\r\n StackAutomationSummary,\r\n StackWiringItem,\r\n StackWiringKey,\r\n StackWiringProviderSummary,\r\n StackWiringSummary\r\n} from './types';\r\nimport type { SifgGraph, SifgLeak } from './sifgTypes';\r\nimport { mcpProviderIdForStackWiringKey } from './providerRegistry';\r\nimport { buildContextualPrompt, type ContextualPromptSection } from './promptRouting';\r\n\r\ntype PromptProfile = {\r\n inspect: string[];\r\n implement: string[];\r\n constraints: string[];\r\n verify: string[];\r\n};\r\n\r\nconst GENERIC_PROMPT_PROFILE: PromptProfile = {\r\n inspect: [\r\n 'Review the relevant routes, server code, client code, config files, package scripts, and env examples before editing.',\r\n 'Identify existing conventions for file names, imports, validation, and error handling.'\r\n ],\r\n implement: [\r\n 'Make the smallest repo-only changes needed for the missing checks.',\r\n 'Keep changes aligned with the current framework and folder structure.'\r\n ],\r\n constraints: [\r\n 'Do not call provider APIs, mutate external projects, or edit webview/dashboard state.',\r\n 'Keep secrets in server-only code and documented env examples.'\r\n ],\r\n verify: [\r\n 'Run the closest relevant build, test, lint, or typecheck command.',\r\n 'Confirm repo evidence exists for each fixed item and list manual checks separately.'\r\n ]\r\n};\r\n\r\nconst PROMPT_PROFILES: Partial<Record<StackWiringKey, PromptProfile>> = {\r\n 'stripe-payments': {\r\n inspect: [\r\n 'Inspect app/api, pages/api, server routes, checkout actions, webhook handlers, and .env.example before editing.',\r\n 'Check how STRIPE_SECRET_KEY, STRIPE_WEBHOOK_SECRET, price IDs, and success/cancel URLs are currently named.'\r\n ],\r\n implement: [\r\n 'Add or tighten a server-side Stripe webhook route that verifies signatures with webhooks.constructEvent before processing events.',\r\n 'Document required Stripe env names and keep checkout/session creation on the server.'\r\n ],\r\n constraints: [\r\n 'Do not create products, prices, customers, or webhooks through the Stripe API.',\r\n 'Do not mark live-mode products, webhook endpoint registration, or dashboard settings complete from repo edits.'\r\n ],\r\n verify: [\r\n 'Run the relevant route/unit tests or typecheck for payment code.',\r\n 'Confirm webhook secret usage and server-only Stripe code are visible in repo evidence.'\r\n ]\r\n },\r\n 'clerk-auth': {\r\n inspect: [\r\n 'Inspect middleware, protected routes, layout providers, server actions, and auth-related env examples.',\r\n 'Check current Clerk package usage, publishable key names, secret key names, and redirect handling.'\r\n ],\r\n implement: [\r\n 'Add route protection, auth provider setup, and server-side user checks where missing.',\r\n 'Document NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY, CLERK_SECRET_KEY, and required redirect URLs in repo examples.'\r\n ],\r\n constraints: [\r\n 'Do not configure Clerk dashboard applications, domains, or production instances.',\r\n 'Do not expose secret keys to client bundles.'\r\n ],\r\n verify: [\r\n 'Run auth-related tests or typecheck.',\r\n 'Confirm protected-route and env documentation evidence exists in the repo.'\r\n ]\r\n },\r\n 'supabase-database': {\r\n inspect: [\r\n 'Inspect Supabase client/server helpers, migrations, SQL policies, schema files, and env examples.',\r\n 'Check whether service-role usage is isolated to server-only paths.'\r\n ],\r\n implement: [\r\n 'Add missing schema, migration, RLS policy, and typed client evidence where repo checks require it.',\r\n 'Document SUPABASE_URL, anon key, and server-only service role env names without committing secrets.'\r\n ],\r\n constraints: [\r\n 'Do not call Supabase APIs, create remote projects, run dashboard changes, or apply migrations remotely.',\r\n 'Do not place service-role keys in client-accessible code.'\r\n ],\r\n verify: [\r\n 'Run database-related tests, migration checks, or typecheck available in the repo.',\r\n 'Confirm RLS and migration evidence is repo-visible and dashboard checks remain manual.'\r\n ]\r\n },\r\n 'vercel-deployment': {\r\n inspect: [\r\n 'Inspect vercel.json, package scripts, framework config, environment examples, and CI/deploy workflows.',\r\n 'Check build command, output settings, redirects, rewrites, and serverless/edge function usage.'\r\n ],\r\n implement: [\r\n 'Add repo deployment configuration, build scripts, env documentation, or route settings needed for missing checks.',\r\n 'Keep deployment assumptions encoded in config files rather than external dashboard state.'\r\n ],\r\n constraints: [\r\n 'Do not deploy, promote, link, or mutate Vercel projects.',\r\n 'Do not claim production domains, env vars, or dashboard settings are configured from repo edits.'\r\n ],\r\n verify: [\r\n 'Run the project build or compile command.',\r\n 'Confirm deployment config evidence exists and list dashboard checks as manual.'\r\n ]\r\n },\r\n 'sentry-monitoring': {\r\n inspect: [\r\n 'Inspect Sentry initialization, framework instrumentation files, error boundaries, source map config, and env examples.',\r\n 'Check client/server DSN separation and release/environment tagging conventions.'\r\n ],\r\n implement: [\r\n 'Add missing Sentry initialization, error capture, tracing, source map, or env documentation evidence.',\r\n 'Ensure captured errors include useful context without leaking secrets or PII.'\r\n ],\r\n constraints: [\r\n 'Do not create Sentry projects, upload releases, or change dashboard alert rules.',\r\n 'Do not hardcode DSNs or auth tokens outside env examples.'\r\n ],\r\n verify: [\r\n 'Run monitoring-related tests, build, or typecheck.',\r\n 'Confirm instrumentation and env evidence are present while dashboard checks remain manual.'\r\n ]\r\n },\r\n 'posthog-monitoring': {\r\n inspect: [\r\n 'Inspect PostHog initialization, analytics providers, event capture calls, consent handling, and env examples.',\r\n 'Check whether user identity, feature flags, and client/server keys are separated correctly.'\r\n ],\r\n implement: [\r\n 'Add missing PostHog setup, event capture, opt-in/consent, feature flag, or env documentation evidence.',\r\n 'Keep analytics initialization resilient around loading, routing, and disabled-key states.'\r\n ],\r\n constraints: [\r\n 'Do not create PostHog projects, change dashboard events, or mutate feature flags remotely.',\r\n 'Do not capture secrets, raw tokens, or unnecessary PII.'\r\n ],\r\n verify: [\r\n 'Run analytics-related tests, build, or typecheck.',\r\n 'Confirm repo evidence for initialization, capture, and privacy controls.'\r\n ]\r\n },\r\n 'react-frontend': {\r\n inspect: [\r\n 'Inspect components, routes, state/data-loading paths, forms, styling, and existing design-system patterns.',\r\n 'Check current loading, error, empty, and responsive states before editing.'\r\n ],\r\n implement: [\r\n 'Add missing loading states, error states, empty states, accessibility attributes, and responsive layout behavior.',\r\n 'Use existing component patterns and keep visual changes focused on the listed repo fixes.'\r\n ],\r\n constraints: [\r\n 'Do not edit external design tools, dashboards, or webview automation state.',\r\n 'Do not replace the app framework or introduce unrelated UI rewrites.'\r\n ],\r\n verify: [\r\n 'Run frontend tests, typecheck, or build.',\r\n 'Confirm loading, error, and responsive behavior have repo-visible evidence.'\r\n ]\r\n },\r\n 'node-backend': {\r\n inspect: [\r\n 'Inspect API routes, controllers, services, middleware, validation, logging, and env examples.',\r\n 'Check current error handling, request validation, authentication boundaries, and server startup scripts.'\r\n ],\r\n implement: [\r\n 'Add missing validation, error handling, health checks, logging, or server-only env documentation evidence.',\r\n 'Keep backend changes small and aligned with existing route/service patterns.'\r\n ],\r\n constraints: [\r\n 'Do not call production provider APIs or mutate external infrastructure.',\r\n 'Do not expose secrets in logs, client responses, or committed examples.'\r\n ],\r\n verify: [\r\n 'Run backend tests, typecheck, or compile.',\r\n 'Confirm fixed checks have repo evidence and operational dashboard checks stay manual.'\r\n ]\r\n }\r\n};\r\n\r\nexport function buildStackAutomationSummary(\r\n stackWiring: StackWiringSummary,\r\n options: { staticInfrastructureFlowGraph?: SifgGraph } = {}\r\n): StackAutomationSummary {\r\n const items = stackWiring.items.map((stack) => buildStackAutomationRecipe(stack, sifgLeaksForStack(stack, options.staticInfrastructureFlowGraph)));\r\n const byKey = items.reduce<StackAutomationSummary['byKey']>((acc, recipe) => {\r\n acc[recipe.key] = recipe;\r\n return acc;\r\n }, {});\r\n return { items, byKey };\r\n}\r\n\r\nexport function buildStackAutomationContext(summary: StackAutomationSummary): string {\r\n const lines = ['## STACK AUTOMATION'];\r\n for (const recipe of summary.items) {\r\n lines.push(`${recipe.key}: ${recipe.automationLevel}; repo fixes=${recipe.repoFixes.length}; manual checks=${recipe.manualChecks.length}; mcp=${recipe.mcpProvider ?? 'none'}`);\r\n for (const fix of recipe.repoFixes.slice(0, 6)) {\r\n lines.push(`${recipe.key} fix: ${fix.label} - ${fix.promptHint}`);\r\n }\r\n }\r\n return lines.join('\\n');\r\n}\r\n\r\nfunction buildStackAutomationRecipe(stack: StackWiringProviderSummary, sifgLeaks: SifgLeak[] = []): StackAutomationRecipe {\r\n const confirmedChecks = stack.items.filter((item) => item.status === 'passed').map(toAction);\r\n const repoFixes = stack.items.filter((item) => item.status === 'missing').map(toAction);\r\n const manualChecks = stack.items.filter((item) => item.status === 'manual').map(toAction);\r\n const mcpProvider = mcpProviderIdForStackWiringKey(stack.key);\r\n const hasRepoFixContext = repoFixes.length > 0 || sifgLeaks.length > 0;\r\n const automationLevel = !hasRepoFixContext && manualChecks.length > 0 ? 'manual-only' : mcpProvider ? 'repo-prompt-plus-mcp' : 'repo-prompt';\r\n const promptRoutes = buildPromptRoutes(stack, repoFixes, manualChecks, mcpProvider, automationLevel, sifgLeaks);\r\n return {\r\n key: stack.key,\r\n provider: stack.provider,\r\n providerLabel: stack.providerLabel,\r\n area: stack.area,\r\n promptSubject: stack.promptSubject,\r\n readinessPercent: stack.readinessPercent,\r\n repoFixes,\r\n manualChecks,\r\n confirmedChecks,\r\n mcpProvider,\r\n repoPrompt: promptRoutes['repo-fix']?.body ?? '',\r\n verificationPrompt: verificationPromptForRecipe(promptRoutes, automationLevel, manualChecks, sifgLeaks),\r\n automationLevel,\r\n promptRoutes\r\n };\r\n}\r\n\r\nfunction toAction(item: StackWiringItem): StackAutomationAction {\r\n return {\r\n id: item.id,\r\n label: item.label,\r\n status: item.status,\r\n promptHint: item.promptHint,\r\n evidence: item.evidence\r\n };\r\n}\r\n\r\nfunction buildPromptRoutes(\r\n stack: StackWiringProviderSummary,\r\n repoFixes: StackAutomationAction[],\r\n manualChecks: StackAutomationAction[],\r\n mcpProvider: string | null,\r\n automationLevel: StackAutomationRecipe['automationLevel'],\r\n sifgLeaks: SifgLeak[]\r\n): Partial<Record<ContextualPromptKind, ContextualPrompt>> {\r\n return {\r\n 'repo-fix': buildContextualPrompt({\r\n kind: 'repo-fix',\r\n promptSubject: stack.promptSubject,\r\n providerLabel: stack.providerLabel,\r\n passedCount: stack.passedCount,\r\n totalCount: stack.totalCount,\r\n readinessPercent: stack.readinessPercent,\r\n repoFixes,\r\n manualChecks,\r\n sifgLeaks,\r\n sections: buildRepoPromptSections(stack),\r\n afterEditing: [\r\n 'Run the relevant build/test/typecheck command.',\r\n 'Summarize changed files, verified commands, and manual checks still needed.'\r\n ],\r\n emptyBody: automationLevel === 'manual-only'\r\n }),\r\n 'manual-checklist': buildContextualPrompt({\r\n kind: 'manual-checklist',\r\n promptSubject: stack.promptSubject,\r\n providerLabel: stack.providerLabel,\r\n manualChecks\r\n }),\r\n 'mcp-verification': buildContextualPrompt({\r\n kind: 'mcp-verification',\r\n promptSubject: stack.promptSubject,\r\n providerLabel: stack.providerLabel,\r\n mcpProvider\r\n })\r\n };\r\n}\r\n\r\nfunction sifgLeaksForStack(stack: StackWiringProviderSummary, graph: SifgGraph | undefined): SifgLeak[] {\r\n if (!graph) {\r\n return [];\r\n }\r\n return graph.leaks.filter((leak) => leak.providerKey === stack.key);\r\n}\r\n\r\nfunction verificationPromptForRecipe(\r\n promptRoutes: Partial<Record<ContextualPromptKind, ContextualPrompt>>,\r\n automationLevel: StackAutomationRecipe['automationLevel'],\r\n manualChecks: StackAutomationAction[],\r\n sifgLeaks: SifgLeak[]\r\n): string {\r\n const manualPrompt = promptRoutes['manual-checklist']?.body ?? '';\r\n const mcpPrompt = promptRoutes['mcp-verification']?.body ?? '';\r\n if (automationLevel === 'manual-only') {\r\n return manualPrompt || mcpPrompt;\r\n }\r\n if (sifgLeaks.length > 0 && manualChecks.length > 0) {\r\n return [manualPrompt, mcpPrompt].filter(Boolean).join('\\n\\n');\r\n }\r\n return mcpPrompt;\r\n}\r\n\r\nfunction buildRepoPromptSections(stack: StackWiringProviderSummary): ContextualPromptSection[] {\r\n const profile = PROMPT_PROFILES[stack.key] ?? GENERIC_PROMPT_PROFILE;\r\n return [\r\n { heading: 'Inspect first:', lines: profile.inspect },\r\n { heading: 'Implement:', lines: profile.implement },\r\n { heading: 'Provider constraints:', lines: profile.constraints },\r\n { heading: 'Verification:', lines: profile.verify }\r\n ];\r\n}\r\n", "import type { ScanResult, StackWiringItem, StackWiringStatus, SupabaseDatabaseWiringSummary } from './types';\r\n\r\ntype ScannableFile = {\r\n path: string;\r\n normalizedPath: string;\r\n content: string;\r\n lowerContent: string;\r\n};\r\n\r\nexport function analyzeSupabaseDatabaseWiring(scan: ScanResult): SupabaseDatabaseWiringSummary {\r\n const files = visibleFiles(scan);\r\n const deps = scan.packageDeps.map((dep) => dep.toLowerCase());\r\n const pathBlob = `${scan.fileTree}\\n${scan.files.map((file) => file.path).join('\\n')}`.replace(/\\\\/g, '/').toLowerCase();\r\n const contentBlob = files.map((file) => file.lowerContent).join('\\n');\r\n\r\n const items: StackWiringItem[] = [\r\n item(\r\n 'package-installed',\r\n 'Supabase package installed',\r\n deps.some((dep) => dep === '@supabase/supabase-js' || dep === '@supabase/ssr' || dep.startsWith('@supabase/')),\r\n packageEvidence(deps),\r\n 'Install the correct Supabase package for this app framework.'\r\n ),\r\n item(\r\n 'env-names-documented',\r\n 'Supabase env names documented',\r\n hasSupabaseUrl(contentBlob) && hasSupabaseAnonKey(contentBlob),\r\n envEvidence(contentBlob),\r\n 'Document NEXT_PUBLIC_SUPABASE_URL/VITE_SUPABASE_URL and the matching anon key in an env example or config docs.'\r\n ),\r\n item(\r\n 'client-file-exists',\r\n 'Supabase client file exists',\r\n hasSupabaseClient(files, pathBlob),\r\n clientEvidence(files, pathBlob),\r\n 'Create a Supabase client helper that follows the existing app structure.'\r\n ),\r\n item(\r\n 'database-query-usage',\r\n 'Database query usage found',\r\n /\\.from\\s*\\(\\s*['\"][a-z0-9_]+['\"]\\s*\\)/i.test(contentBlob),\r\n queryEvidence(files),\r\n 'Use the Supabase client from server-safe code paths for real database reads or writes.'\r\n ),\r\n item(\r\n 'schema-or-migrations',\r\n 'Schema or migration file found',\r\n hasSchemaOrMigration(files, pathBlob),\r\n schemaEvidence(files, pathBlob),\r\n 'Add a checked-in schema or migration path so database structure is reproducible.'\r\n ),\r\n item(\r\n 'rls-policy-evidence',\r\n 'Supabase RLS policy evidence found',\r\n hasRlsEvidence(files, pathBlob),\r\n rlsEvidence(files, pathBlob),\r\n 'Add or document Supabase RLS policies for user-owned tables before launch.'\r\n ),\r\n item(\r\n 'generated-types',\r\n 'Generated database types found',\r\n hasGeneratedTypes(files, pathBlob),\r\n generatedTypeEvidence(files, pathBlob),\r\n 'Generate and commit Supabase database types for safer app code.'\r\n ),\r\n serviceRoleSafetyItem(files)\r\n ];\r\n\r\n const passedCount = items.filter((entry) => entry.status === 'passed').length;\r\n const totalCount = items.length;\r\n const readinessPercent = Math.round((passedCount / Math.max(totalCount, 1)) * 100);\r\n\r\n return {\r\n key: 'supabase-database',\r\n provider: 'supabase',\r\n providerLabel: 'Supabase',\r\n area: 'database',\r\n areaLabel: 'Database',\r\n promptSubject: 'Supabase database',\r\n items,\r\n passedCount,\r\n totalCount,\r\n readinessPercent\r\n };\r\n}\r\n\r\nexport function buildSupabaseDatabaseWiringPrompt(wiring: SupabaseDatabaseWiringSummary): string {\r\n const passed = wiring.items.filter((entry) => entry.status === 'passed');\r\n const missing = wiring.items.filter((entry) => entry.status === 'missing');\r\n const passedLines = passed.length > 0\r\n ? passed.map((entry) => `- ${entry.label}${formatEvidence(entry.evidence)}`).join('\\n')\r\n : '- No Supabase wiring checks passed yet.';\r\n const missingLines = missing.length > 0\r\n ? missing.map((entry) => `- ${entry.label}: ${entry.promptHint}`).join('\\n')\r\n : '- No missing Supabase database wiring checks were found by VibeRaven.';\r\n\r\n return [\r\n 'Wire Supabase database for this app safely.',\r\n '',\r\n `Current Supabase database wiring readiness: ${wiring.passedCount}/${wiring.totalCount} checks passed (${wiring.readinessPercent}%).`,\r\n '',\r\n 'Repo evidence already found:',\r\n passedLines,\r\n '',\r\n 'Missing Supabase database wiring checks:',\r\n missingLines,\r\n '',\r\n 'First inspect the existing package.json files, env examples, Supabase client helpers, database access files, and supabase/ or migrations/ directories. Identify the current framework and data access pattern before editing.',\r\n '',\r\n 'Implement:',\r\n '1. Close only the missing Supabase database wiring checks listed above.',\r\n '2. Follow the existing file structure and naming patterns.',\r\n '3. Keep database setup reproducible through checked-in schema, migrations, or documented generation commands.',\r\n '4. Keep service-role keys out of frontend and client-executed files.',\r\n '',\r\n 'Constraints:',\r\n '- Do not rewrite unrelated auth, payments, UI, billing, or deployment code.',\r\n '- Do not claim Supabase dashboard setup is complete from repo evidence alone.',\r\n '- Do not expose SUPABASE_SERVICE_ROLE_KEY to browser code, Vite public env, or NEXT_PUBLIC env variables.',\r\n '',\r\n 'Verification:',\r\n '- Run the relevant TypeScript/build/test command for this repo.',\r\n '- Confirm VibeRaven can rescan and move the missing Supabase wiring checks to passed where repo evidence exists.',\r\n '- Summarize what changed and what still requires manual Supabase dashboard verification.'\r\n ].join('\\n');\r\n}\r\n\r\nexport function buildSupabaseDatabaseWiringContext(wiring: SupabaseDatabaseWiringSummary): string {\r\n const lines = [\r\n '## SUPABASE DATABASE WIRING',\r\n `${wiring.passedCount}/${wiring.totalCount} checks passed (${wiring.readinessPercent}%).`\r\n ];\r\n\r\n for (const entry of wiring.items) {\r\n const evidence = entry.evidence.length > 0 ? ` (${entry.evidence.slice(0, 3).join('; ')})` : '';\r\n lines.push(`${entry.status}: ${entry.label}${evidence}`);\r\n }\r\n\r\n return lines.join('\\n');\r\n}\r\n\r\nfunction visibleFiles(scan: ScanResult): ScannableFile[] {\r\n return scan.files\r\n .filter((file) => !file.isSecret && typeof file.content === 'string')\r\n .map((file) => ({\r\n path: file.path.replace(/\\\\/g, '/'),\r\n normalizedPath: file.path.replace(/\\\\/g, '/').toLowerCase(),\r\n content: file.content as string,\r\n lowerContent: (file.content as string).toLowerCase()\r\n }));\r\n}\r\n\r\nfunction item(\r\n id: string,\r\n label: string,\r\n passed: boolean,\r\n evidence: string[],\r\n promptHint: string\r\n): StackWiringItem {\r\n return {\r\n id,\r\n label,\r\n status: passed ? 'passed' : 'missing',\r\n evidence,\r\n promptHint\r\n };\r\n}\r\n\r\nfunction packageEvidence(deps: string[]): string[] {\r\n return deps.filter((dep) => dep === '@supabase/supabase-js' || dep === '@supabase/ssr' || dep.startsWith('@supabase/'))\r\n .map((dep) => `package: ${dep}`);\r\n}\r\n\r\nfunction hasSupabaseUrl(contentBlob: string): boolean {\r\n return /\\b(vite_|next_public_)?supabase_url\\b/i.test(contentBlob);\r\n}\r\n\r\nfunction hasSupabaseAnonKey(contentBlob: string): boolean {\r\n return /\\b(vite_|next_public_)?supabase_anon_key\\b/i.test(contentBlob);\r\n}\r\n\r\nfunction envEvidence(contentBlob: string): string[] {\r\n const evidence: string[] = [];\r\n if (hasSupabaseUrl(contentBlob)) {\r\n evidence.push('env: SUPABASE_URL');\r\n }\r\n if (hasSupabaseAnonKey(contentBlob)) {\r\n evidence.push('env: SUPABASE_ANON_KEY');\r\n }\r\n return evidence;\r\n}\r\n\r\nfunction hasSupabaseClient(files: ScannableFile[], pathBlob: string): boolean {\r\n return /(^|\\n|\\/)(lib|utils|src\\/lib|src\\/utils)\\/supabase\\.[jt]s\\b/i.test(pathBlob) ||\r\n files.some((file) => /createclient\\s*\\(/i.test(file.content) && /@supabase\\/(supabase-js|ssr)/i.test(file.content));\r\n}\r\n\r\nfunction clientEvidence(files: ScannableFile[], pathBlob: string): string[] {\r\n const evidence: string[] = [];\r\n const pathMatch = pathBlob.split(/\\r?\\n/).find((path) => /(^|\\/)(lib|utils|src\\/lib|src\\/utils)\\/supabase\\.[jt]s\\b/i.test(path));\r\n if (pathMatch) {\r\n evidence.push(`file: ${pathMatch}`);\r\n }\r\n const importFile = files.find((file) => /createclient\\s*\\(/i.test(file.content) && /@supabase\\/(supabase-js|ssr)/i.test(file.content));\r\n if (importFile && !evidence.includes(`file: ${importFile.path}`)) {\r\n evidence.push(`file: ${importFile.path}`);\r\n }\r\n return evidence;\r\n}\r\n\r\nfunction queryEvidence(files: ScannableFile[]): string[] {\r\n return files\r\n .filter((file) => /\\.from\\s*\\(\\s*['\"][a-z0-9_]+['\"]\\s*\\)/i.test(file.content))\r\n .slice(0, 4)\r\n .map((file) => `query: ${file.path}`);\r\n}\r\n\r\nfunction hasSchemaOrMigration(files: ScannableFile[], pathBlob: string): boolean {\r\n return /(^|\\n|\\/)supabase\\/migrations\\/[^/\\n]+\\.sql\\b/i.test(pathBlob) ||\r\n /(^|\\n|\\/)(migrations?|schema)\\/[^/\\n]+\\.(sql|ts|js)\\b/i.test(pathBlob) ||\r\n files.some((file) => /create\\s+table|alter\\s+table/i.test(file.content));\r\n}\r\n\r\nfunction schemaEvidence(files: ScannableFile[], pathBlob: string): string[] {\r\n const path = pathBlob.split(/\\r?\\n/).find((entry) =>\r\n /(^|\\/)supabase\\/migrations\\/[^/]+\\.sql\\b/i.test(entry) ||\r\n /(^|\\/)(migrations?|schema)\\/[^/]+\\.(sql|ts|js)\\b/i.test(entry)\r\n );\r\n if (path) {\r\n return [`schema: ${path}`];\r\n }\r\n const file = files.find((entry) => /create\\s+table|alter\\s+table/i.test(entry.content));\r\n return file ? [`schema: ${file.path}`] : [];\r\n}\r\n\r\nfunction hasRlsEvidence(files: ScannableFile[], pathBlob: string): boolean {\r\n return /\\/policies\\/|_rls\\.sql|\\brls\\b/i.test(pathBlob) ||\r\n files.some((file) => /enable\\s+row\\s+level\\s+security|create\\s+policy|alter\\s+table[\\s\\S]{0,200}enable\\s+row\\s+level/i.test(file.content));\r\n}\r\n\r\nfunction rlsEvidence(files: ScannableFile[], pathBlob: string): string[] {\r\n const path = pathBlob.split(/\\r?\\n/).find((entry) => /\\/policies\\/|_rls\\.sql|\\brls\\b/i.test(entry));\r\n if (path) {\r\n return [`rls: ${path}`];\r\n }\r\n const file = files.find((entry) => /enable\\s+row\\s+level\\s+security|create\\s+policy|alter\\s+table[\\s\\S]{0,200}enable\\s+row\\s+level/i.test(entry.content));\r\n return file ? [`rls: ${file.path}`] : [];\r\n}\r\n\r\nfunction hasGeneratedTypes(files: ScannableFile[], pathBlob: string): boolean {\r\n return /database\\.types\\.[jt]s\\b|supabase.*types\\.[jt]s\\b|types\\/database\\.[jt]s\\b/i.test(pathBlob) ||\r\n files.some((file) => /export\\s+type\\s+database\\b|export\\s+interface\\s+database\\b/i.test(file.content));\r\n}\r\n\r\nfunction generatedTypeEvidence(files: ScannableFile[], pathBlob: string): string[] {\r\n const path = pathBlob.split(/\\r?\\n/).find((entry) =>\r\n /database\\.types\\.[jt]s\\b|supabase.*types\\.[jt]s\\b|types\\/database\\.[jt]s\\b/i.test(entry)\r\n );\r\n if (path) {\r\n return [`types: ${path}`];\r\n }\r\n const file = files.find((entry) => /export\\s+type\\s+database\\b|export\\s+interface\\s+database\\b/i.test(entry.content));\r\n return file ? [`types: ${file.path}`] : [];\r\n}\r\n\r\nfunction serviceRoleSafetyItem(files: ScannableFile[]): StackWiringItem {\r\n const exposed = files.filter((file) =>\r\n isClientExecutedPath(file.normalizedPath) &&\r\n /\\bsupabase_service_role_key\\b|next_public_supabase_service_role|vite_supabase_service_role/i.test(file.content)\r\n );\r\n return {\r\n id: 'service-role-not-exposed',\r\n label: 'Service role key not exposed to frontend',\r\n status: exposed.length > 0 ? 'missing' : 'passed',\r\n evidence: exposed.slice(0, 4).map((file) => `unsafe reference: ${file.path}`),\r\n promptHint: 'Move service-role usage to server-only code and use public anon keys in frontend clients.'\r\n };\r\n}\r\n\r\nfunction isClientExecutedPath(path: string): boolean {\r\n return /\\.(tsx|jsx)$/.test(path) ||\r\n /(^|\\/)(components|pages|app|client|frontend|web)\\//.test(path) ||\r\n /\\.client\\.[jt]sx?$/.test(path);\r\n}\r\n\r\nfunction formatEvidence(evidence: string[]): string {\r\n return evidence.length > 0 ? ` (${evidence.slice(0, 3).join('; ')})` : '';\r\n}\r\n", "import { analyzeSupabaseDatabaseWiring } from './supabaseWiring';\r\nimport type {\r\n ScanResult,\r\n ScannedFile,\r\n StackWiringItem,\r\n StackWiringKey,\r\n StackWiringProviderSummary,\r\n StackWiringSummary\r\n} from './types';\r\n\r\ntype VisibleFile = {\r\n path: string;\r\n normalizedPath: string;\r\n content: string;\r\n lowerContent: string;\r\n};\r\n\r\ntype StackContext = {\r\n scan: ScanResult;\r\n files: VisibleFile[];\r\n deps: string[];\r\n pathBlob: string;\r\n contentBlob: string;\r\n};\r\n\r\nexport function analyzeStackWiring(scan: ScanResult): StackWiringSummary {\r\n const ctx = buildContext(scan);\r\n const supabaseDatabase = analyzeSupabaseDatabaseWiring(scan);\r\n const items: StackWiringProviderSummary[] = [\r\n analyzeFigmaAppFlow(ctx),\r\n analyzeStorybookAppFlow(ctx),\r\n analyzeProductSpecAppFlow(ctx),\r\n analyzeRouteMapAppFlow(ctx),\r\n analyzeReactFrontend(ctx),\r\n analyzeVueFrontend(ctx),\r\n analyzeSvelteFrontend(ctx),\r\n analyzeAngularFrontend(ctx),\r\n analyzeNodeBackend(ctx),\r\n analyzePythonBackend(ctx),\r\n analyzeRailsBackend(ctx),\r\n analyzeGoBackend(ctx),\r\n analyzeRateLimitSecurity(ctx),\r\n analyzeBotProtectionSecurity(ctx),\r\n analyzeSecretsHygiene(ctx),\r\n analyzeClerkAuth(ctx),\r\n analyzeAuthJsAuth(ctx),\r\n analyzeSupabaseAuth(ctx),\r\n supabaseDatabase,\r\n analyzeNeonDatabase(ctx),\r\n analyzeTursoDatabase(ctx),\r\n analyzeMongoDatabase(ctx),\r\n analyzePlanetScaleDatabase(ctx),\r\n analyzeStripePayments(ctx),\r\n analyzePaddlePayments(ctx),\r\n analyzeVercelDeployment(ctx),\r\n analyzeNetlifyDeployment(ctx),\r\n analyzeAwsDeployment(ctx),\r\n analyzeSupabaseLanding(ctx),\r\n analyzePostHogMonitoring(ctx),\r\n analyzeSentryMonitoring(ctx),\r\n analyzeLogRocketMonitoring(ctx),\r\n analyzeVitestTesting(ctx),\r\n analyzePlaywrightTesting(ctx),\r\n analyzeSentryErrorHandling(ctx),\r\n analyzePostHogErrorHandling(ctx)\r\n ];\r\n const byKey = items.reduce<Partial<Record<StackWiringKey, StackWiringProviderSummary>>>((acc, summary) => {\r\n acc[summary.key] = summary;\r\n return acc;\r\n }, {});\r\n\r\n return {\r\n items,\r\n byKey,\r\n supabaseDatabase\r\n };\r\n}\r\n\r\nexport function buildStackWiringPrompt(summary: StackWiringProviderSummary): string {\r\n const passed = summary.items.filter((entry) => entry.status === 'passed');\r\n const missing = summary.items.filter((entry) => entry.status === 'missing');\r\n const manual = summary.items.filter((entry) => entry.status === 'manual');\r\n const passedLines = passed.length > 0\r\n ? passed.map((entry) => `- ${entry.label}${formatEvidence(entry.evidence)}`).join('\\n')\r\n : `- No ${summary.promptSubject} checks passed yet.`;\r\n const missingLines = missing.length > 0\r\n ? missing.map((entry) => `- ${entry.label}: ${entry.promptHint}`).join('\\n')\r\n : `- No missing ${summary.promptSubject} checks were found by VibeRaven.`;\r\n const manualLines = manual.length > 0\r\n ? manual.map((entry) => `- ${entry.label}: ${entry.promptHint}`).join('\\n')\r\n : '- No manual dashboard checks were listed.';\r\n\r\n return [\r\n `Wire ${summary.promptSubject} for this app safely.`,\r\n '',\r\n `Current ${summary.promptSubject} readiness: ${summary.passedCount}/${summary.totalCount} repo checks passed (${summary.readinessPercent}%).`,\r\n '',\r\n 'Repo evidence already found:',\r\n passedLines,\r\n '',\r\n `Missing ${summary.promptSubject} checks:`,\r\n missingLines,\r\n '',\r\n 'Manual checks that repo evidence cannot prove:',\r\n manualLines,\r\n '',\r\n 'First inspect the existing package.json files, env examples, framework routes, provider helpers, and server/client boundaries before editing.',\r\n '',\r\n 'Implement:',\r\n `1. Close only the missing ${summary.promptSubject} checks listed above.`,\r\n '2. Follow the existing file structure and naming patterns.',\r\n '3. Keep provider secrets in server-only code and documented env templates.',\r\n '4. Keep external dashboard work explicit instead of claiming it from repo evidence.',\r\n '',\r\n 'Constraints:',\r\n '- Do not rewrite unrelated auth, payments, UI, billing, deployment, or analytics code.',\r\n '- Do not expose secret keys to browser code, public env variables, or client-executed files.',\r\n '- Do not claim external provider dashboard setup is complete from repo evidence alone.',\r\n '',\r\n 'Verification:',\r\n '- Run the relevant TypeScript/build/test command for this repo.',\r\n '- Confirm VibeRaven can rescan and move the missing checks to passed where repo evidence exists.',\r\n '- Summarize what changed and what still requires manual provider dashboard verification.'\r\n ].join('\\n');\r\n}\r\n\r\nexport function buildStackWiringContext(summary: StackWiringSummary): string {\r\n const lines = ['## STACK READINESS'];\r\n for (const stack of summary.items) {\r\n lines.push(`${stack.key}: ${stack.passedCount}/${stack.totalCount} repo checks passed (${stack.readinessPercent}%).`);\r\n for (const entry of stack.items) {\r\n const evidence = entry.evidence.length > 0 ? ` (${entry.evidence.slice(0, 3).join('; ')})` : '';\r\n lines.push(`${stack.key} ${entry.status}: ${entry.label}${evidence}`);\r\n }\r\n }\r\n return lines.join('\\n');\r\n}\r\n\r\nfunction analyzeFigmaAppFlow(ctx: StackContext): StackWiringProviderSummary {\r\n return summarize({\r\n key: 'figma-app-flow',\r\n provider: 'figma',\r\n providerLabel: 'Figma',\r\n area: 'appFlow',\r\n areaLabel: 'App Flow / UX',\r\n promptSubject: 'Figma app flow',\r\n items: [\r\n item('flow-doc-found', 'Flow or design doc found', /figma|wireframe|user flow|journey|prototype|screen map/i.test(ctx.contentBlob + '\\n' + ctx.pathBlob), fileEvidence(ctx, /figma|wireframe|user flow|journey|prototype|screen map/i), 'Add or link a simple screen flow, user journey, or Figma handoff note.'),\r\n item('onboarding-states-found', 'Onboarding and empty states documented', /onboarding|empty state|first run|activation|welcome/i.test(ctx.contentBlob + '\\n' + ctx.pathBlob), fileEvidence(ctx, /onboarding|empty state|first run|activation|welcome/i), 'Document the first-run, empty, loading, and error states for the main user journey.'),\r\n item('primary-cta-found', 'Primary user action is visible', /primary cta|call to action|cta|start|continue|create|connect/i.test(ctx.contentBlob), fileEvidence(ctx, /primary cta|call to action|cta|start|continue|create|connect/i), 'Make the main action obvious on the key product screens.'),\r\n manualItem('figma-source-checked', 'Current Figma or flow source checked', 'Confirm the latest Figma/design source still matches the implemented product flow.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzeStorybookAppFlow(ctx: StackContext): StackWiringProviderSummary {\r\n return summarize({\r\n key: 'storybook-app-flow',\r\n provider: 'storybook',\r\n providerLabel: 'Storybook',\r\n area: 'appFlow',\r\n areaLabel: 'App Flow / UX',\r\n promptSubject: 'Storybook app flow',\r\n items: [\r\n item('storybook-package-found', 'Storybook package installed', hasPackage(ctx, [/^storybook$/, /^@storybook\\//]) || /\\.storybook\\/|\\.stories\\.[jt]sx?\\b/i.test(ctx.pathBlob), packageEvidence(ctx, [/^storybook$/, /^@storybook\\//]).concat(pathEvidence(ctx, /\\.storybook\\/|\\.stories\\.[jt]sx?\\b/i)), 'Install or confirm Storybook for visible component state coverage.'),\r\n item('stories-found', 'Component stories found', /\\.stories\\.[jt]sx?\\b|\\.mdx\\b/i.test(ctx.pathBlob), pathEvidence(ctx, /\\.stories\\.[jt]sx?\\b|\\.mdx\\b/i), 'Add stories for the primary product components.'),\r\n item('state-variants-found', 'Loading, empty, or error variants found', /loading|empty|error|disabled|success|variant/i.test(ctx.contentBlob), fileEvidence(ctx, /loading|empty|error|disabled|success|variant/i), 'Cover loading, empty, error, disabled, and success variants in stories.'),\r\n manualItem('storybook-reviewed', 'Current Storybook states reviewed', 'Open Storybook and confirm the primary user journey states still match the product.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzeProductSpecAppFlow(ctx: StackContext): StackWiringProviderSummary {\r\n return summarize({\r\n key: 'product-spec-app-flow',\r\n provider: 'product-spec',\r\n providerLabel: 'Product Spec',\r\n area: 'appFlow',\r\n areaLabel: 'App Flow / UX',\r\n promptSubject: 'product spec app flow',\r\n items: [\r\n item('spec-doc-found', 'Product spec or PRD found', /prd|product requirements|requirements|product spec|specification/i.test(ctx.contentBlob + '\\n' + ctx.pathBlob), fileEvidence(ctx, /prd|product requirements|requirements|product spec|specification/i).concat(pathEvidence(ctx, /prd|requirements|spec/i)), 'Add a short product spec or PRD for the main workflow.'),\r\n item('acceptance-criteria-found', 'Acceptance criteria or user stories found', /acceptance criteria|user stor(y|ies)|jobs to be done|given\\s+.*when\\s+.*then/i.test(ctx.contentBlob), fileEvidence(ctx, /acceptance criteria|user stor(y|ies)|jobs to be done|given\\s+.*when\\s+.*then/i), 'Document acceptance criteria or user stories for the main flow.'),\r\n item('success-metric-found', 'Success metric or activation goal found', /success metric|activation|north star|conversion|retention|time to value/i.test(ctx.contentBlob), fileEvidence(ctx, /success metric|activation|north star|conversion|retention|time to value/i), 'Define the activation or success metric for this workflow.'),\r\n manualItem('latest-product-intent-checked', 'Latest product intent checked', 'Confirm the spec still matches the current product direction and user promise.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzeRouteMapAppFlow(ctx: StackContext): StackWiringProviderSummary {\r\n return summarize({\r\n key: 'route-map-app-flow',\r\n provider: 'route-map',\r\n providerLabel: 'Route Map',\r\n area: 'appFlow',\r\n areaLabel: 'App Flow / UX',\r\n promptSubject: 'route map app flow',\r\n items: [\r\n item('routes-found', 'App routes found', /(^|\\n|\\/)(app|pages|routes)\\//i.test(ctx.pathBlob) || /router|route map|sitemap/i.test(ctx.contentBlob), pathEvidence(ctx, /(^|\\/)(app|pages|routes)\\//i).concat(fileEvidence(ctx, /router|route map|sitemap/i)), 'Map the key routes or screens in the repo.'),\r\n item('navigation-documented', 'Navigation path documented', /navigation|nav|breadcrumb|route map|screen map|journey/i.test(ctx.contentBlob), fileEvidence(ctx, /navigation|nav|breadcrumb|route map|screen map|journey/i), 'Document how users move through the primary screens.'),\r\n item('protected-or-edge-routes-found', 'Protected or edge routes noted', /protected|auth required|404|not-found|error route|redirect/i.test(ctx.contentBlob + '\\n' + ctx.pathBlob), fileEvidence(ctx, /protected|auth required|404|not-found|error route|redirect/i), 'Mark protected, redirect, 404, and error routes explicitly.'),\r\n manualItem('core-journey-clicked', 'Core journey clicked manually', 'Click through the core route path in the running app and verify the map is current.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzeReactFrontend(ctx: StackContext): StackWiringProviderSummary {\r\n return summarize({\r\n key: 'react-frontend',\r\n provider: 'react',\r\n providerLabel: 'React',\r\n area: 'frontend',\r\n areaLabel: 'Frontend',\r\n promptSubject: 'React frontend',\r\n items: [\r\n item('package-installed', 'React package installed', hasPackage(ctx, [/^react$/, /^next$/, /^vite$/]) || Boolean(ctx.scan.stackSignals.hasNextJs || ctx.scan.stackSignals.hasVite), packageEvidence(ctx, [/^react$/, /^next$/, /^vite$/]), 'Install or confirm the React framework package used by this app.'),\r\n item('component-structure-found', 'Component structure found', /(^|\\n|\\/)(src\\/)?(components|app|pages)\\//i.test(ctx.pathBlob), pathEvidence(ctx, /(^|\\/)(src\\/)?(components|app|pages)\\//i), 'Keep UI components in a predictable app/pages/components structure.'),\r\n item('loading-state-found', 'Loading state found', Boolean(ctx.scan.stackSignals.hasLoadingStates) || /loading\\.tsx|skeleton|spinner|aria-busy|isloading/i.test(ctx.contentBlob + '\\n' + ctx.pathBlob), fileEvidence(ctx, /loading\\.tsx|skeleton|spinner|aria-busy|isloading/i), 'Add loading states for async product views.'),\r\n item('error-state-found', 'Error boundary or empty state found', Boolean(ctx.scan.stackSignals.hasErrorBoundary) || /errorboundary|global-error|empty state|not-found\\.tsx/i.test(ctx.contentBlob + '\\n' + ctx.pathBlob), fileEvidence(ctx, /errorboundary|global-error|empty state|not-found\\.tsx/i), 'Add error and empty states for the primary product workflow.'),\r\n manualItem('responsive-ui-checked', 'Responsive UI checked manually', 'Open the main screens at mobile and desktop widths and confirm there is no overflow or overlapping text.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzeVueFrontend(ctx: StackContext): StackWiringProviderSummary {\r\n return summarize({\r\n key: 'vue-frontend',\r\n provider: 'vue',\r\n providerLabel: 'Vue',\r\n area: 'frontend',\r\n areaLabel: 'Frontend',\r\n promptSubject: 'Vue frontend',\r\n items: [\r\n item('package-installed', 'Vue package installed', hasPackage(ctx, [/^vue$/, /^nuxt$/, /^@vitejs\\/plugin-vue$/]), packageEvidence(ctx, [/^vue$/, /^nuxt$/, /^@vitejs\\/plugin-vue$/]), 'Install or confirm Vue, Nuxt, or the Vue build plugin used by this app.'),\r\n item('component-structure-found', 'Vue component structure found', /\\.vue\\b|(^|\\n|\\/)(src\\/)?(components|pages|layouts)\\//i.test(ctx.pathBlob), pathEvidence(ctx, /\\.vue\\b|(^|\\/)(src\\/)?(components|pages|layouts)\\//i), 'Keep Vue components, pages, and layouts in predictable folders.'),\r\n item('routing-or-layout-found', 'Vue routing or layout found', /vue-router|routerview|router-view|<router-view|(^|\\n|\\/)pages\\//i.test(ctx.contentBlob + '\\n' + ctx.pathBlob), fileEvidence(ctx, /vue-router|routerview|router-view|<router-view/i).concat(pathEvidence(ctx, /(^|\\/)pages\\//i)), 'Add or confirm Vue Router, Nuxt pages, or layout routing for the main product screens.'),\r\n item('loading-or-error-state-found', 'Loading or error state found', /loading|suspense|error|empty state|isloading/i.test(ctx.contentBlob), fileEvidence(ctx, /loading|suspense|error|empty state|isloading/i), 'Add loading, empty, and error states for async Vue screens.'),\r\n manualItem('responsive-ui-checked', 'Responsive UI checked manually', 'Open the main Vue screens at mobile and desktop widths and confirm there is no overflow or overlapping text.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzeSvelteFrontend(ctx: StackContext): StackWiringProviderSummary {\r\n return summarize({\r\n key: 'svelte-frontend',\r\n provider: 'svelte',\r\n providerLabel: 'Svelte',\r\n area: 'frontend',\r\n areaLabel: 'Frontend',\r\n promptSubject: 'Svelte frontend',\r\n items: [\r\n item('package-installed', 'Svelte package installed', hasPackage(ctx, [/^svelte$/, /^@sveltejs\\/kit$/]), packageEvidence(ctx, [/^svelte$/, /^@sveltejs\\/kit$/]), 'Install or confirm Svelte or SvelteKit for this app.'),\r\n item('component-structure-found', 'Svelte component or route structure found', /\\.svelte\\b|(^|\\n|\\/)src\\/routes\\//i.test(ctx.pathBlob), pathEvidence(ctx, /\\.svelte\\b|(^|\\/)src\\/routes\\//i), 'Keep Svelte components and routes in predictable folders.'),\r\n item('load-or-form-found', 'Svelte load or form handling found', /\\bload\\s*=|export\\s+(async\\s+)?function\\s+load|actions\\s*=|use:enhance/i.test(ctx.contentBlob), fileEvidence(ctx, /\\bload\\s*=|export\\s+(async\\s+)?function\\s+load|actions\\s*=|use:enhance/i), 'Use SvelteKit load functions or actions for route data and form flows.'),\r\n item('loading-or-error-state-found', 'Loading or error state found', /loading|error|empty state|\\+error\\.svelte/i.test(ctx.contentBlob + '\\n' + ctx.pathBlob), fileEvidence(ctx, /loading|error|empty state|\\+error\\.svelte/i), 'Add loading, empty, and error states for async Svelte screens.'),\r\n manualItem('responsive-ui-checked', 'Responsive UI checked manually', 'Open the main Svelte screens at mobile and desktop widths and confirm there is no overflow or overlapping text.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzeAngularFrontend(ctx: StackContext): StackWiringProviderSummary {\r\n return summarize({\r\n key: 'angular-frontend',\r\n provider: 'angular',\r\n providerLabel: 'Angular',\r\n area: 'frontend',\r\n areaLabel: 'Frontend',\r\n promptSubject: 'Angular frontend',\r\n items: [\r\n item('package-installed', 'Angular package installed', hasPackage(ctx, [/^@angular\\/core$/, /^@angular\\/router$/, /^@angular\\/cli$/]), packageEvidence(ctx, [/^@angular\\/core$/, /^@angular\\/router$/, /^@angular\\/cli$/]), 'Install or confirm Angular framework packages for this app.'),\r\n item('component-structure-found', 'Angular component structure found', /\\.component\\.ts\\b|angular\\.json|(^|\\n|\\/)src\\/app\\//i.test(ctx.pathBlob), pathEvidence(ctx, /\\.component\\.ts\\b|angular\\.json|(^|\\/)src\\/app\\//i), 'Keep Angular components and app modules or standalone routes in predictable folders.'),\r\n item('routing-found', 'Angular routing found', /routermodule|providerouter|router-outlet|routes\\s*:/i.test(ctx.contentBlob), fileEvidence(ctx, /routermodule|providerouter|router-outlet|routes\\s*:/i), 'Add or confirm Angular Router for the primary product screens.'),\r\n item('loading-or-error-state-found', 'Loading or error state found', /loading|isloading|error|empty state|catcherror/i.test(ctx.contentBlob), fileEvidence(ctx, /loading|isloading|error|empty state|catcherror/i), 'Add loading, empty, and error states for async Angular screens.'),\r\n manualItem('responsive-ui-checked', 'Responsive UI checked manually', 'Open the main Angular screens at mobile and desktop widths and confirm there is no overflow or overlapping text.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzeNodeBackend(ctx: StackContext): StackWiringProviderSummary {\r\n return summarize({\r\n key: 'node-backend',\r\n provider: 'node',\r\n providerLabel: 'Node.js',\r\n area: 'backend',\r\n areaLabel: 'Backend / API',\r\n promptSubject: 'Node.js backend',\r\n items: [\r\n item('server-runtime-found', 'Server runtime or API framework found', hasPackage(ctx, [/^express$/, /^fastify$/, /^hono$/, /^next$/, /^@nestjs\\//]) || /api\\/|route\\.[jt]s|server\\.[jt]s/i.test(ctx.pathBlob), packageEvidence(ctx, [/^express$/, /^fastify$/, /^hono$/, /^next$/, /^@nestjs\\//]).concat(pathEvidence(ctx, /api\\/|route\\.[jt]s|server\\.[jt]s/i)), 'Add a clear server/API runtime or route structure.'),\r\n item('api-routes-found', 'API routes found', /api\\/|route\\.[jt]s|routes?\\//i.test(ctx.pathBlob), pathEvidence(ctx, /api\\/|route\\.[jt]s|routes?\\//i), 'Create server routes for backend operations instead of pushing secrets into frontend code.'),\r\n item('request-validation-found', 'Request validation found', hasPackage(ctx, [/^zod$/, /^joi$/, /^yup$/, /^valibot$/]) || /z\\.object|safeparse|request validation|validate\\s*\\(/i.test(ctx.contentBlob), packageEvidence(ctx, [/^zod$/, /^joi$/, /^yup$/, /^valibot$/]).concat(fileEvidence(ctx, /z\\.object|safeparse|request validation|validate\\s*\\(/i)), 'Validate request bodies and parameters before processing backend operations.'),\r\n item('backend-error-handling-found', 'Backend error handling found', /try\\s*{|catch\\s*\\(|next\\(error\\)|return\\s+new\\s+response\\([^)]*500|status\\s*:\\s*500/i.test(ctx.contentBlob), fileEvidence(ctx, /try\\s*{|catch\\s*\\(|next\\(error\\)|status\\s*:\\s*500/i), 'Add consistent backend error handling for API routes.'),\r\n manualItem('production-runtime-checked', 'Production runtime limits checked', 'Confirm serverless/runtime limits, body size, timeout, and region choices for production.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzePythonBackend(ctx: StackContext): StackWiringProviderSummary {\r\n return summarize({\r\n key: 'python-backend',\r\n provider: 'python',\r\n providerLabel: 'Python / FastAPI',\r\n area: 'backend',\r\n areaLabel: 'Backend / API',\r\n promptSubject: 'Python backend',\r\n items: [\r\n item('server-runtime-found', 'Python API framework found', hasPackage(ctx, [/^fastapi$/, /^flask$/, /^django$/, /^pydantic$/]) || /fastapi|flask|django|pydantic/i.test(ctx.contentBlob), packageEvidence(ctx, [/^fastapi$/, /^flask$/, /^django$/, /^pydantic$/]).concat(fileEvidence(ctx, /fastapi|flask|django|pydantic/i)), 'Add or confirm FastAPI, Flask, Django, or the Python API framework used by this app.'),\r\n item('api-entry-found', 'Python API entrypoint found', /(^|\\n|\\/)(api\\/)?(main|app)\\.py\\b|(^|\\n|\\/)manage\\.py\\b/i.test(ctx.pathBlob), pathEvidence(ctx, /(^|\\/)(api\\/)?(main|app)\\.py\\b|(^|\\/)manage\\.py\\b/i), 'Keep a clear Python API entrypoint for production routes.'),\r\n item('request-validation-found', 'Request validation found', /basemodel|pydantic|serializer|marshmallow|request validation/i.test(ctx.contentBlob), fileEvidence(ctx, /basemodel|pydantic|serializer|marshmallow|request validation/i), 'Validate request bodies and parameters before processing backend operations.'),\r\n item('backend-error-handling-found', 'Backend error handling found', /exception_handler|try\\s*:|except\\s+|raise\\s+http|abort\\(|handler404|handler500/i.test(ctx.contentBlob), fileEvidence(ctx, /exception_handler|try\\s*:|except\\s+|raise\\s+http|abort\\(|handler404|handler500/i), 'Add consistent backend error handling for Python routes.'),\r\n manualItem('production-runtime-checked', 'Production runtime limits checked', 'Confirm server/runtime limits, worker count, timeout, and region choices for production.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzeRailsBackend(ctx: StackContext): StackWiringProviderSummary {\r\n return summarize({\r\n key: 'rails-backend',\r\n provider: 'rails',\r\n providerLabel: 'Rails',\r\n area: 'backend',\r\n areaLabel: 'Backend / API',\r\n promptSubject: 'Rails backend',\r\n items: [\r\n item('rails-runtime-found', 'Rails runtime found', hasPackage(ctx, [/^rails$/]) || /gem ['\"]rails['\"]|rails\\.application|actioncontroller/i.test(ctx.contentBlob + '\\n' + ctx.pathBlob), packageEvidence(ctx, [/^rails$/]).concat(fileEvidence(ctx, /gem ['\"]rails['\"]|rails\\.application|actioncontroller/i)), 'Add or confirm Rails is the backend runtime for this app.'),\r\n item('controllers-or-routes-found', 'Controllers or routes found', /app\\/controllers\\/|config\\/routes\\.rb/i.test(ctx.pathBlob) || /resources\\s+:|namespace\\s+:|ActionController/i.test(ctx.contentBlob), pathEvidence(ctx, /app\\/controllers\\/|config\\/routes\\.rb/i).concat(fileEvidence(ctx, /resources\\s+:|namespace\\s+:|ActionController/i)), 'Keep Rails controllers and routes visible in the repo.'),\r\n item('request-validation-found', 'Validation or strong params found', /validates\\s+:|params\\.require|permit\\(|ActiveModel::Serializer|dry-validation/i.test(ctx.contentBlob), fileEvidence(ctx, /validates\\s+:|params\\.require|permit\\(|ActiveModel::Serializer|dry-validation/i), 'Validate request bodies and model inputs before processing backend operations.'),\r\n item('backend-error-handling-found', 'Backend error handling found', /rescue_from|rescue\\s+|render\\s+json:.*status:|head\\s+:/i.test(ctx.contentBlob), fileEvidence(ctx, /rescue_from|rescue\\s+|render\\s+json:.*status:|head\\s+:/i), 'Add consistent Rails error handling for API routes.'),\r\n manualItem('production-runtime-checked', 'Production runtime limits checked', 'Confirm Puma/workers, job queues, database pool, timeout, and region choices for production.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzeGoBackend(ctx: StackContext): StackWiringProviderSummary {\r\n return summarize({\r\n key: 'go-backend',\r\n provider: 'go',\r\n providerLabel: 'Go',\r\n area: 'backend',\r\n areaLabel: 'Backend / API',\r\n promptSubject: 'Go backend',\r\n items: [\r\n item('go-runtime-found', 'Go API runtime found', /(^|\\n|\\/)go\\.mod\\b|gin-gonic|go-chi|gofiber|net\\/http/i.test(ctx.contentBlob + '\\n' + ctx.pathBlob), fileEvidence(ctx, /gin-gonic|go-chi|gofiber|net\\/http/i).concat(pathEvidence(ctx, /(^|\\/)go\\.mod\\b/i)), 'Add or confirm Go modules and the HTTP framework used by this app.'),\r\n item('handlers-or-routes-found', 'Handlers or routes found', /\\.go\\b/i.test(ctx.pathBlob) && /\\b(GET|POST|PUT|DELETE)\\s*\\(|http\\.Handle|HandleFunc|router\\./i.test(ctx.contentBlob), fileEvidence(ctx, /\\b(GET|POST|PUT|DELETE)\\s*\\(|http\\.Handle|HandleFunc|router\\./i), 'Keep Go handlers and route registration visible in the repo.'),\r\n item('request-validation-found', 'Request validation found', /validator|binding:|bindjson|shouldbind|json\\.newdecoder|validate\\./i.test(ctx.contentBlob), fileEvidence(ctx, /validator|binding:|bindjson|shouldbind|json\\.newdecoder|validate\\./i), 'Validate request bodies and parameters before processing backend operations.'),\r\n item('backend-error-handling-found', 'Backend error handling found', /if\\s+err\\s*!=\\s*nil|http\\.Error|statusinternalservererror|c\\.json\\([^)]*500/i.test(ctx.contentBlob), fileEvidence(ctx, /if\\s+err\\s*!=\\s*nil|http\\.Error|statusinternalservererror|c\\.json\\([^)]*500/i), 'Add consistent Go error handling for API routes.'),\r\n manualItem('production-runtime-checked', 'Production runtime limits checked', 'Confirm binary build, health checks, timeout, concurrency, and region choices for production.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzeClerkAuth(ctx: StackContext): StackWiringProviderSummary {\r\n return summarize({\r\n key: 'clerk-auth',\r\n provider: 'clerk',\r\n providerLabel: 'Clerk',\r\n area: 'auth',\r\n areaLabel: 'Auth',\r\n promptSubject: 'Clerk auth',\r\n items: [\r\n item('package-installed', 'Clerk package installed', hasPackage(ctx, [/^@clerk\\//]), packageEvidence(ctx, [/^@clerk\\//]), 'Install the Clerk package that matches this app framework.'),\r\n item('env-names-documented', 'Clerk env names documented', hasAllContent(ctx, [/next_public_clerk_publishable_key/i, /clerk_secret_key/i]), envEvidence(ctx, [/next_public_clerk_publishable_key/i, /clerk_secret_key/i]), 'Document NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY and CLERK_SECRET_KEY in an env example or setup docs.'),\r\n item('route-protection-found', 'Auth middleware or route protection found', /(^|\\n|\\/)middleware\\.[jt]sx?\\b/i.test(ctx.pathBlob) || /clerkmiddleware|authmiddleware|createRouteMatcher/i.test(ctx.contentBlob), fileEvidence(ctx, /middleware\\.[jt]sx?$|clerkmiddleware|authmiddleware|createRouteMatcher/i), 'Add Clerk middleware or route guards around authenticated app routes.'),\r\n item('provider-mounted', 'Clerk provider mounted', /clerkprovider/i.test(ctx.contentBlob), fileEvidence(ctx, /clerkprovider/i), 'Mount ClerkProvider in the app root or framework-specific provider layer.'),\r\n item('sign-in-flow-found', 'Sign-in or sign-up flow found', /sign-?in|sign-?up/i.test(ctx.pathBlob) || /<\\s*sign(in|up)\\b|sign(in|up)button/i.test(ctx.contentBlob), fileEvidence(ctx, /sign-?in|sign-?up|<\\s*sign(in|up)\\b|sign(in|up)button/i), 'Add a visible sign-in/sign-up route or component for users.'),\r\n item('server-auth-usage-found', 'Server auth usage found', /\\bauth\\s*\\(|currentuser\\s*\\(|getauth\\s*\\(/i.test(ctx.contentBlob), fileEvidence(ctx, /\\bauth\\s*\\(|currentuser\\s*\\(|getauth\\s*\\(/i), 'Use Clerk server auth in protected data routes or server components.'),\r\n secretSafetyItem(ctx, 'secret-not-exposed', 'Clerk secret key not exposed to frontend', /clerk_secret_key|sk_live_/i, 'Move Clerk secret key usage to server-only files and keep frontend code on publishable keys.'),\r\n manualItem('production-dashboard-checked', 'Production Clerk app and domains checked', 'Confirm production domains, OAuth redirects, allowed origins, and social provider settings in Clerk Dashboard.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzeAuthJsAuth(ctx: StackContext): StackWiringProviderSummary {\r\n return summarize({\r\n key: 'authjs-auth',\r\n provider: 'authjs',\r\n providerLabel: 'Auth.js',\r\n area: 'auth',\r\n areaLabel: 'Auth',\r\n promptSubject: 'Auth.js auth',\r\n items: [\r\n item('package-installed', 'Auth.js package installed', hasPackage(ctx, [/^next-auth$/, /^@auth\\//]), packageEvidence(ctx, [/^next-auth$/, /^@auth\\//]), 'Install next-auth or the correct @auth package for this framework.'),\r\n item('env-names-documented', 'Auth secret env documented', /auth_secret|nextauth_secret/i.test(ctx.contentBlob), envEvidence(ctx, [/auth_secret/i, /nextauth_secret/i, /nextauth_url/i]), 'Document AUTH_SECRET or NEXTAUTH_SECRET in env examples or setup docs.'),\r\n item('auth-config-found', 'Auth config found', /(^|\\n|\\/)auth\\.[jt]s\\b|nextauth|NextAuth\\s*\\(/i.test(ctx.contentBlob + '\\n' + ctx.pathBlob), fileEvidence(ctx, /auth\\.[jt]s$|nextauth|NextAuth\\s*\\(/i), 'Add a central Auth.js config with providers and callbacks.'),\r\n item('route-handler-found', 'Auth route handler found', /api\\/auth|handlers\\s*:\\s*{|GET|POST/i.test(ctx.pathBlob + '\\n' + ctx.contentBlob), pathEvidence(ctx, /api\\/auth/i).concat(fileEvidence(ctx, /handlers\\s*:\\s*{|NextAuth\\s*\\(/i)), 'Expose the Auth.js route handler expected by this framework.'),\r\n item('session-usage-found', 'Session usage found', /\\bauth\\s*\\(|getserversession|usesession\\s*\\(/i.test(ctx.contentBlob), fileEvidence(ctx, /\\bauth\\s*\\(|getserversession|usesession\\s*\\(/i), 'Use server or client session checks around authenticated product routes.'),\r\n secretSafetyItem(ctx, 'secret-not-exposed', 'Auth secret not exposed to frontend', /auth_secret|nextauth_secret/i, 'Move Auth.js secrets to server-only env and never expose them through public env variables.'),\r\n manualItem('production-provider-checked', 'Production OAuth providers checked', 'Confirm OAuth app callback URLs, secrets, and production domain settings in each provider dashboard.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzeSupabaseAuth(ctx: StackContext): StackWiringProviderSummary {\r\n return summarize({\r\n key: 'supabase-auth',\r\n provider: 'supabase-auth',\r\n providerLabel: 'Supabase Auth',\r\n area: 'auth',\r\n areaLabel: 'Auth',\r\n promptSubject: 'Supabase Auth',\r\n items: [\r\n item('package-installed', 'Supabase auth package installed', hasPackage(ctx, [/@supabase\\//]), packageEvidence(ctx, [/@supabase\\//]), 'Install @supabase/supabase-js or @supabase/ssr for auth helpers.'),\r\n item('env-names-documented', 'Supabase auth env names documented', /supabase_url/i.test(ctx.contentBlob) && /supabase_anon_key/i.test(ctx.contentBlob), envEvidence(ctx, [/supabase_url/i, /supabase_anon_key/i]), 'Document SUPABASE_URL and SUPABASE_ANON_KEY style env names in examples or setup docs.'),\r\n item('auth-helper-found', 'Supabase auth helper found', /auth\\.getuser|auth\\.getsession|auth\\.signin|auth\\.signup|createServerClient|createBrowserClient/i.test(ctx.contentBlob), fileEvidence(ctx, /auth\\.getuser|auth\\.getsession|auth\\.signin|auth\\.signup|createServerClient|createBrowserClient/i), 'Use Supabase auth helpers for session reads and sign-in flows.'),\r\n item('protected-route-found', 'Protected route or server session check found', /auth\\.getuser|auth\\.getsession|middleware|protected/i.test(ctx.contentBlob + '\\n' + ctx.pathBlob), fileEvidence(ctx, /auth\\.getuser|auth\\.getsession|middleware|protected/i), 'Protect signed-in routes with a server session check or middleware.'),\r\n secretSafetyItem(ctx, 'service-role-not-exposed', 'Service role key not exposed to frontend', /supabase_service_role_key|next_public_supabase_service_role|vite_supabase_service_role/i, 'Keep service-role keys in server-only code and use anon keys in frontend clients.'),\r\n manualItem('production-auth-dashboard-checked', 'Production Supabase Auth settings checked', 'Confirm site URL, redirect URLs, email provider, OAuth providers, and auth policies in Supabase Dashboard.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzeStripePayments(ctx: StackContext): StackWiringProviderSummary {\r\n return summarize({\r\n key: 'stripe-payments',\r\n provider: 'stripe',\r\n providerLabel: 'Stripe',\r\n area: 'payments',\r\n areaLabel: 'Payments',\r\n promptSubject: 'Stripe payments',\r\n items: [\r\n item('package-installed', 'Stripe package installed', hasPackage(ctx, [/^stripe$/, /^@stripe\\//]), packageEvidence(ctx, [/^stripe$/, /^@stripe\\//]), 'Install Stripe server/client packages that match this app framework.'),\r\n item('env-names-documented', 'Stripe env names documented', hasAllContent(ctx, [/stripe_secret_key/i, /stripe_webhook_secret/i]), envEvidence(ctx, [/stripe_secret_key/i, /stripe_webhook_secret/i, /next_public_stripe_publishable_key/i]), 'Document STRIPE_SECRET_KEY, STRIPE_WEBHOOK_SECRET, and publishable key names in env examples or setup docs.'),\r\n item('checkout-session-found', 'Checkout session creation found', /checkout\\.sessions\\.create|redirecttocheckout/i.test(ctx.contentBlob), fileEvidence(ctx, /checkout\\.sessions\\.create|redirecttocheckout/i), 'Create a server-side Stripe Checkout session path for paid plans.'),\r\n item('webhook-route-found', 'Stripe webhook route found', /stripe.*webhook|webhook.*stripe/i.test(ctx.pathBlob), pathEvidence(ctx, /stripe.*webhook|webhook.*stripe/i), 'Add a Stripe webhook route for subscription and payment lifecycle events.'),\r\n item('webhook-signature-found', 'Webhook signature verification found', /webhooks\\.constructevent/i.test(ctx.contentBlob), fileEvidence(ctx, /webhooks\\.constructevent/i), 'Verify Stripe webhook signatures with STRIPE_WEBHOOK_SECRET before processing events.'),\r\n item('billing-management-found', 'Subscription or customer portal found', /billingportal\\.sessions\\.create|subscriptions\\.create|mode\\s*:\\s*['\"]subscription['\"]/i.test(ctx.contentBlob), fileEvidence(ctx, /billingportal\\.sessions\\.create|subscriptions\\.create|mode\\s*:\\s*['\"]subscription['\"]/i), 'Add subscription creation or customer portal handling for paid users.'),\r\n secretSafetyItem(ctx, 'secret-not-exposed', 'Stripe secret key not exposed to frontend', /stripe_secret_key|sk_live_|sk_test_/i, 'Move Stripe secret-key usage to server-only routes and use publishable keys in frontend code.'),\r\n manualItem('production-dashboard-checked', 'Production Stripe products and webhooks checked', 'Confirm live-mode products, prices, webhook endpoint URL, and event list in Stripe Dashboard.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzePaddlePayments(ctx: StackContext): StackWiringProviderSummary {\r\n return summarize({\r\n key: 'paddle-payments',\r\n provider: 'paddle',\r\n providerLabel: 'Paddle',\r\n area: 'payments',\r\n areaLabel: 'Payments',\r\n promptSubject: 'Paddle payments',\r\n items: [\r\n item('package-installed', 'Paddle package installed', hasPackage(ctx, [/@paddle\\//]), packageEvidence(ctx, [/@paddle\\//]), 'Install Paddle client/server SDK packages that match this app framework.'),\r\n item('env-names-documented', 'Paddle env names documented', /paddle_api_key|paddle_webhook_secret|next_public_paddle/i.test(ctx.contentBlob), envEvidence(ctx, [/paddle_api_key/i, /paddle_webhook_secret/i, /next_public_paddle_client_token/i]), 'Document Paddle API key, webhook secret, and public client token env names.'),\r\n item('checkout-found', 'Paddle checkout flow found', /paddle.*checkout|checkout.*paddle|paddle\\.checkout|openCheckout/i.test(ctx.contentBlob + '\\n' + ctx.pathBlob), fileEvidence(ctx, /paddle.*checkout|checkout.*paddle|paddle\\.checkout|openCheckout/i), 'Add a Paddle checkout flow for paid plans.'),\r\n item('webhook-route-found', 'Paddle webhook route found', /paddle.*webhook|webhook.*paddle/i.test(ctx.pathBlob), pathEvidence(ctx, /paddle.*webhook|webhook.*paddle/i), 'Add a Paddle webhook route for subscription lifecycle events.'),\r\n item('webhook-signature-found', 'Paddle webhook verification found', /verify.*paddle|paddle.*signature|webhook.*signature/i.test(ctx.contentBlob), fileEvidence(ctx, /verify.*paddle|paddle.*signature|webhook.*signature/i), 'Verify Paddle webhook signatures before processing events.'),\r\n secretSafetyItem(ctx, 'secret-not-exposed', 'Paddle secret not exposed to frontend', /paddle_api_key|paddle_webhook_secret/i, 'Move Paddle API keys and webhook secrets to server-only code.'),\r\n manualItem('production-dashboard-checked', 'Production Paddle products and webhooks checked', 'Confirm live products, prices, tax settings, webhook URL, and event list in Paddle Dashboard.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzeNeonDatabase(ctx: StackContext): StackWiringProviderSummary {\r\n return databaseSummary(ctx, {\r\n key: 'neon-database',\r\n provider: 'neon',\r\n providerLabel: 'Neon',\r\n promptSubject: 'Neon database',\r\n packagePatterns: [/@neondatabase\\//],\r\n envPatterns: [/neon_database_url/i, /database_url/i],\r\n usagePatterns: [/@neondatabase\\/serverless/i, /\\bneon\\s*\\(/i, /\\bsql`/i],\r\n manualLabel: 'Production Neon branch and pooling checked',\r\n manualHint: 'Confirm production branch, pooled connection string, backups, and region in Neon.'\r\n });\r\n}\r\n\r\nfunction analyzeTursoDatabase(ctx: StackContext): StackWiringProviderSummary {\r\n return databaseSummary(ctx, {\r\n key: 'turso-database',\r\n provider: 'turso',\r\n providerLabel: 'Turso',\r\n promptSubject: 'Turso database',\r\n packagePatterns: [/@libsql\\/client/],\r\n envPatterns: [/turso_database_url/i, /turso_auth_token/i],\r\n usagePatterns: [/@libsql\\/client/i, /createClient\\s*\\(/i],\r\n manualLabel: 'Production Turso database checked',\r\n manualHint: 'Confirm production database, auth token scope, replica/region, and backup strategy in Turso.'\r\n });\r\n}\r\n\r\nfunction analyzeMongoDatabase(ctx: StackContext): StackWiringProviderSummary {\r\n return databaseSummary(ctx, {\r\n key: 'mongodb-database',\r\n provider: 'mongodb',\r\n providerLabel: 'MongoDB',\r\n promptSubject: 'MongoDB database',\r\n packagePatterns: [/^mongodb$/, /^mongoose$/],\r\n envPatterns: [/mongodb_uri/i, /mongodb_url/i, /mongodb_atlas_uri/i],\r\n usagePatterns: [/new\\s+MongoClient|mongoose\\.connect|mongodb/i],\r\n manualLabel: 'Production MongoDB Atlas settings checked',\r\n manualHint: 'Confirm Atlas network access, database user permissions, backups, indexes, and production cluster sizing.'\r\n });\r\n}\r\n\r\nfunction analyzePlanetScaleDatabase(ctx: StackContext): StackWiringProviderSummary {\r\n return databaseSummary(ctx, {\r\n key: 'planetscale-database',\r\n provider: 'planetscale',\r\n providerLabel: 'PlanetScale',\r\n promptSubject: 'PlanetScale database',\r\n packagePatterns: [/@planetscale\\/database/],\r\n envPatterns: [/planetscale_database_url/i, /database_url/i],\r\n usagePatterns: [/@planetscale\\/database/i, /connect\\s*\\(/i],\r\n manualLabel: 'Production PlanetScale branch checked',\r\n manualHint: 'Confirm production branch, deploy requests, connection credentials, backups, and schema migration workflow.'\r\n });\r\n}\r\n\r\nfunction analyzeVercelDeployment(ctx: StackContext): StackWiringProviderSummary {\r\n return summarize({\r\n key: 'vercel-deployment',\r\n provider: 'vercel',\r\n providerLabel: 'Vercel',\r\n area: 'deployment',\r\n areaLabel: 'Deployment',\r\n promptSubject: 'Vercel deployment',\r\n items: [\r\n item('deploy-target-detected', 'Vercel-compatible app detected', Boolean(ctx.scan.stackSignals.hasVercel || ctx.scan.stackSignals.hasNextJs || ctx.scan.stackSignals.hasVite || /vercel\\.json|next\\.config|vite\\.config/i.test(ctx.pathBlob)), pathEvidence(ctx, /vercel\\.json|next\\.config|vite\\.config/i), 'Confirm this app has a Vercel-compatible framework or deployment target.'),\r\n item('build-script-found', 'Production build script found', /\"build\"\\s*:\\s*\"[^\"]+\"/i.test(ctx.contentBlob), fileEvidence(ctx, /\"build\"\\s*:\\s*\"[^\"]+\"/i), 'Add a package.json build script that Vercel can run.'),\r\n item('deployment-config-found', 'Deployment config or command found', /vercel\\.json/i.test(ctx.pathBlob) || /\"deploy\"\\s*:\\s*\"[^\"]*vercel/i.test(ctx.contentBlob), pathEvidence(ctx, /vercel\\.json/i).concat(fileEvidence(ctx, /\"deploy\"\\s*:\\s*\"[^\"]*vercel/i)), 'Add vercel.json or a documented Vercel deploy command when the project needs custom deployment behavior.'),\r\n item('env-template-found', 'Production env template found', Boolean(ctx.scan.stackSignals.hasEnvExample || /(^|\\n|\\/)\\.env\\.example\\b|env\\.example|environment variables/i.test(ctx.pathBlob + '\\n' + ctx.contentBlob)), pathEvidence(ctx, /\\.env\\.example|env\\.example/i), 'Document production env variable names in .env.example or setup docs.'),\r\n item('preview-or-ci-found', 'Preview deploy or CI config found', Boolean(ctx.scan.stackSignals.hasCI || /\\.github\\/workflows|vercel\\.json/i.test(ctx.pathBlob)), pathEvidence(ctx, /\\.github\\/workflows|vercel\\.json/i), 'Add CI or Vercel preview-deploy configuration so production changes are tested before release.'),\r\n manualItem('production-dashboard-checked', 'Production Vercel env and domain checked', 'Confirm production env values, project link, framework preset, build command, and production domain in Vercel Dashboard.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzeNetlifyDeployment(ctx: StackContext): StackWiringProviderSummary {\r\n const base = deploymentSummary(ctx, {\r\n key: 'netlify-deployment',\r\n provider: 'netlify',\r\n providerLabel: 'Netlify',\r\n promptSubject: 'Netlify deployment',\r\n packagePatterns: [/@netlify\\//],\r\n configPatterns: [/netlify\\.toml/i, /\\.netlify\\//i],\r\n envPatterns: [/netlify_auth_token/i, /netlify_site_id/i],\r\n manualLabel: 'Production Netlify env and domain checked',\r\n manualHint: 'Confirm build command, publish directory, functions runtime, env values, redirects, and production domain in Netlify.'\r\n });\r\n const redirectsOrFunctionsPattern = /(\\[\\[redirects\\]\\]|(^|\\n|\\/)_redirects\\b|(^|\\n|\\/)netlify\\/functions\\/|\\[functions\\]|functions\\s*=)/i;\r\n return summarize({\r\n ...base,\r\n items: [\r\n ...base.items.filter((entry) => entry.status !== 'manual'),\r\n item('redirects-or-functions-found', 'Redirects or Netlify Functions found', redirectsOrFunctionsPattern.test(ctx.contentBlob + '\\n' + ctx.pathBlob), fileEvidence(ctx, redirectsOrFunctionsPattern).concat(pathEvidence(ctx, redirectsOrFunctionsPattern)), 'Add Netlify redirects or functions configuration when deployment behavior depends on routing or serverless handlers.'),\r\n ...base.items.filter((entry) => entry.status === 'manual')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzeAwsDeployment(ctx: StackContext): StackWiringProviderSummary {\r\n const base = deploymentSummary(ctx, {\r\n key: 'aws-deployment',\r\n provider: 'aws',\r\n providerLabel: 'AWS',\r\n promptSubject: 'AWS deployment',\r\n packagePatterns: [/@aws-sdk\\//, /^aws-cdk-lib$/, /^serverless$/],\r\n configPatterns: [/serverless\\.ya?ml/i, /template\\.ya?ml/i, /cdk\\.json/i, /amplify\\//i, /\\.github\\/workflows/i],\r\n envPatterns: [/aws_region/i, /aws_access_key_id/i],\r\n manualLabel: 'Production AWS account and IAM checked',\r\n manualHint: 'Confirm IAM permissions, region, secrets, logs, alarms, domains, and rollback strategy in AWS.'\r\n });\r\n const infrastructurePattern = /serverless\\.ya?ml|template\\.ya?ml|cdk\\.json|sst\\.config|terraform|cloudformation|aws-cdk-lib|provider:\\s*\\n\\s*name:\\s*aws|resources:\\s*|functions:\\s*/i;\r\n return summarize({\r\n ...base,\r\n items: [\r\n ...base.items.filter((entry) => entry.status !== 'manual'),\r\n item('infrastructure-config-found', 'AWS infrastructure config found', infrastructurePattern.test(ctx.contentBlob + '\\n' + ctx.pathBlob), fileEvidence(ctx, infrastructurePattern).concat(pathEvidence(ctx, infrastructurePattern)), 'Add reproducible AWS infrastructure config such as Serverless, CDK, SAM, CloudFormation, or Terraform.'),\r\n ...base.items.filter((entry) => entry.status === 'manual')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzeSupabaseLanding(ctx: StackContext): StackWiringProviderSummary {\r\n return summarize({\r\n key: 'supabase-landing',\r\n provider: 'supabase',\r\n providerLabel: 'Supabase',\r\n area: 'landing',\r\n areaLabel: 'Landing / Onboarding',\r\n promptSubject: 'Supabase landing data',\r\n items: [\r\n item('package-installed', 'Supabase package installed', hasPackage(ctx, [/@supabase\\//]), packageEvidence(ctx, [/@supabase\\//]), 'Install Supabase client/server helpers for waitlist or onboarding storage.'),\r\n item('env-names-documented', 'Supabase env names documented', /supabase_url/i.test(ctx.contentBlob) && /supabase_anon_key/i.test(ctx.contentBlob), envEvidence(ctx, [/supabase_url/i, /supabase_anon_key/i]), 'Document Supabase URL and anon key env names for landing/onboarding data.'),\r\n item('lead-table-usage-found', 'Lead or onboarding data usage found', /waitlist|lead|onboarding|signup|profiles|subscribers/i.test(ctx.contentBlob), fileEvidence(ctx, /waitlist|lead|onboarding|signup|profiles|subscribers/i), 'Store waitlist, lead, or onboarding records in a clear Supabase table.'),\r\n item('form-submit-found', 'Form submission path found', /formdata|onSubmit|action=|submit|insert\\s*\\(/i.test(ctx.contentBlob), fileEvidence(ctx, /formdata|onSubmit|action=|submit|insert\\s*\\(/i), 'Wire the landing/onboarding form to a real server-safe submission path.'),\r\n manualItem('production-data-policy-checked', 'Production data policy checked', 'Confirm table permissions, spam handling, and privacy policy alignment in Supabase.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzeSentryMonitoring(ctx: StackContext): StackWiringProviderSummary {\r\n return summarize({\r\n key: 'sentry-monitoring',\r\n provider: 'sentry',\r\n providerLabel: 'Sentry',\r\n area: 'monitoring',\r\n areaLabel: 'Monitoring',\r\n promptSubject: 'Sentry monitoring',\r\n items: [\r\n item('package-installed', 'Sentry package installed', hasPackage(ctx, [/^@sentry\\//]), packageEvidence(ctx, [/^@sentry\\//]), 'Install the Sentry package that matches this app framework.'),\r\n item('env-names-documented', 'Sentry DSN env documented', /sentry_dsn|next_public_sentry_dsn/i.test(ctx.contentBlob), envEvidence(ctx, [/sentry_dsn/i, /next_public_sentry_dsn/i]), 'Document SENTRY_DSN or NEXT_PUBLIC_SENTRY_DSN in env examples or setup docs.'),\r\n item('init-found', 'Sentry initialization found', /sentry\\.init\\s*\\(|instrumentation\\.[jt]s/i.test(ctx.contentBlob + '\\n' + ctx.pathBlob), fileEvidence(ctx, /sentry\\.init\\s*\\(|instrumentation\\.[jt]s/i), 'Initialize Sentry in the framework entrypoint for client and server errors.'),\r\n item('error-capture-found', 'Error capture or boundary found', /captureexception|global-error|errorboundary|onerror/i.test(ctx.contentBlob + '\\n' + ctx.pathBlob), fileEvidence(ctx, /captureexception|global-error|errorboundary|onerror/i), 'Capture production exceptions through Sentry error boundaries or server handlers.'),\r\n item('release-config-found', 'Release or source map config found', /sentry_auth_token|withsentryconfig|sentry-cli|sourcemap/i.test(ctx.contentBlob), fileEvidence(ctx, /sentry_auth_token|withsentryconfig|sentry-cli|sourcemap/i), 'Configure Sentry releases or source maps so production stack traces are useful.'),\r\n manualItem('production-dashboard-checked', 'Production Sentry project checked', 'Confirm DSN, environment names, alerts, retention, and source-map upload status in Sentry.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzePostHogMonitoring(ctx: StackContext): StackWiringProviderSummary {\r\n return summarize({\r\n key: 'posthog-monitoring',\r\n provider: 'posthog',\r\n providerLabel: 'PostHog',\r\n area: 'monitoring',\r\n areaLabel: 'Monitoring',\r\n promptSubject: 'PostHog analytics',\r\n items: [\r\n item('package-installed', 'PostHog package installed', hasPackage(ctx, [/^posthog-js$/, /^posthog-node$/]), packageEvidence(ctx, [/^posthog-js$/, /^posthog-node$/]), 'Install posthog-js or posthog-node for the app surface that needs analytics.'),\r\n item('env-names-documented', 'PostHog env names documented', /posthog_key|next_public_posthog_key/i.test(ctx.contentBlob), envEvidence(ctx, [/posthog_key/i, /next_public_posthog_key/i, /next_public_posthog_host/i]), 'Document NEXT_PUBLIC_POSTHOG_KEY and host/project settings in env examples or setup docs.'),\r\n item('init-found', 'PostHog initialization found', /posthog\\.init\\s*\\(/i.test(ctx.contentBlob), fileEvidence(ctx, /posthog\\.init\\s*\\(/i), 'Initialize PostHog once in the app client/provider layer.'),\r\n item('provider-or-wrapper-found', 'Analytics provider or wrapper found', /posthogprovider|analytics\\/posthog|useposthog/i.test(ctx.contentBlob + '\\n' + ctx.pathBlob), fileEvidence(ctx, /posthogprovider|analytics\\/posthog|useposthog/i), 'Add a reusable analytics provider or wrapper instead of scattering raw setup code.'),\r\n item('event-capture-found', 'Product event capture found', /posthog\\.capture\\s*\\(/i.test(ctx.contentBlob), fileEvidence(ctx, /posthog\\.capture\\s*\\(/i), 'Capture at least one activation or conversion event.'),\r\n item('identity-found', 'User identify or group call found', /posthog\\.identify\\s*\\(|posthog\\.group\\s*\\(/i.test(ctx.contentBlob), fileEvidence(ctx, /posthog\\.identify\\s*\\(|posthog\\.group\\s*\\(/i), 'Identify signed-in users or groups where privacy rules allow it.'),\r\n manualItem('production-dashboard-checked', 'Production PostHog project checked', 'Confirm project key, allowed domains, privacy settings, autocapture choice, and retention in PostHog.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzeLogRocketMonitoring(ctx: StackContext): StackWiringProviderSummary {\r\n const privacyScrubbingPattern = /requestSanitizer|responseSanitizer|dom\\.inputSanitizer|dom\\.textSanitizer|maskAllInputs|maskInputOptions|sanitize|scrub|redact|privacy/i;\r\n return summarize({\r\n key: 'logrocket-monitoring',\r\n provider: 'logrocket',\r\n providerLabel: 'LogRocket',\r\n area: 'monitoring',\r\n areaLabel: 'Monitoring',\r\n promptSubject: 'LogRocket monitoring',\r\n items: [\r\n item('package-installed', 'LogRocket package installed', hasPackage(ctx, [/^logrocket$/]), packageEvidence(ctx, [/^logrocket$/]), 'Install LogRocket for session replay if this product needs replay debugging.'),\r\n item('env-names-documented', 'LogRocket app id env documented', /logrocket_app_id|next_public_logrocket_app_id/i.test(ctx.contentBlob), envEvidence(ctx, [/logrocket_app_id/i, /next_public_logrocket_app_id/i]), 'Document the LogRocket app id env name.'),\r\n item('init-found', 'LogRocket initialization found', /logrocket\\.init\\s*\\(/i.test(ctx.contentBlob), fileEvidence(ctx, /logrocket\\.init\\s*\\(/i), 'Initialize LogRocket once in the client app shell.'),\r\n item('identify-found', 'User identification found', /logrocket\\.identify\\s*\\(/i.test(ctx.contentBlob), fileEvidence(ctx, /logrocket\\.identify\\s*\\(/i), 'Identify signed-in users where privacy rules allow it.'),\r\n item('privacy-scrubbing-found', 'Privacy scrubbing found', privacyScrubbingPattern.test(ctx.contentBlob), fileEvidence(ctx, privacyScrubbingPattern), 'Add repo-visible LogRocket privacy scrubbing for sensitive DOM fields or network payloads.'),\r\n manualItem('production-dashboard-checked', 'Production LogRocket privacy settings checked', 'Confirm app id, domain, privacy masking, network scrubbing, and retention in LogRocket.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzeVitestTesting(ctx: StackContext): StackWiringProviderSummary {\r\n return summarize({\r\n key: 'vitest-testing',\r\n provider: 'vitest',\r\n providerLabel: 'Vitest',\r\n area: 'testing',\r\n areaLabel: 'Testing',\r\n promptSubject: 'Vitest tests',\r\n items: [\r\n item('package-installed', 'Vitest package installed', hasPackage(ctx, [/^vitest$/]), packageEvidence(ctx, [/^vitest$/]), 'Install Vitest for unit or component test coverage.'),\r\n item('test-script-found', 'Test script found', /\"test\"\\s*:\\s*\"[^\"]*(vitest|npm run|pnpm|yarn)/i.test(ctx.contentBlob), fileEvidence(ctx, /\"test\"\\s*:\\s*\"[^\"]*(vitest|npm run|pnpm|yarn)/i), 'Add a package.json test script that runs Vitest.'),\r\n item('test-files-found', 'Unit test files found', Boolean(ctx.scan.stackSignals.hasTests) || /\\.(test|spec)\\.[jt]sx?\\b/i.test(ctx.pathBlob), pathEvidence(ctx, /\\.(test|spec)\\.[jt]sx?\\b/i), 'Add unit tests for critical product logic.'),\r\n item('assertions-found', 'Assertions found', /expect\\s*\\(|assert\\s*\\(|test\\s*\\(/i.test(ctx.contentBlob), fileEvidence(ctx, /expect\\s*\\(|assert\\s*\\(|test\\s*\\(/i), 'Ensure tests include real assertions, not only smoke imports.'),\r\n manualItem('coverage-risk-reviewed', 'Critical path coverage reviewed', 'Confirm auth, billing, database, and main user flows have meaningful tests.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzePlaywrightTesting(ctx: StackContext): StackWiringProviderSummary {\r\n return summarize({\r\n key: 'playwright-testing',\r\n provider: 'playwright',\r\n providerLabel: 'Playwright',\r\n area: 'testing',\r\n areaLabel: 'Testing',\r\n promptSubject: 'Playwright tests',\r\n items: [\r\n item('package-installed', 'Playwright package installed', hasPackage(ctx, [/@playwright\\/test/]) || Boolean(ctx.scan.stackSignals.hasPlaywright), packageEvidence(ctx, [/@playwright\\/test/]), 'Install @playwright/test for browser-flow coverage.'),\r\n item('config-found', 'Playwright config found', /playwright\\.config\\.[jt]s/i.test(ctx.pathBlob), pathEvidence(ctx, /playwright\\.config\\.[jt]s/i), 'Add a Playwright config with browser and base URL settings.'),\r\n item('e2e-tests-found', 'Browser flow tests found', /(^|\\n|\\/)(e2e|tests?)\\/[^/\\n]+\\.(spec|test)\\.[jt]s/i.test(ctx.pathBlob), pathEvidence(ctx, /(^|\\/)(e2e|tests?)\\/[^/]+\\.(spec|test)\\.[jt]s/i), 'Add at least one browser test for the core signup or happy path.'),\r\n item('page-actions-found', 'Real browser actions found', /page\\.goto|page\\.click|page\\.getByRole|expect\\(page/i.test(ctx.contentBlob), fileEvidence(ctx, /page\\.goto|page\\.click|page\\.getByRole|expect\\(page/i), 'Use real browser actions and visible assertions in Playwright tests.'),\r\n manualItem('production-like-test-env-checked', 'Production-like test env checked', 'Confirm test env variables, seed data, and CI browser dependencies are ready.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzeSentryErrorHandling(ctx: StackContext): StackWiringProviderSummary {\r\n const base = analyzeSentryMonitoring(ctx);\r\n return summarize({\r\n ...base,\r\n key: 'sentry-error-handling',\r\n area: 'errorHandling',\r\n areaLabel: 'Error Handling',\r\n promptSubject: 'Sentry error handling',\r\n items: [\r\n ...base.items.filter((entry) => entry.id !== 'release-config-found'),\r\n item('user-facing-fallback-found', 'User-facing error fallback found', /global-error|errorboundary|fallback|try again|toast/i.test(ctx.contentBlob + '\\n' + ctx.pathBlob), fileEvidence(ctx, /global-error|errorboundary|fallback|try again|toast/i), 'Add a user-facing fallback for production errors.'),\r\n manualItem('alert-routing-checked', 'Production alert routing checked', 'Confirm alert routing and issue ownership in Sentry.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzePostHogErrorHandling(ctx: StackContext): StackWiringProviderSummary {\r\n return summarize({\r\n key: 'posthog-error-handling',\r\n provider: 'posthog',\r\n providerLabel: 'PostHog',\r\n area: 'errorHandling',\r\n areaLabel: 'Error Handling',\r\n promptSubject: 'PostHog error events',\r\n items: [\r\n item('package-installed', 'PostHog package installed', hasPackage(ctx, [/^posthog-js$/, /^posthog-node$/]), packageEvidence(ctx, [/^posthog-js$/, /^posthog-node$/]), 'Install PostHog before using it for error or recovery events.'),\r\n item('env-names-documented', 'PostHog env names documented', /posthog_key|next_public_posthog_key/i.test(ctx.contentBlob), envEvidence(ctx, [/posthog_key/i, /next_public_posthog_key/i]), 'Document PostHog project env names.'),\r\n item('error-event-capture-found', 'Error or recovery event capture found', /posthog\\.capture\\s*\\([^)]*(error|exception|failed|recovery|retry)/i.test(ctx.contentBlob), fileEvidence(ctx, /posthog\\.capture\\s*\\([^)]*(error|exception|failed|recovery|retry)/i), 'Capture meaningful error or recovery events for product analytics.'),\r\n item('fallback-state-found', 'Fallback state found', /errorboundary|global-error|fallback|try again|retry/i.test(ctx.contentBlob + '\\n' + ctx.pathBlob), fileEvidence(ctx, /errorboundary|global-error|fallback|try again|retry/i), 'Add fallback states that users can recover from.'),\r\n manualItem('privacy-settings-checked', 'Error analytics privacy checked', 'Confirm error analytics avoid sensitive payloads and follow the product privacy policy.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzeRateLimitSecurity(ctx: StackContext): StackWiringProviderSummary {\r\n return summarize({\r\n key: 'rate-limit-security',\r\n provider: 'rate-limit',\r\n providerLabel: 'Rate limiting',\r\n area: 'security',\r\n areaLabel: 'Security',\r\n promptSubject: 'rate limiting',\r\n items: [\r\n item('package-installed', 'Rate limit package installed', hasPackage(ctx, [/@upstash\\/ratelimit/, /express-rate-limit/, /rate-limiter-flexible/, /@fastify\\/rate-limit/]) || Boolean(ctx.scan.stackSignals.hasRateLimit), packageEvidence(ctx, [/@upstash\\/ratelimit/, /express-rate-limit/, /rate-limiter-flexible/, /@fastify\\/rate-limit/]), 'Install a rate-limit library appropriate for this backend.'),\r\n item('env-names-documented', 'Rate limit backing store env documented', /upstash_redis_rest_url|redis_url|rate_limit/i.test(ctx.contentBlob), envEvidence(ctx, [/upstash_redis_rest_url/i, /upstash_redis_rest_token/i, /redis_url/i]), 'Document Redis or provider env names used by rate limiting.'),\r\n item('guard-code-found', 'Rate limit guard code found', /ratelimit|rateLimit|Too many requests|429/i.test(ctx.contentBlob), fileEvidence(ctx, /ratelimit|rateLimit|Too many requests|429/i), 'Add a rate-limit guard to expensive or abusive API routes.'),\r\n item('api-route-coverage-found', 'Protected API route found', /api\\/|route\\.[jt]s/i.test(ctx.pathBlob) && /ratelimit|rateLimit|429/i.test(ctx.contentBlob), pathEvidence(ctx, /api\\/|route\\.[jt]s/i), 'Apply rate limits to public mutation, auth, AI, or checkout endpoints.'),\r\n manualItem('production-thresholds-checked', 'Production thresholds checked', 'Confirm limits, burst behavior, and allowlists match real production traffic.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzeBotProtectionSecurity(ctx: StackContext): StackWiringProviderSummary {\r\n return summarize({\r\n key: 'bot-protection-security',\r\n provider: 'bot-protection',\r\n providerLabel: 'Bot protection',\r\n area: 'security',\r\n areaLabel: 'Security',\r\n promptSubject: 'bot protection',\r\n items: [\r\n item('package-or-widget-found', 'Bot protection package or widget found', hasPackage(ctx, [/turnstile|recaptcha|hcaptcha/]) || /turnstile|recaptcha|hcaptcha|cf-turnstile/i.test(ctx.contentBlob), packageEvidence(ctx, [/turnstile|recaptcha|hcaptcha/]).concat(fileEvidence(ctx, /turnstile|recaptcha|hcaptcha|cf-turnstile/i)), 'Add Turnstile, reCAPTCHA, hCaptcha, or an equivalent bot check for exposed forms.'),\r\n item('env-names-documented', 'Bot protection env names documented', /turnstile.*(site|secret)|recaptcha.*(site|secret)|hcaptcha.*(site|secret)/i.test(ctx.contentBlob), envEvidence(ctx, [/turnstile/i, /recaptcha/i, /hcaptcha/i]), 'Document site key and secret key env names.'),\r\n item('server-verification-found', 'Server-side bot verification found', /siteverify|turnstile.*verify|recaptcha.*verify|hcaptcha.*verify/i.test(ctx.contentBlob), fileEvidence(ctx, /siteverify|turnstile.*verify|recaptcha.*verify|hcaptcha.*verify/i), 'Verify bot tokens server-side before accepting form or signup requests.'),\r\n manualItem('production-challenge-checked', 'Production challenge settings checked', 'Confirm allowed domains, challenge mode, and privacy settings in the bot-protection provider.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzeSecretsHygiene(ctx: StackContext): StackWiringProviderSummary {\r\n const unsafePublicSecret = ctx.files.filter((file) =>\r\n isClientExecutedPath(file.normalizedPath) &&\r\n /(secret_key|api_secret|private_key|service_role|webhook_secret|password)/i.test(file.content)\r\n );\r\n return summarize({\r\n key: 'secrets-hygiene-security',\r\n provider: 'secrets-hygiene',\r\n providerLabel: 'Secrets hygiene',\r\n area: 'security',\r\n areaLabel: 'Security',\r\n promptSubject: 'secrets hygiene',\r\n items: [\r\n item('env-example-found', 'Env example or docs found', Boolean(ctx.scan.stackSignals.hasEnvExample) || /\\.env\\.example|env\\.example|environment variables/i.test(ctx.pathBlob + '\\n' + ctx.contentBlob), pathEvidence(ctx, /\\.env\\.example|env\\.example/i), 'Add an env example or setup docs with variable names only.'),\r\n item('secret-files-ignored', 'Secret files detected as private', Array.isArray(ctx.scan.secretsFound) && ctx.scan.secretsFound.length > 0, ctx.scan.secretsFound.slice(0, 4).map((path) => `secret file: ${path}`), 'Keep real .env files private and out of copied prompts or docs.'),\r\n item('frontend-secrets-clean', 'No obvious frontend secret exposure found', unsafePublicSecret.length === 0, unsafePublicSecret.slice(0, 4).map((file) => `unsafe reference: ${file.path}`), 'Move secret values and private keys out of frontend/client-executed files.'),\r\n item('gitignore-env-found', 'Env files ignored by git', /\\.gitignore/i.test(ctx.pathBlob) && /\\.env/i.test(ctx.contentBlob), pathEvidence(ctx, /\\.gitignore/i), 'Ensure .gitignore excludes real .env files while keeping .env.example committed.'),\r\n manualItem('production-secret-rotation-checked', 'Production secret rotation checked', 'Confirm production secrets can be rotated and revoked in provider dashboards.')\r\n ]\r\n });\r\n}\r\n\r\nfunction databaseSummary(\r\n ctx: StackContext,\r\n spec: {\r\n key: StackWiringKey;\r\n provider: StackWiringProviderSummary['provider'];\r\n providerLabel: string;\r\n promptSubject: string;\r\n packagePatterns: RegExp[];\r\n envPatterns: RegExp[];\r\n usagePatterns: RegExp[];\r\n manualLabel: string;\r\n manualHint: string;\r\n }\r\n): StackWiringProviderSummary {\r\n const usagePattern = new RegExp(spec.usagePatterns.map((pattern) => pattern.source).join('|'), 'i');\r\n const indexOrPerformancePattern = /create\\s+(unique\\s+)?index|\\bindex\\s*:\\s*true|@@index|\\.index\\s*\\(|\\bindexes\\b|\\bexplain\\s*\\(|connection\\s*pool|pooling|pgbouncer/i;\r\n return summarize({\r\n key: spec.key,\r\n provider: spec.provider,\r\n providerLabel: spec.providerLabel,\r\n area: 'database',\r\n areaLabel: 'Database',\r\n promptSubject: spec.promptSubject,\r\n items: [\r\n item('package-installed', `${spec.providerLabel} package installed`, hasPackage(ctx, spec.packagePatterns), packageEvidence(ctx, spec.packagePatterns), `Install the ${spec.providerLabel} package or SDK for this app.`),\r\n item('env-names-documented', `${spec.providerLabel} env names documented`, spec.envPatterns.some((pattern) => pattern.test(ctx.contentBlob)), envEvidence(ctx, spec.envPatterns), `Document ${spec.providerLabel} connection env names in an env example or setup docs.`),\r\n item('client-or-connection-found', `${spec.providerLabel} connection code found`, usagePattern.test(ctx.contentBlob), fileEvidence(ctx, usagePattern), `Add ${spec.providerLabel} connection code in a server-safe helper.`),\r\n item('query-usage-found', 'Database query usage found', /select\\s*\\(|insert\\s*\\(|update\\s*\\(|delete\\s*\\(|findOne|findMany|collection\\s*\\(|execute\\s*\\(|query\\s*\\(|sql`/i.test(ctx.contentBlob), fileEvidence(ctx, /select\\s*\\(|insert\\s*\\(|update\\s*\\(|delete\\s*\\(|findOne|findMany|collection\\s*\\(|execute\\s*\\(|query\\s*\\(|sql`/i), 'Use the database connection for real reads or writes.'),\r\n item('schema-or-model-found', 'Schema, model, or migration found', /schema|migration|model|create\\s+table|mongoose\\.schema|drizzle|prisma/i.test(ctx.contentBlob + '\\n' + ctx.pathBlob), fileEvidence(ctx, /schema|migration|model|create\\s+table|mongoose\\.schema|drizzle|prisma/i), 'Keep schema, models, or migrations reproducible in the repo.'),\r\n item('index-or-performance-evidence', 'Index or performance evidence found', indexOrPerformancePattern.test(ctx.contentBlob), fileEvidence(ctx, indexOrPerformancePattern), 'Add repo-visible indexes, query plans, connection pooling, or equivalent performance evidence for production database access.'),\r\n manualItem('production-dashboard-checked', spec.manualLabel, spec.manualHint)\r\n ]\r\n });\r\n}\r\n\r\nfunction deploymentSummary(\r\n ctx: StackContext,\r\n spec: {\r\n key: StackWiringKey;\r\n provider: StackWiringProviderSummary['provider'];\r\n providerLabel: string;\r\n promptSubject: string;\r\n packagePatterns: RegExp[];\r\n configPatterns: RegExp[];\r\n envPatterns: RegExp[];\r\n manualLabel: string;\r\n manualHint: string;\r\n }\r\n): StackWiringProviderSummary {\r\n const configPattern = new RegExp(spec.configPatterns.map((pattern) => pattern.source).join('|'), 'i');\r\n return summarize({\r\n key: spec.key,\r\n provider: spec.provider,\r\n providerLabel: spec.providerLabel,\r\n area: 'deployment',\r\n areaLabel: 'Deployment',\r\n promptSubject: spec.promptSubject,\r\n items: [\r\n item('package-or-config-found', `${spec.providerLabel} package or config found`, hasPackage(ctx, spec.packagePatterns) || configPattern.test(ctx.pathBlob), packageEvidence(ctx, spec.packagePatterns).concat(pathEvidence(ctx, configPattern)), `Add ${spec.providerLabel} config when this project needs provider-specific deployment behavior.`),\r\n item('build-script-found', 'Production build script found', /\"build\"\\s*:\\s*\"[^\"]+\"/i.test(ctx.contentBlob), fileEvidence(ctx, /\"build\"\\s*:\\s*\"[^\"]+\"/i), 'Add a package.json build script for production deploys.'),\r\n item('env-names-documented', 'Deployment env names documented', spec.envPatterns.some((pattern) => pattern.test(ctx.contentBlob)) || /\\.env\\.example|environment variables/i.test(ctx.pathBlob + '\\n' + ctx.contentBlob), envEvidence(ctx, spec.envPatterns).concat(pathEvidence(ctx, /\\.env\\.example/i)), 'Document production env variable names needed by deployment.'),\r\n item('ci-or-deploy-doc-found', 'CI or deploy docs found', /\\.github\\/workflows|deploy|deployment|preview/i.test(ctx.pathBlob + '\\n' + ctx.contentBlob), pathEvidence(ctx, /\\.github\\/workflows/i).concat(fileEvidence(ctx, /deploy|deployment|preview/i)), 'Document or automate deployment and preview checks.'),\r\n manualItem('production-dashboard-checked', spec.manualLabel, spec.manualHint)\r\n ]\r\n });\r\n}\r\n\r\nfunction buildContext(scan: ScanResult): StackContext {\r\n const files = visibleFiles(scan);\r\n return {\r\n scan,\r\n files,\r\n deps: scan.packageDeps.map((dep) => dep.toLowerCase()),\r\n pathBlob: `${scan.fileTree}\\n${scan.files.map((file) => file.path).join('\\n')}`.replace(/\\\\/g, '/').toLowerCase(),\r\n contentBlob: files.map((file) => file.lowerContent).join('\\n')\r\n };\r\n}\r\n\r\nfunction visibleFiles(scan: ScanResult): VisibleFile[] {\r\n return scan.files\r\n .filter((file: ScannedFile) => !file.isSecret && typeof file.content === 'string')\r\n .map((file) => ({\r\n path: file.path.replace(/\\\\/g, '/'),\r\n normalizedPath: file.path.replace(/\\\\/g, '/').toLowerCase(),\r\n content: file.content as string,\r\n lowerContent: (file.content as string).toLowerCase()\r\n }));\r\n}\r\n\r\nfunction summarize(summary: Omit<StackWiringProviderSummary, 'passedCount' | 'totalCount' | 'readinessPercent'>): StackWiringProviderSummary {\r\n const repoItems = summary.items.filter((entry) => entry.status !== 'manual');\r\n const passedCount = repoItems.filter((entry) => entry.status === 'passed').length;\r\n const totalCount = repoItems.length;\r\n return {\r\n ...summary,\r\n passedCount,\r\n totalCount,\r\n readinessPercent: Math.round((passedCount / Math.max(totalCount, 1)) * 100)\r\n };\r\n}\r\n\r\nfunction item(id: string, label: string, passed: boolean, evidence: string[], promptHint: string): StackWiringItem {\r\n return {\r\n id,\r\n label,\r\n status: passed ? 'passed' : 'missing',\r\n evidence,\r\n promptHint\r\n };\r\n}\r\n\r\nfunction manualItem(id: string, label: string, promptHint: string): StackWiringItem {\r\n return {\r\n id,\r\n label,\r\n status: 'manual',\r\n evidence: [],\r\n promptHint\r\n };\r\n}\r\n\r\nfunction secretSafetyItem(ctx: StackContext, id: string, label: string, pattern: RegExp, promptHint: string): StackWiringItem {\r\n const exposed = ctx.files.filter((file) => isClientExecutedPath(file.normalizedPath) && pattern.test(file.content));\r\n return {\r\n id,\r\n label,\r\n status: exposed.length > 0 ? 'missing' : 'passed',\r\n evidence: exposed.slice(0, 4).map((file) => `unsafe reference: ${file.path}`),\r\n promptHint\r\n };\r\n}\r\n\r\nfunction hasPackage(ctx: StackContext, patterns: RegExp[]): boolean {\r\n return ctx.deps.some((dep) => patterns.some((pattern) => pattern.test(dep)));\r\n}\r\n\r\nfunction hasAllContent(ctx: StackContext, patterns: RegExp[]): boolean {\r\n return patterns.every((pattern) => pattern.test(ctx.contentBlob));\r\n}\r\n\r\nfunction packageEvidence(ctx: StackContext, patterns: RegExp[]): string[] {\r\n return ctx.deps\r\n .filter((dep) => patterns.some((pattern) => pattern.test(dep)))\r\n .slice(0, 4)\r\n .map((dep) => `package: ${dep}`);\r\n}\r\n\r\nfunction envEvidence(ctx: StackContext, patterns: RegExp[]): string[] {\r\n const evidence: string[] = [];\r\n for (const pattern of patterns) {\r\n if (pattern.test(ctx.contentBlob)) {\r\n evidence.push(`env: ${pattern.source.replace(/\\\\b|\\(|\\)|\\?|\\||\\^|\\$|_/g, ' ').trim().toUpperCase().replace(/\\s+/g, '_')}`);\r\n }\r\n }\r\n return evidence.slice(0, 4);\r\n}\r\n\r\nfunction pathEvidence(ctx: StackContext, pattern: RegExp): string[] {\r\n return ctx.pathBlob\r\n .split(/\\r?\\n/)\r\n .filter((path) => pattern.test(path))\r\n .slice(0, 4)\r\n .map((path) => `file: ${path}`);\r\n}\r\n\r\nfunction fileEvidence(ctx: StackContext, pattern: RegExp): string[] {\r\n return ctx.files\r\n .filter((file) => pattern.test(file.path) || pattern.test(file.content))\r\n .slice(0, 4)\r\n .map((file) => `file: ${file.path}`);\r\n}\r\n\r\nfunction isClientExecutedPath(path: string): boolean {\r\n return /\\.(tsx|jsx)$/.test(path) ||\r\n /(^|\\/)(components|pages|app|client|frontend|web)\\//.test(path) ||\r\n /\\.client\\.[jt]sx?$/.test(path);\r\n}\r\n\r\nfunction formatEvidence(evidence: string[]): string {\r\n return evidence.length > 0 ? ` (${evidence.slice(0, 3).join('; ')})` : '';\r\n}\r\n", "import type {\r\n ProductionConnectionSummary,\r\n ScanResult,\r\n VerificationArea,\r\n VerificationAreaSummary,\r\n VerificationItem,\r\n VerificationItemStatus,\r\n VerificationSummary\r\n} from './types';\r\n\r\ntype ProductionConnectionSummaryPayload = {\r\n byArea: Partial<Record<string, ProductionConnectionSummary>>;\r\n items: ProductionConnectionSummary[];\r\n stackRow: ProductionConnectionSummary[];\r\n};\r\n\r\ntype VerificationContext = {\n deps: Set<string>;\n paths: Set<string>;\n contents: string;\n secretPaths: Set<string>;\n scan: ScanResult;\n};\n\nconst PROVIDER_LABELS: Record<string, string> = {\n supabase: 'Supabase',\n clerk: 'Clerk',\n authjs: 'Auth.js',\n neon: 'Neon',\n planetscale: 'PlanetScale',\n mongodb: 'MongoDB',\n turso: 'Turso',\n stripe: 'Stripe',\n paddle: 'Paddle',\n vercel: 'Vercel',\n sentry: 'Sentry',\n posthog: 'PostHog',\n logrocket: 'LogRocket',\n 'rate-limit': 'Rate limit',\n 'bot-protection': 'Bot protection',\n 'secrets-hygiene': 'Secrets hygiene'\n};\n\nconst AREAS: VerificationArea[] = [\n 'auth',\r\n 'database',\r\n 'payments',\r\n 'deployment',\r\n 'monitoring',\r\n 'security',\r\n 'testing',\r\n 'landing',\r\n 'frontend',\r\n 'backend',\r\n 'appFlow',\r\n 'errorHandling'\r\n];\r\n\r\nconst CONTENT_CAP = 500_000;\r\n\r\nexport function buildVerificationSummary(\n scan: ScanResult,\n productionConnections: ProductionConnectionSummaryPayload\n): VerificationSummary {\n const ctx = buildContext(scan);\n const byArea: VerificationSummary['byArea'] = {};\n\r\n for (const area of AREAS) {\r\n byArea[area] = emptyArea(area);\r\n }\r\n\r\n applyAuthRules(byArea.auth!, ctx);\r\n applyDatabaseRules(byArea.database!, ctx);\r\n applyPaymentRules(byArea.payments!, ctx);\r\n applyDeploymentRules(byArea.deployment!, ctx);\r\n applyMonitoringRules(byArea.monitoring!, ctx);\r\n applySecurityRules(byArea.security!, ctx);\r\n applyTestingRules(byArea.testing!, ctx);\r\n applyLandingRules(byArea.landing!, ctx);\r\n applyFrontendRules(byArea.frontend!, ctx);\r\n applyBackendRules(byArea.backend!, ctx);\n applyAppFlowRules(byArea.appFlow!, ctx);\n applyErrorHandlingRules(byArea.errorHandling!, ctx);\n applyProductionConnectionEvidence(byArea, productionConnections);\n\n return { byArea };\n}\n\nexport function buildVerificationEvidenceContext(summary: VerificationSummary): string {\n const lines: string[] = [];\n for (const area of AREAS) {\n const areaSummary = summary.byArea[area];\n if (!areaSummary) {\n continue;\n }\n const found = areaSummary.found.slice(0, 6).map(formatVerificationContextItem);\n const missing = areaSummary.missing.slice(0, 6).map(formatVerificationContextItem);\n if (found.length > 0) {\n lines.push(`${area} found: ${found.join(' | ')}`);\n }\n if (missing.length > 0) {\n lines.push(`${area} missing: ${missing.join(' | ')}`);\n }\n }\n\n return lines.join('\\n');\n}\n\nfunction formatVerificationContextItem(item: VerificationItem): string {\n return item.detail ? `${item.label} (${item.detail})` : item.label;\n}\n\r\nfunction buildContext(scan: ScanResult): VerificationContext {\r\n const deps = new Set(scan.packageDeps.map((dep) => dep.toLowerCase()));\r\n const paths = new Set<string>();\r\n const secretPaths = new Set<string>();\r\n const contentParts: string[] = [];\r\n let contentLength = 0;\r\n\r\n for (const line of scan.fileTree.split(/\\r?\\n/)) {\r\n const normalized = normalizePath(line);\r\n if (normalized) {\r\n paths.add(normalized);\r\n }\r\n }\r\n\r\n for (const file of scan.files) {\r\n if (!file.isSecret) {\r\n const normalized = normalizePath(file.path);\r\n if (normalized) {\r\n paths.add(normalized);\r\n }\r\n }\r\n\r\n if (!file.isSecret && file.content) {\r\n const next = file.content.toLowerCase();\r\n const remaining = CONTENT_CAP - contentLength;\r\n if (remaining > 0) {\r\n contentParts.push(next.slice(0, remaining));\r\n contentLength += Math.min(next.length, remaining);\r\n }\r\n }\r\n }\r\n\r\n for (const secretPath of scan.secretsFound) {\r\n const normalized = normalizePath(secretPath);\r\n if (normalized) {\r\n secretPaths.add(normalized);\r\n }\r\n }\r\n\r\n return {\r\n deps,\r\n paths,\r\n contents: contentParts.join('\\n'),\r\n secretPaths,\r\n scan\r\n };\r\n}\r\n\r\nfunction emptyArea(area: VerificationArea): VerificationAreaSummary {\r\n return {\r\n area,\r\n found: [],\r\n missing: [],\r\n manual: []\r\n };\r\n}\r\n\r\nfunction normalizePath(path: string): string {\r\n return path\r\n .replace(/\\\\/g, '/')\r\n .replace(/^[\\s\\u2500\\u2502\\u2514\\u251c>*+-]+/u, '')\r\n .trim()\r\n .toLowerCase();\r\n}\r\n\r\nfunction addFound(area: VerificationAreaSummary, label: string, source: string, detail?: string): void {\r\n addItem(area, 'found', label, source, detail);\r\n}\r\n\r\nfunction addMissing(area: VerificationAreaSummary, label: string, source: string, detail?: string): void {\r\n addItem(area, 'missing', label, source, detail);\r\n}\r\n\r\nfunction addManual(area: VerificationAreaSummary, label: string, source: string, detail?: string): void {\r\n addItem(area, 'manual', label, source, detail);\r\n}\r\n\r\nfunction addItem(\r\n area: VerificationAreaSummary,\r\n status: VerificationItemStatus,\r\n label: string,\r\n source: string,\r\n detail?: string\r\n): void {\r\n const item = compactItem(label, status, source, detail);\r\n const bucket = area[status];\r\n if (!bucket.some((existing) => existing.label === item.label)) {\r\n bucket.push(item);\r\n }\r\n}\r\n\r\nfunction compactItem(\r\n label: string,\r\n status: VerificationItemStatus,\r\n source: string,\r\n detail?: string\r\n): VerificationItem {\r\n return detail ? { label, status, source, detail } : { label, status, source };\r\n}\r\n\r\nfunction hasDep(ctx: VerificationContext, patterns: string[]): boolean {\r\n return patterns.some((pattern) => {\r\n const normalized = pattern.toLowerCase();\r\n return [...ctx.deps].some((dep) => dep === normalized || dep.includes(normalized));\r\n });\r\n}\r\n\r\nfunction hasPath(ctx: VerificationContext, patterns: RegExp[]): boolean {\r\n return [...ctx.paths].some((path) => !ctx.secretPaths.has(path) && patterns.some((pattern) => pattern.test(path)));\r\n}\r\n\r\nfunction hasContent(ctx: VerificationContext, patterns: RegExp[]): boolean {\r\n return patterns.some((pattern) => pattern.test(ctx.contents));\r\n}\r\n\r\nfunction hasEnvName(ctx: VerificationContext, names: string[]): boolean {\r\n return names.some((name) => ctx.contents.includes(name.toLowerCase()));\r\n}\r\n\r\nfunction applyAuthRules(area: VerificationAreaSummary, ctx: VerificationContext): void {\r\n if (hasDep(ctx, ['@clerk/nextjs', 'clerk'])) {\r\n addFound(area, 'Clerk dependency found', 'package.json dependencies');\r\n } else if (hasDep(ctx, ['next-auth', '@auth/core', '@auth/nextjs'])) {\r\n addFound(area, 'Auth.js dependency found', 'package.json dependencies');\r\n } else if (hasDep(ctx, ['@supabase/supabase-js', '@supabase/auth-helpers-nextjs', '@supabase/ssr'])) {\r\n addFound(area, 'Supabase auth dependency found', 'package.json dependencies');\r\n } else {\r\n addMissing(area, 'Auth dependency missing', 'package.json dependencies');\r\n }\r\n\r\n if (\r\n hasPath(ctx, [/^middleware\\.[jt]sx?$/, /\\/middleware\\.[jt]sx?$/]) ||\r\n hasContent(ctx, [/clerkmiddleware\\s*\\(/, /withauth\\s*\\(/, /authmiddleware\\s*\\(/])\r\n ) {\r\n addFound(area, 'Auth middleware found', 'middleware file or auth middleware call');\r\n } else {\r\n addMissing(area, 'Auth middleware missing', 'middleware file or auth middleware call');\r\n }\r\n\r\n if (\r\n hasEnvName(ctx, [\r\n 'NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY',\r\n 'CLERK_SECRET_KEY',\r\n 'NEXTAUTH_SECRET',\r\n 'AUTH_SECRET',\r\n 'SUPABASE_SERVICE_ROLE_KEY',\r\n 'NEXT_PUBLIC_SUPABASE_ANON_KEY'\r\n ])\r\n ) {\r\n addFound(area, 'Auth env names listed', 'non-secret scanned content');\r\n } else {\r\n addMissing(area, 'Auth env names missing', 'non-secret scanned content');\r\n }\r\n\r\n addManual(area, 'Provider dashboard settings', 'external provider dashboard');\r\n addManual(area, 'Real production auth keys', 'external provider dashboard');\r\n}\r\n\r\nfunction applyDatabaseRules(area: VerificationAreaSummary, ctx: VerificationContext): void {\n if (hasDep(ctx, ['prisma', 'drizzle-orm', '@supabase/supabase-js', 'mongoose', 'mongodb', '@neondatabase/serverless'])) {\n addFound(area, 'Database dependency found', 'package.json dependencies');\n } else {\r\n addMissing(area, 'Database dependency missing', 'package.json dependencies');\r\n }\r\n\r\n if (hasPath(ctx, [/prisma\\/schema\\.prisma$/, /migrations?\\//, /drizzle\\//, /schema\\.(ts|js|sql)$/])) {\n addFound(area, 'Schema or migration file found', 'repo paths');\n } else {\n addMissing(area, 'Schema or migration file missing', 'repo paths');\n }\n\n if (\n hasContent(ctx, [\n /prisma\\.[a-z0-9_]+\\.(find|create|update|delete|upsert|aggregate)/i,\n /\\bdb\\.(select|insert|update|delete|query)\\s*\\(/i,\n /\\bmongoose\\.model\\s*\\(/i,\n /\\bnew\\s+mongoclient\\s*\\(/i,\n /\\bcreateclient\\s*\\([^)]*supabase/i,\n /\\.from\\s*\\(\\s*['\"][a-z0-9_]+['\"]\\s*\\)/i\n ])\n ) {\n addFound(area, 'Database query usage found', 'repo evidence');\n }\n\n if (ctx.scan.stackSignals.hasSupabase || hasDep(ctx, ['@supabase/supabase-js', '@supabase/ssr'])) {\n if (\n hasPath(ctx, [/supabase\\/migrations\\/.*\\.sql$/, /\\/policies\\//, /rls/i]) ||\n hasContent(ctx, [/enable\\s+row\\s+level\\s+security/i, /create\\s+policy/i, /alter\\s+table[\\s\\S]{0,200}enable\\s+row\\s+level/i])\n ) {\n addFound(area, 'Supabase RLS policy evidence found', 'repo evidence');\n } else {\n addMissing(area, 'Supabase RLS policy evidence missing', 'repo evidence');\n }\n }\n\n if (\n hasEnvName(ctx, [\n 'DATABASE_URL',\n 'POSTGRES_URL',\n 'SUPABASE_URL',\n 'NEXT_PUBLIC_SUPABASE_URL',\n 'NEON_DATABASE_URL',\n 'PLANETSCALE_DATABASE_URL',\n 'MONGODB_URI',\n 'MONGODB_URL',\n 'TURSO_DATABASE_URL',\n 'TURSO_AUTH_TOKEN'\n ])\r\n ) {\r\n addFound(area, 'Database env names listed', 'non-secret scanned content');\r\n } else {\r\n addMissing(area, 'Database env names missing', 'non-secret scanned content');\r\n }\r\n\r\n addManual(area, 'Hosted DB project settings', 'external database dashboard');\r\n addManual(area, 'Production access policy', 'external database dashboard');\r\n}\r\n\r\nfunction applyPaymentRules(area: VerificationAreaSummary, ctx: VerificationContext): void {\r\n if (hasDep(ctx, ['stripe'])) {\r\n addFound(area, 'Stripe dependency found', 'package.json dependencies');\r\n } else if (hasDep(ctx, ['@paddle/paddle-js', 'paddle'])) {\r\n addFound(area, 'Paddle dependency found', 'package.json dependencies');\r\n } else {\r\n addMissing(area, 'Payment dependency missing', 'package.json dependencies');\r\n }\r\n\r\n if (\r\n hasPath(ctx, [\r\n /stripe\\/.*webhook/,\r\n /webhook.*stripe/,\r\n /paddle\\/.*webhook/,\r\n /webhook.*paddle/,\r\n /stripe\\/route\\.[jt]s$/,\r\n /paddle\\/route\\.[jt]s$/\r\n ]) ||\r\n hasContent(ctx, [/stripe[^.\\n]*webhook/, /webhook[^.\\n]*stripe/, /paddle[^.\\n]*webhook/, /webhook[^.\\n]*paddle/, /constructevent\\s*\\(/])\r\n ) {\r\n addFound(area, 'Payment webhook route found', 'repo paths or webhook handler code');\r\n } else {\r\n addMissing(area, 'Payment webhook route missing', 'repo paths or webhook handler code');\r\n }\r\n\r\n if (\r\n hasPath(ctx, [\r\n /checkout/,\r\n /billing/,\r\n /stripe\\/.*session/,\r\n /session.*stripe/,\r\n /paddle\\/.*session/,\r\n /session.*paddle/\r\n ]) ||\r\n hasContent(ctx, [/checkout\\.sessions\\.create\\s*\\(/, /createcheckoutsession/, /billing_portal/])\r\n ) {\r\n addFound(area, 'Checkout/session route found', 'repo paths or checkout code');\r\n } else {\r\n addMissing(area, 'Checkout/session route missing', 'repo paths or checkout code');\r\n }\r\n\r\n if (\r\n hasEnvName(ctx, [\r\n 'STRIPE_SECRET_KEY',\r\n 'STRIPE_WEBHOOK_SECRET',\r\n 'NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY',\r\n 'PADDLE_API_KEY',\r\n 'PADDLE_WEBHOOK_SECRET',\r\n 'NEXT_PUBLIC_PADDLE_CLIENT_TOKEN'\r\n ])\r\n ) {\r\n addFound(area, 'Payment env names listed', 'non-secret scanned content');\r\n } else {\r\n addMissing(area, 'Payment env names missing', 'non-secret scanned content');\r\n }\r\n\r\n addManual(area, 'Provider dashboard configuration', 'external payment dashboard');\r\n addManual(area, 'Webhook endpoint registered with provider', 'external payment dashboard');\r\n}\r\n\r\nfunction applyDeploymentRules(area: VerificationAreaSummary, ctx: VerificationContext): void {\n if (hasPath(ctx, [/vercel\\.json$/, /netlify\\.toml$/, /render\\.ya?ml$/, /dockerfile$/, /docker-compose\\.ya?ml$/])) {\n addFound(area, 'Deployment config found', 'repo paths');\n } else {\r\n addMissing(area, 'Deployment config missing', 'repo paths');\r\n }\r\n\r\n if (hasContent(ctx, [/\"build\"\\s*:/])) {\n addFound(area, 'Build script found', 'package scripts');\n } else {\n addMissing(area, 'Build script missing', 'package scripts');\n }\n\n if (ctx.scan.stackSignals.hasCI || hasPath(ctx, [/(^|\\/)\\.github\\/workflows\\/[^/]+\\.ya?ml$/, /(^|\\/)\\.gitlab-ci\\.yml$/, /(^|\\/)circle\\.yml$/])) {\n addFound(area, 'CI config found', 'repo paths');\n } else {\n addMissing(area, 'CI config missing', 'repo paths');\n }\n\n addManual(area, 'Hosting environment variables checked', 'hosting dashboard');\n addManual(area, 'DNS and production domain checked', 'hosting dashboard');\n}\r\n\r\nfunction applyMonitoringRules(area: VerificationAreaSummary, ctx: VerificationContext): void {\r\n if (hasDep(ctx, ['@sentry/nextjs', '@sentry/node', 'posthog-js', 'logrocket'])) {\r\n addFound(area, 'Monitoring dependency found', 'package.json dependencies');\r\n } else {\r\n addMissing(area, 'Monitoring dependency missing', 'package.json dependencies');\r\n }\r\n\r\n if (hasContent(ctx, [/sentry\\.init\\s*\\(/, /posthog\\.init\\s*\\(/, /logrocket\\.init\\s*\\(/])) {\r\n addFound(area, 'Monitoring SDK init found', 'non-secret scanned content');\r\n } else {\r\n addMissing(area, 'Monitoring SDK init missing', 'non-secret scanned content');\r\n }\r\n\r\n if (hasEnvName(ctx, ['SENTRY_DSN', 'NEXT_PUBLIC_SENTRY_DSN', 'NEXT_PUBLIC_POSTHOG_KEY', 'LOGROCKET_APP_ID'])) {\r\n addFound(area, 'Monitoring env names listed', 'non-secret scanned content');\r\n } else {\r\n addMissing(area, 'Monitoring env names missing', 'non-secret scanned content');\r\n }\r\n\r\n addManual(area, 'Dashboard receiving events', 'external monitoring dashboard');\r\n}\r\n\r\nfunction applySecurityRules(area: VerificationAreaSummary, ctx: VerificationContext): void {\r\n if (ctx.scan.stackSignals.hasRateLimit || hasDep(ctx, ['@upstash/ratelimit']) || hasContent(ctx, [/ratelimit/, /rate limit/])) {\r\n addFound(area, 'Rate limit evidence found', 'repo evidence');\r\n } else {\r\n addMissing(area, 'Rate limit evidence missing', 'repo evidence');\r\n }\r\n\r\n if (hasContent(ctx, [/bot protection/, /turnstile/, /recaptcha/, /hcaptcha/]) || hasDep(ctx, ['@marsidev/react-turnstile'])) {\r\n addFound(area, 'Bot protection evidence found', 'repo evidence');\r\n } else {\r\n addMissing(area, 'Bot protection evidence missing', 'repo evidence');\r\n }\r\n\r\n if (ctx.scan.stackSignals.hasEnvExample || hasPath(ctx, [/\\.env\\.example$/, /\\.env\\.sample$/, /example\\.env$/])) {\r\n addFound(area, '.env.example found', 'repo paths');\r\n } else {\r\n addMissing(area, '.env.example missing', 'repo paths');\r\n }\r\n\r\n if (ctx.secretPaths.size > 0) {\r\n addFound(area, 'Secret-like files excluded from scan content', 'secret filename list');\r\n }\r\n\r\n addManual(area, 'WAF and abuse controls', 'hosting or security dashboard');\r\n addManual(area, 'Real secret rotation', 'production secret manager');\r\n}\r\n\r\nfunction applyTestingRules(area: VerificationAreaSummary, ctx: VerificationContext): void {\n if (hasDep(ctx, ['vitest', 'jest', '@playwright/test', 'cypress', 'mocha']) || hasContent(ctx, [/\"test\"\\s*:/])) {\n addFound(area, 'Test tooling found', 'package.json dependencies or scripts');\n } else {\n addMissing(area, 'Test tooling missing', 'package.json dependencies or scripts');\n }\n\n if (hasDep(ctx, ['@playwright/test']) || hasPath(ctx, [/playwright\\.config\\.[jt]s$/])) {\n addFound(area, 'Playwright dependency found', 'package.json dependencies or config');\n }\n\n if (ctx.scan.stackSignals.hasTests || hasPath(ctx, [/\\.test\\.[jt]sx?$/, /\\.spec\\.[jt]sx?$/, /__tests__\\//])) {\n addFound(area, 'Test files found', 'repo paths');\n } else {\n addMissing(area, 'Test files missing', 'repo paths');\n }\n\n if (hasDep(ctx, ['@playwright/test']) && hasPath(ctx, [/\\.spec\\.[jt]sx?$/, /e2e\\//, /tests?\\//])) {\n addFound(area, 'End-to-end test files found', 'repo paths');\n }\n\n if (ctx.scan.stackSignals.hasCI || hasPath(ctx, [/(^|\\/)\\.github\\/workflows\\/[^/]+\\.ya?ml$/, /(^|\\/)\\.gitlab-ci\\.yml$/, /(^|\\/)circle\\.yml$/])) {\n addFound(area, 'CI workflow found', 'repo paths');\n }\n\n addManual(area, 'CI status', 'CI provider dashboard');\n}\n\r\nfunction applyLandingRules(area: VerificationAreaSummary, ctx: VerificationContext): void {\r\n if (\r\n ctx.scan.stackSignals.hasLanding ||\r\n hasPath(ctx, [/app\\/page\\.[jt]sx?$/, /pages\\/index\\.[jt]sx?$/, /landing\\//, /home\\.[jt]sx?$/])\r\n ) {\r\n addFound(area, 'Landing page found', 'repo paths');\r\n } else {\r\n addMissing(area, 'Landing page missing', 'repo paths');\r\n }\r\n\r\n if (hasPath(ctx, [/pricing/, /account/, /onboarding/])) {\r\n addFound(area, 'Pricing/account/onboarding path found', 'repo paths');\r\n } else {\r\n addMissing(area, 'Pricing/account/onboarding path missing', 'repo paths');\r\n }\r\n\r\n if (hasContent(ctx, [/analytics/, /posthog/, /gtag\\(/, /plausible/])) {\n addFound(area, 'Funnel or analytics evidence found', 'non-secret scanned content');\n } else {\n addMissing(area, 'Funnel or analytics evidence missing', 'non-secret scanned content');\n }\n\n if (ctx.scan.stackSignals.hasRobots && ctx.scan.stackSignals.hasSitemap) {\n addFound(area, 'SEO crawl files found', 'repo paths');\n } else {\n addMissing(area, 'SEO crawl files missing', 'repo paths');\n }\n\n addManual(area, 'Conversion quality', 'manual product review');\n}\n\r\nfunction applyFrontendRules(area: VerificationAreaSummary, ctx: VerificationContext): void {\r\n if (hasDep(ctx, ['react', 'vue', 'svelte', '@angular/core']) || hasPath(ctx, [/src\\/.*\\.[jt]sx$/, /app\\/.*\\.[jt]sx$/])) {\r\n addFound(area, 'Frontend framework evidence found', 'repo evidence');\r\n } else {\r\n addMissing(area, 'Frontend framework evidence missing', 'repo evidence');\r\n }\r\n\r\n if (ctx.scan.stackSignals.hasLoadingStates || hasPath(ctx, [/loading\\.[jt]sx?$/]) || hasContent(ctx, [/loading/i])) {\r\n addFound(area, 'Loading state evidence found', 'repo evidence');\r\n } else {\r\n addMissing(area, 'Loading state evidence missing', 'repo evidence');\r\n }\r\n\r\n addManual(area, 'Responsive UX review', 'manual product review');\r\n}\r\n\r\nfunction applyBackendRules(area: VerificationAreaSummary, ctx: VerificationContext): void {\n if (hasPath(ctx, [/api\\//, /route\\.[jt]s$/, /server\\.[jt]s$/, /controllers?\\//])) {\r\n addFound(area, 'Backend route evidence found', 'repo paths');\r\n } else {\r\n addMissing(area, 'Backend route evidence missing', 'repo paths');\r\n }\r\n\r\n if (\n hasDep(ctx, ['zod', 'joi', 'yup', 'valibot', '@sinclair/typebox', 'class-validator']) ||\n hasContent(ctx, [\n /\\bzod\\b/,\n /\\bjoi\\b/,\n /\\byup\\b/,\n /\\bvalibot\\b/,\n /from\\s+['\"]joi['\"]/,\n /require\\s*\\(\\s*['\"]joi['\"]\\s*\\)/,\n /\\.safeparse\\s*\\(/,\n /\\.parse\\s*\\(/,\n /request validation/\n ])\n ) {\n addFound(area, 'Input validation evidence found', 'non-secret scanned content');\r\n } else {\r\n addMissing(area, 'Input validation evidence missing', 'non-secret scanned content');\r\n }\r\n\r\n addManual(area, 'Production data behavior reviewed', 'manual product review');\r\n}\r\n\r\nfunction applyAppFlowRules(area: VerificationAreaSummary, ctx: VerificationContext): void {\r\n if (hasPath(ctx, [/onboarding/, /dashboard/, /account/, /settings/])) {\r\n addFound(area, 'Core app flow paths found', 'repo paths');\r\n } else {\r\n addMissing(area, 'Core app flow paths missing', 'repo paths');\r\n }\r\n\r\n if (hasContent(ctx, [/redirect\\(/, /router\\.push/, /navigate\\(/])) {\r\n addFound(area, 'Navigation flow evidence found', 'non-secret scanned content');\r\n } else {\r\n addMissing(area, 'Navigation flow evidence missing', 'non-secret scanned content');\r\n }\r\n\r\n addManual(area, 'End-to-end user journey checked', 'manual product review');\r\n}\r\n\r\nfunction applyErrorHandlingRules(area: VerificationAreaSummary, ctx: VerificationContext): void {\n if (\n ctx.scan.stackSignals.hasErrorBoundary ||\n hasPath(ctx, [/error\\.[jt]sx?$/, /error-boundary/i, /errorboundary/i]) ||\n hasContent(ctx, [/componentdidcatch/i, /\\berrorboundary\\b/i, /react\\.component/i])\n ) {\n addFound(area, 'Error boundary evidence found', 'repo evidence');\n } else {\n addMissing(area, 'Error boundary evidence missing', 'repo evidence');\r\n }\r\n\r\n if (hasContent(ctx, [/try\\s*{/, /\\.catch\\s*\\(/, /throw new error/])) {\r\n addFound(area, 'Runtime error handling evidence found', 'non-secret scanned content');\r\n } else {\r\n addMissing(area, 'Runtime error handling evidence missing', 'non-secret scanned content');\r\n }\r\n\n addManual(area, 'Production failure paths reviewed', 'manual product review');\n}\n\nfunction applyProductionConnectionEvidence(\n byArea: VerificationSummary['byArea'],\n productionConnections: ProductionConnectionSummaryPayload\n): void {\n const summaries = collectProductionConnectionSummaries(productionConnections);\n\n for (const summary of summaries) {\n if (!summary || summary.source !== 'detected' || !summary.provider) {\n continue;\n }\n\n const area = byArea[summary.area as VerificationArea];\n if (!area) {\n continue;\n }\n\n const provider = providerLabel(summary.provider);\n const detail = summary.signals.length > 0 ? summary.signals.slice(0, 4).join('; ') : undefined;\n addFound(area, `${provider} detected by scanner`, 'production connection scanner', detail);\n\n if (summary.status.includes('needs-env')) {\n addMissing(area, `${provider} env evidence missing`, 'production connection scanner');\n }\n if (summary.status.includes('needs-webhook')) {\n addMissing(area, `${provider} webhook evidence missing`, 'production connection scanner');\n }\n }\n}\n\nfunction collectProductionConnectionSummaries(\n productionConnections: ProductionConnectionSummaryPayload\n): ProductionConnectionSummary[] {\n const seen = new Set<string>();\n const summaries: ProductionConnectionSummary[] = [];\n\n function add(summary: ProductionConnectionSummary | undefined): void {\n if (!summary || !summary.provider) {\n return;\n }\n const key = `${summary.area}:${summary.provider}:${summary.source}`;\n if (seen.has(key)) {\n return;\n }\n seen.add(key);\n summaries.push(summary);\n }\n\n for (const summary of Object.values(productionConnections.byArea)) {\n add(summary);\n }\n for (const summary of productionConnections.items) {\n add(summary);\n }\n for (const summary of productionConnections.stackRow) {\n add(summary);\n }\n\n return summaries;\n}\n\nfunction providerLabel(provider: string): string {\n return PROVIDER_LABELS[provider] ?? provider.replace(/(^|-)([a-z])/g, (_: string, prefix: string, letter: string) =>\n `${prefix === '-' ? ' ' : ''}${letter.toUpperCase()}`\n );\n}\n", "import { join } from 'node:path';\r\nimport { deepScanWorkspace } from '../../../src/station/fileScanner';\r\nimport {\r\n createStationOrchestrator,\r\n isManagedRequiredResult,\r\n isManagedSessionInvalidResult,\r\n isScanLimitResult,\r\n type StationRunResult\r\n} from '../../../src/station/orchestrator';\r\nimport { runManagedStation } from '../../../src/station/backendClient';\r\nimport type { ProductionConnectionChoices } from '../../../src/station/productionConnections';\r\nimport { productionProvidersByArea, providerLabel } from '../../../src/station/providerRegistry';\r\nimport type { CliProviderOption, CliScanArtifact, StationRunSuccess } from './types';\r\nimport { loadStackChoicesFile } from './config';\r\n\r\nfunction computeProductionCorePercent(missionGraph: StationRunResult['missionGraph']): number {\r\n const areas = missionGraph.areas ?? [];\r\n if (areas.length === 0) {\r\n return 0;\r\n }\r\n const sum = areas.reduce((acc, area) => acc + (area.readinessPercent ?? 0), 0);\r\n return Math.round(sum / areas.length);\r\n}\r\n\r\nfunction buildProviderOptions(): Record<string, CliProviderOption[]> {\r\n const byArea = productionProvidersByArea();\r\n const options: Record<string, CliProviderOption[]> = {};\r\n for (const [area, providers] of Object.entries(byArea)) {\r\n options[area] = providers.map((provider) => ({ provider, label: providerLabel(provider) }));\r\n }\r\n return options;\r\n}\r\n\r\nfunction toArtifact(\r\n workspacePath: string,\r\n result: StationRunSuccess,\r\n selectedProviders: Record<string, string>\r\n): CliScanArtifact {\r\n return {\r\n version: 1,\r\n scannedAt: new Date().toISOString(),\r\n workspacePath,\r\n score: result.score,\r\n scoreLabel: result.scoreLabel,\r\n summary: result.summary,\r\n archetype: result.archetype,\r\n gaps: result.gaps,\r\n missionGraph: result.missionGraph,\r\n stackWiring: result.stackWiring,\r\n providerRegistry: result.providerRegistry,\r\n verificationSummary: result.verificationSummary,\r\n productionCorePercent: computeProductionCorePercent(result.missionGraph),\r\n providerOptions: buildProviderOptions(),\r\n selectedProviders,\r\n usage: result.usage\r\n };\r\n}\r\n\r\nasync function loadProductionChoices(workspacePath: string): Promise<ProductionConnectionChoices | undefined> {\r\n const file = await loadStackChoicesFile(workspacePath);\r\n if (Object.keys(file.choices).length === 0) {\r\n return undefined;\r\n }\r\n // The orchestrator normalizes this shape via `normalizeProductionChoice`.\r\n return file as unknown as ProductionConnectionChoices;\r\n}\r\n\r\nexport type RunScanOptions = {\r\n workspacePath?: string;\r\n accessToken: string;\r\n apiBaseUrl: string;\r\n};\r\n\r\nexport type RunScanResult =\r\n | { ok: true; artifact: CliScanArtifact }\r\n | { ok: false; kind: 'scan_limit'; upgradeUrl: string }\r\n | { ok: false; kind: 'auth_required'; message: string }\r\n | { ok: false; kind: 'session_invalid'; message: string }\r\n | { ok: false; kind: 'error'; message: string };\r\n\r\nexport async function runProjectScan(options: RunScanOptions): Promise<RunScanResult> {\r\n const workspacePath = options.workspacePath ?? process.cwd();\r\n const orchestrator = createStationOrchestrator({\r\n scanWorkspace: (root) => deepScanWorkspace(root),\r\n getManagedAccessToken: async () => options.accessToken,\r\n runManagedStation: async (token, payload) => runManagedStation(options.apiBaseUrl, token, payload),\r\n getProductionConnectionChoices: () => loadProductionChoices(workspacePath),\r\n isLocalStationFallbackAllowed: async () => false,\r\n fetchStationOutput: async () => {\r\n throw new Error('Local OpenAI fallback is disabled in the CLI. Use `viberaven login`.');\r\n }\r\n });\r\n\r\n try {\r\n const result = await orchestrator.run({\r\n workspaceRoot: workspacePath,\r\n prompt: 'Full station scan for CLI launch report',\r\n configuration: undefined\r\n });\r\n\r\n if (isScanLimitResult(result)) {\r\n return { ok: false, kind: 'scan_limit', upgradeUrl: result.upgradeUrl };\r\n }\r\n if (isManagedRequiredResult(result)) {\r\n return { ok: false, kind: 'auth_required', message: result.message };\r\n }\r\n if (isManagedSessionInvalidResult(result)) {\r\n return { ok: false, kind: 'session_invalid', message: result.message };\r\n }\r\n\r\n const stackFile = await loadStackChoicesFile(workspacePath);\r\n const selectedProviders: Record<string, string> = {};\r\n for (const [area, choice] of Object.entries(stackFile.choices)) {\r\n if (choice && typeof choice.provider === 'string') {\r\n selectedProviders[area] = choice.provider;\r\n }\r\n }\r\n const artifact = toArtifact(workspacePath, result as StationRunSuccess, selectedProviders);\r\n return { ok: true, artifact };\r\n } catch (error) {\r\n const message = error instanceof Error ? error.message : String(error);\r\n return { ok: false, kind: 'error', message };\r\n }\r\n}\r\n\r\nexport function defaultPromptPath(workspacePath: string): string {\r\n return join(workspacePath, '.viberaven', 'last-scan.json');\r\n}\r\n", "import { mkdir, writeFile } from 'node:fs/promises';\r\nimport { join } from 'node:path';\r\nimport type { CliScanArtifact } from './types';\r\nimport { generateAgentSummary } from './report/agentSummary';\r\nimport { generateReportHtml } from './report/reportHtml';\r\nimport { getProjectArtifactsDir } from './config';\r\n\r\nexport interface WriteArtifactsOptions {\r\n artifact: CliScanArtifact;\r\n cwd?: string;\r\n}\r\n\r\nexport interface WriteArtifactsResult {\r\n dir: string;\r\n jsonPath: string;\r\n summaryPath: string;\r\n reportPath: string;\r\n}\r\n\r\nexport async function writeScanArtifacts(options: WriteArtifactsOptions): Promise<WriteArtifactsResult> {\r\n const cwd = options.cwd ?? options.artifact.workspacePath;\r\n const dir = getProjectArtifactsDir(cwd);\r\n await mkdir(dir, { recursive: true });\r\n\r\n const jsonPath = join(dir, 'last-scan.json');\r\n const summaryPath = join(dir, 'agent-summary.md');\r\n const reportPath = join(dir, 'report.html');\r\n\r\n const json = `${JSON.stringify(options.artifact, null, 2)}\\n`;\r\n const summary = generateAgentSummary(options.artifact);\r\n const html = generateReportHtml(options.artifact);\r\n\r\n await writeFile(jsonPath, json, 'utf-8');\r\n await writeFile(summaryPath, summary, 'utf-8');\r\n await writeFile(reportPath, html, 'utf-8');\r\n\r\n return { dir, jsonPath, summaryPath, reportPath };\r\n}\r\n", "import type { CliScanArtifact } from '../types';\r\nimport type { Gap } from '../../../../src/station/types';\r\n\r\nconst SEVERITY_ORDER: Record<Gap['severity'], number> = {\r\n critical: 0,\r\n warning: 1,\r\n info: 2\r\n};\r\n\r\nfunction sortGaps(gaps: Gap[]): Gap[] {\r\n return [...gaps].sort((a, b) => {\r\n const sev = SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity];\r\n if (sev !== 0) {\r\n return sev;\r\n }\r\n return a.title.localeCompare(b.title);\r\n });\r\n}\r\n\r\nexport function generateAgentSummary(artifact: CliScanArtifact): string {\r\n const lines: string[] = [];\r\n const topGaps = sortGaps(artifact.gaps).slice(0, 8);\r\n\r\n lines.push('# VibeRaven agent summary', '');\r\n lines.push(`Scanned: \\`${artifact.workspacePath}\\``);\r\n lines.push(`At: ${artifact.scannedAt}`);\r\n lines.push(\r\n `Production core: **${artifact.productionCorePercent}%** \u00B7 Model score: **${artifact.score}** (${artifact.scoreLabel})`\r\n );\r\n lines.push('');\r\n lines.push('## Summary');\r\n lines.push(artifact.summary || '_No summary returned._');\r\n lines.push('');\r\n lines.push('## Mission map (repo wiring)');\r\n lines.push('');\r\n lines.push('| Area | Provider | Readiness | Notes |');\r\n lines.push('|------|----------|-----------|-------|');\r\n\r\n for (const area of artifact.missionGraph.areas ?? []) {\r\n for (const mission of area.providerMissions) {\r\n const failed = mission.checks.filter(\r\n (c) => c.status === 'missing' || c.status === 'failed' || c.status === 'needs-connection'\r\n ).length;\r\n const notes =\r\n failed > 0\r\n ? `${failed} open check${failed === 1 ? '' : 's'}`\r\n : `${mission.readinessPercent}% repo checks`;\r\n lines.push(\r\n `| ${area.label} | ${mission.providerLabel} | ${mission.readinessPercent}% | ${notes} |`\r\n );\r\n }\r\n }\r\n\r\n lines.push('');\r\n lines.push('## Top launch gaps (model)');\r\n if (topGaps.length === 0) {\r\n lines.push('_No model gaps returned \u2014 rely on mission map checks above._');\r\n } else {\r\n topGaps.forEach((gap, index) => {\r\n lines.push(\r\n `${index + 1}. **${gap.title}** (\\`${gap.id}\\`, ${gap.severity}, map: \\`${gap.primaryMapCategory}\\`)`\r\n );\r\n lines.push(` - ${gap.detail}`);\r\n lines.push(` - Prompt: \\`viberaven prompt --gap ${gap.id}\\``);\r\n });\r\n }\r\n\r\n lines.push('');\r\n lines.push('## Agent workflow');\r\n lines.push('1. Pick the highest-severity gap unless the user names an area or provider.');\r\n lines.push('2. Run `viberaven prompt --gap <id>` (or read `copyPrompt` from `last-scan.json`).');\r\n lines.push('3. Implement the fix in the repo.');\r\n lines.push('4. Run `npx -y @viberaven/cli@beta scan` again to verify readiness improved.');\r\n lines.push('5. Tell the user to open `.viberaven/report.html` for the visual mission map.');\r\n lines.push('');\r\n\r\n if (artifact.usage) {\r\n lines.push('## Account usage');\r\n lines.push(\r\n `- Plan: ${artifact.usage.plan} \u00B7 Scans used: ${artifact.usage.used}/${artifact.usage.limit} (${artifact.usage.period})`\r\n );\r\n lines.push('');\r\n }\r\n\r\n return `${lines.join('\\n')}\\n`;\r\n}\r\n", "// Vendored from media/station.css (studio map visual language) so the CLI\r\n// launch report matches the VibeRaven extension map. Kept standalone \u2014 no\r\n// VS Code webview variables, no plan gating.\r\nexport const REPORT_STYLES = `\r\n:root {\r\n color-scheme: dark;\r\n --vr-gold: rgba(232, 189, 98, 0.92);\r\n --vr-bg: #050608;\r\n --vr-panel: #0c0f12;\r\n --vr-line: rgba(255, 255, 255, 0.1);\r\n --vr-text: rgba(245, 242, 235, 0.96);\r\n --vr-muted: rgba(245, 242, 235, 0.62);\r\n --vr-ease-out: cubic-bezier(0.22, 1, 0.36, 1);\r\n}\r\n* { box-sizing: border-box; }\r\nbody {\r\n margin: 0;\r\n font-family: \"Inter\", \"Segoe UI\", system-ui, sans-serif;\r\n background:\r\n radial-gradient(circle at 50% -10%, rgba(232, 189, 98, 0.08), transparent 45%),\r\n var(--vr-bg);\r\n color: var(--vr-text);\r\n min-height: 100vh;\r\n}\r\n.report-header {\r\n display: flex; justify-content: space-between; align-items: center;\r\n gap: 16px; padding: 18px 26px; border-bottom: 1px solid var(--vr-line);\r\n}\r\n.report-header h1 { margin: 0; font-size: 1.05rem; font-weight: 800; letter-spacing: 0.04em; }\r\n.report-header p { margin: 4px 0 0; color: var(--vr-muted); font-size: 0.8rem; }\r\n.report-score {\r\n padding: 6px 14px; border-radius: 999px; border: 1px solid rgba(232, 189, 98, 0.4);\r\n color: var(--vr-gold); font-size: 0.82rem; font-weight: 800; letter-spacing: 0.04em;\r\n}\r\n.report-workspace {\r\n display: grid; grid-template-columns: minmax(0, 1fr) minmax(320px, 420px);\r\n gap: 18px; padding: 22px; align-items: start;\r\n}\r\n@media (max-width: 920px) { .report-workspace { grid-template-columns: 1fr; } }\r\n\r\n.studio-system-map {\r\n position: relative; min-height: 600px; display: grid;\r\n grid-template-rows: minmax(560px, 1fr); gap: 14px; padding: 14px;\r\n border-radius: 22px; border: 1px solid rgba(232, 189, 98, 0.2);\r\n background:\r\n radial-gradient(circle at 50% 48%, rgba(232, 189, 98, 0.14), transparent 18%),\r\n radial-gradient(circle at 20% 20%, rgba(91, 205, 194, 0.08), transparent 25%),\r\n radial-gradient(circle at 80% 76%, rgba(248, 113, 113, 0.06), transparent 24%),\r\n linear-gradient(160deg, rgba(16, 16, 18, 0.98), rgba(5, 6, 8, 0.99));\r\n box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.07), 0 18px 48px rgba(0, 0, 0, 0.42);\r\n overflow: hidden;\r\n}\r\n.studio-node-layer {\r\n position: relative; min-height: 560px; max-width: 680px;\r\n width: min(100%, 680px); justify-self: center; overflow: hidden; border-radius: 16px;\r\n}\r\n.studio-connector-layer {\r\n position: absolute; inset: 32px; pointer-events: none; opacity: 0.5;\r\n background:\r\n radial-gradient(circle at 50% 50%, transparent 0 88px, rgba(232, 189, 98, 0.26) 89px 90px, transparent 91px),\r\n linear-gradient(90deg, transparent 8%, rgba(232, 189, 98, 0.18) 49%, rgba(232, 189, 98, 0.18) 51%, transparent 92%),\r\n linear-gradient(180deg, transparent 10%, rgba(232, 189, 98, 0.14) 49%, rgba(232, 189, 98, 0.14) 51%, transparent 90%);\r\n mask-image: radial-gradient(circle at center, black, transparent 76%);\r\n}\r\n.studio-core-node {\r\n position: absolute; left: 50%; top: 50%; z-index: 3; width: 132px; height: 132px;\r\n transform: translate(-50%, -50%); display: grid; place-items: center; align-content: center;\r\n gap: 5px; border-radius: 999px; border: 1px solid rgba(232, 189, 98, 0.48);\r\n background:\r\n radial-gradient(circle at 50% 22%, rgba(255, 233, 166, 0.24), transparent 42%),\r\n linear-gradient(180deg, rgba(42, 32, 13, 0.98), rgba(10, 10, 12, 0.99));\r\n color: rgba(255, 248, 226, 0.98); text-align: center;\r\n box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.12), 0 18px 44px rgba(0, 0, 0, 0.48), 0 0 0 10px rgba(232, 189, 98, 0.05);\r\n}\r\n.studio-core-node span { color: var(--vr-gold); font-size: 11px; font-weight: 900; letter-spacing: 0.12em; line-height: 1; }\r\n.studio-core-node strong { font-size: 30px; font-weight: 900; line-height: 1; }\r\n.studio-core-node small { color: rgba(245, 242, 235, 0.66); font-size: 10px; font-weight: 760; letter-spacing: 0.08em; text-transform: uppercase; }\r\n\r\n.studio-node {\r\n position: absolute; z-index: 2; width: 96px; height: 96px; display: grid;\r\n grid-template-columns: 10px minmax(0, 1fr); align-items: center; align-content: center;\r\n gap: 2px 6px; padding: 12px 10px; border-radius: 999px;\r\n border: 1px solid rgba(255, 255, 255, 0.13);\r\n background: linear-gradient(160deg, rgba(22, 23, 26, 0.96), rgba(8, 9, 11, 0.99));\r\n color: var(--vr-text); font: inherit; text-align: left; cursor: pointer;\r\n transform: translate(-50%, -50%);\r\n box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.07), 0 12px 28px rgba(0, 0, 0, 0.34);\r\n transition: transform 170ms var(--vr-ease-out), border-color 150ms ease, box-shadow 150ms ease;\r\n}\r\n.studio-node:hover { transform: translate(-50%, calc(-50% - 2px)); border-color: rgba(232, 189, 98, 0.34); }\r\n.studio-node:focus-visible { outline: 2px solid rgba(232, 189, 98, 0.78); outline-offset: 3px; }\r\n.studio-node--selected {\r\n border-color: rgba(232, 189, 98, 0.66);\r\n background:\r\n radial-gradient(circle at 20% 10%, rgba(232, 189, 98, 0.18), transparent 42%),\r\n linear-gradient(160deg, rgba(30, 25, 16, 0.98), rgba(9, 9, 11, 0.99));\r\n box-shadow: inset 0 1px 0 rgba(255, 248, 226, 0.1), 0 0 0 1px rgba(232, 189, 98, 0.16), 0 16px 36px rgba(0, 0, 0, 0.4);\r\n}\r\n.studio-node--critical { border-color: rgba(248, 113, 113, 0.58); }\r\n.studio-node--warning { border-color: rgba(245, 158, 11, 0.5); }\r\n.studio-node--in-project {\r\n border-color: rgba(93, 240, 175, 0.66);\r\n background:\r\n radial-gradient(circle at 50% 0%, rgba(93, 240, 175, 0.18), transparent 48%),\r\n linear-gradient(160deg, rgba(7, 34, 28, 0.92), rgba(4, 10, 14, 0.98));\r\n}\r\n.studio-node__dot { grid-row: 1 / 3; width: 9px; height: 9px; border-radius: 999px; background: #d4af37; box-shadow: 0 0 0 4px rgba(212, 175, 55, 0.12); }\r\n.studio-node--critical .studio-node__dot { background: #ef6f6f; box-shadow: 0 0 0 4px rgba(239, 111, 111, 0.13); }\r\n.studio-node--warning .studio-node__dot { background: #f0b94e; box-shadow: 0 0 0 4px rgba(240, 185, 78, 0.13); }\r\n.studio-node__title, .studio-node__provider, .studio-node__meta { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\r\n.studio-node__title { color: rgba(255, 253, 247, 0.98); font-size: 10.5px; font-weight: 860; line-height: 1.05; }\r\n.studio-node__provider { color: rgba(245, 242, 235, 0.64); font-size: 9px; font-weight: 700; line-height: 1.05; }\r\n.studio-node__meta { grid-column: 2; color: var(--vr-gold); font-size: 9px; font-weight: 850; line-height: 1.05; }\r\n.studio-node--critical .studio-node__meta { color: #ef9a9a; }\r\n\r\n.studio-node--appFlow { left: 22%; top: 18%; }\r\n.studio-node--frontend { left: 50%; top: 12%; }\r\n.studio-node--backend { left: 78%; top: 18%; }\r\n.studio-node--auth { left: 14%; top: 38%; }\r\n.studio-node--database { left: 50%; top: 32%; }\r\n.studio-node--payments { left: 86%; top: 40%; }\r\n.studio-node--deployment { left: 18%; top: 64%; }\r\n.studio-node--monitoring { left: 50%; top: 68%; }\r\n.studio-node--security { left: 82%; top: 64%; }\r\n.studio-node--testing { left: 28%; top: 84%; }\r\n.studio-node--landing { left: 50%; top: 88%; }\r\n.studio-node--errorHandling { left: 72%; top: 84%; }\r\n\r\n.studio-setup-panel {\r\n border: 1px solid var(--vr-line); border-radius: 18px; background: var(--vr-panel);\r\n padding: 20px 20px 26px; position: sticky; top: 22px; max-height: calc(100vh - 44px); overflow: auto;\r\n}\r\n.studio-setup-panel__eyebrow { margin: 0; font-size: 0.66rem; letter-spacing: 0.14em; text-transform: uppercase; color: var(--vr-muted); }\r\n.studio-setup-panel__title { margin: 6px 0 0; font-size: 1.05rem; font-weight: 800; }\r\n.studio-setup-panel__hint { margin: 6px 0 0; color: var(--vr-muted); font-size: 0.82rem; line-height: 1.5; }\r\n.panel-section { margin-top: 18px; }\r\n.panel-section h3 { margin: 0 0 10px; font-size: 0.7rem; letter-spacing: 0.12em; text-transform: uppercase; color: var(--vr-muted); }\r\n.provider-switch { display: flex; flex-wrap: wrap; gap: 6px; }\r\n.provider-chip {\r\n border: 1px solid var(--vr-line); background: rgba(255,255,255,0.02); color: var(--vr-text);\r\n border-radius: 999px; padding: 5px 11px; font-size: 0.76rem; cursor: pointer; transition: border-color 0.15s;\r\n}\r\n.provider-chip:hover { border-color: rgba(232, 189, 98, 0.45); }\r\n.provider-chip--active { border-color: rgba(93, 240, 175, 0.66); color: rgba(111, 255, 190, 0.96); background: rgba(93, 240, 175, 0.08); }\r\n.switch-hint { margin-top: 8px; font-size: 0.75rem; color: var(--vr-muted); }\r\n.switch-hint code { color: var(--vr-gold); }\r\n.check, .gap-card { border: 1px solid var(--vr-line); border-radius: 12px; padding: 10px 12px; margin-bottom: 8px; background: rgba(0,0,0,0.22); }\r\n.check strong, .gap-card strong { display: block; font-size: 0.86rem; }\r\n.check .status, .gap-card p { margin: 4px 0 0; font-size: 0.78rem; color: var(--vr-muted); line-height: 1.45; }\r\n.status-passed { color: rgba(111, 255, 190, 0.96); }\r\n.status-missing, .status-failed { color: #ef9a9a; }\r\n.status-needs-connection { color: #f0b94e; }\r\n.copy-btn { margin-top: 8px; border: 1px solid var(--vr-line); background: transparent; color: var(--vr-text); border-radius: 8px; padding: 6px 10px; font-size: 0.76rem; cursor: pointer; }\r\n.copy-btn:hover { border-color: rgba(232, 189, 98, 0.45); }\r\n`;\r\n", "import type { CliScanArtifact } from '../types';\r\nimport type { MissionArea } from '../../../../src/station/types';\r\nimport { REPORT_STYLES } from './reportStyles';\r\n\r\nfunction escapeHtml(value: string): string {\r\n return value\r\n .replace(/&/g, '&amp;')\r\n .replace(/</g, '&lt;')\r\n .replace(/>/g, '&gt;')\r\n .replace(/\"/g, '&quot;');\r\n}\r\n\r\n/** Fixed 12-section order + labels, matching the extension Mission Map. */\r\nconst CATEGORY_META: Array<{ key: string; label: string }> = [\r\n { key: 'appFlow', label: 'App Flow' },\r\n { key: 'frontend', label: 'Frontend' },\r\n { key: 'backend', label: 'Backend / API' },\r\n { key: 'auth', label: 'Auth' },\r\n { key: 'database', label: 'Database' },\r\n { key: 'payments', label: 'Payments' },\r\n { key: 'deployment', label: 'Deployment' },\r\n { key: 'monitoring', label: 'Monitoring' },\r\n { key: 'security', label: 'Security' },\r\n { key: 'testing', label: 'Testing' },\r\n { key: 'landing', label: 'Landing / Onboarding' },\r\n { key: 'errorHandling', label: 'Error Handling' }\r\n];\r\n\r\nfunction gapCountForArea(artifact: CliScanArtifact, areaKey: string): number {\r\n return artifact.gaps.filter((g) => g.primaryMapCategory === areaKey).length;\r\n}\r\n\r\nfunction openChecksForArea(area: MissionArea | undefined): number {\r\n if (!area) {\r\n return 0;\r\n }\r\n return area.providerMissions\r\n .flatMap((m) => m.checks)\r\n .filter((c) => c.status === 'missing' || c.status === 'failed' || c.status === 'needs-connection').length;\r\n}\r\n\r\nfunction buildNodeHtml(artifact: CliScanArtifact, meta: { key: string; label: string }): string {\r\n const area = (artifact.missionGraph.areas ?? []).find((a) => a.key === meta.key);\r\n const mission = area?.providerMissions[0];\r\n const provider = mission?.providerLabel ?? '\u2014';\r\n const readiness = mission?.readinessPercent ?? area?.readinessPercent ?? 0;\r\n const openChecks = openChecksForArea(area);\r\n const modelGaps = gapCountForArea(artifact, meta.key);\r\n\r\n const stateClass =\r\n modelGaps > 0\r\n ? ' studio-node--critical'\r\n : openChecks > 0\r\n ? ' studio-node--warning'\r\n : area\r\n ? ' studio-node--in-project'\r\n : '';\r\n\r\n const meta1 =\r\n modelGaps > 0\r\n ? `GAP ${modelGaps}`\r\n : openChecks > 0\r\n ? `${openChecks} stack fix${openChecks === 1 ? '' : 'es'}`\r\n : `${readiness}% health`;\r\n\r\n return `<button type=\"button\" class=\"studio-node studio-node--${escapeHtml(meta.key)}${stateClass}\" data-area-key=\"${escapeHtml(meta.key)}\" aria-label=\"${escapeHtml(meta.label)}\">\r\n <span class=\"studio-node__dot\" aria-hidden=\"true\"></span>\r\n <span class=\"studio-node__title\">${escapeHtml(meta.label)}</span>\r\n <span class=\"studio-node__provider\">${escapeHtml(provider)}</span>\r\n <span class=\"studio-node__meta\">${escapeHtml(meta1)}</span>\r\n </button>`;\r\n}\r\n\r\nexport function generateReportHtml(artifact: CliScanArtifact): string {\r\n const dataJson = JSON.stringify(artifact).replace(/</g, '\\\\u003c');\r\n const nodesHtml = CATEGORY_META.map((meta) => buildNodeHtml(artifact, meta)).join('\\n');\r\n\r\n return `<!DOCTYPE html>\r\n<html lang=\"en\">\r\n<head>\r\n <meta charset=\"utf-8\" />\r\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\r\n <title>VibeRaven Launch Report</title>\r\n <style>${REPORT_STYLES}</style>\r\n</head>\r\n<body>\r\n <header class=\"report-header\">\r\n <div>\r\n <h1>VIBERAVEN \u00B7 LAUNCH REPORT</h1>\r\n <p>${escapeHtml(artifact.workspacePath)} \u00B7 ${escapeHtml(artifact.scannedAt)}</p>\r\n </div>\r\n <div class=\"report-score\">Model ${artifact.score} \u00B7 ${escapeHtml(artifact.scoreLabel)}</div>\r\n </header>\r\n <div class=\"report-workspace\">\r\n <section class=\"studio-system-map\" aria-label=\"Production system map\">\r\n <div class=\"studio-node-layer\">\r\n <div class=\"studio-connector-layer\" aria-hidden=\"true\"></div>\r\n <div class=\"studio-core-node\" aria-label=\"Production core\">\r\n <span>VIBERAVEN</span>\r\n <strong>${artifact.productionCorePercent}%</strong>\r\n <small>Production core</small>\r\n </div>\r\n ${nodesHtml}\r\n </div>\r\n </section>\r\n <aside class=\"studio-setup-panel\" id=\"detail-panel\" aria-live=\"polite\">\r\n <p class=\"studio-setup-panel__eyebrow\">No section selected</p>\r\n <p class=\"studio-setup-panel__title\">Choose a node on the map</p>\r\n <p class=\"studio-setup-panel__hint\">${escapeHtml(artifact.summary || 'Click any provider node to see stack checks, launch gaps, and switch providers.')}</p>\r\n </aside>\r\n </div>\r\n <script type=\"application/json\" id=\"scan-data\">${dataJson}</script>\r\n <script>${CLIENT_SCRIPT}</script>\r\n</body>\r\n</html>`;\r\n}\r\n\r\nconst CLIENT_SCRIPT = `\r\n(function () {\r\n var artifact = JSON.parse(document.getElementById('scan-data').textContent);\r\n var panel = document.getElementById('detail-panel');\r\n var areas = (artifact.missionGraph && artifact.missionGraph.areas) || [];\r\n var gaps = artifact.gaps || [];\r\n var providerOptions = artifact.providerOptions || {};\r\n var selectedProviders = artifact.selectedProviders || {};\r\n var LABELS = {\r\n appFlow: 'App Flow', frontend: 'Frontend', backend: 'Backend / API', auth: 'Auth',\r\n database: 'Database', payments: 'Payments', deployment: 'Deployment', monitoring: 'Monitoring',\r\n security: 'Security', testing: 'Testing', landing: 'Landing / Onboarding', errorHandling: 'Error Handling'\r\n };\r\n\r\n function esc(s) {\r\n return String(s == null ? '' : s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');\r\n }\r\n function statusClass(status) {\r\n if (status === 'passed') return 'status-passed';\r\n if (status === 'needs-connection') return 'status-needs-connection';\r\n return 'status-missing';\r\n }\r\n\r\n function providerSwitchHtml(areaKey, mission) {\r\n var options = providerOptions[areaKey];\r\n if (!options || !options.length) return '';\r\n var current = selectedProviders[areaKey] || (mission ? (mission.provider || '') : '');\r\n var chips = options.map(function (opt) {\r\n var active = String(opt.provider).toLowerCase() === String(current).toLowerCase();\r\n return '<button type=\"button\" class=\"provider-chip' + (active ? ' provider-chip--active' : '') +\r\n '\" data-switch-area=\"' + esc(areaKey) + '\" data-switch-provider=\"' + esc(opt.provider) + '\">' + esc(opt.label) + '</button>';\r\n }).join('');\r\n return '<div class=\"panel-section\"><h3>Switch provider</h3><div class=\"provider-switch\">' + chips +\r\n '</div><p class=\"switch-hint\" id=\"switch-hint\">Pick a provider, then rescan to re-map this area.</p></div>';\r\n }\r\n\r\n function render(areaKey) {\r\n var area = areas.find(function (a) { return a.key === areaKey; });\r\n document.querySelectorAll('.studio-node').forEach(function (n) {\r\n n.classList.toggle('studio-node--selected', n.getAttribute('data-area-key') === areaKey);\r\n });\r\n var label = (area && area.label) || LABELS[areaKey] || areaKey;\r\n var missions = (area && area.providerMissions) || [];\r\n var mission = missions[0];\r\n var areaGaps = gaps.filter(function (g) { return g.primaryMapCategory === areaKey; });\r\n\r\n var checksHtml = missions.flatMap(function (m) {\r\n return (m.checks || []).map(function (c) {\r\n var ev = (c.evidence && c.evidence[0]) ? c.evidence[0] : (c.promptHint || '');\r\n return '<div class=\"check\"><strong>' + esc(c.label) + '</strong>' +\r\n '<div class=\"status ' + statusClass(c.status) + '\">' + esc(c.status) + '</div>' +\r\n (ev ? '<div class=\"status\">' + esc(ev) + '</div>' : '') + '</div>';\r\n });\r\n }).join('');\r\n\r\n var gapsHtml = areaGaps.map(function (g) {\r\n return '<div class=\"gap-card\"><strong>' + esc(g.title) + '</strong><p>' + esc(g.detail) +\r\n '</p><button type=\"button\" class=\"copy-btn\" data-copy-gap=\"' + esc(g.id) + '\">Copy agent prompt</button></div>';\r\n }).join('');\r\n\r\n var head =\r\n '<p class=\"studio-setup-panel__eyebrow\">' + esc(areaKey) + '</p>' +\r\n '<p class=\"studio-setup-panel__title\">' + esc(label) + '</p>' +\r\n '<p class=\"studio-setup-panel__hint\">' +\r\n (missions.map(function (m) { return esc(m.providerLabel) + ' \u00B7 ' + m.readinessPercent + '% repo readiness'; }).join(' \u00B7 ') || 'No provider detected for this area.') +\r\n '</p>';\r\n\r\n panel.innerHTML = head +\r\n providerSwitchHtml(areaKey, mission) +\r\n '<div class=\"panel-section\"><h3>Stack checks</h3>' + (checksHtml || '<p class=\"switch-hint\">No checks for this area.</p>') + '</div>' +\r\n '<div class=\"panel-section\"><h3>Launch gaps</h3>' + (gapsHtml || '<p class=\"switch-hint\">No model gaps tagged here.</p>') + '</div>';\r\n\r\n panel.querySelectorAll('[data-copy-gap]').forEach(function (btn) {\r\n btn.addEventListener('click', function () {\r\n var gap = gaps.find(function (g) { return g.id === btn.getAttribute('data-copy-gap'); });\r\n if (!gap) return;\r\n navigator.clipboard.writeText(gap.copyPrompt).then(function () {\r\n btn.textContent = 'Copied';\r\n setTimeout(function () { btn.textContent = 'Copy agent prompt'; }, 1200);\r\n });\r\n });\r\n });\r\n\r\n panel.querySelectorAll('[data-switch-provider]').forEach(function (btn) {\r\n btn.addEventListener('click', function () {\r\n var a = btn.getAttribute('data-switch-area');\r\n var p = btn.getAttribute('data-switch-provider');\r\n var cmd = 'viberaven stack set ' + a + ' ' + p + ' && viberaven scan --open';\r\n navigator.clipboard.writeText(cmd);\r\n var hint = document.getElementById('switch-hint');\r\n if (hint) hint.innerHTML = 'Copied: <code>' + esc(cmd) + '</code> \u2014 run it (or ask your agent) to re-map this area.';\r\n panel.querySelectorAll('[data-switch-area=\"' + a + '\"]').forEach(function (c) {\r\n c.classList.toggle('provider-chip--active', c === btn);\r\n });\r\n });\r\n });\r\n }\r\n\r\n document.querySelectorAll('.studio-node').forEach(function (n) {\r\n n.addEventListener('click', function () { render(n.getAttribute('data-area-key')); });\r\n });\r\n if (areas[0]) render(areas[0].key);\r\n})();\r\n`;\r\n", "import { spawn } from 'node:child_process';\r\n\r\nexport async function openPathInBrowser(filePath: string): Promise<void> {\r\n const absolute = filePath;\r\n let command: string;\r\n let args: string[];\r\n\r\n if (process.platform === 'win32') {\r\n command = 'cmd';\r\n args = ['/c', 'start', '', absolute];\r\n } else if (process.platform === 'darwin') {\r\n command = 'open';\r\n args = [absolute];\r\n } else {\r\n command = 'xdg-open';\r\n args = [absolute];\r\n }\r\n\r\n await new Promise<void>((resolve, reject) => {\r\n const child = spawn(command, args, { stdio: 'ignore', shell: process.platform === 'win32' });\r\n child.on('error', reject);\r\n child.on('exit', (code) => {\r\n if (code === 0) {\r\n resolve();\r\n } else {\r\n reject(new Error(`Could not open browser (exit ${code ?? 'unknown'}). Open manually: ${absolute}`));\r\n }\r\n });\r\n });\r\n}\r\n", "import type { CliScanArtifact } from './types';\r\n\r\nexport function printScanSummary(\r\n artifact: CliScanArtifact,\r\n paths: { reportPath: string; jsonPath: string; summaryPath: string }\r\n): void {\r\n console.log('');\r\n console.log(`VibeRaven \u00B7 Production core ${artifact.productionCorePercent}% \u00B7 ${artifact.gaps.length} gap(s)`);\r\n console.log(`Score ${artifact.score} \u00B7 ${artifact.scoreLabel}`);\r\n console.log('');\r\n\r\n for (const area of artifact.missionGraph.areas ?? []) {\r\n const mission = area.providerMissions[0];\r\n if (!mission) {\r\n continue;\r\n }\r\n const open = mission.checks.filter(\r\n (c) => c.status === 'missing' || c.status === 'failed' || c.status === 'needs-connection'\r\n ).length;\r\n const modelGaps = artifact.gaps.filter((g) => g.primaryMapCategory === area.key).length;\r\n const gapTag = modelGaps > 0 ? ` GAP ${modelGaps}` : open > 0 ? ` ${open} fix` : '';\r\n const label = area.label.padEnd(18);\r\n const provider = mission.providerLabel.padEnd(14);\r\n console.log(` ${label} ${provider} ${mission.readinessPercent}%${gapTag}`);\r\n }\r\n\r\n console.log('');\r\n console.log('Artifacts:');\r\n console.log(` ${paths.reportPath}`);\r\n console.log(` ${paths.jsonPath}`);\r\n console.log(` ${paths.summaryPath}`);\r\n console.log('');\r\n console.log('Next: viberaven prompt (top gap for your coding agent)');\r\n console.log('Agents: read .viberaven/agent-summary.md');\r\n console.log('');\r\n}\r\n"],
5
- "mappings": ";;;;AAAA,IAAAA,mBAAyB;AACzB,IAAAC,oBAAqB;;;ACDrB,qBAAwB;AACxB,uBAAqB;AACrB,sBAA2C;AAC3C,qBAA0B;AAC1B,IAAAC,mBAAuB;AAGhB,IAAM,uBACX;AAmBK,SAAS,oBAAoB,MAAc,QAAQ,IAAI,GAAW;AACvE,aAAO,uBAAK,uBAAuB,GAAG,GAAG,YAAY;AACvD;AAEO,SAAS,eAAuB;AACrC,QAAM,WAAW,QAAQ,IAAI,sBAAsB,KAAK;AACxD,MAAI,UAAU;AACZ,WAAO;AAAA,EACT;AACA,MAAI,QAAQ,a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AACE,cAAQ,MAAM,oBAAoB,OAAO,EAAE;AAC3C,gBAAU;AACV,aAAO;AAAA,EACX;AACF;AAEA,KAAK,EACF,KAAK,CAAC,SAAS;AACd,MAAI,SAAS,GAAG;AACd,YAAQ,WAAW;AAAA,EACrB;AACF,CAAC,EACA,MAAM,CAAC,UAAU;AAChB,UAAQ,MAAM,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AACpE,UAAQ,WAAW;AACrB,CAAC;",
6
- "names": ["import_promises", "import_node_path", "import_promises", "e", "import_node_fs", "import_node_path", "fs", "import_node_fs", "import_node_path", "isRecord", "item", "provider", "item", "PROVIDERS", "provider", "item", "normalizePath", "item", "visibleFiles", "visibleFiles", "item", "hasPackage", "packageEvidence", "pathEvidence", "envEvidence", "isClientExecutedPath", "visibleFiles", "AREAS", "buildContext", "item", "normalizePath", "provider", "providerLabel", "raw", "normalized", "scanContext", "fs", "provider", "import_promises", "import_node_path", "provider", "provider", "provider"]
3
+ "sources": ["../node_modules/picocolors/picocolors.js", "../node_modules/sisteransi/src/index.js", "../src/cli.ts", "../src/config.ts", "../../../src/station/fetchUtils.ts", "../../../src/station/backendClient.ts", "../src/account.ts", "../src/auth.ts", "../../../src/station/fileScanner.ts", "../../../src/station/orchestrator.ts", "../../../src/station/engines.ts", "../../../src/station/sifgTemplates.ts", "../../../src/station/providerRegistry.ts", "../../../src/station/missionGraph.ts", "../../../src/station/promptBuilder.ts", "../../../src/station/productionConnections.ts", "../../../src/station/envEvidence.ts", "../../../src/station/repositoryEvidence.ts", "../../../src/station/scanContext.ts", "../../../src/station/sifgExtractors.ts", "../../../src/station/sifgEngine.ts", "../../../src/station/sifgPrompt.ts", "../../../src/station/promptRouting.ts", "../../../src/station/stackAutomation.ts", "../../../src/station/supabaseWiring.ts", "../../../src/station/stackWiring.ts", "../../../src/station/verification.ts", "../../../src/station/stackMapProviderOptions.ts", "../src/report/hydrateArtifact.ts", "../src/runScan.ts", "../src/artifacts.ts", "../src/report/agentSummary.ts", "../src/report/missionSelection.ts", "../src/report/panelClientScript.ts", "../src/report/providerLogos.ts", "../src/report/reportHtml.ts", "../src/report/reportAssets.ts", "../src/sanitizeArtifact.ts", "../src/tui/menu.ts", "../src/report/refreshReport.ts", "../src/openBrowser.ts", "../src/clipboard.ts", "../src/terminalSummary.ts", "../src/tui/runInteractive.ts", "../node_modules/node_modules/.pnpm/ansi-regex@6.1.0/node_modules/ansi-regex/index.js", "../node_modules/node_modules/.pnpm/strip-ansi@7.1.0/node_modules/strip-ansi/index.js", "../node_modules/node_modules/.pnpm/eastasianwidth@0.2.0/node_modules/eastasianwidth/eastasianwidth.js", "../node_modules/node_modules/.pnpm/emoji-regex@9.2.2/node_modules/emoji-regex/index.js", "../node_modules/node_modules/.pnpm/string-width@5.1.2/node_modules/string-width/index.js", "../node_modules/node_modules/.pnpm/ansi-styles@6.2.1/node_modules/ansi-styles/index.js", "../node_modules/node_modules/.pnpm/wrap-ansi@8.1.0/node_modules/wrap-ansi/index.js", "../node_modules/@clack/core/src/utils/settings.ts", "../node_modules/@clack/core/src/utils/string.ts", "../node_modules/@clack/core/src/utils/index.ts", "../node_modules/@clack/core/src/prompts/prompt.ts", "../node_modules/@clack/core/src/prompts/confirm.ts", "../node_modules/@clack/core/src/prompts/group-multiselect.ts", "../node_modules/@clack/core/src/prompts/multi-select.ts", "../node_modules/@clack/core/src/prompts/password.ts", "../node_modules/@clack/core/src/prompts/select.ts", "../node_modules/@clack/core/src/prompts/select-key.ts", "../node_modules/@clack/core/src/prompts/text.ts", "../node_modules/node_modules/.pnpm/is-unicode-supported@1.3.0/node_modules/is-unicode-supported/index.js", "../node_modules/@clack/prompts/src/index.ts", "../src/version.ts"],
4
+ "sourcesContent": ["let p = process || {}, argv = p.argv || [], env = p.env || {}\nlet isColorSupported =\n\t!(!!env.NO_COLOR || argv.includes(\"--no-color\")) &&\n\t(!!env.FORCE_COLOR || argv.includes(\"--color\") || p.platform === \"win32\" || ((p.stdout || {}).isTTY && env.TERM !== \"dumb\") || !!env.CI)\n\nlet formatter = (open, close, replace = open) =>\n\tinput => {\n\t\tlet string = \"\" + input, index = string.indexOf(close, open.length)\n\t\treturn ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close\n\t}\n\nlet replaceClose = (string, close, replace, index) => {\n\tlet result = \"\", cursor = 0\n\tdo {\n\t\tresult += string.substring(cursor, index) + replace\n\t\tcursor = index + close.length\n\t\tindex = string.indexOf(close, cursor)\n\t} while (~index)\n\treturn result + string.substring(cursor)\n}\n\nlet createColors = (enabled = isColorSupported) => {\n\tlet f = enabled ? formatter : () => String\n\treturn {\n\t\tisColorSupported: enabled,\n\t\treset: f(\"\\x1b[0m\", \"\\x1b[0m\"),\n\t\tbold: f(\"\\x1b[1m\", \"\\x1b[22m\", \"\\x1b[22m\\x1b[1m\"),\n\t\tdim: f(\"\\x1b[2m\", \"\\x1b[22m\", \"\\x1b[22m\\x1b[2m\"),\n\t\titalic: f(\"\\x1b[3m\", \"\\x1b[23m\"),\n\t\tunderline: f(\"\\x1b[4m\", \"\\x1b[24m\"),\n\t\tinverse: f(\"\\x1b[7m\", \"\\x1b[27m\"),\n\t\thidden: f(\"\\x1b[8m\", \"\\x1b[28m\"),\n\t\tstrikethrough: f(\"\\x1b[9m\", \"\\x1b[29m\"),\n\n\t\tblack: f(\"\\x1b[30m\", \"\\x1b[39m\"),\n\t\tred: f(\"\\x1b[31m\", \"\\x1b[39m\"),\n\t\tgreen: f(\"\\x1b[32m\", \"\\x1b[39m\"),\n\t\tyellow: f(\"\\x1b[33m\", \"\\x1b[39m\"),\n\t\tblue: f(\"\\x1b[34m\", \"\\x1b[39m\"),\n\t\tmagenta: f(\"\\x1b[35m\", \"\\x1b[39m\"),\n\t\tcyan: f(\"\\x1b[36m\", \"\\x1b[39m\"),\n\t\twhite: f(\"\\x1b[37m\", \"\\x1b[39m\"),\n\t\tgray: f(\"\\x1b[90m\", \"\\x1b[39m\"),\n\n\t\tbgBlack: f(\"\\x1b[40m\", \"\\x1b[49m\"),\n\t\tbgRed: f(\"\\x1b[41m\", \"\\x1b[49m\"),\n\t\tbgGreen: f(\"\\x1b[42m\", \"\\x1b[49m\"),\n\t\tbgYellow: f(\"\\x1b[43m\", \"\\x1b[49m\"),\n\t\tbgBlue: f(\"\\x1b[44m\", \"\\x1b[49m\"),\n\t\tbgMagenta: f(\"\\x1b[45m\", \"\\x1b[49m\"),\n\t\tbgCyan: f(\"\\x1b[46m\", \"\\x1b[49m\"),\n\t\tbgWhite: f(\"\\x1b[47m\", \"\\x1b[49m\"),\n\n\t\tblackBright: f(\"\\x1b[90m\", \"\\x1b[39m\"),\n\t\tredBright: f(\"\\x1b[91m\", \"\\x1b[39m\"),\n\t\tgreenBright: f(\"\\x1b[92m\", \"\\x1b[39m\"),\n\t\tyellowBright: f(\"\\x1b[93m\", \"\\x1b[39m\"),\n\t\tblueBright: f(\"\\x1b[94m\", \"\\x1b[39m\"),\n\t\tmagentaBright: f(\"\\x1b[95m\", \"\\x1b[39m\"),\n\t\tcyanBright: f(\"\\x1b[96m\", \"\\x1b[39m\"),\n\t\twhiteBright: f(\"\\x1b[97m\", \"\\x1b[39m\"),\n\n\t\tbgBlackBright: f(\"\\x1b[100m\", \"\\x1b[49m\"),\n\t\tbgRedBright: f(\"\\x1b[101m\", \"\\x1b[49m\"),\n\t\tbgGreenBright: f(\"\\x1b[102m\", \"\\x1b[49m\"),\n\t\tbgYellowBright: f(\"\\x1b[103m\", \"\\x1b[49m\"),\n\t\tbgBlueBright: f(\"\\x1b[104m\", \"\\x1b[49m\"),\n\t\tbgMagentaBright: f(\"\\x1b[105m\", \"\\x1b[49m\"),\n\t\tbgCyanBright: f(\"\\x1b[106m\", \"\\x1b[49m\"),\n\t\tbgWhiteBright: f(\"\\x1b[107m\", \"\\x1b[49m\"),\n\t}\n}\n\nmodule.exports = createColors()\nmodule.exports.createColors = createColors\n", "'use strict';\n\nconst ESC = '\\x1B';\nconst CSI = `${ESC}[`;\nconst beep = '\\u0007';\n\nconst cursor = {\n to(x, y) {\n if (!y) return `${CSI}${x + 1}G`;\n return `${CSI}${y + 1};${x + 1}H`;\n },\n move(x, y) {\n let ret = '';\n\n if (x < 0) ret += `${CSI}${-x}D`;\n else if (x > 0) ret += `${CSI}${x}C`;\n\n if (y < 0) ret += `${CSI}${-y}A`;\n else if (y > 0) ret += `${CSI}${y}B`;\n\n return ret;\n },\n up: (count = 1) => `${CSI}${count}A`,\n down: (count = 1) => `${CSI}${count}B`,\n forward: (count = 1) => `${CSI}${count}C`,\n backward: (count = 1) => `${CSI}${count}D`,\n nextLine: (count = 1) => `${CSI}E`.repeat(count),\n prevLine: (count = 1) => `${CSI}F`.repeat(count),\n left: `${CSI}G`,\n hide: `${CSI}?25l`,\n show: `${CSI}?25h`,\n save: `${ESC}7`,\n restore: `${ESC}8`\n}\n\nconst scroll = {\n up: (count = 1) => `${CSI}S`.repeat(count),\n down: (count = 1) => `${CSI}T`.repeat(count)\n}\n\nconst erase = {\n screen: `${CSI}2J`,\n up: (count = 1) => `${CSI}1J`.repeat(count),\n down: (count = 1) => `${CSI}J`.repeat(count),\n line: `${CSI}2K`,\n lineEnd: `${CSI}K`,\n lineStart: `${CSI}1K`,\n lines(count) {\n let clear = '';\n for (let i = 0; i < count; i++)\n clear += this.line + (i < count - 1 ? cursor.up() : '');\n if (count)\n clear += cursor.left;\n return clear;\n }\n}\n\nmodule.exports = { cursor, scroll, erase, beep };\n", "import { join } from 'node:path';\r\n\r\nimport {\r\n\r\n clearCredentials,\r\n\r\n loadCredentials,\r\n\r\n loadStackChoicesFile,\r\n\r\n resolveApiBaseUrl,\r\n resolveWorkspaceRoot,\r\n saveStackChoicesFile\r\n\r\n} from './config';\r\n\r\nimport { requireCredentials, runDeviceLogin } from './auth';\r\n\r\nimport {\r\n enrichArtifactWithAccount,\r\n fetchAccountMe,\r\n formatScanLimitMessage,\r\n formatUsageLine,\r\n syncCredentialsFromAccount\r\n} from './account';\r\n\r\nimport { runProjectScan } from './runScan';\r\n\r\nimport { writeScanArtifacts } from './artifacts';\r\n\r\nimport { refreshReportFromDisk } from './report/refreshReport';\r\n\r\nimport { openPathInBrowser } from './openBrowser';\r\n\r\nimport { copyToClipboard } from './clipboard';\r\nimport { printScanSummary } from './terminalSummary';\r\n\r\nimport { isScanNotFoundError, loadLastArtifact, pickGap } from './tui/menu';\r\n\r\nimport { runInteractiveSession } from './tui/runInteractive';\r\n\r\nimport { VERSION } from './version';\r\n\r\n\r\n\r\nfunction printHelp(): void {\r\n\r\n console.log(`viberaven ${VERSION} \u2014 launch readiness for AI-built apps\r\n\r\n\r\n\r\nUsage:\r\n\r\n viberaven Interactive menu (default for vibe coders)\r\n\r\n viberaven tui Same interactive menu\r\n\r\n viberaven login [--api-url <url>]\r\n\r\n viberaven logout\r\n\r\n viberaven status\r\n\r\n viberaven scan [--open] [--json] [--api-url <url>] [path]\r\n\r\n viberaven report [--open] [path]\r\n Rebuild report.html from last scan (no new API scan)\r\n\r\n viberaven prompt [--gap <id>] [--provider <key>] [--area <key>] [--no-copy]\r\n\r\n viberaven stack set <area> <provider>\r\n\r\n viberaven stack clear <area>\r\n\r\n viberaven stack list\r\n\r\n\r\n\r\nAgent workflow (Claude Code / Codex):\r\n\r\n npx -y @viberaven/cli@beta scan\r\n\r\n Read .viberaven/agent-summary.md and fix the top gap, then scan again.\r\n\r\n\r\n\r\nHumans: run \\`viberaven\\` or \\`viberaven tui\\` for the interactive menu.\r\n\r\nAgents: use \\`npx -y @viberaven/cli@beta scan\\` directly (no --open required).\r\n\r\n\r\n\r\nEnvironment:\r\n\r\n VIBERAVEN_API_URL Managed API base URL (same server as the VS Code extension)\r\n\r\nSecurity:\r\n\r\n CLI scans use VibeRaven login \u2014 not OPENAI_API_KEY. See packages/cli/SECURITY.md.\r\n\r\n`);\r\n\r\n}\r\n\r\n\r\n\r\nfunction parseArgs(argv: string[]): {\r\n\r\n command: string;\r\n\r\n flags: Record<string, string | boolean>;\r\n\r\n positional: string[];\r\n\r\n} {\r\n\r\n const flags: Record<string, string | boolean> = {};\r\n\r\n const positional: string[] = [];\r\n\r\n let command = '';\r\n\r\n\r\n\r\n for (let i = 0; i < argv.length; i += 1) {\r\n\r\n const arg = argv[i];\r\n\r\n if (arg === '--help' || arg === '-h') {\r\n\r\n flags.help = true;\r\n\r\n continue;\r\n\r\n }\r\n\r\n if (arg.startsWith('--')) {\r\n\r\n const key = arg.slice(2);\r\n\r\n const next = argv[i + 1];\r\n\r\n if (next && !next.startsWith('-')) {\r\n\r\n flags[key] = next;\r\n\r\n i += 1;\r\n\r\n } else {\r\n\r\n flags[key] = true;\r\n\r\n }\r\n\r\n continue;\r\n\r\n }\r\n\r\n if (!command) {\r\n\r\n command = arg;\r\n\r\n } else {\r\n\r\n positional.push(arg);\r\n\r\n }\r\n\r\n }\r\n\r\n\r\n\r\n return { command, flags, positional };\r\n\r\n}\r\n\r\n\r\n\r\nasync function cmdLogin(flags: Record<string, string | boolean>): Promise<void> {\r\n\r\n const apiBaseUrl = resolveApiBaseUrl(typeof flags['api-url'] === 'string' ? flags['api-url'] : undefined);\r\n\r\n await runDeviceLogin(apiBaseUrl);\r\n\r\n}\r\n\r\n\r\n\r\nasync function cmdLogout(): Promise<void> {\r\n\r\n await clearCredentials();\r\n\r\n console.log('Signed out.');\r\n\r\n}\r\n\r\n\r\n\r\nasync function cmdStatus(): Promise<number> {\r\n\r\n const creds = await loadCredentials();\r\n\r\n if (!creds?.accessToken) {\r\n\r\n console.log('Not signed in. Run: viberaven login');\r\n\r\n return 1;\r\n\r\n }\r\n\r\n try {\r\n\r\n const synced = await syncCredentialsFromAccount(creds);\r\n\r\n console.log(`Signed in: ${synced.email ?? '(email unknown)'}`);\r\n\r\n console.log(`Plan: ${synced.plan ?? 'unknown'}`);\r\n\r\n console.log(formatUsageLine(synced.account.usage));\r\n\r\n console.log(`API: ${synced.apiBaseUrl}`);\r\n\r\n return 0;\r\n\r\n } catch (error) {\r\n\r\n console.log(`Signed in (cached): ${creds.email ?? '(email unknown)'}`);\r\n\r\n console.log(`Plan: ${creds.plan ?? 'unknown'}`);\r\n\r\n console.log(`API: ${creds.apiBaseUrl}`);\r\n\r\n console.warn(error instanceof Error ? error.message : String(error));\r\n\r\n return 1;\r\n\r\n }\r\n\r\n}\r\n\r\n\r\n\r\nasync function cmdScan(\r\n\r\n flags: Record<string, string | boolean>,\r\n\r\n positional: string[]\r\n\r\n): Promise<number> {\r\n\r\n const workspacePath = positional[0]\r\n ? join(process.cwd(), positional[0])\r\n : await resolveWorkspaceRoot(process.cwd());\r\n\r\n const apiBaseUrl = resolveApiBaseUrl(typeof flags['api-url'] === 'string' ? flags['api-url'] : undefined);\r\n\r\n\r\n\r\n let accessToken: string;\r\n\r\n try {\r\n\r\n ({ accessToken } = await requireCredentials(apiBaseUrl));\r\n\r\n } catch (error) {\r\n\r\n console.error(error instanceof Error ? error.message : String(error));\r\n\r\n return 1;\r\n\r\n }\r\n\r\n\r\n\r\n console.log(`Scanning ${workspacePath}\u2026`);\r\n\r\n const result = await runProjectScan({ workspacePath, accessToken, apiBaseUrl });\r\n\r\n\r\n\r\n if (!result.ok) {\r\n\r\n if (result.kind === 'scan_limit') {\r\n\r\n console.error(formatScanLimitMessage(result.upgradeUrl));\r\n\r\n try {\r\n\r\n const account = await fetchAccountMe(apiBaseUrl, accessToken);\r\n\r\n console.error(formatUsageLine(account.usage));\r\n\r\n } catch {\r\n\r\n // usage refresh is best-effort when blocked\r\n\r\n }\r\n\r\n return 2;\r\n\r\n }\r\n\r\n console.error(result.message);\r\n\r\n return 1;\r\n\r\n }\r\n\r\n\r\n\r\n const artifact = await enrichArtifactWithAccount(result.artifact, apiBaseUrl, accessToken);\r\n\r\n const paths = await writeScanArtifacts({ artifact, cwd: workspacePath });\r\n\r\n\r\n\r\n if (flags.json) {\r\n\r\n console.log(JSON.stringify(artifact, null, 2));\r\n\r\n return 0;\r\n\r\n }\r\n\r\n\r\n\r\n printScanSummary(artifact, paths);\r\n\r\n if (artifact.usage) {\r\n\r\n console.log(formatUsageLine(artifact.usage));\r\n\r\n }\r\n\r\n\r\n\r\n if (flags.open) {\r\n\r\n try {\r\n\r\n await openPathInBrowser(paths.reportPath);\r\n\r\n } catch (error) {\r\n\r\n console.warn(error instanceof Error ? error.message : String(error));\r\n\r\n }\r\n\r\n }\r\n\r\n\r\n\r\n return 0;\r\n\r\n}\r\n\r\n\r\n\r\nasync function cmdReport(\r\n flags: Record<string, string | boolean>,\r\n positional: string[]\r\n): Promise<number> {\r\n const startDir = positional[0] ? join(process.cwd(), positional[0]) : process.cwd();\r\n\r\n try {\r\n const paths = await refreshReportFromDisk(startDir);\r\n console.log(`Report refreshed: ${paths.reportPath}`);\r\n\r\n if (flags.open) {\r\n try {\r\n await openPathInBrowser(paths.reportPath);\r\n } catch (error) {\r\n console.warn(error instanceof Error ? error.message : String(error));\r\n }\r\n }\r\n\r\n return 0;\r\n } catch (error) {\r\n if (isScanNotFoundError(error)) {\r\n console.error(error.message);\r\n return 1;\r\n }\r\n console.error(error instanceof Error ? error.message : String(error));\r\n return 1;\r\n }\r\n}\r\n\r\nasync function cmdPrompt(\r\n\r\n flags: Record<string, string | boolean>,\r\n\r\n positional: string[]\r\n\r\n): Promise<number> {\r\n\r\n const startDir = positional[0] ? join(process.cwd(), positional[0]) : process.cwd();\r\n\r\n let artifact;\r\n\r\n try {\r\n\r\n artifact = await loadLastArtifact(startDir);\r\n\r\n } catch (error) {\r\n\r\n console.error(error instanceof Error ? error.message : 'No scan found. Run: viberaven scan');\r\n\r\n return 1;\r\n\r\n }\r\n\r\n\r\n\r\n const gap = pickGap(artifact, {\r\n\r\n gapId: typeof flags.gap === 'string' ? flags.gap : undefined,\r\n\r\n provider: typeof flags.provider === 'string' ? flags.provider : undefined,\r\n\r\n area: typeof flags.area === 'string' ? flags.area : undefined\r\n\r\n });\r\n\r\n\r\n\r\n if (!gap) {\r\n\r\n console.error('No matching gap. Run `viberaven scan` or pass --gap <id>.');\r\n\r\n return 1;\r\n\r\n }\r\n\r\n\r\n\r\n const skipCopy = flags['no-copy'] === true;\r\n\r\n if (!skipCopy) {\r\n try {\r\n await copyToClipboard(gap.copyPrompt);\r\n console.log(`Copied to clipboard: ${gap.title}`);\r\n return 0;\r\n } catch (error) {\r\n console.warn(error instanceof Error ? error.message : String(error));\r\n }\r\n }\r\n\r\n console.log(gap.copyPrompt);\r\n\r\n return 0;\r\n\r\n}\r\n\r\n\r\n\r\nconst STACK_AREAS = new Set(['database', 'auth', 'payments', 'deployment', 'monitoring', 'security']);\r\n\r\n\r\n\r\nasync function cmdStack(positional: string[]): Promise<number> {\r\n\r\n const cwd = process.cwd();\r\n\r\n const sub = positional[0];\r\n\r\n\r\n\r\n if (sub === 'list' || !sub) {\r\n\r\n const file = await loadStackChoicesFile(cwd);\r\n\r\n const entries = Object.entries(file.choices);\r\n\r\n if (entries.length === 0) {\r\n\r\n console.log('No provider overrides. Detection runs from repo evidence.');\r\n\r\n return 0;\r\n\r\n }\r\n\r\n for (const [area, choice] of entries) {\r\n\r\n console.log(`${area}: ${choice.provider}`);\r\n\r\n }\r\n\r\n return 0;\r\n\r\n }\r\n\r\n\r\n\r\n if (sub === 'set') {\r\n\r\n const area = positional[1];\r\n\r\n const provider = positional[2];\r\n\r\n if (!area || !provider) {\r\n\r\n console.error('Usage: viberaven stack set <area> <provider>');\r\n\r\n return 1;\r\n\r\n }\r\n\r\n if (!STACK_AREAS.has(area)) {\r\n\r\n console.error(`Unknown area \"${area}\". Valid: ${[...STACK_AREAS].join(', ')}`);\r\n\r\n return 1;\r\n\r\n }\r\n\r\n const file = await loadStackChoicesFile(cwd);\r\n\r\n file.choices[area] = { provider, selectedAt: new Date().toISOString() };\r\n\r\n await saveStackChoicesFile(cwd, file);\r\n\r\n console.log(`Set ${area} \u2192 ${provider}. Run \\`viberaven scan\\` to re-map.`);\r\n\r\n return 0;\r\n\r\n }\r\n\r\n\r\n\r\n if (sub === 'clear') {\r\n\r\n const area = positional[1];\r\n\r\n const file = await loadStackChoicesFile(cwd);\r\n\r\n if (area) {\r\n\r\n delete file.choices[area];\r\n\r\n } else {\r\n\r\n file.choices = {};\r\n\r\n }\r\n\r\n await saveStackChoicesFile(cwd, file);\r\n\r\n console.log(area ? `Cleared ${area}.` : 'Cleared all provider overrides.');\r\n\r\n return 0;\r\n\r\n }\r\n\r\n\r\n\r\n console.error(`Unknown stack subcommand \"${sub}\". Use set, clear, or list.`);\r\n\r\n return 1;\r\n\r\n}\r\n\r\n\r\n\r\nasync function main(): Promise<number> {\r\n\r\n const { command, flags, positional } = parseArgs(process.argv.slice(2));\r\n\r\n\r\n\r\n if (flags.help) {\r\n\r\n printHelp();\r\n\r\n return 0;\r\n\r\n }\r\n\r\n if (!command) {\r\n\r\n await runInteractiveSession();\r\n\r\n return 0;\r\n\r\n }\r\n\r\n\r\n\r\n switch (command) {\r\n\r\n case 'tui':\r\n\r\n case 'interactive':\r\n\r\n await runInteractiveSession();\r\n\r\n return 0;\r\n\r\n case 'login':\r\n\r\n await cmdLogin(flags);\r\n\r\n return 0;\r\n\r\n case 'logout':\r\n\r\n await cmdLogout();\r\n\r\n return 0;\r\n\r\n case 'status':\r\n\r\n return cmdStatus();\r\n\r\n case 'scan':\r\n\r\n return cmdScan(flags, positional);\r\n\r\n case 'report':\r\n\r\n return cmdReport(flags, positional);\r\n\r\n case 'prompt':\r\n\r\n return cmdPrompt(flags, positional);\r\n\r\n case 'stack':\r\n\r\n return cmdStack(positional);\r\n\r\n case '--version':\r\n\r\n case '-v':\r\n\r\n case 'version':\r\n\r\n console.log(VERSION);\r\n\r\n return 0;\r\n\r\n default:\r\n\r\n console.error(`Unknown command: ${command}`);\r\n\r\n printHelp();\r\n\r\n return 1;\r\n\r\n }\r\n\r\n}\r\n\r\n\r\n\r\nmain()\r\n\r\n .then((code) => {\r\n\r\n if (code !== 0) {\r\n\r\n process.exitCode = code;\r\n\r\n }\r\n\r\n })\r\n\r\n .catch((error) => {\r\n\r\n console.error(error instanceof Error ? error.message : String(error));\r\n\r\n process.exitCode = 1;\r\n\r\n });\r\n\r\n", "import { homedir } from 'node:os';\r\nimport { dirname, join, parse, resolve } from 'node:path';\r\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\r\nimport { constants } from 'node:fs';\r\nimport { access } from 'node:fs/promises';\r\n\r\n/** Same default as the shipped VS Code extension (`getBackendBaseUrl`). */\r\nexport const DEFAULT_API_BASE_URL =\r\n 'https://jaohiwzjhtwljyqligpu.supabase.co/functions/v1/viberice-api';\r\n\r\nexport interface CliCredentials {\r\n accessToken: string;\r\n apiBaseUrl: string;\r\n email?: string;\r\n plan?: string;\r\n}\r\n\r\nexport interface CliStackChoice {\r\n provider: string;\r\n selectedAt: string;\r\n}\r\n\r\nexport interface CliStackChoicesFile {\r\n version: 1;\r\n choices: Record<string, CliStackChoice>;\r\n}\r\n\r\nexport function getStackChoicesPath(cwd: string = process.cwd()): string {\r\n return join(getProjectArtifactsDir(cwd), 'stack.json');\r\n}\r\n\r\nexport function getConfigDir(): string {\r\n const override = process.env.VIBERAVEN_CONFIG_DIR?.trim();\r\n if (override) {\r\n return override;\r\n }\r\n if (process.platform === 'win32') {\r\n const appData = process.env.APPDATA?.trim();\r\n if (appData) {\r\n return join(appData, 'viberaven');\r\n }\r\n }\r\n return join(homedir(), '.config', 'viberaven');\r\n}\r\n\r\nexport function getCredentialsPath(): string {\r\n return join(getConfigDir(), 'credentials.json');\r\n}\r\n\r\nexport function getProjectArtifactsDir(cwd: string = process.cwd()): string {\r\n return join(cwd, '.viberaven');\r\n}\r\n\r\nconst LAST_SCAN_FILE = 'last-scan.json';\r\n\r\n/**\r\n * Walk up from `startDir` for `.viberaven/last-scan.json` (nearest ancestor wins).\r\n */\r\nexport async function findArtifactsWorkspace(startDir: string = process.cwd()): Promise<string | undefined> {\r\n let dir = resolve(startDir);\r\n const fsRoot = parse(dir).root;\r\n\r\n while (true) {\r\n try {\r\n await access(join(dir, '.viberaven', LAST_SCAN_FILE), constants.F_OK);\r\n return dir;\r\n } catch {\r\n // keep walking up\r\n }\r\n const parent = dirname(dir);\r\n if (parent === dir || dir === fsRoot) {\r\n return undefined;\r\n }\r\n dir = parent;\r\n }\r\n}\r\n\r\n/**\r\n * Best folder for scan/read artifacts: nearest `.viberaven` scan, else git root, else `startDir`.\r\n */\r\nexport async function resolveWorkspaceRoot(startDir: string = process.cwd()): Promise<string> {\r\n const withArtifacts = await findArtifactsWorkspace(startDir);\r\n if (withArtifacts) {\r\n return withArtifacts;\r\n }\r\n\r\n let dir = resolve(startDir);\r\n const fsRoot = parse(dir).root;\r\n\r\n while (true) {\r\n try {\r\n await access(join(dir, '.git'), constants.F_OK);\r\n return dir;\r\n } catch {\r\n // keep walking up\r\n }\r\n const parent = dirname(dir);\r\n if (parent === dir || dir === fsRoot) {\r\n return resolve(startDir);\r\n }\r\n dir = parent;\r\n }\r\n}\r\n\r\nexport async function ensureConfigDir(): Promise<string> {\r\n const dir = getConfigDir();\r\n await mkdir(dir, { recursive: true });\r\n return dir;\r\n}\r\n\r\nexport async function loadCredentials(): Promise<CliCredentials | undefined> {\r\n try {\r\n const raw = await readFile(getCredentialsPath(), 'utf-8');\r\n const parsed = JSON.parse(raw) as Partial<CliCredentials>;\r\n if (typeof parsed.accessToken !== 'string' || !parsed.accessToken.trim()) {\r\n return undefined;\r\n }\r\n return {\r\n accessToken: parsed.accessToken.trim(),\r\n apiBaseUrl: (parsed.apiBaseUrl?.trim() || DEFAULT_API_BASE_URL).replace(/\\/+$/, ''),\r\n email: typeof parsed.email === 'string' ? parsed.email : undefined,\r\n plan: typeof parsed.plan === 'string' ? parsed.plan : undefined\r\n };\r\n } catch {\r\n return undefined;\r\n }\r\n}\r\n\r\nexport async function saveCredentials(credentials: CliCredentials): Promise<void> {\r\n await ensureConfigDir();\r\n await writeFile(getCredentialsPath(), `${JSON.stringify(credentials, null, 2)}\\n`, {\r\n mode: constants.S_IRUSR | constants.S_IWUSR\r\n });\r\n}\r\n\r\nexport async function clearCredentials(): Promise<void> {\r\n try {\r\n await access(getCredentialsPath());\r\n await writeFile(getCredentialsPath(), '{}\\n');\r\n } catch {\r\n // no credentials file\r\n }\r\n}\r\n\r\nexport function resolveApiBaseUrl(flag?: string): string {\r\n const fromFlag = flag?.trim();\r\n if (fromFlag) {\r\n return fromFlag.replace(/\\/+$/, '');\r\n }\r\n const fromEnv = process.env.VIBERAVEN_API_URL?.trim() || process.env.VRAVEN_API_URL?.trim();\r\n if (fromEnv) {\r\n return fromEnv.replace(/\\/+$/, '');\r\n }\r\n return DEFAULT_API_BASE_URL;\r\n}\r\n\r\nexport async function loadStackChoicesFile(cwd: string): Promise<CliStackChoicesFile> {\r\n try {\r\n const raw = await readFile(getStackChoicesPath(cwd), 'utf-8');\r\n const parsed = JSON.parse(raw) as Partial<CliStackChoicesFile>;\r\n if (parsed && parsed.version === 1 && parsed.choices && typeof parsed.choices === 'object') {\r\n return { version: 1, choices: parsed.choices };\r\n }\r\n } catch {\r\n // optional file\r\n }\r\n return { version: 1, choices: {} };\r\n}\r\n\r\nexport async function saveStackChoicesFile(cwd: string, file: CliStackChoicesFile): Promise<void> {\r\n await mkdir(getProjectArtifactsDir(cwd), { recursive: true });\r\n await writeFile(getStackChoicesPath(cwd), `${JSON.stringify(file, null, 2)}\\n`, 'utf-8');\r\n}\r\n", "/**\r\n * True when the failure is a low-level network/transport error (no HTTP response),\r\n * e.g. ECONNREFUSED to localhost, DNS failure, or offline.\r\n */\r\nexport function isNetworkFetchFailure(error: unknown): boolean {\r\n if (error == null) {\r\n return false;\r\n }\r\n\r\n if (error instanceof TypeError) {\r\n const m = error.message;\r\n if (m === 'fetch failed' || m.toLowerCase().includes('fetch failed') || m.includes('Failed to fetch')) {\r\n return true;\r\n }\r\n }\r\n\r\n if (error instanceof AggregateError) {\r\n return error.errors.some((e) => isNetworkFetchFailure(e));\r\n }\r\n\r\n if (error instanceof Error && 'cause' in error && (error as Error & { cause?: unknown }).cause != null) {\r\n return isNetworkFetchFailure((error as Error & { cause?: unknown }).cause);\r\n }\r\n\r\n const e = error as NodeJS.ErrnoException;\r\n if (typeof e.code === 'string') {\r\n if (\r\n ['ECONNREFUSED', 'ECONNRESET', 'ENOTFOUND', 'EAI_AGAIN', 'ETIMEDOUT', 'ENETUNREACH', 'EHOSTUNREACH'].includes(\r\n e.code\r\n )\r\n ) {\r\n return true;\r\n }\r\n }\r\n\r\n return false;\r\n}\r\n", "import type { DevicePollResponse, DeviceStartResponse } from '../../shared/auth';\nimport { isNetworkFetchFailure } from './fetchUtils';\nimport type {\n ManagedStationRequest,\n ManagedStationResponse,\n ManagedStationUsage\n} from '../../shared/station';\n\nexport const MANAGED_ACCESS_TOKEN_SECRET_KEY = 'viberice.managedAccessToken';\nexport const MANAGED_SESSION_STATE_KEY = 'viberice.managedSession';\n\nexport interface ManagedAccount {\n email?: string;\n plan?: string;\n trialEndsAt?: string | null;\n}\n\nexport interface ManagedSession {\n account?: ManagedAccount;\n usage?: ManagedUsage;\n}\n\nexport type ManagedUsage = ManagedStationUsage;\n\nexport type ManagedSignInStart = DeviceStartResponse;\n\nexport type ManagedSignInPoll =\n | DevicePollResponse\n | { status: 'expired' | 'denied' };\n\nexport async function startManagedSignIn(baseUrl: string): Promise<ManagedSignInStart> {\n const payload = await postJson(`${normalizeBaseUrl(baseUrl)}/v1/auth/device/start`, undefined, {\n failurePrefix: 'Managed sign-in start'\n });\n\n if (!isManagedSignInStart(payload)) {\n throw new Error('Managed sign-in start response was invalid.');\n }\n\n return payload;\n}\n\nexport async function pollManagedSignIn(\n baseUrl: string,\n deviceCode: string\n): Promise<ManagedSignInPoll> {\n let payload: unknown;\n try {\n payload = await postJson(\n `${normalizeBaseUrl(baseUrl)}/v1/auth/device/poll`,\n { deviceCode },\n { failurePrefix: 'Managed sign-in poll' }\n );\n } catch (error) {\n if (error instanceof BackendHttpError && error.status === 410) {\n return { status: 'expired' };\n }\n\n throw error;\n }\n\n if (!isManagedSignInPoll(payload)) {\n throw new Error('Managed sign-in poll response was invalid.');\n }\n\n return payload;\n}\n\nexport async function runManagedStation(\n baseUrl: string,\n accessToken: string,\n payload: ManagedStationRequest\n): Promise<ManagedStationResponse> {\n const responsePayload = await postJson(`${normalizeBaseUrl(baseUrl)}/v1/station/run`, payload, {\n accessToken,\n failurePrefix: 'Managed station run'\n });\n\n if (!isManagedStationResponse(responsePayload)) {\n throw new Error('Managed station run response was invalid.');\n }\n\n return responsePayload;\n}\n\nasync function postJson(\n url: string,\n payload: unknown,\n options: { accessToken?: string; failurePrefix: string }\n): Promise<unknown> {\n let response: Response;\n try {\n response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...(options.accessToken ? { Authorization: `Bearer ${options.accessToken}` } : {})\n },\n // Fastify rejects `Content-Type: application/json` with an empty body (FST_ERR_CTP_EMPTY_JSON_BODY).\n body: JSON.stringify(payload === undefined ? {} : payload)\n });\n } catch (error) {\n if (isNetworkFetchFailure(error)) {\n throw new Error(\n `Could not reach the VibeRaven backend at ${url}. Check your network, then sign in again if needed.`,\n { cause: error }\n );\n }\n throw error;\n }\n\n if (!response.ok) {\n const bodyText = await readError(response);\n let upgradeUrl: string | undefined;\n try {\n const parsed = JSON.parse(bodyText) as Record<string, unknown>;\n if (typeof parsed.upgrade_url === 'string' && parsed.upgrade_url.length > 0) {\n upgradeUrl = parsed.upgrade_url;\n }\n } catch {\n /* body may not be JSON */\n }\n throw new BackendHttpError(\n `${options.failurePrefix} failed with ${response.status}: ${bodyText}`,\n response.status,\n upgradeUrl\n );\n }\n\n return response.json();\n}\n\nasync function readError(response: Response): Promise<string> {\n try {\n const body = await response.text();\n return body.trim() || response.statusText || 'Unknown error';\n } catch {\n return response.statusText || 'Unknown error';\n }\n}\n\nexport function normalizeBaseUrl(baseUrl: string): string {\n return baseUrl.replace(/\\/+$/, '');\n}\n\nfunction isManagedSignInStart(value: unknown): value is ManagedSignInStart {\n return (\n isRecord(value) &&\n isNonEmptyString(value.deviceCode) &&\n isNonEmptyString(value.verificationUrl) &&\n typeof value.pollIntervalSeconds === 'number' &&\n value.pollIntervalSeconds > 0 &&\n isNonEmptyString(value.expiresAt)\n );\n}\n\nfunction isManagedSignInPoll(value: unknown): value is ManagedSignInPoll {\n if (!isRecord(value) || !isNonEmptyString(value.status)) {\n return false;\n }\n\n if (value.status === 'pending' || value.status === 'expired' || value.status === 'denied') {\n return true;\n }\n\n return (\n value.status === 'approved' &&\n isNonEmptyString(value.accessToken) &&\n isManagedAccount(value.account)\n );\n}\n\nfunction isManagedStationResponse(value: unknown): value is ManagedStationResponse {\n return (\n isRecord(value) &&\n (value.status === 'stable' || value.status === 'drifting' || value.status === 'chaos') &&\n isNonEmptyString(value.reason) &&\n isNonEmptyString(value.impact) &&\n (value.confidence === 'low' || value.confidence === 'medium' || value.confidence === 'high') &&\n typeof value.output === 'string' &&\n isManagedUsage(value.usage)\n );\n}\n\nfunction isManagedAccount(value: unknown): value is ManagedAccount {\n return (\n isRecord(value) &&\n isNonEmptyString(value.email) &&\n (value.plan === 'free' || value.plan === 'pro') &&\n (value.trialEndsAt === null || isNonEmptyString(value.trialEndsAt))\n );\n}\n\nfunction isManagedUsage(value: unknown): value is ManagedUsage {\n if (!isRecord(value) || (value.plan !== 'free' && value.plan !== 'pro')) {\n return false;\n }\n if (value.remainingPrompts !== null && typeof value.remainingPrompts !== 'number') {\n return false;\n }\n if (typeof value.used !== 'number' || typeof value.limit !== 'number') {\n return false;\n }\n if (value.period !== 'lifetime' && value.period !== 'monthly') {\n return false;\n }\n if (!Array.isArray(value.unlockedMapCategoryKeys)) {\n return false;\n }\n return value.unlockedMapCategoryKeys.every((k) => typeof k === 'string');\n}\n\nexport class BackendHttpError extends Error {\n constructor(\n message: string,\n public readonly status: number,\n public readonly upgradeUrl?: string\n ) {\n super(message);\n }\n}\n\nfunction isOptionalString(value: unknown): boolean {\n return value === undefined || typeof value === 'string';\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === 'string' && value.trim().length > 0;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n", "import { normalizeBaseUrl } from '../../../src/station/backendClient';\r\nimport type { ManagedStationUsage } from '../../../shared/station';\r\nimport { saveCredentials, type CliCredentials } from './config';\r\nimport type { CliScanArtifact } from './types';\r\n\r\nexport interface AccountMeResponse {\r\n email: string;\r\n plan: 'free' | 'pro';\r\n trialEndsAt?: string | null;\r\n usage: ManagedStationUsage;\r\n billing?: {\r\n status?: string | null;\r\n renewsAt?: string | null;\r\n endsAt?: string | null;\r\n currentPeriodStart?: string | null;\r\n };\r\n}\r\n\r\nexport async function fetchAccountMe(\r\n apiBaseUrl: string,\r\n accessToken: string\r\n): Promise<AccountMeResponse> {\r\n const url = `${normalizeBaseUrl(apiBaseUrl)}/v1/account/me`;\r\n let response: Response;\r\n try {\r\n response = await fetch(url, {\r\n headers: { Authorization: `Bearer ${accessToken}` }\r\n });\r\n } catch (error) {\r\n const cause = error instanceof Error ? error.message : String(error);\r\n throw new Error(`Could not reach VibeRaven API at ${url}: ${cause}`);\r\n }\r\n\r\n if (response.status === 401) {\r\n throw new Error('Session expired. Run `viberaven login` again.');\r\n }\r\n\r\n const bodyText = await response.text();\r\n if (!response.ok) {\r\n throw new Error(`Account lookup failed (${response.status}): ${bodyText.trim() || response.statusText}`);\r\n }\r\n\r\n const data = JSON.parse(bodyText) as AccountMeResponse;\r\n if (!data.usage || (data.plan !== 'free' && data.plan !== 'pro')) {\r\n throw new Error('Account response was missing usage or plan.');\r\n }\r\n return data;\r\n}\r\n\r\nexport async function syncCredentialsFromAccount(\r\n credentials: CliCredentials\r\n): Promise<CliCredentialsWithAccount> {\r\n const account = await fetchAccountMe(credentials.apiBaseUrl, credentials.accessToken);\r\n const updated: CliCredentials = {\r\n ...credentials,\r\n email: account.email,\r\n plan: account.plan\r\n };\r\n await saveCredentials(updated);\r\n return { ...updated, account };\r\n}\r\n\r\nexport type CliCredentialsWithAccount = CliCredentials & { account: AccountMeResponse };\r\n\r\n/** Attach account strip fields for static report.html (best-effort). */\r\nexport async function enrichArtifactWithAccount(\r\n artifact: CliScanArtifact,\r\n apiBaseUrl: string,\r\n accessToken: string\r\n): Promise<CliScanArtifact> {\r\n try {\r\n const account = await fetchAccountMe(apiBaseUrl, accessToken);\r\n return {\r\n ...artifact,\r\n accountEmail: account.email,\r\n plan: account.plan,\r\n usage: account.usage,\r\n usageLine: formatUsageLine(account.usage)\r\n };\r\n } catch {\r\n return artifact;\r\n }\r\n}\r\n\r\nexport function formatUsageLine(usage: ManagedStationUsage): string {\r\n const periodLabel = usage.period === 'monthly' ? 'this month' : 'lifetime';\r\n return `Scans: ${usage.used}/${usage.limit} (${periodLabel}, ${usage.plan}) \u00B7 ${usage.remainingPrompts} remaining`;\r\n}\r\n\r\nexport function formatScanLimitMessage(upgradeUrl: string): string {\r\n return [\r\n '',\r\n 'Free scan limit reached. Upgrade to Pro to continue.',\r\n 'Your last scan artifacts are unchanged if you already ran a scan in this repo.',\r\n '',\r\n `Upgrade & account: ${upgradeUrl}`,\r\n ''\r\n ].join('\\n');\r\n}\r\n", "import { pollManagedSignIn, startManagedSignIn } from '../../../src/station/backendClient';\r\nimport { formatUsageLine, syncCredentialsFromAccount } from './account';\r\nimport { loadCredentials, resolveApiBaseUrl, saveCredentials } from './config';\r\n\r\nfunction sleep(ms: number): Promise<void> {\r\n return new Promise((resolve) => setTimeout(resolve, ms));\r\n}\r\n\r\nexport async function runDeviceLogin(apiBaseUrl: string): Promise<void> {\r\n const signIn = await startManagedSignIn(apiBaseUrl);\r\n const verificationUrl = buildVerificationUrl(signIn.verificationUrl, signIn.deviceCode);\r\n\r\n console.log('\\nVibeRaven sign-in\\n');\r\n console.log(`Open: ${verificationUrl}`);\r\n console.log(`Code: ${signIn.deviceCode}\\n`);\r\n console.log('Waiting for approval in the browser\u2026\\n');\r\n\r\n const expiresAt = Date.parse(signIn.expiresAt);\r\n const pollMs = Math.max(2, signIn.pollIntervalSeconds) * 1000;\r\n\r\n while (Date.now() < expiresAt) {\r\n const result = await pollManagedSignIn(apiBaseUrl, signIn.deviceCode);\r\n if (result.status === 'pending') {\r\n await sleep(pollMs);\r\n continue;\r\n }\r\n if (result.status === 'expired') {\r\n throw new Error('Sign-in expired. Run `viberaven login` again.');\r\n }\r\n if (result.status === 'denied') {\r\n throw new Error('Sign-in was denied.');\r\n }\r\n if (result.status === 'approved') {\r\n const baseCreds = {\r\n accessToken: result.accessToken,\r\n apiBaseUrl,\r\n email: result.account?.email,\r\n plan: result.account?.plan\r\n };\r\n await saveCredentials(baseCreds);\r\n try {\r\n const synced = await syncCredentialsFromAccount(baseCreds);\r\n const email = synced.email ?? 'your account';\r\n const usage = synced.account?.usage;\r\n console.log(`Signed in as ${email} (${synced.plan ?? 'unknown'}).`);\r\n if (usage) {\r\n console.log(formatUsageLine(usage));\r\n }\r\n } catch (error) {\r\n const email = result.account?.email ?? 'your account';\r\n console.log(`Signed in as ${email}.`);\r\n console.warn(\r\n error instanceof Error\r\n ? `Could not refresh account usage: ${error.message}`\r\n : 'Could not refresh account usage.'\r\n );\r\n }\r\n return;\r\n }\r\n }\r\n\r\n throw new Error('Sign-in timed out. Run `viberaven login` again.');\r\n}\r\n\r\nfunction buildVerificationUrl(verificationUrl: string, deviceCode: string): string {\r\n try {\r\n const url = new URL(verificationUrl);\r\n url.searchParams.set('device_code', deviceCode);\r\n return url.toString();\r\n } catch {\r\n const separator = verificationUrl.includes('?') ? '&' : '?';\r\n return `${verificationUrl}${separator}device_code=${encodeURIComponent(deviceCode)}`;\r\n }\r\n}\r\n\r\nexport async function requireCredentials(apiBaseUrl?: string): Promise<{\r\n accessToken: string;\r\n apiBaseUrl: string;\r\n}> {\r\n const creds = await loadCredentials();\r\n const base = apiBaseUrl ?? creds?.apiBaseUrl ?? resolveApiBaseUrl();\r\n if (!creds?.accessToken) {\r\n throw new Error('Not signed in. Run `viberaven login` first (or set credentials via device flow).');\r\n }\r\n return { accessToken: creds.accessToken, apiBaseUrl: base };\r\n}\r\n", "import { promises as fs } from 'node:fs';\r\nimport { join, relative, basename, sep } from 'node:path';\r\nimport type { ScanResult, ScannedFile, StackSignalKey } from './types';\r\n\r\nconst ALWAYS_SKIP = new Set([\r\n 'node_modules', '.git', '.next', 'dist', 'build', 'out',\r\n '.cache', 'coverage', '.nyc_output', 'storybook-static',\r\n 'public', 'static', '.turbo', '.vercel'\r\n]);\r\n\r\nconst SECRET_PATTERNS = [\r\n /\\.env$/, /\\.env\\..+/, /\\.pem$/, /\\.key$/,\r\n /\\.p8$/, /\\.p12$/, /\\.pfx$/, /\\.ppk$/,\r\n /secrets?\\./i, /credentials?\\./i, /\\.secret\\./i,\r\n /service[-_]?account/i, /private[-_]?key/i\r\n];\r\n\r\nconst SECRET_FILE_NAMES = new Set([\r\n '.npmrc',\r\n '.netrc',\r\n '.pypirc',\r\n 'id_rsa',\r\n 'id_dsa',\r\n 'id_ecdsa',\r\n 'id_ed25519',\r\n 'npmrc',\r\n 'kubeconfig',\r\n 'dockerconfigjson'\r\n]);\r\n\r\nconst HIGH_SIGNAL_FILES = [\r\n 'package.json', 'tsconfig.json', 'SPEC.md', 'README.md',\r\n '.env.example', 'middleware.ts', 'middleware.js',\r\n 'vite.config.ts', 'vite.config.js',\r\n 'next.config.ts', 'next.config.js',\r\n 'tailwind.config.ts', 'tailwind.config.js',\r\n 'vercel.json', 'sentry.client.config.ts', 'sentry.server.config.ts',\r\n 'playwright.config.ts', 'playwright.config.js',\r\n 'drizzle.config.ts', 'drizzle.config.js',\r\n 'prisma/schema.prisma', 'supabase/config.toml',\r\n 'src/middleware.ts', 'app/middleware.ts',\r\n];\r\n\r\nconst STACK_SIGNAL_PATHS: Record<StackSignalKey, string[]> = {\r\n hasSupabase: ['supabase/config.toml', 'src/utils/supabase.ts', 'lib/supabase.ts'],\r\n hasPrisma: ['prisma/schema.prisma'],\r\n hasDrizzle: ['drizzle.config.ts', 'drizzle.config.js'],\r\n hasMongoose: [],\r\n hasNextJs: ['next.config.ts', 'next.config.js', 'app/layout.tsx'],\r\n hasVite: ['vite.config.ts', 'vite.config.js'],\r\n hasAuth: [\r\n 'middleware.ts', 'src/middleware.ts', 'app/middleware.ts',\r\n 'src/lib/auth.ts', 'lib/auth.ts', 'auth.config.ts'\r\n ],\r\n hasTests: ['jest.config.ts', 'vitest.config.ts'],\r\n hasDocker: ['Dockerfile', 'docker-compose.yml', 'docker-compose.yaml'],\r\n hasCI: ['.github/workflows', '.gitlab-ci.yml', 'circle.yml'],\n hasStripe: [],\n hasPolar: [],\n hasClerk: [],\n hasAuthJs: [],\r\n hasPaddle: [],\r\n hasVercel: ['vercel.json'],\r\n hasSentry: ['sentry.client.config.ts', 'sentry.server.config.ts', 'instrumentation.ts'],\r\n hasPostHog: [],\r\n hasPlaywright: ['playwright.config.ts', 'playwright.config.js'],\r\n hasUpstash: [],\r\n hasTurnstile: [],\r\n hasNeon: [],\r\n hasMongoDb: [],\r\n hasPlanetScale: [],\r\n hasTurso: ['turso/config.toml'],\r\n hasLanding: ['landing', 'pages/index.tsx', 'app/page.tsx', 'index.html'],\r\n hasRateLimit: [],\r\n hasEnvExample: ['.env.example'],\r\n hasRobots: ['public/robots.txt', 'robots.txt'],\r\n hasSitemap: ['public/sitemap.xml', 'sitemap.xml'],\r\n hasErrorBoundary: [],\r\n hasLoadingStates: [],\r\n};\r\n\r\nexport interface DeepScanOptions {\r\n maxFiles: number;\r\n maxBytesPerFile: number;\r\n maxTotalBytes: number;\r\n maxDepth: number;\r\n}\r\n\r\nconst DEFAULT_OPTIONS: DeepScanOptions = {\r\n maxFiles: 80,\r\n maxBytesPerFile: 6000,\r\n maxTotalBytes: 120000,\r\n maxDepth: 8,\r\n};\r\n\r\nexport async function deepScanWorkspace(\r\n workspaceRoot: string,\r\n options: Partial<DeepScanOptions> = {}\r\n): Promise<ScanResult> {\r\n const opts = { ...DEFAULT_OPTIONS, ...options };\r\n let ignoredByGitignore: (relPath: string) => boolean = () => false;\r\n\r\n try {\r\n const gitignoreContent = await fs.readFile(join(workspaceRoot, '.gitignore'), 'utf-8');\r\n ignoredByGitignore = createGitignoreMatcher(gitignoreContent);\r\n } catch {\r\n // No .gitignore is fine\r\n }\r\n\r\n const allFiles: string[] = [];\r\n const secretsFound: string[] = [];\r\n\r\n async function walk(dir: string, depth: number): Promise<void> {\r\n if (depth > opts.maxDepth) return;\r\n let entries: import('node:fs').Dirent<string>[];\r\n try {\r\n entries = await fs.readdir(dir, { withFileTypes: true });\r\n } catch {\r\n return;\r\n }\r\n entries.sort((a, b) => a.name.localeCompare(b.name));\r\n\r\n for (const entry of entries) {\r\n const fullPath = join(dir, entry.name);\r\n const relPath = relative(workspaceRoot, fullPath);\r\n\r\n if (entry.isDirectory()) {\r\n if (ALWAYS_SKIP.has(entry.name)) {\r\n if (entry.name === 'public' || entry.name === 'static') {\r\n await collectPublicMetadataFiles(fullPath, relPath, depth + 1);\r\n }\r\n continue;\r\n }\r\n if (relPath && ignoredByGitignore(relPath)) continue;\r\n await walk(fullPath, depth + 1);\r\n } else {\r\n if (relPath && ignoredByGitignore(relPath)) continue;\r\n if (isSecretFileName(entry.name)) {\r\n secretsFound.push(relPath);\r\n continue;\r\n }\r\n allFiles.push(relPath);\r\n }\r\n }\r\n }\r\n\r\n async function collectPublicMetadataFiles(dir: string, relDir: string, depth: number): Promise<void> {\r\n if (depth > opts.maxDepth) return;\r\n let entries: import('node:fs').Dirent<string>[];\r\n try {\r\n entries = await fs.readdir(dir, { withFileTypes: true });\r\n } catch {\r\n return;\r\n }\r\n entries.sort((a, b) => a.name.localeCompare(b.name));\r\n\r\n for (const entry of entries) {\r\n const fullPath = join(dir, entry.name);\r\n const relPath = join(relDir, entry.name);\r\n if (entry.isDirectory()) {\r\n await collectPublicMetadataFiles(fullPath, relPath, depth + 1);\r\n continue;\r\n }\r\n if (/^(robots\\.txt|sitemap\\.xml)$/i.test(entry.name)) {\r\n allFiles.push(relPath);\r\n }\r\n }\r\n }\r\n\r\n await walk(workspaceRoot, 0);\r\n\r\n const scored = allFiles\r\n .map((f) => ({ path: f, score: scoreFile(f) }))\r\n .sort((a, b) => b.score - a.score || a.path.localeCompare(b.path))\r\n .slice(0, opts.maxFiles);\r\n\r\n let totalBytes = 0;\r\n const scannedFiles: ScannedFile[] = [];\r\n\r\n for (const { path: relPath, score } of scored) {\r\n if (totalBytes >= opts.maxTotalBytes) break;\r\n const fullPath = join(workspaceRoot, relPath);\r\n let content: string | null = null;\r\n let sizeBytes = 0;\r\n\r\n try {\r\n const raw = await fs.readFile(fullPath);\r\n if (isLikelyBinary(raw)) {\r\n scannedFiles.push({ path: relPath, content: null, isSecret: false, sizeBytes: raw.length, heat: Math.round(score) });\r\n continue;\r\n }\r\n const text = raw.toString('utf-8');\r\n const safeText = redactSecretValues(text);\r\n sizeBytes = Buffer.byteLength(text, 'utf-8');\r\n const budget = Math.min(opts.maxBytesPerFile, opts.maxTotalBytes - totalBytes);\r\n content = safeText.slice(0, budget);\r\n totalBytes += Math.min(sizeBytes, budget);\r\n } catch {\r\n // Unreadable file \u2014 still record path\r\n }\r\n\r\n scannedFiles.push({ path: relPath, content, isSecret: false, sizeBytes, heat: Math.round(score) });\r\n }\r\n\r\n // Stack signals from file paths\r\n const allPathsSet = new Set(allFiles);\r\n const stackSignals: Partial<Record<StackSignalKey, boolean>> = {};\r\n\r\n for (const [signal, paths] of Object.entries(STACK_SIGNAL_PATHS) as Array<[StackSignalKey, string[]]>) {\r\n if (paths.length > 0) {\r\n stackSignals[signal] = paths.some(\r\n (p) => allPathsSet.has(p) || [...allPathsSet].some((ap) => ap.replace(/\\\\/g, '/').includes(p))\r\n );\r\n }\r\n }\r\n\r\n // Stack signals from package.json files across monorepos/sub-apps.\r\n const packageDeps = await readPackageDependencies(workspaceRoot, allFiles);\r\n const packageDepsLower = packageDeps.map((dep) => dep.toLowerCase());\r\n const pathBlob = allFiles.map((file) => file.replace(/\\\\/g, '/').toLowerCase()).join('\\n');\r\n const contentBlob = scannedFiles\r\n .filter((file) => !file.isSecret && typeof file.content === 'string')\r\n .map((file) => file.content as string)\r\n .join('\\n')\r\n .toLowerCase();\r\n const repoBlob = `${packageDepsLower.join('\\n')}\\n${pathBlob}\\n${contentBlob}`;\r\n\r\n stackSignals.hasSupabase = Boolean(stackSignals.hasSupabase) || hasPackage(packageDepsLower, ['@supabase/']) || /\\bsupabase\\b/.test(repoBlob);\n stackSignals.hasStripe = hasPackage(packageDepsLower, ['stripe']) || /\\bstripe_(secret_key|webhook_secret)\\b/.test(repoBlob) || /stripe/.test(pathBlob);\n stackSignals.hasPolar = hasPackage(packageDepsLower, ['@polar-sh/']) || /\\bpolar_(access_token|webhook_secret|pro_product_id|sandbox)\\b/.test(repoBlob) || /\\bpolar\\b/.test(pathBlob);\n stackSignals.hasClerk = hasPackage(packageDepsLower, ['@clerk/']) || /\\bclerk_(secret_key|publishable_key)\\b|\\bnext_public_clerk_/.test(repoBlob);\n stackSignals.hasAuthJs = hasPackage(packageDepsLower, ['next-auth', '@auth/']) || /\\b(auth_secret|nextauth_secret)\\b|\\bauth\\.js\\b/.test(repoBlob);\r\n stackSignals.hasAuth = Boolean(stackSignals.hasAuth) || Boolean(stackSignals.hasClerk) || Boolean(stackSignals.hasAuthJs) || /\\bauthmiddleware\\b|\\bclerkmiddleware\\b/.test(repoBlob);\r\n stackSignals.hasPaddle = hasPackage(packageDepsLower, ['@paddle/', 'paddle']) || /\\bpaddle_(api_key|webhook_secret|client_token)\\b/.test(repoBlob);\r\n stackSignals.hasVercel = Boolean(stackSignals.hasVercel) || hasPackage(packageDepsLower, ['@vercel/']) || /\\bvercel\\.json\\b|\\bvercel\\b/.test(repoBlob);\r\n stackSignals.hasSentry = Boolean(stackSignals.hasSentry) || hasPackage(packageDepsLower, ['@sentry/']) || /\\bsentry_dsn\\b|\\bsentry\\.init\\b|\\bsentry\\b/.test(repoBlob);\r\n stackSignals.hasPostHog = hasPackage(packageDepsLower, ['posthog-js', 'posthog-node']) || /\\b(next_public_)?posthog_key\\b|\\bposthog\\.init\\b|\\bposthog\\b/.test(repoBlob);\r\n stackSignals.hasPlaywright = Boolean(stackSignals.hasPlaywright) || hasPackage(packageDepsLower, ['@playwright/test']) || /(^|\\/)playwright\\.config\\.[jt]s\\b|\\.spec\\.[jt]sx?\\b/.test(pathBlob);\r\n stackSignals.hasUpstash = hasPackage(packageDepsLower, ['@upstash/']) || /\\bupstash_redis_rest_(url|token)\\b|\\bupstash\\b/.test(repoBlob);\r\n stackSignals.hasTurnstile = hasPackage(packageDepsLower, ['turnstile']) || /\\bturnstile_(secret_key|site_key)\\b|\\bnext_public_turnstile_site_key\\b|\\bcloudflare turnstile\\b/.test(repoBlob);\r\n stackSignals.hasNeon = hasPackage(packageDepsLower, ['@neondatabase/']) || /\\bneon_database_url\\b|\\bneon\\b/.test(repoBlob);\r\n stackSignals.hasMongoDb = hasPackage(packageDepsLower, ['mongodb', 'mongoose']) || /\\bmongodb_(uri|url)\\b|\\bmongodb\\b/.test(repoBlob);\r\n stackSignals.hasPlanetScale = hasPackage(packageDepsLower, ['@planetscale/database']) || /\\bplanetscale_database_url\\b|\\bplanetscale\\b/.test(repoBlob);\r\n stackSignals.hasTurso = hasPackage(packageDepsLower, ['@libsql/client']) || /\\bturso_(database_url|auth_token)\\b|\\bturso\\b/.test(repoBlob);\r\n stackSignals.hasMongoose = packageDepsLower.includes('mongoose');\r\n stackSignals.hasTests = Boolean(stackSignals.hasTests) || hasPackage(packageDepsLower, ['vitest', 'jest', '@playwright/test', 'cypress']) || /\\.test\\.[jt]sx?\\b|\\.spec\\.[jt]sx?\\b/.test(pathBlob);\r\n stackSignals.hasRateLimit = packageDeps.some((d) =>\r\n ['express-rate-limit', 'rate-limiter-flexible', '@fastify/rate-limit', 'upstash'].some((r) => d.includes(r))\r\n ) || scanContainsRateLimit(scannedFiles);\r\n stackSignals.hasCI = Boolean(stackSignals.hasCI) || /(^|\\n)\\.github\\/workflows\\/[^/\\n]+\\.ya?ml(\\n|$)|(^|\\n)(\\.gitlab-ci\\.yml|circle\\.yml)(\\n|$)/i.test(pathBlob);\r\n stackSignals.hasRobots = Boolean(stackSignals.hasRobots) || /(^|\\n|\\/)robots\\.txt(\\n|$)/i.test(pathBlob);\r\n stackSignals.hasSitemap = Boolean(stackSignals.hasSitemap) || /(^|\\n|\\/)sitemap\\.xml(\\n|$)/i.test(pathBlob);\r\n stackSignals.hasErrorBoundary = Boolean(stackSignals.hasErrorBoundary) ||\r\n /(^|\\n|\\/)(error|error-boundary|errorboundary)\\.[jt]sx?(\\n|$)|(^|\\n).*errorboundary\\.[jt]sx?(\\n|$)/i.test(pathBlob) ||\r\n /\\b(componentdidcatch|errorboundary|react\\.component<.*error)/i.test(contentBlob);\r\n stackSignals.hasLoadingStates = Boolean(stackSignals.hasLoadingStates) ||\r\n /(^|\\n|\\/)(loading|skeleton|spinner)\\.[jt]sx?(\\n|$)|(^|\\n).*skeleton\\.[jt]sx?(\\n|$)/i.test(pathBlob) ||\r\n /\\b(isloading|loading state|suspense fallback|<skeleton|<spinner)/i.test(contentBlob);\r\n\r\n return {\r\n files: scannedFiles,\r\n stackSignals,\r\n packageDeps,\r\n fileTree: allFiles.slice(0, 200).join('\\n'),\r\n secretsFound,\r\n totalFilesScanned: allFiles.length,\r\n };\r\n}\r\n\r\nfunction hasPackage(packageDepsLower: string[], needles: string[]): boolean {\r\n return needles.some((needle) => packageDepsLower.some((dep) => dep === needle || dep.includes(needle)));\r\n}\r\n\r\nfunction scoreFile(relPath: string): number {\r\n const name = basename(relPath);\r\n const parts = relPath.split(sep);\r\n let score = 0;\r\n\r\n if (HIGH_SIGNAL_FILES.some((f) => relPath === f || relPath.replace(/\\\\/g, '/').endsWith(f))) score += 10;\r\n if (/config|Config/.test(name)) score += 6;\r\n if (/auth|middleware|guard|permission|role|policy/i.test(relPath)) score += 7;\r\n if (/schema|migration|seed|\\.prisma/i.test(relPath)) score += 6;\r\n if (/\\.github[/\\\\]workflows[/\\\\].+\\.ya?ml$|\\.gitlab-ci\\.yml$|circle\\.yml$/i.test(relPath)) score += 9;\r\n if (/(^|[/\\\\])robots\\.txt$|(^|[/\\\\])sitemap\\.xml$/i.test(relPath)) score += 9;\r\n if (/sentry\\.(client|server)\\.config\\.[jt]s$|instrumentation\\.[jt]s$/i.test(relPath)) score += 9;\r\n if (/error[-_]?boundary|errorboundary|(^|[/\\\\])error\\.[jt]sx?$/i.test(relPath)) score += 8;\r\n if (/(^|[/\\\\])loading\\.[jt]sx?$|skeleton|spinner/i.test(relPath)) score += 7;\r\n if (/webhook|checkout|billing|rate-?limit|validation|validator/i.test(relPath)) score += 7;\r\n if (parts.includes('api') || parts.includes('routes')) score += 5;\r\n if (['main.ts', 'main.tsx', 'index.ts', 'index.tsx', 'App.tsx', 'App.ts',\r\n 'layout.tsx', 'page.tsx', 'server.ts', 'app.ts'].includes(name)) score += 5;\r\n if (/types?|\\.d\\.ts/.test(name)) score += 3;\r\n if (parts.some((p) => ['hooks', 'store', 'stores', 'context'].includes(p))) score += 4;\r\n if (/db|database/i.test(relPath)) score += 5;\r\n score -= Math.max(0, parts.length - 3) * 0.5;\r\n\r\n return score;\r\n}\r\n\r\nasync function readPackageDependencies(workspaceRoot: string, allFiles: string[]): Promise<string[]> {\r\n const deps = new Set<string>();\r\n const packagePaths = allFiles.filter((file) => basename(file) === 'package.json');\r\n\r\n for (const relPath of packagePaths) {\r\n try {\r\n const raw = await fs.readFile(join(workspaceRoot, relPath), 'utf-8');\r\n const pkg = JSON.parse(raw) as Record<string, unknown>;\r\n for (const key of ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies']) {\r\n const group = pkg[key];\r\n if (!group || typeof group !== 'object' || Array.isArray(group)) {\r\n continue;\r\n }\r\n for (const name of Object.keys(group)) {\r\n deps.add(name);\r\n }\r\n }\r\n } catch {\r\n // Invalid or unreadable package.json files should not fail the scan.\r\n }\r\n }\r\n\r\n return [...deps].sort();\r\n}\r\n\r\nfunction scanContainsRateLimit(files: ScannedFile[]): boolean {\r\n const haystack = files\r\n .filter((file) => typeof file.content === 'string' && /[/\\\\](api|routes|server|src)[/\\\\]|app\\.(ts|js)$/i.test(file.path))\r\n .map((file) => file.content as string)\r\n .join('\\n');\r\n\r\n return /\\b(rateLimit|rateLimiter|rate-limiter|rateLimitBuckets|Too many requests)\\b/i.test(haystack);\r\n}\r\n\r\nfunction redactSecretValues(text: string): string {\r\n return text\r\n .replace(/\\b(sk_(?:live|test)_[A-Za-z0-9]{12,}|sk-proj-[A-Za-z0-9_-]{16,}|sk-[A-Za-z0-9_-]{20,}|whsec_[A-Za-z0-9]{12,}|rk_(?:live|test)_[A-Za-z0-9]{12,})\\b/g, '[REDACTED_SECRET]')\r\n .replace(\r\n /\\b([A-Z0-9_]*(?:SECRET|TOKEN|API_KEY|PRIVATE_KEY|SERVICE_ROLE|PASSWORD|WEBHOOK_SECRET)[A-Z0-9_]*)[ \\t]*=[ \\t]*(['\"]?)([^\\s'\"`#]+)\\2/g,\r\n (_match, key: string, quote: string, value: string) => value.length > 0 ? `${key}=${quote}[REDACTED_SECRET]${quote}` : `${key}=`\r\n );\r\n}\r\n\r\nfunction isSecretFileName(fileName: string): boolean {\r\n if (fileName === '.env.example') {\r\n return false;\r\n }\r\n\r\n if (SECRET_FILE_NAMES.has(fileName.toLowerCase())) {\r\n return true;\r\n }\r\n\r\n return SECRET_PATTERNS.some((pattern) => pattern.test(fileName));\r\n}\r\n\r\nfunction isLikelyBinary(buffer: Buffer): boolean {\r\n return buffer.includes(0);\r\n}\r\n\r\ntype GitignoreRule = {\r\n directoryOnly: boolean;\r\n anchored: boolean;\r\n hasSlash: boolean;\r\n pattern: string;\r\n regex: RegExp;\r\n};\r\n\r\nfunction createGitignoreMatcher(gitignoreContent: string): (relPath: string) => boolean {\r\n const rules = gitignoreContent\r\n .split(/\\r?\\n/)\r\n .map((line) => line.trim())\r\n .filter((line) => line.length > 0 && !line.startsWith('#') && !line.startsWith('!'))\r\n .map(parseGitignoreRule);\r\n\r\n return (relPath: string) => {\r\n const normalized = relPath.replace(/\\\\/g, '/').replace(/^\\/+/, '');\r\n return rules.some((rule) => ruleMatchesPath(rule, normalized));\r\n };\r\n}\r\n\r\nfunction parseGitignoreRule(raw: string): GitignoreRule {\r\n const anchored = raw.startsWith('/');\r\n let pattern = raw.replace(/^\\/+/, '');\r\n const directoryOnly = pattern.endsWith('/');\r\n pattern = pattern.replace(/\\/+$/, '');\r\n const hasSlash = pattern.includes('/');\r\n\r\n return {\r\n directoryOnly,\r\n anchored,\r\n hasSlash,\r\n pattern,\r\n regex: new RegExp(`^${gitignoreGlobToRegex(pattern)}$`)\r\n };\r\n}\r\n\r\nfunction ruleMatchesPath(rule: GitignoreRule, relPath: string): boolean {\r\n const candidates = rule.anchored || rule.hasSlash ? [relPath] : relPath.split('/');\r\n const directMatch = candidates.some((candidate) => rule.regex.test(candidate));\r\n if (directMatch && !rule.directoryOnly) {\r\n return true;\r\n }\r\n if (directMatch && rule.directoryOnly) {\r\n return true;\r\n }\r\n\r\n if (!rule.directoryOnly) {\r\n return false;\r\n }\r\n\r\n if (rule.anchored || rule.hasSlash) {\r\n return relPath === rule.pattern || relPath.startsWith(`${rule.pattern}/`);\r\n }\r\n\r\n return relPath.split('/').includes(rule.pattern);\r\n}\r\n\r\nfunction gitignoreGlobToRegex(pattern: string): string {\r\n let out = '';\r\n for (let i = 0; i < pattern.length; i += 1) {\r\n const ch = pattern[i];\r\n if (ch === '*') {\r\n out += '[^/]*';\r\n continue;\r\n }\r\n if (ch === '?') {\r\n out += '[^/]';\r\n continue;\r\n }\r\n out += escapeRegex(ch);\r\n }\r\n return out;\r\n}\r\n\r\nfunction escapeRegex(value: string): string {\r\n return value.replace(/[|\\\\{}()[\\]^$+?.]/g, '\\\\$&');\r\n}\r\n", "import { promises as fs } from 'node:fs';\r\nimport { join } from 'node:path';\r\nimport { BackendHttpError } from './backendClient';\r\nimport { adaptManagedStationResponse, normalizeModelOutput } from './engines';\r\nimport { isNetworkFetchFailure } from './fetchUtils';\r\nimport { buildMissionGraph } from './missionGraph';\r\nimport { buildProviderRegistrySnapshot } from './providerRegistry';\r\nimport { buildAnalysisPrompt } from './promptBuilder';\r\nimport {\r\n buildProductionConnectionContext,\r\n detectProductionConnectionEvidence,\r\n normalizeProductionChoice,\r\n summarizeProductionConnections\r\n} from './productionConnections';\r\nimport { analyzeRepositoryEvidence } from './repositoryEvidence';\r\nimport { computeStationScanContext } from './scanContext';\r\nimport { buildStaticInfrastructureFlowGraph } from './sifgEngine';\r\nimport { buildStackAutomationContext, buildStackAutomationSummary } from './stackAutomation';\r\nimport { analyzeStackWiring, buildStackWiringContext } from './stackWiring';\r\nimport { buildVerificationEvidenceContext, buildVerificationSummary } from './verification';\r\nimport type { ManagedStationRequest, ManagedStationResponse } from '../../shared/station';\r\nimport type { ProductionConnectionChoices } from './productionConnections';\r\nimport type { SifgGraph } from './sifgTypes';\r\nimport type {\r\n MissionGraph,\r\n ModelStationOutput,\r\n RepositoryEvidenceSummary,\r\n ScanResult,\r\n ScannedFile,\r\n StackAutomationSummary,\r\n StackWiringSummary,\r\n StationScanContext,\r\n VerificationSummary\r\n} from './types';\r\n\r\ninterface StationOrchestratorDeps {\r\n scanWorkspace: (root: string) => Promise<ScanResult>;\r\n fetchStationOutput: (prompt: string, configuration?: unknown) => Promise<Partial<ModelStationOutput>>;\r\n getManagedAccessToken?: () => Promise<string | undefined>;\r\n runManagedStation?: (\r\n accessToken: string,\r\n payload: ManagedStationRequest\r\n ) => Promise<ManagedStationResponse>;\r\n /**\r\n * When false (default for shipped builds), Station never falls back to BYOK/local OpenAI \u2014\r\n * users must be signed in and reach the managed API.\r\n */\r\n isLocalStationFallbackAllowed?: () => boolean | Promise<boolean>;\r\n getProductionConnectionChoices?: () => Promise<ProductionConnectionChoices | undefined>;\r\n}\r\n\r\ninterface StationOrchestratorInput {\r\n workspaceRoot: string;\r\n prompt: string;\r\n configuration?: unknown;\r\n}\r\n\r\nexport interface StationRunResult extends ModelStationOutput {\r\n scannedFiles: ScannedFile[];\r\n scanContext: StationScanContext;\r\n providerRegistry: ReturnType<typeof buildProviderRegistrySnapshot>;\r\n productionConnections: ReturnType<typeof summarizeProductionConnections>;\r\n verificationSummary: VerificationSummary;\r\n stackWiring: StackWiringSummary;\r\n stackAutomation: StackAutomationSummary;\r\n repositoryEvidence: RepositoryEvidenceSummary;\r\n missionGraph: MissionGraph;\r\n staticInfrastructureFlowGraph: SifgGraph;\r\n usage?: ManagedStationResponse['usage'];\r\n}\r\n\r\nexport interface ScanLimitResult {\r\n kind: 'scan_limit_reached';\r\n upgradeUrl: string;\r\n}\r\n\r\nexport interface ManagedRequiredResult {\r\n kind: 'managed_required';\r\n message: string;\r\n}\r\n\r\n/** Managed API rejected the stored access token (wrong server or rotated API secret). */\r\nexport interface ManagedSessionInvalidResult {\r\n kind: 'managed_session_invalid';\r\n message: string;\r\n}\r\n\r\nexport type OrchestratorResult =\r\n | StationRunResult\r\n | ScanLimitResult\r\n | ManagedRequiredResult\r\n | ManagedSessionInvalidResult;\r\n\r\nexport function isScanLimitResult(value: OrchestratorResult): value is ScanLimitResult {\r\n return (value as ScanLimitResult).kind === 'scan_limit_reached';\r\n}\r\n\r\nexport function isManagedRequiredResult(value: OrchestratorResult): value is ManagedRequiredResult {\r\n return (value as ManagedRequiredResult).kind === 'managed_required';\r\n}\r\n\r\nexport function isManagedSessionInvalidResult(\r\n value: OrchestratorResult\r\n): value is ManagedSessionInvalidResult {\r\n return (value as ManagedSessionInvalidResult).kind === 'managed_session_invalid';\r\n}\r\n\r\nexport function createStationOrchestrator(deps: StationOrchestratorDeps) {\r\n return {\r\n async run(input: StationOrchestratorInput): Promise<OrchestratorResult> {\r\n const allowLocal = Boolean(await deps.isLocalStationFallbackAllowed?.());\r\n\r\n const scan = await deps.scanWorkspace(input.workspaceRoot);\r\n const productionConnectionChoices = await loadProductionConnectionChoices(deps);\r\n const productionConnectionEvidence = detectProductionConnectionEvidence(scan);\r\n const productionConnections = summarizeProductionConnections(\r\n productionConnectionChoices,\r\n productionConnectionEvidence\r\n );\r\n const productionConnectionContext = buildProductionConnectionContext(\r\n productionConnectionChoices,\r\n productionConnectionEvidence\r\n );\r\n const verificationSummary = buildVerificationSummary(scan, productionConnections);\r\n const verificationEvidenceContext = buildVerificationEvidenceContext(verificationSummary);\r\n const stackWiring: StackWiringSummary = analyzeStackWiring(scan);\r\n const stackWiringContext = buildStackWiringContext(stackWiring);\r\n const repositoryEvidence = analyzeRepositoryEvidence(scan);\r\n const providerRegistry = buildProviderRegistrySnapshot();\r\n const staticInfrastructureFlowGraph = buildStaticInfrastructureFlowGraph(scan);\r\n const stackAutomation = buildStackAutomationSummary(stackWiring, { staticInfrastructureFlowGraph });\r\n const stackAutomationContext = buildStackAutomationContext(stackAutomation);\r\n const missionGraph = buildMissionGraph({\r\n stackWiring,\r\n repositoryEvidence,\r\n staticInfrastructureFlowGraph\r\n });\r\n const specContent = await readSpec(input.workspaceRoot);\r\n const modelPrompt = buildAnalysisPrompt(\r\n scan,\r\n specContent,\r\n productionConnectionContext,\r\n verificationEvidenceContext,\r\n stackWiringContext,\r\n stackAutomationContext\r\n );\r\n\r\n const managedToken = await deps.getManagedAccessToken?.();\r\n let managedResponse: ManagedStationResponse | undefined;\r\n\r\n if (managedToken && deps.runManagedStation) {\r\n try {\r\n managedResponse = await deps.runManagedStation(managedToken, {\r\n prompt: modelPrompt,\r\n workspacePath: input.workspaceRoot,\r\n specMarkdown: specContent.trim().length > 0 ? specContent : null,\r\n files: scan.files\r\n .filter((f) => !f.isSecret && f.content !== null)\r\n .slice(0, 20)\r\n .map((f) => ({\r\n path: f.path,\r\n summary: f.content!.slice(0, 200),\r\n heat: f.heat >= 7 ? 'hot' : f.heat >= 4 ? 'warm' : 'cool',\r\n })),\r\n });\r\n } catch (error) {\r\n if (error instanceof BackendHttpError && error.status === 402) {\r\n return {\r\n kind: 'scan_limit_reached',\r\n upgradeUrl: error.upgradeUrl ?? 'https://viberice.com/account'\r\n };\r\n }\r\n if (error instanceof BackendHttpError && error.status === 401) {\r\n return {\r\n kind: 'managed_session_invalid',\r\n message:\r\n 'VibeRaven returned 401 Unauthorized for this scan. Your saved sign-in no longer matches the managed API. Use VibeRaven: Sign Out, then VibeRaven: Sign In again.'\r\n };\r\n }\r\n if (isNetworkFetchFailure(error)) {\r\n if (!allowLocal) {\r\n return {\r\n kind: 'managed_required',\r\n message:\r\n 'Could not reach the VibeRaven managed API. This is not a Pro-only restriction \u2014 Free accounts include two managed scans once the server is reachable. Check your connection, then retry.'\r\n };\r\n }\r\n // fall through to BYOK below\r\n } else {\r\n throw error;\r\n }\r\n }\r\n }\r\n\r\n if (managedResponse !== undefined) {\r\n const raw: Partial<ModelStationOutput> = adaptManagedStationResponse(managedResponse);\r\n const normalized = normalizeModelOutput(raw);\r\n const scanContext = computeStationScanContext(scan);\r\n return {\r\n ...normalized,\r\n scannedFiles: scan.files,\r\n scanContext,\r\n providerRegistry,\r\n productionConnections,\r\n verificationSummary,\r\n stackWiring,\r\n stackAutomation,\r\n repositoryEvidence,\r\n missionGraph,\r\n staticInfrastructureFlowGraph,\r\n usage: managedResponse.usage\r\n };\r\n }\r\n\r\n if (!allowLocal) {\r\n return {\r\n kind: 'managed_required',\r\n message:\r\n managedToken && deps.runManagedStation\r\n ? 'Managed scan could not complete. Sign in again or check your VibeRaven backend URL.'\r\n : 'Sign in to VibeRaven (VibeRaven: Sign In) to run managed scans. Local-only API keys are disabled in this build unless you turn on \u201CAllow local Station without managed account\u201D in settings.'\r\n };\r\n }\r\n\r\n const raw: Partial<ModelStationOutput> = await deps.fetchStationOutput(modelPrompt, input.configuration);\r\n const normalized = normalizeModelOutput(raw);\r\n const scanContext = computeStationScanContext(scan);\r\n\r\n return {\r\n ...normalized,\r\n scannedFiles: scan.files,\r\n scanContext,\r\n providerRegistry,\r\n productionConnections,\r\n verificationSummary,\r\n stackWiring,\r\n stackAutomation,\r\n repositoryEvidence,\r\n missionGraph,\r\n staticInfrastructureFlowGraph\r\n };\r\n },\r\n };\r\n}\r\n\r\nasync function readSpec(workspaceRoot: string): Promise<string> {\r\n try {\r\n return await fs.readFile(join(workspaceRoot, 'SPEC.md'), 'utf-8');\r\n } catch {\r\n return '';\r\n }\r\n}\r\n\r\nasync function loadProductionConnectionChoices(\r\n deps: StationOrchestratorDeps\r\n): Promise<ProductionConnectionChoices> {\r\n try {\r\n return normalizeProductionChoice(await deps.getProductionConnectionChoices?.());\r\n } catch {\r\n return normalizeProductionChoice(undefined);\r\n }\r\n}\r\n", "import type {\r\n Gap,\r\n GapCategory,\r\n GapSeverity,\r\n ModelStationOutput,\r\n ProductionMapCategoryKey,\r\n ProductionChecklist,\r\n ToolSuggestion,\r\n} from './types';\r\nimport type { ManagedStationResponse } from '../../shared/station';\r\n\r\nconst VALID_SEVERITY: GapSeverity[] = ['critical', 'warning', 'info'];\r\nconst VALID_CATEGORIES: GapCategory[] = [\r\n 'SECURITY & AUTH', 'DATABASE & DATA', 'ERROR HANDLING', 'DEPLOYMENT',\r\n 'PERFORMANCE', 'MISSING FEATURES', 'EDGE CASES & RISKS', 'LANDING & MARKETING'\r\n];\r\nconst VALID_MAP_CATEGORIES: ProductionMapCategoryKey[] = [\r\n 'appFlow',\r\n 'frontend',\r\n 'backend',\r\n 'auth',\r\n 'database',\r\n 'payments',\r\n 'deployment',\r\n 'monitoring',\r\n 'security',\r\n 'testing',\r\n 'landing',\r\n 'errorHandling',\r\n];\r\nconst MAP_CATEGORY_RULES: Array<{ key: ProductionMapCategoryKey; match: RegExp }> = [\r\n { key: 'monitoring', match: /\\b(monitor|monitoring|observability|sentry|logrocket|posthog|analytics|telemetry|logs?)\\b/i },\r\n { key: 'errorHandling', match: /\\b(error handling|error boundary|exception|unhandled|crash|fallback|failure|failures|rejected promise)\\b/i },\r\n { key: 'auth', match: /\\b(auth|login|logout|session|jwt|oauth|supabase auth|protected route|role|roles|permission|permissions)\\b/i },\r\n { key: 'payments', match: /\\b(payment|payments|billing|checkout|stripe|polar|paddle|subscription|webhook|lemon squeezy|lemonsqueezy|invoice)\\b/i },\r\n { key: 'backend', match: /\\b(backend|api|server|route|handler|endpoint|station run|station runs|fastify|express)\\b/i },\r\n { key: 'security', match: /\\b(security|secret|secrets|rate limit|ratelimit|csrf|xss|bot|abuse|signature)\\b/i },\r\n { key: 'database', match: /\\b(database|data|postgres|mysql|mongo|schema|migration|storage|rls|supabase|repository)\\b/i },\r\n { key: 'deployment', match: /\\b(deploy|deployment|hosting|vercel|netlify|docker|ci|pipeline|environment|env|release)\\b/i },\r\n { key: 'testing', match: /\\b(test|testing|spec|coverage|vitest|jest|playwright|cypress|qa)\\b/i },\r\n { key: 'landing', match: /\\b(landing|marketing|homepage|hero|cta|pricing|seo|sitemap|robots|onboarding|funnel)\\b/i },\r\n { key: 'frontend', match: /\\b(frontend|react|ui|component|layout|state|loading|client)\\b/i },\r\n { key: 'appFlow', match: /\\b(app flow|ux|user flow|journey|activation|empty state)\\b/i },\r\n];\r\nconst SEVERITY_RANK: Record<GapSeverity, number> = { info: 0, warning: 1, critical: 2 };\r\n\r\nfunction isRecord(v: unknown): v is Record<string, unknown> {\r\n return typeof v === 'object' && v !== null && !Array.isArray(v);\r\n}\r\n\r\nfunction clampScore(v: unknown, fallback = 50): number {\r\n if (typeof v !== 'number' || Number.isNaN(v)) return fallback;\r\n return Math.max(0, Math.min(100, Math.round(v)));\r\n}\r\n\r\nfunction stableVisibleScore(v: unknown, fallback = 50): number {\r\n const clamped = clampScore(v, fallback);\r\n return Math.max(0, Math.min(100, Math.round(clamped / 5) * 5));\r\n}\r\n\r\nfunction toStringArray(v: unknown): string[] {\r\n if (!Array.isArray(v)) return [];\r\n return v.filter((item): item is string => typeof item === 'string');\r\n}\r\n\r\nfunction isProductionMapCategoryKey(value: unknown): value is ProductionMapCategoryKey {\r\n return typeof value === 'string' && VALID_MAP_CATEGORIES.includes(value as ProductionMapCategoryKey);\r\n}\r\n\r\nfunction uniqueMapCategories(values: ProductionMapCategoryKey[]): ProductionMapCategoryKey[] {\r\n const seen = new Set<ProductionMapCategoryKey>();\r\n const out: ProductionMapCategoryKey[] = [];\r\n for (const value of values) {\r\n if (!seen.has(value)) {\r\n seen.add(value);\r\n out.push(value);\r\n }\r\n }\r\n return out;\r\n}\r\n\r\nfunction fallbackMapCategoryForGap(category: GapCategory, text: string): ProductionMapCategoryKey {\r\n switch (category) {\r\n case 'SECURITY & AUTH':\r\n return /\\b(auth|login|session|oauth|jwt|role|permission|protected route)\\b/i.test(text) ? 'auth' : 'security';\r\n case 'DATABASE & DATA':\r\n return 'database';\r\n case 'ERROR HANDLING':\r\n return 'errorHandling';\r\n case 'DEPLOYMENT':\r\n return 'deployment';\r\n case 'PERFORMANCE':\r\n return 'frontend';\r\n case 'LANDING & MARKETING':\r\n return 'landing';\r\n case 'EDGE CASES & RISKS':\r\n return 'testing';\r\n case 'MISSING FEATURES':\r\n default:\r\n return 'appFlow';\r\n }\r\n}\r\n\r\nfunction inferMapCategories(\r\n category: GapCategory,\r\n title: string,\r\n detail: string,\r\n copyPrompt: string,\r\n explicitPrimary: unknown,\r\n explicitAffected: unknown\r\n): ProductionMapCategoryKey[] {\r\n const text = [category, title, detail, copyPrompt].filter(Boolean).join(' ');\r\n const fallback = fallbackMapCategoryForGap(category, text);\r\n const matched = MAP_CATEGORY_RULES.filter((rule) => rule.match.test(text)).map((rule) => rule.key);\r\n const explicit = isProductionMapCategoryKey(explicitPrimary) ? [explicitPrimary] : [];\r\n const affected = Array.isArray(explicitAffected)\r\n ? explicitAffected.filter(isProductionMapCategoryKey)\r\n : [];\r\n\r\n const primarySeed = matched[0] ? [matched[0], fallback] : [fallback];\r\n return uniqueMapCategories([...explicit, ...primarySeed, ...matched, ...affected]);\r\n}\r\n\r\nfunction slugify(value: string): string {\r\n return value\r\n .trim()\r\n .toLowerCase()\r\n .replace(/&/g, 'and')\r\n .replace(/[^a-z0-9]+/g, '-')\r\n .replace(/^-+|-+$/g, '')\r\n .slice(0, 52);\r\n}\r\n\r\nfunction normalizeToolSuggestion(v: unknown): ToolSuggestion | null {\r\n if (!isRecord(v)) return null;\r\n const name = typeof v.name === 'string' ? v.name.trim() : '';\r\n const url = typeof v.url === 'string' ? v.url.trim() : '';\r\n if (!name || !url) return null;\r\n return { name, url, reason: typeof v.reason === 'string' ? v.reason : '' };\r\n}\r\n\r\nexport function normalizeGap(v: unknown): Gap | null {\r\n if (!isRecord(v)) return null;\r\n const title = typeof v.title === 'string' ? v.title.trim() : '';\r\n const copyPrompt = typeof v.copyPrompt === 'string' ? v.copyPrompt.trim() : '';\r\n if (!title || !copyPrompt) return null;\r\n\r\n const severity = VALID_SEVERITY.includes(v.severity as GapSeverity)\r\n ? (v.severity as GapSeverity)\r\n : 'warning';\r\n\r\n const category = VALID_CATEGORIES.includes(v.category as GapCategory)\r\n ? (v.category as GapCategory)\r\n : 'MISSING FEATURES';\r\n\r\n const toolSuggestions = Array.isArray(v.toolSuggestions)\r\n ? v.toolSuggestions.map(normalizeToolSuggestion).filter((t): t is ToolSuggestion => t !== null)\r\n : [];\r\n\r\n const affectedMapCategories = inferMapCategories(\r\n category,\r\n title,\r\n typeof v.detail === 'string' ? v.detail : '',\r\n copyPrompt,\r\n v.primaryMapCategory,\r\n v.affectedMapCategories\r\n );\r\n\r\n return {\r\n id: typeof v.id === 'string' && v.id.trim() ? v.id.trim() : `gap-${slugify(title) || 'root'}`,\r\n category,\r\n severity,\r\n title,\r\n detail: typeof v.detail === 'string' ? v.detail : '',\r\n copyPrompt,\r\n toolSuggestions,\r\n mcpSuggestion: typeof v.mcpSuggestion === 'string' ? v.mcpSuggestion : null,\r\n primaryMapCategory: affectedMapCategories[0],\r\n affectedMapCategories,\r\n };\r\n}\r\n\r\nfunction rootGapKey(gap: Gap): string {\r\n const titleKey = slugify(gap.title);\r\n if (titleKey) {\r\n return titleKey;\r\n }\r\n return slugify([gap.category, gap.copyPrompt].join(' ')) || gap.id;\r\n}\r\n\r\nfunction mergeToolSuggestions(a: ToolSuggestion[], b: ToolSuggestion[]): ToolSuggestion[] {\r\n const seen = new Set<string>();\r\n const out: ToolSuggestion[] = [];\r\n for (const tool of [...a, ...b]) {\r\n const key = `${tool.name.trim().toLowerCase()}|${tool.url.trim().toLowerCase()}`;\r\n if (!seen.has(key)) {\r\n seen.add(key);\r\n out.push(tool);\r\n }\r\n }\r\n return out;\r\n}\r\n\r\nfunction mergeRootGaps(a: Gap, b: Gap): Gap {\r\n const severity = SEVERITY_RANK[b.severity] > SEVERITY_RANK[a.severity] ? b.severity : a.severity;\r\n return {\r\n ...a,\r\n severity,\r\n detail: b.detail.length > a.detail.length ? b.detail : a.detail,\r\n copyPrompt: b.copyPrompt.length > a.copyPrompt.length ? b.copyPrompt : a.copyPrompt,\r\n toolSuggestions: mergeToolSuggestions(a.toolSuggestions, b.toolSuggestions),\r\n mcpSuggestion: a.mcpSuggestion ?? b.mcpSuggestion,\r\n primaryMapCategory: a.primaryMapCategory,\r\n affectedMapCategories: a.affectedMapCategories,\r\n };\r\n}\r\n\r\nfunction dedupeRootGaps(gaps: Gap[]): Gap[] {\r\n const byKey = new Map<string, Gap>();\r\n const order: string[] = [];\r\n for (const gap of gaps) {\r\n const key = rootGapKey(gap);\r\n const existing = byKey.get(key);\r\n if (!existing) {\r\n byKey.set(key, gap);\r\n order.push(key);\r\n continue;\r\n }\r\n byKey.set(key, mergeRootGaps(existing, gap));\r\n }\r\n return order.map((key) => byKey.get(key)).filter((gap): gap is Gap => Boolean(gap));\r\n}\r\n\r\nfunction normalizeChecklist(v: unknown): ProductionChecklist {\r\n const defaults: ProductionChecklist = {\r\n security: 50, database: 50, auth: 50, errorHandling: 50,\r\n deployment: 50, testing: 50, landing: 50, monitoring: 50\r\n };\r\n if (!isRecord(v)) return defaults;\r\n return {\r\n security: clampScore(v.security),\r\n database: clampScore(v.database),\r\n auth: clampScore(v.auth),\r\n errorHandling: clampScore(v.errorHandling),\r\n deployment: clampScore(v.deployment),\r\n testing: clampScore(v.testing),\r\n landing: clampScore(v.landing),\r\n monitoring: clampScore(v.monitoring),\r\n };\r\n}\r\n\r\nexport function normalizeModelOutput(raw: Partial<ModelStationOutput>): ModelStationOutput {\r\n const gaps = Array.isArray(raw.gaps)\r\n ? raw.gaps.map(normalizeGap).filter((g): g is Gap => g !== null)\r\n : [];\r\n const uniqueGaps = dedupeRootGaps(gaps);\r\n\r\n return {\r\n score: stableVisibleScore(raw.score),\r\n scoreLabel: typeof raw.scoreLabel === 'string' && raw.scoreLabel.trim() ? raw.scoreLabel : 'Drifting',\r\n summary: typeof raw.summary === 'string' && raw.summary.trim() ? raw.summary : 'Scan complete.',\r\n archetype: typeof raw.archetype === 'string' && raw.archetype.trim() ? raw.archetype : 'unknown',\r\n gaps: uniqueGaps,\r\n stackDetected: toStringArray(raw.stackDetected),\r\n missingLayers: toStringArray(raw.missingLayers),\r\n quickWins: toStringArray(raw.quickWins),\r\n productionChecklist: normalizeChecklist(raw.productionChecklist),\r\n };\r\n}\r\n\r\nexport function adaptManagedStationResponse(response: ManagedStationResponse): ModelStationOutput {\r\n const structured = parseManagedStructuredOutput(response.output);\r\n if (structured) {\r\n return structured;\r\n }\r\n\r\n const scoreMap: Record<string, number> = { stable: 75, drifting: 50, chaos: 25 };\r\n const labelMap: Record<string, string> = { stable: 'Stable', drifting: 'Drifting', chaos: 'Chaos' };\r\n const score = scoreMap[response.status] ?? 50;\r\n\r\n const gaps: Gap[] = [];\r\n if (response.output && response.output.trim()) {\r\n gaps.push({\r\n id: 'managed-output',\r\n category: 'MISSING FEATURES',\r\n severity: 'warning',\r\n title: 'Station recommendation',\r\n detail: response.reason,\r\n copyPrompt: response.output,\r\n toolSuggestions: [],\r\n mcpSuggestion: null,\r\n primaryMapCategory: 'appFlow',\r\n affectedMapCategories: ['appFlow'],\r\n });\r\n }\r\n\r\n const checklist: ProductionChecklist = {\r\n security: score, database: score, auth: score, errorHandling: score,\r\n deployment: score, testing: score, landing: score, monitoring: score,\r\n };\r\n\r\n return {\r\n score,\r\n scoreLabel: labelMap[response.status] ?? 'Drifting',\r\n summary: response.reason,\r\n archetype: 'unknown',\r\n gaps,\r\n stackDetected: [],\r\n missingLayers: [],\r\n quickWins: [],\r\n productionChecklist: checklist,\r\n };\r\n}\r\n\r\nfunction parseManagedStructuredOutput(output: string): ModelStationOutput | null {\r\n try {\r\n const parsed = JSON.parse(output) as Partial<ModelStationOutput>;\r\n if (!Array.isArray(parsed.gaps) || !isRecord(parsed.productionChecklist)) {\r\n return null;\r\n }\r\n return normalizeModelOutput(parsed);\r\n } catch {\r\n return null;\r\n }\r\n}\r\n", "import type {\r\n ProductionConnectionProvider,\r\n StackWiringArea,\r\n StackWiringKey,\r\n StackWiringProvider\r\n} from './types';\r\n\r\ntype SifgTemplateRegistryProvider =\r\n | StackWiringProvider\r\n | ProductionConnectionProvider\r\n | 'netlify'\r\n | 'aws'\r\n | 'playwright';\r\n\r\nexport interface SifgTemplate {\r\n id: string;\r\n label: string;\r\n registryProvider: SifgTemplateRegistryProvider;\r\n providerKey: StackWiringKey;\r\n area: StackWiringArea;\r\n sourceMatchers: Array<Record<string, string>>;\r\n requiredGuards: Array<{\r\n kind: string;\r\n symbols: string[];\r\n requiresEnvNames?: string[];\r\n mustPrecede: string[];\r\n }>;\r\n forbiddenFlows: Array<Record<string, string>>;\r\n repoFixPolicy: {\r\n allowedFileGlobs: string[];\r\n blockedFileGlobs: string[];\r\n requiresApproval: true;\r\n };\r\n}\r\n\r\nconst BLOCKED_PRODUCT_GLOBS = ['landing/**', 'services/api/**', 'marketing/**'];\r\n\r\nconst TEMPLATES: SifgTemplate[] = [\r\n {\r\n id: 'template:payments:stripe:webhook-ingress',\r\n label: 'Stripe webhook ingress',\r\n registryProvider: 'stripe',\r\n providerKey: 'stripe-payments',\r\n area: 'payments',\r\n sourceMatchers: [\r\n { kind: 'route-handler', framework: 'nextjs-app-router', routePattern: '/api/**/stripe/**', method: 'POST' },\r\n { kind: 'sdk-symbol', importName: 'stripe', member: 'webhooks.constructEvent' }\r\n ],\r\n requiredGuards: [\r\n {\r\n kind: 'signature-verifier',\r\n symbols: ['stripe.webhooks.constructEvent'],\r\n requiresEnvNames: ['STRIPE_WEBHOOK_SECRET'],\r\n mustPrecede: ['database-write', 'entitlement-update', 'provider-mutation']\r\n },\r\n {\r\n kind: 'idempotency-guard',\r\n symbols: ['event.id', 'idempotencyKey', 'processed_events'],\r\n mustPrecede: ['entitlement-update']\r\n }\r\n ],\r\n forbiddenFlows: [\r\n { from: 'request-body', to: 'database-write', unlessGuardedBy: 'signature-verifier' },\r\n { from: 'env:STRIPE_SECRET_KEY', to: 'client-bundle', severity: 'critical' }\r\n ],\r\n repoFixPolicy: {\r\n allowedFileGlobs: ['app/**/route.ts', 'src/server/**', 'lib/server/**'],\r\n blockedFileGlobs: BLOCKED_PRODUCT_GLOBS,\r\n requiresApproval: true\r\n }\r\n },\r\n {\r\n id: 'template:auth:protected-data-access',\r\n label: 'Protected data access',\r\n registryProvider: 'clerk',\r\n providerKey: 'clerk-auth',\r\n area: 'auth',\r\n sourceMatchers: [{ kind: 'route-handler', routePattern: '/api/**', method: 'ANY' }],\r\n requiredGuards: [{ kind: 'auth-guard', symbols: ['auth', 'getServerSession', 'currentUser'], mustPrecede: ['database-read', 'database-write'] }],\r\n forbiddenFlows: [{ from: 'private-data', to: 'response', unlessGuardedBy: 'auth-guard' }],\r\n repoFixPolicy: {\r\n allowedFileGlobs: ['app/**/route.ts', 'src/server/**', 'lib/server/**', 'middleware.ts', 'src/middleware.ts'],\r\n blockedFileGlobs: BLOCKED_PRODUCT_GLOBS,\r\n requiresApproval: true\r\n }\r\n },\r\n {\r\n id: 'template:database:supabase:service-role-boundary',\r\n label: 'Supabase service role boundary',\r\n registryProvider: 'supabase',\r\n providerKey: 'supabase-database',\r\n area: 'database',\r\n sourceMatchers: [{ kind: 'env-read', envName: 'SUPABASE_SERVICE_ROLE_KEY' }],\r\n requiredGuards: [{ kind: 'server-only-boundary', symbols: ['server-only'], mustPrecede: ['database-read', 'database-write'] }],\r\n forbiddenFlows: [{ from: 'env:SUPABASE_SERVICE_ROLE_KEY', to: 'client-bundle', severity: 'critical' }],\r\n repoFixPolicy: {\r\n allowedFileGlobs: ['src/server/**', 'lib/server/**', 'app/**/route.ts', 'supabase/**'],\r\n blockedFileGlobs: BLOCKED_PRODUCT_GLOBS,\r\n requiresApproval: true\r\n }\r\n },\r\n {\r\n id: 'template:security:public-route-abuse-guard',\r\n label: 'Public route abuse guard',\r\n registryProvider: 'rate-limit',\r\n providerKey: 'rate-limit-security',\r\n area: 'security',\r\n sourceMatchers: [{ kind: 'route-handler', routePattern: '/api/**', method: 'ANY' }],\r\n requiredGuards: [{ kind: 'rate-limit-guard', symbols: ['ratelimit', 'rateLimit', 'upstash'], mustPrecede: ['provider-mutation', 'database-write'] }],\r\n forbiddenFlows: [{ from: 'public-request', to: 'expensive-sink', unlessGuardedBy: 'rate-limit-guard' }],\r\n repoFixPolicy: {\r\n allowedFileGlobs: ['app/**/route.ts', 'src/server/**', 'lib/server/**'],\r\n blockedFileGlobs: BLOCKED_PRODUCT_GLOBS,\r\n requiresApproval: true\r\n }\r\n },\r\n {\r\n id: 'template:security:secret-boundary',\r\n label: 'Secret boundary',\r\n registryProvider: 'secrets-hygiene',\r\n providerKey: 'secrets-hygiene-security',\r\n area: 'security',\r\n sourceMatchers: [{ kind: 'env-read', envName: '*' }],\r\n requiredGuards: [{ kind: 'server-only-boundary', symbols: ['server-only'], mustPrecede: ['client-bundle'] }],\r\n forbiddenFlows: [{ from: 'env:*', to: 'client-bundle', severity: 'critical' }],\r\n repoFixPolicy: {\r\n allowedFileGlobs: ['src/**', 'lib/**', 'app/**'],\r\n blockedFileGlobs: BLOCKED_PRODUCT_GLOBS,\r\n requiresApproval: true\r\n }\r\n },\r\n {\r\n id: 'template:errorHandling:safe-error-response',\r\n label: 'Safe error response',\r\n registryProvider: 'sentry',\r\n providerKey: 'sentry-error-handling',\r\n area: 'errorHandling',\r\n sourceMatchers: [{ kind: 'throw-or-catch', routePattern: '/api/**' }],\r\n requiredGuards: [{ kind: 'error-capture', symbols: ['Sentry.captureException', 'captureException'], mustPrecede: ['safe-response'] }],\r\n forbiddenFlows: [{ from: 'provider-error', to: 'client-response', unlessGuardedBy: 'safe-response' }],\r\n repoFixPolicy: {\r\n allowedFileGlobs: ['app/**/route.ts', 'src/server/**', 'lib/server/**'],\r\n blockedFileGlobs: BLOCKED_PRODUCT_GLOBS,\r\n requiresApproval: true\r\n }\r\n }\r\n];\r\n\r\nexport const SIFG_TEMPLATE_IDS = TEMPLATES.map((template) => template.id);\r\n\r\nexport function allSifgTemplates(): SifgTemplate[] {\r\n return TEMPLATES.map((template) => ({\r\n ...template,\r\n sourceMatchers: template.sourceMatchers.map((matcher) => ({ ...matcher })),\r\n requiredGuards: template.requiredGuards.map((guard) => ({\r\n ...guard,\r\n symbols: [...guard.symbols],\r\n requiresEnvNames: guard.requiresEnvNames ? [...guard.requiresEnvNames] : undefined,\r\n mustPrecede: [...guard.mustPrecede]\r\n })),\r\n forbiddenFlows: template.forbiddenFlows.map((flow) => ({ ...flow })),\r\n repoFixPolicy: {\r\n allowedFileGlobs: [...template.repoFixPolicy.allowedFileGlobs],\r\n blockedFileGlobs: [...template.repoFixPolicy.blockedFileGlobs],\r\n requiresApproval: true\r\n }\r\n }));\r\n}\r\n\r\nexport function sifgTemplatesForProviderKey(providerKey: StackWiringKey): SifgTemplate[] {\r\n return allSifgTemplates().filter((template) => template.providerKey === providerKey);\r\n}\r\n\r\nexport function sifgTemplatesForRegistryProviderArea(\r\n registryProvider: SifgTemplateRegistryProvider,\r\n area: StackWiringArea\r\n): SifgTemplate[] {\r\n return allSifgTemplates().filter((template) =>\r\n template.registryProvider === registryProvider && template.area === area\r\n );\r\n}\r\n", "import type {\r\n ProductionConnectionArea,\r\n ProductionConnectionProvider,\r\n ProviderMcpTemplate,\r\n ProviderRegistryEntry,\r\n ProviderRegistrySnapshot,\r\n ProviderRegistryStatus,\r\n StackWiringArea,\r\n StackWiringKey\r\n} from './types';\r\nimport { sifgTemplatesForRegistryProviderArea } from './sifgTemplates';\r\n\r\nexport const PROVIDER_REGISTRY_STALE_AFTER_DAYS = 45;\r\n\r\ntype RegistryProvider = ProviderRegistryEntry['provider'];\r\ntype NonProductionRegistryProvider = Exclude<RegistryProvider, ProductionConnectionProvider>;\r\ntype ProviderSeedBase = Omit<ProviderRegistryEntry, 'provider' | 'productionAreas' | 'status'>;\r\ntype ProductionProviderSeed = ProviderSeedBase & {\r\n provider: ProductionConnectionProvider;\r\n productionAreas: ProductionConnectionArea[];\r\n};\r\ntype NonProductionProviderSeed = ProviderSeedBase & {\r\n provider: NonProductionRegistryProvider;\r\n productionAreas: [];\r\n};\r\ntype ProviderSeed = ProductionProviderSeed | NonProductionProviderSeed;\r\n\r\nconst PROVIDERS: ProviderSeed[] = [\r\n provider('supabase', 'Supabase', ['supabase'], ['database', 'landing'], ['database', 'auth'], 'supabase', {\r\n docsUrl: 'https://supabase.com/docs',\r\n dashboardUrl: 'https://supabase.com/dashboard',\r\n mcp: {\r\n label: 'Supabase',\r\n serverName: 'supabase',\r\n vscodeServer: { type: 'http', url: 'https://mcp.supabase.com/mcp?read_only=true' },\r\n cursorServer: { url: 'https://mcp.supabase.com/mcp?read_only=true' },\r\n keyInstructions: 'For hosted Supabase MCP, no API key goes in this file. Your IDE opens browser OAuth after you add the server. A Supabase access token is only needed for CI/manual-header setups, where it is passed as Authorization: Bearer ${SUPABASE_ACCESS_TOKEN}.'\r\n },\r\n verification: { supportsReadOnly: true }\r\n }),\r\n provider('supabase-auth', 'Supabase Auth', ['supabaseauth'], ['auth'], [], 'supabase', {\r\n docsUrl: 'https://supabase.com/docs/guides/auth',\r\n dashboardUrl: 'https://supabase.com/dashboard'\r\n }),\r\n provider('clerk', 'Clerk', ['clerk'], ['auth'], ['auth'], 'clerk', {\r\n docsUrl: 'https://clerk.com/docs',\r\n dashboardUrl: 'https://dashboard.clerk.com',\r\n mcp: {\r\n label: 'Clerk',\r\n serverName: 'clerk',\r\n vscodeServer: { type: 'http', url: 'https://mcp.clerk.com/mcp' },\r\n cursorServer: { url: 'https://mcp.clerk.com/mcp' },\r\n keyInstructions: 'Clerk MCP uses your Clerk credentials. If your IDE asks for a token, create one from the Clerk Dashboard developer settings.'\r\n },\r\n verification: { supportsReadOnly: true }\r\n }),\r\n provider('authjs', 'Auth.js', ['authjs', 'auth', 'nextauth'], ['auth'], ['auth'], 'authjs', {\r\n docsUrl: 'https://authjs.dev'\r\n }),\r\n provider('neon', 'Neon', ['neon'], ['database'], ['database'], 'neon', {\r\n docsUrl: 'https://neon.tech/docs',\r\n dashboardUrl: 'https://console.neon.tech',\r\n mcp: {\r\n label: 'Neon',\r\n serverName: 'neon',\r\n vscodeServer: { type: 'http', url: 'https://mcp.neon.tech/mcp' },\r\n cursorServer: { url: 'https://mcp.neon.tech/mcp' },\r\n keyInstructions: 'Neon MCP normally opens browser OAuth. Use Neon project/database credentials only when your IDE asks for them.'\r\n },\r\n verification: { supportsReadOnly: true }\r\n }),\r\n provider('planetscale', 'PlanetScale', ['planetscale'], ['database'], ['database'], 'planetscale', {\r\n docsUrl: 'https://planetscale.com/docs',\r\n dashboardUrl: 'https://app.planetscale.com',\r\n mcp: {\r\n label: 'PlanetScale',\r\n serverName: 'planetscale',\r\n vscodeServer: { type: 'http', url: 'https://mcp.pscale.dev/mcp/planetscale' },\r\n cursorServer: { url: 'https://mcp.pscale.dev/mcp/planetscale' },\r\n keyInstructions: 'PlanetScale MCP normally opens browser OAuth. Use a PlanetScale service token only for local/manual fallback setups.'\r\n },\r\n verification: { supportsReadOnly: true }\r\n }),\r\n provider('mongodb', 'MongoDB Atlas', ['mongodb', 'mongodbatlas'], ['database'], ['database'], 'mongodb', {\r\n docsUrl: 'https://www.mongodb.com/docs',\r\n dashboardUrl: 'https://cloud.mongodb.com',\r\n mcp: {\r\n label: 'MongoDB',\r\n serverName: 'mongodb',\r\n vscodeServer: { type: 'stdio', command: 'npx', args: ['-y', 'mongodb-mcp-server', '--connectionString', 'mongodb://localhost:27017/myDatabase', '--readOnly'] },\r\n cursorServer: { command: 'npx', args: ['-y', 'mongodb-mcp-server', '--connectionString', 'mongodb://localhost:27017/myDatabase', '--readOnly'] },\r\n keyInstructions: 'MongoDB MCP runs locally. Replace the connection string placeholder with a local or Atlas connection string and keep readOnly until you trust the workflow.'\r\n },\r\n verification: { supportsReadOnly: false }\r\n }),\r\n provider('turso', 'Turso', ['turso'], ['database'], ['database'], 'turso', {\r\n docsUrl: 'https://docs.turso.tech',\r\n dashboardUrl: 'https://app.turso.tech'\r\n }),\r\n provider('stripe', 'Stripe', ['stripe'], ['payments'], ['payments'], 'stripe', {\r\n docsUrl: 'https://docs.stripe.com',\r\n dashboardUrl: 'https://dashboard.stripe.com',\r\n mcp: {\r\n label: 'Stripe',\r\n serverName: 'stripe',\r\n vscodeServer: { type: 'http', url: 'https://mcp.stripe.com' },\r\n cursorServer: { url: 'https://mcp.stripe.com' },\r\n keyInstructions: 'Stripe remote MCP normally authenticates with OAuth in the IDE. For local or custom bearer-token setups, use a restricted Stripe secret key from Developers > API keys.'\r\n },\r\n verification: { supportsReadOnly: true }\r\n }),\r\n provider('paddle', 'Paddle', ['paddle'], ['payments'], ['payments'], 'paddle', {\n docsUrl: 'https://developer.paddle.com',\n dashboardUrl: 'https://vendors.paddle.com',\n mcp: {\r\n label: 'Paddle',\r\n serverName: 'paddle',\r\n vscodeServer: { type: 'stdio', command: 'npx', args: ['-y', '@paddle/paddle-mcp', '--api-key=YOUR_API_KEY', '--environment=sandbox', '--tools=non-destructive'] },\r\n cursorServer: { command: 'npx', args: ['-y', '@paddle/paddle-mcp', '--api-key=YOUR_API_KEY', '--environment=sandbox', '--tools=non-destructive'] },\r\n keyInstructions: 'Paddle MCP needs your Paddle authentication. Replace YOUR_API_KEY with a sandbox or production API key before enabling write-capable tools.'\r\n },\n verification: { supportsReadOnly: false }\n }),\n provider('polar', 'Polar', ['polar', 'polarsh'], ['payments'], ['payments'], 'polar', {\n docsUrl: 'https://polar.sh/docs',\n dashboardUrl: 'https://polar.sh/dashboard',\n verification: { supportsReadOnly: false }\n }),\n provider('vercel', 'Vercel', ['vercel'], ['deployment'], ['deployment'], 'vercel', {\n docsUrl: 'https://vercel.com/docs',\r\n dashboardUrl: 'https://vercel.com/dashboard',\r\n mcp: {\r\n label: 'Vercel',\r\n serverName: 'vercel',\r\n vscodeServer: { type: 'http', url: 'https://mcp.vercel.com' },\r\n cursorServer: { url: 'https://mcp.vercel.com' },\r\n keyInstructions: 'Vercel MCP is a remote OAuth server. Finish the browser sign-in your IDE opens; only use a Vercel token for a separate CLI/local fallback.'\r\n },\r\n verification: { supportsReadOnly: true }\r\n }),\r\n provider('netlify', 'Netlify', ['netlify'], ['deployment'], [], 'netlify', {\r\n docsUrl: 'https://docs.netlify.com',\r\n dashboardUrl: 'https://app.netlify.com',\r\n mcp: {\r\n label: 'Netlify',\r\n serverName: 'netlify',\r\n vscodeServer: { type: 'stdio', command: 'npx', args: ['-y', '@netlify/mcp'] },\r\n cursorServer: { command: 'npx', args: ['-y', '@netlify/mcp'] },\r\n keyInstructions: 'Netlify MCP uses Netlify authentication from the IDE or CLI. Finish the browser sign-in or token prompt it opens.'\r\n },\r\n verification: { supportsReadOnly: false }\r\n }),\r\n provider('aws', 'AWS', ['aws'], ['deployment'], [], 'aws', {\r\n docsUrl: 'https://docs.aws.amazon.com',\r\n dashboardUrl: 'https://console.aws.amazon.com'\r\n }),\r\n provider('sentry', 'Sentry', ['sentry'], ['monitoring', 'errorHandling'], ['monitoring'], 'sentry', {\r\n docsUrl: 'https://docs.sentry.io',\r\n dashboardUrl: 'https://sentry.io',\r\n mcp: {\r\n label: 'Sentry',\r\n serverName: 'sentry',\r\n vscodeServer: { type: 'http', url: 'https://mcp.sentry.dev/mcp' },\r\n cursorServer: { url: 'https://mcp.sentry.dev/mcp' },\r\n keyInstructions: 'Sentry MCP is a remote MCP server. Finish the IDE/browser authentication flow; only use a Sentry auth token for separate local or CLI fallback setups.'\r\n },\r\n verification: { supportsReadOnly: true }\r\n }),\r\n provider('posthog', 'PostHog', ['posthog'], ['monitoring', 'errorHandling', 'landing'], ['monitoring'], 'posthog', {\r\n docsUrl: 'https://posthog.com/docs',\r\n dashboardUrl: 'https://app.posthog.com',\r\n mcp: {\r\n label: 'PostHog',\r\n serverName: 'posthog',\r\n vscodeServer: { type: 'http', url: 'https://mcp.posthog.com/mcp' },\r\n cursorServer: { url: 'https://mcp.posthog.com/mcp' },\r\n keyInstructions: 'PostHog MCP opens an authentication flow. Use a PostHog personal API key only if the IDE or local fallback asks for one.'\r\n },\r\n verification: { supportsReadOnly: true }\r\n }),\r\n provider('logrocket', 'LogRocket', ['logrocket'], ['monitoring'], ['monitoring'], 'logrocket', {\r\n docsUrl: 'https://docs.logrocket.com',\r\n dashboardUrl: 'https://app.logrocket.com'\r\n }),\r\n provider('playwright', 'Playwright', ['playwright', 'playwrighttest'], ['testing'], [], 'playwright', {\r\n docsUrl: 'https://playwright.dev/docs/intro',\r\n mcp: {\r\n label: 'Playwright',\r\n serverName: 'playwright',\r\n vscodeServer: { type: 'stdio', command: 'npx', args: ['-y', '@playwright/mcp@latest'] },\r\n cursorServer: { command: 'npx', args: ['-y', '@playwright/mcp@latest'] },\r\n keyInstructions: 'Playwright MCP runs locally through npx and normally does not need an API key.'\r\n },\r\n verification: { supportsReadOnly: false }\r\n }),\r\n provider('rate-limit', 'Rate limiting', ['upstash', 'upstashratelimit', 'ratelimit', 'ratelimiting', 'expressratelimit'], ['security'], ['security'], 'rate-limit', {\r\n docsUrl: 'https://upstash.com/docs/redis/sdks/ratelimit/overview',\r\n dashboardUrl: 'https://console.upstash.com',\r\n mcp: {\r\n label: 'Upstash',\r\n serverName: 'upstash',\r\n vscodeServer: { type: 'stdio', command: 'npx', args: ['-y', '@upstash/mcp-server@latest', '--email', '<UPSTASH_EMAIL>', '--api-key', '<UPSTASH_API_KEY>'] },\r\n cursorServer: { command: 'npx', args: ['-y', '@upstash/mcp-server@latest', '--email', '<UPSTASH_EMAIL>', '--api-key', '<UPSTASH_API_KEY>'] },\r\n keyInstructions: 'Upstash MCP needs your Upstash account email and API key. Replace the placeholders before enabling the server.'\r\n },\r\n verification: { supportsReadOnly: false }\r\n }),\r\n provider('bot-protection', 'Bot protection', ['botprotection', 'cloudflareturnstile', 'turnstile', 'cloudflare'], ['security'], ['security'], 'bot-protection', {\r\n docsUrl: 'https://developers.cloudflare.com/turnstile',\r\n dashboardUrl: 'https://dash.cloudflare.com',\r\n mcp: {\r\n label: 'Cloudflare',\r\n serverName: 'cloudflare-api',\r\n vscodeServer: { type: 'http', url: 'https://mcp.cloudflare.com/mcp' },\r\n cursorServer: { url: 'https://mcp.cloudflare.com/mcp' },\r\n keyInstructions: 'Cloudflare MCP uses Cloudflare account authentication. Finish browser sign-in or provide an API token only when prompted.'\r\n },\r\n verification: { supportsReadOnly: true }\r\n }),\r\n provider('secrets-hygiene', 'Secrets hygiene', ['secretshygiene', 'envhygiene'], ['security'], ['security'], 'secrets-hygiene'),\r\n provider('figma', 'Figma', ['figma'], ['appFlow'], [], 'figma', { docsUrl: 'https://help.figma.com' }),\r\n provider('storybook', 'Storybook', ['storybook'], ['appFlow'], [], 'storybook', { docsUrl: 'https://storybook.js.org/docs' }),\r\n provider('product-spec', 'Product Spec', ['productspec', 'prd'], ['appFlow'], [], 'product-spec'),\r\n provider('route-map', 'Route Map', ['routemap', 'routes'], ['appFlow'], [], 'route-map'),\r\n provider('react', 'React', ['react', 'reactjs'], ['frontend'], [], 'react', { docsUrl: 'https://react.dev' }),\r\n provider('vue', 'Vue', ['vue', 'vuejs'], ['frontend'], [], 'vue', { docsUrl: 'https://vuejs.org/guide' }),\r\n provider('svelte', 'Svelte', ['svelte', 'sveltekit'], ['frontend'], [], 'svelte', { docsUrl: 'https://svelte.dev/docs' }),\r\n provider('angular', 'Angular', ['angular'], ['frontend'], [], 'angular', { docsUrl: 'https://angular.dev' }),\r\n provider('node', 'Node.js', ['node', 'nodejs', 'node.js'], ['backend'], [], 'nodejs', { docsUrl: 'https://nodejs.org/docs/latest/api' }),\r\n provider('python', 'Python / FastAPI', ['python', 'pythonfastapi', 'fastapi'], ['backend'], [], 'python', { docsUrl: 'https://fastapi.tiangolo.com' }),\r\n provider('rails', 'Rails', ['rails', 'rubyonrails'], ['backend'], [], 'rails', { docsUrl: 'https://guides.rubyonrails.org' }),\r\n provider('go', 'Go', ['go', 'golang'], ['backend'], [], 'go', { docsUrl: 'https://go.dev/doc' }),\r\n provider('vitest', 'Vitest', ['vitest'], ['testing'], [], 'vitest', { docsUrl: 'https://vitest.dev' })\r\n];\r\n\r\nconst PROVIDERS_BY_KEY = new Map<string, ProviderSeed>(PROVIDERS.map((entry) => [entry.provider, entry]));\r\nconst PROVIDERS_BY_ALIAS = new Map<string, ProviderSeed>();\r\nfor (const entry of PROVIDERS) {\r\n PROVIDERS_BY_ALIAS.set(normalizeProviderToken(entry.provider), entry);\r\n for (const alias of entry.aliases) {\r\n PROVIDERS_BY_ALIAS.set(normalizeProviderToken(alias), entry);\r\n }\r\n}\r\n\r\nexport function getProviderRegistryEntry(provider: string): ProviderRegistryEntry | null {\r\n const entry = PROVIDERS_BY_ALIAS.get(normalizeProviderToken(provider)) ?? null;\r\n return entry ? withStatus(entry, new Date()) : null;\r\n}\r\n\r\nexport function normalizeProviderKey(provider: string): string {\r\n return PROVIDERS_BY_ALIAS.get(normalizeProviderToken(provider))?.provider ?? normalizeProviderToken(provider);\r\n}\r\n\r\nexport function providerLabel(provider: string): string {\r\n return getProviderRegistryEntry(provider)?.label ?? titleizeProvider(provider);\r\n}\r\n\r\nexport function productionProviders(): ProductionConnectionProvider[] {\r\n return PROVIDERS\r\n .filter(isProductionProviderSeed)\r\n .map((entry) => entry.provider);\r\n}\r\n\r\nexport function productionProvidersByArea(): Record<ProductionConnectionArea, readonly ProductionConnectionProvider[]> {\r\n return {\r\n database: providersForProductionArea('database'),\r\n auth: providersForProductionArea('auth'),\r\n payments: providersForProductionArea('payments'),\r\n deployment: providersForProductionArea('deployment'),\r\n monitoring: providersForProductionArea('monitoring'),\r\n security: providersForProductionArea('security')\r\n };\r\n}\r\n\r\nexport function mcpTemplateForProvider(provider: string): ProviderMcpTemplate | null {\r\n const normalized = normalizeProviderKey(provider);\r\n const entry = PROVIDERS_BY_KEY.get(normalized);\r\n if (entry?.mcp) {\r\n return cloneMcpTemplate(entry.mcp);\r\n }\r\n if (normalized === 'supabase-auth') {\r\n const supabaseMcp = PROVIDERS_BY_KEY.get('supabase')?.mcp;\r\n return supabaseMcp ? cloneMcpTemplate(supabaseMcp) : null;\r\n }\r\n return null;\r\n}\r\n\r\nexport function stackWiringKeyHasMcp(key: StackWiringKey): boolean {\r\n return Boolean(mcpTemplateForProvider(providerFromStackWiringKey(key)));\r\n}\r\n\r\nexport function mcpProviderIdForStackWiringKey(key: StackWiringKey): string | null {\r\n const provider = providerFromStackWiringKey(key);\r\n return mcpTemplateForProvider(provider) ? mcpServerProviderId(provider) : null;\r\n}\r\n\r\nexport function buildProviderRegistrySnapshot(now = new Date()): ProviderRegistrySnapshot {\r\n const providers = PROVIDERS.map((entry) => withStatus(entry, now));\r\n return {\r\n version: 1,\r\n source: 'bundled',\r\n generatedAt: now.toISOString(),\r\n staleAfterDays: PROVIDER_REGISTRY_STALE_AFTER_DAYS,\r\n status: providers.some((entry) => entry.status === 'stale') ? 'stale' : 'fresh',\r\n providers\r\n };\r\n}\r\n\r\nfunction provider(\r\n providerKey: ProductionConnectionProvider,\r\n label: string,\r\n aliases: string[],\r\n areas: StackWiringArea[],\r\n productionAreas: ProductionConnectionArea[],\r\n iconKey: string,\r\n extras?: Partial<Omit<ProviderSeedBase, 'label' | 'aliases' | 'areas' | 'iconKey' | 'verifiedAt'>>\r\n): ProductionProviderSeed;\r\nfunction provider(\r\n providerKey: NonProductionRegistryProvider,\r\n label: string,\r\n aliases: string[],\r\n areas: StackWiringArea[],\r\n productionAreas: [],\r\n iconKey: string,\r\n extras?: Partial<Omit<ProviderSeedBase, 'label' | 'aliases' | 'areas' | 'iconKey' | 'verifiedAt'>>\r\n): NonProductionProviderSeed;\r\nfunction provider(\r\n providerKey: RegistryProvider,\r\n label: string,\r\n aliases: string[],\r\n areas: StackWiringArea[],\r\n productionAreas: ProductionConnectionArea[],\r\n iconKey: string,\r\n extras: Partial<Omit<ProviderSeedBase, 'label' | 'aliases' | 'areas' | 'iconKey' | 'verifiedAt'>> = {}\r\n): ProviderSeed {\r\n const sifgTemplateIds = areas\r\n .flatMap((area) => sifgTemplatesForRegistryProviderArea(providerKey, area))\r\n .map((template) => template.id);\r\n\r\n return {\r\n provider: providerKey,\r\n label,\r\n aliases,\r\n areas,\r\n productionAreas,\r\n iconKey,\r\n verifiedAt: '2026-05-18',\r\n ...(sifgTemplateIds.length > 0 ? { sifgTemplateIds } : {}),\r\n ...extras\r\n } as ProviderSeed;\r\n}\r\n\r\nfunction providersForProductionArea(area: ProductionConnectionArea): ProductionConnectionProvider[] {\r\n return PROVIDERS\r\n .filter(isProductionProviderSeed)\r\n .filter((entry) => entry.productionAreas.includes(area))\r\n .map((entry) => entry.provider);\r\n}\r\n\r\nfunction isProductionProviderSeed(entry: ProviderSeed): entry is ProductionProviderSeed {\r\n return entry.productionAreas.length > 0;\r\n}\r\n\r\nfunction withStatus(entry: ProviderSeed, now: Date): ProviderRegistryEntry {\r\n const mcp = entry.mcp ? cloneMcpTemplate(entry.mcp) : undefined;\r\n const verification = entry.verification ? { ...entry.verification } : undefined;\r\n return {\r\n provider: entry.provider,\r\n label: entry.label,\r\n aliases: [...entry.aliases],\r\n areas: [...entry.areas],\r\n productionAreas: [...entry.productionAreas],\r\n iconKey: entry.iconKey,\r\n ...(entry.sifgTemplateIds ? { sifgTemplateIds: [...entry.sifgTemplateIds] } : {}),\r\n ...(entry.docsUrl ? { docsUrl: entry.docsUrl } : {}),\r\n ...(entry.dashboardUrl ? { dashboardUrl: entry.dashboardUrl } : {}),\r\n ...(mcp ? { mcp } : {}),\r\n ...(verification ? { verification } : {}),\r\n verifiedAt: entry.verifiedAt,\r\n status: registryStatus(entry.verifiedAt, now)\r\n };\r\n}\r\n\r\nfunction cloneMcpTemplate(template: ProviderMcpTemplate): ProviderMcpTemplate {\r\n return {\r\n label: template.label,\r\n serverName: template.serverName,\r\n vscodeServer: cloneRecord(template.vscodeServer),\r\n cursorServer: cloneRecord(template.cursorServer),\r\n keyInstructions: template.keyInstructions\r\n };\r\n}\r\n\r\nfunction cloneRecord(record: Record<string, unknown>): Record<string, unknown> {\r\n return Object.fromEntries(\r\n Object.entries(record).map(([key, value]) => [key, cloneUnknown(value)])\r\n );\r\n}\r\n\r\nfunction cloneUnknown(value: unknown): unknown {\r\n if (Array.isArray(value)) {\r\n return value.map(cloneUnknown);\r\n }\r\n if (value && typeof value === 'object') {\r\n return cloneRecord(value as Record<string, unknown>);\r\n }\r\n return value;\r\n}\r\n\r\nfunction registryStatus(verifiedAt: string, now: Date): ProviderRegistryStatus {\r\n const verifiedTime = Date.parse(`${verifiedAt}T00:00:00.000Z`);\r\n if (Number.isNaN(verifiedTime)) {\r\n return 'stale';\r\n }\r\n const ageMs = now.getTime() - verifiedTime;\r\n return ageMs > PROVIDER_REGISTRY_STALE_AFTER_DAYS * 24 * 60 * 60 * 1000 ? 'stale' : 'fresh';\r\n}\r\n\r\nfunction normalizeProviderToken(provider: string): string {\r\n return provider\r\n .toLowerCase()\r\n .replace(/&/g, 'and')\r\n .replace(/[^a-z0-9]+/g, '');\r\n}\r\n\r\nfunction providerFromStackWiringKey(key: StackWiringKey): string {\r\n return key\r\n .replace(/-(app-flow|frontend|backend|security|auth|database|payments|deployment|landing|monitoring|testing|error-handling)$/, '')\r\n .replace(/^supabase-database$/, 'supabase')\r\n .replace(/^supabase-landing$/, 'supabase')\r\n .replace(/^supabase-auth$/, 'supabase-auth');\r\n}\r\n\r\nfunction mcpServerProviderId(provider: string): string {\r\n if (provider === 'supabase-auth') {\r\n return 'supabase';\r\n }\r\n if (provider === 'rate-limit') {\r\n return 'upstash';\r\n }\r\n if (provider === 'bot-protection') {\r\n return 'cloudflare';\r\n }\r\n return provider;\r\n}\r\n\r\nfunction titleizeProvider(provider: string): string {\r\n return provider.replace(/(^|-)([a-z])/g, (_match, prefix: string, letter: string) =>\r\n `${prefix ? ' ' : ''}${letter.toUpperCase()}`\r\n );\r\n}\r\n", "import type {\r\n MissionArea,\r\n MissionCheck,\r\n MissionCheckStatus,\r\n MissionEvidenceClass,\r\n MissionGraph,\r\n ProviderMission,\r\n RepositoryEvidenceSummary,\r\n StackWiringArea,\r\n StackWiringItem,\r\n StackWiringProviderSummary,\r\n StackWiringSummary\r\n} from './types';\r\nimport { stackWiringKeyHasMcp } from './providerRegistry';\r\nimport type { SifgGraph, SifgLeak, SifgPipeline } from './sifgTypes';\r\n\r\ntype BuildMissionGraphInput = {\r\n stackWiring: StackWiringSummary;\r\n repositoryEvidence: RepositoryEvidenceSummary;\r\n staticInfrastructureFlowGraph?: SifgGraph;\r\n};\r\n\r\nconst AREA_LABELS: Record<StackWiringArea, string> = {\r\n appFlow: 'App Flow',\r\n frontend: 'Frontend',\r\n backend: 'Backend / API',\r\n database: 'Database',\r\n auth: 'Auth',\r\n payments: 'Payments',\r\n deployment: 'Deployment',\r\n monitoring: 'Monitoring',\r\n security: 'Security',\r\n testing: 'Testing',\r\n landing: 'Landing / Onboarding',\r\n errorHandling: 'Error Handling'\r\n};\r\n\r\nexport function buildMissionGraph(input: BuildMissionGraphInput): MissionGraph {\r\n const providerMissions = input.stackWiring.items.map(toProviderMission);\r\n if (input.staticInfrastructureFlowGraph) {\r\n overlaySifgLeaks(providerMissions, input.staticInfrastructureFlowGraph);\r\n }\r\n const byProvider = providerMissions.reduce<MissionGraph['byProvider']>((acc, mission) => {\r\n acc[mission.key] = mission;\r\n return acc;\r\n }, {});\r\n const areas = buildAreas(providerMissions);\r\n const byArea = areas.reduce<MissionGraph['byArea']>((acc, area) => {\r\n acc[area.key] = area;\r\n return acc;\r\n }, {});\r\n\r\n return {\r\n areas,\r\n byArea,\r\n byProvider,\r\n repositoryEvidence: input.repositoryEvidence,\r\n ...(input.staticInfrastructureFlowGraph\r\n ? { staticInfrastructureFlowGraph: input.staticInfrastructureFlowGraph }\r\n : {})\r\n };\r\n}\r\n\r\nfunction toProviderMission(summary: StackWiringProviderSummary): ProviderMission {\r\n const checks = summary.items.map((item) => toMissionCheck(summary, item));\r\n if (stackWiringKeyHasMcp(summary.key)) {\r\n checks.push({\r\n id: `${summary.key}-mcp-verifier`,\r\n label: `${summary.providerLabel} MCP verifier available`,\r\n providerKey: summary.key,\r\n providerLabel: summary.providerLabel,\r\n area: summary.area,\r\n evidenceClass: 'mcp-verifier',\r\n status: 'needs-connection',\r\n evidence: [],\r\n promptHint: `Connect the official ${summary.providerLabel} MCP/tool verifier before claiming external dashboard state.`\r\n });\r\n }\r\n\r\n return {\r\n key: summary.key,\r\n provider: summary.provider,\r\n providerLabel: summary.providerLabel,\r\n area: summary.area,\r\n promptSubject: summary.promptSubject,\r\n readinessPercent: summary.readinessPercent,\r\n checks\r\n };\r\n}\r\n\r\nfunction toMissionCheck(summary: StackWiringProviderSummary, item: StackWiringItem): MissionCheck {\r\n const evidenceClass = evidenceClassForStatus(item.status);\r\n return {\r\n id: item.id,\r\n label: item.label,\r\n providerKey: summary.key,\r\n providerLabel: summary.providerLabel,\r\n area: summary.area,\r\n evidenceClass,\r\n status: missionStatusForEvidenceClass(evidenceClass),\r\n evidence: item.evidence,\r\n promptHint: item.promptHint\r\n };\r\n}\r\n\r\nfunction evidenceClassForStatus(status: StackWiringItem['status']): MissionEvidenceClass {\r\n if (status === 'passed') {\r\n return 'repo-verified';\r\n }\r\n if (status === 'manual') {\r\n return 'manual-dashboard';\r\n }\r\n return 'missing-repo-fix';\r\n}\r\n\r\nfunction missionStatusForEvidenceClass(evidenceClass: MissionEvidenceClass): MissionCheckStatus {\r\n if (evidenceClass === 'repo-verified') {\r\n return 'passed';\r\n }\r\n if (evidenceClass === 'manual-dashboard') {\r\n return 'manual-required';\r\n }\r\n if (evidenceClass === 'mcp-verifier') {\r\n return 'needs-connection';\r\n }\r\n return 'missing';\r\n}\r\n\r\nfunction overlaySifgLeaks(providerMissions: ProviderMission[], graph: SifgGraph): void {\r\n const pipelinesById = new Map(graph.pipelines.map((pipeline) => [pipeline.id, pipeline]));\r\n const leaksByPipeline = new Map<string, SifgLeak[]>();\r\n const providerCheckIds = new Map(\r\n providerMissions.map((mission) => [\r\n mission.key,\r\n new Set(mission.checks.map((check) => check.id))\r\n ])\r\n );\r\n\r\n for (const leak of graph.leaks) {\r\n const leaks = leaksByPipeline.get(leak.pipelineId) ?? [];\r\n leaks.push(leak);\r\n leaksByPipeline.set(leak.pipelineId, leaks);\r\n }\r\n\r\n for (const [pipelineId, leaks] of leaksByPipeline.entries()) {\r\n const pipeline = pipelinesById.get(pipelineId);\r\n const providerKey = pipeline?.providerKey ?? leaks[0]?.providerKey;\r\n if (!providerKey) {\r\n continue;\r\n }\r\n\r\n const mission = providerMissions.find((candidate) => candidate.key === providerKey);\r\n if (!mission) {\r\n continue;\r\n }\r\n\r\n const usedCheckIds = providerCheckIds.get(mission.key) ?? new Set<string>();\r\n const check = toSifgMissionCheck(mission, pipeline, pipelineId, leaks, usedCheckIds);\r\n mission.checks.push(check);\r\n usedCheckIds.add(check.id);\r\n providerCheckIds.set(mission.key, usedCheckIds);\r\n }\r\n\r\n for (const mission of providerMissions) {\r\n mission.readinessPercent = readinessPercentForChecks(mission.checks);\r\n }\r\n}\r\n\r\nfunction toSifgMissionCheck(\r\n mission: ProviderMission,\r\n pipeline: SifgPipeline | undefined,\r\n pipelineId: string,\r\n leaks: SifgLeak[],\r\n usedCheckIds: Set<string>\r\n): MissionCheck {\r\n const firstLeak = leaks[0];\r\n const baseCheckId = pipeline?.missionCheckIds[0] ?? firstLeak?.id ?? pipelineId;\r\n const checkId = uniqueSifgCheckId(baseCheckId, pipelineId, firstLeak?.id, usedCheckIds);\r\n const evidence = leaks.flatMap((leak) =>\r\n leak.evidencePath.map((step) => `${step.file}:${step.range.startLine}-${step.range.endLine}`)\r\n );\r\n\r\n return {\r\n id: checkId,\r\n label: pipeline?.label ?? firstLeak?.summary ?? 'SIFG structural leak',\r\n providerKey: mission.key,\r\n providerLabel: mission.providerLabel,\r\n area: mission.area,\r\n evidenceClass: 'missing-repo-fix',\r\n status: 'missing',\r\n evidence,\r\n promptHint: firstLeak?.repoFix.requiredOutcome ?? 'Fix the SIFG structural leak in repository code.',\r\n sifg: {\r\n pipelineId,\r\n leakIds: leaks.map((leak) => leak.id),\r\n proofStatus: 'leak'\r\n }\r\n };\r\n}\r\n\r\nfunction uniqueSifgCheckId(\r\n baseCheckId: string,\r\n pipelineId: string,\r\n leakId: string | undefined,\r\n usedCheckIds: Set<string>\r\n): string {\r\n if (!usedCheckIds.has(baseCheckId)) {\r\n return baseCheckId;\r\n }\r\n\r\n const suffix = stableSifgSuffix(pipelineId) || (leakId ? stableSifgSuffix(leakId) : '') || 'sifg';\r\n const suffixed = `${baseCheckId}--${suffix}`;\r\n if (!usedCheckIds.has(suffixed)) {\r\n return suffixed;\r\n }\r\n\r\n let counter = 2;\r\n while (usedCheckIds.has(`${suffixed}-${counter}`)) {\r\n counter += 1;\r\n }\r\n return `${suffixed}-${counter}`;\r\n}\r\n\r\nfunction stableSifgSuffix(id: string): string {\r\n return id.split(':').filter(Boolean).at(-1)?.replace(/[^a-zA-Z0-9._-]/g, '-') ?? '';\r\n}\r\n\r\nfunction readinessPercentForChecks(checks: MissionCheck[]): number {\r\n const actionableChecks = checks.filter(isActionableCheck);\r\n const passed = actionableChecks.filter((check) => check.status === 'passed').length;\r\n return Math.round((passed / Math.max(actionableChecks.length, 1)) * 100);\r\n}\r\n\r\nfunction isActionableCheck(check: MissionCheck): boolean {\r\n return check.evidenceClass !== 'manual-dashboard' && check.evidenceClass !== 'mcp-verifier';\r\n}\r\n\r\nfunction buildAreas(providerMissions: ProviderMission[]): MissionArea[] {\r\n const byArea = new Map<StackWiringArea, ProviderMission[]>();\r\n for (const mission of providerMissions) {\r\n const current = byArea.get(mission.area) ?? [];\r\n current.push(mission);\r\n byArea.set(mission.area, current);\r\n }\r\n\r\n return [...byArea.entries()].map(([key, missions]) => {\r\n const actionableChecks = missions\r\n .flatMap((mission) => mission.checks)\r\n .filter(isActionableCheck);\r\n const passed = actionableChecks.filter((check) => check.status === 'passed').length;\r\n const missing = actionableChecks.filter((check) => check.status === 'missing' || check.status === 'failed').length;\r\n\r\n return {\r\n key,\r\n label: AREA_LABELS[key],\r\n readinessPercent: Math.round((passed / Math.max(actionableChecks.length, 1)) * 100),\r\n criticalCount: missing,\r\n providerMissions: missions\r\n };\r\n });\r\n}\r\n", "import type { ScanResult } from './types';\r\n\r\nexport function buildAnalysisPrompt(\r\n scan: ScanResult,\r\n specContent?: string,\r\n productionConnectionContext?: string,\r\n scannerEvidenceContext?: string,\r\n stackWiringContext?: string,\r\n stackAutomationContext?: string\r\n): string {\r\n const sections: string[] = [];\r\n\r\n const detectedStack = (Object.entries(scan.stackSignals) as Array<[string, boolean | undefined]>)\r\n .filter(([, v]) => v === true)\r\n .map(([k]) => k)\r\n .join(', ');\r\n\r\n sections.push(`## PROJECT CONTEXT\r\nTotal files in repo: ${scan.totalFilesScanned}\r\nFiles analyzed: ${scan.files.length}\r\nDetected stack signals: ${detectedStack || 'none detected'}\r\nAll dependencies: ${scan.packageDeps.join(', ') || 'none found'}\r\nSecret files found (contents not read): ${scan.secretsFound.join(', ') || 'none'}\r\n`);\r\n\r\n if (scan.fileTree) {\r\n sections.push(`## FILE TREE (compact)\r\n${scan.fileTree}\r\n`);\r\n }\r\n\r\n if (specContent && specContent.trim().length > 0) {\r\n sections.push(`## PROJECT SPEC (SPEC.md)\r\n${specContent.slice(0, 4000)}\r\n`);\r\n }\r\n\r\n const filesWithContent = scan.files.filter((f) => !f.isSecret && f.content !== null && f.content.trim().length > 0);\r\n if (filesWithContent.length > 0) {\r\n sections.push('## FILE CONTENTS (highest relevance first)');\r\n for (const file of filesWithContent) {\r\n const safePath = file.path.replace(/[\\r\\n]/g, ' ');\r\n const escapedContent = (file.content as string).replace(/`{3}/g, '\\\\`\\\\`\\\\`');\r\n sections.push(`### ${safePath} (heat: ${file.heat})\\n\\`\\`\\`\\n${escapedContent}\\n\\`\\`\\`\\n`);\r\n }\r\n }\r\n\r\n if (productionConnectionContext && productionConnectionContext.trim().length > 0) {\r\n sections.push(productionConnectionContext.trim());\r\n }\r\n\r\n if (scannerEvidenceContext && scannerEvidenceContext.trim().length > 0) {\r\n sections.push(`## LOCAL SCANNER EVIDENCE\r\n${scannerEvidenceContext.trim()}\r\n`);\r\n }\r\n\r\n if (stackWiringContext && stackWiringContext.trim().length > 0) {\r\n sections.push(stackWiringContext.trim());\r\n }\r\n\r\n if (stackAutomationContext && stackAutomationContext.trim().length > 0) {\r\n sections.push(stackAutomationContext.trim());\r\n }\r\n\r\n sections.push(`## YOUR TASK\r\n\r\nYou are a senior software engineer reviewing a vibe-coded project for production readiness.\r\nAnalyze everything above and return ONLY valid JSON with this exact structure:\r\n\r\n{\r\n \"score\": 75,\r\n \"scoreLabel\": \"Stable\",\r\n \"summary\": \"2 critical gaps before launch\",\r\n \"archetype\": \"saas-app\",\r\n \"gaps\": [\r\n {\r\n \"id\": \"unique-kebab-id\",\r\n \"category\": \"SECURITY & AUTH\",\r\n \"severity\": \"critical\",\r\n \"title\": \"No rate limiting on API routes\",\r\n \"detail\": \"Any user can spam your API endpoints causing cost and abuse.\",\r\n \"primaryMapCategory\": \"security\",\r\n \"affectedMapCategories\": [\"security\", \"backend\", \"auth\"],\r\n \"copyPrompt\": \"Harden API rate limiting. First inspect src, route handlers, middleware, and existing auth/session helpers. Identify every public or write-heavy endpoint that can be abused. Implement: 1. Add Upstash rate limiting to sensitive API routes. 2. Use conservative defaults such as 10 requests per minute per IP for auth/write endpoints. 3. Return clear 429 responses without leaking internals. Constraints: Preserve existing API contracts unless they are unsafe. Do not rely on client-side checks for server protection. Verification: Add or update tests/manual checks for allowed and rate-limited requests. Run the relevant test suite and TypeScript check. Summarize what changed and what scanner/rescan evidence should confirm.\",\r\n \"toolSuggestions\": [\r\n {\r\n \"name\": \"Upstash Rate Limit\",\r\n \"url\": \"https://upstash.com/docs/redis/sdks/ratelimit-ts/overview\",\r\n \"reason\": \"Best rate limiter for serverless/edge\"\r\n }\r\n ],\r\n \"mcpSuggestion\": null\r\n }\r\n ],\r\n \"stackDetected\": [\"nextjs\", \"supabase\", \"typescript\"],\r\n \"missingLayers\": [\"landing-page\", \"error-monitoring\"],\r\n \"quickWins\": [\"Add .env.example\", \"Add error boundary to root layout\"],\r\n \"productionChecklist\": {\r\n \"security\": 40,\r\n \"database\": 80,\r\n \"auth\": 60,\r\n \"errorHandling\": 30,\r\n \"deployment\": 70,\r\n \"testing\": 10,\r\n \"landing\": 50,\r\n \"monitoring\": 0\r\n }\r\n}\r\n\r\nGap categories must be one of:\r\nSECURITY & AUTH, DATABASE & DATA, ERROR HANDLING, DEPLOYMENT,\r\nPERFORMANCE, MISSING FEATURES, EDGE CASES & RISKS, LANDING & MARKETING\r\n\r\nMission Map category keys must be one of:\r\nappFlow, frontend, backend, auth, database, payments, deployment, monitoring, security, testing, landing, errorHandling\r\n\r\nSeverity: critical (blocks launch), warning (should fix soon), info (nice to have)\r\nScore: 0-100 overall production readiness. Be honest \u2014 most vibe-coded projects score 30-60.\r\nUse a stable scoring rubric: the same evidence should receive the same score on repeat scans. Do not move the score up or down for wording variety; only change it when the scanned evidence changes.\r\n\r\nReturn unique root gaps, not one copy of the same root problem for each affected section. For each gap:\r\n- Set primaryMapCategory to the single Mission Map section that should own/count the blocker.\r\n- Set affectedMapCategories to related sections that the blocker touches, but do not duplicate the gap for those sections.\r\n- Example: \"No production error monitoring is wired up\" should be one monitoring gap with affectedMapCategories such as [\"monitoring\", \"errorHandling\", \"auth\", \"payments\", \"backend\"], not separate auth, billing, backend, and error gaps.\r\n- Example: \"Auth enforcement is split across app layers\" should be one auth or security gap, depending on the strongest evidence, not repeated across every protected route.\r\n\r\nFor toolSuggestions: suggest real tools that solve this specific gap.\r\n- Database gaps: suggest Supabase, PlanetScale, Neon, Turso, or MongoDB Atlas based on detected stack.\r\n- Auth gaps: suggest Supabase Auth, Clerk, NextAuth, or Lucia based on detected stack.\r\n- Monitoring: suggest Sentry, LogRocket, or PostHog.\r\n- Deployment: suggest Vercel, Railway, Fly.io, or Render.\r\n\r\nEvery copyPrompt must be ready to paste into a coding agent. Use this VibeRaven execution structure inside the string:\r\n\r\n1. Start with the outcome in one sentence.\r\n2. Include a \"First inspect\" paragraph naming concrete files, directories, or helpers from the scanned project when possible.\r\n3. Include an \"Implement\" section with numbered steps.\r\n4. Include a \"Constraints\" section with safety rules and behavior that must not break.\r\n5. Include a \"Verification\" section with tests, commands, manual checks, or scanner evidence.\r\n6. End by asking the agent to \"Summarize what changed\" and what remains manual or external.\r\n\r\nMake each gap Raven-friendly: include a concrete copyPrompt, likely tool paths where relevant, and verification steps the user or scanner can check after implementation. Do not claim external dashboard setup is complete from repo evidence alone. If a step needs a provider dashboard, account, MCP connection, billing console, OAuth callback, RLS setting, alert route, or any other external system, say so explicitly and mark it as manual or MCP-verifiable instead of repo-verifiable.\r\n\r\nBe specific. A vibe coder needs to know EXACTLY what to do, not generic advice.\r\nReturn ONLY the JSON object \u2014 no markdown, no explanation.\r\n`);\r\n\r\n return sections.join('\\n');\r\n}\r\n", "import type {\r\n ProductionConnectionArea,\r\n ProductionConnectionChoice,\r\n ProductionConnectionChoices,\r\n ProductionConnectionEvidence,\r\n ProductionConnectionProvider,\r\n ProductionConnectionStatus,\r\n ProductionConnectionSummary,\r\n ScanResult\r\n} from './types';\r\nimport {\r\n normalizeProviderKey,\r\n productionProviders,\r\n productionProvidersByArea,\r\n providerLabel\r\n} from './providerRegistry';\r\n\r\nexport type {\r\n ProductionConnectionArea,\r\n ProductionConnectionChoice,\r\n ProductionConnectionChoices,\r\n ProductionConnectionEvidence,\r\n ProductionConnectionProvider,\r\n ProductionConnectionStatus,\r\n ProductionConnectionSummary\r\n} from './types';\r\n\r\nconst AREAS: ProductionConnectionArea[] = [\r\n 'database',\r\n 'auth',\r\n 'payments',\r\n 'deployment',\r\n 'monitoring',\r\n 'security'\r\n];\r\n\r\nconst PROVIDERS = productionProviders();\r\nconst PROVIDERS_BY_AREA = productionProvidersByArea();\r\n\r\ntype EvidenceMap = Partial<Record<ProductionConnectionArea, ProductionConnectionEvidence>>;\r\n\r\ntype ScannableFile = {\r\n path: string;\r\n displayPath: string;\r\n content: string;\r\n lowerContent: string;\r\n};\r\n\r\ntype ProviderDetectionRule = {\r\n area: ProductionConnectionArea;\r\n provider: ProductionConnectionProvider;\r\n label: string;\r\n packages?: RegExp[];\r\n env?: string[];\r\n paths?: RegExp[];\r\n imports?: string[];\r\n docs?: string[];\r\n content?: Array<{ pattern: RegExp; signal: string }>;\r\n};\r\n\r\ntype RawProductionConnectionChoice = {\r\n provider?: unknown;\r\n selectedAt?: unknown;\r\n};\r\n\r\ntype ChoiceInput =\r\n | ProductionConnectionChoices\r\n | Partial<Record<string, RawProductionConnectionChoice | undefined>>\r\n | null\r\n | undefined;\r\n\r\nconst PROVIDER_RULES: ProviderDetectionRule[] = [\r\n {\r\n area: 'database',\r\n provider: 'supabase',\r\n label: 'Supabase',\r\n packages: [/@supabase\\//],\r\n env: ['VITE_SUPABASE_URL', 'NEXT_PUBLIC_SUPABASE_URL', 'SUPABASE_URL', 'SUPABASE_SERVICE_ROLE_KEY'],\r\n paths: [/supabase\\/config\\.toml$/, /(^|\\/)(lib|utils)\\/supabase\\.[jt]s$/],\r\n imports: ['@supabase/supabase-js', '@supabase/ssr'],\r\n docs: ['supabase']\r\n },\r\n {\r\n area: 'database',\r\n provider: 'neon',\r\n label: 'Neon',\r\n packages: [/@neondatabase\\//],\r\n env: ['NEON_DATABASE_URL'],\r\n imports: ['@neondatabase/serverless'],\r\n docs: ['neon']\r\n },\r\n {\r\n area: 'database',\r\n provider: 'planetscale',\r\n label: 'PlanetScale',\r\n packages: [/@planetscale\\/database/],\r\n env: ['PLANETSCALE_DATABASE_URL'],\r\n imports: ['@planetscale/database'],\r\n docs: ['planetscale']\r\n },\r\n {\r\n area: 'database',\r\n provider: 'mongodb',\r\n label: 'MongoDB',\r\n packages: [/^mongodb$/, /^mongoose$/],\r\n env: ['MONGODB_URI', 'MONGODB_URL', 'MONGODB_ATLAS_URI'],\r\n imports: ['mongodb', 'mongoose'],\r\n docs: ['mongodb', 'mongo atlas']\r\n },\r\n {\r\n area: 'database',\r\n provider: 'turso',\r\n label: 'Turso',\r\n packages: [/@libsql\\/client/],\r\n env: ['TURSO_DATABASE_URL', 'TURSO_AUTH_TOKEN'],\r\n imports: ['@libsql/client'],\r\n docs: ['turso']\r\n },\r\n {\r\n area: 'auth',\r\n provider: 'clerk',\r\n label: 'Clerk',\r\n packages: [/@clerk\\//],\r\n env: ['CLERK_SECRET_KEY', 'NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY'],\r\n paths: [/middleware\\.[jt]sx?$/],\r\n imports: ['@clerk/nextjs', '@clerk/clerk-react', '@clerk/express'],\r\n docs: ['clerk']\r\n },\r\n {\r\n area: 'auth',\r\n provider: 'authjs',\r\n label: 'Auth.js',\r\n packages: [/^next-auth$/, /^@auth\\//],\r\n env: ['AUTH_SECRET', 'NEXTAUTH_SECRET', 'NEXTAUTH_URL'],\r\n paths: [/(^|\\/)auth\\.[jt]s$/, /api\\/auth\\//],\r\n imports: ['next-auth', '@auth/core', '@auth/nextjs'],\r\n docs: ['auth.js', 'nextauth', 'next-auth']\r\n },\r\n {\r\n area: 'payments',\r\n provider: 'stripe',\r\n label: 'Stripe',\r\n packages: [/^stripe$/, /@stripe\\//],\r\n env: ['STRIPE_SECRET_KEY', 'STRIPE_WEBHOOK_SECRET', 'NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY'],\r\n paths: [/stripe.*webhook/, /webhook.*stripe/, /stripe.*checkout/, /checkout.*stripe/],\r\n imports: ['stripe', '@stripe/stripe-js'],\r\n docs: ['stripe']\r\n },\r\n {\r\n area: 'payments',\r\n provider: 'paddle',\r\n label: 'Paddle',\r\n packages: [/@paddle\\//],\r\n env: ['PADDLE_API_KEY', 'PADDLE_WEBHOOK_SECRET', 'NEXT_PUBLIC_PADDLE_CLIENT_TOKEN'],\r\n paths: [/paddle.*webhook/, /webhook.*paddle/, /paddle.*checkout/, /checkout.*paddle/],\r\n imports: ['@paddle/paddle-js', '@paddle/paddle-node-sdk'],\r\n docs: ['paddle']\r\n },\r\n {\r\n area: 'deployment',\r\n provider: 'vercel',\r\n label: 'Vercel',\r\n packages: [/@vercel\\//],\r\n env: ['VERCEL_TOKEN', 'VERCEL_PROJECT_ID', 'VERCEL_ORG_ID'],\r\n paths: [/vercel\\.json$/],\r\n docs: ['vercel']\r\n },\r\n {\r\n area: 'monitoring',\r\n provider: 'sentry',\r\n label: 'Sentry',\r\n packages: [/@sentry\\//],\r\n env: ['SENTRY_DSN', 'NEXT_PUBLIC_SENTRY_DSN', 'SENTRY_AUTH_TOKEN'],\r\n paths: [/sentry\\.(client|server)\\.config\\.[jt]s$/, /instrumentation\\.[jt]s$/],\r\n imports: ['@sentry/nextjs', '@sentry/node', '@sentry/react'],\r\n content: [{ pattern: /sentry\\.init\\s*\\(/i, signal: 'init: Sentry.init' }],\r\n docs: ['sentry']\r\n },\r\n {\r\n area: 'monitoring',\r\n provider: 'posthog',\r\n label: 'PostHog',\r\n packages: [/^posthog-js$/, /^posthog-node$/],\r\n env: ['POSTHOG_KEY', 'NEXT_PUBLIC_POSTHOG_KEY', 'NEXT_PUBLIC_POSTHOG_HOST'],\r\n imports: ['posthog-js', 'posthog-node'],\r\n content: [{ pattern: /posthog\\.init\\s*\\(/i, signal: 'init: posthog.init' }],\r\n docs: ['posthog']\r\n },\r\n {\r\n area: 'monitoring',\r\n provider: 'logrocket',\r\n label: 'LogRocket',\r\n packages: [/^logrocket$/],\r\n env: ['LOGROCKET_APP_ID', 'NEXT_PUBLIC_LOGROCKET_APP_ID'],\r\n imports: ['logrocket'],\r\n content: [{ pattern: /logrocket\\.init\\s*\\(/i, signal: 'init: LogRocket.init' }],\r\n docs: ['logrocket']\r\n },\r\n {\r\n area: 'security',\r\n provider: 'rate-limit',\r\n label: 'Upstash rate limit',\r\n packages: [/@upstash\\/ratelimit/, /express-rate-limit/, /rate-limiter-flexible/, /@fastify\\/rate-limit/],\r\n env: ['UPSTASH_REDIS_REST_URL', 'UPSTASH_REDIS_REST_TOKEN'],\r\n paths: [/rate-?limit/, /ratelimit/],\r\n imports: ['@upstash/ratelimit', 'express-rate-limit', 'rate-limiter-flexible', '@fastify/rate-limit'],\r\n content: [{ pattern: /\\brateLimit\\b|\\bRatelimit\\b|\\bToo many requests\\b/i, signal: 'code: rate limit guard' }],\r\n docs: ['upstash', 'rate limit']\r\n },\r\n {\r\n area: 'security',\r\n provider: 'bot-protection',\r\n label: 'Cloudflare Turnstile',\r\n packages: [/turnstile/],\r\n env: ['NEXT_PUBLIC_TURNSTILE_SITE_KEY', 'TURNSTILE_SECRET_KEY', 'TURNSTILE_SITE_KEY'],\r\n paths: [/turnstile/, /bot.?protection/],\r\n imports: ['@marsidev/react-turnstile', 'react-turnstile'],\r\n content: [{ pattern: /\\bturnstile\\b|\\bcf-turnstile\\b|\\brecaptcha\\b|\\bhcaptcha\\b/i, signal: 'code: bot protection guard' }],\r\n docs: ['turnstile', 'cloudflare turnstile', 'bot protection']\r\n }\r\n];\r\n\r\nexport function normalizeProductionChoice(input: ChoiceInput): ProductionConnectionChoices {\r\n const source = isObject(input) && isObject(input.choices) ? input.choices : input;\r\n const choices: ProductionConnectionChoices['choices'] = {};\r\n\r\n if (!isObject(source)) {\r\n return { version: 1, choices };\r\n }\r\n\r\n for (const [areaKey, value] of Object.entries(source)) {\r\n const area = normalizeArea(areaKey);\r\n const provider = normalizeProviderForArea(area, isObject(value) ? value.provider : undefined);\r\n\r\n if (!area || !provider) {\r\n continue;\r\n }\r\n\r\n const selectedAt = isObject(value) ? normalizeSelectedAt(value.selectedAt) : null;\r\n if (!selectedAt) {\r\n continue;\r\n }\r\n\r\n choices[area] = { provider, selectedAt };\r\n }\r\n\r\n return { version: 1, choices };\r\n}\r\n\r\nexport function detectProductionConnectionEvidence(scan: ScanResult): EvidenceMap {\r\n const evidence: EvidenceMap = {};\r\n const deps = scan.packageDeps.map((dep) => dep.toLowerCase());\r\n const files = scan.files.map((file) => ({\r\n path: normalizePath(file.path),\r\n displayPath: file.path.replace(/\\\\/g, '/'),\r\n content: file.isSecret || typeof file.content !== 'string' ? '' : file.content,\r\n lowerContent: file.isSecret || typeof file.content !== 'string' ? '' : file.content.toLowerCase()\r\n }));\r\n const secretPathBlob = scan.secretsFound.map((path) => normalizePath(path)).join('\\n');\r\n const pathBlob = `${scan.fileTree}\\n${files.map((file) => file.path).join('\\n')}`.toLowerCase();\r\n const contentBlob = files.map((file) => file.lowerContent).join('\\n').slice(0, 120000);\r\n const secretsHygieneBlob = `${pathBlob}\\n${secretPathBlob}`;\r\n\r\n for (const rule of PROVIDER_RULES) {\r\n detectProvider(evidence, rule, deps, files, pathBlob);\r\n }\r\n\r\n detectSecretsHygiene(evidence, secretsHygieneBlob);\r\n\r\n for (const item of Object.values(evidence)) {\r\n if (!item) {\r\n continue;\r\n }\r\n applyVerificationStatus(item, pathBlob, contentBlob);\r\n }\r\n\r\n return evidence;\r\n}\r\n\r\nexport function summarizeProductionConnections(\r\n choices: ProductionConnectionChoices | null | undefined,\r\n evidence: EvidenceMap\r\n): {\r\n byArea: Partial<Record<ProductionConnectionArea, ProductionConnectionSummary>>;\r\n items: ProductionConnectionSummary[];\r\n stackRow: ProductionConnectionSummary[];\r\n} {\r\n const normalized = normalizeProductionChoice(choices);\r\n const byArea: Partial<Record<ProductionConnectionArea, ProductionConnectionSummary>> = {};\r\n const items: ProductionConnectionSummary[] = [];\r\n\r\n for (const area of AREAS) {\r\n const detected = evidence[area];\r\n const selected = normalized.choices[area];\r\n let summary: ProductionConnectionSummary | null = null;\r\n\r\n if (detected) {\r\n summary = {\r\n area,\r\n provider: detected.provider,\r\n source: 'detected',\r\n status: detected.status,\r\n label: `${providerLabel(detected.provider)} detected`,\r\n signals: detected.signals\r\n };\r\n } else if (selected) {\r\n summary = {\r\n area,\r\n provider: selected.provider,\r\n source: 'selected',\r\n status: ['selected', 'setup-not-verified'],\r\n label: `${providerLabel(selected.provider)} selected - setup not verified`,\r\n signals: [`Selected locally at ${selected.selectedAt}`]\r\n };\r\n }\r\n\r\n if (summary) {\r\n byArea[area] = summary;\r\n items.push(summary);\r\n }\r\n }\r\n\r\n const stackRow = items.filter((item) => item.provider !== null);\r\n\r\n return { byArea, items, stackRow };\r\n}\r\n\r\nexport function buildProductionConnectionContext(\r\n choices: ProductionConnectionChoices | null | undefined,\r\n evidence: EvidenceMap\r\n): string {\r\n const summary = summarizeProductionConnections(choices, evidence);\r\n const lines = summary.items.map((item) => `${item.area}: ${item.label}`);\r\n\r\n if (lines.some((line) => line.includes('selected - setup not verified'))) {\r\n lines.push('Do not treat selected as connected; only detected repo evidence can verify setup.');\r\n }\r\n\r\n return lines.length > 0 ? lines.join('\\n') : 'production connections: no selected or detected providers';\r\n}\r\n\r\nfunction detectProvider(\r\n evidence: EvidenceMap,\r\n rule: ProviderDetectionRule,\r\n deps: string[],\r\n files: ScannableFile[],\r\n pathBlob: string\r\n): void {\r\n if (evidence[rule.area]) {\r\n return;\r\n }\r\n\r\n const signals = collectSignals(rule, deps, files, pathBlob);\r\n if (signals.length === 0) {\r\n return;\r\n }\r\n\r\n evidence[rule.area] = {\r\n area: rule.area,\r\n provider: rule.provider,\r\n status: ['detected'],\r\n signals\r\n };\r\n}\r\n\r\nfunction collectSignals(\r\n rule: ProviderDetectionRule,\r\n deps: string[],\r\n files: ScannableFile[],\r\n pathBlob: string\r\n): string[] {\r\n const signals: string[] = [];\r\n\r\n for (const dep of deps) {\r\n if ((rule.packages ?? []).some((pattern) => pattern.test(dep))) {\r\n addSignal(signals, `package: ${dep}`);\r\n }\r\n }\r\n\r\n const upperContents = files.map((file) => file.content).join('\\n').toUpperCase();\r\n for (const envName of rule.env ?? []) {\r\n if (upperContents.includes(envName.toUpperCase())) {\r\n addSignal(signals, `env: ${envName}`);\r\n }\r\n }\r\n\r\n const pathLines = pathBlob.split(/\\r?\\n/).map((path) => path.trim()).filter(Boolean);\r\n for (const path of pathLines) {\r\n if ((rule.paths ?? []).some((pattern) => pattern.test(path))) {\r\n addSignal(signals, `${pathSignalPrefix(path)}: ${path}`);\r\n }\r\n }\r\n\r\n for (const file of files) {\r\n for (const importName of rule.imports ?? []) {\r\n if (containsImport(file.lowerContent, importName)) {\r\n addSignal(signals, `import: ${importName}`);\r\n }\r\n }\r\n\r\n for (const item of rule.content ?? []) {\r\n if (item.pattern.test(file.content)) {\r\n addSignal(signals, item.signal);\r\n }\r\n }\r\n\r\n if (isDocsPath(file.path)) {\r\n for (const docsTerm of rule.docs ?? []) {\r\n if (file.lowerContent.includes(docsTerm.toLowerCase())) {\r\n addSignal(signals, `docs: ${file.displayPath} mentions ${rule.label}`);\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n\r\n return signals;\r\n}\r\n\r\nfunction containsImport(content: string, importName: string): boolean {\r\n const escaped = importName.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&').toLowerCase();\r\n return new RegExp(`(?:from\\\\s+['\"]${escaped}['\"]|import\\\\s*\\\\(\\\\s*['\"]${escaped}['\"]|require\\\\s*\\\\(\\\\s*['\"]${escaped}['\"])`).test(content);\r\n}\r\n\r\nfunction isDocsPath(path: string): boolean {\r\n return /(^|\\/)(readme|product|spec)\\.md$/.test(path) || /(^|\\/)docs\\/.*\\.md$/.test(path);\r\n}\r\n\r\nfunction pathSignalPrefix(path: string): string {\r\n if (/webhook|checkout|billing|api\\/|route\\.[jt]s$/.test(path)) {\r\n return 'route';\r\n }\r\n if (/config|\\.json$|\\.toml$|\\.ya?ml$/.test(path)) {\r\n return 'config';\r\n }\r\n return 'file';\r\n}\r\n\r\nfunction addSignal(signals: string[], signal: string): void {\r\n if (!signals.includes(signal)) {\r\n signals.push(signal);\r\n }\r\n}\r\n\r\nfunction detectSecretsHygiene(evidence: EvidenceMap, secretsHygieneBlob: string): void {\r\n if (evidence.security) {\r\n return;\r\n }\r\n\r\n const signals: string[] = [];\r\n if (/(^|[/\\\\])\\.env\\.example\\b/m.test(secretsHygieneBlob)) {\r\n signals.push('file: .env.example');\r\n }\r\n if (/(^|[/\\\\])\\.env(\\.|$)/m.test(secretsHygieneBlob)) {\r\n signals.push('secret file excluded from scan');\r\n }\r\n if (signals.length === 0) {\r\n return;\r\n }\r\n\r\n evidence.security = {\r\n area: 'security',\r\n provider: 'secrets-hygiene',\r\n status: ['detected'],\r\n signals\r\n };\r\n}\r\n\r\nfunction applyVerificationStatus(\r\n evidence: ProductionConnectionEvidence,\r\n pathBlob: string,\r\n contentBlob: string\r\n): void {\r\n if (evidence.provider === 'secrets-hygiene') {\r\n addStatus(evidence.status, 'repo-verified');\r\n return;\r\n }\r\n\r\n const hasEnv = envPatternFor(evidence.provider).test(contentBlob);\r\n const hasWebhook = webhookPatternFor(evidence.provider).test(`${pathBlob}\\n${contentBlob}`);\r\n\r\n if (hasEnv || hasWebhook || evidence.area === 'deployment') {\r\n addStatus(evidence.status, 'repo-verified');\r\n }\r\n\r\n if (evidence.area === 'payments' && !hasWebhook) {\r\n addStatus(evidence.status, 'needs-webhook');\r\n }\r\n\r\n if (!hasEnv && evidence.area !== 'deployment') {\r\n addStatus(evidence.status, 'needs-env');\r\n }\r\n}\r\n\r\nfunction envPatternFor(provider: ProductionConnectionProvider): RegExp {\r\n switch (provider) {\r\n case 'supabase':\r\n return /\\b((vite|next_public)_)?supabase_(url|anon_key|service_role_key)\\b/i;\r\n case 'clerk':\r\n return /\\b(clerk_secret_key|next_public_clerk_)/i;\r\n case 'authjs':\r\n return /\\b(auth_secret|nextauth_secret)\\b/i;\r\n case 'neon':\r\n return /\\b(neon_database_url|database_url)\\b/i;\r\n case 'planetscale':\r\n return /\\b(planetscale_database_url|database_url)\\b/i;\r\n case 'mongodb':\r\n return /\\b(mongodb_uri|mongodb_url|database_url)\\b/i;\r\n case 'turso':\r\n return /\\b(turso_database_url|turso_auth_token|database_url)\\b/i;\r\n case 'stripe':\r\n return /\\bstripe_(secret_key|webhook_secret)\\b/i;\r\n case 'paddle':\n return /\\bpaddle_(api_key|webhook_secret|client_token)\\b/i;\n case 'polar':\n return /\\bpolar_(access_token|webhook_secret|pro_product_id|sandbox)\\b/i;\n case 'sentry':\r\n return /\\bsentry_dsn\\b/i;\r\n case 'posthog':\r\n return /\\b(posthog_key|next_public_posthog_key)\\b/i;\r\n case 'logrocket':\r\n return /\\b(logrocket_app_id|next_public_logrocket_app_id)\\b/i;\r\n case 'rate-limit':\r\n return /\\b(upstash_redis_rest_url|upstash_redis_rest_token)\\b/i;\r\n case 'bot-protection':\r\n return /\\b(next_public_turnstile_site_key|turnstile_secret_key|turnstile_site_key)\\b/i;\r\n default:\r\n return /\\b[A-Z0-9_]+_(KEY|SECRET|TOKEN|URL)\\b/i;\r\n }\r\n}\r\n\r\nfunction webhookPatternFor(provider: ProductionConnectionProvider): RegExp {\r\n switch (provider) {\r\n case 'stripe':\r\n return /\\bstripe\\b.*\\bwebhook\\b|\\bwebhook\\b.*\\bstripe\\b/i;\r\n case 'paddle':\n return /\\bpaddle\\b.*\\bwebhook\\b|\\bwebhook\\b.*\\bpaddle\\b/i;\n case 'polar':\n return /\\bpolar\\b.*\\bwebhook\\b|\\bwebhook\\b.*\\bpolar\\b/i;\n default:\r\n return /\\bwebhook\\b/i;\r\n }\r\n}\r\n\r\nfunction addStatus(status: ProductionConnectionStatus[], value: ProductionConnectionStatus): void {\r\n if (!status.includes(value)) {\r\n status.push(value);\r\n }\r\n}\r\n\r\nfunction normalizeArea(value: unknown): ProductionConnectionArea | null {\r\n const normalized = String(value).toLowerCase();\r\n return AREAS.includes(normalized as ProductionConnectionArea) ? (normalized as ProductionConnectionArea) : null;\r\n}\r\n\r\nfunction normalizeProvider(value: unknown): ProductionConnectionProvider | null {\r\n const normalized = normalizeProviderKey(String(value));\r\n const productionProvider = normalized === 'supabase-auth' ? 'supabase' : normalized;\r\n return PROVIDERS.includes(productionProvider as ProductionConnectionProvider)\r\n ? (productionProvider as ProductionConnectionProvider)\r\n : null;\r\n}\r\n\r\nfunction normalizeProviderForArea(\r\n area: ProductionConnectionArea | null,\r\n value: unknown\r\n): ProductionConnectionProvider | null {\r\n if (!area) {\r\n return null;\r\n }\r\n\r\n const provider = normalizeProvider(value);\r\n if (!provider || !PROVIDERS_BY_AREA[area].includes(provider)) {\r\n return null;\r\n }\r\n\r\n return provider;\r\n}\r\n\r\nfunction normalizeSelectedAt(value: unknown): string | null {\r\n if (typeof value === 'string') {\r\n const date = new Date(value);\r\n if (!Number.isNaN(date.getTime())) {\r\n return date.toISOString();\r\n }\r\n }\r\n\r\n return null;\r\n}\r\n\r\nfunction normalizePath(path: string): string {\r\n return path.replace(/\\\\/g, '/').toLowerCase();\r\n}\r\n\r\nfunction isObject(value: unknown): value is Record<string, unknown> {\r\n return typeof value === 'object' && value !== null;\r\n}\r\n", "import type { EnvEvidenceMode, EnvVarEvidence, ScanResult } from './types';\r\n\r\nfunction normalizeEvidencePath(path: string): string {\r\n return path.replace(/\\\\/g, '/');\r\n}\r\n\r\nfunction uniquePaths(paths: string[]): string[] {\r\n return Array.from(new Set(paths.map(normalizeEvidencePath)));\r\n}\r\n\r\nfunction escapeRegExp(value: string): string {\r\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\r\n}\r\n\r\nfunction stripEnvValueQuotes(value: string): string {\r\n const trimmed = value.trim();\r\n const quote = trimmed[0];\r\n\r\n if ((quote === '\"' || quote === \"'\") && trimmed.endsWith(quote)) {\r\n return trimmed.slice(1, -1);\r\n }\r\n\r\n return trimmed;\r\n}\r\n\r\nexport function classifySafeEnvMode(value: string): EnvEvidenceMode {\r\n const normalized = stripEnvValueQuotes(value).toLowerCase();\r\n\r\n if (/^(?:sk|pk|rk)_test_/.test(normalized) || normalized.includes('_test_') || normalized.includes('test_example')) {\r\n return 'test';\r\n }\r\n\r\n if (/^(?:sk|pk|rk)_live_/.test(normalized) || normalized.includes('_live_') || normalized.includes('live_example')) {\r\n return 'live';\r\n }\r\n\r\n return 'unknown';\r\n}\r\n\r\nexport function collectEnvVarEvidence(scan: ScanResult, names: string[]): EnvVarEvidence[] {\r\n const nonSecretFiles = scan.files.filter((file) => !file.isSecret && typeof file.content === 'string');\r\n const secretEvidence = uniquePaths(scan.secretsFound);\r\n\r\n return names.map((name) => {\r\n const assignmentPattern = new RegExp(\r\n String.raw`^[ \\t]*(?:export[ \\t]+)?${escapeRegExp(name)}[ \\t]*=[ \\t]*([^\\r\\n#]*)`,\r\n 'm'\r\n );\r\n const namePattern = new RegExp(\r\n String.raw`^[ \\t]*(?:export[ \\t]+)?${escapeRegExp(name)}(?:[ \\t]*=|[ \\t]*(?:#|$))`,\r\n 'm'\r\n );\r\n const contentEvidence: string[] = [];\r\n const nameOnlyEvidence: string[] = [];\r\n const nonEmptyAssignmentEvidence: string[] = [];\r\n let mode: EnvEvidenceMode = 'unknown';\r\n\r\n for (const file of nonSecretFiles) {\r\n const content = file.content as string;\r\n const assignment = content.match(assignmentPattern);\r\n\r\n if (assignment) {\r\n const value = assignment[1] ?? '';\r\n const classifiedMode = classifySafeEnvMode(value);\r\n\r\n if (classifiedMode !== 'unknown') {\r\n contentEvidence.push(file.path);\r\n mode = classifiedMode;\r\n continue;\r\n }\r\n\r\n if (stripEnvValueQuotes(value).length > 0) {\r\n nonEmptyAssignmentEvidence.push(file.path);\r\n continue;\r\n }\r\n }\r\n\r\n if (namePattern.test(content)) {\r\n nameOnlyEvidence.push(file.path);\r\n }\r\n }\r\n\r\n if (contentEvidence.length > 0) {\r\n return {\r\n name,\r\n present: true,\r\n mode,\r\n source: 'non-secret-content',\r\n evidence: uniquePaths(contentEvidence).map((path) => `file: ${path}`)\r\n };\r\n }\r\n\r\n if (nonEmptyAssignmentEvidence.length > 0) {\r\n return {\r\n name,\r\n present: true,\r\n mode: 'unknown',\r\n source: 'non-secret-content',\r\n evidence: uniquePaths(nonEmptyAssignmentEvidence).map((path) => `file: ${path}`)\r\n };\r\n }\r\n\r\n if (nameOnlyEvidence.length > 0) {\r\n return {\r\n name,\r\n present: true,\r\n mode: 'unknown',\r\n source: 'variable-name-only',\r\n evidence: uniquePaths(nameOnlyEvidence).map((path) => `file: ${path}`)\r\n };\r\n }\r\n\r\n if (secretEvidence.length > 0) {\r\n return {\r\n name,\r\n present: false,\r\n mode: 'unknown',\r\n source: 'secret-file-path',\r\n evidence: secretEvidence.map((path) => `secret file: ${path}`)\r\n };\r\n }\r\n\r\n return {\r\n name,\r\n present: false,\r\n mode: 'unknown',\r\n source: 'variable-name-only',\r\n evidence: []\r\n };\r\n });\r\n}\r\n", "import { collectEnvVarEvidence } from './envEvidence';\r\nimport type {\r\n RepositoryEvidenceItem,\r\n RepositoryEvidenceSummary,\r\n ScanResult,\r\n ScannedFile\r\n} from './types';\r\n\r\nconst CORE_ENV_NAMES = [\r\n 'STRIPE_SECRET_KEY',\r\n 'STRIPE_WEBHOOK_SECRET',\r\n 'NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY',\r\n 'GOOGLE_CLIENT_ID',\r\n 'GOOGLE_CLIENT_SECRET',\r\n 'NEXT_PUBLIC_SUPABASE_URL',\r\n 'NEXT_PUBLIC_SUPABASE_ANON_KEY',\r\n 'SUPABASE_SERVICE_ROLE_KEY',\r\n 'NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY',\r\n 'CLERK_SECRET_KEY',\r\n 'AUTH_SECRET',\r\n 'NEXTAUTH_SECRET',\r\n 'VERCEL_PROJECT_ID',\r\n 'SENTRY_DSN',\r\n 'NEXT_PUBLIC_SENTRY_DSN',\r\n 'SENTRY_AUTH_TOKEN',\r\n 'NEXT_PUBLIC_POSTHOG_KEY',\r\n 'PADDLE_API_KEY',\r\n 'PADDLE_WEBHOOK_SECRET',\r\n 'UPSTASH_REDIS_REST_URL',\r\n 'UPSTASH_REDIS_REST_TOKEN',\r\n 'NEXT_PUBLIC_TURNSTILE_SITE_KEY',\r\n 'TURNSTILE_SECRET_KEY'\r\n];\r\n\r\nconst SECRET_ENV_REFERENCE = /\\b(?:STRIPE_SECRET_KEY|STRIPE_WEBHOOK_SECRET|GOOGLE_CLIENT_SECRET|SUPABASE_SERVICE_ROLE_KEY|CLERK_SECRET_KEY|AUTH_SECRET|NEXTAUTH_SECRET|SENTRY_AUTH_TOKEN|PADDLE_API_KEY|PADDLE_WEBHOOK_SECRET|UPSTASH_REDIS_REST_TOKEN|TURNSTILE_SECRET_KEY)\\b/i;\r\nconst RLS_POLICY = /enable\\s+row\\s+level\\s+security|create\\s+policy|alter\\s+policy/i;\r\nconst WEBHOOK_SIGNATURE = /webhooks\\.constructevent|stripe-signature|verify(?:signature|webhook)|svix\\.webhook|webhook\\.verify/i;\r\nconst RATE_LIMIT = /ratelimit|rate-limit|rate_limiter|too many requests|status\\s*:\\s*429/i;\r\nconst OAUTH_CALLBACK = /oauth|callback|redirect_uri|redirecturl|authorized redirect|allowed redirect/i;\r\nconst SECURITY_HEADERS = /content-security-policy|strict-transport-security|x-frame-options|x-content-type-options|referrer-policy|permissions-policy/i;\r\nconst SERVICE_ROLE = /\\bSUPABASE_SERVICE_ROLE_KEY\\b|service[-_]?role/i;\r\nconst SERVER_ONLY_HINT = /server-only|\\.server\\.|\\/server\\/|app\\/api\\/|pages\\/api\\/|\\/api\\/|route\\.[jt]s|actions?\\.[jt]s/i;\r\nconst ENV_OR_DOC_PATH = /(^|\\/)(\\.env\\.example|env\\.example|readme|docs?)|\\.md$/i;\r\n\r\nexport function analyzeRepositoryEvidence(scan: ScanResult): RepositoryEvidenceSummary {\r\n const files = visibleFiles(scan);\r\n const pathBlob = `${scan.fileTree}\\n${scan.files.map((file) => file.path).join('\\n')}`.replace(/\\\\/g, '/');\r\n const contentBlob = files.map((file) => file.content as string).join('\\n');\r\n\r\n return {\r\n env: collectEnvVarEvidence(scan, CORE_ENV_NAMES),\r\n security: [\r\n clientSecretReference(files),\r\n serviceRoleScope(files),\r\n foundOrMissing(\r\n 'supabase-rls-policy',\r\n 'Supabase RLS policy evidence',\r\n RLS_POLICY.test(contentBlob),\r\n evidenceFor(files, RLS_POLICY)\r\n ),\r\n foundOrMissing(\r\n 'webhook-signature-verification',\r\n 'Webhook signature verification evidence',\r\n WEBHOOK_SIGNATURE.test(contentBlob),\r\n evidenceFor(files, WEBHOOK_SIGNATURE)\r\n ),\r\n foundOrMissing(\r\n 'rate-limit-evidence',\r\n 'Rate limit evidence',\r\n Boolean(scan.stackSignals.hasRateLimit) || RATE_LIMIT.test(contentBlob),\r\n evidenceFor(files, RATE_LIMIT)\r\n ),\r\n foundOrMissing(\r\n 'oauth-callback-evidence',\r\n 'OAuth callback or redirect evidence',\r\n OAUTH_CALLBACK.test(`${contentBlob}\\n${pathBlob}`),\r\n evidenceFor(files, OAUTH_CALLBACK).concat(pathEvidence(scan, OAUTH_CALLBACK))\r\n ),\r\n foundOrMissing(\r\n 'security-headers',\r\n 'Security headers evidence',\r\n SECURITY_HEADERS.test(contentBlob),\r\n evidenceFor(files, SECURITY_HEADERS)\r\n )\r\n ]\r\n };\r\n}\r\n\r\nfunction visibleFiles(scan: ScanResult): ScannedFile[] {\r\n return scan.files.filter((file) => !file.isSecret && typeof file.content === 'string');\r\n}\r\n\r\nfunction foundOrMissing(id: string, label: string, found: boolean, evidence: string[]): RepositoryEvidenceItem {\r\n return {\r\n id,\r\n label,\r\n status: found ? 'found' : 'missing',\r\n evidence: unique(evidence).slice(0, 6)\r\n };\r\n}\r\n\r\nfunction clientSecretReference(files: ScannedFile[]): RepositoryEvidenceItem {\r\n const risky = files.filter((file) => isClientReachableFile(file) && SECRET_ENV_REFERENCE.test(file.content as string));\r\n return {\r\n id: 'client-secret-reference',\r\n label: 'No client-side secret references found',\r\n status: risky.length > 0 ? 'risk' : 'found',\r\n evidence: risky.map((file) => `file: ${normalizePath(file.path)}`).slice(0, 6)\r\n };\r\n}\r\n\r\nfunction serviceRoleScope(files: ScannedFile[]): RepositoryEvidenceItem {\r\n const references = files.filter((file) => SERVICE_ROLE.test(file.content as string));\r\n const risky = references.filter((file) => isClientReachableFile(file) && !SERVER_ONLY_HINT.test(normalizePath(file.path)));\r\n if (risky.length > 0) {\r\n return {\r\n id: 'service-role-scope',\r\n label: 'Supabase service role stays server-only',\r\n status: 'risk',\r\n evidence: risky.map((file) => `file: ${normalizePath(file.path)}`).slice(0, 6)\r\n };\r\n }\r\n\r\n const serverEvidence = references.filter((file) => isServerOnlyPath(file.path) && !isEnvOrDocPath(file.path));\r\n\r\n return {\r\n id: 'service-role-scope',\r\n label: 'Supabase service role stays server-only',\r\n status: serverEvidence.length > 0 ? 'found' : 'unknown',\r\n evidence: serverEvidence.map((file) => `file: ${normalizePath(file.path)}`).slice(0, 6)\r\n };\r\n}\r\n\r\nfunction evidenceFor(files: ScannedFile[], pattern: RegExp): string[] {\r\n return files\r\n .filter((file) => pattern.test(file.content as string))\r\n .map((file) => `file: ${normalizePath(file.path)}`)\r\n .slice(0, 6);\r\n}\r\n\r\nfunction pathEvidence(scan: ScanResult, pattern: RegExp): string[] {\r\n return scan.files\r\n .map((file) => normalizePath(file.path))\r\n .filter((path) => pattern.test(path))\r\n .map((path) => `file: ${path}`)\r\n .slice(0, 6);\r\n}\r\n\r\nfunction isClientReachableFile(file: ScannedFile): boolean {\r\n const content = file.content as string;\r\n const normalized = normalizePath(file.path).toLowerCase();\r\n if (hasUseClientDirective(content)) {\r\n return true;\r\n }\r\n if (/\\.client\\.[jt]sx?$|(^|\\/)(client|frontend|public)\\//.test(normalized)) {\r\n return true;\r\n }\r\n\r\n return isBrowserOnlyPath(file.path) && /\\b(window|document|localStorage|sessionStorage|navigator|useEffect|onClick)\\b/.test(content);\r\n}\r\n\r\nfunction hasUseClientDirective(content: string): boolean {\r\n return /^(?:\\s|;|\\/\\/[^\\n]*(?:\\n|$)|\\/\\*[\\s\\S]*?\\*\\/)*['\"]use client['\"]/.test(content);\r\n}\r\n\r\nfunction isBrowserOnlyPath(path: string): boolean {\r\n const normalized = normalizePath(path).toLowerCase();\r\n if (isServerOnlyPath(path)) {\r\n return false;\r\n }\r\n\r\n return (\r\n /(^|\\/)(components|hooks|contexts|providers)\\//.test(normalized) ||\r\n /\\.(jsx|tsx)$/.test(normalized)\r\n );\r\n}\r\n\r\nfunction isServerOnlyPath(path: string): boolean {\r\n const normalized = normalizePath(path).toLowerCase();\r\n return /\\/api\\/|app\\/api\\/|pages\\/api\\/|route\\.[jt]s$|\\.server\\.[jt]sx?$|\\/server\\//.test(normalized);\r\n}\r\n\r\nfunction isEnvOrDocPath(path: string): boolean {\r\n return ENV_OR_DOC_PATH.test(normalizePath(path).toLowerCase());\r\n}\r\n\r\nfunction normalizePath(path: string): string {\r\n return path.replace(/\\\\/g, '/');\r\n}\r\n\r\nfunction unique(values: string[]): string[] {\r\n return [...new Set(values)];\r\n}\r\n", "import type { ScanResult, StationScanContext } from './types';\n\nexport function computeStationScanContext(scan: ScanResult): StationScanContext {\n const s = scan.stackSignals;\n const hasDb = Boolean(s.hasSupabase || s.hasPrisma || s.hasDrizzle || s.hasMongoose);\n const pathBlob = `${scan.fileTree}\\n${scan.files.map((f) => f.path).join('\\n')}`;\n const apiHeavy = /[/\\\\]api[/\\\\]|[/\\\\]routes[/\\\\]|\\btrpc\\b|\\bserver\\.(ts|js|mjs)\\b/i.test(pathBlob);\n\n const sqlish = scan.files\n .filter((f) => /\\.sql$/i.test(f.path) && typeof f.content === 'string')\n .map((f) => f.content as string)\n .join('\\n')\n .slice(0, 80000);\n const rlsInSql = /create\\s+policy|enable\\s+row\\s+level\\s+security|alter\\s+table.*enable\\s+row\\s+level/i.test(\n sqlish\n );\n const rlsPaths = /supabase\\/migrations[/\\\\].*\\.sql|\\/policies\\/|_rls\\.sql|\\brls\\b/i.test(pathBlob);\n const rlsHint = rlsPaths || rlsInSql;\n\n return {\n suggestDatabaseLayer: !hasDb && apiHeavy,\n suggestSupabaseRlsReview: Boolean(s.hasSupabase && !rlsHint),\n suggestLandingPage: Boolean(!s.hasLanding && (s.hasNextJs || s.hasVite)),\n };\n}\n", "import type { SifgNodeKind, SifgRange } from './sifgTypes';\r\nimport type { ScanResult, StackWiringArea, StackWiringKey } from './types';\r\n\r\ntype CandidateBucket = 'sources' | 'guards' | 'sinks';\r\n\r\nexport interface SifgCandidate {\r\n kind: SifgNodeKind;\r\n area: StackWiringArea;\r\n providerKey: StackWiringKey;\r\n label: string;\r\n file: string;\r\n range: SifgRange;\r\n symbol: string;\r\n evidence: Record<string, string>;\r\n secretPolicy: 'no-values';\r\n}\r\n\r\nexport interface SifgUnknownCandidate {\r\n file: string;\r\n range: SifgRange;\r\n reason: 'Dynamic handler forwarding prevents deterministic flow proof.';\r\n}\r\n\r\nexport interface SifgCandidateSet {\r\n sources: SifgCandidate[];\r\n guards: SifgCandidate[];\r\n sinks: SifgCandidate[];\r\n unknowns: SifgUnknownCandidate[];\r\n}\r\n\r\nconst ROUTE_FILE_PATTERN = /^(?:src\\/)?app\\/api\\/(?:.*\\/)?route\\.(?:ts|js)$/;\r\nconst ROUTE_METHOD_PATTERN = /export\\s+async\\s+function\\s+(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\\b/;\r\nconst POST_METHOD_PATTERN = /export\\s+async\\s+function\\s+POST\\b/;\r\nconst STRIPE_SIGNATURE_PATTERN = /webhooks\\.constructEvent\\b/;\r\nconst PRISMA_WRITE_PATTERN = /\\bprisma\\.[A-Za-z0-9_]+\\.(?:create|update|delete)\\s*\\(/;\r\nconst SUPABASE_WRITE_PATTERN = /\\bsupabase\\.from\\s*\\([^)]*\\)\\s*\\.\\s*(?:insert|update|delete)\\s*\\(/;\r\nconst DB_WRITE_PATTERN = /\\bdb\\.(?:insert|update|delete)\\s*\\(/;\r\nconst DYNAMIC_FORWARD_PATTERN = /return\\s+handler\\s*\\(\\s*req\\s*\\)/;\r\n\r\nexport function extractSifgCandidates(scan: ScanResult): SifgCandidateSet {\r\n const candidates: SifgCandidateSet = {\r\n sources: [],\r\n guards: [],\r\n sinks: [],\r\n unknowns: []\r\n };\r\n\r\n for (const scannedFile of scan.files) {\r\n if (scannedFile.isSecret || typeof scannedFile.content !== 'string') {\r\n continue;\r\n }\r\n\r\n const file = scannedFile.path.replace(/\\\\/g, '/');\r\n const content = scannedFile.content;\r\n const isRouteFile = ROUTE_FILE_PATTERN.test(file);\r\n\r\n if (isRouteFile && ROUTE_METHOD_PATTERN.test(content)) {\r\n const symbol = POST_METHOD_PATTERN.test(content) ? 'POST' : 'ANY';\r\n const isStripePostRoute = /stripe/i.test(file) && symbol === 'POST';\r\n addCandidate(candidates, 'sources', {\r\n kind: 'entrypoint',\r\n area: isStripePostRoute ? 'payments' : 'security',\r\n providerKey: isStripePostRoute ? 'stripe-payments' : 'rate-limit-security',\r\n label: isStripePostRoute ? 'Stripe route handler' : 'API route handler',\r\n file,\r\n range: rangeForMatch(content, symbol === 'POST' ? POST_METHOD_PATTERN : ROUTE_METHOD_PATTERN),\r\n symbol,\r\n evidence: { detector: 'nextjs-route-handler', symbol },\r\n secretPolicy: 'no-values'\r\n });\r\n }\r\n\r\n if (/stripe/i.test(`${file}\\n${content}`) && STRIPE_SIGNATURE_PATTERN.test(content)) {\r\n addCandidate(candidates, 'guards', {\r\n kind: 'signature-verifier',\r\n area: 'payments',\r\n providerKey: 'stripe-payments',\r\n label: 'Stripe signature verifier',\r\n file,\r\n range: rangeForMatch(content, STRIPE_SIGNATURE_PATTERN),\r\n symbol: 'stripe.webhooks.constructEvent',\r\n evidence: {\r\n detector: 'stripe-signature-guard',\r\n proof: 'stripe.webhooks.constructEvent'\r\n },\r\n secretPolicy: 'no-values'\r\n });\r\n }\r\n\r\n const databaseWritePattern = firstMatchingPattern(content, [\r\n PRISMA_WRITE_PATTERN,\r\n SUPABASE_WRITE_PATTERN,\r\n DB_WRITE_PATTERN\r\n ]);\r\n if (databaseWritePattern) {\r\n addCandidate(candidates, 'sinks', {\r\n kind: 'database-write',\r\n area: 'database',\r\n providerKey: 'supabase-database',\r\n label: 'Database write',\r\n file,\r\n range: rangeForMatch(content, databaseWritePattern),\r\n symbol: 'database-write',\r\n evidence: { detector: 'database-write', symbol: 'database-write' },\r\n secretPolicy: 'no-values'\r\n });\r\n }\r\n\r\n if (isRouteFile && DYNAMIC_FORWARD_PATTERN.test(content)) {\r\n candidates.unknowns.push({\r\n file,\r\n range: rangeForMatch(content, DYNAMIC_FORWARD_PATTERN),\r\n reason: 'Dynamic handler forwarding prevents deterministic flow proof.'\r\n });\r\n }\r\n }\r\n\r\n return candidates;\r\n}\r\n\r\nfunction addCandidate(\r\n candidates: SifgCandidateSet,\r\n bucket: CandidateBucket,\r\n candidate: SifgCandidate\r\n): void {\r\n candidates[bucket].push(candidate);\r\n}\r\n\r\nfunction firstMatchingPattern(content: string, patterns: RegExp[]): RegExp | null {\r\n return patterns.find((pattern) => pattern.test(content)) ?? null;\r\n}\r\n\r\nfunction rangeForMatch(content: string, pattern: RegExp): SifgRange {\r\n const match = pattern.exec(content);\r\n if (!match || match.index < 0) {\r\n return { startLine: 1, endLine: 1 };\r\n }\r\n\r\n const startLine = lineNumberAtOffset(content, match.index);\r\n const endOffset = Math.max(match.index, match.index + match[0].length - 1);\r\n const endLine = lineNumberAtOffset(content, endOffset);\r\n return { startLine, endLine };\r\n}\r\n\r\nfunction lineNumberAtOffset(content: string, offset: number): number {\r\n let line = 1;\r\n for (let index = 0; index < offset; index += 1) {\r\n if (content[index] === '\\n') {\r\n line += 1;\r\n }\r\n }\r\n return line;\r\n}\r\n", "import { extractSifgCandidates, type SifgCandidate } from './sifgExtractors';\r\nimport { allSifgTemplates, type SifgTemplate } from './sifgTemplates';\r\nimport type { ScanResult } from './types';\r\nimport type {\r\n SifgEdge,\r\n SifgGraph,\r\n SifgGraphStatus,\r\n SifgLeak,\r\n SifgNode,\r\n SifgNodeKind,\r\n SifgPipeline,\r\n SifgSeverity\r\n} from './sifgTypes';\r\n\r\nconst STRIPE_PIPELINE_ID_PREFIX = 'pipeline:payments:stripe:webhook-ingress';\r\nconst STRIPE_LEAK_ID_PREFIX = 'leak:payments:stripe:missing-signature-before-db';\r\nconst STRIPE_MISSION_CHECK_ID = 'stripe-webhook-signature-verification';\r\n\r\nexport function buildStaticInfrastructureFlowGraph(scan: ScanResult, now = new Date()): SifgGraph {\r\n const candidates = extractSifgCandidates(scan);\r\n const templates = allSifgTemplates();\r\n const nodeIndex = new Map<SifgCandidate, SifgNode>();\r\n const usedNodeIds = new Set<string>();\r\n\r\n const nodes = [...candidates.sources, ...candidates.guards, ...candidates.sinks].map((candidate) => {\r\n const node = candidateToNode(candidate, usedNodeIds);\r\n nodeIndex.set(candidate, node);\r\n return node;\r\n });\r\n\r\n const edges: SifgEdge[] = [];\r\n const pipelines: SifgPipeline[] = [];\r\n const leaks: SifgLeak[] = [];\r\n const stripeTemplate = templates.find((template) => template.id === 'template:payments:stripe:webhook-ingress');\r\n\r\n if (stripeTemplate && scan.stackSignals.hasStripe) {\r\n evaluateStripeWebhookIngress({\r\n candidates,\r\n nodeIndex,\r\n edges,\r\n pipelines,\r\n leaks,\r\n stripeTemplate\r\n });\r\n }\r\n\r\n return sanitizeGraph({\r\n version: 1,\r\n graphId: `sifg:workspace:${now.toISOString()}`,\r\n generatedAt: now.toISOString(),\r\n registryVersion: 1,\r\n status: graphStatus(pipelines, leaks),\r\n nodes,\r\n edges,\r\n pipelines,\r\n leaks\r\n });\r\n}\r\n\r\ninterface StripeEvaluationInput {\r\n candidates: ReturnType<typeof extractSifgCandidates>;\r\n nodeIndex: Map<SifgCandidate, SifgNode>;\r\n edges: SifgEdge[];\r\n pipelines: SifgPipeline[];\r\n leaks: SifgLeak[];\r\n stripeTemplate: SifgTemplate;\r\n}\r\n\r\nfunction evaluateStripeWebhookIngress(input: StripeEvaluationInput): void {\r\n const stripeSources = input.candidates.sources\r\n .filter((candidate) =>\r\n candidate.kind === 'entrypoint' &&\r\n candidate.providerKey === 'stripe-payments' &&\r\n candidate.symbol === 'POST'\r\n )\r\n .sort(compareCandidatePosition);\r\n\r\n for (const sourceCandidate of stripeSources) {\r\n const source = input.nodeIndex.get(sourceCandidate);\r\n if (!source) {\r\n continue;\r\n }\r\n\r\n const sameFileGuards = input.candidates.guards\r\n .filter((candidate) => candidate.file === source.file && candidate.kind === 'signature-verifier')\r\n .sort(compareCandidatePosition);\r\n const sameFileSinks = input.candidates.sinks\r\n .filter((candidate) => candidate.file === source.file && candidate.kind === 'database-write')\r\n .sort(compareCandidatePosition);\r\n const guard = sameFileGuards.map((candidate) => input.nodeIndex.get(candidate)).find(isSifgNode);\r\n const sink = sameFileSinks.map((candidate) => input.nodeIndex.get(candidate)).find(isSifgNode);\r\n const hasUnknown = input.candidates.unknowns.some((unknown) => unknown.file === source.file);\r\n const requiredEdges: string[] = [];\r\n const forbiddenEdges: string[] = [];\r\n const sourceSuffix = sourceSlug(source);\r\n const pipelineId = `${STRIPE_PIPELINE_ID_PREFIX}:${sourceSuffix}`;\r\n\r\n let status: SifgGraphStatus = 'unknown';\r\n let severity: SifgSeverity = 'warning';\r\n\r\n if (guard && sink && guard.range.startLine < sink.range.startLine) {\r\n const edge = buildEdge(source, sink, 'guarded-flow', 'verified', guard);\r\n input.edges.push(edge);\r\n requiredEdges.push(edge.id);\r\n status = 'verified';\r\n severity = 'info';\r\n } else if (sink && (!guard || guard.range.startLine > sink.range.startLine)) {\r\n const edge = buildEdge(source, sink, 'forbidden-flow', 'leak');\r\n input.edges.push(edge);\r\n forbiddenEdges.push(edge.id);\r\n status = 'leak';\r\n severity = 'critical';\r\n input.leaks.push(buildStripeMissingSignatureLeak(\r\n source,\r\n sink,\r\n input.stripeTemplate,\r\n pipelineId,\r\n `${STRIPE_LEAK_ID_PREFIX}:${sourceSuffix}`\r\n ));\r\n } else if (hasUnknown) {\r\n const target = sink ?? guard ?? source;\r\n const edge = buildEdge(source, target, 'unknown-flow', 'unknown');\r\n input.edges.push(edge);\r\n requiredEdges.push(edge.id);\r\n }\r\n\r\n input.pipelines.push({\r\n id: pipelineId,\r\n area: 'payments',\r\n providerKey: 'stripe-payments',\r\n label: input.stripeTemplate.label,\r\n source: source.id,\r\n requiredEdges,\r\n forbiddenEdges,\r\n status,\r\n severity,\r\n missionCheckIds: [STRIPE_MISSION_CHECK_ID]\r\n });\r\n }\r\n}\r\n\r\nfunction candidateToNode(candidate: SifgCandidate, usedNodeIds: Set<string>): SifgNode {\r\n const baseId = sanitizeId(`node:${candidate.kind}:${candidate.file}:${candidate.range.startLine}`);\r\n const id = uniqueId(baseId, usedNodeIds);\r\n\r\n return {\r\n id,\r\n area: candidate.area,\r\n providerKey: candidate.providerKey,\r\n kind: candidate.kind,\r\n label: symbolicNodeLabel(candidate),\r\n file: candidate.file,\r\n range: { ...candidate.range },\r\n evidence: normalizeCandidateEvidence(candidate),\r\n secretPolicy: 'no-values'\r\n };\r\n}\r\n\r\nfunction buildEdge(\r\n source: SifgNode,\r\n target: SifgNode,\r\n kind: SifgEdge['kind'],\r\n status: SifgEdge['status'],\r\n guard?: SifgNode\r\n): SifgEdge {\r\n return {\r\n id: sanitizeId(`edge:${kind}:${source.id}:${target.id}`),\r\n from: source.id,\r\n to: target.id,\r\n kind,\r\n status,\r\n evidence: [{\r\n file: target.file,\r\n range: target.range,\r\n proof: guard ? `${guard.kind}: ${guard.evidence.symbol ?? guard.label}` : target.kind\r\n }]\r\n };\r\n}\r\n\r\nfunction buildStripeMissingSignatureLeak(\r\n source: SifgNode,\r\n sink: SifgNode,\r\n stripeTemplate: SifgTemplate,\r\n pipelineId: string,\r\n leakId: string\r\n): SifgLeak {\r\n const requiredGuard = stripeTemplate.requiredGuards.find((guard) => guard.kind === 'signature-verifier');\r\n const guardKind = normalizeTemplateGuardKind(requiredGuard?.kind);\r\n\r\n return {\r\n id: leakId,\r\n pipelineId,\r\n area: 'payments',\r\n providerKey: 'stripe-payments',\r\n kind: 'missing-mandatory-guard',\r\n severity: 'critical',\r\n summary: 'Stripe webhook request body reaches database code without proven signature verification.',\r\n evidencePath: [\r\n { nodeId: source.id, file: source.file, range: source.range, role: 'source' },\r\n { nodeId: sink.id, file: sink.file, range: sink.range, role: 'sink' }\r\n ],\r\n missingGuard: {\r\n expectedNodeKind: guardKind,\r\n expectedEvidence: buildExpectedGuardEvidence(requiredGuard, guardKind)\r\n },\r\n repoFix: {\r\n allowedFiles: [source.file],\r\n forbiddenFiles: [...stripeTemplate.repoFixPolicy.blockedFileGlobs],\r\n requiredOutcome: buildRequiredOutcome(requiredGuard, guardKind)\r\n }\r\n };\r\n}\r\n\r\nfunction graphStatus(pipelines: SifgPipeline[], leaks: SifgLeak[]): SifgGraphStatus {\r\n if (leaks.length > 0) {\r\n return 'leak';\r\n }\r\n\r\n if (pipelines.some((pipeline) => pipeline.status === 'unknown')) {\r\n return 'unknown';\r\n }\r\n\r\n if (pipelines.some((pipeline) => pipeline.status === 'verified')) {\r\n return 'verified';\r\n }\r\n\r\n return 'unknown';\r\n}\r\n\r\nfunction compareCandidatePosition(left: SifgCandidate, right: SifgCandidate): number {\r\n return left.file.localeCompare(right.file) || left.range.startLine - right.range.startLine;\r\n}\r\n\r\nfunction isSifgNode(value: SifgNode | undefined): value is SifgNode {\r\n return Boolean(value);\r\n}\r\n\r\nfunction symbolicNodeLabel(candidate: SifgCandidate): string {\r\n if (candidate.providerKey === 'stripe-payments' && candidate.kind === 'entrypoint') {\r\n return 'Stripe webhook entrypoint';\r\n }\r\n\r\n if (candidate.kind === 'signature-verifier') {\r\n return 'Stripe signature verifier';\r\n }\r\n\r\n if (candidate.kind === 'database-write') {\r\n return 'Database write sink';\r\n }\r\n\r\n return `${candidate.providerKey} ${candidate.kind}`;\r\n}\r\n\r\nfunction normalizeCandidateEvidence(candidate: SifgCandidate): Record<string, string> {\r\n return {\r\n detector: normalizeDetector(candidate.evidence.detector, candidate.kind),\r\n symbol: normalizeSymbol(candidate)\r\n };\r\n}\r\n\r\nfunction normalizeDetector(detector: string | undefined, kind: SifgCandidate['kind']): string {\r\n if (detector && /^[a-z0-9-]+$/i.test(detector)) {\r\n return detector;\r\n }\r\n\r\n return kind;\r\n}\r\n\r\nfunction normalizeSymbol(candidate: SifgCandidate): string {\r\n if (candidate.kind === 'entrypoint' && (candidate.symbol === 'POST' || candidate.symbol === 'ANY')) {\r\n return candidate.symbol;\r\n }\r\n\r\n if (\r\n candidate.kind === 'signature-verifier' &&\r\n (candidate.symbol.includes('stripe.webhooks.constructEvent') ||\r\n candidate.evidence.proof?.includes('stripe.webhooks.constructEvent'))\r\n ) {\r\n return 'stripe.webhooks.constructEvent';\r\n }\r\n\r\n if (candidate.kind === 'database-write') {\r\n return 'database-write';\r\n }\r\n\r\n return candidate.kind;\r\n}\r\n\r\nfunction normalizeTemplateGuardKind(kind: string | undefined): SifgNodeKind {\r\n return kind === 'signature-verifier' ? 'signature-verifier' : 'signature-verifier';\r\n}\r\n\r\nfunction buildExpectedGuardEvidence(\r\n guard: SifgTemplate['requiredGuards'][number] | undefined,\r\n guardKind: SifgNodeKind\r\n): string {\r\n const symbols = guard?.symbols.length ? guard.symbols.join(', ') : guardKind;\r\n const envNames = guard?.requiresEnvNames?.length ? ` using ${guard.requiresEnvNames.join(', ')}` : '';\r\n const targets = guard?.mustPrecede.length ? ` before ${formatList(guard.mustPrecede)}` : '';\r\n return `${guardKind}: ${symbols}${envNames}${targets}`;\r\n}\r\n\r\nfunction buildRequiredOutcome(\r\n guard: SifgTemplate['requiredGuards'][number] | undefined,\r\n guardKind: SifgNodeKind\r\n): string {\r\n const symbols = guard?.symbols.length ? guard.symbols.join(', ') : guardKind;\r\n const envNames = guard?.requiresEnvNames?.length ? ` using ${guard.requiresEnvNames.join(', ')}` : '';\r\n const targets = guard?.mustPrecede.length ? formatList(guard.mustPrecede) : 'database-write';\r\n return `Verify ${guardKind} (${symbols}${envNames}) before ${targets}.`;\r\n}\r\n\r\nfunction formatList(items: string[]): string {\r\n if (items.length <= 1) {\r\n return items.join('');\r\n }\r\n\r\n if (items.length === 2) {\r\n return `${items[0]} or ${items[1]}`;\r\n }\r\n\r\n return `${items.slice(0, -1).join(', ')}, or ${items[items.length - 1]}`;\r\n}\r\n\r\nfunction uniqueId(baseId: string, usedNodeIds: Set<string>): string {\r\n let id = baseId;\r\n let suffix = 2;\r\n while (usedNodeIds.has(id)) {\r\n id = `${baseId}.${suffix}`;\r\n suffix += 1;\r\n }\r\n usedNodeIds.add(id);\r\n return id;\r\n}\r\n\r\nfunction sanitizeId(value: string): string {\r\n return value.replace(/[^a-zA-Z0-9:._-]/g, '-');\r\n}\r\n\r\nfunction sourceSlug(source: SifgNode): string {\r\n return sanitizeId(source.id);\r\n}\r\n\r\nfunction sanitizeGraph(graph: SifgGraph): SifgGraph {\r\n return redactStructured(graph) as SifgGraph;\r\n}\r\n\r\nfunction redactStructured(value: unknown): unknown {\r\n if (typeof value === 'string') {\r\n return redactSecretLike(value);\r\n }\r\n\r\n if (Array.isArray(value)) {\r\n return value.map(redactStructured);\r\n }\r\n\r\n if (value && typeof value === 'object') {\r\n return Object.fromEntries(\r\n Object.entries(value).map(([key, child]) => [key, redactStructured(child)])\r\n );\r\n }\r\n\r\n return value;\r\n}\r\n\r\nfunction redactSecretLike(value: string): string {\r\n return value\r\n .replace(/\\bsk_(?:live|test)_[a-zA-Z0-9_]+\\b/g, '[redacted]')\r\n .replace(/\\bBearer\\s+[a-zA-Z0-9._~+/=-]+\\b/gi, 'Bearer [redacted]')\r\n .replace(/\\b(api[_-]?key|access[_-]?token|refresh[_-]?token|secret)\\s*[:=]\\s*[^\\s\"'`,;)}]+/gi, '$1=[redacted]');\r\n}\r\n", "import type { ContextualPromptSection } from './promptRouting';\r\nimport type { SifgLeak } from './sifgTypes';\r\n\r\nexport function buildSifgFixPromptSection(leak: SifgLeak): ContextualPromptSection {\r\n return {\r\n heading: 'SIFG leak context',\r\n lines: [\r\n `Leak ID: ${sanitizePromptValue(leak.id)}`,\r\n `Pipeline ID: ${sanitizePromptValue(leak.pipelineId)}`,\r\n `Severity: ${sanitizePromptValue(leak.severity)}`,\r\n `Summary: ${sanitizePromptValue(leak.summary)}`,\r\n `Evidence path: ${evidencePathLine(leak)}`,\r\n leak.missingGuard\r\n ? `Missing guard: ${sanitizePromptValue(leak.missingGuard.expectedNodeKind)} (${sanitizePromptValue(leak.missingGuard.expectedEvidence)})`\r\n : 'Missing guard: none',\r\n `Allowed files: ${sanitizeList(leak.repoFix.allowedFiles)}`,\r\n `Blocked files: ${sanitizeList(leak.repoFix.forbiddenFiles)}`,\r\n `Required outcome: ${sanitizePromptValue(leak.repoFix.requiredOutcome)}`,\r\n 'Manual dashboard and MCP checks remain separate.',\r\n 'Do not read, print, invent, or store real secret values.',\r\n 'After editing, rescan VibeRaven so SIFG can verify the structural flow.'\r\n ]\r\n };\r\n}\r\n\r\nfunction evidencePathLine(leak: SifgLeak): string {\r\n if (leak.evidencePath.length === 0) {\r\n return 'none';\r\n }\r\n return leak.evidencePath\r\n .map((step) => `${sanitizePromptValue(step.role)} ${sanitizePromptValue(step.file)}:${step.range.startLine}-${step.range.endLine}`)\r\n .join(' -> ');\r\n}\r\n\r\nfunction sanitizeList(values: string[]): string {\r\n return values.map(sanitizePromptValue).join(', ');\r\n}\r\n\r\nfunction sanitizePromptValue(value: string): string {\r\n return value\r\n .replace(/[\\r\\n\\t]+/g, ' ')\r\n .replace(/[\\u0000-\\u001f\\u007f]+/g, ' ')\r\n .replace(/\\s{2,}/g, ' ')\r\n .trim()\r\n .replace(/\\b(Authorization\\s*:\\s*Bearer)\\s+[A-Za-z0-9._~+/=-]{8,}/gi, '$1 [redacted]')\r\n .replace(\r\n /\\b(client_secret|secret|password|access_token|refresh_token|private_key)\\s*([:=])\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s,;]+)/gi,\r\n (_match, key: string, separator: string) => `${key}${separator === ':' ? ': ' : '='}[redacted]`\r\n )\r\n .replace(/\\b(apiKey|accessToken|refreshToken|serviceRoleKey)\\s*:\\s*(?:\"[^\"]+\"|'[^']+'|[^\\s,;]+)/g, '$1: [redacted]')\r\n .replace(/\\b(apiKey|accessToken|refreshToken|serviceRoleKey)\\s*=\\s*(?:\"[^\"]+\"|'[^']+'|[^\\s,;]+)/g, '$1=[redacted]')\r\n .replace(\r\n /\\b([A-Za-z_][A-Za-z0-9_.-]*(?:SECRET|TOKEN|PASSWORD|PRIVATE_KEY|SERVICE_ROLE_KEY|apiKey|ApiKey|apikey|api_key|accessToken|refreshToken|serviceRoleKey)[A-Za-z0-9_.-]*)\\s*([:=])\\s*(?:\"[^\"]+\"|'[^']+'|[^\\s,;]+)/g,\r\n '$1$2[redacted]'\r\n )\r\n .replace(/\\b(?:whsec|github_pat|ghp|gho|ghu|ghs|ghr|gh_pat)_[A-Za-z0-9_]{8,}\\b/g, '[redacted-secret]')\r\n .replace(/\\b(?:sk|pk)_(?:live|test)_[a-zA-Z0-9_]+\\b/g, '[redacted-secret]')\r\n .replace(/\\beyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]{2,}\\.[A-Za-z0-9_-]{2,}\\b/g, '[redacted-secret]');\r\n}\r\n", "import type {\r\n ContextualPrompt,\r\n ContextualPromptKind,\r\n StackAutomationAction\r\n} from './types';\r\nimport { buildSifgFixPromptSection } from './sifgPrompt';\r\nimport type { SifgLeak } from './sifgTypes';\r\n\r\nexport interface ContextualPromptSection {\r\n heading: string;\r\n lines: string[];\r\n}\r\n\r\nexport interface BuildContextualPromptInput {\r\n kind: ContextualPromptKind;\r\n promptSubject: string;\r\n providerLabel?: string;\r\n passedCount?: number;\r\n totalCount?: number;\r\n readinessPercent?: number;\r\n repoFixes?: StackAutomationAction[];\r\n manualChecks?: StackAutomationAction[];\r\n mcpProvider?: string | null;\r\n ravenGap?: {\r\n title: string;\r\n detail?: string;\r\n };\r\n sections?: ContextualPromptSection[];\r\n sifgLeaks?: SifgLeak[];\r\n afterEditing?: string[];\r\n emptyBody?: boolean;\r\n}\r\n\r\nexport function buildContextualPrompt(input: BuildContextualPromptInput): ContextualPrompt {\r\n switch (input.kind) {\r\n case 'repo-fix':\r\n return buildRepoFixPrompt(input);\r\n case 'manual-checklist':\r\n return buildManualChecklistPrompt(input);\r\n case 'mcp-verification':\r\n return buildMcpVerificationPrompt(input);\r\n case 'raven-gap':\r\n return buildRavenGapPrompt(input);\r\n }\r\n}\r\n\r\nfunction buildRepoFixPrompt(input: BuildContextualPromptInput): ContextualPrompt {\r\n const sifgSections = input.sifgLeaks?.map(buildSifgFixPromptSection) ?? [];\r\n return {\r\n kind: 'repo-fix',\r\n title: `Repo fix: ${input.promptSubject}`,\r\n body: input.emptyBody ? '' : compactLines([\r\n `Automate ${input.promptSubject} production fixes safely.`,\r\n readinessLine(input),\r\n '',\r\n ...sectionLines([...sifgSections, ...(input.sections ?? [])]),\r\n 'Repo fixes to make:',\r\n actionLines(input.repoFixes, '- No repo fixes are currently missing.'),\r\n '',\r\n 'Manual checks to preserve as manual:',\r\n actionLines(input.manualChecks, '- No manual dashboard checks are listed.'),\r\n '',\r\n 'Rules:',\r\n '- Work only inside the local repository.',\r\n '- Do not open external dashboards.',\r\n '- Do not claim provider dashboard checks are complete.',\r\n '- Do not claim dashboard checks are complete from repo edits.',\r\n '- Do not print, request, store, or invent provider secrets.',\r\n '- Use placeholder env names only.',\r\n '- Change only files needed for the listed repo fixes.',\r\n '- Treat SIFG leak IDs as the source of truth for repo-local structural gaps.',\r\n '- Do not edit outside SIFG allowed files when SIFG context is present.',\r\n '- Follow the existing framework, file structure, and naming style.',\r\n '- Keep secrets in server-only code and env examples.',\r\n ...prefixedLines(input.afterEditing, '', 'After editing:')\r\n ]),\r\n allowedActions: ['edit-repo', 'run-local-tests'],\r\n forbiddenActions: ['verify-dashboard', 'open-dashboard', 'request-secrets', 'store-secrets', 'invent-secrets']\r\n };\r\n}\r\n\r\nfunction buildManualChecklistPrompt(input: BuildContextualPromptInput): ContextualPrompt {\r\n return {\r\n kind: 'manual-checklist',\r\n title: `Manual checklist: ${input.promptSubject}`,\r\n body: compactLines([\r\n `Prepare manual setup checklist for ${input.promptSubject}.`,\r\n '',\r\n 'Rules:',\r\n '- Prepare a checklist for the developer.',\r\n '- Do not mark dashboard setup complete.',\r\n '- Do not request, print, store, or invent secrets.',\r\n '',\r\n 'Manual checks:',\r\n actionLines(input.manualChecks, '- No manual dashboard checks are listed.')\r\n ]),\r\n allowedActions: ['explain-manual-steps'],\r\n forbiddenActions: ['mark-dashboard-complete', 'request-secrets', 'store-secrets', 'invent-secrets']\r\n };\r\n}\r\n\r\nfunction buildMcpVerificationPrompt(input: BuildContextualPromptInput): ContextualPrompt {\r\n return {\r\n kind: 'mcp-verification',\r\n title: `MCP verification: ${input.promptSubject}`,\r\n body: compactLines([\r\n `Verify ${input.promptSubject} after VibeRaven automation.`,\r\n input.mcpProvider ? `MCP verifier: ${input.mcpProvider}.` : 'MCP verifier: none configured.',\r\n '',\r\n 'Rules:',\r\n '- Use only read-only MCP calls if already configured and authenticated by the IDE.',\r\n '- Never store OAuth tokens, API keys, or MCP credentials.',\r\n '- Report MCP evidence as verifier evidence, not manual dashboard completion.',\r\n '- If the verifier is unavailable, say that and stop.',\r\n '',\r\n 'Verification:',\r\n '- Rescan the repo and confirm missing checks moved to passed where repo evidence exists.',\r\n '- Report any remaining missing repo fixes separately from dashboard/manual checks.',\r\n '- If no repo fixes remain, keep the remaining dashboard/manual checks explicit instead of editing unrelated code.'\r\n ]),\r\n allowedActions: ['read-only-mcp', 'summarize-evidence'],\r\n forbiddenActions: ['write-mcp', 'mutate-provider', 'store-mcp-credentials', 'mark-dashboard-complete']\r\n };\r\n}\r\n\r\nfunction buildRavenGapPrompt(input: BuildContextualPromptInput): ContextualPrompt {\r\n const gapTitle = input.ravenGap?.title ?? input.promptSubject;\r\n return {\r\n kind: 'raven-gap',\r\n title: `Raven gap: ${gapTitle}`,\r\n body: compactLines([\r\n `Fix Raven product gap: ${gapTitle}.`,\r\n input.ravenGap?.detail ? `Gap detail: ${input.ravenGap.detail}` : '',\r\n '',\r\n 'Rules:',\r\n '- Fix only the Raven product gap described.',\r\n '- Work only in the repo.',\r\n '- Do not rewrite unrelated product areas.',\r\n '- Do not open dashboards or claim external setup.',\r\n '',\r\n 'After editing:',\r\n '- Run the closest relevant local tests, compile, or typecheck command.',\r\n '- Summarize changed files and verified commands.'\r\n ]),\r\n allowedActions: ['edit-repo', 'run-local-tests'],\r\n forbiddenActions: ['open-dashboard', 'claim-external-setup', 'rewrite-unrelated-product-areas']\r\n };\r\n}\r\n\r\nfunction readinessLine(input: BuildContextualPromptInput): string {\r\n if (input.passedCount === undefined || input.totalCount === undefined || input.readinessPercent === undefined) {\r\n return '';\r\n }\r\n return `Current readiness: ${input.passedCount}/${input.totalCount} repo checks passed (${input.readinessPercent}%).`;\r\n}\r\n\r\nfunction sectionLines(sections: ContextualPromptSection[] | undefined): string[] {\r\n if (!sections || sections.length === 0) {\r\n return [];\r\n }\r\n return sections.flatMap((section) => [\r\n section.heading,\r\n ...section.lines.map((line) => `- ${line}`),\r\n ''\r\n ]);\r\n}\r\n\r\nfunction actionLines(actions: StackAutomationAction[] | undefined, fallback: string): string {\r\n if (!actions || actions.length === 0) {\r\n return fallback;\r\n }\r\n return actions.map((action) => `- ${action.label}: ${action.promptHint}`).join('\\n');\r\n}\r\n\r\nfunction prefixedLines(lines: string[] | undefined, fallback: string, heading: string): string[] {\r\n if (!lines || lines.length === 0) {\r\n return fallback ? [heading, fallback] : [];\r\n }\r\n return ['', heading, ...lines.map((line) => `- ${line}`)];\r\n}\r\n\r\nfunction compactLines(lines: Array<string | string[]>): string {\r\n return lines.flat().join('\\n').replace(/\\n{3,}/g, '\\n\\n').trim();\r\n}\r\n", "import type {\r\n ContextualPrompt,\r\n ContextualPromptKind,\r\n StackAutomationAction,\r\n StackAutomationRecipe,\r\n StackAutomationSummary,\r\n StackWiringItem,\r\n StackWiringKey,\r\n StackWiringProviderSummary,\r\n StackWiringSummary\r\n} from './types';\r\nimport type { SifgGraph, SifgLeak } from './sifgTypes';\r\nimport { mcpProviderIdForStackWiringKey } from './providerRegistry';\r\nimport { buildContextualPrompt, type ContextualPromptSection } from './promptRouting';\r\n\r\ntype PromptProfile = {\r\n inspect: string[];\r\n implement: string[];\r\n constraints: string[];\r\n verify: string[];\r\n};\r\n\r\nconst GENERIC_PROMPT_PROFILE: PromptProfile = {\r\n inspect: [\r\n 'Review the relevant routes, server code, client code, config files, package scripts, and env examples before editing.',\r\n 'Identify existing conventions for file names, imports, validation, and error handling.'\r\n ],\r\n implement: [\r\n 'Make the smallest repo-only changes needed for the missing checks.',\r\n 'Keep changes aligned with the current framework and folder structure.'\r\n ],\r\n constraints: [\r\n 'Do not call provider APIs, mutate external projects, or edit webview/dashboard state.',\r\n 'Keep secrets in server-only code and documented env examples.'\r\n ],\r\n verify: [\r\n 'Run the closest relevant build, test, lint, or typecheck command.',\r\n 'Confirm repo evidence exists for each fixed item and list manual checks separately.'\r\n ]\r\n};\r\n\r\nconst PROMPT_PROFILES: Partial<Record<StackWiringKey, PromptProfile>> = {\r\n 'stripe-payments': {\r\n inspect: [\r\n 'Inspect app/api, pages/api, server routes, checkout actions, webhook handlers, and .env.example before editing.',\r\n 'Check how STRIPE_SECRET_KEY, STRIPE_WEBHOOK_SECRET, price IDs, and success/cancel URLs are currently named.'\r\n ],\r\n implement: [\r\n 'Add or tighten a server-side Stripe webhook route that verifies signatures with webhooks.constructEvent before processing events.',\r\n 'Document required Stripe env names and keep checkout/session creation on the server.'\r\n ],\r\n constraints: [\r\n 'Do not create products, prices, customers, or webhooks through the Stripe API.',\r\n 'Do not mark live-mode products, webhook endpoint registration, or dashboard settings complete from repo edits.'\r\n ],\r\n verify: [\r\n 'Run the relevant route/unit tests or typecheck for payment code.',\r\n 'Confirm webhook secret usage and server-only Stripe code are visible in repo evidence.'\r\n ]\r\n },\r\n 'clerk-auth': {\r\n inspect: [\r\n 'Inspect middleware, protected routes, layout providers, server actions, and auth-related env examples.',\r\n 'Check current Clerk package usage, publishable key names, secret key names, and redirect handling.'\r\n ],\r\n implement: [\r\n 'Add route protection, auth provider setup, and server-side user checks where missing.',\r\n 'Document NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY, CLERK_SECRET_KEY, and required redirect URLs in repo examples.'\r\n ],\r\n constraints: [\r\n 'Do not configure Clerk dashboard applications, domains, or production instances.',\r\n 'Do not expose secret keys to client bundles.'\r\n ],\r\n verify: [\r\n 'Run auth-related tests or typecheck.',\r\n 'Confirm protected-route and env documentation evidence exists in the repo.'\r\n ]\r\n },\r\n 'supabase-database': {\r\n inspect: [\r\n 'Inspect Supabase client/server helpers, migrations, SQL policies, schema files, and env examples.',\r\n 'Check whether service-role usage is isolated to server-only paths.'\r\n ],\r\n implement: [\r\n 'Add missing schema, migration, RLS policy, and typed client evidence where repo checks require it.',\r\n 'Document SUPABASE_URL, anon key, and server-only service role env names without committing secrets.'\r\n ],\r\n constraints: [\r\n 'Do not call Supabase APIs, create remote projects, run dashboard changes, or apply migrations remotely.',\r\n 'Do not place service-role keys in client-accessible code.'\r\n ],\r\n verify: [\r\n 'Run database-related tests, migration checks, or typecheck available in the repo.',\r\n 'Confirm RLS and migration evidence is repo-visible and dashboard checks remain manual.'\r\n ]\r\n },\r\n 'vercel-deployment': {\r\n inspect: [\r\n 'Inspect vercel.json, package scripts, framework config, environment examples, and CI/deploy workflows.',\r\n 'Check build command, output settings, redirects, rewrites, and serverless/edge function usage.'\r\n ],\r\n implement: [\r\n 'Add repo deployment configuration, build scripts, env documentation, or route settings needed for missing checks.',\r\n 'Keep deployment assumptions encoded in config files rather than external dashboard state.'\r\n ],\r\n constraints: [\r\n 'Do not deploy, promote, link, or mutate Vercel projects.',\r\n 'Do not claim production domains, env vars, or dashboard settings are configured from repo edits.'\r\n ],\r\n verify: [\r\n 'Run the project build or compile command.',\r\n 'Confirm deployment config evidence exists and list dashboard checks as manual.'\r\n ]\r\n },\r\n 'sentry-monitoring': {\r\n inspect: [\r\n 'Inspect Sentry initialization, framework instrumentation files, error boundaries, source map config, and env examples.',\r\n 'Check client/server DSN separation and release/environment tagging conventions.'\r\n ],\r\n implement: [\r\n 'Add missing Sentry initialization, error capture, tracing, source map, or env documentation evidence.',\r\n 'Ensure captured errors include useful context without leaking secrets or PII.'\r\n ],\r\n constraints: [\r\n 'Do not create Sentry projects, upload releases, or change dashboard alert rules.',\r\n 'Do not hardcode DSNs or auth tokens outside env examples.'\r\n ],\r\n verify: [\r\n 'Run monitoring-related tests, build, or typecheck.',\r\n 'Confirm instrumentation and env evidence are present while dashboard checks remain manual.'\r\n ]\r\n },\r\n 'posthog-monitoring': {\r\n inspect: [\r\n 'Inspect PostHog initialization, analytics providers, event capture calls, consent handling, and env examples.',\r\n 'Check whether user identity, feature flags, and client/server keys are separated correctly.'\r\n ],\r\n implement: [\r\n 'Add missing PostHog setup, event capture, opt-in/consent, feature flag, or env documentation evidence.',\r\n 'Keep analytics initialization resilient around loading, routing, and disabled-key states.'\r\n ],\r\n constraints: [\r\n 'Do not create PostHog projects, change dashboard events, or mutate feature flags remotely.',\r\n 'Do not capture secrets, raw tokens, or unnecessary PII.'\r\n ],\r\n verify: [\r\n 'Run analytics-related tests, build, or typecheck.',\r\n 'Confirm repo evidence for initialization, capture, and privacy controls.'\r\n ]\r\n },\r\n 'react-frontend': {\r\n inspect: [\r\n 'Inspect components, routes, state/data-loading paths, forms, styling, and existing design-system patterns.',\r\n 'Check current loading, error, empty, and responsive states before editing.'\r\n ],\r\n implement: [\r\n 'Add missing loading states, error states, empty states, accessibility attributes, and responsive layout behavior.',\r\n 'Use existing component patterns and keep visual changes focused on the listed repo fixes.'\r\n ],\r\n constraints: [\r\n 'Do not edit external design tools, dashboards, or webview automation state.',\r\n 'Do not replace the app framework or introduce unrelated UI rewrites.'\r\n ],\r\n verify: [\r\n 'Run frontend tests, typecheck, or build.',\r\n 'Confirm loading, error, and responsive behavior have repo-visible evidence.'\r\n ]\r\n },\r\n 'node-backend': {\r\n inspect: [\r\n 'Inspect API routes, controllers, services, middleware, validation, logging, and env examples.',\r\n 'Check current error handling, request validation, authentication boundaries, and server startup scripts.'\r\n ],\r\n implement: [\r\n 'Add missing validation, error handling, health checks, logging, or server-only env documentation evidence.',\r\n 'Keep backend changes small and aligned with existing route/service patterns.'\r\n ],\r\n constraints: [\r\n 'Do not call production provider APIs or mutate external infrastructure.',\r\n 'Do not expose secrets in logs, client responses, or committed examples.'\r\n ],\r\n verify: [\r\n 'Run backend tests, typecheck, or compile.',\r\n 'Confirm fixed checks have repo evidence and operational dashboard checks stay manual.'\r\n ]\r\n }\r\n};\r\n\r\nexport function buildStackAutomationSummary(\r\n stackWiring: StackWiringSummary,\r\n options: { staticInfrastructureFlowGraph?: SifgGraph } = {}\r\n): StackAutomationSummary {\r\n const items = stackWiring.items.map((stack) => buildStackAutomationRecipe(stack, sifgLeaksForStack(stack, options.staticInfrastructureFlowGraph)));\r\n const byKey = items.reduce<StackAutomationSummary['byKey']>((acc, recipe) => {\r\n acc[recipe.key] = recipe;\r\n return acc;\r\n }, {});\r\n return { items, byKey };\r\n}\r\n\r\nexport function buildStackAutomationContext(summary: StackAutomationSummary): string {\r\n const lines = ['## STACK AUTOMATION'];\r\n for (const recipe of summary.items) {\r\n lines.push(`${recipe.key}: ${recipe.automationLevel}; repo fixes=${recipe.repoFixes.length}; manual checks=${recipe.manualChecks.length}; mcp=${recipe.mcpProvider ?? 'none'}`);\r\n for (const fix of recipe.repoFixes.slice(0, 6)) {\r\n lines.push(`${recipe.key} fix: ${fix.label} - ${fix.promptHint}`);\r\n }\r\n }\r\n return lines.join('\\n');\r\n}\r\n\r\nfunction buildStackAutomationRecipe(stack: StackWiringProviderSummary, sifgLeaks: SifgLeak[] = []): StackAutomationRecipe {\r\n const confirmedChecks = stack.items.filter((item) => item.status === 'passed').map(toAction);\r\n const repoFixes = stack.items.filter((item) => item.status === 'missing').map(toAction);\r\n const manualChecks = stack.items.filter((item) => item.status === 'manual').map(toAction);\r\n const mcpProvider = mcpProviderIdForStackWiringKey(stack.key);\r\n const hasRepoFixContext = repoFixes.length > 0 || sifgLeaks.length > 0;\r\n const automationLevel = !hasRepoFixContext && manualChecks.length > 0 ? 'manual-only' : mcpProvider ? 'repo-prompt-plus-mcp' : 'repo-prompt';\r\n const promptRoutes = buildPromptRoutes(stack, repoFixes, manualChecks, mcpProvider, automationLevel, sifgLeaks);\r\n return {\r\n key: stack.key,\r\n provider: stack.provider,\r\n providerLabel: stack.providerLabel,\r\n area: stack.area,\r\n promptSubject: stack.promptSubject,\r\n readinessPercent: stack.readinessPercent,\r\n repoFixes,\r\n manualChecks,\r\n confirmedChecks,\r\n mcpProvider,\r\n repoPrompt: promptRoutes['repo-fix']?.body ?? '',\r\n verificationPrompt: verificationPromptForRecipe(promptRoutes, automationLevel, manualChecks, sifgLeaks),\r\n automationLevel,\r\n promptRoutes\r\n };\r\n}\r\n\r\nfunction toAction(item: StackWiringItem): StackAutomationAction {\r\n return {\r\n id: item.id,\r\n label: item.label,\r\n status: item.status,\r\n promptHint: item.promptHint,\r\n evidence: item.evidence\r\n };\r\n}\r\n\r\nfunction buildPromptRoutes(\r\n stack: StackWiringProviderSummary,\r\n repoFixes: StackAutomationAction[],\r\n manualChecks: StackAutomationAction[],\r\n mcpProvider: string | null,\r\n automationLevel: StackAutomationRecipe['automationLevel'],\r\n sifgLeaks: SifgLeak[]\r\n): Partial<Record<ContextualPromptKind, ContextualPrompt>> {\r\n return {\r\n 'repo-fix': buildContextualPrompt({\r\n kind: 'repo-fix',\r\n promptSubject: stack.promptSubject,\r\n providerLabel: stack.providerLabel,\r\n passedCount: stack.passedCount,\r\n totalCount: stack.totalCount,\r\n readinessPercent: stack.readinessPercent,\r\n repoFixes,\r\n manualChecks,\r\n sifgLeaks,\r\n sections: buildRepoPromptSections(stack),\r\n afterEditing: [\r\n 'Run the relevant build/test/typecheck command.',\r\n 'Summarize changed files, verified commands, and manual checks still needed.'\r\n ],\r\n emptyBody: automationLevel === 'manual-only'\r\n }),\r\n 'manual-checklist': buildContextualPrompt({\r\n kind: 'manual-checklist',\r\n promptSubject: stack.promptSubject,\r\n providerLabel: stack.providerLabel,\r\n manualChecks\r\n }),\r\n 'mcp-verification': buildContextualPrompt({\r\n kind: 'mcp-verification',\r\n promptSubject: stack.promptSubject,\r\n providerLabel: stack.providerLabel,\r\n mcpProvider\r\n })\r\n };\r\n}\r\n\r\nfunction sifgLeaksForStack(stack: StackWiringProviderSummary, graph: SifgGraph | undefined): SifgLeak[] {\r\n if (!graph) {\r\n return [];\r\n }\r\n return graph.leaks.filter((leak) => leak.providerKey === stack.key);\r\n}\r\n\r\nfunction verificationPromptForRecipe(\r\n promptRoutes: Partial<Record<ContextualPromptKind, ContextualPrompt>>,\r\n automationLevel: StackAutomationRecipe['automationLevel'],\r\n manualChecks: StackAutomationAction[],\r\n sifgLeaks: SifgLeak[]\r\n): string {\r\n const manualPrompt = promptRoutes['manual-checklist']?.body ?? '';\r\n const mcpPrompt = promptRoutes['mcp-verification']?.body ?? '';\r\n if (automationLevel === 'manual-only') {\r\n return manualPrompt || mcpPrompt;\r\n }\r\n if (sifgLeaks.length > 0 && manualChecks.length > 0) {\r\n return [manualPrompt, mcpPrompt].filter(Boolean).join('\\n\\n');\r\n }\r\n return mcpPrompt;\r\n}\r\n\r\nfunction buildRepoPromptSections(stack: StackWiringProviderSummary): ContextualPromptSection[] {\r\n const profile = PROMPT_PROFILES[stack.key] ?? GENERIC_PROMPT_PROFILE;\r\n return [\r\n { heading: 'Inspect first:', lines: profile.inspect },\r\n { heading: 'Implement:', lines: profile.implement },\r\n { heading: 'Provider constraints:', lines: profile.constraints },\r\n { heading: 'Verification:', lines: profile.verify }\r\n ];\r\n}\r\n", "import type { ScanResult, StackWiringItem, StackWiringStatus, SupabaseDatabaseWiringSummary } from './types';\r\n\r\ntype ScannableFile = {\r\n path: string;\r\n normalizedPath: string;\r\n content: string;\r\n lowerContent: string;\r\n};\r\n\r\nexport function analyzeSupabaseDatabaseWiring(scan: ScanResult): SupabaseDatabaseWiringSummary {\r\n const files = visibleFiles(scan);\r\n const deps = scan.packageDeps.map((dep) => dep.toLowerCase());\r\n const pathBlob = `${scan.fileTree}\\n${scan.files.map((file) => file.path).join('\\n')}`.replace(/\\\\/g, '/').toLowerCase();\r\n const contentBlob = files.map((file) => file.lowerContent).join('\\n');\r\n\r\n const items: StackWiringItem[] = [\r\n item(\r\n 'package-installed',\r\n 'Supabase package installed',\r\n deps.some((dep) => dep === '@supabase/supabase-js' || dep === '@supabase/ssr' || dep.startsWith('@supabase/')),\r\n packageEvidence(deps),\r\n 'Install the correct Supabase package for this app framework.'\r\n ),\r\n item(\r\n 'env-names-documented',\r\n 'Supabase env names documented',\r\n hasSupabaseUrl(contentBlob) && hasSupabaseAnonKey(contentBlob),\r\n envEvidence(contentBlob),\r\n 'Document NEXT_PUBLIC_SUPABASE_URL/VITE_SUPABASE_URL and the matching anon key in an env example or config docs.'\r\n ),\r\n item(\r\n 'client-file-exists',\r\n 'Supabase client file exists',\r\n hasSupabaseClient(files, pathBlob),\r\n clientEvidence(files, pathBlob),\r\n 'Create a Supabase client helper that follows the existing app structure.'\r\n ),\r\n item(\r\n 'database-query-usage',\r\n 'Database query usage found',\r\n /\\.from\\s*\\(\\s*['\"][a-z0-9_]+['\"]\\s*\\)/i.test(contentBlob),\r\n queryEvidence(files),\r\n 'Use the Supabase client from server-safe code paths for real database reads or writes.'\r\n ),\r\n item(\r\n 'schema-or-migrations',\r\n 'Schema or migration file found',\r\n hasSchemaOrMigration(files, pathBlob),\r\n schemaEvidence(files, pathBlob),\r\n 'Add a checked-in schema or migration path so database structure is reproducible.'\r\n ),\r\n item(\r\n 'rls-policy-evidence',\r\n 'Supabase RLS policy evidence found',\r\n hasRlsEvidence(files, pathBlob),\r\n rlsEvidence(files, pathBlob),\r\n 'Add or document Supabase RLS policies for user-owned tables before launch.'\r\n ),\r\n item(\r\n 'generated-types',\r\n 'Generated database types found',\r\n hasGeneratedTypes(files, pathBlob),\r\n generatedTypeEvidence(files, pathBlob),\r\n 'Generate and commit Supabase database types for safer app code.'\r\n ),\r\n serviceRoleSafetyItem(files)\r\n ];\r\n\r\n const passedCount = items.filter((entry) => entry.status === 'passed').length;\r\n const totalCount = items.length;\r\n const readinessPercent = Math.round((passedCount / Math.max(totalCount, 1)) * 100);\r\n\r\n return {\r\n key: 'supabase-database',\r\n provider: 'supabase',\r\n providerLabel: 'Supabase',\r\n area: 'database',\r\n areaLabel: 'Database',\r\n promptSubject: 'Supabase database',\r\n items,\r\n passedCount,\r\n totalCount,\r\n readinessPercent\r\n };\r\n}\r\n\r\nexport function buildSupabaseDatabaseWiringPrompt(wiring: SupabaseDatabaseWiringSummary): string {\r\n const passed = wiring.items.filter((entry) => entry.status === 'passed');\r\n const missing = wiring.items.filter((entry) => entry.status === 'missing');\r\n const passedLines = passed.length > 0\r\n ? passed.map((entry) => `- ${entry.label}${formatEvidence(entry.evidence)}`).join('\\n')\r\n : '- No Supabase wiring checks passed yet.';\r\n const missingLines = missing.length > 0\r\n ? missing.map((entry) => `- ${entry.label}: ${entry.promptHint}`).join('\\n')\r\n : '- No missing Supabase database wiring checks were found by VibeRaven.';\r\n\r\n return [\r\n 'Wire Supabase database for this app safely.',\r\n '',\r\n `Current Supabase database wiring readiness: ${wiring.passedCount}/${wiring.totalCount} checks passed (${wiring.readinessPercent}%).`,\r\n '',\r\n 'Repo evidence already found:',\r\n passedLines,\r\n '',\r\n 'Missing Supabase database wiring checks:',\r\n missingLines,\r\n '',\r\n 'First inspect the existing package.json files, env examples, Supabase client helpers, database access files, and supabase/ or migrations/ directories. Identify the current framework and data access pattern before editing.',\r\n '',\r\n 'Implement:',\r\n '1. Close only the missing Supabase database wiring checks listed above.',\r\n '2. Follow the existing file structure and naming patterns.',\r\n '3. Keep database setup reproducible through checked-in schema, migrations, or documented generation commands.',\r\n '4. Keep service-role keys out of frontend and client-executed files.',\r\n '',\r\n 'Constraints:',\r\n '- Do not rewrite unrelated auth, payments, UI, billing, or deployment code.',\r\n '- Do not claim Supabase dashboard setup is complete from repo evidence alone.',\r\n '- Do not expose SUPABASE_SERVICE_ROLE_KEY to browser code, Vite public env, or NEXT_PUBLIC env variables.',\r\n '',\r\n 'Verification:',\r\n '- Run the relevant TypeScript/build/test command for this repo.',\r\n '- Confirm VibeRaven can rescan and move the missing Supabase wiring checks to passed where repo evidence exists.',\r\n '- Summarize what changed and what still requires manual Supabase dashboard verification.'\r\n ].join('\\n');\r\n}\r\n\r\nexport function buildSupabaseDatabaseWiringContext(wiring: SupabaseDatabaseWiringSummary): string {\r\n const lines = [\r\n '## SUPABASE DATABASE WIRING',\r\n `${wiring.passedCount}/${wiring.totalCount} checks passed (${wiring.readinessPercent}%).`\r\n ];\r\n\r\n for (const entry of wiring.items) {\r\n const evidence = entry.evidence.length > 0 ? ` (${entry.evidence.slice(0, 3).join('; ')})` : '';\r\n lines.push(`${entry.status}: ${entry.label}${evidence}`);\r\n }\r\n\r\n return lines.join('\\n');\r\n}\r\n\r\nfunction visibleFiles(scan: ScanResult): ScannableFile[] {\r\n return scan.files\r\n .filter((file) => !file.isSecret && typeof file.content === 'string')\r\n .map((file) => ({\r\n path: file.path.replace(/\\\\/g, '/'),\r\n normalizedPath: file.path.replace(/\\\\/g, '/').toLowerCase(),\r\n content: file.content as string,\r\n lowerContent: (file.content as string).toLowerCase()\r\n }));\r\n}\r\n\r\nfunction item(\r\n id: string,\r\n label: string,\r\n passed: boolean,\r\n evidence: string[],\r\n promptHint: string\r\n): StackWiringItem {\r\n return {\r\n id,\r\n label,\r\n status: passed ? 'passed' : 'missing',\r\n evidence,\r\n promptHint\r\n };\r\n}\r\n\r\nfunction packageEvidence(deps: string[]): string[] {\r\n return deps.filter((dep) => dep === '@supabase/supabase-js' || dep === '@supabase/ssr' || dep.startsWith('@supabase/'))\r\n .map((dep) => `package: ${dep}`);\r\n}\r\n\r\nfunction hasSupabaseUrl(contentBlob: string): boolean {\r\n return /\\b(vite_|next_public_)?supabase_url\\b/i.test(contentBlob);\r\n}\r\n\r\nfunction hasSupabaseAnonKey(contentBlob: string): boolean {\r\n return /\\b(vite_|next_public_)?supabase_anon_key\\b/i.test(contentBlob);\r\n}\r\n\r\nfunction envEvidence(contentBlob: string): string[] {\r\n const evidence: string[] = [];\r\n if (hasSupabaseUrl(contentBlob)) {\r\n evidence.push('env: SUPABASE_URL');\r\n }\r\n if (hasSupabaseAnonKey(contentBlob)) {\r\n evidence.push('env: SUPABASE_ANON_KEY');\r\n }\r\n return evidence;\r\n}\r\n\r\nfunction hasSupabaseClient(files: ScannableFile[], pathBlob: string): boolean {\r\n return /(^|\\n|\\/)(lib|utils|src\\/lib|src\\/utils)\\/supabase\\.[jt]s\\b/i.test(pathBlob) ||\r\n files.some((file) => /createclient\\s*\\(/i.test(file.content) && /@supabase\\/(supabase-js|ssr)/i.test(file.content));\r\n}\r\n\r\nfunction clientEvidence(files: ScannableFile[], pathBlob: string): string[] {\r\n const evidence: string[] = [];\r\n const pathMatch = pathBlob.split(/\\r?\\n/).find((path) => /(^|\\/)(lib|utils|src\\/lib|src\\/utils)\\/supabase\\.[jt]s\\b/i.test(path));\r\n if (pathMatch) {\r\n evidence.push(`file: ${pathMatch}`);\r\n }\r\n const importFile = files.find((file) => /createclient\\s*\\(/i.test(file.content) && /@supabase\\/(supabase-js|ssr)/i.test(file.content));\r\n if (importFile && !evidence.includes(`file: ${importFile.path}`)) {\r\n evidence.push(`file: ${importFile.path}`);\r\n }\r\n return evidence;\r\n}\r\n\r\nfunction queryEvidence(files: ScannableFile[]): string[] {\r\n return files\r\n .filter((file) => /\\.from\\s*\\(\\s*['\"][a-z0-9_]+['\"]\\s*\\)/i.test(file.content))\r\n .slice(0, 4)\r\n .map((file) => `query: ${file.path}`);\r\n}\r\n\r\nfunction hasSchemaOrMigration(files: ScannableFile[], pathBlob: string): boolean {\r\n return /(^|\\n|\\/)supabase\\/migrations\\/[^/\\n]+\\.sql\\b/i.test(pathBlob) ||\r\n /(^|\\n|\\/)(migrations?|schema)\\/[^/\\n]+\\.(sql|ts|js)\\b/i.test(pathBlob) ||\r\n files.some((file) => /create\\s+table|alter\\s+table/i.test(file.content));\r\n}\r\n\r\nfunction schemaEvidence(files: ScannableFile[], pathBlob: string): string[] {\r\n const path = pathBlob.split(/\\r?\\n/).find((entry) =>\r\n /(^|\\/)supabase\\/migrations\\/[^/]+\\.sql\\b/i.test(entry) ||\r\n /(^|\\/)(migrations?|schema)\\/[^/]+\\.(sql|ts|js)\\b/i.test(entry)\r\n );\r\n if (path) {\r\n return [`schema: ${path}`];\r\n }\r\n const file = files.find((entry) => /create\\s+table|alter\\s+table/i.test(entry.content));\r\n return file ? [`schema: ${file.path}`] : [];\r\n}\r\n\r\nfunction hasRlsEvidence(files: ScannableFile[], pathBlob: string): boolean {\r\n return /\\/policies\\/|_rls\\.sql|\\brls\\b/i.test(pathBlob) ||\r\n files.some((file) => /enable\\s+row\\s+level\\s+security|create\\s+policy|alter\\s+table[\\s\\S]{0,200}enable\\s+row\\s+level/i.test(file.content));\r\n}\r\n\r\nfunction rlsEvidence(files: ScannableFile[], pathBlob: string): string[] {\r\n const path = pathBlob.split(/\\r?\\n/).find((entry) => /\\/policies\\/|_rls\\.sql|\\brls\\b/i.test(entry));\r\n if (path) {\r\n return [`rls: ${path}`];\r\n }\r\n const file = files.find((entry) => /enable\\s+row\\s+level\\s+security|create\\s+policy|alter\\s+table[\\s\\S]{0,200}enable\\s+row\\s+level/i.test(entry.content));\r\n return file ? [`rls: ${file.path}`] : [];\r\n}\r\n\r\nfunction hasGeneratedTypes(files: ScannableFile[], pathBlob: string): boolean {\r\n return /database\\.types\\.[jt]s\\b|supabase.*types\\.[jt]s\\b|types\\/database\\.[jt]s\\b/i.test(pathBlob) ||\r\n files.some((file) => /export\\s+type\\s+database\\b|export\\s+interface\\s+database\\b/i.test(file.content));\r\n}\r\n\r\nfunction generatedTypeEvidence(files: ScannableFile[], pathBlob: string): string[] {\r\n const path = pathBlob.split(/\\r?\\n/).find((entry) =>\r\n /database\\.types\\.[jt]s\\b|supabase.*types\\.[jt]s\\b|types\\/database\\.[jt]s\\b/i.test(entry)\r\n );\r\n if (path) {\r\n return [`types: ${path}`];\r\n }\r\n const file = files.find((entry) => /export\\s+type\\s+database\\b|export\\s+interface\\s+database\\b/i.test(entry.content));\r\n return file ? [`types: ${file.path}`] : [];\r\n}\r\n\r\nfunction serviceRoleSafetyItem(files: ScannableFile[]): StackWiringItem {\r\n const exposed = files.filter((file) =>\r\n isClientExecutedPath(file.normalizedPath) &&\r\n /\\bsupabase_service_role_key\\b|next_public_supabase_service_role|vite_supabase_service_role/i.test(file.content)\r\n );\r\n return {\r\n id: 'service-role-not-exposed',\r\n label: 'Service role key not exposed to frontend',\r\n status: exposed.length > 0 ? 'missing' : 'passed',\r\n evidence: exposed.slice(0, 4).map((file) => `unsafe reference: ${file.path}`),\r\n promptHint: 'Move service-role usage to server-only code and use public anon keys in frontend clients.'\r\n };\r\n}\r\n\r\nfunction isClientExecutedPath(path: string): boolean {\r\n return /\\.(tsx|jsx)$/.test(path) ||\r\n /(^|\\/)(components|pages|app|client|frontend|web)\\//.test(path) ||\r\n /\\.client\\.[jt]sx?$/.test(path);\r\n}\r\n\r\nfunction formatEvidence(evidence: string[]): string {\r\n return evidence.length > 0 ? ` (${evidence.slice(0, 3).join('; ')})` : '';\r\n}\r\n", "import { analyzeSupabaseDatabaseWiring } from './supabaseWiring';\r\nimport type {\r\n ScanResult,\r\n ScannedFile,\r\n StackWiringItem,\r\n StackWiringKey,\r\n StackWiringProviderSummary,\r\n StackWiringSummary\r\n} from './types';\r\n\r\ntype VisibleFile = {\r\n path: string;\r\n normalizedPath: string;\r\n content: string;\r\n lowerContent: string;\r\n};\r\n\r\ntype StackContext = {\r\n scan: ScanResult;\r\n files: VisibleFile[];\r\n deps: string[];\r\n pathBlob: string;\r\n contentBlob: string;\r\n};\r\n\r\nexport function analyzeStackWiring(scan: ScanResult): StackWiringSummary {\r\n const ctx = buildContext(scan);\r\n const supabaseDatabase = analyzeSupabaseDatabaseWiring(scan);\r\n const items: StackWiringProviderSummary[] = [\r\n analyzeFigmaAppFlow(ctx),\r\n analyzeStorybookAppFlow(ctx),\r\n analyzeProductSpecAppFlow(ctx),\r\n analyzeRouteMapAppFlow(ctx),\r\n analyzeReactFrontend(ctx),\r\n analyzeVueFrontend(ctx),\r\n analyzeSvelteFrontend(ctx),\r\n analyzeAngularFrontend(ctx),\r\n analyzeNodeBackend(ctx),\r\n analyzePythonBackend(ctx),\r\n analyzeRailsBackend(ctx),\r\n analyzeGoBackend(ctx),\r\n analyzeRateLimitSecurity(ctx),\r\n analyzeBotProtectionSecurity(ctx),\r\n analyzeSecretsHygiene(ctx),\r\n analyzeClerkAuth(ctx),\r\n analyzeAuthJsAuth(ctx),\r\n analyzeSupabaseAuth(ctx),\r\n supabaseDatabase,\r\n analyzeNeonDatabase(ctx),\r\n analyzeTursoDatabase(ctx),\r\n analyzeMongoDatabase(ctx),\r\n analyzePlanetScaleDatabase(ctx),\n analyzeStripePayments(ctx),\n analyzePaddlePayments(ctx),\n analyzePolarPayments(ctx),\n analyzeVercelDeployment(ctx),\n analyzeNetlifyDeployment(ctx),\r\n analyzeAwsDeployment(ctx),\r\n analyzeSupabaseLanding(ctx),\r\n analyzePostHogMonitoring(ctx),\r\n analyzeSentryMonitoring(ctx),\r\n analyzeLogRocketMonitoring(ctx),\r\n analyzeVitestTesting(ctx),\r\n analyzePlaywrightTesting(ctx),\r\n analyzeSentryErrorHandling(ctx),\r\n analyzePostHogErrorHandling(ctx)\r\n ];\r\n const byKey = items.reduce<Partial<Record<StackWiringKey, StackWiringProviderSummary>>>((acc, summary) => {\r\n acc[summary.key] = summary;\r\n return acc;\r\n }, {});\r\n\r\n return {\r\n items,\r\n byKey,\r\n supabaseDatabase\r\n };\r\n}\r\n\r\nexport function buildStackWiringPrompt(summary: StackWiringProviderSummary): string {\r\n const passed = summary.items.filter((entry) => entry.status === 'passed');\r\n const missing = summary.items.filter((entry) => entry.status === 'missing');\r\n const manual = summary.items.filter((entry) => entry.status === 'manual');\r\n const passedLines = passed.length > 0\r\n ? passed.map((entry) => `- ${entry.label}${formatEvidence(entry.evidence)}`).join('\\n')\r\n : `- No ${summary.promptSubject} checks passed yet.`;\r\n const missingLines = missing.length > 0\r\n ? missing.map((entry) => `- ${entry.label}: ${entry.promptHint}`).join('\\n')\r\n : `- No missing ${summary.promptSubject} checks were found by VibeRaven.`;\r\n const manualLines = manual.length > 0\r\n ? manual.map((entry) => `- ${entry.label}: ${entry.promptHint}`).join('\\n')\r\n : '- No manual dashboard checks were listed.';\r\n\r\n return [\r\n `Wire ${summary.promptSubject} for this app safely.`,\r\n '',\r\n `Current ${summary.promptSubject} readiness: ${summary.passedCount}/${summary.totalCount} repo checks passed (${summary.readinessPercent}%).`,\r\n '',\r\n 'Repo evidence already found:',\r\n passedLines,\r\n '',\r\n `Missing ${summary.promptSubject} checks:`,\r\n missingLines,\r\n '',\r\n 'Manual checks that repo evidence cannot prove:',\r\n manualLines,\r\n '',\r\n 'First inspect the existing package.json files, env examples, framework routes, provider helpers, and server/client boundaries before editing.',\r\n '',\r\n 'Implement:',\r\n `1. Close only the missing ${summary.promptSubject} checks listed above.`,\r\n '2. Follow the existing file structure and naming patterns.',\r\n '3. Keep provider secrets in server-only code and documented env templates.',\r\n '4. Keep external dashboard work explicit instead of claiming it from repo evidence.',\r\n '',\r\n 'Constraints:',\r\n '- Do not rewrite unrelated auth, payments, UI, billing, deployment, or analytics code.',\r\n '- Do not expose secret keys to browser code, public env variables, or client-executed files.',\r\n '- Do not claim external provider dashboard setup is complete from repo evidence alone.',\r\n '',\r\n 'Verification:',\r\n '- Run the relevant TypeScript/build/test command for this repo.',\r\n '- Confirm VibeRaven can rescan and move the missing checks to passed where repo evidence exists.',\r\n '- Summarize what changed and what still requires manual provider dashboard verification.'\r\n ].join('\\n');\r\n}\r\n\r\nexport function buildStackWiringContext(summary: StackWiringSummary): string {\r\n const lines = ['## STACK READINESS'];\r\n for (const stack of summary.items) {\r\n lines.push(`${stack.key}: ${stack.passedCount}/${stack.totalCount} repo checks passed (${stack.readinessPercent}%).`);\r\n for (const entry of stack.items) {\r\n const evidence = entry.evidence.length > 0 ? ` (${entry.evidence.slice(0, 3).join('; ')})` : '';\r\n lines.push(`${stack.key} ${entry.status}: ${entry.label}${evidence}`);\r\n }\r\n }\r\n return lines.join('\\n');\r\n}\r\n\r\nfunction analyzeFigmaAppFlow(ctx: StackContext): StackWiringProviderSummary {\r\n return summarize({\r\n key: 'figma-app-flow',\r\n provider: 'figma',\r\n providerLabel: 'Figma',\r\n area: 'appFlow',\r\n areaLabel: 'App Flow / UX',\r\n promptSubject: 'Figma app flow',\r\n items: [\r\n item('flow-doc-found', 'Flow or design doc found', /figma|wireframe|user flow|journey|prototype|screen map/i.test(ctx.contentBlob + '\\n' + ctx.pathBlob), fileEvidence(ctx, /figma|wireframe|user flow|journey|prototype|screen map/i), 'Add or link a simple screen flow, user journey, or Figma handoff note.'),\r\n item('onboarding-states-found', 'Onboarding and empty states documented', /onboarding|empty state|first run|activation|welcome/i.test(ctx.contentBlob + '\\n' + ctx.pathBlob), fileEvidence(ctx, /onboarding|empty state|first run|activation|welcome/i), 'Document the first-run, empty, loading, and error states for the main user journey.'),\r\n item('primary-cta-found', 'Primary user action is visible', /primary cta|call to action|cta|start|continue|create|connect/i.test(ctx.contentBlob), fileEvidence(ctx, /primary cta|call to action|cta|start|continue|create|connect/i), 'Make the main action obvious on the key product screens.'),\r\n manualItem('figma-source-checked', 'Current Figma or flow source checked', 'Confirm the latest Figma/design source still matches the implemented product flow.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzeStorybookAppFlow(ctx: StackContext): StackWiringProviderSummary {\r\n return summarize({\r\n key: 'storybook-app-flow',\r\n provider: 'storybook',\r\n providerLabel: 'Storybook',\r\n area: 'appFlow',\r\n areaLabel: 'App Flow / UX',\r\n promptSubject: 'Storybook app flow',\r\n items: [\r\n item('storybook-package-found', 'Storybook package installed', hasPackage(ctx, [/^storybook$/, /^@storybook\\//]) || /\\.storybook\\/|\\.stories\\.[jt]sx?\\b/i.test(ctx.pathBlob), packageEvidence(ctx, [/^storybook$/, /^@storybook\\//]).concat(pathEvidence(ctx, /\\.storybook\\/|\\.stories\\.[jt]sx?\\b/i)), 'Install or confirm Storybook for visible component state coverage.'),\r\n item('stories-found', 'Component stories found', /\\.stories\\.[jt]sx?\\b|\\.mdx\\b/i.test(ctx.pathBlob), pathEvidence(ctx, /\\.stories\\.[jt]sx?\\b|\\.mdx\\b/i), 'Add stories for the primary product components.'),\r\n item('state-variants-found', 'Loading, empty, or error variants found', /loading|empty|error|disabled|success|variant/i.test(ctx.contentBlob), fileEvidence(ctx, /loading|empty|error|disabled|success|variant/i), 'Cover loading, empty, error, disabled, and success variants in stories.'),\r\n manualItem('storybook-reviewed', 'Current Storybook states reviewed', 'Open Storybook and confirm the primary user journey states still match the product.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzeProductSpecAppFlow(ctx: StackContext): StackWiringProviderSummary {\r\n return summarize({\r\n key: 'product-spec-app-flow',\r\n provider: 'product-spec',\r\n providerLabel: 'Product Spec',\r\n area: 'appFlow',\r\n areaLabel: 'App Flow / UX',\r\n promptSubject: 'product spec app flow',\r\n items: [\r\n item('spec-doc-found', 'Product spec or PRD found', /prd|product requirements|requirements|product spec|specification/i.test(ctx.contentBlob + '\\n' + ctx.pathBlob), fileEvidence(ctx, /prd|product requirements|requirements|product spec|specification/i).concat(pathEvidence(ctx, /prd|requirements|spec/i)), 'Add a short product spec or PRD for the main workflow.'),\r\n item('acceptance-criteria-found', 'Acceptance criteria or user stories found', /acceptance criteria|user stor(y|ies)|jobs to be done|given\\s+.*when\\s+.*then/i.test(ctx.contentBlob), fileEvidence(ctx, /acceptance criteria|user stor(y|ies)|jobs to be done|given\\s+.*when\\s+.*then/i), 'Document acceptance criteria or user stories for the main flow.'),\r\n item('success-metric-found', 'Success metric or activation goal found', /success metric|activation|north star|conversion|retention|time to value/i.test(ctx.contentBlob), fileEvidence(ctx, /success metric|activation|north star|conversion|retention|time to value/i), 'Define the activation or success metric for this workflow.'),\r\n manualItem('latest-product-intent-checked', 'Latest product intent checked', 'Confirm the spec still matches the current product direction and user promise.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzeRouteMapAppFlow(ctx: StackContext): StackWiringProviderSummary {\r\n return summarize({\r\n key: 'route-map-app-flow',\r\n provider: 'route-map',\r\n providerLabel: 'Route Map',\r\n area: 'appFlow',\r\n areaLabel: 'App Flow / UX',\r\n promptSubject: 'route map app flow',\r\n items: [\r\n item('routes-found', 'App routes found', /(^|\\n|\\/)(app|pages|routes)\\//i.test(ctx.pathBlob) || /router|route map|sitemap/i.test(ctx.contentBlob), pathEvidence(ctx, /(^|\\/)(app|pages|routes)\\//i).concat(fileEvidence(ctx, /router|route map|sitemap/i)), 'Map the key routes or screens in the repo.'),\r\n item('navigation-documented', 'Navigation path documented', /navigation|nav|breadcrumb|route map|screen map|journey/i.test(ctx.contentBlob), fileEvidence(ctx, /navigation|nav|breadcrumb|route map|screen map|journey/i), 'Document how users move through the primary screens.'),\r\n item('protected-or-edge-routes-found', 'Protected or edge routes noted', /protected|auth required|404|not-found|error route|redirect/i.test(ctx.contentBlob + '\\n' + ctx.pathBlob), fileEvidence(ctx, /protected|auth required|404|not-found|error route|redirect/i), 'Mark protected, redirect, 404, and error routes explicitly.'),\r\n manualItem('core-journey-clicked', 'Core journey clicked manually', 'Click through the core route path in the running app and verify the map is current.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzeReactFrontend(ctx: StackContext): StackWiringProviderSummary {\r\n return summarize({\r\n key: 'react-frontend',\r\n provider: 'react',\r\n providerLabel: 'React',\r\n area: 'frontend',\r\n areaLabel: 'Frontend',\r\n promptSubject: 'React frontend',\r\n items: [\r\n item('package-installed', 'React package installed', hasPackage(ctx, [/^react$/, /^next$/, /^vite$/]) || Boolean(ctx.scan.stackSignals.hasNextJs || ctx.scan.stackSignals.hasVite), packageEvidence(ctx, [/^react$/, /^next$/, /^vite$/]), 'Install or confirm the React framework package used by this app.'),\r\n item('component-structure-found', 'Component structure found', /(^|\\n|\\/)(src\\/)?(components|app|pages)\\//i.test(ctx.pathBlob), pathEvidence(ctx, /(^|\\/)(src\\/)?(components|app|pages)\\//i), 'Keep UI components in a predictable app/pages/components structure.'),\r\n item('loading-state-found', 'Loading state found', Boolean(ctx.scan.stackSignals.hasLoadingStates) || /loading\\.tsx|skeleton|spinner|aria-busy|isloading/i.test(ctx.contentBlob + '\\n' + ctx.pathBlob), fileEvidence(ctx, /loading\\.tsx|skeleton|spinner|aria-busy|isloading/i), 'Add loading states for async product views.'),\r\n item('error-state-found', 'Error boundary or empty state found', Boolean(ctx.scan.stackSignals.hasErrorBoundary) || /errorboundary|global-error|empty state|not-found\\.tsx/i.test(ctx.contentBlob + '\\n' + ctx.pathBlob), fileEvidence(ctx, /errorboundary|global-error|empty state|not-found\\.tsx/i), 'Add error and empty states for the primary product workflow.'),\r\n manualItem('responsive-ui-checked', 'Responsive UI checked manually', 'Open the main screens at mobile and desktop widths and confirm there is no overflow or overlapping text.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzeVueFrontend(ctx: StackContext): StackWiringProviderSummary {\r\n return summarize({\r\n key: 'vue-frontend',\r\n provider: 'vue',\r\n providerLabel: 'Vue',\r\n area: 'frontend',\r\n areaLabel: 'Frontend',\r\n promptSubject: 'Vue frontend',\r\n items: [\r\n item('package-installed', 'Vue package installed', hasPackage(ctx, [/^vue$/, /^nuxt$/, /^@vitejs\\/plugin-vue$/]), packageEvidence(ctx, [/^vue$/, /^nuxt$/, /^@vitejs\\/plugin-vue$/]), 'Install or confirm Vue, Nuxt, or the Vue build plugin used by this app.'),\r\n item('component-structure-found', 'Vue component structure found', /\\.vue\\b|(^|\\n|\\/)(src\\/)?(components|pages|layouts)\\//i.test(ctx.pathBlob), pathEvidence(ctx, /\\.vue\\b|(^|\\/)(src\\/)?(components|pages|layouts)\\//i), 'Keep Vue components, pages, and layouts in predictable folders.'),\r\n item('routing-or-layout-found', 'Vue routing or layout found', /vue-router|routerview|router-view|<router-view|(^|\\n|\\/)pages\\//i.test(ctx.contentBlob + '\\n' + ctx.pathBlob), fileEvidence(ctx, /vue-router|routerview|router-view|<router-view/i).concat(pathEvidence(ctx, /(^|\\/)pages\\//i)), 'Add or confirm Vue Router, Nuxt pages, or layout routing for the main product screens.'),\r\n item('loading-or-error-state-found', 'Loading or error state found', /loading|suspense|error|empty state|isloading/i.test(ctx.contentBlob), fileEvidence(ctx, /loading|suspense|error|empty state|isloading/i), 'Add loading, empty, and error states for async Vue screens.'),\r\n manualItem('responsive-ui-checked', 'Responsive UI checked manually', 'Open the main Vue screens at mobile and desktop widths and confirm there is no overflow or overlapping text.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzeSvelteFrontend(ctx: StackContext): StackWiringProviderSummary {\r\n return summarize({\r\n key: 'svelte-frontend',\r\n provider: 'svelte',\r\n providerLabel: 'Svelte',\r\n area: 'frontend',\r\n areaLabel: 'Frontend',\r\n promptSubject: 'Svelte frontend',\r\n items: [\r\n item('package-installed', 'Svelte package installed', hasPackage(ctx, [/^svelte$/, /^@sveltejs\\/kit$/]), packageEvidence(ctx, [/^svelte$/, /^@sveltejs\\/kit$/]), 'Install or confirm Svelte or SvelteKit for this app.'),\r\n item('component-structure-found', 'Svelte component or route structure found', /\\.svelte\\b|(^|\\n|\\/)src\\/routes\\//i.test(ctx.pathBlob), pathEvidence(ctx, /\\.svelte\\b|(^|\\/)src\\/routes\\//i), 'Keep Svelte components and routes in predictable folders.'),\r\n item('load-or-form-found', 'Svelte load or form handling found', /\\bload\\s*=|export\\s+(async\\s+)?function\\s+load|actions\\s*=|use:enhance/i.test(ctx.contentBlob), fileEvidence(ctx, /\\bload\\s*=|export\\s+(async\\s+)?function\\s+load|actions\\s*=|use:enhance/i), 'Use SvelteKit load functions or actions for route data and form flows.'),\r\n item('loading-or-error-state-found', 'Loading or error state found', /loading|error|empty state|\\+error\\.svelte/i.test(ctx.contentBlob + '\\n' + ctx.pathBlob), fileEvidence(ctx, /loading|error|empty state|\\+error\\.svelte/i), 'Add loading, empty, and error states for async Svelte screens.'),\r\n manualItem('responsive-ui-checked', 'Responsive UI checked manually', 'Open the main Svelte screens at mobile and desktop widths and confirm there is no overflow or overlapping text.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzeAngularFrontend(ctx: StackContext): StackWiringProviderSummary {\r\n return summarize({\r\n key: 'angular-frontend',\r\n provider: 'angular',\r\n providerLabel: 'Angular',\r\n area: 'frontend',\r\n areaLabel: 'Frontend',\r\n promptSubject: 'Angular frontend',\r\n items: [\r\n item('package-installed', 'Angular package installed', hasPackage(ctx, [/^@angular\\/core$/, /^@angular\\/router$/, /^@angular\\/cli$/]), packageEvidence(ctx, [/^@angular\\/core$/, /^@angular\\/router$/, /^@angular\\/cli$/]), 'Install or confirm Angular framework packages for this app.'),\r\n item('component-structure-found', 'Angular component structure found', /\\.component\\.ts\\b|angular\\.json|(^|\\n|\\/)src\\/app\\//i.test(ctx.pathBlob), pathEvidence(ctx, /\\.component\\.ts\\b|angular\\.json|(^|\\/)src\\/app\\//i), 'Keep Angular components and app modules or standalone routes in predictable folders.'),\r\n item('routing-found', 'Angular routing found', /routermodule|providerouter|router-outlet|routes\\s*:/i.test(ctx.contentBlob), fileEvidence(ctx, /routermodule|providerouter|router-outlet|routes\\s*:/i), 'Add or confirm Angular Router for the primary product screens.'),\r\n item('loading-or-error-state-found', 'Loading or error state found', /loading|isloading|error|empty state|catcherror/i.test(ctx.contentBlob), fileEvidence(ctx, /loading|isloading|error|empty state|catcherror/i), 'Add loading, empty, and error states for async Angular screens.'),\r\n manualItem('responsive-ui-checked', 'Responsive UI checked manually', 'Open the main Angular screens at mobile and desktop widths and confirm there is no overflow or overlapping text.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzeNodeBackend(ctx: StackContext): StackWiringProviderSummary {\r\n return summarize({\r\n key: 'node-backend',\r\n provider: 'node',\r\n providerLabel: 'Node.js',\r\n area: 'backend',\r\n areaLabel: 'Backend / API',\r\n promptSubject: 'Node.js backend',\r\n items: [\r\n item('server-runtime-found', 'Server runtime or API framework found', hasPackage(ctx, [/^express$/, /^fastify$/, /^hono$/, /^next$/, /^@nestjs\\//]) || /api\\/|route\\.[jt]s|server\\.[jt]s/i.test(ctx.pathBlob), packageEvidence(ctx, [/^express$/, /^fastify$/, /^hono$/, /^next$/, /^@nestjs\\//]).concat(pathEvidence(ctx, /api\\/|route\\.[jt]s|server\\.[jt]s/i)), 'Add a clear server/API runtime or route structure.'),\r\n item('api-routes-found', 'API routes found', /api\\/|route\\.[jt]s|routes?\\//i.test(ctx.pathBlob), pathEvidence(ctx, /api\\/|route\\.[jt]s|routes?\\//i), 'Create server routes for backend operations instead of pushing secrets into frontend code.'),\r\n item('request-validation-found', 'Request validation found', hasPackage(ctx, [/^zod$/, /^joi$/, /^yup$/, /^valibot$/]) || /z\\.object|safeparse|request validation|validate\\s*\\(/i.test(ctx.contentBlob), packageEvidence(ctx, [/^zod$/, /^joi$/, /^yup$/, /^valibot$/]).concat(fileEvidence(ctx, /z\\.object|safeparse|request validation|validate\\s*\\(/i)), 'Validate request bodies and parameters before processing backend operations.'),\r\n item('backend-error-handling-found', 'Backend error handling found', /try\\s*{|catch\\s*\\(|next\\(error\\)|return\\s+new\\s+response\\([^)]*500|status\\s*:\\s*500/i.test(ctx.contentBlob), fileEvidence(ctx, /try\\s*{|catch\\s*\\(|next\\(error\\)|status\\s*:\\s*500/i), 'Add consistent backend error handling for API routes.'),\r\n manualItem('production-runtime-checked', 'Production runtime limits checked', 'Confirm serverless/runtime limits, body size, timeout, and region choices for production.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzePythonBackend(ctx: StackContext): StackWiringProviderSummary {\r\n return summarize({\r\n key: 'python-backend',\r\n provider: 'python',\r\n providerLabel: 'Python / FastAPI',\r\n area: 'backend',\r\n areaLabel: 'Backend / API',\r\n promptSubject: 'Python backend',\r\n items: [\r\n item('server-runtime-found', 'Python API framework found', hasPackage(ctx, [/^fastapi$/, /^flask$/, /^django$/, /^pydantic$/]) || /fastapi|flask|django|pydantic/i.test(ctx.contentBlob), packageEvidence(ctx, [/^fastapi$/, /^flask$/, /^django$/, /^pydantic$/]).concat(fileEvidence(ctx, /fastapi|flask|django|pydantic/i)), 'Add or confirm FastAPI, Flask, Django, or the Python API framework used by this app.'),\r\n item('api-entry-found', 'Python API entrypoint found', /(^|\\n|\\/)(api\\/)?(main|app)\\.py\\b|(^|\\n|\\/)manage\\.py\\b/i.test(ctx.pathBlob), pathEvidence(ctx, /(^|\\/)(api\\/)?(main|app)\\.py\\b|(^|\\/)manage\\.py\\b/i), 'Keep a clear Python API entrypoint for production routes.'),\r\n item('request-validation-found', 'Request validation found', /basemodel|pydantic|serializer|marshmallow|request validation/i.test(ctx.contentBlob), fileEvidence(ctx, /basemodel|pydantic|serializer|marshmallow|request validation/i), 'Validate request bodies and parameters before processing backend operations.'),\r\n item('backend-error-handling-found', 'Backend error handling found', /exception_handler|try\\s*:|except\\s+|raise\\s+http|abort\\(|handler404|handler500/i.test(ctx.contentBlob), fileEvidence(ctx, /exception_handler|try\\s*:|except\\s+|raise\\s+http|abort\\(|handler404|handler500/i), 'Add consistent backend error handling for Python routes.'),\r\n manualItem('production-runtime-checked', 'Production runtime limits checked', 'Confirm server/runtime limits, worker count, timeout, and region choices for production.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzeRailsBackend(ctx: StackContext): StackWiringProviderSummary {\r\n return summarize({\r\n key: 'rails-backend',\r\n provider: 'rails',\r\n providerLabel: 'Rails',\r\n area: 'backend',\r\n areaLabel: 'Backend / API',\r\n promptSubject: 'Rails backend',\r\n items: [\r\n item('rails-runtime-found', 'Rails runtime found', hasPackage(ctx, [/^rails$/]) || /gem ['\"]rails['\"]|rails\\.application|actioncontroller/i.test(ctx.contentBlob + '\\n' + ctx.pathBlob), packageEvidence(ctx, [/^rails$/]).concat(fileEvidence(ctx, /gem ['\"]rails['\"]|rails\\.application|actioncontroller/i)), 'Add or confirm Rails is the backend runtime for this app.'),\r\n item('controllers-or-routes-found', 'Controllers or routes found', /app\\/controllers\\/|config\\/routes\\.rb/i.test(ctx.pathBlob) || /resources\\s+:|namespace\\s+:|ActionController/i.test(ctx.contentBlob), pathEvidence(ctx, /app\\/controllers\\/|config\\/routes\\.rb/i).concat(fileEvidence(ctx, /resources\\s+:|namespace\\s+:|ActionController/i)), 'Keep Rails controllers and routes visible in the repo.'),\r\n item('request-validation-found', 'Validation or strong params found', /validates\\s+:|params\\.require|permit\\(|ActiveModel::Serializer|dry-validation/i.test(ctx.contentBlob), fileEvidence(ctx, /validates\\s+:|params\\.require|permit\\(|ActiveModel::Serializer|dry-validation/i), 'Validate request bodies and model inputs before processing backend operations.'),\r\n item('backend-error-handling-found', 'Backend error handling found', /rescue_from|rescue\\s+|render\\s+json:.*status:|head\\s+:/i.test(ctx.contentBlob), fileEvidence(ctx, /rescue_from|rescue\\s+|render\\s+json:.*status:|head\\s+:/i), 'Add consistent Rails error handling for API routes.'),\r\n manualItem('production-runtime-checked', 'Production runtime limits checked', 'Confirm Puma/workers, job queues, database pool, timeout, and region choices for production.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzeGoBackend(ctx: StackContext): StackWiringProviderSummary {\r\n return summarize({\r\n key: 'go-backend',\r\n provider: 'go',\r\n providerLabel: 'Go',\r\n area: 'backend',\r\n areaLabel: 'Backend / API',\r\n promptSubject: 'Go backend',\r\n items: [\r\n item('go-runtime-found', 'Go API runtime found', /(^|\\n|\\/)go\\.mod\\b|gin-gonic|go-chi|gofiber|net\\/http/i.test(ctx.contentBlob + '\\n' + ctx.pathBlob), fileEvidence(ctx, /gin-gonic|go-chi|gofiber|net\\/http/i).concat(pathEvidence(ctx, /(^|\\/)go\\.mod\\b/i)), 'Add or confirm Go modules and the HTTP framework used by this app.'),\r\n item('handlers-or-routes-found', 'Handlers or routes found', /\\.go\\b/i.test(ctx.pathBlob) && /\\b(GET|POST|PUT|DELETE)\\s*\\(|http\\.Handle|HandleFunc|router\\./i.test(ctx.contentBlob), fileEvidence(ctx, /\\b(GET|POST|PUT|DELETE)\\s*\\(|http\\.Handle|HandleFunc|router\\./i), 'Keep Go handlers and route registration visible in the repo.'),\r\n item('request-validation-found', 'Request validation found', /validator|binding:|bindjson|shouldbind|json\\.newdecoder|validate\\./i.test(ctx.contentBlob), fileEvidence(ctx, /validator|binding:|bindjson|shouldbind|json\\.newdecoder|validate\\./i), 'Validate request bodies and parameters before processing backend operations.'),\r\n item('backend-error-handling-found', 'Backend error handling found', /if\\s+err\\s*!=\\s*nil|http\\.Error|statusinternalservererror|c\\.json\\([^)]*500/i.test(ctx.contentBlob), fileEvidence(ctx, /if\\s+err\\s*!=\\s*nil|http\\.Error|statusinternalservererror|c\\.json\\([^)]*500/i), 'Add consistent Go error handling for API routes.'),\r\n manualItem('production-runtime-checked', 'Production runtime limits checked', 'Confirm binary build, health checks, timeout, concurrency, and region choices for production.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzeClerkAuth(ctx: StackContext): StackWiringProviderSummary {\r\n return summarize({\r\n key: 'clerk-auth',\r\n provider: 'clerk',\r\n providerLabel: 'Clerk',\r\n area: 'auth',\r\n areaLabel: 'Auth',\r\n promptSubject: 'Clerk auth',\r\n items: [\r\n item('package-installed', 'Clerk package installed', hasPackage(ctx, [/^@clerk\\//]), packageEvidence(ctx, [/^@clerk\\//]), 'Install the Clerk package that matches this app framework.'),\r\n item('env-names-documented', 'Clerk env names documented', hasAllContent(ctx, [/next_public_clerk_publishable_key/i, /clerk_secret_key/i]), envEvidence(ctx, [/next_public_clerk_publishable_key/i, /clerk_secret_key/i]), 'Document NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY and CLERK_SECRET_KEY in an env example or setup docs.'),\r\n item('route-protection-found', 'Auth middleware or route protection found', /(^|\\n|\\/)middleware\\.[jt]sx?\\b/i.test(ctx.pathBlob) || /clerkmiddleware|authmiddleware|createRouteMatcher/i.test(ctx.contentBlob), fileEvidence(ctx, /middleware\\.[jt]sx?$|clerkmiddleware|authmiddleware|createRouteMatcher/i), 'Add Clerk middleware or route guards around authenticated app routes.'),\r\n item('provider-mounted', 'Clerk provider mounted', /clerkprovider/i.test(ctx.contentBlob), fileEvidence(ctx, /clerkprovider/i), 'Mount ClerkProvider in the app root or framework-specific provider layer.'),\r\n item('sign-in-flow-found', 'Sign-in or sign-up flow found', /sign-?in|sign-?up/i.test(ctx.pathBlob) || /<\\s*sign(in|up)\\b|sign(in|up)button/i.test(ctx.contentBlob), fileEvidence(ctx, /sign-?in|sign-?up|<\\s*sign(in|up)\\b|sign(in|up)button/i), 'Add a visible sign-in/sign-up route or component for users.'),\r\n item('server-auth-usage-found', 'Server auth usage found', /\\bauth\\s*\\(|currentuser\\s*\\(|getauth\\s*\\(/i.test(ctx.contentBlob), fileEvidence(ctx, /\\bauth\\s*\\(|currentuser\\s*\\(|getauth\\s*\\(/i), 'Use Clerk server auth in protected data routes or server components.'),\r\n secretSafetyItem(ctx, 'secret-not-exposed', 'Clerk secret key not exposed to frontend', /clerk_secret_key|sk_live_/i, 'Move Clerk secret key usage to server-only files and keep frontend code on publishable keys.'),\r\n manualItem('production-dashboard-checked', 'Production Clerk app and domains checked', 'Confirm production domains, OAuth redirects, allowed origins, and social provider settings in Clerk Dashboard.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzeAuthJsAuth(ctx: StackContext): StackWiringProviderSummary {\r\n return summarize({\r\n key: 'authjs-auth',\r\n provider: 'authjs',\r\n providerLabel: 'Auth.js',\r\n area: 'auth',\r\n areaLabel: 'Auth',\r\n promptSubject: 'Auth.js auth',\r\n items: [\r\n item('package-installed', 'Auth.js package installed', hasPackage(ctx, [/^next-auth$/, /^@auth\\//]), packageEvidence(ctx, [/^next-auth$/, /^@auth\\//]), 'Install next-auth or the correct @auth package for this framework.'),\r\n item('env-names-documented', 'Auth secret env documented', /auth_secret|nextauth_secret/i.test(ctx.contentBlob), envEvidence(ctx, [/auth_secret/i, /nextauth_secret/i, /nextauth_url/i]), 'Document AUTH_SECRET or NEXTAUTH_SECRET in env examples or setup docs.'),\r\n item('auth-config-found', 'Auth config found', /(^|\\n|\\/)auth\\.[jt]s\\b|nextauth|NextAuth\\s*\\(/i.test(ctx.contentBlob + '\\n' + ctx.pathBlob), fileEvidence(ctx, /auth\\.[jt]s$|nextauth|NextAuth\\s*\\(/i), 'Add a central Auth.js config with providers and callbacks.'),\r\n item('route-handler-found', 'Auth route handler found', /api\\/auth|handlers\\s*:\\s*{|GET|POST/i.test(ctx.pathBlob + '\\n' + ctx.contentBlob), pathEvidence(ctx, /api\\/auth/i).concat(fileEvidence(ctx, /handlers\\s*:\\s*{|NextAuth\\s*\\(/i)), 'Expose the Auth.js route handler expected by this framework.'),\r\n item('session-usage-found', 'Session usage found', /\\bauth\\s*\\(|getserversession|usesession\\s*\\(/i.test(ctx.contentBlob), fileEvidence(ctx, /\\bauth\\s*\\(|getserversession|usesession\\s*\\(/i), 'Use server or client session checks around authenticated product routes.'),\r\n secretSafetyItem(ctx, 'secret-not-exposed', 'Auth secret not exposed to frontend', /auth_secret|nextauth_secret/i, 'Move Auth.js secrets to server-only env and never expose them through public env variables.'),\r\n manualItem('production-provider-checked', 'Production OAuth providers checked', 'Confirm OAuth app callback URLs, secrets, and production domain settings in each provider dashboard.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzeSupabaseAuth(ctx: StackContext): StackWiringProviderSummary {\r\n return summarize({\r\n key: 'supabase-auth',\r\n provider: 'supabase-auth',\r\n providerLabel: 'Supabase Auth',\r\n area: 'auth',\r\n areaLabel: 'Auth',\r\n promptSubject: 'Supabase Auth',\r\n items: [\r\n item('package-installed', 'Supabase auth package installed', hasPackage(ctx, [/@supabase\\//]), packageEvidence(ctx, [/@supabase\\//]), 'Install @supabase/supabase-js or @supabase/ssr for auth helpers.'),\r\n item('env-names-documented', 'Supabase auth env names documented', /supabase_url/i.test(ctx.contentBlob) && /supabase_anon_key/i.test(ctx.contentBlob), envEvidence(ctx, [/supabase_url/i, /supabase_anon_key/i]), 'Document SUPABASE_URL and SUPABASE_ANON_KEY style env names in examples or setup docs.'),\r\n item('auth-helper-found', 'Supabase auth helper found', /auth\\.getuser|auth\\.getsession|auth\\.signin|auth\\.signup|createServerClient|createBrowserClient/i.test(ctx.contentBlob), fileEvidence(ctx, /auth\\.getuser|auth\\.getsession|auth\\.signin|auth\\.signup|createServerClient|createBrowserClient/i), 'Use Supabase auth helpers for session reads and sign-in flows.'),\r\n item('protected-route-found', 'Protected route or server session check found', /auth\\.getuser|auth\\.getsession|middleware|protected/i.test(ctx.contentBlob + '\\n' + ctx.pathBlob), fileEvidence(ctx, /auth\\.getuser|auth\\.getsession|middleware|protected/i), 'Protect signed-in routes with a server session check or middleware.'),\r\n secretSafetyItem(ctx, 'service-role-not-exposed', 'Service role key not exposed to frontend', /supabase_service_role_key|next_public_supabase_service_role|vite_supabase_service_role/i, 'Keep service-role keys in server-only code and use anon keys in frontend clients.'),\r\n manualItem('production-auth-dashboard-checked', 'Production Supabase Auth settings checked', 'Confirm site URL, redirect URLs, email provider, OAuth providers, and auth policies in Supabase Dashboard.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzeStripePayments(ctx: StackContext): StackWiringProviderSummary {\r\n return summarize({\r\n key: 'stripe-payments',\r\n provider: 'stripe',\r\n providerLabel: 'Stripe',\r\n area: 'payments',\r\n areaLabel: 'Payments',\r\n promptSubject: 'Stripe payments',\r\n items: [\r\n item('package-installed', 'Stripe package installed', hasPackage(ctx, [/^stripe$/, /^@stripe\\//]), packageEvidence(ctx, [/^stripe$/, /^@stripe\\//]), 'Install Stripe server/client packages that match this app framework.'),\r\n item('env-names-documented', 'Stripe env names documented', hasAllContent(ctx, [/stripe_secret_key/i, /stripe_webhook_secret/i]), envEvidence(ctx, [/stripe_secret_key/i, /stripe_webhook_secret/i, /next_public_stripe_publishable_key/i]), 'Document STRIPE_SECRET_KEY, STRIPE_WEBHOOK_SECRET, and publishable key names in env examples or setup docs.'),\r\n item('checkout-session-found', 'Checkout session creation found', /checkout\\.sessions\\.create|redirecttocheckout/i.test(ctx.contentBlob), fileEvidence(ctx, /checkout\\.sessions\\.create|redirecttocheckout/i), 'Create a server-side Stripe Checkout session path for paid plans.'),\r\n item('webhook-route-found', 'Stripe webhook route found', /stripe.*webhook|webhook.*stripe/i.test(ctx.pathBlob), pathEvidence(ctx, /stripe.*webhook|webhook.*stripe/i), 'Add a Stripe webhook route for subscription and payment lifecycle events.'),\r\n item('webhook-signature-found', 'Webhook signature verification found', /webhooks\\.constructevent/i.test(ctx.contentBlob), fileEvidence(ctx, /webhooks\\.constructevent/i), 'Verify Stripe webhook signatures with STRIPE_WEBHOOK_SECRET before processing events.'),\r\n item('billing-management-found', 'Subscription or customer portal found', /billingportal\\.sessions\\.create|subscriptions\\.create|mode\\s*:\\s*['\"]subscription['\"]/i.test(ctx.contentBlob), fileEvidence(ctx, /billingportal\\.sessions\\.create|subscriptions\\.create|mode\\s*:\\s*['\"]subscription['\"]/i), 'Add subscription creation or customer portal handling for paid users.'),\r\n secretSafetyItem(ctx, 'secret-not-exposed', 'Stripe secret key not exposed to frontend', /stripe_secret_key|sk_live_|sk_test_/i, 'Move Stripe secret-key usage to server-only routes and use publishable keys in frontend code.'),\r\n manualItem('production-dashboard-checked', 'Production Stripe products and webhooks checked', 'Confirm live-mode products, prices, webhook endpoint URL, and event list in Stripe Dashboard.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzePaddlePayments(ctx: StackContext): StackWiringProviderSummary {\n return summarize({\n key: 'paddle-payments',\r\n provider: 'paddle',\r\n providerLabel: 'Paddle',\r\n area: 'payments',\r\n areaLabel: 'Payments',\r\n promptSubject: 'Paddle payments',\r\n items: [\r\n item('package-installed', 'Paddle package installed', hasPackage(ctx, [/@paddle\\//]), packageEvidence(ctx, [/@paddle\\//]), 'Install Paddle client/server SDK packages that match this app framework.'),\r\n item('env-names-documented', 'Paddle env names documented', /paddle_api_key|paddle_webhook_secret|next_public_paddle/i.test(ctx.contentBlob), envEvidence(ctx, [/paddle_api_key/i, /paddle_webhook_secret/i, /next_public_paddle_client_token/i]), 'Document Paddle API key, webhook secret, and public client token env names.'),\r\n item('checkout-found', 'Paddle checkout flow found', /paddle.*checkout|checkout.*paddle|paddle\\.checkout|openCheckout/i.test(ctx.contentBlob + '\\n' + ctx.pathBlob), fileEvidence(ctx, /paddle.*checkout|checkout.*paddle|paddle\\.checkout|openCheckout/i), 'Add a Paddle checkout flow for paid plans.'),\r\n item('webhook-route-found', 'Paddle webhook route found', /paddle.*webhook|webhook.*paddle/i.test(ctx.pathBlob), pathEvidence(ctx, /paddle.*webhook|webhook.*paddle/i), 'Add a Paddle webhook route for subscription lifecycle events.'),\r\n item('webhook-signature-found', 'Paddle webhook verification found', /verify.*paddle|paddle.*signature|webhook.*signature/i.test(ctx.contentBlob), fileEvidence(ctx, /verify.*paddle|paddle.*signature|webhook.*signature/i), 'Verify Paddle webhook signatures before processing events.'),\r\n secretSafetyItem(ctx, 'secret-not-exposed', 'Paddle secret not exposed to frontend', /paddle_api_key|paddle_webhook_secret/i, 'Move Paddle API keys and webhook secrets to server-only code.'),\r\n manualItem('production-dashboard-checked', 'Production Paddle products and webhooks checked', 'Confirm live products, prices, tax settings, webhook URL, and event list in Paddle Dashboard.')\r\n ]\r\n });\n}\n\nfunction analyzePolarPayments(ctx: StackContext): StackWiringProviderSummary {\n return summarize({\n key: 'polar-payments',\n provider: 'polar',\n providerLabel: 'Polar',\n area: 'payments',\n areaLabel: 'Payments',\n promptSubject: 'Polar payments',\n items: [\n item('api-client-found', 'Polar SDK or API client found', hasPackage(ctx, [/@polar-sh\\//]) || Boolean(ctx.scan.stackSignals.hasPolar) || /api\\.polar\\.sh|sandbox-api\\.polar\\.sh|polarbillingservice/i.test(ctx.contentBlob), packageEvidence(ctx, [/@polar-sh\\//]).concat(fileEvidence(ctx, /api\\.polar\\.sh|sandbox-api\\.polar\\.sh|polarbillingservice/i)), 'Add a Polar SDK or server-side API client for checkout and customer state.'),\n item('env-names-documented', 'Polar env names documented', /polar_access_token|polar_webhook_secret|polar_pro_product_id/i.test(ctx.contentBlob), envEvidence(ctx, [/polar_access_token/i, /polar_webhook_secret/i, /polar_pro_product_id/i, /polar_sandbox/i]), 'Document POLAR_ACCESS_TOKEN, POLAR_WEBHOOK_SECRET, and product ID env names in safe examples.'),\n item('checkout-found', 'Polar checkout flow found', /polar.*checkout|checkout.*polar|\\/checkouts\\b|createcheckoutsession/i.test(ctx.contentBlob + '\\n' + ctx.pathBlob), fileEvidence(ctx, /polar.*checkout|checkout.*polar|\\/checkouts\\b|createcheckoutsession/i), 'Add a server-side Polar checkout flow for paid plans.'),\n item('webhook-route-found', 'Polar webhook route found', /polar.*webhook|webhook.*polar/i.test(ctx.pathBlob + '\\n' + ctx.contentBlob), pathEvidence(ctx, /polar.*webhook|webhook.*polar/i).concat(fileEvidence(ctx, /polar.*webhook|webhook.*polar/i)), 'Add a Polar webhook route for subscription and customer lifecycle events.'),\n item('webhook-signature-found', 'Polar webhook verification found', /polar_webhook_secret|verify.*polar|polar.*signature|webhook.*signature/i.test(ctx.contentBlob), fileEvidence(ctx, /polar_webhook_secret|verify.*polar|polar.*signature|webhook.*signature/i), 'Verify Polar webhook signatures before processing billing events.'),\n item('customer-state-found', 'Polar customer or subscription state found', /external_customer_id|customer_portal|customer[_-]?state|polar_subscription_id|polar_customer_id/i.test(ctx.contentBlob), fileEvidence(ctx, /external_customer_id|customer_portal|customer[_-]?state|polar_subscription_id|polar_customer_id/i), 'Persist Polar customer/subscription state and expose a customer portal path for paid users.'),\n secretSafetyItem(ctx, 'secret-not-exposed', 'Polar secret not exposed to frontend', /polar_access_token|polar_webhook_secret/i, 'Move Polar access tokens and webhook secrets to server-only code.'),\n manualItem('production-dashboard-checked', 'Production Polar products and webhooks checked', 'Confirm products, prices, customer portal, webhook URL, and event list in Polar Dashboard.')\n ]\n });\n}\n\nfunction analyzeNeonDatabase(ctx: StackContext): StackWiringProviderSummary {\n return databaseSummary(ctx, {\r\n key: 'neon-database',\r\n provider: 'neon',\r\n providerLabel: 'Neon',\r\n promptSubject: 'Neon database',\r\n packagePatterns: [/@neondatabase\\//],\r\n envPatterns: [/neon_database_url/i, /database_url/i],\r\n usagePatterns: [/@neondatabase\\/serverless/i, /\\bneon\\s*\\(/i, /\\bsql`/i],\r\n manualLabel: 'Production Neon branch and pooling checked',\r\n manualHint: 'Confirm production branch, pooled connection string, backups, and region in Neon.'\r\n });\r\n}\r\n\r\nfunction analyzeTursoDatabase(ctx: StackContext): StackWiringProviderSummary {\r\n return databaseSummary(ctx, {\r\n key: 'turso-database',\r\n provider: 'turso',\r\n providerLabel: 'Turso',\r\n promptSubject: 'Turso database',\r\n packagePatterns: [/@libsql\\/client/],\r\n envPatterns: [/turso_database_url/i, /turso_auth_token/i],\r\n usagePatterns: [/@libsql\\/client/i, /createClient\\s*\\(/i],\r\n manualLabel: 'Production Turso database checked',\r\n manualHint: 'Confirm production database, auth token scope, replica/region, and backup strategy in Turso.'\r\n });\r\n}\r\n\r\nfunction analyzeMongoDatabase(ctx: StackContext): StackWiringProviderSummary {\r\n return databaseSummary(ctx, {\r\n key: 'mongodb-database',\r\n provider: 'mongodb',\r\n providerLabel: 'MongoDB',\r\n promptSubject: 'MongoDB database',\r\n packagePatterns: [/^mongodb$/, /^mongoose$/],\r\n envPatterns: [/mongodb_uri/i, /mongodb_url/i, /mongodb_atlas_uri/i],\r\n usagePatterns: [/new\\s+MongoClient|mongoose\\.connect|mongodb/i],\r\n manualLabel: 'Production MongoDB Atlas settings checked',\r\n manualHint: 'Confirm Atlas network access, database user permissions, backups, indexes, and production cluster sizing.'\r\n });\r\n}\r\n\r\nfunction analyzePlanetScaleDatabase(ctx: StackContext): StackWiringProviderSummary {\r\n return databaseSummary(ctx, {\r\n key: 'planetscale-database',\r\n provider: 'planetscale',\r\n providerLabel: 'PlanetScale',\r\n promptSubject: 'PlanetScale database',\r\n packagePatterns: [/@planetscale\\/database/],\r\n envPatterns: [/planetscale_database_url/i, /database_url/i],\r\n usagePatterns: [/@planetscale\\/database/i, /connect\\s*\\(/i],\r\n manualLabel: 'Production PlanetScale branch checked',\r\n manualHint: 'Confirm production branch, deploy requests, connection credentials, backups, and schema migration workflow.'\r\n });\r\n}\r\n\r\nfunction analyzeVercelDeployment(ctx: StackContext): StackWiringProviderSummary {\r\n return summarize({\r\n key: 'vercel-deployment',\r\n provider: 'vercel',\r\n providerLabel: 'Vercel',\r\n area: 'deployment',\r\n areaLabel: 'Deployment',\r\n promptSubject: 'Vercel deployment',\r\n items: [\r\n item('deploy-target-detected', 'Vercel-compatible app detected', Boolean(ctx.scan.stackSignals.hasVercel || ctx.scan.stackSignals.hasNextJs || ctx.scan.stackSignals.hasVite || /vercel\\.json|next\\.config|vite\\.config/i.test(ctx.pathBlob)), pathEvidence(ctx, /vercel\\.json|next\\.config|vite\\.config/i), 'Confirm this app has a Vercel-compatible framework or deployment target.'),\r\n item('build-script-found', 'Production build script found', /\"build\"\\s*:\\s*\"[^\"]+\"/i.test(ctx.contentBlob), fileEvidence(ctx, /\"build\"\\s*:\\s*\"[^\"]+\"/i), 'Add a package.json build script that Vercel can run.'),\r\n item('deployment-config-found', 'Deployment config or command found', /vercel\\.json/i.test(ctx.pathBlob) || /\"deploy\"\\s*:\\s*\"[^\"]*vercel/i.test(ctx.contentBlob), pathEvidence(ctx, /vercel\\.json/i).concat(fileEvidence(ctx, /\"deploy\"\\s*:\\s*\"[^\"]*vercel/i)), 'Add vercel.json or a documented Vercel deploy command when the project needs custom deployment behavior.'),\r\n item('env-template-found', 'Production env template found', Boolean(ctx.scan.stackSignals.hasEnvExample || /(^|\\n|\\/)\\.env\\.example\\b|env\\.example|environment variables/i.test(ctx.pathBlob + '\\n' + ctx.contentBlob)), pathEvidence(ctx, /\\.env\\.example|env\\.example/i), 'Document production env variable names in .env.example or setup docs.'),\r\n item('preview-or-ci-found', 'Preview deploy or CI config found', Boolean(ctx.scan.stackSignals.hasCI || /\\.github\\/workflows|vercel\\.json/i.test(ctx.pathBlob)), pathEvidence(ctx, /\\.github\\/workflows|vercel\\.json/i), 'Add CI or Vercel preview-deploy configuration so production changes are tested before release.'),\r\n manualItem('production-dashboard-checked', 'Production Vercel env and domain checked', 'Confirm production env values, project link, framework preset, build command, and production domain in Vercel Dashboard.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzeNetlifyDeployment(ctx: StackContext): StackWiringProviderSummary {\r\n const base = deploymentSummary(ctx, {\r\n key: 'netlify-deployment',\r\n provider: 'netlify',\r\n providerLabel: 'Netlify',\r\n promptSubject: 'Netlify deployment',\r\n packagePatterns: [/@netlify\\//],\r\n configPatterns: [/netlify\\.toml/i, /\\.netlify\\//i],\r\n envPatterns: [/netlify_auth_token/i, /netlify_site_id/i],\r\n manualLabel: 'Production Netlify env and domain checked',\r\n manualHint: 'Confirm build command, publish directory, functions runtime, env values, redirects, and production domain in Netlify.'\r\n });\r\n const redirectsOrFunctionsPattern = /(\\[\\[redirects\\]\\]|(^|\\n|\\/)_redirects\\b|(^|\\n|\\/)netlify\\/functions\\/|\\[functions\\]|functions\\s*=)/i;\r\n return summarize({\r\n ...base,\r\n items: [\r\n ...base.items.filter((entry) => entry.status !== 'manual'),\r\n item('redirects-or-functions-found', 'Redirects or Netlify Functions found', redirectsOrFunctionsPattern.test(ctx.contentBlob + '\\n' + ctx.pathBlob), fileEvidence(ctx, redirectsOrFunctionsPattern).concat(pathEvidence(ctx, redirectsOrFunctionsPattern)), 'Add Netlify redirects or functions configuration when deployment behavior depends on routing or serverless handlers.'),\r\n ...base.items.filter((entry) => entry.status === 'manual')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzeAwsDeployment(ctx: StackContext): StackWiringProviderSummary {\r\n const base = deploymentSummary(ctx, {\r\n key: 'aws-deployment',\r\n provider: 'aws',\r\n providerLabel: 'AWS',\r\n promptSubject: 'AWS deployment',\r\n packagePatterns: [/@aws-sdk\\//, /^aws-cdk-lib$/, /^serverless$/],\r\n configPatterns: [/serverless\\.ya?ml/i, /template\\.ya?ml/i, /cdk\\.json/i, /amplify\\//i, /\\.github\\/workflows/i],\r\n envPatterns: [/aws_region/i, /aws_access_key_id/i],\r\n manualLabel: 'Production AWS account and IAM checked',\r\n manualHint: 'Confirm IAM permissions, region, secrets, logs, alarms, domains, and rollback strategy in AWS.'\r\n });\r\n const infrastructurePattern = /serverless\\.ya?ml|template\\.ya?ml|cdk\\.json|sst\\.config|terraform|cloudformation|aws-cdk-lib|provider:\\s*\\n\\s*name:\\s*aws|resources:\\s*|functions:\\s*/i;\r\n return summarize({\r\n ...base,\r\n items: [\r\n ...base.items.filter((entry) => entry.status !== 'manual'),\r\n item('infrastructure-config-found', 'AWS infrastructure config found', infrastructurePattern.test(ctx.contentBlob + '\\n' + ctx.pathBlob), fileEvidence(ctx, infrastructurePattern).concat(pathEvidence(ctx, infrastructurePattern)), 'Add reproducible AWS infrastructure config such as Serverless, CDK, SAM, CloudFormation, or Terraform.'),\r\n ...base.items.filter((entry) => entry.status === 'manual')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzeSupabaseLanding(ctx: StackContext): StackWiringProviderSummary {\r\n return summarize({\r\n key: 'supabase-landing',\r\n provider: 'supabase',\r\n providerLabel: 'Supabase',\r\n area: 'landing',\r\n areaLabel: 'Landing / Onboarding',\r\n promptSubject: 'Supabase landing data',\r\n items: [\r\n item('package-installed', 'Supabase package installed', hasPackage(ctx, [/@supabase\\//]), packageEvidence(ctx, [/@supabase\\//]), 'Install Supabase client/server helpers for waitlist or onboarding storage.'),\r\n item('env-names-documented', 'Supabase env names documented', /supabase_url/i.test(ctx.contentBlob) && /supabase_anon_key/i.test(ctx.contentBlob), envEvidence(ctx, [/supabase_url/i, /supabase_anon_key/i]), 'Document Supabase URL and anon key env names for landing/onboarding data.'),\r\n item('lead-table-usage-found', 'Lead or onboarding data usage found', /waitlist|lead|onboarding|signup|profiles|subscribers/i.test(ctx.contentBlob), fileEvidence(ctx, /waitlist|lead|onboarding|signup|profiles|subscribers/i), 'Store waitlist, lead, or onboarding records in a clear Supabase table.'),\r\n item('form-submit-found', 'Form submission path found', /formdata|onSubmit|action=|submit|insert\\s*\\(/i.test(ctx.contentBlob), fileEvidence(ctx, /formdata|onSubmit|action=|submit|insert\\s*\\(/i), 'Wire the landing/onboarding form to a real server-safe submission path.'),\r\n manualItem('production-data-policy-checked', 'Production data policy checked', 'Confirm table permissions, spam handling, and privacy policy alignment in Supabase.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzeSentryMonitoring(ctx: StackContext): StackWiringProviderSummary {\r\n return summarize({\r\n key: 'sentry-monitoring',\r\n provider: 'sentry',\r\n providerLabel: 'Sentry',\r\n area: 'monitoring',\r\n areaLabel: 'Monitoring',\r\n promptSubject: 'Sentry monitoring',\r\n items: [\r\n item('package-installed', 'Sentry package installed', hasPackage(ctx, [/^@sentry\\//]), packageEvidence(ctx, [/^@sentry\\//]), 'Install the Sentry package that matches this app framework.'),\r\n item('env-names-documented', 'Sentry DSN env documented', /sentry_dsn|next_public_sentry_dsn/i.test(ctx.contentBlob), envEvidence(ctx, [/sentry_dsn/i, /next_public_sentry_dsn/i]), 'Document SENTRY_DSN or NEXT_PUBLIC_SENTRY_DSN in env examples or setup docs.'),\r\n item('init-found', 'Sentry initialization found', /sentry\\.init\\s*\\(|instrumentation\\.[jt]s/i.test(ctx.contentBlob + '\\n' + ctx.pathBlob), fileEvidence(ctx, /sentry\\.init\\s*\\(|instrumentation\\.[jt]s/i), 'Initialize Sentry in the framework entrypoint for client and server errors.'),\r\n item('error-capture-found', 'Error capture or boundary found', /captureexception|global-error|errorboundary|onerror/i.test(ctx.contentBlob + '\\n' + ctx.pathBlob), fileEvidence(ctx, /captureexception|global-error|errorboundary|onerror/i), 'Capture production exceptions through Sentry error boundaries or server handlers.'),\r\n item('release-config-found', 'Release or source map config found', /sentry_auth_token|withsentryconfig|sentry-cli|sourcemap/i.test(ctx.contentBlob), fileEvidence(ctx, /sentry_auth_token|withsentryconfig|sentry-cli|sourcemap/i), 'Configure Sentry releases or source maps so production stack traces are useful.'),\r\n manualItem('production-dashboard-checked', 'Production Sentry project checked', 'Confirm DSN, environment names, alerts, retention, and source-map upload status in Sentry.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzePostHogMonitoring(ctx: StackContext): StackWiringProviderSummary {\r\n return summarize({\r\n key: 'posthog-monitoring',\r\n provider: 'posthog',\r\n providerLabel: 'PostHog',\r\n area: 'monitoring',\r\n areaLabel: 'Monitoring',\r\n promptSubject: 'PostHog analytics',\r\n items: [\r\n item('package-installed', 'PostHog package installed', hasPackage(ctx, [/^posthog-js$/, /^posthog-node$/]), packageEvidence(ctx, [/^posthog-js$/, /^posthog-node$/]), 'Install posthog-js or posthog-node for the app surface that needs analytics.'),\r\n item('env-names-documented', 'PostHog env names documented', /posthog_key|next_public_posthog_key/i.test(ctx.contentBlob), envEvidence(ctx, [/posthog_key/i, /next_public_posthog_key/i, /next_public_posthog_host/i]), 'Document NEXT_PUBLIC_POSTHOG_KEY and host/project settings in env examples or setup docs.'),\r\n item('init-found', 'PostHog initialization found', /posthog\\.init\\s*\\(/i.test(ctx.contentBlob), fileEvidence(ctx, /posthog\\.init\\s*\\(/i), 'Initialize PostHog once in the app client/provider layer.'),\r\n item('provider-or-wrapper-found', 'Analytics provider or wrapper found', /posthogprovider|analytics\\/posthog|useposthog/i.test(ctx.contentBlob + '\\n' + ctx.pathBlob), fileEvidence(ctx, /posthogprovider|analytics\\/posthog|useposthog/i), 'Add a reusable analytics provider or wrapper instead of scattering raw setup code.'),\r\n item('event-capture-found', 'Product event capture found', /posthog\\.capture\\s*\\(/i.test(ctx.contentBlob), fileEvidence(ctx, /posthog\\.capture\\s*\\(/i), 'Capture at least one activation or conversion event.'),\r\n item('identity-found', 'User identify or group call found', /posthog\\.identify\\s*\\(|posthog\\.group\\s*\\(/i.test(ctx.contentBlob), fileEvidence(ctx, /posthog\\.identify\\s*\\(|posthog\\.group\\s*\\(/i), 'Identify signed-in users or groups where privacy rules allow it.'),\r\n manualItem('production-dashboard-checked', 'Production PostHog project checked', 'Confirm project key, allowed domains, privacy settings, autocapture choice, and retention in PostHog.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzeLogRocketMonitoring(ctx: StackContext): StackWiringProviderSummary {\r\n const privacyScrubbingPattern = /requestSanitizer|responseSanitizer|dom\\.inputSanitizer|dom\\.textSanitizer|maskAllInputs|maskInputOptions|sanitize|scrub|redact|privacy/i;\r\n return summarize({\r\n key: 'logrocket-monitoring',\r\n provider: 'logrocket',\r\n providerLabel: 'LogRocket',\r\n area: 'monitoring',\r\n areaLabel: 'Monitoring',\r\n promptSubject: 'LogRocket monitoring',\r\n items: [\r\n item('package-installed', 'LogRocket package installed', hasPackage(ctx, [/^logrocket$/]), packageEvidence(ctx, [/^logrocket$/]), 'Install LogRocket for session replay if this product needs replay debugging.'),\r\n item('env-names-documented', 'LogRocket app id env documented', /logrocket_app_id|next_public_logrocket_app_id/i.test(ctx.contentBlob), envEvidence(ctx, [/logrocket_app_id/i, /next_public_logrocket_app_id/i]), 'Document the LogRocket app id env name.'),\r\n item('init-found', 'LogRocket initialization found', /logrocket\\.init\\s*\\(/i.test(ctx.contentBlob), fileEvidence(ctx, /logrocket\\.init\\s*\\(/i), 'Initialize LogRocket once in the client app shell.'),\r\n item('identify-found', 'User identification found', /logrocket\\.identify\\s*\\(/i.test(ctx.contentBlob), fileEvidence(ctx, /logrocket\\.identify\\s*\\(/i), 'Identify signed-in users where privacy rules allow it.'),\r\n item('privacy-scrubbing-found', 'Privacy scrubbing found', privacyScrubbingPattern.test(ctx.contentBlob), fileEvidence(ctx, privacyScrubbingPattern), 'Add repo-visible LogRocket privacy scrubbing for sensitive DOM fields or network payloads.'),\r\n manualItem('production-dashboard-checked', 'Production LogRocket privacy settings checked', 'Confirm app id, domain, privacy masking, network scrubbing, and retention in LogRocket.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzeVitestTesting(ctx: StackContext): StackWiringProviderSummary {\r\n return summarize({\r\n key: 'vitest-testing',\r\n provider: 'vitest',\r\n providerLabel: 'Vitest',\r\n area: 'testing',\r\n areaLabel: 'Testing',\r\n promptSubject: 'Vitest tests',\r\n items: [\r\n item('package-installed', 'Vitest package installed', hasPackage(ctx, [/^vitest$/]), packageEvidence(ctx, [/^vitest$/]), 'Install Vitest for unit or component test coverage.'),\r\n item('test-script-found', 'Test script found', /\"test\"\\s*:\\s*\"[^\"]*(vitest|npm run|pnpm|yarn)/i.test(ctx.contentBlob), fileEvidence(ctx, /\"test\"\\s*:\\s*\"[^\"]*(vitest|npm run|pnpm|yarn)/i), 'Add a package.json test script that runs Vitest.'),\r\n item('test-files-found', 'Unit test files found', Boolean(ctx.scan.stackSignals.hasTests) || /\\.(test|spec)\\.[jt]sx?\\b/i.test(ctx.pathBlob), pathEvidence(ctx, /\\.(test|spec)\\.[jt]sx?\\b/i), 'Add unit tests for critical product logic.'),\r\n item('assertions-found', 'Assertions found', /expect\\s*\\(|assert\\s*\\(|test\\s*\\(/i.test(ctx.contentBlob), fileEvidence(ctx, /expect\\s*\\(|assert\\s*\\(|test\\s*\\(/i), 'Ensure tests include real assertions, not only smoke imports.'),\r\n manualItem('coverage-risk-reviewed', 'Critical path coverage reviewed', 'Confirm auth, billing, database, and main user flows have meaningful tests.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzePlaywrightTesting(ctx: StackContext): StackWiringProviderSummary {\r\n return summarize({\r\n key: 'playwright-testing',\r\n provider: 'playwright',\r\n providerLabel: 'Playwright',\r\n area: 'testing',\r\n areaLabel: 'Testing',\r\n promptSubject: 'Playwright tests',\r\n items: [\r\n item('package-installed', 'Playwright package installed', hasPackage(ctx, [/@playwright\\/test/]) || Boolean(ctx.scan.stackSignals.hasPlaywright), packageEvidence(ctx, [/@playwright\\/test/]), 'Install @playwright/test for browser-flow coverage.'),\r\n item('config-found', 'Playwright config found', /playwright\\.config\\.[jt]s/i.test(ctx.pathBlob), pathEvidence(ctx, /playwright\\.config\\.[jt]s/i), 'Add a Playwright config with browser and base URL settings.'),\r\n item('e2e-tests-found', 'Browser flow tests found', /(^|\\n|\\/)(e2e|tests?)\\/[^/\\n]+\\.(spec|test)\\.[jt]s/i.test(ctx.pathBlob), pathEvidence(ctx, /(^|\\/)(e2e|tests?)\\/[^/]+\\.(spec|test)\\.[jt]s/i), 'Add at least one browser test for the core signup or happy path.'),\r\n item('page-actions-found', 'Real browser actions found', /page\\.goto|page\\.click|page\\.getByRole|expect\\(page/i.test(ctx.contentBlob), fileEvidence(ctx, /page\\.goto|page\\.click|page\\.getByRole|expect\\(page/i), 'Use real browser actions and visible assertions in Playwright tests.'),\r\n manualItem('production-like-test-env-checked', 'Production-like test env checked', 'Confirm test env variables, seed data, and CI browser dependencies are ready.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzeSentryErrorHandling(ctx: StackContext): StackWiringProviderSummary {\r\n const base = analyzeSentryMonitoring(ctx);\r\n return summarize({\r\n ...base,\r\n key: 'sentry-error-handling',\r\n area: 'errorHandling',\r\n areaLabel: 'Error Handling',\r\n promptSubject: 'Sentry error handling',\r\n items: [\r\n ...base.items.filter((entry) => entry.id !== 'release-config-found'),\r\n item('user-facing-fallback-found', 'User-facing error fallback found', /global-error|errorboundary|fallback|try again|toast/i.test(ctx.contentBlob + '\\n' + ctx.pathBlob), fileEvidence(ctx, /global-error|errorboundary|fallback|try again|toast/i), 'Add a user-facing fallback for production errors.'),\r\n manualItem('alert-routing-checked', 'Production alert routing checked', 'Confirm alert routing and issue ownership in Sentry.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzePostHogErrorHandling(ctx: StackContext): StackWiringProviderSummary {\r\n return summarize({\r\n key: 'posthog-error-handling',\r\n provider: 'posthog',\r\n providerLabel: 'PostHog',\r\n area: 'errorHandling',\r\n areaLabel: 'Error Handling',\r\n promptSubject: 'PostHog error events',\r\n items: [\r\n item('package-installed', 'PostHog package installed', hasPackage(ctx, [/^posthog-js$/, /^posthog-node$/]), packageEvidence(ctx, [/^posthog-js$/, /^posthog-node$/]), 'Install PostHog before using it for error or recovery events.'),\r\n item('env-names-documented', 'PostHog env names documented', /posthog_key|next_public_posthog_key/i.test(ctx.contentBlob), envEvidence(ctx, [/posthog_key/i, /next_public_posthog_key/i]), 'Document PostHog project env names.'),\r\n item('error-event-capture-found', 'Error or recovery event capture found', /posthog\\.capture\\s*\\([^)]*(error|exception|failed|recovery|retry)/i.test(ctx.contentBlob), fileEvidence(ctx, /posthog\\.capture\\s*\\([^)]*(error|exception|failed|recovery|retry)/i), 'Capture meaningful error or recovery events for product analytics.'),\r\n item('fallback-state-found', 'Fallback state found', /errorboundary|global-error|fallback|try again|retry/i.test(ctx.contentBlob + '\\n' + ctx.pathBlob), fileEvidence(ctx, /errorboundary|global-error|fallback|try again|retry/i), 'Add fallback states that users can recover from.'),\r\n manualItem('privacy-settings-checked', 'Error analytics privacy checked', 'Confirm error analytics avoid sensitive payloads and follow the product privacy policy.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzeRateLimitSecurity(ctx: StackContext): StackWiringProviderSummary {\r\n return summarize({\r\n key: 'rate-limit-security',\r\n provider: 'rate-limit',\r\n providerLabel: 'Rate limiting',\r\n area: 'security',\r\n areaLabel: 'Security',\r\n promptSubject: 'rate limiting',\r\n items: [\r\n item('package-installed', 'Rate limit package installed', hasPackage(ctx, [/@upstash\\/ratelimit/, /express-rate-limit/, /rate-limiter-flexible/, /@fastify\\/rate-limit/]) || Boolean(ctx.scan.stackSignals.hasRateLimit), packageEvidence(ctx, [/@upstash\\/ratelimit/, /express-rate-limit/, /rate-limiter-flexible/, /@fastify\\/rate-limit/]), 'Install a rate-limit library appropriate for this backend.'),\r\n item('env-names-documented', 'Rate limit backing store env documented', /upstash_redis_rest_url|redis_url|rate_limit/i.test(ctx.contentBlob), envEvidence(ctx, [/upstash_redis_rest_url/i, /upstash_redis_rest_token/i, /redis_url/i]), 'Document Redis or provider env names used by rate limiting.'),\r\n item('guard-code-found', 'Rate limit guard code found', /ratelimit|rateLimit|Too many requests|429/i.test(ctx.contentBlob), fileEvidence(ctx, /ratelimit|rateLimit|Too many requests|429/i), 'Add a rate-limit guard to expensive or abusive API routes.'),\r\n item('api-route-coverage-found', 'Protected API route found', /api\\/|route\\.[jt]s/i.test(ctx.pathBlob) && /ratelimit|rateLimit|429/i.test(ctx.contentBlob), pathEvidence(ctx, /api\\/|route\\.[jt]s/i), 'Apply rate limits to public mutation, auth, AI, or checkout endpoints.'),\r\n manualItem('production-thresholds-checked', 'Production thresholds checked', 'Confirm limits, burst behavior, and allowlists match real production traffic.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzeBotProtectionSecurity(ctx: StackContext): StackWiringProviderSummary {\r\n return summarize({\r\n key: 'bot-protection-security',\r\n provider: 'bot-protection',\r\n providerLabel: 'Bot protection',\r\n area: 'security',\r\n areaLabel: 'Security',\r\n promptSubject: 'bot protection',\r\n items: [\r\n item('package-or-widget-found', 'Bot protection package or widget found', hasPackage(ctx, [/turnstile|recaptcha|hcaptcha/]) || /turnstile|recaptcha|hcaptcha|cf-turnstile/i.test(ctx.contentBlob), packageEvidence(ctx, [/turnstile|recaptcha|hcaptcha/]).concat(fileEvidence(ctx, /turnstile|recaptcha|hcaptcha|cf-turnstile/i)), 'Add Turnstile, reCAPTCHA, hCaptcha, or an equivalent bot check for exposed forms.'),\r\n item('env-names-documented', 'Bot protection env names documented', /turnstile.*(site|secret)|recaptcha.*(site|secret)|hcaptcha.*(site|secret)/i.test(ctx.contentBlob), envEvidence(ctx, [/turnstile/i, /recaptcha/i, /hcaptcha/i]), 'Document site key and secret key env names.'),\r\n item('server-verification-found', 'Server-side bot verification found', /siteverify|turnstile.*verify|recaptcha.*verify|hcaptcha.*verify/i.test(ctx.contentBlob), fileEvidence(ctx, /siteverify|turnstile.*verify|recaptcha.*verify|hcaptcha.*verify/i), 'Verify bot tokens server-side before accepting form or signup requests.'),\r\n manualItem('production-challenge-checked', 'Production challenge settings checked', 'Confirm allowed domains, challenge mode, and privacy settings in the bot-protection provider.')\r\n ]\r\n });\r\n}\r\n\r\nfunction analyzeSecretsHygiene(ctx: StackContext): StackWiringProviderSummary {\r\n const unsafePublicSecret = ctx.files.filter((file) =>\r\n isClientExecutedPath(file.normalizedPath) &&\r\n /(secret_key|api_secret|private_key|service_role|webhook_secret|password)/i.test(file.content)\r\n );\r\n return summarize({\r\n key: 'secrets-hygiene-security',\r\n provider: 'secrets-hygiene',\r\n providerLabel: 'Secrets hygiene',\r\n area: 'security',\r\n areaLabel: 'Security',\r\n promptSubject: 'secrets hygiene',\r\n items: [\r\n item('env-example-found', 'Env example or docs found', Boolean(ctx.scan.stackSignals.hasEnvExample) || /\\.env\\.example|env\\.example|environment variables/i.test(ctx.pathBlob + '\\n' + ctx.contentBlob), pathEvidence(ctx, /\\.env\\.example|env\\.example/i), 'Add an env example or setup docs with variable names only.'),\r\n item('secret-files-ignored', 'Secret files detected as private', Array.isArray(ctx.scan.secretsFound) && ctx.scan.secretsFound.length > 0, ctx.scan.secretsFound.slice(0, 4).map((path) => `secret file: ${path}`), 'Keep real .env files private and out of copied prompts or docs.'),\r\n item('frontend-secrets-clean', 'No obvious frontend secret exposure found', unsafePublicSecret.length === 0, unsafePublicSecret.slice(0, 4).map((file) => `unsafe reference: ${file.path}`), 'Move secret values and private keys out of frontend/client-executed files.'),\r\n item('gitignore-env-found', 'Env files ignored by git', /\\.gitignore/i.test(ctx.pathBlob) && /\\.env/i.test(ctx.contentBlob), pathEvidence(ctx, /\\.gitignore/i), 'Ensure .gitignore excludes real .env files while keeping .env.example committed.'),\r\n manualItem('production-secret-rotation-checked', 'Production secret rotation checked', 'Confirm production secrets can be rotated and revoked in provider dashboards.')\r\n ]\r\n });\r\n}\r\n\r\nfunction databaseSummary(\r\n ctx: StackContext,\r\n spec: {\r\n key: StackWiringKey;\r\n provider: StackWiringProviderSummary['provider'];\r\n providerLabel: string;\r\n promptSubject: string;\r\n packagePatterns: RegExp[];\r\n envPatterns: RegExp[];\r\n usagePatterns: RegExp[];\r\n manualLabel: string;\r\n manualHint: string;\r\n }\r\n): StackWiringProviderSummary {\r\n const usagePattern = new RegExp(spec.usagePatterns.map((pattern) => pattern.source).join('|'), 'i');\r\n const indexOrPerformancePattern = /create\\s+(unique\\s+)?index|\\bindex\\s*:\\s*true|@@index|\\.index\\s*\\(|\\bindexes\\b|\\bexplain\\s*\\(|connection\\s*pool|pooling|pgbouncer/i;\r\n return summarize({\r\n key: spec.key,\r\n provider: spec.provider,\r\n providerLabel: spec.providerLabel,\r\n area: 'database',\r\n areaLabel: 'Database',\r\n promptSubject: spec.promptSubject,\r\n items: [\r\n item('package-installed', `${spec.providerLabel} package installed`, hasPackage(ctx, spec.packagePatterns), packageEvidence(ctx, spec.packagePatterns), `Install the ${spec.providerLabel} package or SDK for this app.`),\r\n item('env-names-documented', `${spec.providerLabel} env names documented`, spec.envPatterns.some((pattern) => pattern.test(ctx.contentBlob)), envEvidence(ctx, spec.envPatterns), `Document ${spec.providerLabel} connection env names in an env example or setup docs.`),\r\n item('client-or-connection-found', `${spec.providerLabel} connection code found`, usagePattern.test(ctx.contentBlob), fileEvidence(ctx, usagePattern), `Add ${spec.providerLabel} connection code in a server-safe helper.`),\r\n item('query-usage-found', 'Database query usage found', /select\\s*\\(|insert\\s*\\(|update\\s*\\(|delete\\s*\\(|findOne|findMany|collection\\s*\\(|execute\\s*\\(|query\\s*\\(|sql`/i.test(ctx.contentBlob), fileEvidence(ctx, /select\\s*\\(|insert\\s*\\(|update\\s*\\(|delete\\s*\\(|findOne|findMany|collection\\s*\\(|execute\\s*\\(|query\\s*\\(|sql`/i), 'Use the database connection for real reads or writes.'),\r\n item('schema-or-model-found', 'Schema, model, or migration found', /schema|migration|model|create\\s+table|mongoose\\.schema|drizzle|prisma/i.test(ctx.contentBlob + '\\n' + ctx.pathBlob), fileEvidence(ctx, /schema|migration|model|create\\s+table|mongoose\\.schema|drizzle|prisma/i), 'Keep schema, models, or migrations reproducible in the repo.'),\r\n item('index-or-performance-evidence', 'Index or performance evidence found', indexOrPerformancePattern.test(ctx.contentBlob), fileEvidence(ctx, indexOrPerformancePattern), 'Add repo-visible indexes, query plans, connection pooling, or equivalent performance evidence for production database access.'),\r\n manualItem('production-dashboard-checked', spec.manualLabel, spec.manualHint)\r\n ]\r\n });\r\n}\r\n\r\nfunction deploymentSummary(\r\n ctx: StackContext,\r\n spec: {\r\n key: StackWiringKey;\r\n provider: StackWiringProviderSummary['provider'];\r\n providerLabel: string;\r\n promptSubject: string;\r\n packagePatterns: RegExp[];\r\n configPatterns: RegExp[];\r\n envPatterns: RegExp[];\r\n manualLabel: string;\r\n manualHint: string;\r\n }\r\n): StackWiringProviderSummary {\r\n const configPattern = new RegExp(spec.configPatterns.map((pattern) => pattern.source).join('|'), 'i');\r\n return summarize({\r\n key: spec.key,\r\n provider: spec.provider,\r\n providerLabel: spec.providerLabel,\r\n area: 'deployment',\r\n areaLabel: 'Deployment',\r\n promptSubject: spec.promptSubject,\r\n items: [\r\n item('package-or-config-found', `${spec.providerLabel} package or config found`, hasPackage(ctx, spec.packagePatterns) || configPattern.test(ctx.pathBlob), packageEvidence(ctx, spec.packagePatterns).concat(pathEvidence(ctx, configPattern)), `Add ${spec.providerLabel} config when this project needs provider-specific deployment behavior.`),\r\n item('build-script-found', 'Production build script found', /\"build\"\\s*:\\s*\"[^\"]+\"/i.test(ctx.contentBlob), fileEvidence(ctx, /\"build\"\\s*:\\s*\"[^\"]+\"/i), 'Add a package.json build script for production deploys.'),\r\n item('env-names-documented', 'Deployment env names documented', spec.envPatterns.some((pattern) => pattern.test(ctx.contentBlob)) || /\\.env\\.example|environment variables/i.test(ctx.pathBlob + '\\n' + ctx.contentBlob), envEvidence(ctx, spec.envPatterns).concat(pathEvidence(ctx, /\\.env\\.example/i)), 'Document production env variable names needed by deployment.'),\r\n item('ci-or-deploy-doc-found', 'CI or deploy docs found', /\\.github\\/workflows|deploy|deployment|preview/i.test(ctx.pathBlob + '\\n' + ctx.contentBlob), pathEvidence(ctx, /\\.github\\/workflows/i).concat(fileEvidence(ctx, /deploy|deployment|preview/i)), 'Document or automate deployment and preview checks.'),\r\n manualItem('production-dashboard-checked', spec.manualLabel, spec.manualHint)\r\n ]\r\n });\r\n}\r\n\r\nfunction buildContext(scan: ScanResult): StackContext {\r\n const files = visibleFiles(scan);\r\n return {\r\n scan,\r\n files,\r\n deps: scan.packageDeps.map((dep) => dep.toLowerCase()),\r\n pathBlob: `${scan.fileTree}\\n${scan.files.map((file) => file.path).join('\\n')}`.replace(/\\\\/g, '/').toLowerCase(),\r\n contentBlob: files.map((file) => file.lowerContent).join('\\n')\r\n };\r\n}\r\n\r\nfunction visibleFiles(scan: ScanResult): VisibleFile[] {\r\n return scan.files\r\n .filter((file: ScannedFile) => !file.isSecret && typeof file.content === 'string')\r\n .map((file) => ({\r\n path: file.path.replace(/\\\\/g, '/'),\r\n normalizedPath: file.path.replace(/\\\\/g, '/').toLowerCase(),\r\n content: file.content as string,\r\n lowerContent: (file.content as string).toLowerCase()\r\n }));\r\n}\r\n\r\nfunction summarize(summary: Omit<StackWiringProviderSummary, 'passedCount' | 'totalCount' | 'readinessPercent'>): StackWiringProviderSummary {\r\n const repoItems = summary.items.filter((entry) => entry.status !== 'manual');\r\n const passedCount = repoItems.filter((entry) => entry.status === 'passed').length;\r\n const totalCount = repoItems.length;\r\n return {\r\n ...summary,\r\n passedCount,\r\n totalCount,\r\n readinessPercent: Math.round((passedCount / Math.max(totalCount, 1)) * 100)\r\n };\r\n}\r\n\r\nfunction item(id: string, label: string, passed: boolean, evidence: string[], promptHint: string): StackWiringItem {\r\n return {\r\n id,\r\n label,\r\n status: passed ? 'passed' : 'missing',\r\n evidence,\r\n promptHint\r\n };\r\n}\r\n\r\nfunction manualItem(id: string, label: string, promptHint: string): StackWiringItem {\r\n return {\r\n id,\r\n label,\r\n status: 'manual',\r\n evidence: [],\r\n promptHint\r\n };\r\n}\r\n\r\nfunction secretSafetyItem(ctx: StackContext, id: string, label: string, pattern: RegExp, promptHint: string): StackWiringItem {\r\n const exposed = ctx.files.filter((file) => isClientExecutedPath(file.normalizedPath) && pattern.test(file.content));\r\n return {\r\n id,\r\n label,\r\n status: exposed.length > 0 ? 'missing' : 'passed',\r\n evidence: exposed.slice(0, 4).map((file) => `unsafe reference: ${file.path}`),\r\n promptHint\r\n };\r\n}\r\n\r\nfunction hasPackage(ctx: StackContext, patterns: RegExp[]): boolean {\r\n return ctx.deps.some((dep) => patterns.some((pattern) => pattern.test(dep)));\r\n}\r\n\r\nfunction hasAllContent(ctx: StackContext, patterns: RegExp[]): boolean {\r\n return patterns.every((pattern) => pattern.test(ctx.contentBlob));\r\n}\r\n\r\nfunction packageEvidence(ctx: StackContext, patterns: RegExp[]): string[] {\r\n return ctx.deps\r\n .filter((dep) => patterns.some((pattern) => pattern.test(dep)))\r\n .slice(0, 4)\r\n .map((dep) => `package: ${dep}`);\r\n}\r\n\r\nfunction envEvidence(ctx: StackContext, patterns: RegExp[]): string[] {\r\n const evidence: string[] = [];\r\n for (const pattern of patterns) {\r\n if (pattern.test(ctx.contentBlob)) {\r\n evidence.push(`env: ${pattern.source.replace(/\\\\b|\\(|\\)|\\?|\\||\\^|\\$|_/g, ' ').trim().toUpperCase().replace(/\\s+/g, '_')}`);\r\n }\r\n }\r\n return evidence.slice(0, 4);\r\n}\r\n\r\nfunction pathEvidence(ctx: StackContext, pattern: RegExp): string[] {\r\n return ctx.pathBlob\r\n .split(/\\r?\\n/)\r\n .filter((path) => pattern.test(path))\r\n .slice(0, 4)\r\n .map((path) => `file: ${path}`);\r\n}\r\n\r\nfunction fileEvidence(ctx: StackContext, pattern: RegExp): string[] {\r\n return ctx.files\r\n .filter((file) => pattern.test(file.path) || pattern.test(file.content))\r\n .slice(0, 4)\r\n .map((file) => `file: ${file.path}`);\r\n}\r\n\r\nfunction isClientExecutedPath(path: string): boolean {\r\n return /\\.(tsx|jsx)$/.test(path) ||\r\n /(^|\\/)(components|pages|app|client|frontend|web)\\//.test(path) ||\r\n /\\.client\\.[jt]sx?$/.test(path);\r\n}\r\n\r\nfunction formatEvidence(evidence: string[]): string {\r\n return evidence.length > 0 ? ` (${evidence.slice(0, 3).join('; ')})` : '';\r\n}\r\n", "import type {\r\n ProductionConnectionSummary,\r\n ScanResult,\r\n VerificationArea,\r\n VerificationAreaSummary,\r\n VerificationItem,\r\n VerificationItemStatus,\r\n VerificationSummary\r\n} from './types';\r\n\r\ntype ProductionConnectionSummaryPayload = {\r\n byArea: Partial<Record<string, ProductionConnectionSummary>>;\r\n items: ProductionConnectionSummary[];\r\n stackRow: ProductionConnectionSummary[];\r\n};\r\n\r\ntype VerificationContext = {\n deps: Set<string>;\n paths: Set<string>;\n contents: string;\n secretPaths: Set<string>;\n scan: ScanResult;\n};\n\nconst PROVIDER_LABELS: Record<string, string> = {\n supabase: 'Supabase',\n clerk: 'Clerk',\n authjs: 'Auth.js',\n neon: 'Neon',\n planetscale: 'PlanetScale',\n mongodb: 'MongoDB',\n turso: 'Turso',\n stripe: 'Stripe',\n paddle: 'Paddle',\n vercel: 'Vercel',\n sentry: 'Sentry',\n posthog: 'PostHog',\n logrocket: 'LogRocket',\n 'rate-limit': 'Rate limit',\n 'bot-protection': 'Bot protection',\n 'secrets-hygiene': 'Secrets hygiene'\n};\n\nconst AREAS: VerificationArea[] = [\n 'auth',\r\n 'database',\r\n 'payments',\r\n 'deployment',\r\n 'monitoring',\r\n 'security',\r\n 'testing',\r\n 'landing',\r\n 'frontend',\r\n 'backend',\r\n 'appFlow',\r\n 'errorHandling'\r\n];\r\n\r\nconst CONTENT_CAP = 500_000;\r\n\r\nexport function buildVerificationSummary(\n scan: ScanResult,\n productionConnections: ProductionConnectionSummaryPayload\n): VerificationSummary {\n const ctx = buildContext(scan);\n const byArea: VerificationSummary['byArea'] = {};\n\r\n for (const area of AREAS) {\r\n byArea[area] = emptyArea(area);\r\n }\r\n\r\n applyAuthRules(byArea.auth!, ctx);\r\n applyDatabaseRules(byArea.database!, ctx);\r\n applyPaymentRules(byArea.payments!, ctx);\r\n applyDeploymentRules(byArea.deployment!, ctx);\r\n applyMonitoringRules(byArea.monitoring!, ctx);\r\n applySecurityRules(byArea.security!, ctx);\r\n applyTestingRules(byArea.testing!, ctx);\r\n applyLandingRules(byArea.landing!, ctx);\r\n applyFrontendRules(byArea.frontend!, ctx);\r\n applyBackendRules(byArea.backend!, ctx);\n applyAppFlowRules(byArea.appFlow!, ctx);\n applyErrorHandlingRules(byArea.errorHandling!, ctx);\n applyProductionConnectionEvidence(byArea, productionConnections);\n\n return { byArea };\n}\n\nexport function buildVerificationEvidenceContext(summary: VerificationSummary): string {\n const lines: string[] = [];\n for (const area of AREAS) {\n const areaSummary = summary.byArea[area];\n if (!areaSummary) {\n continue;\n }\n const found = areaSummary.found.slice(0, 6).map(formatVerificationContextItem);\n const missing = areaSummary.missing.slice(0, 6).map(formatVerificationContextItem);\n if (found.length > 0) {\n lines.push(`${area} found: ${found.join(' | ')}`);\n }\n if (missing.length > 0) {\n lines.push(`${area} missing: ${missing.join(' | ')}`);\n }\n }\n\n return lines.join('\\n');\n}\n\nfunction formatVerificationContextItem(item: VerificationItem): string {\n return item.detail ? `${item.label} (${item.detail})` : item.label;\n}\n\r\nfunction buildContext(scan: ScanResult): VerificationContext {\r\n const deps = new Set(scan.packageDeps.map((dep) => dep.toLowerCase()));\r\n const paths = new Set<string>();\r\n const secretPaths = new Set<string>();\r\n const contentParts: string[] = [];\r\n let contentLength = 0;\r\n\r\n for (const line of scan.fileTree.split(/\\r?\\n/)) {\r\n const normalized = normalizePath(line);\r\n if (normalized) {\r\n paths.add(normalized);\r\n }\r\n }\r\n\r\n for (const file of scan.files) {\r\n if (!file.isSecret) {\r\n const normalized = normalizePath(file.path);\r\n if (normalized) {\r\n paths.add(normalized);\r\n }\r\n }\r\n\r\n if (!file.isSecret && file.content) {\r\n const next = file.content.toLowerCase();\r\n const remaining = CONTENT_CAP - contentLength;\r\n if (remaining > 0) {\r\n contentParts.push(next.slice(0, remaining));\r\n contentLength += Math.min(next.length, remaining);\r\n }\r\n }\r\n }\r\n\r\n for (const secretPath of scan.secretsFound) {\r\n const normalized = normalizePath(secretPath);\r\n if (normalized) {\r\n secretPaths.add(normalized);\r\n }\r\n }\r\n\r\n return {\r\n deps,\r\n paths,\r\n contents: contentParts.join('\\n'),\r\n secretPaths,\r\n scan\r\n };\r\n}\r\n\r\nfunction emptyArea(area: VerificationArea): VerificationAreaSummary {\r\n return {\r\n area,\r\n found: [],\r\n missing: [],\r\n manual: []\r\n };\r\n}\r\n\r\nfunction normalizePath(path: string): string {\r\n return path\r\n .replace(/\\\\/g, '/')\r\n .replace(/^[\\s\\u2500\\u2502\\u2514\\u251c>*+-]+/u, '')\r\n .trim()\r\n .toLowerCase();\r\n}\r\n\r\nfunction addFound(area: VerificationAreaSummary, label: string, source: string, detail?: string): void {\r\n addItem(area, 'found', label, source, detail);\r\n}\r\n\r\nfunction addMissing(area: VerificationAreaSummary, label: string, source: string, detail?: string): void {\r\n addItem(area, 'missing', label, source, detail);\r\n}\r\n\r\nfunction addManual(area: VerificationAreaSummary, label: string, source: string, detail?: string): void {\r\n addItem(area, 'manual', label, source, detail);\r\n}\r\n\r\nfunction addItem(\r\n area: VerificationAreaSummary,\r\n status: VerificationItemStatus,\r\n label: string,\r\n source: string,\r\n detail?: string\r\n): void {\r\n const item = compactItem(label, status, source, detail);\r\n const bucket = area[status];\r\n if (!bucket.some((existing) => existing.label === item.label)) {\r\n bucket.push(item);\r\n }\r\n}\r\n\r\nfunction compactItem(\r\n label: string,\r\n status: VerificationItemStatus,\r\n source: string,\r\n detail?: string\r\n): VerificationItem {\r\n return detail ? { label, status, source, detail } : { label, status, source };\r\n}\r\n\r\nfunction hasDep(ctx: VerificationContext, patterns: string[]): boolean {\r\n return patterns.some((pattern) => {\r\n const normalized = pattern.toLowerCase();\r\n return [...ctx.deps].some((dep) => dep === normalized || dep.includes(normalized));\r\n });\r\n}\r\n\r\nfunction hasPath(ctx: VerificationContext, patterns: RegExp[]): boolean {\r\n return [...ctx.paths].some((path) => !ctx.secretPaths.has(path) && patterns.some((pattern) => pattern.test(path)));\r\n}\r\n\r\nfunction hasContent(ctx: VerificationContext, patterns: RegExp[]): boolean {\r\n return patterns.some((pattern) => pattern.test(ctx.contents));\r\n}\r\n\r\nfunction hasEnvName(ctx: VerificationContext, names: string[]): boolean {\r\n return names.some((name) => ctx.contents.includes(name.toLowerCase()));\r\n}\r\n\r\nfunction applyAuthRules(area: VerificationAreaSummary, ctx: VerificationContext): void {\r\n if (hasDep(ctx, ['@clerk/nextjs', 'clerk'])) {\r\n addFound(area, 'Clerk dependency found', 'package.json dependencies');\r\n } else if (hasDep(ctx, ['next-auth', '@auth/core', '@auth/nextjs'])) {\r\n addFound(area, 'Auth.js dependency found', 'package.json dependencies');\r\n } else if (hasDep(ctx, ['@supabase/supabase-js', '@supabase/auth-helpers-nextjs', '@supabase/ssr'])) {\r\n addFound(area, 'Supabase auth dependency found', 'package.json dependencies');\r\n } else {\r\n addMissing(area, 'Auth dependency missing', 'package.json dependencies');\r\n }\r\n\r\n if (\r\n hasPath(ctx, [/^middleware\\.[jt]sx?$/, /\\/middleware\\.[jt]sx?$/]) ||\r\n hasContent(ctx, [/clerkmiddleware\\s*\\(/, /withauth\\s*\\(/, /authmiddleware\\s*\\(/])\r\n ) {\r\n addFound(area, 'Auth middleware found', 'middleware file or auth middleware call');\r\n } else {\r\n addMissing(area, 'Auth middleware missing', 'middleware file or auth middleware call');\r\n }\r\n\r\n if (\r\n hasEnvName(ctx, [\r\n 'NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY',\r\n 'CLERK_SECRET_KEY',\r\n 'NEXTAUTH_SECRET',\r\n 'AUTH_SECRET',\r\n 'SUPABASE_SERVICE_ROLE_KEY',\r\n 'NEXT_PUBLIC_SUPABASE_ANON_KEY'\r\n ])\r\n ) {\r\n addFound(area, 'Auth env names listed', 'non-secret scanned content');\r\n } else {\r\n addMissing(area, 'Auth env names missing', 'non-secret scanned content');\r\n }\r\n\r\n addManual(area, 'Provider dashboard settings', 'external provider dashboard');\r\n addManual(area, 'Real production auth keys', 'external provider dashboard');\r\n}\r\n\r\nfunction applyDatabaseRules(area: VerificationAreaSummary, ctx: VerificationContext): void {\n if (hasDep(ctx, ['prisma', 'drizzle-orm', '@supabase/supabase-js', 'mongoose', 'mongodb', '@neondatabase/serverless'])) {\n addFound(area, 'Database dependency found', 'package.json dependencies');\n } else {\r\n addMissing(area, 'Database dependency missing', 'package.json dependencies');\r\n }\r\n\r\n if (hasPath(ctx, [/prisma\\/schema\\.prisma$/, /migrations?\\//, /drizzle\\//, /schema\\.(ts|js|sql)$/])) {\n addFound(area, 'Schema or migration file found', 'repo paths');\n } else {\n addMissing(area, 'Schema or migration file missing', 'repo paths');\n }\n\n if (\n hasContent(ctx, [\n /prisma\\.[a-z0-9_]+\\.(find|create|update|delete|upsert|aggregate)/i,\n /\\bdb\\.(select|insert|update|delete|query)\\s*\\(/i,\n /\\bmongoose\\.model\\s*\\(/i,\n /\\bnew\\s+mongoclient\\s*\\(/i,\n /\\bcreateclient\\s*\\([^)]*supabase/i,\n /\\.from\\s*\\(\\s*['\"][a-z0-9_]+['\"]\\s*\\)/i\n ])\n ) {\n addFound(area, 'Database query usage found', 'repo evidence');\n }\n\n if (ctx.scan.stackSignals.hasSupabase || hasDep(ctx, ['@supabase/supabase-js', '@supabase/ssr'])) {\n if (\n hasPath(ctx, [/supabase\\/migrations\\/.*\\.sql$/, /\\/policies\\//, /rls/i]) ||\n hasContent(ctx, [/enable\\s+row\\s+level\\s+security/i, /create\\s+policy/i, /alter\\s+table[\\s\\S]{0,200}enable\\s+row\\s+level/i])\n ) {\n addFound(area, 'Supabase RLS policy evidence found', 'repo evidence');\n } else {\n addMissing(area, 'Supabase RLS policy evidence missing', 'repo evidence');\n }\n }\n\n if (\n hasEnvName(ctx, [\n 'DATABASE_URL',\n 'POSTGRES_URL',\n 'SUPABASE_URL',\n 'NEXT_PUBLIC_SUPABASE_URL',\n 'NEON_DATABASE_URL',\n 'PLANETSCALE_DATABASE_URL',\n 'MONGODB_URI',\n 'MONGODB_URL',\n 'TURSO_DATABASE_URL',\n 'TURSO_AUTH_TOKEN'\n ])\r\n ) {\r\n addFound(area, 'Database env names listed', 'non-secret scanned content');\r\n } else {\r\n addMissing(area, 'Database env names missing', 'non-secret scanned content');\r\n }\r\n\r\n addManual(area, 'Hosted DB project settings', 'external database dashboard');\r\n addManual(area, 'Production access policy', 'external database dashboard');\r\n}\r\n\r\nfunction applyPaymentRules(area: VerificationAreaSummary, ctx: VerificationContext): void {\r\n if (hasDep(ctx, ['stripe'])) {\r\n addFound(area, 'Stripe dependency found', 'package.json dependencies');\r\n } else if (hasDep(ctx, ['@paddle/paddle-js', 'paddle'])) {\r\n addFound(area, 'Paddle dependency found', 'package.json dependencies');\r\n } else {\r\n addMissing(area, 'Payment dependency missing', 'package.json dependencies');\r\n }\r\n\r\n if (\r\n hasPath(ctx, [\r\n /stripe\\/.*webhook/,\r\n /webhook.*stripe/,\r\n /paddle\\/.*webhook/,\r\n /webhook.*paddle/,\r\n /stripe\\/route\\.[jt]s$/,\r\n /paddle\\/route\\.[jt]s$/\r\n ]) ||\r\n hasContent(ctx, [/stripe[^.\\n]*webhook/, /webhook[^.\\n]*stripe/, /paddle[^.\\n]*webhook/, /webhook[^.\\n]*paddle/, /constructevent\\s*\\(/])\r\n ) {\r\n addFound(area, 'Payment webhook route found', 'repo paths or webhook handler code');\r\n } else {\r\n addMissing(area, 'Payment webhook route missing', 'repo paths or webhook handler code');\r\n }\r\n\r\n if (\r\n hasPath(ctx, [\r\n /checkout/,\r\n /billing/,\r\n /stripe\\/.*session/,\r\n /session.*stripe/,\r\n /paddle\\/.*session/,\r\n /session.*paddle/\r\n ]) ||\r\n hasContent(ctx, [/checkout\\.sessions\\.create\\s*\\(/, /createcheckoutsession/, /billing_portal/])\r\n ) {\r\n addFound(area, 'Checkout/session route found', 'repo paths or checkout code');\r\n } else {\r\n addMissing(area, 'Checkout/session route missing', 'repo paths or checkout code');\r\n }\r\n\r\n if (\r\n hasEnvName(ctx, [\r\n 'STRIPE_SECRET_KEY',\r\n 'STRIPE_WEBHOOK_SECRET',\r\n 'NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY',\r\n 'PADDLE_API_KEY',\r\n 'PADDLE_WEBHOOK_SECRET',\r\n 'NEXT_PUBLIC_PADDLE_CLIENT_TOKEN'\r\n ])\r\n ) {\r\n addFound(area, 'Payment env names listed', 'non-secret scanned content');\r\n } else {\r\n addMissing(area, 'Payment env names missing', 'non-secret scanned content');\r\n }\r\n\r\n addManual(area, 'Provider dashboard configuration', 'external payment dashboard');\r\n addManual(area, 'Webhook endpoint registered with provider', 'external payment dashboard');\r\n}\r\n\r\nfunction applyDeploymentRules(area: VerificationAreaSummary, ctx: VerificationContext): void {\n if (hasPath(ctx, [/vercel\\.json$/, /netlify\\.toml$/, /render\\.ya?ml$/, /dockerfile$/, /docker-compose\\.ya?ml$/])) {\n addFound(area, 'Deployment config found', 'repo paths');\n } else {\r\n addMissing(area, 'Deployment config missing', 'repo paths');\r\n }\r\n\r\n if (hasContent(ctx, [/\"build\"\\s*:/])) {\n addFound(area, 'Build script found', 'package scripts');\n } else {\n addMissing(area, 'Build script missing', 'package scripts');\n }\n\n if (ctx.scan.stackSignals.hasCI || hasPath(ctx, [/(^|\\/)\\.github\\/workflows\\/[^/]+\\.ya?ml$/, /(^|\\/)\\.gitlab-ci\\.yml$/, /(^|\\/)circle\\.yml$/])) {\n addFound(area, 'CI config found', 'repo paths');\n } else {\n addMissing(area, 'CI config missing', 'repo paths');\n }\n\n addManual(area, 'Hosting environment variables checked', 'hosting dashboard');\n addManual(area, 'DNS and production domain checked', 'hosting dashboard');\n}\r\n\r\nfunction applyMonitoringRules(area: VerificationAreaSummary, ctx: VerificationContext): void {\r\n if (hasDep(ctx, ['@sentry/nextjs', '@sentry/node', 'posthog-js', 'logrocket'])) {\r\n addFound(area, 'Monitoring dependency found', 'package.json dependencies');\r\n } else {\r\n addMissing(area, 'Monitoring dependency missing', 'package.json dependencies');\r\n }\r\n\r\n if (hasContent(ctx, [/sentry\\.init\\s*\\(/, /posthog\\.init\\s*\\(/, /logrocket\\.init\\s*\\(/])) {\r\n addFound(area, 'Monitoring SDK init found', 'non-secret scanned content');\r\n } else {\r\n addMissing(area, 'Monitoring SDK init missing', 'non-secret scanned content');\r\n }\r\n\r\n if (hasEnvName(ctx, ['SENTRY_DSN', 'NEXT_PUBLIC_SENTRY_DSN', 'NEXT_PUBLIC_POSTHOG_KEY', 'LOGROCKET_APP_ID'])) {\r\n addFound(area, 'Monitoring env names listed', 'non-secret scanned content');\r\n } else {\r\n addMissing(area, 'Monitoring env names missing', 'non-secret scanned content');\r\n }\r\n\r\n addManual(area, 'Dashboard receiving events', 'external monitoring dashboard');\r\n}\r\n\r\nfunction applySecurityRules(area: VerificationAreaSummary, ctx: VerificationContext): void {\r\n if (ctx.scan.stackSignals.hasRateLimit || hasDep(ctx, ['@upstash/ratelimit']) || hasContent(ctx, [/ratelimit/, /rate limit/])) {\r\n addFound(area, 'Rate limit evidence found', 'repo evidence');\r\n } else {\r\n addMissing(area, 'Rate limit evidence missing', 'repo evidence');\r\n }\r\n\r\n if (hasContent(ctx, [/bot protection/, /turnstile/, /recaptcha/, /hcaptcha/]) || hasDep(ctx, ['@marsidev/react-turnstile'])) {\r\n addFound(area, 'Bot protection evidence found', 'repo evidence');\r\n } else {\r\n addMissing(area, 'Bot protection evidence missing', 'repo evidence');\r\n }\r\n\r\n if (ctx.scan.stackSignals.hasEnvExample || hasPath(ctx, [/\\.env\\.example$/, /\\.env\\.sample$/, /example\\.env$/])) {\r\n addFound(area, '.env.example found', 'repo paths');\r\n } else {\r\n addMissing(area, '.env.example missing', 'repo paths');\r\n }\r\n\r\n if (ctx.secretPaths.size > 0) {\r\n addFound(area, 'Secret-like files excluded from scan content', 'secret filename list');\r\n }\r\n\r\n addManual(area, 'WAF and abuse controls', 'hosting or security dashboard');\r\n addManual(area, 'Real secret rotation', 'production secret manager');\r\n}\r\n\r\nfunction applyTestingRules(area: VerificationAreaSummary, ctx: VerificationContext): void {\n if (hasDep(ctx, ['vitest', 'jest', '@playwright/test', 'cypress', 'mocha']) || hasContent(ctx, [/\"test\"\\s*:/])) {\n addFound(area, 'Test tooling found', 'package.json dependencies or scripts');\n } else {\n addMissing(area, 'Test tooling missing', 'package.json dependencies or scripts');\n }\n\n if (hasDep(ctx, ['@playwright/test']) || hasPath(ctx, [/playwright\\.config\\.[jt]s$/])) {\n addFound(area, 'Playwright dependency found', 'package.json dependencies or config');\n }\n\n if (ctx.scan.stackSignals.hasTests || hasPath(ctx, [/\\.test\\.[jt]sx?$/, /\\.spec\\.[jt]sx?$/, /__tests__\\//])) {\n addFound(area, 'Test files found', 'repo paths');\n } else {\n addMissing(area, 'Test files missing', 'repo paths');\n }\n\n if (hasDep(ctx, ['@playwright/test']) && hasPath(ctx, [/\\.spec\\.[jt]sx?$/, /e2e\\//, /tests?\\//])) {\n addFound(area, 'End-to-end test files found', 'repo paths');\n }\n\n if (ctx.scan.stackSignals.hasCI || hasPath(ctx, [/(^|\\/)\\.github\\/workflows\\/[^/]+\\.ya?ml$/, /(^|\\/)\\.gitlab-ci\\.yml$/, /(^|\\/)circle\\.yml$/])) {\n addFound(area, 'CI workflow found', 'repo paths');\n }\n\n addManual(area, 'CI status', 'CI provider dashboard');\n}\n\r\nfunction applyLandingRules(area: VerificationAreaSummary, ctx: VerificationContext): void {\r\n if (\r\n ctx.scan.stackSignals.hasLanding ||\r\n hasPath(ctx, [/app\\/page\\.[jt]sx?$/, /pages\\/index\\.[jt]sx?$/, /landing\\//, /home\\.[jt]sx?$/])\r\n ) {\r\n addFound(area, 'Landing page found', 'repo paths');\r\n } else {\r\n addMissing(area, 'Landing page missing', 'repo paths');\r\n }\r\n\r\n if (hasPath(ctx, [/pricing/, /account/, /onboarding/])) {\r\n addFound(area, 'Pricing/account/onboarding path found', 'repo paths');\r\n } else {\r\n addMissing(area, 'Pricing/account/onboarding path missing', 'repo paths');\r\n }\r\n\r\n if (hasContent(ctx, [/analytics/, /posthog/, /gtag\\(/, /plausible/])) {\n addFound(area, 'Funnel or analytics evidence found', 'non-secret scanned content');\n } else {\n addMissing(area, 'Funnel or analytics evidence missing', 'non-secret scanned content');\n }\n\n if (ctx.scan.stackSignals.hasRobots && ctx.scan.stackSignals.hasSitemap) {\n addFound(area, 'SEO crawl files found', 'repo paths');\n } else {\n addMissing(area, 'SEO crawl files missing', 'repo paths');\n }\n\n addManual(area, 'Conversion quality', 'manual product review');\n}\n\r\nfunction applyFrontendRules(area: VerificationAreaSummary, ctx: VerificationContext): void {\r\n if (hasDep(ctx, ['react', 'vue', 'svelte', '@angular/core']) || hasPath(ctx, [/src\\/.*\\.[jt]sx$/, /app\\/.*\\.[jt]sx$/])) {\r\n addFound(area, 'Frontend framework evidence found', 'repo evidence');\r\n } else {\r\n addMissing(area, 'Frontend framework evidence missing', 'repo evidence');\r\n }\r\n\r\n if (ctx.scan.stackSignals.hasLoadingStates || hasPath(ctx, [/loading\\.[jt]sx?$/]) || hasContent(ctx, [/loading/i])) {\r\n addFound(area, 'Loading state evidence found', 'repo evidence');\r\n } else {\r\n addMissing(area, 'Loading state evidence missing', 'repo evidence');\r\n }\r\n\r\n addManual(area, 'Responsive UX review', 'manual product review');\r\n}\r\n\r\nfunction applyBackendRules(area: VerificationAreaSummary, ctx: VerificationContext): void {\n if (hasPath(ctx, [/api\\//, /route\\.[jt]s$/, /server\\.[jt]s$/, /controllers?\\//])) {\r\n addFound(area, 'Backend route evidence found', 'repo paths');\r\n } else {\r\n addMissing(area, 'Backend route evidence missing', 'repo paths');\r\n }\r\n\r\n if (\n hasDep(ctx, ['zod', 'joi', 'yup', 'valibot', '@sinclair/typebox', 'class-validator']) ||\n hasContent(ctx, [\n /\\bzod\\b/,\n /\\bjoi\\b/,\n /\\byup\\b/,\n /\\bvalibot\\b/,\n /from\\s+['\"]joi['\"]/,\n /require\\s*\\(\\s*['\"]joi['\"]\\s*\\)/,\n /\\.safeparse\\s*\\(/,\n /\\.parse\\s*\\(/,\n /request validation/\n ])\n ) {\n addFound(area, 'Input validation evidence found', 'non-secret scanned content');\r\n } else {\r\n addMissing(area, 'Input validation evidence missing', 'non-secret scanned content');\r\n }\r\n\r\n addManual(area, 'Production data behavior reviewed', 'manual product review');\r\n}\r\n\r\nfunction applyAppFlowRules(area: VerificationAreaSummary, ctx: VerificationContext): void {\r\n if (hasPath(ctx, [/onboarding/, /dashboard/, /account/, /settings/])) {\r\n addFound(area, 'Core app flow paths found', 'repo paths');\r\n } else {\r\n addMissing(area, 'Core app flow paths missing', 'repo paths');\r\n }\r\n\r\n if (hasContent(ctx, [/redirect\\(/, /router\\.push/, /navigate\\(/])) {\r\n addFound(area, 'Navigation flow evidence found', 'non-secret scanned content');\r\n } else {\r\n addMissing(area, 'Navigation flow evidence missing', 'non-secret scanned content');\r\n }\r\n\r\n addManual(area, 'End-to-end user journey checked', 'manual product review');\r\n}\r\n\r\nfunction applyErrorHandlingRules(area: VerificationAreaSummary, ctx: VerificationContext): void {\n if (\n ctx.scan.stackSignals.hasErrorBoundary ||\n hasPath(ctx, [/error\\.[jt]sx?$/, /error-boundary/i, /errorboundary/i]) ||\n hasContent(ctx, [/componentdidcatch/i, /\\berrorboundary\\b/i, /react\\.component/i])\n ) {\n addFound(area, 'Error boundary evidence found', 'repo evidence');\n } else {\n addMissing(area, 'Error boundary evidence missing', 'repo evidence');\r\n }\r\n\r\n if (hasContent(ctx, [/try\\s*{/, /\\.catch\\s*\\(/, /throw new error/])) {\r\n addFound(area, 'Runtime error handling evidence found', 'non-secret scanned content');\r\n } else {\r\n addMissing(area, 'Runtime error handling evidence missing', 'non-secret scanned content');\r\n }\r\n\n addManual(area, 'Production failure paths reviewed', 'manual product review');\n}\n\nfunction applyProductionConnectionEvidence(\n byArea: VerificationSummary['byArea'],\n productionConnections: ProductionConnectionSummaryPayload\n): void {\n const summaries = collectProductionConnectionSummaries(productionConnections);\n\n for (const summary of summaries) {\n if (!summary || summary.source !== 'detected' || !summary.provider) {\n continue;\n }\n\n const area = byArea[summary.area as VerificationArea];\n if (!area) {\n continue;\n }\n\n const provider = providerLabel(summary.provider);\n const detail = summary.signals.length > 0 ? summary.signals.slice(0, 4).join('; ') : undefined;\n addFound(area, `${provider} detected by scanner`, 'production connection scanner', detail);\n\n if (summary.status.includes('needs-env')) {\n addMissing(area, `${provider} env evidence missing`, 'production connection scanner');\n }\n if (summary.status.includes('needs-webhook')) {\n addMissing(area, `${provider} webhook evidence missing`, 'production connection scanner');\n }\n }\n}\n\nfunction collectProductionConnectionSummaries(\n productionConnections: ProductionConnectionSummaryPayload\n): ProductionConnectionSummary[] {\n const seen = new Set<string>();\n const summaries: ProductionConnectionSummary[] = [];\n\n function add(summary: ProductionConnectionSummary | undefined): void {\n if (!summary || !summary.provider) {\n return;\n }\n const key = `${summary.area}:${summary.provider}:${summary.source}`;\n if (seen.has(key)) {\n return;\n }\n seen.add(key);\n summaries.push(summary);\n }\n\n for (const summary of Object.values(productionConnections.byArea)) {\n add(summary);\n }\n for (const summary of productionConnections.items) {\n add(summary);\n }\n for (const summary of productionConnections.stackRow) {\n add(summary);\n }\n\n return summaries;\n}\n\nfunction providerLabel(provider: string): string {\n return PROVIDER_LABELS[provider] ?? provider.replace(/(^|-)([a-z])/g, (_: string, prefix: string, letter: string) =>\n `${prefix === '-' ? ' ' : ''}${letter.toUpperCase()}`\n );\n}\n", "/** Stack-map provider choices \u2014 keep in sync with `STACK_MAP_PROVIDER_OPTIONS` in `media/station.js`. */\r\n\r\nexport type StackMapProviderOption = {\r\n name: string;\r\n toolName: string;\r\n description: string;\r\n};\r\n\r\nexport const STACK_MAP_PROVIDER_OPTIONS: Record<string, StackMapProviderOption[]> = {\r\n appFlow: [\r\n { name: 'Figma', toolName: 'Figma', description: 'Map flows, screens, and onboarding states' },\r\n { name: 'Storybook', toolName: 'Storybook', description: 'Component states and UI variants' },\r\n { name: 'Product Spec', toolName: 'product-spec', description: 'PRD, acceptance criteria, and success goals' },\r\n { name: 'Route Map', toolName: 'route-map', description: 'Routes, navigation, and protected paths' }\r\n ],\r\n frontend: [\r\n { name: 'React', toolName: 'React', description: 'Component UI and client state' },\r\n { name: 'Vue', toolName: 'Vue', description: 'Vue or Nuxt product UI' },\r\n { name: 'Svelte', toolName: 'Svelte', description: 'SvelteKit routes and components' },\r\n { name: 'Angular', toolName: 'Angular', description: 'Angular components and router' }\r\n ],\r\n backend: [\r\n { name: 'Node.js', toolName: 'Node.js', description: 'API routes and server behavior' },\r\n { name: 'Python / FastAPI', toolName: 'Python', description: 'Python API services and validation' },\r\n { name: 'Rails', toolName: 'Rails', description: 'Rails routes, controllers, and models' },\r\n { name: 'Go', toolName: 'Go', description: 'Go HTTP handlers and services' }\r\n ],\r\n security: [\r\n { name: 'Rate limiting', toolName: 'rate-limit', description: 'Protect API routes from abuse and retry loops' },\r\n { name: 'Bot protection', toolName: 'bot protection', description: 'Screen bots before expensive flows' },\r\n { name: 'Secrets hygiene', toolName: 'secrets hygiene', description: 'Keep env examples and secret files safe' }\r\n ],\r\n auth: [\r\n { name: 'Clerk', toolName: 'Clerk', description: 'Managed auth' },\r\n { name: 'Auth.js', toolName: 'Auth.js', description: 'Framework auth' },\r\n { name: 'Supabase Auth', toolName: 'Supabase Auth', description: 'Auth with Supabase' },\r\n { name: 'Auth0', toolName: 'Auth0', description: 'Enterprise identity and social login' },\r\n { name: 'Better Auth', toolName: 'better-auth', description: 'Type-safe auth in your codebase' }\r\n ],\r\n database: [\r\n { name: 'Supabase', toolName: 'Supabase', description: 'Postgres + auth + storage' },\r\n { name: 'Neon', toolName: 'Neon', description: 'Serverless Postgres' },\r\n { name: 'Turso', toolName: 'Turso', description: 'Edge SQLite' },\r\n { name: 'MongoDB', toolName: 'MongoDB', description: 'Document database' },\r\n { name: 'PlanetScale', toolName: 'PlanetScale', description: 'Serverless MySQL' }\r\n ],\r\n payments: [\r\n { name: 'Stripe', toolName: 'Stripe', description: 'Global standard' },\r\n { name: 'Paddle', toolName: 'Paddle', description: 'MoR subscriptions' },\r\n { name: 'Polar', toolName: 'Polar', description: 'Developer-native MoR billing' },\r\n { name: 'Lemon Squeezy', toolName: 'Lemon Squeezy', description: 'Digital products and SaaS billing' }\r\n ],\r\n deployment: [\r\n { name: 'Vercel', toolName: 'Vercel', description: 'Preview, env, domains' },\r\n { name: 'Netlify', toolName: 'Netlify', description: 'Static and serverless deploy' },\r\n { name: 'Render', toolName: 'Render', description: 'Simple web services and background jobs' },\r\n { name: 'Railway', toolName: 'Railway', description: 'Fast deploy loops and managed infra' },\r\n { name: 'Cloudflare', toolName: 'Cloudflare', description: 'Pages, Workers, DNS, and edge stack' },\r\n { name: 'AWS', toolName: 'AWS', description: 'Cloud infrastructure' }\r\n ],\r\n landing: [\r\n { name: 'Supabase', toolName: 'Supabase', description: 'Waitlist and onboarding data' },\r\n { name: 'PostHog', toolName: 'PostHog', description: 'Activation tracking' }\r\n ],\r\n monitoring: [\r\n { name: 'Sentry', toolName: 'Sentry', description: 'Errors and replay' },\r\n { name: 'PostHog', toolName: 'PostHog', description: 'Analytics and events' },\r\n { name: 'LogRocket', toolName: 'LogRocket', description: 'Session replay' }\r\n ],\r\n testing: [\r\n { name: 'Vitest', toolName: 'Vitest', description: 'Unit coverage' },\r\n { name: 'Playwright', toolName: 'Playwright', description: 'Browser flows' },\r\n { name: 'GitHub', toolName: 'GitHub', description: 'Actions CI and PR checks' },\r\n { name: 'GitLab', toolName: 'GitLab', description: 'Pipelines and merge checks' }\r\n ],\r\n errorHandling: [\r\n { name: 'Sentry', toolName: 'Sentry', description: 'Exception capture' },\r\n { name: 'PostHog', toolName: 'PostHog', description: 'Error events' }\r\n ]\r\n};\r\n\r\nexport function stackMapProviderOptionsForArea(\r\n areaKey: string\r\n): Array<{ provider: string; label: string; description: string }> {\r\n const rows = STACK_MAP_PROVIDER_OPTIONS[areaKey] ?? [];\r\n return rows.slice(0, 6).map((row) => ({\r\n provider: row.toolName,\r\n label: row.name,\r\n description: row.description\r\n }));\r\n}\r\n", "import { stackMapProviderOptionsForArea } from '../../../../src/station/stackMapProviderOptions';\r\nimport type { CliScanArtifact } from '../types';\r\n\r\nconst STACK_MAP_AREAS = [\r\n 'appFlow',\r\n 'frontend',\r\n 'backend',\r\n 'auth',\r\n 'database',\r\n 'payments',\r\n 'deployment',\r\n 'monitoring',\r\n 'security',\r\n 'testing',\r\n 'landing',\r\n 'errorHandling'\r\n] as const;\r\n\r\n/** Ensures report UI has the same provider lists as the VS Code extension (stack map). */\r\nexport function hydrateArtifactForReport(artifact: CliScanArtifact): CliScanArtifact {\r\n const providerOptions = { ...(artifact.providerOptions ?? {}) };\r\n for (const area of STACK_MAP_AREAS) {\r\n providerOptions[area] = stackMapProviderOptionsForArea(area);\r\n }\r\n return { ...artifact, providerOptions };\r\n}\r\n", "import { join } from 'node:path';\r\nimport { deepScanWorkspace } from '../../../src/station/fileScanner';\r\nimport {\r\n createStationOrchestrator,\r\n isManagedRequiredResult,\r\n isManagedSessionInvalidResult,\r\n isScanLimitResult,\r\n type StationRunResult\r\n} from '../../../src/station/orchestrator';\r\nimport { runManagedStation } from '../../../src/station/backendClient';\r\nimport type { ProductionConnectionChoices } from '../../../src/station/productionConnections';\r\nimport { hydrateArtifactForReport } from './report/hydrateArtifact';\r\nimport type { CliScanArtifact, StationRunSuccess } from './types';\r\nimport { loadStackChoicesFile } from './config';\r\n\r\nfunction computeProductionCorePercent(missionGraph: StationRunResult['missionGraph']): number {\r\n const areas = missionGraph.areas ?? [];\r\n if (areas.length === 0) {\r\n return 0;\r\n }\r\n const sum = areas.reduce((acc, area) => acc + (area.readinessPercent ?? 0), 0);\r\n return Math.round(sum / areas.length);\r\n}\r\n\r\nfunction toArtifact(\r\n workspacePath: string,\r\n result: StationRunSuccess,\r\n selectedProviders: Record<string, string>\r\n): CliScanArtifact {\r\n return {\r\n version: 1,\r\n scannedAt: new Date().toISOString(),\r\n workspacePath,\r\n score: result.score,\r\n scoreLabel: result.scoreLabel,\r\n summary: result.summary,\r\n archetype: result.archetype,\r\n gaps: result.gaps,\n missionGraph: result.missionGraph,\n stackWiring: result.stackWiring,\n stackAutomation: result.stackAutomation,\n providerRegistry: result.providerRegistry,\n verificationSummary: result.verificationSummary,\r\n productionCorePercent: computeProductionCorePercent(result.missionGraph),\r\n selectedProviders,\r\n usage: result.usage\r\n };\r\n}\r\n\r\nasync function loadProductionChoices(workspacePath: string): Promise<ProductionConnectionChoices | undefined> {\r\n const file = await loadStackChoicesFile(workspacePath);\r\n if (Object.keys(file.choices).length === 0) {\r\n return undefined;\r\n }\r\n // The orchestrator normalizes this shape via `normalizeProductionChoice`.\r\n return file as unknown as ProductionConnectionChoices;\r\n}\r\n\r\nexport type RunScanOptions = {\r\n workspacePath?: string;\r\n accessToken: string;\r\n apiBaseUrl: string;\r\n};\r\n\r\nexport type RunScanResult =\r\n | { ok: true; artifact: CliScanArtifact }\r\n | { ok: false; kind: 'scan_limit'; upgradeUrl: string }\r\n | { ok: false; kind: 'auth_required'; message: string }\r\n | { ok: false; kind: 'session_invalid'; message: string }\r\n | { ok: false; kind: 'error'; message: string };\r\n\r\nexport async function runProjectScan(options: RunScanOptions): Promise<RunScanResult> {\r\n const workspacePath = options.workspacePath ?? process.cwd();\r\n const orchestrator = createStationOrchestrator({\r\n scanWorkspace: (root) => deepScanWorkspace(root),\r\n getManagedAccessToken: async () => options.accessToken,\r\n runManagedStation: async (token, payload) => runManagedStation(options.apiBaseUrl, token, payload),\r\n getProductionConnectionChoices: () => loadProductionChoices(workspacePath),\r\n isLocalStationFallbackAllowed: async () => false,\r\n fetchStationOutput: async () => {\r\n throw new Error('Local OpenAI fallback is disabled in the CLI. Use `viberaven login`.');\r\n }\r\n });\r\n\r\n try {\r\n const result = await orchestrator.run({\r\n workspaceRoot: workspacePath,\r\n prompt: 'Full station scan for CLI launch report',\r\n configuration: undefined\r\n });\r\n\r\n if (isScanLimitResult(result)) {\r\n return { ok: false, kind: 'scan_limit', upgradeUrl: result.upgradeUrl };\r\n }\r\n if (isManagedRequiredResult(result)) {\r\n return { ok: false, kind: 'auth_required', message: result.message };\r\n }\r\n if (isManagedSessionInvalidResult(result)) {\r\n return { ok: false, kind: 'session_invalid', message: result.message };\r\n }\r\n\r\n const stackFile = await loadStackChoicesFile(workspacePath);\r\n const selectedProviders: Record<string, string> = {};\r\n for (const [area, choice] of Object.entries(stackFile.choices)) {\r\n if (choice && typeof choice.provider === 'string') {\r\n selectedProviders[area] = choice.provider;\r\n }\r\n }\r\n const artifact = hydrateArtifactForReport(\r\n toArtifact(workspacePath, result as StationRunSuccess, selectedProviders)\r\n );\r\n return { ok: true, artifact };\r\n } catch (error) {\r\n const message = error instanceof Error ? error.message : String(error);\r\n return { ok: false, kind: 'error', message };\r\n }\r\n}\r\n\r\nexport function defaultPromptPath(workspacePath: string): string {\r\n return join(workspacePath, '.viberaven', 'last-scan.json');\r\n}\r\n", "import { copyFile, mkdir, writeFile } from 'node:fs/promises';\r\nimport { join } from 'node:path';\r\nimport type { CliScanArtifact } from './types';\r\nimport { generateAgentSummary } from './report/agentSummary';\r\nimport { generateReportHtml } from './report/reportHtml';\r\nimport { getBundledReportAssetsDir, REPORT_ASSET_FILES } from './report/reportAssets';\r\nimport { getProjectArtifactsDir } from './config';\r\nimport { sanitizeArtifactForDisk } from './sanitizeArtifact';\r\n\r\nexport interface WriteArtifactsOptions {\r\n artifact: CliScanArtifact;\r\n cwd?: string;\r\n}\r\n\r\nexport interface WriteArtifactsResult {\r\n dir: string;\r\n jsonPath: string;\r\n summaryPath: string;\r\n reportPath: string;\r\n reportAssetsDir: string;\r\n}\r\n\r\nasync function copyReportAssets(reportAssetsDir: string): Promise<void> {\r\n const sourceDir = getBundledReportAssetsDir();\r\n await mkdir(join(reportAssetsDir, 'assets'), { recursive: true });\r\n\r\n for (const rel of REPORT_ASSET_FILES) {\r\n await copyFile(join(sourceDir, rel), join(reportAssetsDir, rel));\r\n }\r\n}\r\n\r\nexport async function writeScanArtifacts(options: WriteArtifactsOptions): Promise<WriteArtifactsResult> {\r\n const cwd = options.cwd ?? options.artifact.workspacePath;\r\n const dir = getProjectArtifactsDir(cwd);\r\n await mkdir(dir, { recursive: true });\r\n\r\n const jsonPath = join(dir, 'last-scan.json');\r\n const summaryPath = join(dir, 'agent-summary.md');\r\n const reportPath = join(dir, 'report.html');\r\n const reportAssetsDir = join(dir, 'report');\r\n\r\n const safe = sanitizeArtifactForDisk(options.artifact);\r\n const json = `${JSON.stringify(safe, null, 2)}\\n`;\r\n const summary = generateAgentSummary(safe);\r\n const html = generateReportHtml(safe);\r\n\r\n await copyReportAssets(reportAssetsDir);\r\n await writeFile(jsonPath, json, 'utf-8');\r\n await writeFile(summaryPath, summary, 'utf-8');\r\n await writeFile(reportPath, html, 'utf-8');\r\n\r\n return { dir, jsonPath, summaryPath, reportPath, reportAssetsDir };\r\n}\r\n", "import type { CliScanArtifact } from '../types';\r\nimport type { Gap } from '../../../../src/station/types';\r\n\r\nconst SEVERITY_ORDER: Record<Gap['severity'], number> = {\r\n critical: 0,\r\n warning: 1,\r\n info: 2\r\n};\r\n\r\nfunction sortGaps(gaps: Gap[]): Gap[] {\r\n return [...gaps].sort((a, b) => {\r\n const sev = SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity];\r\n if (sev !== 0) {\r\n return sev;\r\n }\r\n return a.title.localeCompare(b.title);\r\n });\r\n}\r\n\r\nexport function generateAgentSummary(artifact: CliScanArtifact): string {\r\n const lines: string[] = [];\r\n const topGaps = sortGaps(artifact.gaps).slice(0, 8);\r\n\r\n lines.push('# VibeRaven agent summary', '');\r\n lines.push(`Scanned: \\`${artifact.workspacePath}\\``);\r\n lines.push(`At: ${artifact.scannedAt}`);\r\n lines.push(\r\n `Production core: **${artifact.productionCorePercent}%** \u00B7 Model score: **${artifact.score}** (${artifact.scoreLabel})`\r\n );\r\n lines.push('');\r\n lines.push('## Summary');\r\n lines.push(artifact.summary || '_No summary returned._');\r\n lines.push('');\r\n lines.push('## Mission map (repo wiring)');\r\n lines.push('');\r\n lines.push('| Area | Provider | Readiness | Notes |');\r\n lines.push('|------|----------|-----------|-------|');\r\n\r\n for (const area of artifact.missionGraph.areas ?? []) {\r\n for (const mission of area.providerMissions) {\r\n const failed = mission.checks.filter(\r\n (c) => c.status === 'missing' || c.status === 'failed' || c.status === 'needs-connection'\r\n ).length;\r\n const notes =\r\n failed > 0\r\n ? `${failed} open check${failed === 1 ? '' : 's'}`\r\n : `${mission.readinessPercent}% repo checks`;\r\n lines.push(\r\n `| ${area.label} | ${mission.providerLabel} | ${mission.readinessPercent}% | ${notes} |`\r\n );\r\n }\r\n }\r\n\r\n lines.push('');\r\n lines.push('## Top launch gaps (model)');\r\n if (topGaps.length === 0) {\r\n lines.push('_No model gaps returned \u2014 rely on mission map checks above._');\r\n } else {\r\n topGaps.forEach((gap, index) => {\r\n lines.push(\r\n `${index + 1}. **${gap.title}** (\\`${gap.id}\\`, ${gap.severity}, map: \\`${gap.primaryMapCategory}\\`)`\r\n );\r\n lines.push(` - ${gap.detail}`);\r\n lines.push(` - Prompt: \\`viberaven prompt --gap ${gap.id}\\``);\r\n });\r\n }\r\n\r\n lines.push('');\r\n lines.push('## Agent workflow');\r\n lines.push('1. Pick the highest-severity gap unless the user names an area or provider.');\r\n lines.push('2. Run `viberaven prompt --gap <id>` (or read `copyPrompt` from `last-scan.json`).');\r\n lines.push('3. Implement the fix in the repo.');\r\n lines.push('4. Run `npx -y @viberaven/cli@beta scan` again to verify readiness improved.');\r\n lines.push('5. Tell the user to open `.viberaven/report.html` for the visual mission map.');\r\n lines.push('');\r\n\r\n if (artifact.usage) {\r\n lines.push('## Account usage');\r\n lines.push(\r\n `- Plan: ${artifact.usage.plan} \u00B7 Scans used: ${artifact.usage.used}/${artifact.usage.limit} (${artifact.usage.period})`\r\n );\r\n lines.push('');\r\n }\r\n\r\n return `${lines.join('\\n')}\\n`;\r\n}\r\n", "import type { MissionArea } from '../../../../src/station/types';\n\nexport type ProviderMission = MissionArea['providerMissions'][number];\n\nexport function normalizeProviderToken(value: string): string {\n return value.toLowerCase().replace(/&/g, 'and').replace(/[^a-z0-9]+/g, '');\n}\n\nexport function missionMatchesProvider(mission: ProviderMission, provider: string): boolean {\n const current = normalizeProviderToken(provider);\n return normalizeProviderToken(mission.provider || mission.providerLabel || mission.key) === current ||\n normalizeProviderToken(mission.providerLabel || mission.provider || mission.key) === current;\n}\n\nexport function missionEvidenceScore(mission: ProviderMission): number {\n const repoVerified = mission.checks.filter((check) => check.evidenceClass === 'repo-verified' || check.status === 'passed').length;\n const missing = mission.checks.filter((check) =>\n check.evidenceClass === 'missing-repo-fix' || check.status === 'missing' || check.status === 'failed'\n ).length;\n return repoVerified * 100 + (mission.readinessPercent ?? 0) - missing;\n}\n\nexport function preferredMissionForArea(area: MissionArea | undefined, selectedProvider: string): ProviderMission | undefined {\n const missions = area?.providerMissions ?? [];\n if (missions.length === 0) {\n return undefined;\n }\n const selected = selectedProvider ? missions.find((mission) => missionMatchesProvider(mission, selectedProvider)) : undefined;\n if (selected) {\n return selected;\n }\n return [...missions].sort((a, b) => missionEvidenceScore(b) - missionEvidenceScore(a))[0] ?? missions[0];\n}\n\nexport function openChecksForMission(mission: ProviderMission | undefined): number {\n if (!mission) {\n return 0;\n }\n return mission.checks.filter((check) =>\n check.status === 'missing' || check.status === 'failed' || check.status === 'needs-connection'\n ).length;\n}\n", "/** Client-side panel renderer for static CLI reports (extension-style sidebar). */\r\n\r\n\r\n\r\nexport const PANEL_CLIENT_SCRIPT = `\r\n\r\n(function () {\r\n\r\n var artifact = JSON.parse(document.getElementById('scan-data').textContent);\r\n\r\n var defaultAreaKey = JSON.parse(document.getElementById('default-area-key').textContent);\r\n\r\n var logoPayload = JSON.parse(document.getElementById('provider-logos').textContent);\r\n\r\n var panel = document.getElementById('detail-panel');\r\n\r\n var areas = (artifact.missionGraph && artifact.missionGraph.areas) || [];\r\n\r\n var gaps = artifact.gaps || [];\r\n\r\n var providerOptions = artifact.providerOptions || {};\r\n\r\n var selectedProviders = Object.assign({}, artifact.selectedProviders || {});\n\n var projectProviders = Object.assign({}, artifact.selectedProviders || {});\n\n var stackAutomation = artifact.stackAutomation || {};\n\n var STACK_AREAS = { database: 1, auth: 1, payments: 1, deployment: 1, monitoring: 1, security: 1 };\n\r\n var CHOICE_HINTS = {\r\n\r\n appFlow: 'Choose flow focus',\r\n\r\n frontend: 'Choose frontend focus',\r\n\r\n backend: 'Choose backend focus',\r\n\r\n auth: 'Choose auth stack',\r\n\r\n database: 'Choose database stack',\r\n\r\n payments: 'Choose payment stack',\r\n\r\n deployment: 'Choose deployment stack',\r\n\r\n monitoring: 'Choose monitoring stack',\r\n\r\n security: 'Choose security control',\r\n\r\n testing: 'Choose coverage target',\r\n\r\n landing: 'Choose launch item',\r\n\r\n errorHandling: 'Choose reliability control'\r\n\r\n };\r\n\r\n var LABELS = {\r\n\r\n appFlow: 'App Flow', frontend: 'Frontend', backend: 'Backend / API', auth: 'Auth',\r\n\r\n database: 'Database', payments: 'Payments', deployment: 'Deployment', monitoring: 'Monitoring / Analytics',\r\n\r\n security: 'Security', testing: 'Testing', landing: 'Landing / Onboarding', errorHandling: 'Error Handling'\r\n\r\n };\r\n\r\n var MAX_GROUP_ITEMS = 6;\r\n\r\n\r\n\r\n function esc(s) {\r\n\r\n return String(s == null ? '' : s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');\r\n\r\n }\r\n\r\n\r\n\r\n function attrEsc(s) {\r\n\r\n return esc(s).replace(/\"/g, '&quot;').replace(/'/g, '&#39;');\r\n\r\n }\r\n\r\n\r\n\r\n function normKey(p) {\r\n\r\n if (!p) return '';\r\n\r\n var raw = String(p).trim().toLowerCase();\r\n\r\n var compact = raw.replace(/[^a-z0-9]+/g, '');\r\n\r\n if (logoPayload.aliases[raw]) return logoPayload.aliases[raw];\r\n\r\n if (logoPayload.aliases[compact]) return logoPayload.aliases[compact];\r\n\r\n if (logoPayload.logos[compact]) return compact;\r\n\r\n var parts = raw.split('-').filter(Boolean);\r\n\r\n if (parts.length >= 2) {\r\n\r\n if (logoPayload.logos[parts[0]] || logoPayload.aliases[parts[0]]) return logoPayload.aliases[parts[0]] || parts[0];\r\n\r\n var two = parts.slice(0, 2).join('');\r\n\r\n if (logoPayload.logos[two] || logoPayload.aliases[two]) return logoPayload.aliases[two] || two;\r\n\r\n var twoHyphen = parts.slice(0, 2).join('-');\r\n\r\n if (logoPayload.aliases[twoHyphen]) return logoPayload.aliases[twoHyphen];\r\n\r\n }\r\n\r\n return compact;\r\n\r\n }\r\n\r\n\r\n\r\n function logoClass(p) {\r\n\r\n var key = normKey(p);\r\n\r\n if (!key) return '';\r\n\r\n var cls = ' provider-logo--' + key;\r\n\r\n if (logoPayload.brandKeys && logoPayload.brandKeys.indexOf(key) >= 0) {\r\n\r\n cls += ' provider-logo--brand';\r\n\r\n }\r\n\r\n return cls;\r\n\r\n }\r\n\r\n\r\n\r\n function logoHtml(p, label) {\r\n\r\n var key = normKey(p);\r\n\r\n if (key && logoPayload.inlineOnly && logoPayload.inlineOnly.indexOf(key) >= 0 && logoPayload.logos[key]) {\r\n\r\n return logoPayload.logos[key];\r\n\r\n }\r\n\r\n if (key && logoPayload.assetUrls && logoPayload.assetUrls[key]) {\r\n\r\n return '<img class=\"provider-logo__img\" src=\"' + esc(logoPayload.assetUrls[key]) + '\" alt=\"\" decoding=\"async\" data-provider-logo-key=\"' + esc(key) + '\" />';\r\n\r\n }\r\n\r\n if (key && logoPayload.iconUrls && logoPayload.iconUrls[key]) {\r\n\r\n return '<img class=\"provider-logo__img\" src=\"' + esc(logoPayload.iconUrls[key]) + '\" alt=\"\" decoding=\"async\" data-provider-logo-key=\"' + esc(key) + '\" />';\r\n\r\n }\r\n\r\n if (key && logoPayload.logos[key]) return logoPayload.logos[key];\r\n\r\n var t = (label || p || '?').trim();\r\n\r\n return '<span aria-hidden=\"true\">' + esc(t.slice(0, 2).toUpperCase()) + '</span>';\r\n\r\n }\r\n\r\n\r\n\r\n function benefitText(p, desc) {\r\n\r\n var key = normKey(p);\r\n\r\n return (key && logoPayload.benefits[key]) || desc || 'Useful path for this section.';\r\n\r\n }\r\n\r\n\r\n\r\n function panelTitle(areaKey, label) {\r\n\r\n return esc(String(label || LABELS[areaKey] || areaKey).toUpperCase()) +\r\n\r\n (STACK_AREAS[areaKey] ? ' STACK' : ' CONTROLS');\r\n\r\n }\r\n\r\n\r\n\r\n function evidenceBadgeHtml(missions) {\n\r\n var open = missions.flatMap(function (m) {\r\n\r\n return (m.checks || []).filter(function (c) {\r\n\r\n return c.status === 'missing' || c.status === 'failed' || c.status === 'needs-connection';\r\n\r\n });\r\n\r\n });\r\n\r\n var tone = open.length > 0 ? 'missing' : 'repo';\r\n\r\n var label = open.length > 0 ? 'Missing repo fixes' : 'Repo evidence found';\r\n\r\n return '<span class=\"studio-evidence-badge studio-evidence-badge--' + tone + '\">' + esc(label) + '</span>';\r\n\r\n }\n\n\n\n function automationFor(areaKey, mission, currentProvider) {\n\n var byKey = stackAutomation.byKey || {};\n\n if (mission && mission.key && byKey[mission.key]) return byKey[mission.key];\n\n var items = stackAutomation.items || [];\n\n var current = normKey(currentProvider || (mission && (mission.provider || mission.providerLabel)));\n\n return items.find(function (item) {\n\n return item.area === areaKey && (!current || normKey(item.provider || item.providerLabel) === current);\n\n }) || null;\n\n }\n\n\n\n function optionFor(areaKey, currentProvider) {\n\n var options = providerOptions[areaKey] || [];\n\n var current = normKey(currentProvider);\n\n return options.find(function (opt) {\n\n var p = opt.provider || opt.label;\n\n return p === currentProvider || normKey(p) === current;\n\n }) || null;\n\n }\n\n\n\n function sameProvider(a, b) {\n\n if (!a || !b) return false;\n\n return String(a).toLowerCase() === String(b).toLowerCase() || normKey(a) === normKey(b);\n\n }\n\n\n\n function projectProviderFor(areaKey, missions) {\n\n if (projectProviders[areaKey]) return projectProviders[areaKey];\n\n var mission = preferredMission(missions, '');\n\n return (mission && (mission.provider || mission.providerLabel)) || '';\n\n }\n\n\n\n function missionMatchesProvider(mission, currentProvider) {\n\n if (!mission || !currentProvider) return false;\n\n var current = normKey(currentProvider);\n\n return normKey(mission.provider || mission.providerLabel || mission.key) === current ||\n\n normKey(mission.providerLabel || mission.provider || mission.key) === current;\n\n }\n\n\n\n function missionForProvider(missions, currentProvider) {\n\n if (!missions || !missions.length) return null;\n\n if (!currentProvider) return missions[0];\n\n return missions.find(function (mission) {\n\n return missionMatchesProvider(mission, currentProvider);\n\n }) || null;\n\n }\n\n function missionEvidenceScore(mission) {\n\n if (!mission || !mission.checks) return 0;\n\n var repoVerified = mission.checks.filter(function (check) {\n\n return check.evidenceClass === 'repo-verified' || check.status === 'passed';\n\n }).length;\n\n var missing = mission.checks.filter(function (check) {\n\n return check.evidenceClass === 'missing-repo-fix' || check.status === 'missing' || check.status === 'failed';\n\n }).length;\n\n return repoVerified * 100 + (mission.readinessPercent || 0) - missing;\n\n }\n\n\n\n function preferredMission(missions, selectedProvider) {\n\n if (!missions || !missions.length) return null;\n\n var selected = selectedProvider ? missionForProvider(missions, selectedProvider) : null;\n\n if (selected) return selected;\n\n return missions.slice().sort(function (a, b) {\n\n return missionEvidenceScore(b) - missionEvidenceScore(a);\n\n })[0] || missions[0];\n\n }\n\n\n\n function providerLabelFor(areaKey, currentProvider, mission, areaLabel) {\n\n var opt = optionFor(areaKey, currentProvider);\n\n return (opt && opt.label) || (mission && mission.providerLabel) || currentProvider || areaLabel;\n\n }\n\n\n\n function itemLines(items, fallback, includeEvidence) {\n\n if (!items || !items.length) return fallback;\n\n return items.map(function (item) {\n\n var evidence = includeEvidence && item.evidence && item.evidence.length\n\n ? ' (' + item.evidence.slice(0, 3).join('; ') + ')'\n\n : '';\n\n return '- ' + item.label + evidence + (item.promptHint && !includeEvidence ? ': ' + item.promptHint : '');\n\n }).join('\\\\n');\n\n }\n\n\n\n function stackPromptFromMission(mission, providerLabel) {\n\n if (!mission || !(mission.checks && mission.checks.length)) return '';\n\n var subject = mission.promptSubject || providerLabel || mission.providerLabel || 'this stack';\n\n var passed = [];\n\n var missing = [];\n\n var manual = [];\n\n mission.checks.forEach(function (check) {\n\n var item = { label: check.label, promptHint: check.promptHint, evidence: check.evidence || [] };\n\n if (check.evidenceClass === 'repo-verified' || check.status === 'passed') passed.push(item);\n\n else if (check.evidenceClass === 'manual-dashboard') manual.push(item);\n\n else if (check.evidenceClass === 'mcp-verifier') manual.push(item);\n\n else if (check.evidenceClass === 'missing-repo-fix' || check.status === 'missing' || check.status === 'failed') missing.push(item);\n\n });\n\n var total = passed.length + missing.length;\n\n return [\n\n 'Wire ' + subject + ' for this app safely.',\n\n '',\n\n 'Current ' + subject + ' readiness: ' + passed.length + '/' + Math.max(total, 1) + ' repo checks passed (' + (mission.readinessPercent || 0) + '%).',\n\n '',\n\n 'Repo evidence already found:',\n\n itemLines(passed, '- No ' + subject + ' checks passed yet.', true),\n\n '',\n\n 'Missing ' + subject + ' checks:',\n\n itemLines(missing, '- No missing ' + subject + ' checks were found by VibeRaven.', false),\n\n '',\n\n 'Manual checks that repo evidence cannot prove:',\n\n itemLines(manual, '- No manual dashboard checks were listed.', false),\n\n '',\n\n 'First inspect the existing package.json files, env examples, framework routes, provider helpers, and server/client boundaries before editing.',\n\n '',\n\n 'Implement:',\n\n '1. Close only the missing ' + subject + ' checks listed above.',\n\n '2. Follow the existing file structure and naming patterns.',\n\n '3. Keep provider secrets in server-only code and documented env templates.',\n\n '4. Keep external dashboard work explicit instead of claiming it from repo evidence.',\n\n '',\n\n 'Constraints:',\n\n '- Do not rewrite unrelated auth, payments, UI, billing, deployment, or analytics code.',\n\n '- Do not expose secret keys to browser code, public env variables, or client-executed files.',\n\n '- Do not claim external provider dashboard setup is complete from repo evidence alone.',\n\n '',\n\n 'Verification:',\n\n '- Run the relevant TypeScript/build/test command for this repo.',\n\n '- Confirm VibeRaven can rescan and move the missing checks to passed where repo evidence exists.',\n\n '- Summarize what changed and what still requires manual provider dashboard verification.'\n\n ].join('\\\\n');\n\n }\n\r\n\r\n\r\n function choiceTilesHtml(areaKey, currentProvider, missions, evidenceMissions) {\n\r\n var options = providerOptions[areaKey];\r\n\r\n if (!options || !options.length) return '';\r\n\r\n var projectProvider = projectProviderFor(areaKey, missions);\n\n var tiles = options.map(function (opt) {\n\n var p = opt.provider || opt.label;\n\n var active = sameProvider(p, currentProvider);\n\n var inProject = sameProvider(p, projectProvider);\n\n var desc = opt.description || benefitText(p);\n\n var status = inProject ? 'Using now' : active ? 'Added to setup' : 'Use this path';\n\n return '<button type=\"button\" class=\"studio-choice-tile' + (active ? ' studio-choice-tile--selected' : '') + (inProject ? ' studio-choice-tile--in-project' : '') +\n\n '\" data-switch-area=\"' + esc(areaKey) + '\" data-switch-provider=\"' + esc(opt.provider) + '\" aria-pressed=\"' + (active ? 'true' : 'false') + '\">' +\n\r\n '<span class=\"studio-choice-tile__icon provider-logo' + logoClass(p) + '\" aria-hidden=\"true\">' + logoHtml(p, opt.label) + '</span>' +\r\n\r\n '<span class=\"studio-choice-tile__name\">' + esc(opt.label) + '</span>' +\r\n\r\n '<span class=\"studio-choice-tile__desc\">' + esc(desc) + '</span>' +\r\n\r\n '<span class=\"studio-choice-tile__status\">' + status + '</span>' +\n\n '</button>';\n\r\n }).join('');\r\n\r\n var hintLabel = CHOICE_HINTS[areaKey] || ('Choose ' + (LABELS[areaKey] || areaKey).toLowerCase());\r\n\r\n return '<div class=\"studio-setup-panel__hint\"><span>' + esc(hintLabel) + '</span>' + evidenceBadgeHtml(evidenceMissions || missions) + '</div>' +\n\r\n '<div class=\"studio-choice-list\" role=\"group\" aria-label=\"' + esc(hintLabel) + '\">' + tiles + '</div>';\r\n\r\n }\r\n\r\n\r\n\r\n function buildPrompt(areaKey, missions, providerLabel, automation) {\n\n if (automation) {\n\n if (automation.automationLevel === 'manual-only' && automation.verificationPrompt) return automation.verificationPrompt;\n\n if (automation.repoPrompt) return automation.repoPrompt;\n\n if (automation.promptRoutes && automation.promptRoutes['repo-fix'] && automation.promptRoutes['repo-fix'].body) {\n\n return automation.promptRoutes['repo-fix'].body;\n\n }\n\n }\n\n var areaGaps = missions[0] ? gaps.filter(function (g) { return g.primaryMapCategory === areaKey; }) : [];\n\n if (areaGaps[0] && areaGaps[0].copyPrompt) return areaGaps[0].copyPrompt;\n\n var missionPrompt = stackPromptFromMission(missions[0], providerLabel);\n\n if (missionPrompt) return missionPrompt;\n\r\n var missing = (missions[0] && missions[0].checks || []).filter(function (c) {\r\n\r\n return c.evidenceClass === 'missing-repo-fix' || c.status === 'missing' || c.status === 'failed';\r\n\r\n });\r\n\n if (missing[0] && missing[0].promptHint) return missing[0].promptHint;\n\n return setupPromptForProvider(areaKey, providerLabel);\n\n }\n\n\n\n function setupPromptForProvider(areaKey, providerLabel) {\n\n var areaLabel = LABELS[areaKey] || areaKey;\n\n var provider = providerLabel || areaLabel;\n\n return [\n\n 'Set up ' + provider + ' for the ' + areaLabel + ' area of this app safely.',\n\n '',\n\n 'First inspect package.json files, env examples, framework routes, provider helpers, server/client boundaries, and existing billing/auth/deployment patterns before editing.',\n\n '',\n\n 'Implement the smallest useful setup:',\n\n '1. Add the right ' + provider + ' package or SDK only if it is missing.',\n\n '2. Document required environment variables in safe examples, without reading or exposing real secrets.',\n\n '3. Add server-side integration points, route handlers, webhooks, or helpers that match this repo structure.',\n\n '4. Keep external provider dashboard setup explicit as a manual step.',\n\n '',\n\n 'Constraints:',\n\n '- Do not rewrite unrelated product, auth, payment, database, deployment, or analytics code.',\n\n '- Do not put secret keys in client code, public env variables, or browser-executed files.',\n\n '- Do not claim live provider configuration is complete from repo changes alone.',\n\n '',\n\n 'Verification:',\n\n '- Run the relevant TypeScript/build/test command for this repo.',\n\n '- Summarize repo changes and list dashboard/provider checks still needed.',\n\n '- Re-run VibeRaven so repo evidence can move from setup needed to verified.'\n\n ].join('\\\\n');\n\n\n }\n\r\n\r\n\r\n function setupActionsHtml(areaKey, missions, providerLabel, automation) {\n\n var prompt = buildPrompt(areaKey, missions, providerLabel, automation);\n\n var hasFixes = (missions[0] && missions[0].checks || []).some(function (c) {\n\r\n return c.evidenceClass === 'missing-repo-fix' || c.status === 'missing' || c.status === 'failed';\r\n\r\n });\r\n\r\n var isManualOnly = automation && automation.automationLevel === 'manual-only';\n\n var mcpCheck = (missions[0] && missions[0].checks || []).find(function (c) {\n\n return c.evidenceClass === 'mcp-verifier';\n\n });\n\n var mcpProvider = (automation && automation.mcpProvider) ||\n\n (mcpCheck && (mcpCheck.providerKey || mcpCheck.provider || normKey(providerLabel)));\n\n var supportsMcp = Boolean(mcpProvider);\n\n var title = esc(providerLabel || LABELS[areaKey] || areaKey) + (isManualOnly ? ' manual check' : hasFixes ? ' fix prompt' : ' setup');\n\n var meta = supportsMcp ? 'MCP verification available' : 'Prompt only';\n\n var copy = isManualOnly\n\n ? 'Repo fixes are already clear. Use the manual checklist for provider dashboard work, then rescan.'\n\n : hasFixes\n\n ? 'One prompt for the missing repo fixes above. Manual dashboard checks stay separate.'\n\n : supportsMcp\n\n ? 'Use this setup prompt when starting with this provider. The MCP helper is optional.'\n\n : 'Use this setup prompt when starting with this provider. No trusted MCP helper is available yet.';\n\n var label = isManualOnly ? 'Copy Checklist' : hasFixes ? 'Copy Fix Prompt' : 'Copy Setup Prompt';\n\n return '<section class=\"studio-setup-actions\" aria-label=\"Setup actions\">' +\n\n '<div class=\"studio-setup-actions__head\"><strong>' + title + '</strong><span>' + meta + '</span></div>' +\n\n '<p class=\"studio-setup-actions__copy\">' + esc(copy) + '</p>' +\n\n '<div class=\"studio-setup-actions__buttons\">' +\n\n '<button type=\"button\" class=\"studio-action-button studio-action-button--primary\" data-copy-prompt=\"' + attrEsc(prompt) + '\">' +\n\n label + '</button>' +\n\n '</div>' +\n\n (supportsMcp\n\n ? '<div class=\"studio-setup-actions__mcp-row\"><p class=\"studio-setup-actions__auth-note\"><strong>MCP verifier not configured</strong><br />Optional MCP verification stays read-only and must use credentials already configured by the IDE. VibeRaven does not read real .env files or store provider API keys.</p><button type=\"button\" class=\"studio-action-button\" data-copy-prompt=\"' + attrEsc('Use read-only ' + mcpProvider + ' MCP verification for ' + (providerLabel || LABELS[areaKey] || areaKey) + '. Report evidence only; do not mutate provider settings or claim dashboard setup from repo edits.') + '\">MCP Verify</button></div>'\n\n : '') +\n\n '</section>';\n\n }\n\n\n\n function addedSetupPathHtml(areaKey, currentProvider, providerLabel, missions) {\n\n var projectProvider = projectProviderFor(areaKey, missions);\n\n if (!currentProvider || sameProvider(currentProvider, projectProvider)) return '';\n\n return '<section class=\"studio-added-path\" aria-label=\"Added setup path\">' +\n\n '<div class=\"studio-added-path__title\">Added setup path</div>' +\n\n '<div class=\"studio-added-path__pill\">' +\n\n '<span class=\"studio-added-path__icon provider-logo' + logoClass(currentProvider) + '\" aria-hidden=\"true\">' + logoHtml(currentProvider, providerLabel) + '</span>' +\n\n '<strong>' + esc(providerLabel) + '</strong>' +\n\n '</div>' +\n\n '</section>';\n\n }\n\n\n\n function setupReadinessHtml(areaKey, currentProvider, providerLabel, missions, automation) {\n\n if (missions[0]) return '';\n\n var provider = providerLabel || currentProvider || (LABELS[areaKey] || areaKey);\n\n var repoItems = [\n\n { label: provider + ' package or SDK installed', detail: 'VibeRaven has not found repo evidence for this setup path yet.' },\n\n { label: provider + ' env names documented', detail: 'Use safe examples only. Do not expose real provider secrets.' },\n\n { label: provider + ' server integration or route found', detail: 'Add provider code on the server side before rescanning.' }\n\n ];\n\n var manualItems = [\n\n { label: 'Production ' + provider + ' account and product checked', detail: 'Dashboard confirmation stays manual unless a trusted MCP verifier is configured.' },\n\n { label: 'Production webhook or provider credentials checked', detail: 'Repo evidence cannot prove live provider settings by itself.' }\n\n ];\n\n var external = automation && automation.mcpProvider\n\n ? groupHtml('MCP verifier', [{ label: provider + ' MCP verifier available', detail: 'Use read-only MCP verification when already configured by the IDE.' }], 'external')\n\n : '';\n\n return '<section class=\"studio-verification studio-provider-readiness\" aria-label=\"' + esc(provider) + ' setup readiness\">' +\n\n '<h3 class=\"studio-verification__title\">' + esc(provider) + '</h3>' +\n\n readinessMetersHtml(0, 0, 'Not checked') +\n\n '<p class=\"studio-provider-readiness__note\">Provider live moves after MCP verification or manual dashboard confirmation. Repo scans cannot prove live provider state.</p>' +\n\n '<p class=\"studio-wiring__summary\">' + esc(provider) + ' is added as a setup path, but VibeRaven has not found repo evidence for it yet.</p>' +\n\n groupHtml('Repo setup needed', repoItems, 'missing') +\n\n external +\n\n groupHtml('Provider live check', manualItems, 'manual') +\n\n '</section>';\n\n }\n\n\n\n function readinessMetersHtml(repoPercent, providerPercent, providerStatus) {\n\n var repo = Math.max(0, Math.min(100, Math.round(repoPercent || 0)));\n\n var provider = Math.max(0, Math.min(100, Math.round(providerPercent || 0)));\n var providerValue = providerStatus || (provider + '%');\n\n return '<div class=\"studio-provider-readiness__meters\" aria-label=\"Provider readiness meters\">' +\n\n '<div class=\"studio-provider-readiness__meter-row\"><span>Repo &middot; files</span><span class=\"studio-provider-readiness__bar\" aria-hidden=\"true\"><span class=\"studio-provider-readiness__bar-fill\" style=\"width:' + repo + '%\"></span></span><strong>' + repo + '%</strong></div>' +\n\n '<div class=\"studio-provider-readiness__meter-row\"><span>Provider &middot; live</span><span class=\"studio-provider-readiness__bar\" aria-hidden=\"true\"><span class=\"studio-provider-readiness__bar-fill\" style=\"width:' + provider + '%\"></span></span><strong>' + esc(providerValue) + '</strong></div>' +\n\n '</div>';\n\n }\n\n\n\n function checkToItem(check) {\n\r\n var ev = (check.evidence && check.evidence[0]) ? check.evidence[0] : (check.promptHint || '');\r\n\r\n return { label: check.label, detail: ev };\r\n\r\n }\r\n\r\n\r\n\r\n function groupHtml(label, items, tone) {\n\r\n if (!items.length) return '';\r\n\r\n var slice = items.slice(0, MAX_GROUP_ITEMS);\r\n\r\n var rows = slice.map(function (item) {\n\n var title = item.detail ? ' title=\"' + esc(item.detail) + '\"' : '';\n\n return '<li class=\"studio-verification__item' + (tone === 'manual' ? ' studio-verification__item--manual' : '') + '\"' + title + '><span class=\"studio-verification__item-label\">' + esc(item.label) + '</span></li>';\n\n }).join('');\n\r\n var more = items.length > MAX_GROUP_ITEMS\r\n\r\n ? '<li class=\"studio-verification__item studio-verification__item--more\">+' + (items.length - MAX_GROUP_ITEMS) + ' more</li>'\r\n\r\n : '';\r\n\r\n return '<div class=\"studio-verification__group studio-verification__group--' + tone + '\">' +\r\n\r\n '<div class=\"studio-verification__group-title\"><strong>' + esc(label) + '</strong>' +\r\n\r\n '<span class=\"studio-verification__count\">' + items.length + '</span></div>' +\r\n\r\n '<ul class=\"studio-verification__list\">' + rows + more + '</ul></div>';\r\n\r\n }\r\n\r\n\r\n\r\n function missionBlockHtml(missions, providerLabel) {\r\n\r\n var mission = missions[0];\r\n\r\n if (!mission || !(mission.checks && mission.checks.length)) return '';\r\n\r\n var groups = {\r\n\r\n 'repo-verified': [],\r\n\r\n 'missing-repo-fix': [],\r\n\r\n 'mcp-verifier': [],\r\n\r\n 'manual-dashboard': []\r\n\r\n };\r\n\r\n mission.checks.forEach(function (check) {\r\n\r\n var bucket = groups[check.evidenceClass] ? check.evidenceClass : 'manual-dashboard';\r\n\r\n groups[bucket].push(checkToItem(check));\r\n\r\n });\r\n\r\n var actionable = groups['repo-verified'].length + groups['missing-repo-fix'].length;\n var manualTotal = groups['manual-dashboard'].length;\n var manualDone = mission.checks.filter(function (check) {\n\n return check.evidenceClass === 'manual-dashboard' && (check.status === 'passed' || check.status === 'user-confirmed');\n\n }).length;\n var providerPercent = manualTotal ? Math.round((manualDone / manualTotal) * 100) : 0;\n var providerValue = manualTotal ? (manualDone > 0 ? providerPercent + '%' : 'Not checked') : 'No live checks';\n\n var summary =\n\r\n 'Stack scanner: ' + groups['repo-verified'].length + ' / ' + Math.max(actionable, 1) +\r\n\r\n ' repo checks verified (' + (mission.readinessPercent || 0) + '%).';\r\n\r\n if (groups['missing-repo-fix'].length > 0) {\r\n\r\n summary += ' Fix ' + groups['missing-repo-fix'].length + ' repo item' +\r\n\r\n (groups['missing-repo-fix'].length === 1 ? '' : 's') + ', then rescan.';\r\n\r\n }\r\n\r\n var body =\r\n\r\n groupHtml('Repo verified', groups['repo-verified'], 'found') +\r\n\r\n groupHtml('Stack fixes needed', groups['missing-repo-fix'], 'missing') +\r\n\r\n groupHtml('MCP verifier', groups['mcp-verifier'], 'external') +\r\n\r\n groupHtml('Manual dashboard check', groups['manual-dashboard'], 'manual');\r\n\r\n if (!body) return '';\r\n\r\n return '<section class=\"studio-verification studio-wiring studio-mission-graph\" aria-label=\"Mission evidence\">' +\n\n '<h3 class=\"studio-verification__title\">' + esc(providerLabel || mission.providerLabel || 'Detected evidence') + '</h3>' +\n\n readinessMetersHtml(mission.readinessPercent || 0, providerPercent, providerValue) +\n\n '<p class=\"studio-provider-readiness__note\">Provider live moves after MCP verification or manual dashboard confirmation. Repo scans cannot prove live provider state.</p>' +\n\n '<p class=\"studio-wiring__summary\">' + esc(summary) + '</p>' + body + '</section>';\n\n }\n\r\n\r\n\r\n function render(areaKey, providerOverride) {\n\n if (providerOverride) selectedProviders[areaKey] = providerOverride;\n\n var area = areas.find(function (a) { return a.key === areaKey; });\n\r\n document.querySelectorAll('.studio-node').forEach(function (n) {\r\n\r\n var selected = n.getAttribute('data-area-key') === areaKey;\r\n\r\n n.classList.toggle('studio-node--selected', selected);\r\n\r\n n.setAttribute('aria-pressed', selected ? 'true' : 'false');\r\n\r\n });\r\n\r\n var label = (area && area.label) || LABELS[areaKey] || areaKey;\n\n var missions = (area && area.providerMissions) || [];\n\n var selectedBeforeRender = selectedProviders[areaKey] || '';\n\n var defaultMission = preferredMission(missions, selectedBeforeRender);\n\n var current = selectedProviders[areaKey] ||\n\n (defaultMission && (defaultMission.provider || defaultMission.providerLabel)) || '';\n\n var mission = missionForProvider(missions, current) || (!selectedBeforeRender ? defaultMission : null);\n\n var panelMissions = mission ? [mission] : [];\n\n var providerLabel = providerLabelFor(areaKey, current, mission, label);\n\n var automation = automationFor(areaKey, mission, current);\n\r\n\r\n\r\n panel.innerHTML =\r\n\r\n '<div class=\"studio-setup-panel__inner\">' +\r\n\r\n '<div class=\"studio-setup-panel__head\">' +\r\n\r\n '<div class=\"studio-setup-panel__title\">' + panelTitle(areaKey, label) + '</div>' +\r\n\r\n '</div>' +\r\n\r\n choiceTilesHtml(areaKey, current, missions, panelMissions) +\n\n addedSetupPathHtml(areaKey, current, providerLabel, missions) +\n\n setupActionsHtml(areaKey, panelMissions, providerLabel, automation) +\n\n setupReadinessHtml(areaKey, current, providerLabel, panelMissions, automation) +\n\n missionBlockHtml(panelMissions, providerLabel) +\n\r\n '</div>';\r\n\r\n\r\n\r\n panel.querySelectorAll('[data-copy-prompt]').forEach(function (btn) {\r\n\r\n btn.addEventListener('click', function () {\r\n\r\n var text = btn.getAttribute('data-copy-prompt') || '';\r\n\r\n navigator.clipboard.writeText(text).then(function () {\r\n\r\n var label = btn.textContent;\r\n\r\n btn.textContent = 'Copied';\r\n\r\n setTimeout(function () { btn.textContent = label; }, 1200);\r\n\r\n });\r\n\r\n });\r\n\r\n });\r\n\r\n\r\n\r\n panel.querySelectorAll('[data-switch-provider]').forEach(function (btn) {\n\n btn.addEventListener('click', function () {\n\n var a = btn.getAttribute('data-switch-area');\n\n var p = btn.getAttribute('data-switch-provider');\n\n render(a, p);\n\n });\n\n });\r\n\r\n }\r\n\r\n\r\n\r\n document.querySelectorAll('.studio-node').forEach(function (n) {\r\n\r\n n.addEventListener('click', function () { render(n.getAttribute('data-area-key')); });\r\n\r\n });\r\n\r\n\r\n\r\n document.addEventListener(\r\n\r\n 'error',\r\n\r\n function (ev) {\r\n\r\n var img = ev.target;\r\n\r\n if (!img || !img.classList || !img.classList.contains('provider-logo__img')) return;\r\n\r\n var key = img.getAttribute('data-provider-logo-key');\r\n\r\n if (!key || !logoPayload.logos[key]) return;\r\n\r\n var wrap = document.createElement('span');\r\n\r\n wrap.innerHTML = logoPayload.logos[key];\r\n\r\n var svg = wrap.firstElementChild;\r\n\r\n if (svg) img.replaceWith(svg);\r\n\r\n },\r\n\r\n true\r\n\r\n );\r\n\r\n\r\n\r\n render(defaultAreaKey);\r\n\r\n})();\r\n\r\n`;\r\n\r\n\r\n", "/** Provider logo SVGs \u2014 kept in sync with `media/station.js` `providerLogoSvg()`. */\r\n\r\nconst PROVIDER_LOGOS: Record<string, string> = {\r\n supabase:\r\n '<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M13.8 2.4 5.6 13.1c-.5.7 0 1.7.9 1.7h4.7l-1 6.1c-.2 1 .9 1.6 1.5.8l8.1-10.8c.5-.7 0-1.7-.9-1.7h-4.7l1-6.1c.2-1-.8-1.6-1.4-.7Z\"/></svg>',\r\n clerk:\r\n '<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path fill=\"#6C47FF\" d=\"M19.2 12c0 3.9-3.1 7.1-7.1 7.1-3.2 0-5.9-2.1-6.8-5h2.9c.7 1.8 2.5 3.1 4.5 3.1 2.7 0 4.9-2.2 4.9-4.9S13.2 7.4 10.5 7.4c-2 0-3.8 1.2-4.5 3H3.3c.9-2.9 3.6-5 6.8-5 4 0 7.1 3.2 7.1 7.1Z\"/></svg>',\r\n authjs:\r\n '<svg viewBox=\"0 0 24 24\" preserveAspectRatio=\"xMidYMid meet\" aria-hidden=\"true\"><path fill=\"#412991\" d=\"M12 2 4 6.5v5.2c0 4.6 3.4 8.9 8 10.3 4.6-1.4 8-5.7 8-10.3V6.5L12 2Z\"/><path fill=\"#EB5424\" d=\"M12 2v18.5c-1.2-.4-2.3-1-3.3-1.7L12 2Z\"/><path fill=\"#FBC22C\" d=\"M12 2 15.3 18.8c-1-.7-2.1-1.3-3.3-1.7V2Z\"/></svg>',\r\n auth0:\r\n '<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><rect fill=\"#EB5424\" x=\"3\" y=\"3\" width=\"18\" height=\"18\" rx=\"3.2\"/><path fill=\"#ffffff\" d=\"M12 7.4c2.5 0 4.6 2.1 4.6 4.6S14.5 16.6 12 16.6 7.4 14.5 7.4 12 9.5 7.4 12 7.4Zm0 2.2a2.4 2.4 0 1 0 0 4.8 2.4 2.4 0 0 0 0-4.8Z\"/></svg>',\r\n 'better-auth':\r\n '<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><rect fill=\"#171717\" x=\"3\" y=\"3\" width=\"18\" height=\"18\" rx=\"4\"/><path fill=\"#ffffff\" d=\"M8 8h3v3H8V8Zm5 0h3v3h-3V8ZM8 13h3v3H8v-3Zm5 0h3v3h-3v-3Z\"/></svg>',\r\n polar:\r\n '<svg viewBox=\"0 0 29 29\" aria-hidden=\"true\"><path fill=\"#0062FF\" fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M9.077 23.057c4.801 3.25 11.328 1.992 14.577-2.808 3.25-4.801 1.993-11.328-2.808-14.578C16.045 2.422 9.519 3.679 6.269 8.48c-3.25 4.801-1.993 11.327 2.808 14.577Zm1.393.086c4.392 2.247 9.963.138 12.444-4.711 2.48-4.848.93-10.6-3.461-12.847-4.392-2.247-9.963-.138-12.443 4.711-2.481 4.848-.932 10.6 3.46 12.847Z\"/><path fill=\"#0062FF\" fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M11.722 24.29c3.965 1.29 8.628-2.118 10.417-7.613 1.788-5.495.024-10.996-3.94-12.286-3.964-1.29-8.628 2.118-10.416 7.613-1.789 5.495-.025 10.995 3.939 12.286Zm1.213-.418c3.355.716 6.982-2.961 8.102-8.212 1.12-5.252-.691-10.089-4.046-10.804-3.356-.716-6.983 2.96-8.103 8.212-1.12 5.251.692 10.088 4.047 10.804Z\"/><path fill=\"#0062FF\" fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M13.854 24.738c2.652.284 5.3-4.14 5.912-9.882.613-5.74-1.04-10.624-3.692-10.907-2.653-.283-5.3 4.141-5.913 9.882-.613 5.741 1.04 10.624 3.693 10.907Zm1.241-1.747c1.92-.031 3.415-3.917 3.34-8.68-.075-4.764-1.693-8.6-3.612-8.57-1.92.03-3.415 3.916-3.34 8.68.076 4.763 1.693 8.6 3.612 8.57Z\"/></svg>',\r\n 'lemon-squeezy':\r\n '<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path fill=\"currentColor\" d=\"M12 3c-3.2 2.8-5 5.8-5 8.6a5 5 0 1 0 10 0c0-2.8-1.8-5.8-5-8.6Zm0 14.2a1.6 1.6 0 1 1 0-3.2 1.6 1.6 0 0 1 0 3.2Z\"/></svg>',\r\n github:\r\n '<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path fill=\"currentColor\" d=\"M12 2C6.48 2 2 6.58 2 12.26c0 4.52 2.87 8.35 6.86 9.71.5.1.69-.22.69-.49 0-.24-.01-.87-.01-1.7-2.78.62-3.37-1.36-3.37-1.36-.45-1.17-1.11-1.48-1.11-1.48-.91-.64.07-.63.07-.63 1 .07 1.53 1.05 1.53 1.05.9 1.56 2.36 1.11 2.94.85.09-.67.35-1.11.63-1.37-2.22-.26-4.56-1.14-4.56-5.07 0-1.12.39-2.03 1.03-2.75-.1-.26-.45-1.3.1-2.7 0 0 .84-.28 2.75 1.05A9.2 9.2 0 0 1 12 6.84c.85 0 1.71.12 2.51.34 1.91-1.33 2.75-1.05 2.75-1.05.55 1.4.2 2.44.1 2.7.64.72 1.03 1.63 1.03 2.75 0 3.94-2.34 4.8-4.57 5.06.36.32.68.94.68 1.9 0 1.37-.01 2.47-.01 2.8 0 .27.18.6.7.49A10.03 10.03 0 0 0 22 12.26C22 6.58 17.52 2 12 2Z\"/></svg>',\r\n gitlab:\r\n '<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path fill=\"#FC6D26\" d=\"M23.2 9.4 12 2.2.8 9.4l1.4 8.2L12 21.8l9.8-4.2 1.4-8.2Z\"/><path fill=\"#E24329\" d=\"M12 2.2v7.1l3.8 1.9 1.8-5.5L12 2.2Z\"/><path fill=\"#FC6D26\" d=\"M12 10.2 7.7 12l1.8-5.5L12 2.2Z\"/><path fill=\"#FCA326\" d=\"M.8 9.4 12 21.8 7.7 12 12 10.2Z\"/><path fill=\"#FC6D26\" d=\"M12 10.2l4.3 1.8 6.1-2.6L12 2.2Z\"/></svg>',\r\n neon:\r\n '<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M5 4.5c0-1 .8-1.7 1.7-1.3l9.5 4.3c1.1.5 1.8 1.6 1.8 2.8v8.6c0 1-.8 1.7-1.7 1.3L6.8 15.9A3 3 0 0 1 5 13.1V4.5Zm4.1 4.1v5l4.9 2.2v-5L9.1 8.6Z\"/></svg>',\r\n planetscale:\r\n '<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path fill=\"currentColor\" d=\"M19.1 4.9A10 10 0 0 0 4.9 19.1L19.1 4.9Zm-12 16A10 10 0 0 0 20.9 7.1L7.1 20.9Z\"/></svg>',\r\n mongodb:\r\n '<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M12 2c3 3 4.8 6.2 4.8 9.6 0 4.2-2.2 7.1-4.8 9.9-2.6-2.8-4.8-5.7-4.8-9.9C7.2 8.2 9 5 12 2Zm0 5.2v10.2\"/></svg>',\r\n turso:\r\n '<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M4 7.5h16v3H4v-3Zm0 6h16v3H4v-3ZM7.5 4h9v3h-9V4Zm0 13h9v3h-9v-3Z\"/></svg>',\r\n stripe:\r\n '<svg viewBox=\"0 0 24 24\" preserveAspectRatio=\"xMidYMid meet\" aria-hidden=\"true\"><path fill=\"#635BFF\" d=\"M4.5 15.4c1.5.9 3.5 1.4 5.4 1.4 1.6 0 2.5-.4 2.5-1.2 0-.7-.7-1-3-1.5-3-.7-4.7-1.8-4.7-4.1 0-2.6 2.1-4.4 5.8-4.4 2.1 0 3.9.4 5.3 1.1v3.4a10 10 0 0 0-5.1-1.4c-1.5 0-2.2.4-2.2 1.1 0 .7.8 1 3 1.5 3.1.7 4.8 1.8 4.8 4.1 0 2.7-2.2 4.5-6.2 4.5-2.2 0-4.3-.5-5.6-1.3v-3.2Z\"/></svg>',\r\n paddle:\r\n '<svg viewBox=\"0 0 90 90\" aria-hidden=\"true\"><rect x=\"11\" y=\"11\" width=\"68\" height=\"68\" rx=\"17\" fill=\"#101318\"/><rect x=\"11.5\" y=\"11.5\" width=\"67\" height=\"67\" rx=\"16.5\" fill=\"none\" stroke=\"#343942\"/><path fill=\"#FFD21E\" d=\"M8.49991 17C8.51217 21.6945 12.3128 25.5001 17 25.5001C12.3128 25.5001 8.51217 29.3055 8.49991 34C8.48783 29.3055 4.68717 25.5001 0 25.5001C4.68717 25.5001 8.48783 21.6945 8.49991 17Z\" transform=\"translate(19.5 -31.5) scale(3)\"/></svg>',\r\n vercel:\r\n '<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M12 4 22 20H2L12 4Z\"/></svg>',\r\n netlify:\r\n '<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"m12 2 3.1 5.4 6.2 1.2-4.2 4.7.8 6.3-5.9-2.6-5.9 2.6.8-6.3-4.2-4.7 6.2-1.2L12 2Z\"/></svg>',\r\n aws:\r\n '<svg viewBox=\"0 0 24 24\" preserveAspectRatio=\"xMidYMid meet\" aria-hidden=\"true\"><path fill=\"#FF9900\" d=\"M6.763 10.582c4.95-2.283 10.563-2.283 15.475 0 .532.243.848.741.848 1.256 0 .532-.323 1.026-.85 1.256-4.912 2.283-10.525 2.283-15.474 0-.528-.23-.851-.724-.851-.279 0-.544.098-.754.243-4.95 2.283-10.563 2.283-15.475 0-.532-.243-.848-.741-.848-1.256 0-.532.323-1.026.85-1.256.228-.098.492-.196.754-.196.279 0 .544.098.754.243Z\"/><path fill=\"#FF9900\" d=\"M12 3.65c-2.772 0-5.027 1.147-5.027 2.553S9.228 8.756 12 8.756s5.027-1.147 5.027-2.553S14.772 3.65 12 3.65Z\"/></svg>',\r\n sentry:\r\n '<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M12 3 22 20H2L12 3Zm0 5.1L6.8 17h2.1l3.1-5.3 3.1 5.3h2.1L12 8.1Z\"/></svg>',\r\n posthog:\r\n '<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path fill=\"#1D4AFF\" d=\"M5 6h8.06c3.19 0 5.44 2.06 5.44 5.31S16.25 16.62 13.06 16.62H5V6Z\"/><path fill=\"#F54E00\" d=\"M4.13 3.94v4.5h3.94a2.25 2.25 0 0 0 0-4.5H4.13Z\"/><circle cx=\"13.5\" cy=\"11.81\" r=\"1.01\" fill=\"#F9BD2B\"/><path fill=\"#F54E00\" d=\"m16.39 9.49 1.88-1.13.79 1.2-2.03 1.28-.64-1.35Zm.34 4.61 2.33.83-.74 1.54-2.33-.98.74-1.39Z\"/></svg>',\r\n playwright:\r\n '<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path fill=\"#2EAD33\" d=\"M8.4 8.2 5.4 17.2h2.3l.8-2.8h2.7l.8 2.8h2.3L11.6 8.2H8.4Zm1.1 4.8.8-2.4.8 2.4H9.5Z\"/><path fill=\"#E2574C\" d=\"M15.6 8.2 12.6 17.2h2.3l.8-2.8h2.7l.8 2.8h2.3L18.8 8.2h-3.2Zm1.1 4.8.8-2.4.8 2.4h-1.6Z\"/><ellipse fill=\"#2EAD33\" cx=\"9.5\" cy=\"13.1\" rx=\"1.1\" ry=\"1.4\"/><ellipse fill=\"#E2574C\" cx=\"16.5\" cy=\"13.1\" rx=\"1.1\" ry=\"1.4\"/></svg>',\r\n logrocket:\r\n '<svg viewBox=\"0 0 24 24\" preserveAspectRatio=\"xMidYMid meet\" aria-hidden=\"true\"><rect x=\"2\" y=\"2\" width=\"20\" height=\"20\" rx=\"5\" fill=\"#764ABC\"/><path fill=\"#FFFFFF\" d=\"M12 7.4c2.7 0 4.9 2.2 4.9 4.9s-2.2 4.9-4.9 4.9-4.9-2.2-4.9-4.9 4.9-4.9 4.9-4.9Zm0 1.9a3 3 0 1 0 0 6 3 3 0 0 0 0-6Zm-3.2 7.4h6.4v1.5H8.8v-1.5Z\"/></svg>',\r\n figma:\r\n '<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M8.5 3h3.5v6H8.5a3 3 0 1 1 0-6Zm3.5 6h3.5a3 3 0 1 0 0-6H12v6Zm0 0h3.5a3 3 0 1 1 0 6H12V9Zm-3.5 0H12v6H8.5a3 3 0 1 1 0-6ZM8.5 15H12v2.5A3.5 3.5 0 1 1 8.5 15Z\"/></svg>',\r\n storybook:\r\n '<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M6.2 3.4 17.9 2l.7 18.1-12.4.7V3.4Zm8.7 3.2.3 2.4 1.7-1.3 1.7 1.1.3-3.4-4 .5v.7Zm-5.2 5.1c0 2 1.6 3.5 4.2 3.5 2.4 0 3.8-1.2 3.8-3 0-1.7-1.1-2.6-3.4-3l-1.2-.2c-.7-.1-1-.4-1-.8 0-.5.5-.8 1.3-.8.9 0 1.5.4 1.8 1.1l2.1-.8c-.5-1.4-1.8-2.2-3.8-2.2-2.3 0-3.8 1.2-3.8 2.9 0 1.6 1.1 2.5 3.3 2.9l1.2.2c.8.1 1.1.4 1.1.9 0 .6-.5.9-1.4.9-1.1 0-1.8-.5-2.1-1.3l-2.1.7Z\"/></svg>',\r\n 'product-spec':\r\n '<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M6 3.2h9.2L19 7v13.8H6V3.2Zm8.2 1.9v3h3l-3-3ZM8.4 10h7.2v1.7H8.4V10Zm0 3.2h7.2v1.7H8.4v-1.7Zm0 3.2h4.9v1.7H8.4v-1.7Z\"/></svg>',\r\n 'route-map':\r\n '<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M6.5 4.2a3 3 0 0 1 3 3c0 2-3 5.1-3 5.1s-3-3.1-3-5.1a3 3 0 0 1 3-3Zm0 1.8a1.2 1.2 0 1 0 0 2.4 1.2 1.2 0 0 0 0-2.4Zm11 5.8a3 3 0 0 1 3 3c0 2-3 5.1-3 5.1s-3-3.1-3-5.1a3 3 0 0 1 3-3Zm0 1.8a1.2 1.2 0 1 0 0 2.4 1.2 1.2 0 0 0 0-2.4ZM9.5 7h2.1c2.8 0 4.9 2 4.9 4.8h-2c0-1.7-1.2-2.8-2.9-2.8H9.5V7Zm4.9 10h-2.1c-2.8 0-4.9-2-4.9-4.8h2c0 1.7 1.2 2.8 2.9 2.8h2.1v2Z\"/></svg>',\r\n react:\r\n '<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><circle cx=\"12\" cy=\"12\" r=\"2.2\"/><ellipse cx=\"12\" cy=\"12\" rx=\"9\" ry=\"3.6\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.6\"/><ellipse cx=\"12\" cy=\"12\" rx=\"9\" ry=\"3.6\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.6\" transform=\"rotate(60 12 12)\"/><ellipse cx=\"12\" cy=\"12\" rx=\"9\" ry=\"3.6\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.6\" transform=\"rotate(120 12 12)\"/></svg>',\r\n vue: '<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M2.6 4h5.1L12 11.4 16.3 4h5.1L12 20 2.6 4Zm5.6 0L12 10.5 15.8 4h-2.7L12 5.9 10.9 4H8.2Z\"/></svg>',\r\n svelte:\r\n '<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M16.9 3.4a5.2 5.2 0 0 0-6.9 1.5L6.3 9.7a4.6 4.6 0 0 0 .8 6.4 5.1 5.1 0 0 0 6.9-1.2l.6-.8a1.6 1.6 0 0 0-.3-2.2 1.8 1.8 0 0 0-2.4.4l-.6.8a1.3 1.3 0 0 1-1.8.3 1.2 1.2 0 0 1-.2-1.6L13 7a1.3 1.3 0 0 1 1.8-.4c.5.4.7 1.1.3 1.6l-.3.4 2.8 2 .3-.4a4.7 4.7 0 0 0-1-6.8Zm-9.8 17.2a5.2 5.2 0 0 0 6.9-1.5l3.7-4.8a4.6 4.6 0 0 0-.8-6.4A5.1 5.1 0 0 0 10 9.1l-.6.8a1.6 1.6 0 0 0 .3 2.2 1.8 1.8 0 0 0 2.4-.4l.6-.8a1.3 1.3 0 0 1 1.8-.3 1.2 1.2 0 0 1 .2 1.6L11 17a1.3 1.3 0 0 1-1.8.4 1.2 1.2 0 0 1-.3-1.6l.3-.4-2.8-2-.3.4a4.7 4.7 0 0 0 1 6.8Z\"/></svg>',\r\n angular:\r\n '<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M12 2.5 20.5 5.6 19.2 17 12 21.5 4.8 17 3.5 5.6 12 2.5Zm0 4.2-5 11h2.4l1-2.4h3.2l1 2.4H17l-5-11Zm0 3.8 1.1 2.9h-2.2l1.1-2.9Z\"/></svg>',\r\n nodejs:\r\n '<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M12 2.5 20.2 7v10L12 21.5 3.8 17V7L12 2.5Zm-3.8 6.7v5.6h1.9v-3.1l3.8 3.1h1.9V9.2h-1.9v3.2l-3.8-3.2H8.2Z\"/></svg>',\r\n python:\r\n '<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M11.8 3c2.7 0 4.2.8 4.2 2.5V9H9.6A2.6 2.6 0 0 0 7 11.6V13H4.5C3.5 13 3 12.2 3 11c0-3.2 1.9-4.9 5.6-4.9h3.8V5H8.8V3.6A10 10 0 0 1 11.8 3Zm-1.4 1.5a.8.8 0 1 0 0 1.6.8.8 0 0 0 0-1.6ZM12.2 21c-2.7 0-4.2-.8-4.2-2.5V15h6.4a2.6 2.6 0 0 0 2.6-2.6V11h2.5c1 0 1.5.8 1.5 2 0 3.2-1.9 4.9-5.6 4.9h-3.8V19h3.6v1.4a10 10 0 0 1-3 .6Zm1.4-3.1a.8.8 0 1 0 0 1.6.8.8 0 0 0 0-1.6Z\"/></svg>',\r\n rails:\r\n '<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M3 17.7C5.8 9.5 11.7 5.2 21 4.8v3.1C13.5 8.3 8.7 11.6 6 18.5L3 17.7Zm4.6.7c2.1-5 5.9-7.5 11.4-7.9v2.4c-4.4.4-7.4 2.5-9 6.2l-2.4-.7Zm4.7.7c1.3-2.4 3.4-3.7 6.7-4.1v2.2c-2.2.4-3.6 1.3-4.5 2.6l-2.2-.7Z\"/></svg>',\r\n go: '<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M3 8.2h7.4v1.5H3V8.2Zm-1 3h7.4v1.5H2v-1.5Zm2 3h5.4v1.5H4v-1.5Zm10.5-6.1c3.1 0 5.5 2 5.5 4.6s-2.4 4.6-5.5 4.6-5.5-2-5.5-4.6 2.4-4.6 5.5-4.6Zm0 2.1c-1.7 0-3 1.1-3 2.5s1.3 2.5 3 2.5 3-1.1 3-2.5-1.3-2.5-3-2.5Zm5.1-2h2.4l-1.2 9h-2.4l1.2-9Z\"/></svg>',\r\n 'testing-library':\r\n '<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M7 3h10v4.2l-3.4 4.5 5.4 7.9c.5.8 0 1.9-1 1.9H6c-1 0-1.6-1.1-1-1.9l5.4-7.9L7 7.2V3Zm3 3.5 2 2.7 2-2.7H10Zm1.9 8.4-2.6 3.8h5.4l-2.8-3.8Z\"/></svg>',\r\n vitest:\r\n '<svg viewBox=\"0 0 24 24\" preserveAspectRatio=\"xMidYMid meet\" aria-hidden=\"true\"><path fill=\"#FCC72B\" d=\"M13.4 3 21 7.4 12 21 3 7.4 10.6 3l1.4 4.5L13.4 3Zm-1.4 7.3-2.1 4h4.2l-2.1-4Z\"/><path fill=\"#729B1B\" d=\"M12 10.3 9.9 14.3h4.2L12 10.3Z\"/></svg>',\r\n 'rate-limit':\r\n '<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M12 3a9 9 0 1 0 9 9h-3a6 6 0 1 1-1.8-4.3L13 11h8V3l-2.7 2.7A9 9 0 0 0 12 3Z\"/></svg>',\r\n 'bot-protection':\r\n '<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M12 2 20 6v6c0 5-3.5 8.6-8 10-4.5-1.4-8-5-8-10V6l8-4Zm-3 8h6v4H9v-4Zm1.5-3.2h3V10h-3V6.8Z\"/></svg>',\r\n 'secrets-hygiene':\r\n '<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M7 10V7a5 5 0 0 1 10 0v3h1.5v11h-13V10H7Zm3 0h4V7a2 2 0 0 0-4 0v3Z\"/></svg>'\r\n};\r\n\r\nconst ALIASES: Record<string, string> = {\r\n authjs: 'authjs',\r\n 'auth.js': 'authjs',\r\n nextauth: 'authjs',\r\n posthog: 'posthog',\r\n node: 'nodejs',\r\n nodejs: 'nodejs',\r\n 'node.js': 'nodejs',\r\n express: 'nodejs',\r\n expressjs: 'nodejs',\r\n supabase: 'supabase',\r\n clerk: 'clerk',\r\n stripe: 'stripe',\r\n vercel: 'vercel',\r\n 'supabase auth': 'supabase',\r\n supabaseauth: 'supabase',\r\n 'bot protection': 'bot-protection',\r\n botprotection: 'bot-protection',\r\n 'secrets hygiene': 'secrets-hygiene',\r\n secretshygiene: 'secrets-hygiene',\r\n 'rate limiting': 'rate-limit',\r\n ratelimiting: 'rate-limit',\r\n polar: 'polar',\r\n lemonsqueezy: 'lemon-squeezy',\r\n 'lemon squeezy': 'lemon-squeezy',\r\n 'lemon-squeezy': 'lemon-squeezy',\r\n github: 'github',\r\n gitlab: 'gitlab',\r\n auth0: 'auth0',\r\n 'better-auth': 'better-auth',\r\n betterauth: 'better-auth',\r\n 'mongodb atlas': 'mongodb',\r\n logrocket: 'logrocket',\r\n sentry: 'sentry',\r\n figma: 'figma',\r\n react: 'react',\r\n vitest: 'vitest',\r\n playwright: 'playwright',\r\n neon: 'neon',\r\n planetscale: 'planetscale',\r\n 'planet scale': 'planetscale',\r\n mongodb: 'mongodb',\r\n netlify: 'netlify',\r\n render: 'render',\r\n rendercom: 'render',\r\n railway: 'railway',\r\n railwayapp: 'railway',\r\n cloudflare: 'cloudflare',\r\n cloudflarepages: 'cloudflare',\r\n workers: 'cloudflare',\r\n aws: 'aws',\r\n paddle: 'paddle',\r\n turso: 'turso',\r\n vue: 'vue',\r\n svelte: 'svelte',\r\n angular: 'angular',\r\n python: 'python',\r\n rails: 'rails',\r\n go: 'go',\r\n storybook: 'storybook',\r\n productspec: 'product-spec',\r\n prd: 'product-spec',\r\n routemap: 'route-map',\r\n routes: 'route-map',\r\n ratelimit: 'rate-limit'\r\n};\r\n\r\n/** CDN slugs that 404 or resolve to the wrong brand \u2014 keep inline SVG in PROVIDER_LOGOS. */\r\nexport const INLINE_ONLY_LOGO_KEYS = new Set(['better-auth', 'paddle', 'polar']);\r\n\r\n/** Bundled SVGs under `report/assets/` \u2014 official marks; avoids CSS fill/squash on inline paths. */\r\nexport const PROVIDER_ASSET_FILES: Record<string, string> = {\r\n authjs: 'provider-authjs.svg',\r\n logrocket: 'provider-logrocket.svg',\r\n aws: 'provider-aws.svg'\r\n};\r\n\r\nconst REPORT_ASSET_PREFIX = 'report/assets';\r\n\r\nexport function providerAssetUrl(key: string): string | undefined {\r\n const file = PROVIDER_ASSET_FILES[key];\r\n return file ? `${REPORT_ASSET_PREFIX}/${file}` : undefined;\r\n}\r\n\r\nexport function providerAssetUrls(): Record<string, string> {\r\n return Object.fromEntries(\r\n Object.keys(PROVIDER_ASSET_FILES)\r\n .map((key) => [key, providerAssetUrl(key)])\r\n .filter((entry): entry is [string, string] => Boolean(entry[1]))\r\n ) as Record<string, string>;\r\n}\r\n\r\n/**\r\n * CDN brand marks (aligned with landing `stackIcons`) \u2014 clearer than tiny inline SVGs\r\n * in sidebar tiles and map nodes. Internal controls keep inline SVG only.\r\n */\r\nexport const PROVIDER_ICON_URLS: Record<string, string> = {\r\n supabase: 'https://cdn.simpleicons.org/supabase/3ECF8E',\r\n clerk: 'https://cdn.simpleicons.org/clerk/6C47FF',\r\n auth0: 'https://cdn.simpleicons.org/auth0/EB5424',\r\n neon: 'https://cdn.simpleicons.org/neon/00E599',\r\n planetscale: 'https://cdn.simpleicons.org/planetscale/000000',\r\n mongodb: 'https://cdn.simpleicons.org/mongodb/47A248',\r\n turso: 'https://cdn.simpleicons.org/turso/4FF8D2',\r\n 'lemon-squeezy': 'https://cdn.simpleicons.org/lemonsqueezy/FFC233',\r\n stripe: 'https://cdn.simpleicons.org/stripe/635BFF',\r\n github: 'https://cdn.simpleicons.org/github/181717',\r\n gitlab: 'https://cdn.simpleicons.org/gitlab/FC6D26',\r\n vercel: 'https://cdn.simpleicons.org/vercel/000000',\r\n netlify: 'https://cdn.simpleicons.org/netlify/00C7B7',\r\n render: 'https://cdn.simpleicons.org/render/46E3B7',\r\n railway: 'https://cdn.simpleicons.org/railway/0B0D0E',\r\n cloudflare: 'https://cdn.simpleicons.org/cloudflare/F38020',\r\n sentry: 'https://cdn.simpleicons.org/sentry/362D59',\r\n posthog: 'https://cdn.simpleicons.org/posthog/F54E00',\r\n playwright:\r\n 'https://cdn.jsdelivr.net/gh/devicons/devicon@latest/icons/playwright/playwright-original.svg',\r\n figma: 'https://cdn.simpleicons.org/figma/F24E1E',\r\n storybook: 'https://cdn.simpleicons.org/storybook/FF4785',\r\n react: 'https://cdn.simpleicons.org/react/61DAFB',\r\n vue: 'https://cdn.simpleicons.org/vuedotjs/4FC08D',\r\n svelte: 'https://cdn.simpleicons.org/svelte/FF3E00',\r\n angular: 'https://cdn.simpleicons.org/angular/DD0031',\r\n nodejs: 'https://cdn.simpleicons.org/nodedotjs/5FA04E',\r\n python: 'https://cdn.simpleicons.org/python/3776AB',\r\n rails: 'https://cdn.simpleicons.org/rubyonrails/D30001',\r\n go: 'https://cdn.simpleicons.org/go/00ADD8',\r\n 'testing-library': 'https://cdn.simpleicons.org/testinglibrary/E33332',\r\n vitest: 'https://cdn.simpleicons.org/vitest/FCC72B'\r\n};\r\n\r\n/** Logos with embedded brand colors \u2014 do not force `fill: currentColor` in the report. */\r\nexport const BRAND_LOGO_KEYS = new Set([\r\n 'auth0',\r\n 'authjs',\r\n 'aws',\r\n 'better-auth',\r\n 'clerk',\r\n 'gitlab',\r\n 'logrocket',\r\n 'auth0',\r\n 'paddle',\r\n 'playwright',\r\n 'polar',\r\n 'posthog',\r\n 'stripe',\r\n 'vitest'\r\n]);\r\n\r\nfunction resolveLogoKey(raw: string, compact: string): string {\r\n if (ALIASES[raw]) {\r\n return ALIASES[raw];\r\n }\r\n if (ALIASES[compact]) {\r\n return ALIASES[compact];\r\n }\r\n if (PROVIDER_LOGOS[compact]) {\r\n return compact;\r\n }\r\n\r\n const parts = raw.split('-').filter(Boolean);\r\n if (parts.length >= 2) {\r\n const first = parts[0];\r\n if (PROVIDER_LOGOS[first] || ALIASES[first]) {\r\n return ALIASES[first] ?? first;\r\n }\r\n const twoPart = parts.slice(0, 2).join('');\r\n if (PROVIDER_LOGOS[twoPart] || ALIASES[twoPart]) {\r\n return ALIASES[twoPart] ?? twoPart;\r\n }\r\n const twoHyphen = parts.slice(0, 2).join('-');\r\n if (ALIASES[twoHyphen]) {\r\n return ALIASES[twoHyphen];\r\n }\r\n }\r\n\r\n return compact;\r\n}\r\n\r\nexport function normalizeProviderKey(providerOrLabel: string | undefined): string {\r\n if (!providerOrLabel) {\r\n return '';\r\n }\r\n const raw = String(providerOrLabel).trim().toLowerCase();\r\n const compact = raw.replace(/[^a-z0-9]+/g, '');\r\n return resolveLogoKey(raw, compact);\r\n}\r\n\r\n/** Prefer mission provider keys like `vercel-deployment` and display labels. */\r\nexport function resolveProviderLogoKey(\r\n ...candidates: Array<string | undefined>\r\n): string {\r\n for (const candidate of candidates) {\r\n const key = normalizeProviderKey(candidate);\r\n if (key && PROVIDER_LOGOS[key]) {\r\n return key;\r\n }\r\n }\r\n for (const candidate of candidates) {\r\n const key = normalizeProviderKey(candidate);\r\n if (key) {\r\n return key;\r\n }\r\n }\r\n return '';\r\n}\r\n\r\nexport function providerLogoClass(\r\n providerOrLabel: string | undefined,\r\n ...moreCandidates: Array<string | undefined>\r\n): string {\r\n const key = resolveProviderLogoKey(providerOrLabel, ...moreCandidates) || normalizeProviderKey(providerOrLabel);\r\n if (!key) {\r\n return '';\r\n }\r\n return ` provider-logo--${key}${BRAND_LOGO_KEYS.has(key) ? ' provider-logo--brand' : ''}`;\r\n}\r\n\r\nfunction providerIconImgHtml(iconUrl: string, logoKey: string): string {\r\n return `<img class=\"provider-logo__img\" src=\"${iconUrl}\" alt=\"\" decoding=\"async\" data-provider-logo-key=\"${logoKey}\" />`;\r\n}\r\n\r\nexport function providerLogoHtml(\r\n providerOrLabel: string | undefined,\r\n labelFallback?: string,\r\n ...moreCandidates: Array<string | undefined>\r\n): string {\r\n const key =\r\n resolveProviderLogoKey(providerOrLabel, labelFallback, ...moreCandidates) ||\r\n normalizeProviderKey(providerOrLabel);\r\n const svg = key && PROVIDER_LOGOS[key];\r\n if (key && INLINE_ONLY_LOGO_KEYS.has(key) && svg) {\r\n return svg;\r\n }\r\n const assetUrl = key ? providerAssetUrl(key) : undefined;\r\n if (assetUrl) {\r\n return providerIconImgHtml(assetUrl, key);\r\n }\r\n const iconUrl = key && PROVIDER_ICON_URLS[key];\r\n if (iconUrl) {\r\n return providerIconImgHtml(iconUrl, key);\r\n }\r\n if (svg) {\r\n return svg;\r\n }\r\n const label = (labelFallback ?? providerOrLabel ?? '?').trim();\r\n const initials = label ? label.slice(0, 2).toUpperCase() : '?';\r\n return `<span aria-hidden=\"true\">${initials}</span>`;\r\n}\r\n\r\n/** Short benefit lines \u2014 kept in sync with `providerBenefitText()` in `media/station.js`. */\r\nexport const PROVIDER_BENEFITS: Record<string, string> = {\r\n supabase: 'Best when you want auth, data, and storage in one stack.',\r\n clerk: 'Fastest managed auth path with clean session primitives.',\r\n authjs: 'Best when you want framework-owned auth and full control.',\r\n neon: 'Good serverless Postgres fit for Vercel-style apps.',\r\n planetscale: 'Good fit for branching MySQL workflows.',\r\n mongodb: 'Good when the app already models document data.',\r\n turso: 'Good edge SQLite option for lightweight apps.',\r\n stripe: 'Best supported global payment ecosystem.',\r\n paddle: 'Handles merchant-of-record subscription operations.',\r\n polar: 'MoR billing built for developers shipping SaaS.',\r\n 'lemon-squeezy': 'Sell digital products and subscriptions with less setup.',\r\n github: 'Best for GitHub Actions CI and required PR checks.',\r\n gitlab: 'Best for GitLab CI pipelines and merge gates.',\r\n vercel: 'Best fit for preview deploys, envs, and domains.',\r\n netlify: 'Good fit for static and serverless deploy workflows.',\r\n render: 'Good fit for simple web services and background jobs.',\r\n railway: 'Good fit for fast deploy loops and managed infra.',\r\n cloudflare: 'Good fit for Pages, Workers, DNS, and edge stack.',\r\n aws: 'Best when the app needs direct cloud infrastructure control.',\r\n sentry: 'Best first choice for production errors and traces.',\r\n posthog: 'Best for product analytics and funnel verification.',\r\n auth0: 'Enterprise identity with rules, MFA, and social login.',\r\n 'better-auth': 'Type-safe auth you own in your codebase.',\r\n playwright: 'Best for browser-flow verification and UI regression checks.',\r\n logrocket: 'Best when session replay is the missing evidence.',\r\n 'rate-limit': 'Protects API routes from abuse and retry loops.',\r\n 'bot-protection': 'Adds bot screening before expensive flows.',\r\n 'secrets-hygiene': 'Hardens env handling and secret exposure risk.',\r\n figma: 'Best for screen flows, handoff, and UX alignment.',\r\n storybook: 'Best for proving component states before production.',\r\n react: 'Best fit for common component UI and app-router projects.',\r\n vue: 'Good fit for Vue or Nuxt product interfaces.',\r\n svelte: 'Good fit for SvelteKit route-first apps.',\r\n angular: 'Good fit for structured enterprise frontend workflows.',\r\n nodejs: 'Best fit for JavaScript API routes and server behavior.',\r\n python: 'Good fit for FastAPI-style APIs and typed validation.',\r\n rails: 'Good fit for full-stack CRUD and convention-heavy APIs.',\r\n go: 'Good fit for lean, fast HTTP services.',\r\n vitest: 'Fast unit and integration tests for modern JS apps.',\r\n 'testing-library': 'User-centric component testing primitives.'\r\n};\r\n\r\nexport function providerBenefitText(providerOrLabel: string | undefined, fallback?: string): string {\r\n const key = normalizeProviderKey(providerOrLabel);\r\n return (key && PROVIDER_BENEFITS[key]) || fallback || 'Useful path for this section.';\r\n}\r\n\r\n/** Embedded in static report for client-side provider tiles. */\r\nexport function providerLogosPayloadJson(): string {\r\n return JSON.stringify({\r\n logos: PROVIDER_LOGOS,\r\n iconUrls: PROVIDER_ICON_URLS,\r\n assetUrls: providerAssetUrls(),\r\n inlineOnly: [...INLINE_ONLY_LOGO_KEYS],\r\n aliases: ALIASES,\r\n benefits: PROVIDER_BENEFITS,\r\n brandKeys: [...BRAND_LOGO_KEYS]\r\n }).replace(/</g, '\\\\u003c');\r\n}\r\n", "import type { CliScanArtifact } from '../types';\nimport { hydrateArtifactForReport } from './hydrateArtifact';\nimport { openChecksForMission, preferredMissionForArea } from './missionSelection';\nimport { PANEL_CLIENT_SCRIPT } from './panelClientScript';\nimport { providerLogoClass, providerLogoHtml, providerLogosPayloadJson } from './providerLogos';\n\r\nconst GEIST_FONTS =\r\n 'https://fonts.googleapis.com/css2?family=Geist:wght@400;500;600;700&amp;family=JetBrains+Mono:wght@400;600&amp;display=swap';\r\n\r\nfunction escapeHtml(value: string): string {\r\n return value\r\n .replace(/&/g, '&amp;')\r\n .replace(/</g, '&lt;')\r\n .replace(/>/g, '&gt;')\r\n .replace(/\"/g, '&quot;');\r\n}\r\n\r\n/** Same order as `PRODUCTION_MAP_CATEGORIES` in `media/station.js`. */\r\nconst CATEGORY_META: Array<{ key: string; label: string }> = [\r\n { key: 'appFlow', label: 'App Flow' },\r\n { key: 'frontend', label: 'Frontend' },\r\n { key: 'backend', label: 'Backend / API' },\r\n { key: 'auth', label: 'Auth' },\r\n { key: 'database', label: 'Database' },\r\n { key: 'payments', label: 'Payments' },\r\n { key: 'deployment', label: 'Deployment' },\r\n { key: 'monitoring', label: 'Monitoring / Analytics' },\r\n { key: 'security', label: 'Security' },\r\n { key: 'testing', label: 'Testing' },\r\n { key: 'landing', label: 'Landing / Onboarding' },\r\n { key: 'errorHandling', label: 'Error Handling' }\r\n];\r\n\r\nfunction gapCountForArea(artifact: CliScanArtifact, areaKey: string): number {\r\n return artifact.gaps.filter((g) => g.primaryMapCategory === areaKey).length;\r\n}\r\n\r\nfunction defaultAreaKey(artifact: CliScanArtifact): string {\n const fromGap = artifact.gaps[0]?.primaryMapCategory;\r\n if (fromGap) {\r\n return fromGap;\r\n }\r\n const areas = artifact.missionGraph.areas ?? [];\r\n if (areas.some((a) => a.key === 'frontend')) {\r\n return 'frontend';\r\n }\r\n return areas[0]?.key ?? 'frontend';\r\n}\r\n\r\nfunction buildAccountStripHtml(artifact: CliScanArtifact): string {\r\n if (!artifact.accountEmail) {\r\n return '';\r\n }\r\n const planLabel = artifact.plan === 'pro' ? 'Pro' : 'Free';\r\n const usage = artifact.usageLine ? `<span class=\"account-bar__meta\">${escapeHtml(artifact.usageLine)}</span>` : '';\r\n return `<div class=\"station-account-strip mc-session\" aria-label=\"Account\">\r\n <div class=\"account-bar\">\r\n <div class=\"account-bar__main\">\r\n <div class=\"account-bar__identity\">\r\n <div class=\"account-bar__id-text\">\r\n <span class=\"account-bar__email\">${escapeHtml(artifact.accountEmail)}</span>\r\n ${usage}\r\n </div>\r\n </div>\r\n <div class=\"account-bar__actions\">\r\n <span class=\"account-bar__plan\">${escapeHtml(planLabel)}</span>\r\n </div>\r\n </div>\r\n </div>\r\n </div>`;\r\n}\r\n\r\nfunction buildNodeHtml(\r\n artifact: CliScanArtifact,\r\n meta: { key: string; label: string },\r\n selectedAreaKey: string\r\n): string {\n const area = (artifact.missionGraph.areas ?? []).find((a) => a.key === meta.key);\n const selectedOverride = artifact.selectedProviders?.[meta.key] ?? '';\n const mission = preferredMissionForArea(area, selectedOverride);\n const selectedProvider =\n selectedOverride || mission?.provider || mission?.providerLabel || '';\n const providerLabel = mission?.providerLabel ?? 'Not selected';\r\n const readiness = mission?.readinessPercent ?? area?.readinessPercent ?? 0;\r\n const openChecks = openChecksForMission(mission);\n const modelGaps = gapCountForArea(artifact, meta.key);\r\n\r\n const stateClass =\r\n modelGaps > 0\r\n ? ' studio-node--critical'\r\n : openChecks > 0\r\n ? ' studio-node--warning'\r\n : area\r\n ? ' studio-node--in-project'\r\n : '';\r\n\r\n const selectedClass = selectedAreaKey === meta.key ? ' studio-node--selected' : '';\r\n\r\n const metaText =\r\n modelGaps > 0\r\n ? `${modelGaps} stack fix${modelGaps === 1 ? '' : 'es'}`\r\n : openChecks > 0\r\n ? `${openChecks} stack fix${openChecks === 1 ? '' : 'es'}`\r\n : `${readiness}% health`;\r\n\r\n const logoClass = providerLogoClass(mission?.provider, mission?.key, String(selectedProvider), providerLabel);\r\n const logoInner = providerLogoHtml(\r\n mission?.provider,\r\n providerLabel,\r\n mission?.key,\r\n String(selectedProvider)\r\n );\r\n\r\n const gapBadge =\r\n modelGaps > 0\r\n ? `<span class=\"studio-node__raven-badge\" role=\"presentation\">Gap ${modelGaps}</span>`\r\n : '';\r\n\r\n return `<button type=\"button\" class=\"studio-node studio-node--${escapeHtml(meta.key)} provider-logo${logoClass}${stateClass}${selectedClass}\" data-area-key=\"${escapeHtml(meta.key)}\" aria-label=\"${escapeHtml(meta.label)}, ${escapeHtml(providerLabel)}, ${escapeHtml(metaText)}\">\r\n <span class=\"studio-node__logo provider-logo${logoClass}\" aria-hidden=\"true\">${logoInner}</span>\r\n <span class=\"studio-node__title\">${escapeHtml(meta.label)}</span>\r\n <span class=\"studio-node__provider\">${escapeHtml(providerLabel)}</span>\r\n <span class=\"studio-node__meta\">${escapeHtml(metaText)}</span>\r\n ${gapBadge}\r\n </button>`;\r\n}\r\n\r\nexport function generateReportHtml(artifact: CliScanArtifact): string {\r\n const hydrated = hydrateArtifactForReport(artifact);\r\n const dataJson = JSON.stringify(hydrated).replace(/</g, '\\\\u003c');\r\n const defaultKey = defaultAreaKey(hydrated);\r\n const nodesHtml = CATEGORY_META.map((meta) => buildNodeHtml(hydrated, meta, defaultKey)).join('\\n');\r\n const accountStrip = buildAccountStripHtml(hydrated);\r\n const logosJson = providerLogosPayloadJson();\r\n const scannedLabel = escapeHtml(hydrated.scannedAt);\r\n\r\n return `<!DOCTYPE html>\r\n<html lang=\"en\" class=\"cli-mission-report\" data-surface=\"panel\" data-skin=\"editorial\">\n<head>\r\n <meta charset=\"utf-8\" />\r\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\r\n <title>VibeRaven Mission Map</title>\r\n <link rel=\"preconnect\" href=\"https://fonts.googleapis.com\" />\r\n <link rel=\"preconnect\" href=\"https://fonts.gstatic.com\" crossorigin />\r\n <link rel=\"stylesheet\" href=\"${GEIST_FONTS}\" />\r\n <link rel=\"stylesheet\" href=\"report/station.css\" />\r\n <link rel=\"stylesheet\" href=\"report/report-cli.css\" />\r\n</head>\r\n<body class=\"station-results-active\">\r\n <div class=\"station-app\">\r\n ${accountStrip}\r\n <div class=\"mc-state mc-state--results\" role=\"region\" aria-label=\"Mission Map results\">\r\n <div class=\"studio-shell\" aria-label=\"VibeRaven Studio cockpit\">\r\n <header class=\"studio-top-rail\" aria-label=\"Studio status\">\r\n <img class=\"studio-top-rail__logo\" src=\"report/assets/viberaven-logo.png\" alt=\"\" width=\"32\" height=\"32\" />\r\n <span class=\"studio-top-rail__brand\"><span>VIBERAVEN / MISSION MAP</span></span>\r\n <div class=\"studio-top-rail__build\">Last scan \u00B7 ${scannedLabel}</div>\r\n </header>\r\n <div class=\"studio-workspace\">\r\n <main class=\"studio-map-canvas\" aria-label=\"Interactive full-stack system map\">\r\n <section class=\"studio-system-map\" aria-label=\"Production system map\">\r\n <div class=\"studio-node-layer\">\r\n <div class=\"studio-connector-layer\" aria-hidden=\"true\"></div>\r\n <div class=\"studio-core-group\">\r\n <div class=\"studio-core-node\" aria-label=\"Production core score\">\r\n <img class=\"studio-core-node__mark\" src=\"report/assets/viberaven-logo.png\" alt=\"VibeRaven\" width=\"92\" height=\"92\" />\r\n <strong>${hydrated.productionCorePercent}%</strong>\r\n <small>Production core</small>\r\n </div>\r\n </div>\r\n ${nodesHtml}\r\n </div>\r\n </section>\r\n </main>\r\n <aside class=\"studio-setup-panel\" id=\"detail-panel\" aria-live=\"polite\"></aside>\r\n </div>\r\n </div>\r\n </div>\r\n </div>\r\n <script type=\"application/json\" id=\"scan-data\">${dataJson}</script>\r\n <script type=\"application/json\" id=\"default-area-key\">${JSON.stringify(defaultKey)}</script>\r\n <script type=\"application/json\" id=\"provider-logos\">${logosJson}</script>\r\n <script>${PANEL_CLIENT_SCRIPT}</script>\r\n</body>\r\n</html>`;\r\n}\r\n", "import { existsSync } from 'node:fs';\r\nimport { dirname, join } from 'node:path';\r\n\r\n/** Directory containing station.css, report-cli.css, and assets/ for bundled CLI reports. */\r\nexport function getBundledReportAssetsDir(): string {\r\n const base = __dirname;\r\n const candidates = [\r\n join(base, 'report'),\r\n join(base, '..', 'assets', 'report'),\r\n join(base, '..', '..', 'assets', 'report')\r\n ];\r\n for (const dir of candidates) {\r\n if (existsSync(join(dir, 'station.css'))) {\r\n return dir;\r\n }\r\n }\r\n throw new Error('Report assets missing. Run `npm run sync-report-assets` and `npm run build` in packages/cli.');\r\n}\r\n\r\nexport const REPORT_ASSET_FILES = [\n 'station.css',\n 'report-cli.css',\n 'assets/viberaven-logo.png',\n 'assets/provider-authjs.svg',\n 'assets/provider-aws.svg',\n 'assets/provider-logrocket.svg'\n] as const;\n", "import type { CliScanArtifact } from './types';\r\n\r\n/** Patterns aligned with `src/station/fileScanner.ts` \u2014 never persist secrets in `.viberaven/`. */\r\nconst INLINE_SECRET_PATTERNS: RegExp[] = [\r\n /\\b(sk_(?:live|test)_[A-Za-z0-9]{12,}|sk-proj-[A-Za-z0-9_-]{16,}|sk-[A-Za-z0-9_-]{20,})\\b/g,\r\n /\\b(whsec_[A-Za-z0-9]{12,}|rk_(?:live|test)_[A-Za-z0-9]{12,})\\b/g,\r\n /\\beyJ[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}\\b/g\r\n];\r\n\r\nconst SENSITIVE_ENV_KEYS =\r\n /^(?:OPENAI_API_KEY|OPENAI_KEY|ANTHROPIC_API_KEY|VIBERAVEN_ACCESS_TOKEN|VRAVEN_.*|SUPABASE_SERVICE_ROLE_KEY|.*_SECRET_KEY)$/i;\r\n\r\nfunction redactString(value: string): string {\r\n let out = value;\r\n for (const pattern of INLINE_SECRET_PATTERNS) {\r\n out = out.replace(pattern, '[REDACTED_SECRET]');\r\n }\r\n return out.replace(\r\n /\\b([A-Za-z0-9_]*(?:API_KEY|SECRET|TOKEN|PASSWORD|PRIVATE_KEY)[A-Za-z0-9_]*)\\s*=\\s*[\"']?[^\"'\\s;,]+[\"']?/gi,\r\n '$1=[REDACTED]'\r\n );\r\n}\r\n\r\nfunction redactUnknown(value: unknown): unknown {\r\n if (typeof value === 'string') {\r\n return redactString(value);\r\n }\r\n if (Array.isArray(value)) {\r\n return value.map(redactUnknown);\r\n }\r\n if (value && typeof value === 'object') {\r\n const record = value as Record<string, unknown>;\r\n const next: Record<string, unknown> = {};\r\n for (const [key, entry] of Object.entries(record)) {\r\n if (SENSITIVE_ENV_KEYS.test(key)) {\r\n next[key] = '[REDACTED]';\r\n } else {\r\n next[key] = redactUnknown(entry);\r\n }\r\n }\r\n return next;\r\n }\r\n return value;\r\n}\r\n\r\n/** Strip likely secrets before writing scan artifacts to disk. */\r\nexport function sanitizeArtifactForDisk(artifact: CliScanArtifact): CliScanArtifact {\r\n return redactUnknown(artifact) as CliScanArtifact;\r\n}\r\n", "import { readFile } from 'node:fs/promises';\r\nimport { join } from 'node:path';\r\nimport { findArtifactsWorkspace, getProjectArtifactsDir } from '../config';\r\nimport type { CliScanArtifact } from '../types';\r\nimport type { Gap } from '../../../../src/station/types';\r\n\r\nexport type PickGapOptions = {\r\n gapId?: string;\r\n provider?: string;\r\n area?: string;\r\n};\r\n\r\nexport type MenuAction =\r\n | 'scan'\r\n | 'gaps'\r\n | 'prompt'\r\n | 'open-report'\r\n | 'auth'\r\n | 'exit';\r\n\r\nconst SEVERITY_RANK: Record<Gap['severity'], number> = {\r\n critical: 0,\r\n warning: 1,\r\n info: 2\r\n};\r\n\r\nexport class ScanNotFoundError extends Error {\r\n constructor(message = 'No scan found. Run a scan first.') {\r\n super(message);\r\n this.name = 'ScanNotFoundError';\r\n }\r\n}\r\n\r\nexport function isScanNotFoundError(error: unknown): error is ScanNotFoundError {\r\n return error instanceof ScanNotFoundError;\r\n}\r\n\r\nexport function needsScanMessage(startDir?: string): string {\r\n const cwd = startDir ?? process.cwd();\r\n return [\r\n 'No CLI scan found for this folder.',\r\n `Looking from: ${cwd}`,\r\n 'Choose \"Scan project\", or run the menu from your repo root (where .viberaven/ lives).',\r\n 'VS Code extension scans stay inside the editor \u2014 run a CLI scan once to create .viberaven/ on disk.'\r\n ].join('\\n');\r\n}\r\n\r\nexport function sortGapsByPriority(gaps: Gap[]): Gap[] {\r\n return [...gaps].sort(\r\n (a, b) =>\r\n SEVERITY_RANK[a.severity] - SEVERITY_RANK[b.severity] || a.title.localeCompare(b.title)\r\n );\r\n}\r\n\r\nexport function pickGap(artifact: CliScanArtifact, options: PickGapOptions = {}): Gap | undefined {\r\n if (options.gapId) {\r\n return artifact.gaps.find((g) => g.id === options.gapId);\r\n }\r\n if (options.provider) {\r\n const key = options.provider.toLowerCase();\r\n return artifact.gaps.find(\r\n (g) =>\r\n g.primaryMapCategory === key ||\r\n g.title.toLowerCase().includes(key) ||\r\n g.id.toLowerCase().includes(key)\r\n );\r\n }\r\n if (options.area) {\r\n return artifact.gaps.find((g) => g.primaryMapCategory === options.area);\r\n }\r\n return sortGapsByPriority(artifact.gaps)[0];\r\n}\r\n\r\nexport function formatTopGapsList(artifact: CliScanArtifact, limit = 10): string {\r\n const sorted = sortGapsByPriority(artifact.gaps);\r\n if (sorted.length === 0) {\r\n return 'No gaps found \u2014 production core looks solid.';\r\n }\r\n return sorted\r\n .slice(0, limit)\r\n .map((gap, index) => {\r\n const severity = gap.severity.toUpperCase().padEnd(8);\r\n const area = gap.primaryMapCategory.padEnd(12);\r\n return `${index + 1}. [${severity}] ${area} ${gap.title}`;\r\n })\r\n .join('\\n');\r\n}\r\n\r\nexport async function loadLastArtifact(startDir: string): Promise<CliScanArtifact> {\r\n const workspace = await findArtifactsWorkspace(startDir);\r\n if (!workspace) {\r\n throw new ScanNotFoundError(needsScanMessage(startDir));\r\n }\r\n const path = join(getProjectArtifactsDir(workspace), 'last-scan.json');\r\n try {\r\n const raw = await readFile(path, 'utf-8');\r\n return JSON.parse(raw) as CliScanArtifact;\r\n } catch {\r\n throw new ScanNotFoundError(needsScanMessage(startDir));\r\n }\r\n}\r\n\r\nexport async function getReportPath(startDir: string): Promise<string | undefined> {\r\n const workspace = await findArtifactsWorkspace(startDir);\r\n if (!workspace) {\r\n return undefined;\r\n }\r\n return join(getProjectArtifactsDir(workspace), 'report.html');\r\n}\r\n", "import { loadLastArtifact, ScanNotFoundError } from '../tui/menu';\r\nimport { writeScanArtifacts, type WriteArtifactsResult } from '../artifacts';\r\nimport { findArtifactsWorkspace } from '../config';\r\n\r\n/** Rebuild `.viberaven/report.html` from existing `last-scan.json` (no API scan). */\r\nexport async function refreshReportFromDisk(startDir: string): Promise<WriteArtifactsResult> {\r\n const workspace = await findArtifactsWorkspace(startDir);\r\n if (!workspace) {\r\n throw new ScanNotFoundError();\r\n }\r\n const artifact = await loadLastArtifact(startDir);\r\n return writeScanArtifacts({ artifact, cwd: workspace });\r\n}\r\n", "import { spawn } from 'node:child_process';\r\n\r\nexport async function openPathInBrowser(filePath: string): Promise<void> {\r\n const absolute = filePath;\r\n let command: string;\r\n let args: string[];\r\n\r\n if (process.platform === 'win32') {\r\n command = 'cmd';\r\n args = ['/c', 'start', '', absolute];\r\n } else if (process.platform === 'darwin') {\r\n command = 'open';\r\n args = [absolute];\r\n } else {\r\n command = 'xdg-open';\r\n args = [absolute];\r\n }\r\n\r\n await new Promise<void>((resolve, reject) => {\r\n const child = spawn(command, args, { stdio: 'ignore', shell: process.platform === 'win32' });\r\n child.on('error', reject);\r\n child.on('exit', (code) => {\r\n if (code === 0) {\r\n resolve();\r\n } else {\r\n reject(new Error(`Could not open browser (exit ${code ?? 'unknown'}). Open manually: ${absolute}`));\r\n }\r\n });\r\n });\r\n}\r\n", "import { spawn } from 'node:child_process';\r\n\r\n/**\r\n * Copy text to the system clipboard (Windows clip, macOS pbcopy, Linux wl-copy/xclip).\r\n */\r\nexport async function copyToClipboard(text: string): Promise<void> {\r\n if (!text) {\r\n throw new Error('Nothing to copy.');\r\n }\r\n\r\n if (process.platform === 'win32') {\r\n await pipeToCommand('clip', text);\r\n return;\r\n }\r\n\r\n if (process.platform === 'darwin') {\r\n await pipeToCommand('pbcopy', text);\r\n return;\r\n }\r\n\r\n try {\r\n await pipeToCommand('wl-copy', text);\r\n return;\r\n } catch {\r\n // fall through\r\n }\r\n\r\n try {\r\n await pipeToCommand('xclip', text, ['-selection', 'clipboard']);\r\n return;\r\n } catch {\r\n throw new Error('Clipboard unavailable. Install wl-clipboard or xclip, or copy from the terminal output.');\r\n }\r\n}\r\n\r\nfunction pipeToCommand(command: string, text: string, extraArgs: string[] = []): Promise<void> {\r\n return new Promise((resolve, reject) => {\r\n const child = spawn(command, extraArgs, { stdio: ['pipe', 'ignore', 'ignore'] });\r\n child.on('error', reject);\r\n child.on('close', (code) => {\r\n if (code === 0) {\r\n resolve();\r\n } else {\r\n reject(new Error(`${command} exited with code ${code ?? 'unknown'}`));\r\n }\r\n });\r\n child.stdin?.write(text, 'utf8', (error) => {\r\n if (error) {\r\n reject(error);\r\n return;\r\n }\r\n child.stdin?.end();\r\n });\r\n });\r\n}\r\n", "import pc from 'picocolors';\nimport type { CliScanArtifact } from './types';\nimport { openChecksForMission, preferredMissionForArea } from './report/missionSelection';\n\r\nfunction boxLine(content: string, width: number): string {\r\n const inner = content.length > width - 4 ? content.slice(0, width - 7) + '\u2026' : content;\r\n const padding = ' '.repeat(Math.max(0, width - inner.length - 4));\r\n return `${pc.dim('\u2502')} ${inner}${padding} ${pc.dim('\u2502')}`;\r\n}\r\n\r\nfunction readinessColor(percent: number): (text: string) => string {\r\n if (percent >= 70) {\r\n return pc.green;\r\n }\r\n if (percent >= 40) {\r\n return pc.yellow;\r\n }\r\n return pc.red;\r\n}\r\n\r\nfunction gapTagColor(modelGaps: number, open: number): (text: string) => string {\r\n if (modelGaps > 0) {\r\n return pc.red;\r\n }\r\n if (open > 0) {\r\n return pc.yellow;\r\n }\r\n return pc.dim;\r\n}\r\n\r\nexport function printScanSummary(\r\n artifact: CliScanArtifact,\r\n paths: { reportPath: string; jsonPath: string; summaryPath: string }\r\n): void {\r\n const pct = artifact.productionCorePercent;\r\n const gapCount = artifact.gaps.length;\r\n const pctColor = readinessColor(pct);\r\n\r\n const headline = `${pc.bold('VibeRaven')} \u00B7 ${pctColor(`Production core ${pct}%`)} \u00B7 ${gapCount} gap(s)`;\r\n const subline = `Score ${artifact.score} \u00B7 ${artifact.scoreLabel}`;\r\n const width = Math.max(headline.length, subline.length, 44) + 4;\r\n\r\n console.log('');\r\n console.log(pc.dim('\u250C') + pc.dim('\u2500'.repeat(width - 2)) + pc.dim('\u2510'));\r\n console.log(boxLine(headline, width));\r\n console.log(boxLine(subline, width));\r\n console.log(pc.dim('\u2514') + pc.dim('\u2500'.repeat(width - 2)) + pc.dim('\u2518'));\r\n console.log('');\r\n\r\n for (const area of artifact.missionGraph.areas ?? []) {\n const mission = preferredMissionForArea(area, artifact.selectedProviders?.[area.key] ?? '');\n if (!mission) {\n continue;\n }\n const open = openChecksForMission(mission);\n const modelGaps = artifact.gaps.filter((g) => g.primaryMapCategory === area.key).length;\r\n const tag =\r\n modelGaps > 0 ? ` GAP ${modelGaps}` : open > 0 ? ` ${open} fix` : '';\r\n const tagColored = tag ? gapTagColor(modelGaps, open)(tag) : '';\r\n const label = area.label.padEnd(18);\r\n const provider = mission.providerLabel.padEnd(14);\r\n const readiness = readinessColor(mission.readinessPercent)(`${mission.readinessPercent}%`);\r\n console.log(` ${pc.dim(label)} ${provider} ${readiness}${tagColored}`);\r\n }\r\n\r\n console.log('');\r\n console.log(pc.bold('Artifacts:'));\r\n console.log(pc.dim(` ${paths.reportPath}`));\r\n console.log(pc.dim(` ${paths.jsonPath}`));\r\n console.log(pc.dim(` ${paths.summaryPath}`));\r\n console.log('');\r\n console.log(pc.dim('Press Enter in `viberaven` menu to rescan \u00B7 `viberaven prompt` for top gap'));\r\n console.log(pc.dim('Agents: read .viberaven/agent-summary.md'));\r\n console.log('');\r\n}\r\n", "import { resolve } from 'node:path';\r\nimport * as p from '@clack/prompts';\r\nimport pc from 'picocolors';\r\nimport {\r\n clearCredentials,\r\n findArtifactsWorkspace,\r\n loadCredentials,\r\n resolveApiBaseUrl,\r\n resolveWorkspaceRoot\r\n} from '../config';\r\nimport { requireCredentials, runDeviceLogin } from '../auth';\r\nimport {\r\n enrichArtifactWithAccount,\r\n fetchAccountMe,\r\n formatScanLimitMessage,\r\n formatUsageLine,\r\n syncCredentialsFromAccount\r\n} from '../account';\r\nimport { runProjectScan } from '../runScan';\r\nimport { writeScanArtifacts } from '../artifacts';\r\nimport { openPathInBrowser } from '../openBrowser';\r\nimport { copyToClipboard } from '../clipboard';\r\nimport { printScanSummary } from '../terminalSummary';\r\nimport { VERSION } from '../version';\r\nimport { refreshReportFromDisk } from '../report/refreshReport';\r\nimport {\r\n formatTopGapsList,\r\n isScanNotFoundError,\r\n loadLastArtifact,\r\n needsScanMessage,\r\n pickGap,\r\n type MenuAction\r\n} from './menu';\r\n\r\nasync function formatStatusLine(): Promise<string> {\r\n const creds = await loadCredentials();\r\n if (!creds?.accessToken) {\r\n return pc.dim('Not signed in');\r\n }\r\n try {\r\n const synced = await syncCredentialsFromAccount(creds);\r\n const plan = synced.plan ?? 'unknown';\r\n return pc.green(`Signed in: ${synced.email ?? '(email unknown)'} \u00B7 ${plan}`);\r\n } catch {\r\n return pc.yellow(`Signed in: ${creds.email ?? '(email unknown)'} (offline)`);\r\n }\r\n}\r\n\r\nasync function handleScan(cwd: string): Promise<void> {\r\n const apiBaseUrl = resolveApiBaseUrl();\r\n const spinner = p.spinner();\r\n spinner.start('Checking credentials\u2026');\r\n\r\n let accessToken: string;\r\n try {\r\n ({ accessToken } = await requireCredentials(apiBaseUrl));\r\n } catch (error) {\r\n spinner.stop('Sign in required');\r\n p.log.error(error instanceof Error ? error.message : String(error));\r\n p.log.message(pc.dim('Choose \"Sign in / Sign out\" from the menu.'));\r\n return;\r\n }\r\n\r\n spinner.message(`Scanning ${cwd}\u2026`);\r\n const result = await runProjectScan({ workspacePath: cwd, accessToken, apiBaseUrl });\r\n\r\n if (!result.ok) {\r\n spinner.stop('Scan failed');\r\n if (result.kind === 'scan_limit') {\r\n p.log.error(formatScanLimitMessage(result.upgradeUrl));\r\n try {\r\n const account = await fetchAccountMe(apiBaseUrl, accessToken);\r\n p.log.message(formatUsageLine(account.usage));\r\n } catch {\r\n // best-effort\r\n }\r\n return;\r\n }\r\n p.log.error(result.message);\r\n return;\r\n }\r\n\r\n const artifact = await enrichArtifactWithAccount(result.artifact, apiBaseUrl, accessToken);\r\n const paths = await writeScanArtifacts({ artifact, cwd });\r\n spinner.stop('Scan complete');\r\n printScanSummary(artifact, paths);\r\n if (artifact.usage) {\r\n p.log.message(formatUsageLine(artifact.usage));\r\n }\r\n}\r\n\r\nasync function handleViewGaps(cwd: string): Promise<void> {\r\n try {\r\n const artifact = await loadLastArtifact(cwd);\r\n p.log.message(formatTopGapsList(artifact));\r\n } catch (error) {\r\n if (isScanNotFoundError(error)) {\r\n p.log.warn(error.message);\r\n return;\r\n }\r\n throw error;\r\n }\r\n}\r\n\r\nasync function handlePrompt(cwd: string): Promise<void> {\r\n try {\r\n const artifact = await loadLastArtifact(cwd);\r\n const gap = pickGap(artifact);\r\n if (!gap) {\r\n p.log.warn('No gaps to fix. Run a scan or pick a different project.');\r\n return;\r\n }\r\n try {\r\n await copyToClipboard(gap.copyPrompt);\r\n p.log.success(pc.green(`Copied top prompt to clipboard \u2014 ${gap.title}`));\r\n } catch (error) {\r\n p.log.warn(error instanceof Error ? error.message : String(error));\r\n console.log('');\r\n console.log(gap.copyPrompt);\r\n console.log('');\r\n p.log.message(pc.dim('Copy the text above manually.'));\r\n }\r\n } catch (error) {\r\n if (isScanNotFoundError(error)) {\r\n p.log.warn(error.message);\r\n return;\r\n }\r\n throw error;\r\n }\r\n}\r\n\r\nasync function handleOpenReport(cwd: string): Promise<void> {\r\n const spinner = p.spinner();\r\n spinner.start('Refreshing report from last scan\u2026');\r\n try {\r\n const paths = await refreshReportFromDisk(cwd);\r\n spinner.stop('Report ready');\r\n await openPathInBrowser(paths.reportPath);\r\n p.log.success(`Opened ${paths.reportPath}`);\r\n } catch (error) {\r\n spinner.stop('Could not open report');\r\n if (isScanNotFoundError(error)) {\r\n p.log.warn(error.message);\r\n return;\r\n }\r\n p.log.warn(error instanceof Error ? error.message : String(error));\r\n }\r\n}\r\n\r\nasync function handleAuth(): Promise<void> {\r\n const creds = await loadCredentials();\r\n if (creds?.accessToken) {\r\n await clearCredentials();\r\n p.log.success('Signed out.');\r\n return;\r\n }\r\n const apiBaseUrl = resolveApiBaseUrl();\r\n await runDeviceLogin(apiBaseUrl);\r\n}\r\n\r\nfunction buildMenuOptions(isSignedIn: boolean): { value: MenuAction; label: string; hint?: string }[] {\r\n return [\r\n { value: 'scan', label: 'Scan project', hint: 'Map launch readiness' },\r\n { value: 'gaps', label: 'View top gaps', hint: 'From last scan' },\r\n { value: 'prompt', label: 'Copy top prompt', hint: 'Agent-ready fix prompt' },\r\n {\r\n value: 'open-report',\r\n label: 'Open report in browser',\r\n hint: 'Rebuilds UI from last scan (no new scan)'\r\n },\r\n {\r\n value: 'auth',\r\n label: isSignedIn ? 'Sign out' : 'Sign in',\r\n hint: isSignedIn ? 'Clear local credentials' : 'Device login flow'\r\n },\r\n { value: 'exit', label: 'Exit' }\r\n ];\r\n}\r\n\r\nexport async function runInteractiveSession(startDir: string = process.cwd()): Promise<void> {\r\n p.intro(`${pc.bold('VibeRaven')} ${pc.dim(VERSION)}`);\r\n\r\n const cwd = await resolveWorkspaceRoot(startDir);\r\n const artifactsAt = await findArtifactsWorkspace(startDir);\r\n if (artifactsAt && resolve(artifactsAt) !== resolve(startDir)) {\r\n p.log.message(pc.dim(`Using scan from: ${artifactsAt}`));\r\n } else {\r\n p.log.message(pc.dim(`Project folder: ${cwd}`));\r\n if (!artifactsAt) {\r\n p.log.message(\r\n pc.dim(\r\n 'No .viberaven/ here yet. Extension scans are separate \u2014 choose Scan project to write CLI artifacts.'\r\n )\r\n );\r\n }\r\n }\r\n\r\n let running = true;\r\n while (running) {\r\n const statusLine = await formatStatusLine();\r\n p.log.message(statusLine);\r\n\r\n const creds = await loadCredentials();\r\n const action = await p.select({\r\n message: 'What would you like to do?',\r\n options: buildMenuOptions(Boolean(creds?.accessToken))\r\n });\r\n\r\n if (p.isCancel(action)) {\r\n p.cancel('Goodbye.');\r\n return;\r\n }\r\n\r\n switch (action as MenuAction) {\r\n case 'scan':\r\n await handleScan(cwd);\r\n break;\r\n case 'gaps':\r\n await handleViewGaps(cwd);\r\n break;\r\n case 'prompt':\r\n await handlePrompt(cwd);\r\n break;\r\n case 'open-report':\r\n await handleOpenReport(cwd);\r\n break;\r\n case 'auth':\r\n await handleAuth();\r\n break;\r\n case 'exit':\r\n running = false;\r\n break;\r\n default:\r\n break;\r\n }\r\n }\r\n\r\n p.outro(pc.dim('Run viberaven anytime for the interactive menu.'));\r\n}\r\n", "export default function ansiRegex({onlyFirst = false} = {}) {\n\t// Valid string terminator sequences are BEL, ESC\\, and 0x9c\n\tconst ST = '(?:\\\\u0007|\\\\u001B\\\\u005C|\\\\u009C)';\n\tconst pattern = [\n\t\t`[\\\\u001B\\\\u009B][[\\\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]+)*|[a-zA-Z\\\\d]+(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]*)*)?${ST})`,\n\t\t'(?:(?:\\\\d{1,4}(?:;\\\\d{0,4})*)?[\\\\dA-PR-TZcf-nq-uy=><~]))',\n\t].join('|');\n\n\treturn new RegExp(pattern, onlyFirst ? undefined : 'g');\n}\n", "import ansiRegex from 'ansi-regex';\n\nconst regex = ansiRegex();\n\nexport default function stripAnsi(string) {\n\tif (typeof string !== 'string') {\n\t\tthrow new TypeError(`Expected a \\`string\\`, got \\`${typeof string}\\``);\n\t}\n\n\t// Even though the regex is global, we don't need to reset the `.lastIndex`\n\t// because unlike `.exec()` and `.test()`, `.replace()` does it automatically\n\t// and doing it manually has a performance penalty.\n\treturn string.replace(regex, '');\n}\n", "var eaw = {};\n\nif ('undefined' == typeof module) {\n window.eastasianwidth = eaw;\n} else {\n module.exports = eaw;\n}\n\neaw.eastAsianWidth = function(character) {\n var x = character.charCodeAt(0);\n var y = (character.length == 2) ? character.charCodeAt(1) : 0;\n var codePoint = x;\n if ((0xD800 <= x && x <= 0xDBFF) && (0xDC00 <= y && y <= 0xDFFF)) {\n x &= 0x3FF;\n y &= 0x3FF;\n codePoint = (x << 10) | y;\n codePoint += 0x10000;\n }\n\n if ((0x3000 == codePoint) ||\n (0xFF01 <= codePoint && codePoint <= 0xFF60) ||\n (0xFFE0 <= codePoint && codePoint <= 0xFFE6)) {\n return 'F';\n }\n if ((0x20A9 == codePoint) ||\n (0xFF61 <= codePoint && codePoint <= 0xFFBE) ||\n (0xFFC2 <= codePoint && codePoint <= 0xFFC7) ||\n (0xFFCA <= codePoint && codePoint <= 0xFFCF) ||\n (0xFFD2 <= codePoint && codePoint <= 0xFFD7) ||\n (0xFFDA <= codePoint && codePoint <= 0xFFDC) ||\n (0xFFE8 <= codePoint && codePoint <= 0xFFEE)) {\n return 'H';\n }\n if ((0x1100 <= codePoint && codePoint <= 0x115F) ||\n (0x11A3 <= codePoint && codePoint <= 0x11A7) ||\n (0x11FA <= codePoint && codePoint <= 0x11FF) ||\n (0x2329 <= codePoint && codePoint <= 0x232A) ||\n (0x2E80 <= codePoint && codePoint <= 0x2E99) ||\n (0x2E9B <= codePoint && codePoint <= 0x2EF3) ||\n (0x2F00 <= codePoint && codePoint <= 0x2FD5) ||\n (0x2FF0 <= codePoint && codePoint <= 0x2FFB) ||\n (0x3001 <= codePoint && codePoint <= 0x303E) ||\n (0x3041 <= codePoint && codePoint <= 0x3096) ||\n (0x3099 <= codePoint && codePoint <= 0x30FF) ||\n (0x3105 <= codePoint && codePoint <= 0x312D) ||\n (0x3131 <= codePoint && codePoint <= 0x318E) ||\n (0x3190 <= codePoint && codePoint <= 0x31BA) ||\n (0x31C0 <= codePoint && codePoint <= 0x31E3) ||\n (0x31F0 <= codePoint && codePoint <= 0x321E) ||\n (0x3220 <= codePoint && codePoint <= 0x3247) ||\n (0x3250 <= codePoint && codePoint <= 0x32FE) ||\n (0x3300 <= codePoint && codePoint <= 0x4DBF) ||\n (0x4E00 <= codePoint && codePoint <= 0xA48C) ||\n (0xA490 <= codePoint && codePoint <= 0xA4C6) ||\n (0xA960 <= codePoint && codePoint <= 0xA97C) ||\n (0xAC00 <= codePoint && codePoint <= 0xD7A3) ||\n (0xD7B0 <= codePoint && codePoint <= 0xD7C6) ||\n (0xD7CB <= codePoint && codePoint <= 0xD7FB) ||\n (0xF900 <= codePoint && codePoint <= 0xFAFF) ||\n (0xFE10 <= codePoint && codePoint <= 0xFE19) ||\n (0xFE30 <= codePoint && codePoint <= 0xFE52) ||\n (0xFE54 <= codePoint && codePoint <= 0xFE66) ||\n (0xFE68 <= codePoint && codePoint <= 0xFE6B) ||\n (0x1B000 <= codePoint && codePoint <= 0x1B001) ||\n (0x1F200 <= codePoint && codePoint <= 0x1F202) ||\n (0x1F210 <= codePoint && codePoint <= 0x1F23A) ||\n (0x1F240 <= codePoint && codePoint <= 0x1F248) ||\n (0x1F250 <= codePoint && codePoint <= 0x1F251) ||\n (0x20000 <= codePoint && codePoint <= 0x2F73F) ||\n (0x2B740 <= codePoint && codePoint <= 0x2FFFD) ||\n (0x30000 <= codePoint && codePoint <= 0x3FFFD)) {\n return 'W';\n }\n if ((0x0020 <= codePoint && codePoint <= 0x007E) ||\n (0x00A2 <= codePoint && codePoint <= 0x00A3) ||\n (0x00A5 <= codePoint && codePoint <= 0x00A6) ||\n (0x00AC == codePoint) ||\n (0x00AF == codePoint) ||\n (0x27E6 <= codePoint && codePoint <= 0x27ED) ||\n (0x2985 <= codePoint && codePoint <= 0x2986)) {\n return 'Na';\n }\n if ((0x00A1 == codePoint) ||\n (0x00A4 == codePoint) ||\n (0x00A7 <= codePoint && codePoint <= 0x00A8) ||\n (0x00AA == codePoint) ||\n (0x00AD <= codePoint && codePoint <= 0x00AE) ||\n (0x00B0 <= codePoint && codePoint <= 0x00B4) ||\n (0x00B6 <= codePoint && codePoint <= 0x00BA) ||\n (0x00BC <= codePoint && codePoint <= 0x00BF) ||\n (0x00C6 == codePoint) ||\n (0x00D0 == codePoint) ||\n (0x00D7 <= codePoint && codePoint <= 0x00D8) ||\n (0x00DE <= codePoint && codePoint <= 0x00E1) ||\n (0x00E6 == codePoint) ||\n (0x00E8 <= codePoint && codePoint <= 0x00EA) ||\n (0x00EC <= codePoint && codePoint <= 0x00ED) ||\n (0x00F0 == codePoint) ||\n (0x00F2 <= codePoint && codePoint <= 0x00F3) ||\n (0x00F7 <= codePoint && codePoint <= 0x00FA) ||\n (0x00FC == codePoint) ||\n (0x00FE == codePoint) ||\n (0x0101 == codePoint) ||\n (0x0111 == codePoint) ||\n (0x0113 == codePoint) ||\n (0x011B == codePoint) ||\n (0x0126 <= codePoint && codePoint <= 0x0127) ||\n (0x012B == codePoint) ||\n (0x0131 <= codePoint && codePoint <= 0x0133) ||\n (0x0138 == codePoint) ||\n (0x013F <= codePoint && codePoint <= 0x0142) ||\n (0x0144 == codePoint) ||\n (0x0148 <= codePoint && codePoint <= 0x014B) ||\n (0x014D == codePoint) ||\n (0x0152 <= codePoint && codePoint <= 0x0153) ||\n (0x0166 <= codePoint && codePoint <= 0x0167) ||\n (0x016B == codePoint) ||\n (0x01CE == codePoint) ||\n (0x01D0 == codePoint) ||\n (0x01D2 == codePoint) ||\n (0x01D4 == codePoint) ||\n (0x01D6 == codePoint) ||\n (0x01D8 == codePoint) ||\n (0x01DA == codePoint) ||\n (0x01DC == codePoint) ||\n (0x0251 == codePoint) ||\n (0x0261 == codePoint) ||\n (0x02C4 == codePoint) ||\n (0x02C7 == codePoint) ||\n (0x02C9 <= codePoint && codePoint <= 0x02CB) ||\n (0x02CD == codePoint) ||\n (0x02D0 == codePoint) ||\n (0x02D8 <= codePoint && codePoint <= 0x02DB) ||\n (0x02DD == codePoint) ||\n (0x02DF == codePoint) ||\n (0x0300 <= codePoint && codePoint <= 0x036F) ||\n (0x0391 <= codePoint && codePoint <= 0x03A1) ||\n (0x03A3 <= codePoint && codePoint <= 0x03A9) ||\n (0x03B1 <= codePoint && codePoint <= 0x03C1) ||\n (0x03C3 <= codePoint && codePoint <= 0x03C9) ||\n (0x0401 == codePoint) ||\n (0x0410 <= codePoint && codePoint <= 0x044F) ||\n (0x0451 == codePoint) ||\n (0x2010 == codePoint) ||\n (0x2013 <= codePoint && codePoint <= 0x2016) ||\n (0x2018 <= codePoint && codePoint <= 0x2019) ||\n (0x201C <= codePoint && codePoint <= 0x201D) ||\n (0x2020 <= codePoint && codePoint <= 0x2022) ||\n (0x2024 <= codePoint && codePoint <= 0x2027) ||\n (0x2030 == codePoint) ||\n (0x2032 <= codePoint && codePoint <= 0x2033) ||\n (0x2035 == codePoint) ||\n (0x203B == codePoint) ||\n (0x203E == codePoint) ||\n (0x2074 == codePoint) ||\n (0x207F == codePoint) ||\n (0x2081 <= codePoint && codePoint <= 0x2084) ||\n (0x20AC == codePoint) ||\n (0x2103 == codePoint) ||\n (0x2105 == codePoint) ||\n (0x2109 == codePoint) ||\n (0x2113 == codePoint) ||\n (0x2116 == codePoint) ||\n (0x2121 <= codePoint && codePoint <= 0x2122) ||\n (0x2126 == codePoint) ||\n (0x212B == codePoint) ||\n (0x2153 <= codePoint && codePoint <= 0x2154) ||\n (0x215B <= codePoint && codePoint <= 0x215E) ||\n (0x2160 <= codePoint && codePoint <= 0x216B) ||\n (0x2170 <= codePoint && codePoint <= 0x2179) ||\n (0x2189 == codePoint) ||\n (0x2190 <= codePoint && codePoint <= 0x2199) ||\n (0x21B8 <= codePoint && codePoint <= 0x21B9) ||\n (0x21D2 == codePoint) ||\n (0x21D4 == codePoint) ||\n (0x21E7 == codePoint) ||\n (0x2200 == codePoint) ||\n (0x2202 <= codePoint && codePoint <= 0x2203) ||\n (0x2207 <= codePoint && codePoint <= 0x2208) ||\n (0x220B == codePoint) ||\n (0x220F == codePoint) ||\n (0x2211 == codePoint) ||\n (0x2215 == codePoint) ||\n (0x221A == codePoint) ||\n (0x221D <= codePoint && codePoint <= 0x2220) ||\n (0x2223 == codePoint) ||\n (0x2225 == codePoint) ||\n (0x2227 <= codePoint && codePoint <= 0x222C) ||\n (0x222E == codePoint) ||\n (0x2234 <= codePoint && codePoint <= 0x2237) ||\n (0x223C <= codePoint && codePoint <= 0x223D) ||\n (0x2248 == codePoint) ||\n (0x224C == codePoint) ||\n (0x2252 == codePoint) ||\n (0x2260 <= codePoint && codePoint <= 0x2261) ||\n (0x2264 <= codePoint && codePoint <= 0x2267) ||\n (0x226A <= codePoint && codePoint <= 0x226B) ||\n (0x226E <= codePoint && codePoint <= 0x226F) ||\n (0x2282 <= codePoint && codePoint <= 0x2283) ||\n (0x2286 <= codePoint && codePoint <= 0x2287) ||\n (0x2295 == codePoint) ||\n (0x2299 == codePoint) ||\n (0x22A5 == codePoint) ||\n (0x22BF == codePoint) ||\n (0x2312 == codePoint) ||\n (0x2460 <= codePoint && codePoint <= 0x24E9) ||\n (0x24EB <= codePoint && codePoint <= 0x254B) ||\n (0x2550 <= codePoint && codePoint <= 0x2573) ||\n (0x2580 <= codePoint && codePoint <= 0x258F) ||\n (0x2592 <= codePoint && codePoint <= 0x2595) ||\n (0x25A0 <= codePoint && codePoint <= 0x25A1) ||\n (0x25A3 <= codePoint && codePoint <= 0x25A9) ||\n (0x25B2 <= codePoint && codePoint <= 0x25B3) ||\n (0x25B6 <= codePoint && codePoint <= 0x25B7) ||\n (0x25BC <= codePoint && codePoint <= 0x25BD) ||\n (0x25C0 <= codePoint && codePoint <= 0x25C1) ||\n (0x25C6 <= codePoint && codePoint <= 0x25C8) ||\n (0x25CB == codePoint) ||\n (0x25CE <= codePoint && codePoint <= 0x25D1) ||\n (0x25E2 <= codePoint && codePoint <= 0x25E5) ||\n (0x25EF == codePoint) ||\n (0x2605 <= codePoint && codePoint <= 0x2606) ||\n (0x2609 == codePoint) ||\n (0x260E <= codePoint && codePoint <= 0x260F) ||\n (0x2614 <= codePoint && codePoint <= 0x2615) ||\n (0x261C == codePoint) ||\n (0x261E == codePoint) ||\n (0x2640 == codePoint) ||\n (0x2642 == codePoint) ||\n (0x2660 <= codePoint && codePoint <= 0x2661) ||\n (0x2663 <= codePoint && codePoint <= 0x2665) ||\n (0x2667 <= codePoint && codePoint <= 0x266A) ||\n (0x266C <= codePoint && codePoint <= 0x266D) ||\n (0x266F == codePoint) ||\n (0x269E <= codePoint && codePoint <= 0x269F) ||\n (0x26BE <= codePoint && codePoint <= 0x26BF) ||\n (0x26C4 <= codePoint && codePoint <= 0x26CD) ||\n (0x26CF <= codePoint && codePoint <= 0x26E1) ||\n (0x26E3 == codePoint) ||\n (0x26E8 <= codePoint && codePoint <= 0x26FF) ||\n (0x273D == codePoint) ||\n (0x2757 == codePoint) ||\n (0x2776 <= codePoint && codePoint <= 0x277F) ||\n (0x2B55 <= codePoint && codePoint <= 0x2B59) ||\n (0x3248 <= codePoint && codePoint <= 0x324F) ||\n (0xE000 <= codePoint && codePoint <= 0xF8FF) ||\n (0xFE00 <= codePoint && codePoint <= 0xFE0F) ||\n (0xFFFD == codePoint) ||\n (0x1F100 <= codePoint && codePoint <= 0x1F10A) ||\n (0x1F110 <= codePoint && codePoint <= 0x1F12D) ||\n (0x1F130 <= codePoint && codePoint <= 0x1F169) ||\n (0x1F170 <= codePoint && codePoint <= 0x1F19A) ||\n (0xE0100 <= codePoint && codePoint <= 0xE01EF) ||\n (0xF0000 <= codePoint && codePoint <= 0xFFFFD) ||\n (0x100000 <= codePoint && codePoint <= 0x10FFFD)) {\n return 'A';\n }\n\n return 'N';\n};\n\neaw.characterLength = function(character) {\n var code = this.eastAsianWidth(character);\n if (code == 'F' || code == 'W' || code == 'A') {\n return 2;\n } else {\n return 1;\n }\n};\n\n// Split a string considering surrogate-pairs.\nfunction stringToArray(string) {\n return string.match(/[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]|[^\\uD800-\\uDFFF]/g) || [];\n}\n\neaw.length = function(string) {\n var characters = stringToArray(string);\n var len = 0;\n for (var i = 0; i < characters.length; i++) {\n len = len + this.characterLength(characters[i]);\n }\n return len;\n};\n\neaw.slice = function(text, start, end) {\n textLen = eaw.length(text)\n start = start ? start : 0;\n end = end ? end : 1;\n if (start < 0) {\n start = textLen + start;\n }\n if (end < 0) {\n end = textLen + end;\n }\n var result = '';\n var eawLen = 0;\n var chars = stringToArray(text);\n for (var i = 0; i < chars.length; i++) {\n var char = chars[i];\n var charLen = eaw.length(char);\n if (eawLen >= start - (charLen == 2 ? 1 : 0)) {\n if (eawLen + charLen <= end) {\n result += char;\n } else {\n break;\n }\n }\n eawLen += charLen;\n }\n return result;\n};\n", "\"use strict\";\n\nmodule.exports = function () {\n // https://mths.be/emoji\n return /\\uD83C\\uDFF4\\uDB40\\uDC67\\uDB40\\uDC62(?:\\uDB40\\uDC77\\uDB40\\uDC6C\\uDB40\\uDC73|\\uDB40\\uDC73\\uDB40\\uDC63\\uDB40\\uDC74|\\uDB40\\uDC65\\uDB40\\uDC6E\\uDB40\\uDC67)\\uDB40\\uDC7F|(?:\\uD83E\\uDDD1\\uD83C\\uDFFF\\u200D\\u2764\\uFE0F\\u200D(?:\\uD83D\\uDC8B\\u200D)?\\uD83E\\uDDD1|\\uD83D\\uDC69\\uD83C\\uDFFF\\u200D\\uD83E\\uDD1D\\u200D(?:\\uD83D[\\uDC68\\uDC69]))(?:\\uD83C[\\uDFFB-\\uDFFE])|(?:\\uD83E\\uDDD1\\uD83C\\uDFFE\\u200D\\u2764\\uFE0F\\u200D(?:\\uD83D\\uDC8B\\u200D)?\\uD83E\\uDDD1|\\uD83D\\uDC69\\uD83C\\uDFFE\\u200D\\uD83E\\uDD1D\\u200D(?:\\uD83D[\\uDC68\\uDC69]))(?:\\uD83C[\\uDFFB-\\uDFFD\\uDFFF])|(?:\\uD83E\\uDDD1\\uD83C\\uDFFD\\u200D\\u2764\\uFE0F\\u200D(?:\\uD83D\\uDC8B\\u200D)?\\uD83E\\uDDD1|\\uD83D\\uDC69\\uD83C\\uDFFD\\u200D\\uD83E\\uDD1D\\u200D(?:\\uD83D[\\uDC68\\uDC69]))(?:\\uD83C[\\uDFFB\\uDFFC\\uDFFE\\uDFFF])|(?:\\uD83E\\uDDD1\\uD83C\\uDFFC\\u200D\\u2764\\uFE0F\\u200D(?:\\uD83D\\uDC8B\\u200D)?\\uD83E\\uDDD1|\\uD83D\\uDC69\\uD83C\\uDFFC\\u200D\\uD83E\\uDD1D\\u200D(?:\\uD83D[\\uDC68\\uDC69]))(?:\\uD83C[\\uDFFB\\uDFFD-\\uDFFF])|(?:\\uD83E\\uDDD1\\uD83C\\uDFFB\\u200D\\u2764\\uFE0F\\u200D(?:\\uD83D\\uDC8B\\u200D)?\\uD83E\\uDDD1|\\uD83D\\uDC69\\uD83C\\uDFFB\\u200D\\uD83E\\uDD1D\\u200D(?:\\uD83D[\\uDC68\\uDC69]))(?:\\uD83C[\\uDFFC-\\uDFFF])|\\uD83D\\uDC68(?:\\uD83C\\uDFFB(?:\\u200D(?:\\u2764\\uFE0F\\u200D(?:\\uD83D\\uDC8B\\u200D\\uD83D\\uDC68(?:\\uD83C[\\uDFFB-\\uDFFF])|\\uD83D\\uDC68(?:\\uD83C[\\uDFFB-\\uDFFF]))|\\uD83E\\uDD1D\\u200D\\uD83D\\uDC68(?:\\uD83C[\\uDFFC-\\uDFFF])|[\\u2695\\u2696\\u2708]\\uFE0F|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E[\\uDDAF-\\uDDB3\\uDDBC\\uDDBD]))?|(?:\\uD83C[\\uDFFC-\\uDFFF])\\u200D\\u2764\\uFE0F\\u200D(?:\\uD83D\\uDC8B\\u200D\\uD83D\\uDC68(?:\\uD83C[\\uDFFB-\\uDFFF])|\\uD83D\\uDC68(?:\\uD83C[\\uDFFB-\\uDFFF]))|\\u200D(?:\\u2764\\uFE0F\\u200D(?:\\uD83D\\uDC8B\\u200D)?\\uD83D\\uDC68|(?:\\uD83D[\\uDC68\\uDC69])\\u200D(?:\\uD83D\\uDC66\\u200D\\uD83D\\uDC66|\\uD83D\\uDC67\\u200D(?:\\uD83D[\\uDC66\\uDC67]))|\\uD83D\\uDC66\\u200D\\uD83D\\uDC66|\\uD83D\\uDC67\\u200D(?:\\uD83D[\\uDC66\\uDC67])|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E[\\uDDAF-\\uDDB3\\uDDBC\\uDDBD])|\\uD83C\\uDFFF\\u200D(?:\\uD83E\\uDD1D\\u200D\\uD83D\\uDC68(?:\\uD83C[\\uDFFB-\\uDFFE])|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E[\\uDDAF-\\uDDB3\\uDDBC\\uDDBD])|\\uD83C\\uDFFE\\u200D(?:\\uD83E\\uDD1D\\u200D\\uD83D\\uDC68(?:\\uD83C[\\uDFFB-\\uDFFD\\uDFFF])|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E[\\uDDAF-\\uDDB3\\uDDBC\\uDDBD])|\\uD83C\\uDFFD\\u200D(?:\\uD83E\\uDD1D\\u200D\\uD83D\\uDC68(?:\\uD83C[\\uDFFB\\uDFFC\\uDFFE\\uDFFF])|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E[\\uDDAF-\\uDDB3\\uDDBC\\uDDBD])|\\uD83C\\uDFFC\\u200D(?:\\uD83E\\uDD1D\\u200D\\uD83D\\uDC68(?:\\uD83C[\\uDFFB\\uDFFD-\\uDFFF])|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E[\\uDDAF-\\uDDB3\\uDDBC\\uDDBD])|(?:\\uD83C\\uDFFF\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFE\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFD\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFC\\u200D[\\u2695\\u2696\\u2708]|\\u200D[\\u2695\\u2696\\u2708])\\uFE0F|\\u200D(?:(?:\\uD83D[\\uDC68\\uDC69])\\u200D(?:\\uD83D[\\uDC66\\uDC67])|\\uD83D[\\uDC66\\uDC67])|\\uD83C\\uDFFF|\\uD83C\\uDFFE|\\uD83C\\uDFFD|\\uD83C\\uDFFC)?|(?:\\uD83D\\uDC69(?:\\uD83C\\uDFFB\\u200D\\u2764\\uFE0F\\u200D(?:\\uD83D\\uDC8B\\u200D(?:\\uD83D[\\uDC68\\uDC69])|\\uD83D[\\uDC68\\uDC69])|(?:\\uD83C[\\uDFFC-\\uDFFF])\\u200D\\u2764\\uFE0F\\u200D(?:\\uD83D\\uDC8B\\u200D(?:\\uD83D[\\uDC68\\uDC69])|\\uD83D[\\uDC68\\uDC69]))|\\uD83E\\uDDD1(?:\\uD83C[\\uDFFB-\\uDFFF])\\u200D\\uD83E\\uDD1D\\u200D\\uD83E\\uDDD1)(?:\\uD83C[\\uDFFB-\\uDFFF])|\\uD83D\\uDC69\\u200D\\uD83D\\uDC69\\u200D(?:\\uD83D\\uDC66\\u200D\\uD83D\\uDC66|\\uD83D\\uDC67\\u200D(?:\\uD83D[\\uDC66\\uDC67]))|\\uD83D\\uDC69(?:\\u200D(?:\\u2764\\uFE0F\\u200D(?:\\uD83D\\uDC8B\\u200D(?:\\uD83D[\\uDC68\\uDC69])|\\uD83D[\\uDC68\\uDC69])|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E[\\uDDAF-\\uDDB3\\uDDBC\\uDDBD])|\\uD83C\\uDFFF\\u200D(?:\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E[\\uDDAF-\\uDDB3\\uDDBC\\uDDBD])|\\uD83C\\uDFFE\\u200D(?:\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E[\\uDDAF-\\uDDB3\\uDDBC\\uDDBD])|\\uD83C\\uDFFD\\u200D(?:\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\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\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E[\\uDDAF-\\uDDB3\\uDDBC\\uDDBD])|\\uD83C\\uDFFC\\u200D(?:\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF84\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E[\\uDDAF-\\uDDB3\\uDDBC\\uDDBD])|\\uD83C\\uDFFB\\u200D(?:\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF84\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E[\\uDDAF-\\uDDB3\\uDDBC\\uDDBD]))|\\uD83D\\uDC69\\u200D\\uD83D\\uDC66\\u200D\\uD83D\\uDC66|\\uD83D\\uDC69\\u200D\\uD83D\\uDC69\\u200D(?:\\uD83D[\\uDC66\\uDC67])|\\uD83D\\uDC69\\u200D\\uD83D\\uDC67\\u200D(?:\\uD83D[\\uDC66\\uDC67])|(?:\\uD83D\\uDC41\\uFE0F\\u200D\\uD83D\\uDDE8|\\uD83E\\uDDD1(?:\\uD83C\\uDFFF\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFE\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFD\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFC\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFB\\u200D[\\u2695\\u2696\\u2708]|\\u200D[\\u2695\\u2696\\u2708])|\\uD83D\\uDC69(?:\\uD83C\\uDFFF\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFE\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFD\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFC\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFB\\u200D[\\u2695\\u2696\\u2708]|\\u200D[\\u2695\\u2696\\u2708])|\\uD83D\\uDE36\\u200D\\uD83C\\uDF2B|\\uD83C\\uDFF3\\uFE0F\\u200D\\u26A7|\\uD83D\\uDC3B\\u200D\\u2744|(?:(?:\\uD83C[\\uDFC3\\uDFC4\\uDFCA]|\\uD83D[\\uDC6E\\uDC70\\uDC71\\uDC73\\uDC77\\uDC81\\uDC82\\uDC86\\uDC87\\uDE45-\\uDE47\\uDE4B\\uDE4D\\uDE4E\\uDEA3\\uDEB4-\\uDEB6]|\\uD83E[\\uDD26\\uDD35\\uDD37-\\uDD39\\uDD3D\\uDD3E\\uDDB8\\uDDB9\\uDDCD-\\uDDCF\\uDDD4\\uDDD6-\\uDDDD])(?:\\uD83C[\\uDFFB-\\uDFFF])|\\uD83D\\uDC6F|\\uD83E[\\uDD3C\\uDDDE\\uDDDF])\\u200D[\\u2640\\u2642]|(?:\\u26F9|\\uD83C[\\uDFCB\\uDFCC]|\\uD83D\\uDD75)(?:\\uFE0F|\\uD83C[\\uDFFB-\\uDFFF])\\u200D[\\u2640\\u2642]|\\uD83C\\uDFF4\\u200D\\u2620|(?:\\uD83C[\\uDFC3\\uDFC4\\uDFCA]|\\uD83D[\\uDC6E\\uDC70\\uDC71\\uDC73\\uDC77\\uDC81\\uDC82\\uDC86\\uDC87\\uDE45-\\uDE47\\uDE4B\\uDE4D\\uDE4E\\uDEA3\\uDEB4-\\uDEB6]|\\uD83E[\\uDD26\\uDD35\\uDD37-\\uDD39\\uDD3D\\uDD3E\\uDDB8\\uDDB9\\uDDCD-\\uDDCF\\uDDD4\\uDDD6-\\uDDDD])\\u200D[\\u2640\\u2642]|[\\xA9\\xAE\\u203C\\u2049\\u2122\\u2139\\u2194-\\u2199\\u21A9\\u21AA\\u2328\\u23CF\\u23ED-\\u23EF\\u23F1\\u23F2\\u23F8-\\u23FA\\u24C2\\u25AA\\u25AB\\u25B6\\u25C0\\u25FB\\u25FC\\u2600-\\u2604\\u260E\\u2611\\u2618\\u2620\\u2622\\u2623\\u2626\\u262A\\u262E\\u262F\\u2638-\\u263A\\u2640\\u2642\\u265F\\u2660\\u2663\\u2665\\u2666\\u2668\\u267B\\u267E\\u2692\\u2694-\\u2697\\u2699\\u269B\\u269C\\u26A0\\u26A7\\u26B0\\u26B1\\u26C8\\u26CF\\u26D1\\u26D3\\u26E9\\u26F0\\u26F1\\u26F4\\u26F7\\u26F8\\u2702\\u2708\\u2709\\u270F\\u2712\\u2714\\u2716\\u271D\\u2721\\u2733\\u2734\\u2744\\u2747\\u2763\\u27A1\\u2934\\u2935\\u2B05-\\u2B07\\u3030\\u303D\\u3297\\u3299]|\\uD83C[\\uDD70\\uDD71\\uDD7E\\uDD7F\\uDE02\\uDE37\\uDF21\\uDF24-\\uDF2C\\uDF36\\uDF7D\\uDF96\\uDF97\\uDF99-\\uDF9B\\uDF9E\\uDF9F\\uDFCD\\uDFCE\\uDFD4-\\uDFDF\\uDFF5\\uDFF7]|\\uD83D[\\uDC3F\\uDCFD\\uDD49\\uDD4A\\uDD6F\\uDD70\\uDD73\\uDD76-\\uDD79\\uDD87\\uDD8A-\\uDD8D\\uDDA5\\uDDA8\\uDDB1\\uDDB2\\uDDBC\\uDDC2-\\uDDC4\\uDDD1-\\uDDD3\\uDDDC-\\uDDDE\\uDDE1\\uDDE3\\uDDE8\\uDDEF\\uDDF3\\uDDFA\\uDECB\\uDECD-\\uDECF\\uDEE0-\\uDEE5\\uDEE9\\uDEF0\\uDEF3])\\uFE0F|\\uD83C\\uDFF3\\uFE0F\\u200D\\uD83C\\uDF08|\\uD83D\\uDC69\\u200D\\uD83D\\uDC67|\\uD83D\\uDC69\\u200D\\uD83D\\uDC66|\\uD83D\\uDE35\\u200D\\uD83D\\uDCAB|\\uD83D\\uDE2E\\u200D\\uD83D\\uDCA8|\\uD83D\\uDC15\\u200D\\uD83E\\uDDBA|\\uD83E\\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DC66\\uDC67\\uDC6B-\\uDC6D\\uDC72\\uDC74-\\uDC76\\uDC78\\uDC7C\\uDC83\\uDC85\\uDC8F\\uDC91\\uDCAA\\uDD7A\\uDD95\\uDD96\\uDE2E\\uDE35\\uDE36\\uDE4C\\uDE4F\\uDEC0\\uDECC]|\\uD83E[\\uDD0C\\uDD0F\\uDD18-\\uDD1C\\uDD1E\\uDD1F\\uDD30-\\uDD34\\uDD36\\uDD77\\uDDB5\\uDDB6\\uDDBB\\uDDD2\\uDDD3\\uDDD5]|\\uD83C[\\uDFC3\\uDFC4\\uDFCA]|\\uD83D[\\uDC6E\\uDC70\\uDC71\\uDC73\\uDC77\\uDC81\\uDC82\\uDC86\\uDC87\\uDE45-\\uDE47\\uDE4B\\uDE4D\\uDE4E\\uDEA3\\uDEB4-\\uDEB6]|\\uD83E[\\uDD26\\uDD35\\uDD37-\\uDD39\\uDD3D\\uDD3E\\uDDB8\\uDDB9\\uDDCD-\\uDDCF\\uDDD4\\uDDD6-\\uDDDD]|\\uD83D\\uDC6F|\\uD83E[\\uDD3C\\uDDDE\\uDDDF]|[\\u231A\\u231B\\u23E9-\\u23EC\\u23F0\\u23F3\\u25FD\\u25FE\\u2614\\u2615\\u2648-\\u2653\\u267F\\u2693\\u26A1\\u26AA\\u26AB\\u26BD\\u26BE\\u26C4\\u26C5\\u26CE\\u26D4\\u26EA\\u26F2\\u26F3\\u26F5\\u26FA\\u26FD\\u2705\\u2728\\u274C\\u274E\\u2753-\\u2755\\u2757\\u2795-\\u2797\\u27B0\\u27BF\\u2B1B\\u2B1C\\u2B50\\u2B55]|\\uD83C[\\uDC04\\uDCCF\\uDD8E\\uDD91-\\uDD9A\\uDE01\\uDE1A\\uDE2F\\uDE32-\\uDE36\\uDE38-\\uDE3A\\uDE50\\uDE51\\uDF00-\\uDF20\\uDF2D-\\uDF35\\uDF37-\\uDF7C\\uDF7E-\\uDF84\\uDF86-\\uDF93\\uDFA0-\\uDFC1\\uDFC5\\uDFC6\\uDFC8\\uDFC9\\uDFCF-\\uDFD3\\uDFE0-\\uDFF0\\uDFF8-\\uDFFF]|\\uD83D[\\uDC00-\\uDC07\\uDC09-\\uDC14\\uDC16-\\uDC3A\\uDC3C-\\uDC3E\\uDC40\\uDC44\\uDC45\\uDC51-\\uDC65\\uDC6A\\uDC79-\\uDC7B\\uDC7D-\\uDC80\\uDC84\\uDC88-\\uDC8E\\uDC90\\uDC92-\\uDCA9\\uDCAB-\\uDCFC\\uDCFF-\\uDD3D\\uDD4B-\\uDD4E\\uDD50-\\uDD67\\uDDA4\\uDDFB-\\uDE2D\\uDE2F-\\uDE34\\uDE37-\\uDE44\\uDE48-\\uDE4A\\uDE80-\\uDEA2\\uDEA4-\\uDEB3\\uDEB7-\\uDEBF\\uDEC1-\\uDEC5\\uDED0-\\uDED2\\uDED5-\\uDED7\\uDEEB\\uDEEC\\uDEF4-\\uDEFC\\uDFE0-\\uDFEB]|\\uD83E[\\uDD0D\\uDD0E\\uDD10-\\uDD17\\uDD1D\\uDD20-\\uDD25\\uDD27-\\uDD2F\\uDD3A\\uDD3F-\\uDD45\\uDD47-\\uDD76\\uDD78\\uDD7A-\\uDDB4\\uDDB7\\uDDBA\\uDDBC-\\uDDCB\\uDDD0\\uDDE0-\\uDDFF\\uDE70-\\uDE74\\uDE78-\\uDE7A\\uDE80-\\uDE86\\uDE90-\\uDEA8\\uDEB0-\\uDEB6\\uDEC0-\\uDEC2\\uDED0-\\uDED6]|(?:[\\u231A\\u231B\\u23E9-\\u23EC\\u23F0\\u23F3\\u25FD\\u25FE\\u2614\\u2615\\u2648-\\u2653\\u267F\\u2693\\u26A1\\u26AA\\u26AB\\u26BD\\u26BE\\u26C4\\u26C5\\u26CE\\u26D4\\u26EA\\u26F2\\u26F3\\u26F5\\u26FA\\u26FD\\u2705\\u270A\\u270B\\u2728\\u274C\\u274E\\u2753-\\u2755\\u2757\\u2795-\\u2797\\u27B0\\u27BF\\u2B1B\\u2B1C\\u2B50\\u2B55]|\\uD83C[\\uDC04\\uDCCF\\uDD8E\\uDD91-\\uDD9A\\uDDE6-\\uDDFF\\uDE01\\uDE1A\\uDE2F\\uDE32-\\uDE36\\uDE38-\\uDE3A\\uDE50\\uDE51\\uDF00-\\uDF20\\uDF2D-\\uDF35\\uDF37-\\uDF7C\\uDF7E-\\uDF93\\uDFA0-\\uDFCA\\uDFCF-\\uDFD3\\uDFE0-\\uDFF0\\uDFF4\\uDFF8-\\uDFFF]|\\uD83D[\\uDC00-\\uDC3E\\uDC40\\uDC42-\\uDCFC\\uDCFF-\\uDD3D\\uDD4B-\\uDD4E\\uDD50-\\uDD67\\uDD7A\\uDD95\\uDD96\\uDDA4\\uDDFB-\\uDE4F\\uDE80-\\uDEC5\\uDECC\\uDED0-\\uDED2\\uDED5-\\uDED7\\uDEEB\\uDEEC\\uDEF4-\\uDEFC\\uDFE0-\\uDFEB]|\\uD83E[\\uDD0C-\\uDD3A\\uDD3C-\\uDD45\\uDD47-\\uDD78\\uDD7A-\\uDDCB\\uDDCD-\\uDDFF\\uDE70-\\uDE74\\uDE78-\\uDE7A\\uDE80-\\uDE86\\uDE90-\\uDEA8\\uDEB0-\\uDEB6\\uDEC0-\\uDEC2\\uDED0-\\uDED6])|(?:[#\\*0-9\\xA9\\xAE\\u203C\\u2049\\u2122\\u2139\\u2194-\\u2199\\u21A9\\u21AA\\u231A\\u231B\\u2328\\u23CF\\u23E9-\\u23F3\\u23F8-\\u23FA\\u24C2\\u25AA\\u25AB\\u25B6\\u25C0\\u25FB-\\u25FE\\u2600-\\u2604\\u260E\\u2611\\u2614\\u2615\\u2618\\u261D\\u2620\\u2622\\u2623\\u2626\\u262A\\u262E\\u262F\\u2638-\\u263A\\u2640\\u2642\\u2648-\\u2653\\u265F\\u2660\\u2663\\u2665\\u2666\\u2668\\u267B\\u267E\\u267F\\u2692-\\u2697\\u2699\\u269B\\u269C\\u26A0\\u26A1\\u26A7\\u26AA\\u26AB\\u26B0\\u26B1\\u26BD\\u26BE\\u26C4\\u26C5\\u26C8\\u26CE\\u26CF\\u26D1\\u26D3\\u26D4\\u26E9\\u26EA\\u26F0-\\u26F5\\u26F7-\\u26FA\\u26FD\\u2702\\u2705\\u2708-\\u270D\\u270F\\u2712\\u2714\\u2716\\u271D\\u2721\\u2728\\u2733\\u2734\\u2744\\u2747\\u274C\\u274E\\u2753-\\u2755\\u2757\\u2763\\u2764\\u2795-\\u2797\\u27A1\\u27B0\\u27BF\\u2934\\u2935\\u2B05-\\u2B07\\u2B1B\\u2B1C\\u2B50\\u2B55\\u3030\\u303D\\u3297\\u3299]|\\uD83C[\\uDC04\\uDCCF\\uDD70\\uDD71\\uDD7E\\uDD7F\\uDD8E\\uDD91-\\uDD9A\\uDDE6-\\uDDFF\\uDE01\\uDE02\\uDE1A\\uDE2F\\uDE32-\\uDE3A\\uDE50\\uDE51\\uDF00-\\uDF21\\uDF24-\\uDF93\\uDF96\\uDF97\\uDF99-\\uDF9B\\uDF9E-\\uDFF0\\uDFF3-\\uDFF5\\uDFF7-\\uDFFF]|\\uD83D[\\uDC00-\\uDCFD\\uDCFF-\\uDD3D\\uDD49-\\uDD4E\\uDD50-\\uDD67\\uDD6F\\uDD70\\uDD73-\\uDD7A\\uDD87\\uDD8A-\\uDD8D\\uDD90\\uDD95\\uDD96\\uDDA4\\uDDA5\\uDDA8\\uDDB1\\uDDB2\\uDDBC\\uDDC2-\\uDDC4\\uDDD1-\\uDDD3\\uDDDC-\\uDDDE\\uDDE1\\uDDE3\\uDDE8\\uDDEF\\uDDF3\\uDDFA-\\uDE4F\\uDE80-\\uDEC5\\uDECB-\\uDED2\\uDED5-\\uDED7\\uDEE0-\\uDEE5\\uDEE9\\uDEEB\\uDEEC\\uDEF0\\uDEF3-\\uDEFC\\uDFE0-\\uDFEB]|\\uD83E[\\uDD0C-\\uDD3A\\uDD3C-\\uDD45\\uDD47-\\uDD78\\uDD7A-\\uDDCB\\uDDCD-\\uDDFF\\uDE70-\\uDE74\\uDE78-\\uDE7A\\uDE80-\\uDE86\\uDE90-\\uDEA8\\uDEB0-\\uDEB6\\uDEC0-\\uDEC2\\uDED0-\\uDED6])\\uFE0F|(?:[\\u261D\\u26F9\\u270A-\\u270D]|\\uD83C[\\uDF85\\uDFC2-\\uDFC4\\uDFC7\\uDFCA-\\uDFCC]|\\uD83D[\\uDC42\\uDC43\\uDC46-\\uDC50\\uDC66-\\uDC78\\uDC7C\\uDC81-\\uDC83\\uDC85-\\uDC87\\uDC8F\\uDC91\\uDCAA\\uDD74\\uDD75\\uDD7A\\uDD90\\uDD95\\uDD96\\uDE45-\\uDE47\\uDE4B-\\uDE4F\\uDEA3\\uDEB4-\\uDEB6\\uDEC0\\uDECC]|\\uD83E[\\uDD0C\\uDD0F\\uDD18-\\uDD1F\\uDD26\\uDD30-\\uDD39\\uDD3C-\\uDD3E\\uDD77\\uDDB5\\uDDB6\\uDDB8\\uDDB9\\uDDBB\\uDDCD-\\uDDCF\\uDDD1-\\uDDDD])/g;\n};\n", "import stripAnsi from 'strip-ansi';\nimport eastAsianWidth from 'eastasianwidth';\nimport emojiRegex from 'emoji-regex';\n\nexport default function stringWidth(string, options = {}) {\n\tif (typeof string !== 'string' || string.length === 0) {\n\t\treturn 0;\n\t}\n\n\toptions = {\n\t\tambiguousIsNarrow: true,\n\t\t...options\n\t};\n\n\tstring = stripAnsi(string);\n\n\tif (string.length === 0) {\n\t\treturn 0;\n\t}\n\n\tstring = string.replace(emojiRegex(), ' ');\n\n\tconst ambiguousCharacterWidth = options.ambiguousIsNarrow ? 1 : 2;\n\tlet width = 0;\n\n\tfor (const character of string) {\n\t\tconst codePoint = character.codePointAt(0);\n\n\t\t// Ignore control characters\n\t\tif (codePoint <= 0x1F || (codePoint >= 0x7F && codePoint <= 0x9F)) {\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Ignore combining characters\n\t\tif (codePoint >= 0x300 && codePoint <= 0x36F) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst code = eastAsianWidth.eastAsianWidth(character);\n\t\tswitch (code) {\n\t\t\tcase 'F':\n\t\t\tcase 'W':\n\t\t\t\twidth += 2;\n\t\t\t\tbreak;\n\t\t\tcase 'A':\n\t\t\t\twidth += ambiguousCharacterWidth;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\twidth += 1;\n\t\t}\n\t}\n\n\treturn width;\n}\n", "const ANSI_BACKGROUND_OFFSET = 10;\n\nconst wrapAnsi16 = (offset = 0) => code => `\\u001B[${code + offset}m`;\n\nconst wrapAnsi256 = (offset = 0) => code => `\\u001B[${38 + offset};5;${code}m`;\n\nconst wrapAnsi16m = (offset = 0) => (red, green, blue) => `\\u001B[${38 + offset};2;${red};${green};${blue}m`;\n\nconst styles = {\n\tmodifier: {\n\t\treset: [0, 0],\n\t\t// 21 isn't widely supported and 22 does the same thing\n\t\tbold: [1, 22],\n\t\tdim: [2, 22],\n\t\titalic: [3, 23],\n\t\tunderline: [4, 24],\n\t\toverline: [53, 55],\n\t\tinverse: [7, 27],\n\t\thidden: [8, 28],\n\t\tstrikethrough: [9, 29],\n\t},\n\tcolor: {\n\t\tblack: [30, 39],\n\t\tred: [31, 39],\n\t\tgreen: [32, 39],\n\t\tyellow: [33, 39],\n\t\tblue: [34, 39],\n\t\tmagenta: [35, 39],\n\t\tcyan: [36, 39],\n\t\twhite: [37, 39],\n\n\t\t// Bright color\n\t\tblackBright: [90, 39],\n\t\tgray: [90, 39], // Alias of `blackBright`\n\t\tgrey: [90, 39], // Alias of `blackBright`\n\t\tredBright: [91, 39],\n\t\tgreenBright: [92, 39],\n\t\tyellowBright: [93, 39],\n\t\tblueBright: [94, 39],\n\t\tmagentaBright: [95, 39],\n\t\tcyanBright: [96, 39],\n\t\twhiteBright: [97, 39],\n\t},\n\tbgColor: {\n\t\tbgBlack: [40, 49],\n\t\tbgRed: [41, 49],\n\t\tbgGreen: [42, 49],\n\t\tbgYellow: [43, 49],\n\t\tbgBlue: [44, 49],\n\t\tbgMagenta: [45, 49],\n\t\tbgCyan: [46, 49],\n\t\tbgWhite: [47, 49],\n\n\t\t// Bright color\n\t\tbgBlackBright: [100, 49],\n\t\tbgGray: [100, 49], // Alias of `bgBlackBright`\n\t\tbgGrey: [100, 49], // Alias of `bgBlackBright`\n\t\tbgRedBright: [101, 49],\n\t\tbgGreenBright: [102, 49],\n\t\tbgYellowBright: [103, 49],\n\t\tbgBlueBright: [104, 49],\n\t\tbgMagentaBright: [105, 49],\n\t\tbgCyanBright: [106, 49],\n\t\tbgWhiteBright: [107, 49],\n\t},\n};\n\nexport const modifierNames = Object.keys(styles.modifier);\nexport const foregroundColorNames = Object.keys(styles.color);\nexport const backgroundColorNames = Object.keys(styles.bgColor);\nexport const colorNames = [...foregroundColorNames, ...backgroundColorNames];\n\nfunction assembleStyles() {\n\tconst codes = new Map();\n\n\tfor (const [groupName, group] of Object.entries(styles)) {\n\t\tfor (const [styleName, style] of Object.entries(group)) {\n\t\t\tstyles[styleName] = {\n\t\t\t\topen: `\\u001B[${style[0]}m`,\n\t\t\t\tclose: `\\u001B[${style[1]}m`,\n\t\t\t};\n\n\t\t\tgroup[styleName] = styles[styleName];\n\n\t\t\tcodes.set(style[0], style[1]);\n\t\t}\n\n\t\tObject.defineProperty(styles, groupName, {\n\t\t\tvalue: group,\n\t\t\tenumerable: false,\n\t\t});\n\t}\n\n\tObject.defineProperty(styles, 'codes', {\n\t\tvalue: codes,\n\t\tenumerable: false,\n\t});\n\n\tstyles.color.close = '\\u001B[39m';\n\tstyles.bgColor.close = '\\u001B[49m';\n\n\tstyles.color.ansi = wrapAnsi16();\n\tstyles.color.ansi256 = wrapAnsi256();\n\tstyles.color.ansi16m = wrapAnsi16m();\n\tstyles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);\n\tstyles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);\n\tstyles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);\n\n\t// From https://github.com/Qix-/color-convert/blob/3f0e0d4e92e235796ccb17f6e85c72094a651f49/conversions.js\n\tObject.defineProperties(styles, {\n\t\trgbToAnsi256: {\n\t\t\tvalue: (red, green, blue) => {\n\t\t\t\t// We use the extended greyscale palette here, with the exception of\n\t\t\t\t// black and white. normal palette only has 4 greyscale shades.\n\t\t\t\tif (red === green && green === blue) {\n\t\t\t\t\tif (red < 8) {\n\t\t\t\t\t\treturn 16;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (red > 248) {\n\t\t\t\t\t\treturn 231;\n\t\t\t\t\t}\n\n\t\t\t\t\treturn Math.round(((red - 8) / 247) * 24) + 232;\n\t\t\t\t}\n\n\t\t\t\treturn 16\n\t\t\t\t\t+ (36 * Math.round(red / 255 * 5))\n\t\t\t\t\t+ (6 * Math.round(green / 255 * 5))\n\t\t\t\t\t+ Math.round(blue / 255 * 5);\n\t\t\t},\n\t\t\tenumerable: false,\n\t\t},\n\t\thexToRgb: {\n\t\t\tvalue: hex => {\n\t\t\t\tconst matches = /[a-f\\d]{6}|[a-f\\d]{3}/i.exec(hex.toString(16));\n\t\t\t\tif (!matches) {\n\t\t\t\t\treturn [0, 0, 0];\n\t\t\t\t}\n\n\t\t\t\tlet [colorString] = matches;\n\n\t\t\t\tif (colorString.length === 3) {\n\t\t\t\t\tcolorString = [...colorString].map(character => character + character).join('');\n\t\t\t\t}\n\n\t\t\t\tconst integer = Number.parseInt(colorString, 16);\n\n\t\t\t\treturn [\n\t\t\t\t\t/* eslint-disable no-bitwise */\n\t\t\t\t\t(integer >> 16) & 0xFF,\n\t\t\t\t\t(integer >> 8) & 0xFF,\n\t\t\t\t\tinteger & 0xFF,\n\t\t\t\t\t/* eslint-enable no-bitwise */\n\t\t\t\t];\n\t\t\t},\n\t\t\tenumerable: false,\n\t\t},\n\t\thexToAnsi256: {\n\t\t\tvalue: hex => styles.rgbToAnsi256(...styles.hexToRgb(hex)),\n\t\t\tenumerable: false,\n\t\t},\n\t\tansi256ToAnsi: {\n\t\t\tvalue: code => {\n\t\t\t\tif (code < 8) {\n\t\t\t\t\treturn 30 + code;\n\t\t\t\t}\n\n\t\t\t\tif (code < 16) {\n\t\t\t\t\treturn 90 + (code - 8);\n\t\t\t\t}\n\n\t\t\t\tlet red;\n\t\t\t\tlet green;\n\t\t\t\tlet blue;\n\n\t\t\t\tif (code >= 232) {\n\t\t\t\t\tred = (((code - 232) * 10) + 8) / 255;\n\t\t\t\t\tgreen = red;\n\t\t\t\t\tblue = red;\n\t\t\t\t} else {\n\t\t\t\t\tcode -= 16;\n\n\t\t\t\t\tconst remainder = code % 36;\n\n\t\t\t\t\tred = Math.floor(code / 36) / 5;\n\t\t\t\t\tgreen = Math.floor(remainder / 6) / 5;\n\t\t\t\t\tblue = (remainder % 6) / 5;\n\t\t\t\t}\n\n\t\t\t\tconst value = Math.max(red, green, blue) * 2;\n\n\t\t\t\tif (value === 0) {\n\t\t\t\t\treturn 30;\n\t\t\t\t}\n\n\t\t\t\t// eslint-disable-next-line no-bitwise\n\t\t\t\tlet result = 30 + ((Math.round(blue) << 2) | (Math.round(green) << 1) | Math.round(red));\n\n\t\t\t\tif (value === 2) {\n\t\t\t\t\tresult += 60;\n\t\t\t\t}\n\n\t\t\t\treturn result;\n\t\t\t},\n\t\t\tenumerable: false,\n\t\t},\n\t\trgbToAnsi: {\n\t\t\tvalue: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)),\n\t\t\tenumerable: false,\n\t\t},\n\t\thexToAnsi: {\n\t\t\tvalue: hex => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),\n\t\t\tenumerable: false,\n\t\t},\n\t});\n\n\treturn styles;\n}\n\nconst ansiStyles = assembleStyles();\n\nexport default ansiStyles;\n", "import stringWidth from 'string-width';\nimport stripAnsi from 'strip-ansi';\nimport ansiStyles from 'ansi-styles';\n\nconst ESCAPES = new Set([\n\t'\\u001B',\n\t'\\u009B',\n]);\n\nconst END_CODE = 39;\nconst ANSI_ESCAPE_BELL = '\\u0007';\nconst ANSI_CSI = '[';\nconst ANSI_OSC = ']';\nconst ANSI_SGR_TERMINATOR = 'm';\nconst ANSI_ESCAPE_LINK = `${ANSI_OSC}8;;`;\n\nconst wrapAnsiCode = code => `${ESCAPES.values().next().value}${ANSI_CSI}${code}${ANSI_SGR_TERMINATOR}`;\nconst wrapAnsiHyperlink = uri => `${ESCAPES.values().next().value}${ANSI_ESCAPE_LINK}${uri}${ANSI_ESCAPE_BELL}`;\n\n// Calculate the length of words split on ' ', ignoring\n// the extra characters added by ansi escape codes\nconst wordLengths = string => string.split(' ').map(character => stringWidth(character));\n\n// Wrap a long word across multiple rows\n// Ansi escape codes do not count towards length\nconst wrapWord = (rows, word, columns) => {\n\tconst characters = [...word];\n\n\tlet isInsideEscape = false;\n\tlet isInsideLinkEscape = false;\n\tlet visible = stringWidth(stripAnsi(rows[rows.length - 1]));\n\n\tfor (const [index, character] of characters.entries()) {\n\t\tconst characterLength = stringWidth(character);\n\n\t\tif (visible + characterLength <= columns) {\n\t\t\trows[rows.length - 1] += character;\n\t\t} else {\n\t\t\trows.push(character);\n\t\t\tvisible = 0;\n\t\t}\n\n\t\tif (ESCAPES.has(character)) {\n\t\t\tisInsideEscape = true;\n\t\t\tisInsideLinkEscape = characters.slice(index + 1).join('').startsWith(ANSI_ESCAPE_LINK);\n\t\t}\n\n\t\tif (isInsideEscape) {\n\t\t\tif (isInsideLinkEscape) {\n\t\t\t\tif (character === ANSI_ESCAPE_BELL) {\n\t\t\t\t\tisInsideEscape = false;\n\t\t\t\t\tisInsideLinkEscape = false;\n\t\t\t\t}\n\t\t\t} else if (character === ANSI_SGR_TERMINATOR) {\n\t\t\t\tisInsideEscape = false;\n\t\t\t}\n\n\t\t\tcontinue;\n\t\t}\n\n\t\tvisible += characterLength;\n\n\t\tif (visible === columns && index < characters.length - 1) {\n\t\t\trows.push('');\n\t\t\tvisible = 0;\n\t\t}\n\t}\n\n\t// It's possible that the last row we copy over is only\n\t// ansi escape characters, handle this edge-case\n\tif (!visible && rows[rows.length - 1].length > 0 && rows.length > 1) {\n\t\trows[rows.length - 2] += rows.pop();\n\t}\n};\n\n// Trims spaces from a string ignoring invisible sequences\nconst stringVisibleTrimSpacesRight = string => {\n\tconst words = string.split(' ');\n\tlet last = words.length;\n\n\twhile (last > 0) {\n\t\tif (stringWidth(words[last - 1]) > 0) {\n\t\t\tbreak;\n\t\t}\n\n\t\tlast--;\n\t}\n\n\tif (last === words.length) {\n\t\treturn string;\n\t}\n\n\treturn words.slice(0, last).join(' ') + words.slice(last).join('');\n};\n\n// The wrap-ansi module can be invoked in either 'hard' or 'soft' wrap mode\n//\n// 'hard' will never allow a string to take up more than columns characters\n//\n// 'soft' allows long words to expand past the column length\nconst exec = (string, columns, options = {}) => {\n\tif (options.trim !== false && string.trim() === '') {\n\t\treturn '';\n\t}\n\n\tlet returnValue = '';\n\tlet escapeCode;\n\tlet escapeUrl;\n\n\tconst lengths = wordLengths(string);\n\tlet rows = [''];\n\n\tfor (const [index, word] of string.split(' ').entries()) {\n\t\tif (options.trim !== false) {\n\t\t\trows[rows.length - 1] = rows[rows.length - 1].trimStart();\n\t\t}\n\n\t\tlet rowLength = stringWidth(rows[rows.length - 1]);\n\n\t\tif (index !== 0) {\n\t\t\tif (rowLength >= columns && (options.wordWrap === false || options.trim === false)) {\n\t\t\t\t// If we start with a new word but the current row length equals the length of the columns, add a new row\n\t\t\t\trows.push('');\n\t\t\t\trowLength = 0;\n\t\t\t}\n\n\t\t\tif (rowLength > 0 || options.trim === false) {\n\t\t\t\trows[rows.length - 1] += ' ';\n\t\t\t\trowLength++;\n\t\t\t}\n\t\t}\n\n\t\t// In 'hard' wrap mode, the length of a line is never allowed to extend past 'columns'\n\t\tif (options.hard && lengths[index] > columns) {\n\t\t\tconst remainingColumns = (columns - rowLength);\n\t\t\tconst breaksStartingThisLine = 1 + Math.floor((lengths[index] - remainingColumns - 1) / columns);\n\t\t\tconst breaksStartingNextLine = Math.floor((lengths[index] - 1) / columns);\n\t\t\tif (breaksStartingNextLine < breaksStartingThisLine) {\n\t\t\t\trows.push('');\n\t\t\t}\n\n\t\t\twrapWord(rows, word, columns);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (rowLength + lengths[index] > columns && rowLength > 0 && lengths[index] > 0) {\n\t\t\tif (options.wordWrap === false && rowLength < columns) {\n\t\t\t\twrapWord(rows, word, columns);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\trows.push('');\n\t\t}\n\n\t\tif (rowLength + lengths[index] > columns && options.wordWrap === false) {\n\t\t\twrapWord(rows, word, columns);\n\t\t\tcontinue;\n\t\t}\n\n\t\trows[rows.length - 1] += word;\n\t}\n\n\tif (options.trim !== false) {\n\t\trows = rows.map(row => stringVisibleTrimSpacesRight(row));\n\t}\n\n\tconst pre = [...rows.join('\\n')];\n\n\tfor (const [index, character] of pre.entries()) {\n\t\treturnValue += character;\n\n\t\tif (ESCAPES.has(character)) {\n\t\t\tconst {groups} = new RegExp(`(?:\\\\${ANSI_CSI}(?<code>\\\\d+)m|\\\\${ANSI_ESCAPE_LINK}(?<uri>.*)${ANSI_ESCAPE_BELL})`).exec(pre.slice(index).join('')) || {groups: {}};\n\t\t\tif (groups.code !== undefined) {\n\t\t\t\tconst code = Number.parseFloat(groups.code);\n\t\t\t\tescapeCode = code === END_CODE ? undefined : code;\n\t\t\t} else if (groups.uri !== undefined) {\n\t\t\t\tescapeUrl = groups.uri.length === 0 ? undefined : groups.uri;\n\t\t\t}\n\t\t}\n\n\t\tconst code = ansiStyles.codes.get(Number(escapeCode));\n\n\t\tif (pre[index + 1] === '\\n') {\n\t\t\tif (escapeUrl) {\n\t\t\t\treturnValue += wrapAnsiHyperlink('');\n\t\t\t}\n\n\t\t\tif (escapeCode && code) {\n\t\t\t\treturnValue += wrapAnsiCode(code);\n\t\t\t}\n\t\t} else if (character === '\\n') {\n\t\t\tif (escapeCode && code) {\n\t\t\t\treturnValue += wrapAnsiCode(escapeCode);\n\t\t\t}\n\n\t\t\tif (escapeUrl) {\n\t\t\t\treturnValue += wrapAnsiHyperlink(escapeUrl);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn returnValue;\n};\n\n// For each newline, invoke the method separately\nexport default function wrapAnsi(string, columns, options) {\n\treturn String(string)\n\t\t.normalize()\n\t\t.replace(/\\r\\n/g, '\\n')\n\t\t.split('\\n')\n\t\t.map(line => exec(line, columns, options))\n\t\t.join('\\n');\n}\n", "const actions = ['up', 'down', 'left', 'right', 'space', 'enter', 'cancel'] as const;\nexport type Action = (typeof actions)[number];\n\n/** Global settings for Clack programs, stored in memory */\ninterface InternalClackSettings {\n\tactions: Set<Action>;\n\taliases: Map<string, Action>;\n}\n\nexport const settings: InternalClackSettings = {\n\tactions: new Set(actions),\n\taliases: new Map<string, Action>([\n\t\t// vim support\n\t\t['k', 'up'],\n\t\t['j', 'down'],\n\t\t['h', 'left'],\n\t\t['l', 'right'],\n\t\t['\\x03', 'cancel'],\n\t\t// opinionated defaults!\n\t\t['escape', 'cancel'],\n\t]),\n};\n\nexport interface ClackSettings {\n\t/**\n\t * Set custom global aliases for the default actions.\n\t * This will not overwrite existing aliases, it will only add new ones!\n\t *\n\t * @param aliases - An object that maps aliases to actions\n\t * @default { k: 'up', j: 'down', h: 'left', l: 'right', '\\x03': 'cancel', 'escape': 'cancel' }\n\t */\n\taliases: Record<string, Action>;\n}\n\nexport function updateSettings(updates: ClackSettings) {\n\tfor (const _key in updates) {\n\t\tconst key = _key as keyof ClackSettings;\n\t\tif (!Object.hasOwn(updates, key)) continue;\n\t\tconst value = updates[key];\n\n\t\tswitch (key) {\n\t\t\tcase 'aliases': {\n\t\t\t\tfor (const alias in value) {\n\t\t\t\t\tif (!Object.hasOwn(value, alias)) continue;\n\t\t\t\t\tif (!settings.aliases.has(alias)) {\n\t\t\t\t\t\tsettings.aliases.set(alias, value[alias]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Check if a key is an alias for a default action\n * @param key - The raw key which might match to an action\n * @param action - The action to match\n * @returns boolean\n */\nexport function isActionKey(key: string | Array<string | undefined>, action: Action) {\n\tif (typeof key === 'string') {\n\t\treturn settings.aliases.get(key) === action;\n\t}\n\n\tfor (const value of key) {\n\t\tif (value === undefined) continue;\n\t\tif (isActionKey(value, action)) {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n", "export function diffLines(a: string, b: string) {\n\tif (a === b) return;\n\n\tconst aLines = a.split('\\n');\n\tconst bLines = b.split('\\n');\n\tconst diff: number[] = [];\n\n\tfor (let i = 0; i < Math.max(aLines.length, bLines.length); i++) {\n\t\tif (aLines[i] !== bLines[i]) diff.push(i);\n\t}\n\n\treturn diff;\n}\n", "import { stdin, stdout } from 'node:process';\nimport type { Key } from 'node:readline';\nimport * as readline from 'node:readline';\nimport type { Readable } from 'node:stream';\nimport { cursor } from 'sisteransi';\nimport { isActionKey } from './settings';\n\nexport * from './string';\nexport * from './settings';\n\nconst isWindows = globalThis.process.platform.startsWith('win');\n\nexport const CANCEL_SYMBOL = Symbol('clack:cancel');\n\nexport function isCancel(value: unknown): value is symbol {\n\treturn value === CANCEL_SYMBOL;\n}\n\nexport function setRawMode(input: Readable, value: boolean) {\n\tconst i = input as typeof stdin;\n\n\tif (i.isTTY) i.setRawMode(value);\n}\n\nexport function block({\n\tinput = stdin,\n\toutput = stdout,\n\toverwrite = true,\n\thideCursor = true,\n} = {}) {\n\tconst rl = readline.createInterface({\n\t\tinput,\n\t\toutput,\n\t\tprompt: '',\n\t\ttabSize: 1,\n\t});\n\treadline.emitKeypressEvents(input, rl);\n\tif (input.isTTY) input.setRawMode(true);\n\n\tconst clear = (data: Buffer, { name, sequence }: Key) => {\n\t\tconst str = String(data);\n\t\tif (isActionKey([str, name, sequence], 'cancel')) {\n\t\t\tif (hideCursor) output.write(cursor.show);\n\t\t\tprocess.exit(0);\n\t\t\treturn;\n\t\t}\n\t\tif (!overwrite) return;\n\t\tconst dx = name === 'return' ? 0 : -1;\n\t\tconst dy = name === 'return' ? -1 : 0;\n\n\t\treadline.moveCursor(output, dx, dy, () => {\n\t\t\treadline.clearLine(output, 1, () => {\n\t\t\t\tinput.once('keypress', clear);\n\t\t\t});\n\t\t});\n\t};\n\tif (hideCursor) output.write(cursor.hide);\n\tinput.once('keypress', clear);\n\n\treturn () => {\n\t\tinput.off('keypress', clear);\n\t\tif (hideCursor) output.write(cursor.show);\n\n\t\t// Prevent Windows specific issues: https://github.com/bombshell-dev/clack/issues/176\n\t\tif (input.isTTY && !isWindows) input.setRawMode(false);\n\n\t\t// @ts-expect-error fix for https://github.com/nodejs/node/issues/31762#issuecomment-1441223907\n\t\trl.terminal = false;\n\t\trl.close();\n\t};\n}\n", "import { stdin, stdout } from 'node:process';\nimport readline, { type Key, type ReadLine } from 'node:readline';\nimport type { Readable } from 'node:stream';\nimport { Writable } from 'node:stream';\nimport { cursor, erase } from 'sisteransi';\nimport wrap from 'wrap-ansi';\n\nimport { CANCEL_SYMBOL, diffLines, isActionKey, setRawMode, settings } from '../utils';\n\nimport type { ClackEvents, ClackState } from '../types';\nimport type { Action } from '../utils';\n\nexport interface PromptOptions<Self extends Prompt> {\n\trender(this: Omit<Self, 'prompt'>): string | undefined;\n\tplaceholder?: string;\n\tinitialValue?: any;\n\tvalidate?: ((value: any) => string | Error | undefined) | undefined;\n\tinput?: Readable;\n\toutput?: Writable;\n\tdebug?: boolean;\n\tsignal?: AbortSignal;\n}\n\nexport default class Prompt {\n\tprotected input: Readable;\n\tprotected output: Writable;\n\tprivate _abortSignal?: AbortSignal;\n\n\tprivate rl: ReadLine | undefined;\n\tprivate opts: Omit<PromptOptions<Prompt>, 'render' | 'input' | 'output'>;\n\tprivate _render: (context: Omit<Prompt, 'prompt'>) => string | undefined;\n\tprivate _track = false;\n\tprivate _prevFrame = '';\n\tprivate _subscribers = new Map<string, { cb: (...args: any) => any; once?: boolean }[]>();\n\tprotected _cursor = 0;\n\n\tpublic state: ClackState = 'initial';\n\tpublic error = '';\n\tpublic value: any;\n\n\tconstructor(options: PromptOptions<Prompt>, trackValue = true) {\n\t\tconst { input = stdin, output = stdout, render, signal, ...opts } = options;\n\n\t\tthis.opts = opts;\n\t\tthis.onKeypress = this.onKeypress.bind(this);\n\t\tthis.close = this.close.bind(this);\n\t\tthis.render = this.render.bind(this);\n\t\tthis._render = render.bind(this);\n\t\tthis._track = trackValue;\n\t\tthis._abortSignal = signal;\n\n\t\tthis.input = input;\n\t\tthis.output = output;\n\t}\n\n\t/**\n\t * Unsubscribe all listeners\n\t */\n\tprotected unsubscribe() {\n\t\tthis._subscribers.clear();\n\t}\n\n\t/**\n\t * Set a subscriber with opts\n\t * @param event - The event name\n\t */\n\tprivate setSubscriber<T extends keyof ClackEvents>(\n\t\tevent: T,\n\t\topts: { cb: ClackEvents[T]; once?: boolean }\n\t) {\n\t\tconst params = this._subscribers.get(event) ?? [];\n\t\tparams.push(opts);\n\t\tthis._subscribers.set(event, params);\n\t}\n\n\t/**\n\t * Subscribe to an event\n\t * @param event - The event name\n\t * @param cb - The callback\n\t */\n\tpublic on<T extends keyof ClackEvents>(event: T, cb: ClackEvents[T]) {\n\t\tthis.setSubscriber(event, { cb });\n\t}\n\n\t/**\n\t * Subscribe to an event once\n\t * @param event - The event name\n\t * @param cb - The callback\n\t */\n\tpublic once<T extends keyof ClackEvents>(event: T, cb: ClackEvents[T]) {\n\t\tthis.setSubscriber(event, { cb, once: true });\n\t}\n\n\t/**\n\t * Emit an event with data\n\t * @param event - The event name\n\t * @param data - The data to pass to the callback\n\t */\n\tpublic emit<T extends keyof ClackEvents>(event: T, ...data: Parameters<ClackEvents[T]>) {\n\t\tconst cbs = this._subscribers.get(event) ?? [];\n\t\tconst cleanup: (() => void)[] = [];\n\n\t\tfor (const subscriber of cbs) {\n\t\t\tsubscriber.cb(...data);\n\n\t\t\tif (subscriber.once) {\n\t\t\t\tcleanup.push(() => cbs.splice(cbs.indexOf(subscriber), 1));\n\t\t\t}\n\t\t}\n\n\t\tfor (const cb of cleanup) {\n\t\t\tcb();\n\t\t}\n\t}\n\n\tpublic prompt() {\n\t\treturn new Promise<string | symbol>((resolve, reject) => {\n\t\t\tif (this._abortSignal) {\n\t\t\t\tif (this._abortSignal.aborted) {\n\t\t\t\t\tthis.state = 'cancel';\n\n\t\t\t\t\tthis.close();\n\t\t\t\t\treturn resolve(CANCEL_SYMBOL);\n\t\t\t\t}\n\n\t\t\t\tthis._abortSignal.addEventListener(\n\t\t\t\t\t'abort',\n\t\t\t\t\t() => {\n\t\t\t\t\t\tthis.state = 'cancel';\n\t\t\t\t\t\tthis.close();\n\t\t\t\t\t},\n\t\t\t\t\t{ once: true }\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst sink = new Writable();\n\t\t\tsink._write = (chunk, encoding, done) => {\n\t\t\t\tif (this._track) {\n\t\t\t\t\tthis.value = this.rl?.line.replace(/\\t/g, '');\n\t\t\t\t\tthis._cursor = this.rl?.cursor ?? 0;\n\t\t\t\t\tthis.emit('value', this.value);\n\t\t\t\t}\n\t\t\t\tdone();\n\t\t\t};\n\t\t\tthis.input.pipe(sink);\n\n\t\t\tthis.rl = readline.createInterface({\n\t\t\t\tinput: this.input,\n\t\t\t\toutput: sink,\n\t\t\t\ttabSize: 2,\n\t\t\t\tprompt: '',\n\t\t\t\tescapeCodeTimeout: 50,\n\t\t\t\tterminal: true,\n\t\t\t});\n\t\t\treadline.emitKeypressEvents(this.input, this.rl);\n\t\t\tthis.rl.prompt();\n\t\t\tif (this.opts.initialValue !== undefined && this._track) {\n\t\t\t\tthis.rl.write(this.opts.initialValue);\n\t\t\t}\n\n\t\t\tthis.input.on('keypress', this.onKeypress);\n\t\t\tsetRawMode(this.input, true);\n\t\t\tthis.output.on('resize', this.render);\n\n\t\t\tthis.render();\n\n\t\t\tthis.once('submit', () => {\n\t\t\t\tthis.output.write(cursor.show);\n\t\t\t\tthis.output.off('resize', this.render);\n\t\t\t\tsetRawMode(this.input, false);\n\t\t\t\tresolve(this.value);\n\t\t\t});\n\t\t\tthis.once('cancel', () => {\n\t\t\t\tthis.output.write(cursor.show);\n\t\t\t\tthis.output.off('resize', this.render);\n\t\t\t\tsetRawMode(this.input, false);\n\t\t\t\tresolve(CANCEL_SYMBOL);\n\t\t\t});\n\t\t});\n\t}\n\n\tprivate onKeypress(char: string, key?: Key) {\n\t\tif (this.state === 'error') {\n\t\t\tthis.state = 'active';\n\t\t}\n\t\tif (key?.name) {\n\t\t\tif (!this._track && settings.aliases.has(key.name)) {\n\t\t\t\tthis.emit('cursor', settings.aliases.get(key.name));\n\t\t\t}\n\t\t\tif (settings.actions.has(key.name as Action)) {\n\t\t\t\tthis.emit('cursor', key.name as Action);\n\t\t\t}\n\t\t}\n\t\tif (char && (char.toLowerCase() === 'y' || char.toLowerCase() === 'n')) {\n\t\t\tthis.emit('confirm', char.toLowerCase() === 'y');\n\t\t}\n\t\tif (char === '\\t' && this.opts.placeholder) {\n\t\t\tif (!this.value) {\n\t\t\t\tthis.rl?.write(this.opts.placeholder);\n\t\t\t\tthis.emit('value', this.opts.placeholder);\n\t\t\t}\n\t\t}\n\t\tif (char) {\n\t\t\tthis.emit('key', char.toLowerCase());\n\t\t}\n\n\t\tif (key?.name === 'return') {\n\t\t\tif (!this.value && this.opts.placeholder) {\n\t\t\t\tthis.rl?.write(this.opts.placeholder);\n\t\t\t\tthis.emit('value', this.opts.placeholder);\n\t\t\t}\n\n\t\t\tif (this.opts.validate) {\n\t\t\t\tconst problem = this.opts.validate(this.value);\n\t\t\t\tif (problem) {\n\t\t\t\t\tthis.error = problem instanceof Error ? problem.message : problem;\n\t\t\t\t\tthis.state = 'error';\n\t\t\t\t\tthis.rl?.write(this.value);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (this.state !== 'error') {\n\t\t\t\tthis.state = 'submit';\n\t\t\t}\n\t\t}\n\n\t\tif (isActionKey([char, key?.name, key?.sequence], 'cancel')) {\n\t\t\tthis.state = 'cancel';\n\t\t}\n\t\tif (this.state === 'submit' || this.state === 'cancel') {\n\t\t\tthis.emit('finalize');\n\t\t}\n\t\tthis.render();\n\t\tif (this.state === 'submit' || this.state === 'cancel') {\n\t\t\tthis.close();\n\t\t}\n\t}\n\n\tprotected close() {\n\t\tthis.input.unpipe();\n\t\tthis.input.removeListener('keypress', this.onKeypress);\n\t\tthis.output.write('\\n');\n\t\tsetRawMode(this.input, false);\n\t\tthis.rl?.close();\n\t\tthis.rl = undefined;\n\t\tthis.emit(`${this.state}`, this.value);\n\t\tthis.unsubscribe();\n\t}\n\n\tprivate restoreCursor() {\n\t\tconst lines =\n\t\t\twrap(this._prevFrame, process.stdout.columns, { hard: true }).split('\\n').length - 1;\n\t\tthis.output.write(cursor.move(-999, lines * -1));\n\t}\n\n\tprivate render() {\n\t\tconst frame = wrap(this._render(this) ?? '', process.stdout.columns, { hard: true });\n\t\tif (frame === this._prevFrame) return;\n\n\t\tif (this.state === 'initial') {\n\t\t\tthis.output.write(cursor.hide);\n\t\t} else {\n\t\t\tconst diff = diffLines(this._prevFrame, frame);\n\t\t\tthis.restoreCursor();\n\t\t\t// If a single line has changed, only update that line\n\t\t\tif (diff && diff?.length === 1) {\n\t\t\t\tconst diffLine = diff[0];\n\t\t\t\tthis.output.write(cursor.move(0, diffLine));\n\t\t\t\tthis.output.write(erase.lines(1));\n\t\t\t\tconst lines = frame.split('\\n');\n\t\t\t\tthis.output.write(lines[diffLine]);\n\t\t\t\tthis._prevFrame = frame;\n\t\t\t\tthis.output.write(cursor.move(0, lines.length - diffLine - 1));\n\t\t\t\treturn;\n\t\t\t\t// If many lines have changed, rerender everything past the first line\n\t\t\t}\n\t\t\tif (diff && diff?.length > 1) {\n\t\t\t\tconst diffLine = diff[0];\n\t\t\t\tthis.output.write(cursor.move(0, diffLine));\n\t\t\t\tthis.output.write(erase.down());\n\t\t\t\tconst lines = frame.split('\\n');\n\t\t\t\tconst newLines = lines.slice(diffLine);\n\t\t\t\tthis.output.write(newLines.join('\\n'));\n\t\t\t\tthis._prevFrame = frame;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthis.output.write(erase.down());\n\t\t}\n\n\t\tthis.output.write(frame);\n\t\tif (this.state === 'initial') {\n\t\t\tthis.state = 'active';\n\t\t}\n\t\tthis._prevFrame = frame;\n\t}\n}\n", "import { cursor } from 'sisteransi';\nimport Prompt, { type PromptOptions } from './prompt';\n\ninterface ConfirmOptions extends PromptOptions<ConfirmPrompt> {\n\tactive: string;\n\tinactive: string;\n\tinitialValue?: boolean;\n}\nexport default class ConfirmPrompt extends Prompt {\n\tget cursor() {\n\t\treturn this.value ? 0 : 1;\n\t}\n\n\tprivate get _value() {\n\t\treturn this.cursor === 0;\n\t}\n\n\tconstructor(opts: ConfirmOptions) {\n\t\tsuper(opts, false);\n\t\tthis.value = !!opts.initialValue;\n\n\t\tthis.on('value', () => {\n\t\t\tthis.value = this._value;\n\t\t});\n\n\t\tthis.on('confirm', (confirm) => {\n\t\t\tthis.output.write(cursor.move(0, -1));\n\t\t\tthis.value = confirm;\n\t\t\tthis.state = 'submit';\n\t\t\tthis.close();\n\t\t});\n\n\t\tthis.on('cursor', () => {\n\t\t\tthis.value = !this.value;\n\t\t});\n\t}\n}\n", "import Prompt, { type PromptOptions } from './prompt';\n\ninterface GroupMultiSelectOptions<T extends { value: any }>\n\textends PromptOptions<GroupMultiSelectPrompt<T>> {\n\toptions: Record<string, T[]>;\n\tinitialValues?: T['value'][];\n\trequired?: boolean;\n\tcursorAt?: T['value'];\n\tselectableGroups?: boolean;\n}\nexport default class GroupMultiSelectPrompt<T extends { value: any }> extends Prompt {\n\toptions: (T & { group: string | boolean })[];\n\tcursor = 0;\n\t#selectableGroups: boolean;\n\n\tgetGroupItems(group: string): T[] {\n\t\treturn this.options.filter((o) => o.group === group);\n\t}\n\n\tisGroupSelected(group: string) {\n\t\tconst items = this.getGroupItems(group);\n\t\treturn items.every((i) => this.value.includes(i.value));\n\t}\n\n\tprivate toggleValue() {\n\t\tconst item = this.options[this.cursor];\n\t\tif (item.group === true) {\n\t\t\tconst group = item.value;\n\t\t\tconst groupedItems = this.getGroupItems(group);\n\t\t\tif (this.isGroupSelected(group)) {\n\t\t\t\tthis.value = this.value.filter(\n\t\t\t\t\t(v: string) => groupedItems.findIndex((i) => i.value === v) === -1\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tthis.value = [...this.value, ...groupedItems.map((i) => i.value)];\n\t\t\t}\n\t\t\tthis.value = Array.from(new Set(this.value));\n\t\t} else {\n\t\t\tconst selected = this.value.includes(item.value);\n\t\t\tthis.value = selected\n\t\t\t\t? this.value.filter((v: T['value']) => v !== item.value)\n\t\t\t\t: [...this.value, item.value];\n\t\t}\n\t}\n\n\tconstructor(opts: GroupMultiSelectOptions<T>) {\n\t\tsuper(opts, false);\n\t\tconst { options } = opts;\n\t\tthis.#selectableGroups = opts.selectableGroups !== false;\n\t\tthis.options = Object.entries(options).flatMap(([key, option]) => [\n\t\t\t{ value: key, group: true, label: key },\n\t\t\t...option.map((opt) => ({ ...opt, group: key })),\n\t\t]) as any;\n\t\tthis.value = [...(opts.initialValues ?? [])];\n\t\tthis.cursor = Math.max(\n\t\t\tthis.options.findIndex(({ value }) => value === opts.cursorAt),\n\t\t\tthis.#selectableGroups ? 0 : 1\n\t\t);\n\n\t\tthis.on('cursor', (key) => {\n\t\t\tswitch (key) {\n\t\t\t\tcase 'left':\n\t\t\t\tcase 'up': {\n\t\t\t\t\tthis.cursor = this.cursor === 0 ? this.options.length - 1 : this.cursor - 1;\n\t\t\t\t\tconst currentIsGroup = this.options[this.cursor]?.group === true;\n\t\t\t\t\tif (!this.#selectableGroups && currentIsGroup) {\n\t\t\t\t\t\tthis.cursor = this.cursor === 0 ? this.options.length - 1 : this.cursor - 1;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase 'down':\n\t\t\t\tcase 'right': {\n\t\t\t\t\tthis.cursor = this.cursor === this.options.length - 1 ? 0 : this.cursor + 1;\n\t\t\t\t\tconst currentIsGroup = this.options[this.cursor]?.group === true;\n\t\t\t\t\tif (!this.#selectableGroups && currentIsGroup) {\n\t\t\t\t\t\tthis.cursor = this.cursor === this.options.length - 1 ? 0 : this.cursor + 1;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase 'space':\n\t\t\t\t\tthis.toggleValue();\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t});\n\t}\n}\n", "import Prompt, { type PromptOptions } from './prompt';\n\ninterface MultiSelectOptions<T extends { value: any }> extends PromptOptions<MultiSelectPrompt<T>> {\n\toptions: T[];\n\tinitialValues?: T['value'][];\n\trequired?: boolean;\n\tcursorAt?: T['value'];\n}\nexport default class MultiSelectPrompt<T extends { value: any }> extends Prompt {\n\toptions: T[];\n\tcursor = 0;\n\n\tprivate get _value() {\n\t\treturn this.options[this.cursor].value;\n\t}\n\n\tprivate toggleAll() {\n\t\tconst allSelected = this.value.length === this.options.length;\n\t\tthis.value = allSelected ? [] : this.options.map((v) => v.value);\n\t}\n\n\tprivate toggleValue() {\n\t\tconst selected = this.value.includes(this._value);\n\t\tthis.value = selected\n\t\t\t? this.value.filter((value: T['value']) => value !== this._value)\n\t\t\t: [...this.value, this._value];\n\t}\n\n\tconstructor(opts: MultiSelectOptions<T>) {\n\t\tsuper(opts, false);\n\n\t\tthis.options = opts.options;\n\t\tthis.value = [...(opts.initialValues ?? [])];\n\t\tthis.cursor = Math.max(\n\t\t\tthis.options.findIndex(({ value }) => value === opts.cursorAt),\n\t\t\t0\n\t\t);\n\t\tthis.on('key', (char) => {\n\t\t\tif (char === 'a') {\n\t\t\t\tthis.toggleAll();\n\t\t\t}\n\t\t});\n\n\t\tthis.on('cursor', (key) => {\n\t\t\tswitch (key) {\n\t\t\t\tcase 'left':\n\t\t\t\tcase 'up':\n\t\t\t\t\tthis.cursor = this.cursor === 0 ? this.options.length - 1 : this.cursor - 1;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'down':\n\t\t\t\tcase 'right':\n\t\t\t\t\tthis.cursor = this.cursor === this.options.length - 1 ? 0 : this.cursor + 1;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'space':\n\t\t\t\t\tthis.toggleValue();\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t});\n\t}\n}\n", "import color from 'picocolors';\nimport Prompt, { type PromptOptions } from './prompt';\n\ninterface PasswordOptions extends PromptOptions<PasswordPrompt> {\n\tmask?: string;\n}\nexport default class PasswordPrompt extends Prompt {\n\tvalueWithCursor = '';\n\tprivate _mask = '•';\n\tget cursor() {\n\t\treturn this._cursor;\n\t}\n\tget masked() {\n\t\treturn this.value.replaceAll(/./g, this._mask);\n\t}\n\tconstructor({ mask, ...opts }: PasswordOptions) {\n\t\tsuper(opts);\n\t\tthis._mask = mask ?? '•';\n\n\t\tthis.on('finalize', () => {\n\t\t\tthis.valueWithCursor = this.masked;\n\t\t});\n\t\tthis.on('value', () => {\n\t\t\tif (this.cursor >= this.value.length) {\n\t\t\t\tthis.valueWithCursor = `${this.masked}${color.inverse(color.hidden('_'))}`;\n\t\t\t} else {\n\t\t\t\tconst s1 = this.masked.slice(0, this.cursor);\n\t\t\t\tconst s2 = this.masked.slice(this.cursor);\n\t\t\t\tthis.valueWithCursor = `${s1}${color.inverse(s2[0])}${s2.slice(1)}`;\n\t\t\t}\n\t\t});\n\t}\n}\n", "import Prompt, { type PromptOptions } from './prompt';\n\ninterface SelectOptions<T extends { value: any }> extends PromptOptions<SelectPrompt<T>> {\n\toptions: T[];\n\tinitialValue?: T['value'];\n}\nexport default class SelectPrompt<T extends { value: any }> extends Prompt {\n\toptions: T[];\n\tcursor = 0;\n\n\tprivate get _value() {\n\t\treturn this.options[this.cursor];\n\t}\n\n\tprivate changeValue() {\n\t\tthis.value = this._value.value;\n\t}\n\n\tconstructor(opts: SelectOptions<T>) {\n\t\tsuper(opts, false);\n\n\t\tthis.options = opts.options;\n\t\tthis.cursor = this.options.findIndex(({ value }) => value === opts.initialValue);\n\t\tif (this.cursor === -1) this.cursor = 0;\n\t\tthis.changeValue();\n\n\t\tthis.on('cursor', (key) => {\n\t\t\tswitch (key) {\n\t\t\t\tcase 'left':\n\t\t\t\tcase 'up':\n\t\t\t\t\tthis.cursor = this.cursor === 0 ? this.options.length - 1 : this.cursor - 1;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'down':\n\t\t\t\tcase 'right':\n\t\t\t\t\tthis.cursor = this.cursor === this.options.length - 1 ? 0 : this.cursor + 1;\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tthis.changeValue();\n\t\t});\n\t}\n}\n", "import Prompt, { type PromptOptions } from './prompt';\n\ninterface SelectKeyOptions<T extends { value: any }> extends PromptOptions<SelectKeyPrompt<T>> {\n\toptions: T[];\n}\nexport default class SelectKeyPrompt<T extends { value: any }> extends Prompt {\n\toptions: T[];\n\tcursor = 0;\n\n\tconstructor(opts: SelectKeyOptions<T>) {\n\t\tsuper(opts, false);\n\n\t\tthis.options = opts.options;\n\t\tconst keys = this.options.map(({ value: [initial] }) => initial?.toLowerCase());\n\t\tthis.cursor = Math.max(keys.indexOf(opts.initialValue), 0);\n\n\t\tthis.on('key', (key) => {\n\t\t\tif (!keys.includes(key)) return;\n\t\t\tconst value = this.options.find(({ value: [initial] }) => initial?.toLowerCase() === key);\n\t\t\tif (value) {\n\t\t\t\tthis.value = value.value;\n\t\t\t\tthis.state = 'submit';\n\t\t\t\tthis.emit('submit');\n\t\t\t}\n\t\t});\n\t}\n}\n", "import color from 'picocolors';\nimport Prompt, { type PromptOptions } from './prompt';\n\nexport interface TextOptions extends PromptOptions<TextPrompt> {\n\tplaceholder?: string;\n\tdefaultValue?: string;\n}\n\nexport default class TextPrompt extends Prompt {\n\tget valueWithCursor() {\n\t\tif (this.state === 'submit') {\n\t\t\treturn this.value;\n\t\t}\n\t\tif (this.cursor >= this.value.length) {\n\t\t\treturn `${this.value}█`;\n\t\t}\n\t\tconst s1 = this.value.slice(0, this.cursor);\n\t\tconst [s2, ...s3] = this.value.slice(this.cursor);\n\t\treturn `${s1}${color.inverse(s2)}${s3.join('')}`;\n\t}\n\tget cursor() {\n\t\treturn this._cursor;\n\t}\n\tconstructor(opts: TextOptions) {\n\t\tsuper(opts);\n\n\t\tthis.on('finalize', () => {\n\t\t\tif (!this.value) {\n\t\t\t\tthis.value = opts.defaultValue;\n\t\t\t}\n\t\t});\n\t}\n}\n", "import process from 'node:process';\n\nexport default function isUnicodeSupported() {\n\tif (process.platform !== 'win32') {\n\t\treturn process.env.TERM !== 'linux'; // Linux console (kernel)\n\t}\n\n\treturn Boolean(process.env.CI)\n\t\t|| Boolean(process.env.WT_SESSION) // Windows Terminal\n\t\t|| Boolean(process.env.TERMINUS_SUBLIME) // Terminus (<0.2.27)\n\t\t|| process.env.ConEmuTask === '{cmd::Cmder}' // ConEmu and cmder\n\t\t|| process.env.TERM_PROGRAM === 'Terminus-Sublime'\n\t\t|| process.env.TERM_PROGRAM === 'vscode'\n\t\t|| process.env.TERM === 'xterm-256color'\n\t\t|| process.env.TERM === 'alacritty'\n\t\t|| process.env.TERMINAL_EMULATOR === 'JetBrains-JediTerm';\n}\n", "import { stripVTControlCharacters as strip } from 'node:util';\nimport {\n\tConfirmPrompt,\n\tGroupMultiSelectPrompt,\n\tMultiSelectPrompt,\n\tPasswordPrompt,\n\tSelectKeyPrompt,\n\tSelectPrompt,\n\ttype State,\n\tTextPrompt,\n\tblock,\n\tisCancel,\n} from '@clack/core';\nimport isUnicodeSupported from 'is-unicode-supported';\nimport color from 'picocolors';\nimport { cursor, erase } from 'sisteransi';\n\nexport { isCancel } from '@clack/core';\nexport { updateSettings, type ClackSettings } from '@clack/core';\n\nconst unicode = isUnicodeSupported();\nconst s = (c: string, fallback: string) => (unicode ? c : fallback);\nconst S_STEP_ACTIVE = s('◆', '*');\nconst S_STEP_CANCEL = s('■', 'x');\nconst S_STEP_ERROR = s('▲', 'x');\nconst S_STEP_SUBMIT = s('◇', 'o');\n\nconst S_BAR_START = s('┌', 'T');\nconst S_BAR = s('│', '|');\nconst S_BAR_END = s('└', '—');\n\nconst S_RADIO_ACTIVE = s('●', '>');\nconst S_RADIO_INACTIVE = s('○', ' ');\nconst S_CHECKBOX_ACTIVE = s('◻', '[•]');\nconst S_CHECKBOX_SELECTED = s('◼', '[+]');\nconst S_CHECKBOX_INACTIVE = s('◻', '[ ]');\nconst S_PASSWORD_MASK = s('▪', '•');\n\nconst S_BAR_H = s('─', '-');\nconst S_CORNER_TOP_RIGHT = s('╮', '+');\nconst S_CONNECT_LEFT = s('├', '+');\nconst S_CORNER_BOTTOM_RIGHT = s('╯', '+');\n\nconst S_INFO = s('●', '•');\nconst S_SUCCESS = s('◆', '*');\nconst S_WARN = s('▲', '!');\nconst S_ERROR = s('■', 'x');\n\nconst symbol = (state: State) => {\n\tswitch (state) {\n\t\tcase 'initial':\n\t\tcase 'active':\n\t\t\treturn color.cyan(S_STEP_ACTIVE);\n\t\tcase 'cancel':\n\t\t\treturn color.red(S_STEP_CANCEL);\n\t\tcase 'error':\n\t\t\treturn color.yellow(S_STEP_ERROR);\n\t\tcase 'submit':\n\t\t\treturn color.green(S_STEP_SUBMIT);\n\t}\n};\n\ninterface LimitOptionsParams<TOption> {\n\toptions: TOption[];\n\tmaxItems: number | undefined;\n\tcursor: number;\n\tstyle: (option: TOption, active: boolean) => string;\n}\n\nconst limitOptions = <TOption>(params: LimitOptionsParams<TOption>): string[] => {\n\tconst { cursor, options, style } = params;\n\n\tconst paramMaxItems = params.maxItems ?? Number.POSITIVE_INFINITY;\n\tconst outputMaxItems = Math.max(process.stdout.rows - 4, 0);\n\t// We clamp to minimum 5 because anything less doesn't make sense UX wise\n\tconst maxItems = Math.min(outputMaxItems, Math.max(paramMaxItems, 5));\n\tlet slidingWindowLocation = 0;\n\n\tif (cursor >= slidingWindowLocation + maxItems - 3) {\n\t\tslidingWindowLocation = Math.max(Math.min(cursor - maxItems + 3, options.length - maxItems), 0);\n\t} else if (cursor < slidingWindowLocation + 2) {\n\t\tslidingWindowLocation = Math.max(cursor - 2, 0);\n\t}\n\n\tconst shouldRenderTopEllipsis = maxItems < options.length && slidingWindowLocation > 0;\n\tconst shouldRenderBottomEllipsis =\n\t\tmaxItems < options.length && slidingWindowLocation + maxItems < options.length;\n\n\treturn options\n\t\t.slice(slidingWindowLocation, slidingWindowLocation + maxItems)\n\t\t.map((option, i, arr) => {\n\t\t\tconst isTopLimit = i === 0 && shouldRenderTopEllipsis;\n\t\t\tconst isBottomLimit = i === arr.length - 1 && shouldRenderBottomEllipsis;\n\t\t\treturn isTopLimit || isBottomLimit\n\t\t\t\t? color.dim('...')\n\t\t\t\t: style(option, i + slidingWindowLocation === cursor);\n\t\t});\n};\n\nexport interface TextOptions {\n\tmessage: string;\n\tplaceholder?: string;\n\tdefaultValue?: string;\n\tinitialValue?: string;\n\tvalidate?: (value: string) => string | Error | undefined;\n}\nexport const text = (opts: TextOptions) => {\n\treturn new TextPrompt({\n\t\tvalidate: opts.validate,\n\t\tplaceholder: opts.placeholder,\n\t\tdefaultValue: opts.defaultValue,\n\t\tinitialValue: opts.initialValue,\n\t\trender() {\n\t\t\tconst title = `${color.gray(S_BAR)}\\n${symbol(this.state)} ${opts.message}\\n`;\n\t\t\tconst placeholder = opts.placeholder\n\t\t\t\t? color.inverse(opts.placeholder[0]) + color.dim(opts.placeholder.slice(1))\n\t\t\t\t: color.inverse(color.hidden('_'));\n\t\t\tconst value = !this.value ? placeholder : this.valueWithCursor;\n\n\t\t\tswitch (this.state) {\n\t\t\t\tcase 'error':\n\t\t\t\t\treturn `${title.trim()}\\n${color.yellow(S_BAR)} ${value}\\n${color.yellow(\n\t\t\t\t\t\tS_BAR_END\n\t\t\t\t\t)} ${color.yellow(this.error)}\\n`;\n\t\t\t\tcase 'submit':\n\t\t\t\t\treturn `${title}${color.gray(S_BAR)} ${color.dim(this.value || opts.placeholder)}`;\n\t\t\t\tcase 'cancel':\n\t\t\t\t\treturn `${title}${color.gray(S_BAR)} ${color.strikethrough(\n\t\t\t\t\t\tcolor.dim(this.value ?? '')\n\t\t\t\t\t)}${this.value?.trim() ? `\\n${color.gray(S_BAR)}` : ''}`;\n\t\t\t\tdefault:\n\t\t\t\t\treturn `${title}${color.cyan(S_BAR)} ${value}\\n${color.cyan(S_BAR_END)}\\n`;\n\t\t\t}\n\t\t},\n\t}).prompt() as Promise<string | symbol>;\n};\n\nexport interface PasswordOptions {\n\tmessage: string;\n\tmask?: string;\n\tvalidate?: (value: string) => string | Error | undefined;\n}\nexport const password = (opts: PasswordOptions) => {\n\treturn new PasswordPrompt({\n\t\tvalidate: opts.validate,\n\t\tmask: opts.mask ?? S_PASSWORD_MASK,\n\t\trender() {\n\t\t\tconst title = `${color.gray(S_BAR)}\\n${symbol(this.state)} ${opts.message}\\n`;\n\t\t\tconst value = this.valueWithCursor;\n\t\t\tconst masked = this.masked;\n\n\t\t\tswitch (this.state) {\n\t\t\t\tcase 'error':\n\t\t\t\t\treturn `${title.trim()}\\n${color.yellow(S_BAR)} ${masked}\\n${color.yellow(\n\t\t\t\t\t\tS_BAR_END\n\t\t\t\t\t)} ${color.yellow(this.error)}\\n`;\n\t\t\t\tcase 'submit':\n\t\t\t\t\treturn `${title}${color.gray(S_BAR)} ${color.dim(masked)}`;\n\t\t\t\tcase 'cancel':\n\t\t\t\t\treturn `${title}${color.gray(S_BAR)} ${color.strikethrough(color.dim(masked ?? ''))}${\n\t\t\t\t\t\tmasked ? `\\n${color.gray(S_BAR)}` : ''\n\t\t\t\t\t}`;\n\t\t\t\tdefault:\n\t\t\t\t\treturn `${title}${color.cyan(S_BAR)} ${value}\\n${color.cyan(S_BAR_END)}\\n`;\n\t\t\t}\n\t\t},\n\t}).prompt() as Promise<string | symbol>;\n};\n\nexport interface ConfirmOptions {\n\tmessage: string;\n\tactive?: string;\n\tinactive?: string;\n\tinitialValue?: boolean;\n}\nexport const confirm = (opts: ConfirmOptions) => {\n\tconst active = opts.active ?? 'Yes';\n\tconst inactive = opts.inactive ?? 'No';\n\treturn new ConfirmPrompt({\n\t\tactive,\n\t\tinactive,\n\t\tinitialValue: opts.initialValue ?? true,\n\t\trender() {\n\t\t\tconst title = `${color.gray(S_BAR)}\\n${symbol(this.state)} ${opts.message}\\n`;\n\t\t\tconst value = this.value ? active : inactive;\n\n\t\t\tswitch (this.state) {\n\t\t\t\tcase 'submit':\n\t\t\t\t\treturn `${title}${color.gray(S_BAR)} ${color.dim(value)}`;\n\t\t\t\tcase 'cancel':\n\t\t\t\t\treturn `${title}${color.gray(S_BAR)} ${color.strikethrough(\n\t\t\t\t\t\tcolor.dim(value)\n\t\t\t\t\t)}\\n${color.gray(S_BAR)}`;\n\t\t\t\tdefault: {\n\t\t\t\t\treturn `${title}${color.cyan(S_BAR)} ${\n\t\t\t\t\t\tthis.value\n\t\t\t\t\t\t\t? `${color.green(S_RADIO_ACTIVE)} ${active}`\n\t\t\t\t\t\t\t: `${color.dim(S_RADIO_INACTIVE)} ${color.dim(active)}`\n\t\t\t\t\t} ${color.dim('/')} ${\n\t\t\t\t\t\t!this.value\n\t\t\t\t\t\t\t? `${color.green(S_RADIO_ACTIVE)} ${inactive}`\n\t\t\t\t\t\t\t: `${color.dim(S_RADIO_INACTIVE)} ${color.dim(inactive)}`\n\t\t\t\t\t}\\n${color.cyan(S_BAR_END)}\\n`;\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t}).prompt() as Promise<boolean | symbol>;\n};\n\ntype Primitive = Readonly<string | boolean | number>;\n\nexport type Option<Value> = Value extends Primitive\n\t? {\n\t\t\t/**\n\t\t\t * Internal data for this option.\n\t\t\t */\n\t\t\tvalue: Value;\n\t\t\t/**\n\t\t\t * The optional, user-facing text for this option.\n\t\t\t *\n\t\t\t * By default, the `value` is converted to a string.\n\t\t\t */\n\t\t\tlabel?: string;\n\t\t\t/**\n\t\t\t * An optional hint to display to the user when\n\t\t\t * this option might be selected.\n\t\t\t *\n\t\t\t * By default, no `hint` is displayed.\n\t\t\t */\n\t\t\thint?: string;\n\t\t}\n\t: {\n\t\t\t/**\n\t\t\t * Internal data for this option.\n\t\t\t */\n\t\t\tvalue: Value;\n\t\t\t/**\n\t\t\t * Required. The user-facing text for this option.\n\t\t\t */\n\t\t\tlabel: string;\n\t\t\t/**\n\t\t\t * An optional hint to display to the user when\n\t\t\t * this option might be selected.\n\t\t\t *\n\t\t\t * By default, no `hint` is displayed.\n\t\t\t */\n\t\t\thint?: string;\n\t\t};\n\nexport interface SelectOptions<Value> {\n\tmessage: string;\n\toptions: Option<Value>[];\n\tinitialValue?: Value;\n\tmaxItems?: number;\n}\n\nexport const select = <Value>(opts: SelectOptions<Value>) => {\n\tconst opt = (option: Option<Value>, state: 'inactive' | 'active' | 'selected' | 'cancelled') => {\n\t\tconst label = option.label ?? String(option.value);\n\t\tswitch (state) {\n\t\t\tcase 'selected':\n\t\t\t\treturn `${color.dim(label)}`;\n\t\t\tcase 'active':\n\t\t\t\treturn `${color.green(S_RADIO_ACTIVE)} ${label} ${\n\t\t\t\t\toption.hint ? color.dim(`(${option.hint})`) : ''\n\t\t\t\t}`;\n\t\t\tcase 'cancelled':\n\t\t\t\treturn `${color.strikethrough(color.dim(label))}`;\n\t\t\tdefault:\n\t\t\t\treturn `${color.dim(S_RADIO_INACTIVE)} ${color.dim(label)}`;\n\t\t}\n\t};\n\n\treturn new SelectPrompt({\n\t\toptions: opts.options,\n\t\tinitialValue: opts.initialValue,\n\t\trender() {\n\t\t\tconst title = `${color.gray(S_BAR)}\\n${symbol(this.state)} ${opts.message}\\n`;\n\n\t\t\tswitch (this.state) {\n\t\t\t\tcase 'submit':\n\t\t\t\t\treturn `${title}${color.gray(S_BAR)} ${opt(this.options[this.cursor], 'selected')}`;\n\t\t\t\tcase 'cancel':\n\t\t\t\t\treturn `${title}${color.gray(S_BAR)} ${opt(\n\t\t\t\t\t\tthis.options[this.cursor],\n\t\t\t\t\t\t'cancelled'\n\t\t\t\t\t)}\\n${color.gray(S_BAR)}`;\n\t\t\t\tdefault: {\n\t\t\t\t\treturn `${title}${color.cyan(S_BAR)} ${limitOptions({\n\t\t\t\t\t\tcursor: this.cursor,\n\t\t\t\t\t\toptions: this.options,\n\t\t\t\t\t\tmaxItems: opts.maxItems,\n\t\t\t\t\t\tstyle: (item, active) => opt(item, active ? 'active' : 'inactive'),\n\t\t\t\t\t}).join(`\\n${color.cyan(S_BAR)} `)}\\n${color.cyan(S_BAR_END)}\\n`;\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t}).prompt() as Promise<Value | symbol>;\n};\n\nexport const selectKey = <Value extends string>(opts: SelectOptions<Value>) => {\n\tconst opt = (\n\t\toption: Option<Value>,\n\t\tstate: 'inactive' | 'active' | 'selected' | 'cancelled' = 'inactive'\n\t) => {\n\t\tconst label = option.label ?? String(option.value);\n\t\tif (state === 'selected') {\n\t\t\treturn `${color.dim(label)}`;\n\t\t}\n\t\tif (state === 'cancelled') {\n\t\t\treturn `${color.strikethrough(color.dim(label))}`;\n\t\t}\n\t\tif (state === 'active') {\n\t\t\treturn `${color.bgCyan(color.gray(` ${option.value} `))} ${label} ${\n\t\t\t\toption.hint ? color.dim(`(${option.hint})`) : ''\n\t\t\t}`;\n\t\t}\n\t\treturn `${color.gray(color.bgWhite(color.inverse(` ${option.value} `)))} ${label} ${\n\t\t\toption.hint ? color.dim(`(${option.hint})`) : ''\n\t\t}`;\n\t};\n\n\treturn new SelectKeyPrompt({\n\t\toptions: opts.options,\n\t\tinitialValue: opts.initialValue,\n\t\trender() {\n\t\t\tconst title = `${color.gray(S_BAR)}\\n${symbol(this.state)} ${opts.message}\\n`;\n\n\t\t\tswitch (this.state) {\n\t\t\t\tcase 'submit':\n\t\t\t\t\treturn `${title}${color.gray(S_BAR)} ${opt(\n\t\t\t\t\t\tthis.options.find((opt) => opt.value === this.value) ?? opts.options[0],\n\t\t\t\t\t\t'selected'\n\t\t\t\t\t)}`;\n\t\t\t\tcase 'cancel':\n\t\t\t\t\treturn `${title}${color.gray(S_BAR)} ${opt(this.options[0], 'cancelled')}\\n${color.gray(\n\t\t\t\t\t\tS_BAR\n\t\t\t\t\t)}`;\n\t\t\t\tdefault: {\n\t\t\t\t\treturn `${title}${color.cyan(S_BAR)} ${this.options\n\t\t\t\t\t\t.map((option, i) => opt(option, i === this.cursor ? 'active' : 'inactive'))\n\t\t\t\t\t\t.join(`\\n${color.cyan(S_BAR)} `)}\\n${color.cyan(S_BAR_END)}\\n`;\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t}).prompt() as Promise<Value | symbol>;\n};\n\nexport interface MultiSelectOptions<Value> {\n\tmessage: string;\n\toptions: Option<Value>[];\n\tinitialValues?: Value[];\n\tmaxItems?: number;\n\trequired?: boolean;\n\tcursorAt?: Value;\n}\nexport const multiselect = <Value>(opts: MultiSelectOptions<Value>) => {\n\tconst opt = (\n\t\toption: Option<Value>,\n\t\tstate: 'inactive' | 'active' | 'selected' | 'active-selected' | 'submitted' | 'cancelled'\n\t) => {\n\t\tconst label = option.label ?? String(option.value);\n\t\tif (state === 'active') {\n\t\t\treturn `${color.cyan(S_CHECKBOX_ACTIVE)} ${label} ${\n\t\t\t\toption.hint ? color.dim(`(${option.hint})`) : ''\n\t\t\t}`;\n\t\t}\n\t\tif (state === 'selected') {\n\t\t\treturn `${color.green(S_CHECKBOX_SELECTED)} ${color.dim(label)} ${\n\t\t\t\toption.hint ? color.dim(`(${option.hint})`) : ''\n\t\t\t}`;\n\t\t}\n\t\tif (state === 'cancelled') {\n\t\t\treturn `${color.strikethrough(color.dim(label))}`;\n\t\t}\n\t\tif (state === 'active-selected') {\n\t\t\treturn `${color.green(S_CHECKBOX_SELECTED)} ${label} ${\n\t\t\t\toption.hint ? color.dim(`(${option.hint})`) : ''\n\t\t\t}`;\n\t\t}\n\t\tif (state === 'submitted') {\n\t\t\treturn `${color.dim(label)}`;\n\t\t}\n\t\treturn `${color.dim(S_CHECKBOX_INACTIVE)} ${color.dim(label)}`;\n\t};\n\n\treturn new MultiSelectPrompt({\n\t\toptions: opts.options,\n\t\tinitialValues: opts.initialValues,\n\t\trequired: opts.required ?? true,\n\t\tcursorAt: opts.cursorAt,\n\t\tvalidate(selected: Value[]) {\n\t\t\tif (this.required && selected.length === 0)\n\t\t\t\treturn `Please select at least one option.\\n${color.reset(\n\t\t\t\t\tcolor.dim(\n\t\t\t\t\t\t`Press ${color.gray(color.bgWhite(color.inverse(' space ')))} to select, ${color.gray(\n\t\t\t\t\t\t\tcolor.bgWhite(color.inverse(' enter '))\n\t\t\t\t\t\t)} to submit`\n\t\t\t\t\t)\n\t\t\t\t)}`;\n\t\t},\n\t\trender() {\n\t\t\tconst title = `${color.gray(S_BAR)}\\n${symbol(this.state)} ${opts.message}\\n`;\n\n\t\t\tconst styleOption = (option: Option<Value>, active: boolean) => {\n\t\t\t\tconst selected = this.value.includes(option.value);\n\t\t\t\tif (active && selected) {\n\t\t\t\t\treturn opt(option, 'active-selected');\n\t\t\t\t}\n\t\t\t\tif (selected) {\n\t\t\t\t\treturn opt(option, 'selected');\n\t\t\t\t}\n\t\t\t\treturn opt(option, active ? 'active' : 'inactive');\n\t\t\t};\n\n\t\t\tswitch (this.state) {\n\t\t\t\tcase 'submit': {\n\t\t\t\t\treturn `${title}${color.gray(S_BAR)} ${\n\t\t\t\t\t\tthis.options\n\t\t\t\t\t\t\t.filter(({ value }) => this.value.includes(value))\n\t\t\t\t\t\t\t.map((option) => opt(option, 'submitted'))\n\t\t\t\t\t\t\t.join(color.dim(', ')) || color.dim('none')\n\t\t\t\t\t}`;\n\t\t\t\t}\n\t\t\t\tcase 'cancel': {\n\t\t\t\t\tconst label = this.options\n\t\t\t\t\t\t.filter(({ value }) => this.value.includes(value))\n\t\t\t\t\t\t.map((option) => opt(option, 'cancelled'))\n\t\t\t\t\t\t.join(color.dim(', '));\n\t\t\t\t\treturn `${title}${color.gray(S_BAR)} ${\n\t\t\t\t\t\tlabel.trim() ? `${label}\\n${color.gray(S_BAR)}` : ''\n\t\t\t\t\t}`;\n\t\t\t\t}\n\t\t\t\tcase 'error': {\n\t\t\t\t\tconst footer = this.error\n\t\t\t\t\t\t.split('\\n')\n\t\t\t\t\t\t.map((ln, i) =>\n\t\t\t\t\t\t\ti === 0 ? `${color.yellow(S_BAR_END)} ${color.yellow(ln)}` : ` ${ln}`\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.join('\\n');\n\t\t\t\t\treturn `${title + color.yellow(S_BAR)} ${limitOptions({\n\t\t\t\t\t\toptions: this.options,\n\t\t\t\t\t\tcursor: this.cursor,\n\t\t\t\t\t\tmaxItems: opts.maxItems,\n\t\t\t\t\t\tstyle: styleOption,\n\t\t\t\t\t}).join(`\\n${color.yellow(S_BAR)} `)}\\n${footer}\\n`;\n\t\t\t\t}\n\t\t\t\tdefault: {\n\t\t\t\t\treturn `${title}${color.cyan(S_BAR)} ${limitOptions({\n\t\t\t\t\t\toptions: this.options,\n\t\t\t\t\t\tcursor: this.cursor,\n\t\t\t\t\t\tmaxItems: opts.maxItems,\n\t\t\t\t\t\tstyle: styleOption,\n\t\t\t\t\t}).join(`\\n${color.cyan(S_BAR)} `)}\\n${color.cyan(S_BAR_END)}\\n`;\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t}).prompt() as Promise<Value[] | symbol>;\n};\n\nexport interface GroupMultiSelectOptions<Value> {\n\tmessage: string;\n\toptions: Record<string, Option<Value>[]>;\n\tinitialValues?: Value[];\n\trequired?: boolean;\n\tcursorAt?: Value;\n\tselectableGroups?: boolean;\n}\nexport const groupMultiselect = <Value>(opts: GroupMultiSelectOptions<Value>) => {\n\tconst { selectableGroups = true } = opts;\n\tconst opt = (\n\t\toption: Option<Value>,\n\t\tstate:\n\t\t\t| 'inactive'\n\t\t\t| 'active'\n\t\t\t| 'selected'\n\t\t\t| 'active-selected'\n\t\t\t| 'group-active'\n\t\t\t| 'group-active-selected'\n\t\t\t| 'submitted'\n\t\t\t| 'cancelled',\n\t\toptions: Option<Value>[] = []\n\t) => {\n\t\tconst label = option.label ?? String(option.value);\n\t\tconst isItem = typeof (option as any).group === 'string';\n\t\tconst next = isItem && (options[options.indexOf(option) + 1] ?? { group: true });\n\t\tconst isLast = isItem && (next as any).group === true;\n\t\tconst prefix = isItem ? (selectableGroups ? `${isLast ? S_BAR_END : S_BAR} ` : ' ') : '';\n\n\t\tif (state === 'active') {\n\t\t\treturn `${color.dim(prefix)}${color.cyan(S_CHECKBOX_ACTIVE)} ${label} ${\n\t\t\t\toption.hint ? color.dim(`(${option.hint})`) : ''\n\t\t\t}`;\n\t\t}\n\t\tif (state === 'group-active') {\n\t\t\treturn `${prefix}${color.cyan(S_CHECKBOX_ACTIVE)} ${color.dim(label)}`;\n\t\t}\n\t\tif (state === 'group-active-selected') {\n\t\t\treturn `${prefix}${color.green(S_CHECKBOX_SELECTED)} ${color.dim(label)}`;\n\t\t}\n\t\tif (state === 'selected') {\n\t\t\tconst selectedCheckbox = isItem || selectableGroups ? color.green(S_CHECKBOX_SELECTED) : '';\n\t\t\treturn `${color.dim(prefix)}${selectedCheckbox} ${color.dim(label)} ${\n\t\t\t\toption.hint ? color.dim(`(${option.hint})`) : ''\n\t\t\t}`;\n\t\t}\n\t\tif (state === 'cancelled') {\n\t\t\treturn `${color.strikethrough(color.dim(label))}`;\n\t\t}\n\t\tif (state === 'active-selected') {\n\t\t\treturn `${color.dim(prefix)}${color.green(S_CHECKBOX_SELECTED)} ${label} ${\n\t\t\t\toption.hint ? color.dim(`(${option.hint})`) : ''\n\t\t\t}`;\n\t\t}\n\t\tif (state === 'submitted') {\n\t\t\treturn `${color.dim(label)}`;\n\t\t}\n\t\tconst unselectedCheckbox = isItem || selectableGroups ? color.dim(S_CHECKBOX_INACTIVE) : '';\n\t\treturn `${color.dim(prefix)}${unselectedCheckbox} ${color.dim(label)}`;\n\t};\n\n\treturn new GroupMultiSelectPrompt({\n\t\toptions: opts.options,\n\t\tinitialValues: opts.initialValues,\n\t\trequired: opts.required ?? true,\n\t\tcursorAt: opts.cursorAt,\n\t\tselectableGroups,\n\t\tvalidate(selected: Value[]) {\n\t\t\tif (this.required && selected.length === 0)\n\t\t\t\treturn `Please select at least one option.\\n${color.reset(\n\t\t\t\t\tcolor.dim(\n\t\t\t\t\t\t`Press ${color.gray(color.bgWhite(color.inverse(' space ')))} to select, ${color.gray(\n\t\t\t\t\t\t\tcolor.bgWhite(color.inverse(' enter '))\n\t\t\t\t\t\t)} to submit`\n\t\t\t\t\t)\n\t\t\t\t)}`;\n\t\t},\n\t\trender() {\n\t\t\tconst title = `${color.gray(S_BAR)}\\n${symbol(this.state)} ${opts.message}\\n`;\n\n\t\t\tswitch (this.state) {\n\t\t\t\tcase 'submit': {\n\t\t\t\t\treturn `${title}${color.gray(S_BAR)} ${this.options\n\t\t\t\t\t\t.filter(({ value }) => this.value.includes(value))\n\t\t\t\t\t\t.map((option) => opt(option, 'submitted'))\n\t\t\t\t\t\t.join(color.dim(', '))}`;\n\t\t\t\t}\n\t\t\t\tcase 'cancel': {\n\t\t\t\t\tconst label = this.options\n\t\t\t\t\t\t.filter(({ value }) => this.value.includes(value))\n\t\t\t\t\t\t.map((option) => opt(option, 'cancelled'))\n\t\t\t\t\t\t.join(color.dim(', '));\n\t\t\t\t\treturn `${title}${color.gray(S_BAR)} ${\n\t\t\t\t\t\tlabel.trim() ? `${label}\\n${color.gray(S_BAR)}` : ''\n\t\t\t\t\t}`;\n\t\t\t\t}\n\t\t\t\tcase 'error': {\n\t\t\t\t\tconst footer = this.error\n\t\t\t\t\t\t.split('\\n')\n\t\t\t\t\t\t.map((ln, i) =>\n\t\t\t\t\t\t\ti === 0 ? `${color.yellow(S_BAR_END)} ${color.yellow(ln)}` : ` ${ln}`\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.join('\\n');\n\t\t\t\t\treturn `${title}${color.yellow(S_BAR)} ${this.options\n\t\t\t\t\t\t.map((option, i, options) => {\n\t\t\t\t\t\t\tconst selected =\n\t\t\t\t\t\t\t\tthis.value.includes(option.value) ||\n\t\t\t\t\t\t\t\t(option.group === true && this.isGroupSelected(`${option.value}`));\n\t\t\t\t\t\t\tconst active = i === this.cursor;\n\t\t\t\t\t\t\tconst groupActive =\n\t\t\t\t\t\t\t\t!active &&\n\t\t\t\t\t\t\t\ttypeof option.group === 'string' &&\n\t\t\t\t\t\t\t\tthis.options[this.cursor].value === option.group;\n\t\t\t\t\t\t\tif (groupActive) {\n\t\t\t\t\t\t\t\treturn opt(option, selected ? 'group-active-selected' : 'group-active', options);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (active && selected) {\n\t\t\t\t\t\t\t\treturn opt(option, 'active-selected', options);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (selected) {\n\t\t\t\t\t\t\t\treturn opt(option, 'selected', options);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn opt(option, active ? 'active' : 'inactive', options);\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.join(`\\n${color.yellow(S_BAR)} `)}\\n${footer}\\n`;\n\t\t\t\t}\n\t\t\t\tdefault: {\n\t\t\t\t\treturn `${title}${color.cyan(S_BAR)} ${this.options\n\t\t\t\t\t\t.map((option, i, options) => {\n\t\t\t\t\t\t\tconst selected =\n\t\t\t\t\t\t\t\tthis.value.includes(option.value) ||\n\t\t\t\t\t\t\t\t(option.group === true && this.isGroupSelected(`${option.value}`));\n\t\t\t\t\t\t\tconst active = i === this.cursor;\n\t\t\t\t\t\t\tconst groupActive =\n\t\t\t\t\t\t\t\t!active &&\n\t\t\t\t\t\t\t\ttypeof option.group === 'string' &&\n\t\t\t\t\t\t\t\tthis.options[this.cursor].value === option.group;\n\t\t\t\t\t\t\tif (groupActive) {\n\t\t\t\t\t\t\t\treturn opt(option, selected ? 'group-active-selected' : 'group-active', options);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (active && selected) {\n\t\t\t\t\t\t\t\treturn opt(option, 'active-selected', options);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (selected) {\n\t\t\t\t\t\t\t\treturn opt(option, 'selected', options);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn opt(option, active ? 'active' : 'inactive', options);\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.join(`\\n${color.cyan(S_BAR)} `)}\\n${color.cyan(S_BAR_END)}\\n`;\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t}).prompt() as Promise<Value[] | symbol>;\n};\n\nexport const note = (message = '', title = '') => {\n\tconst lines = `\\n${message}\\n`.split('\\n');\n\tconst titleLen = strip(title).length;\n\tconst len =\n\t\tMath.max(\n\t\t\tlines.reduce((sum, ln) => {\n\t\t\t\tconst line = strip(ln);\n\t\t\t\treturn line.length > sum ? line.length : sum;\n\t\t\t}, 0),\n\t\t\ttitleLen\n\t\t) + 2;\n\tconst msg = lines\n\t\t.map(\n\t\t\t(ln) =>\n\t\t\t\t`${color.gray(S_BAR)} ${color.dim(ln)}${' '.repeat(len - strip(ln).length)}${color.gray(\n\t\t\t\t\tS_BAR\n\t\t\t\t)}`\n\t\t)\n\t\t.join('\\n');\n\tprocess.stdout.write(\n\t\t`${color.gray(S_BAR)}\\n${color.green(S_STEP_SUBMIT)} ${color.reset(title)} ${color.gray(\n\t\t\tS_BAR_H.repeat(Math.max(len - titleLen - 1, 1)) + S_CORNER_TOP_RIGHT\n\t\t)}\\n${msg}\\n${color.gray(S_CONNECT_LEFT + S_BAR_H.repeat(len + 2) + S_CORNER_BOTTOM_RIGHT)}\\n`\n\t);\n};\n\nexport const cancel = (message = '') => {\n\tprocess.stdout.write(`${color.gray(S_BAR_END)} ${color.red(message)}\\n\\n`);\n};\n\nexport const intro = (title = '') => {\n\tprocess.stdout.write(`${color.gray(S_BAR_START)} ${title}\\n`);\n};\n\nexport const outro = (message = '') => {\n\tprocess.stdout.write(`${color.gray(S_BAR)}\\n${color.gray(S_BAR_END)} ${message}\\n\\n`);\n};\n\nexport type LogMessageOptions = {\n\tsymbol?: string;\n};\nexport const log = {\n\tmessage: (message = '', { symbol = color.gray(S_BAR) }: LogMessageOptions = {}) => {\n\t\tconst parts = [`${color.gray(S_BAR)}`];\n\t\tif (message) {\n\t\t\tconst [firstLine, ...lines] = message.split('\\n');\n\t\t\tparts.push(`${symbol} ${firstLine}`, ...lines.map((ln) => `${color.gray(S_BAR)} ${ln}`));\n\t\t}\n\t\tprocess.stdout.write(`${parts.join('\\n')}\\n`);\n\t},\n\tinfo: (message: string) => {\n\t\tlog.message(message, { symbol: color.blue(S_INFO) });\n\t},\n\tsuccess: (message: string) => {\n\t\tlog.message(message, { symbol: color.green(S_SUCCESS) });\n\t},\n\tstep: (message: string) => {\n\t\tlog.message(message, { symbol: color.green(S_STEP_SUBMIT) });\n\t},\n\twarn: (message: string) => {\n\t\tlog.message(message, { symbol: color.yellow(S_WARN) });\n\t},\n\t/** alias for `log.warn()`. */\n\twarning: (message: string) => {\n\t\tlog.warn(message);\n\t},\n\terror: (message: string) => {\n\t\tlog.message(message, { symbol: color.red(S_ERROR) });\n\t},\n};\n\nconst prefix = `${color.gray(S_BAR)} `;\nexport const stream = {\n\tmessage: async (\n\t\titerable: Iterable<string> | AsyncIterable<string>,\n\t\t{ symbol = color.gray(S_BAR) }: LogMessageOptions = {}\n\t) => {\n\t\tprocess.stdout.write(`${color.gray(S_BAR)}\\n${symbol} `);\n\t\tlet lineWidth = 3;\n\t\tfor await (let chunk of iterable) {\n\t\t\tchunk = chunk.replace(/\\n/g, `\\n${prefix}`);\n\t\t\tif (chunk.includes('\\n')) {\n\t\t\t\tlineWidth = 3 + strip(chunk.slice(chunk.lastIndexOf('\\n'))).length;\n\t\t\t}\n\t\t\tconst chunkLen = strip(chunk).length;\n\t\t\tif (lineWidth + chunkLen < process.stdout.columns) {\n\t\t\t\tlineWidth += chunkLen;\n\t\t\t\tprocess.stdout.write(chunk);\n\t\t\t} else {\n\t\t\t\tprocess.stdout.write(`\\n${prefix}${chunk.trimStart()}`);\n\t\t\t\tlineWidth = 3 + strip(chunk.trimStart()).length;\n\t\t\t}\n\t\t}\n\t\tprocess.stdout.write('\\n');\n\t},\n\tinfo: (iterable: Iterable<string> | AsyncIterable<string>) => {\n\t\treturn stream.message(iterable, { symbol: color.blue(S_INFO) });\n\t},\n\tsuccess: (iterable: Iterable<string> | AsyncIterable<string>) => {\n\t\treturn stream.message(iterable, { symbol: color.green(S_SUCCESS) });\n\t},\n\tstep: (iterable: Iterable<string> | AsyncIterable<string>) => {\n\t\treturn stream.message(iterable, { symbol: color.green(S_STEP_SUBMIT) });\n\t},\n\twarn: (iterable: Iterable<string> | AsyncIterable<string>) => {\n\t\treturn stream.message(iterable, { symbol: color.yellow(S_WARN) });\n\t},\n\t/** alias for `log.warn()`. */\n\twarning: (iterable: Iterable<string> | AsyncIterable<string>) => {\n\t\treturn stream.warn(iterable);\n\t},\n\terror: (iterable: Iterable<string> | AsyncIterable<string>) => {\n\t\treturn stream.message(iterable, { symbol: color.red(S_ERROR) });\n\t},\n};\n\nexport interface SpinnerOptions {\n\tindicator?: 'dots' | 'timer';\n}\n\nexport const spinner = ({ indicator = 'dots' }: SpinnerOptions = {}) => {\n\tconst frames = unicode ? ['◒', '◐', '◓', '◑'] : ['•', 'o', 'O', '0'];\n\tconst delay = unicode ? 80 : 120;\n\tconst isCI = process.env.CI === 'true';\n\n\tlet unblock: () => void;\n\tlet loop: NodeJS.Timeout;\n\tlet isSpinnerActive = false;\n\tlet _message = '';\n\tlet _prevMessage: string | undefined = undefined;\n\tlet _origin: number = performance.now();\n\n\tconst handleExit = (code: number) => {\n\t\tconst msg = code > 1 ? 'Something went wrong' : 'Canceled';\n\t\tif (isSpinnerActive) stop(msg, code);\n\t};\n\n\tconst errorEventHandler = () => handleExit(2);\n\tconst signalEventHandler = () => handleExit(1);\n\n\tconst registerHooks = () => {\n\t\t// Reference: https://nodejs.org/api/process.html#event-uncaughtexception\n\t\tprocess.on('uncaughtExceptionMonitor', errorEventHandler);\n\t\t// Reference: https://nodejs.org/api/process.html#event-unhandledrejection\n\t\tprocess.on('unhandledRejection', errorEventHandler);\n\t\t// Reference Signal Events: https://nodejs.org/api/process.html#signal-events\n\t\tprocess.on('SIGINT', signalEventHandler);\n\t\tprocess.on('SIGTERM', signalEventHandler);\n\t\tprocess.on('exit', handleExit);\n\t};\n\n\tconst clearHooks = () => {\n\t\tprocess.removeListener('uncaughtExceptionMonitor', errorEventHandler);\n\t\tprocess.removeListener('unhandledRejection', errorEventHandler);\n\t\tprocess.removeListener('SIGINT', signalEventHandler);\n\t\tprocess.removeListener('SIGTERM', signalEventHandler);\n\t\tprocess.removeListener('exit', handleExit);\n\t};\n\n\tconst clearPrevMessage = () => {\n\t\tif (_prevMessage === undefined) return;\n\t\tif (isCI) process.stdout.write('\\n');\n\t\tconst prevLines = _prevMessage.split('\\n');\n\t\tprocess.stdout.write(cursor.move(-999, prevLines.length - 1));\n\t\tprocess.stdout.write(erase.down(prevLines.length));\n\t};\n\n\tconst parseMessage = (msg: string): string => {\n\t\treturn msg.replace(/\\.+$/, '');\n\t};\n\n\tconst formatTimer = (origin: number): string => {\n\t\tconst duration = (performance.now() - origin) / 1000;\n\t\tconst min = Math.floor(duration / 60);\n\t\tconst secs = Math.floor(duration % 60);\n\t\treturn min > 0 ? `[${min}m ${secs}s]` : `[${secs}s]`;\n\t};\n\n\tconst start = (msg = ''): void => {\n\t\tisSpinnerActive = true;\n\t\tunblock = block();\n\t\t_message = parseMessage(msg);\n\t\t_origin = performance.now();\n\t\tprocess.stdout.write(`${color.gray(S_BAR)}\\n`);\n\t\tlet frameIndex = 0;\n\t\tlet indicatorTimer = 0;\n\t\tregisterHooks();\n\t\tloop = setInterval(() => {\n\t\t\tif (isCI && _message === _prevMessage) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tclearPrevMessage();\n\t\t\t_prevMessage = _message;\n\t\t\tconst frame = color.magenta(frames[frameIndex]);\n\n\t\t\tif (isCI) {\n\t\t\t\tprocess.stdout.write(`${frame} ${_message}...`);\n\t\t\t} else if (indicator === 'timer') {\n\t\t\t\tprocess.stdout.write(`${frame} ${_message} ${formatTimer(_origin)}`);\n\t\t\t} else {\n\t\t\t\tconst loadingDots = '.'.repeat(Math.floor(indicatorTimer)).slice(0, 3);\n\t\t\t\tprocess.stdout.write(`${frame} ${_message}${loadingDots}`);\n\t\t\t}\n\n\t\t\tframeIndex = frameIndex + 1 < frames.length ? frameIndex + 1 : 0;\n\t\t\tindicatorTimer = indicatorTimer < frames.length ? indicatorTimer + 0.125 : 0;\n\t\t}, delay);\n\t};\n\n\tconst stop = (msg = '', code = 0): void => {\n\t\tisSpinnerActive = false;\n\t\tclearInterval(loop);\n\t\tclearPrevMessage();\n\t\tconst step =\n\t\t\tcode === 0\n\t\t\t\t? color.green(S_STEP_SUBMIT)\n\t\t\t\t: code === 1\n\t\t\t\t\t? color.red(S_STEP_CANCEL)\n\t\t\t\t\t: color.red(S_STEP_ERROR);\n\t\t_message = parseMessage(msg ?? _message);\n\t\tif (indicator === 'timer') {\n\t\t\tprocess.stdout.write(`${step} ${_message} ${formatTimer(_origin)}\\n`);\n\t\t} else {\n\t\t\tprocess.stdout.write(`${step} ${_message}\\n`);\n\t\t}\n\t\tclearHooks();\n\t\tunblock();\n\t};\n\n\tconst message = (msg = ''): void => {\n\t\t_message = parseMessage(msg ?? _message);\n\t};\n\n\treturn {\n\t\tstart,\n\t\tstop,\n\t\tmessage,\n\t};\n};\n\nexport type PromptGroupAwaitedReturn<T> = {\n\t[P in keyof T]: Exclude<Awaited<T[P]>, symbol>;\n};\n\nexport interface PromptGroupOptions<T> {\n\t/**\n\t * Control how the group can be canceled\n\t * if one of the prompts is canceled.\n\t */\n\tonCancel?: (opts: { results: Prettify<Partial<PromptGroupAwaitedReturn<T>>> }) => void;\n}\n\ntype Prettify<T> = {\n\t[P in keyof T]: T[P];\n} & {};\n\nexport type PromptGroup<T> = {\n\t[P in keyof T]: (opts: {\n\t\tresults: Prettify<Partial<PromptGroupAwaitedReturn<Omit<T, P>>>>;\n\t}) => undefined | Promise<T[P] | undefined>;\n};\n\n/**\n * Define a group of prompts to be displayed\n * and return a results of objects within the group\n */\nexport const group = async <T>(\n\tprompts: PromptGroup<T>,\n\topts?: PromptGroupOptions<T>\n): Promise<Prettify<PromptGroupAwaitedReturn<T>>> => {\n\tconst results = {} as any;\n\tconst promptNames = Object.keys(prompts);\n\n\tfor (const name of promptNames) {\n\t\tconst prompt = prompts[name as keyof T];\n\t\tconst result = await prompt({ results })?.catch((e) => {\n\t\t\tthrow e;\n\t\t});\n\n\t\t// Pass the results to the onCancel function\n\t\t// so the user can decide what to do with the results\n\t\t// TODO: Switch to callback within core to avoid isCancel Fn\n\t\tif (typeof opts?.onCancel === 'function' && isCancel(result)) {\n\t\t\tresults[name] = 'canceled';\n\t\t\topts.onCancel({ results });\n\t\t\tcontinue;\n\t\t}\n\n\t\tresults[name] = result;\n\t}\n\n\treturn results;\n};\n\nexport type Task = {\n\t/**\n\t * Task title\n\t */\n\ttitle: string;\n\t/**\n\t * Task function\n\t */\n\ttask: (message: (string: string) => void) => string | Promise<string> | void | Promise<void>;\n\n\t/**\n\t * If enabled === false the task will be skipped\n\t */\n\tenabled?: boolean;\n};\n\n/**\n * Define a group of tasks to be executed\n */\nexport const tasks = async (tasks: Task[]) => {\n\tfor (const task of tasks) {\n\t\tif (task.enabled === false) continue;\n\n\t\tconst s = spinner();\n\t\ts.start(task.title);\n\t\tconst result = await task.task(s.message);\n\t\ts.stop(result || task.title);\n\t}\n};\n", "export const VERSION = '0.1.0-beta.1';\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,0CAAAA,UAAAC,SAAA;AAAA,QAAIC,KAAI,WAAW,CAAC;AAApB,QAAuB,OAAOA,GAAE,QAAQ,CAAC;AAAzC,QAA4C,MAAMA,GAAE,OAAO,CAAC;AAC5D,QAAI,mBACH,EAAE,CAAC,CAAC,IAAI,YAAY,KAAK,SAAS,YAAY,OAC7C,CAAC,CAAC,IAAI,eAAe,KAAK,SAAS,SAAS,KAAKA,GAAE,aAAa,YAAaA,GAAE,UAAU,CAAC,GAAG,SA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AEF;AAIA,KAAK,EAEF,KAAK,CAAC,SAAS;AAEd,MAAI,SAAS,GAAG;AAEd,YAAQ,WAAW;AAAA,EAErB;AAEF,CAAC,EAEA,MAAM,CAAC,UAAU;AAEhB,UAAQ,MAAM,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AAEpE,UAAQ,WAAW;AAErB,CAAC;",
6
+ "names": ["exports", "module", "p", "exports", "module", "x", "y", "import_node_path", "import_promises", "m", "e", "k", "resolve", "import_node_fs", "import_node_path", "fs", "b", "p", "d", "import_node_fs", "import_node_path", "isRecord", "item", "b", "g", "provider", "item", "k", "PROVIDERS", "provider", "item", "normalizePath", "item", "visibleFiles", "visibleFiles", "item", "hasPackage", "packageEvidence", "pathEvidence", "envEvidence", "isClientExecutedPath", "visibleFiles", "AREAS", "buildContext", "item", "normalizePath", "provider", "providerLabel", "_", "raw", "normalized", "scanContext", "fs", "import_promises", "import_node_path", "b", "normalizeProviderToken", "provider", "b", "normalizeProviderKey", "g", "providerLabel", "import_node_fs", "import_node_path", "import_promises", "import_node_path", "SEVERITY_RANK", "b", "g", "resolve", "import_node_child_process", "resolve", "pc", "g", "provider", "import_node_path", "ansiRegex", "onlyFirst", "pattern", "regex", "stripAnsi", "string", "e", "eaw", "module", "character", "x", "y", "codePoint", "code", "stringToArray", "characters", "len", "i", "text", "start", "end", "result", "eawLen", "chars", "char", "charLen", "emojiRegex", "stringWidth", "options", "ambiguousCharacterWidth", "width", "eastAsianWidth", "ANSI_BACKGROUND_OFFSET", "wrapAnsi16", "offset", "wrapAnsi256", "wrapAnsi16m", "red", "green", "blue", "styles", "foregroundColorNames", "backgroundColorNames", "assembleStyles", "codes", "groupName", "group", "styleName", "style", "hex", "matches", "colorString", "integer", "remainder", "value", "ansiStyles", "ESCAPES", "END_CODE", "ANSI_ESCAPE_BELL", "ANSI_CSI", "ANSI_OSC", "ANSI_SGR_TERMINATOR", "ANSI_ESCAPE_LINK", "wrapAnsiCode", "wrapAnsiHyperlink", "uri", "wordLengths", "wrapWord", "rows", "word", "columns", "isInsideEscape", "isInsideLinkEscape", "visible", "index", "characterLength", "stringVisibleTrimSpacesRight", "words", "last", "exec", "returnValue", "escapeCode", "escapeUrl", "lengths", "rowLength", "remainingColumns", "breaksStartingThisLine", "row", "pre", "groups", "wrapAnsi", "line", "actions", "settings", "isActionKey", "key", "action", "settings", "value", "diffLines", "a", "b", "aLines", "bLines", "diff", "i", "isWindows", "CANCEL_SYMBOL", "isCancel", "setRawMode", "input", "block", "stdin", "output", "stdout", "overwrite", "hideCursor", "rl", "readline", "clear", "data", "name", "sequence", "str", "cursor", "dx", "dy", "v", "t", "e", "s", "Prompt", "options", "trackValue", "__publicField", "render", "signal", "opts", "event", "params", "cb", "cbs", "cleanup", "subscriber", "resolve", "reject", "sink", "Writable", "chunk", "encoding", "done", "char", "problem", "lines", "wrap", "frame", "diffLine", "erase", "newLines", "_selectableGroups", "_selectableGroups", "e", "u", "SelectPrompt", "Prompt", "opts", "__publicField", "value", "key", "isUnicodeSupported", "process", "unicode", "s", "c", "fallback", "S_STEP_ACTIVE", "S_STEP_CANCEL", "S_STEP_ERROR", "S_STEP_SUBMIT", "S_BAR_START", "S_BAR", "S_BAR_END", "S_RADIO_ACTIVE", "S_RADIO_INACTIVE", "S_CHECKBOX_ACTIVE", "S_CHECKBOX_SELECTED", "S_CHECKBOX_INACTIVE", "S_PASSWORD_MASK", "S_BAR_H", "S_CORNER_TOP_RIGHT", "S_CONNECT_LEFT", "S_CORNER_BOTTOM_RIGHT", "S_INFO", "S_SUCCESS", "S_WARN", "S_ERROR", "symbol", "state", "color", "limitOptions", "params", "cursor", "options", "style", "paramMaxItems", "outputMaxItems", "maxItems", "slidingWindowLocation", "shouldRenderTopEllipsis", "shouldRenderBottomEllipsis", "option", "i", "arr", "isTopLimit", "isBottomLimit", "select", "opts", "opt", "option", "state", "label", "color", "S_RADIO_ACTIVE", "S_RADIO_INACTIVE", "SelectPrompt", "title", "S_BAR", "symbol", "limitOptions", "item", "active", "S_BAR_END", "cancel", "message", "color", "S_BAR_END", "intro", "title", "S_BAR_START", "outro", "S_BAR", "log", "symbol", "parts", "firstLine", "lines", "ln", "S_INFO", "S_SUCCESS", "S_STEP_SUBMIT", "S_WARN", "S_ERROR", "prefix", "spinner", "indicator", "frames", "unicode", "delay", "isCI", "unblock", "loop", "isSpinnerActive", "_message", "_prevMessage", "_origin", "handleExit", "code", "msg", "stop", "errorEventHandler", "signalEventHandler", "registerHooks", "clearHooks", "clearPrevMessage", "prevLines", "cursor", "erase", "parseMessage", "formatTimer", "origin", "duration", "min", "secs", "start", "block", "color", "S_BAR", "frameIndex", "indicatorTimer", "frame", "loadingDots", "step", "S_STEP_SUBMIT", "S_STEP_CANCEL", "S_STEP_ERROR", "import_picocolors", "pc", "Y", "M", "provider"]
7
7
  }