Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

error-mode.setup.ts

205 lines5.5 KB

1import { execSync, spawn } from 'node:child_process'
2import fs from 'node:fs'
3import path from 'node:path'
4import { stripVTControlCharacters } from 'node:util'
5import { appServerReadyPattern } from '@tanstack/router-e2e-utils'
6import { chromium, expect } from '@playwright/test'
7import type { FullConfig } from '@playwright/test'
8​
9/**
10 * Global setup for error-mode E2E tests.
11 *
12 * 1. Runs `BEHAVIOR=error pnpm build` β€” expected to fail because the plugin
13 * calls `this.error()` on the first violation, aborting the Rollup build.
14 * Output is written to `error-build-result.json`.
15 *
16 * 2. Starts a dev server with `BEHAVIOR=error`, navigates all violation
17 * routes, then captures the server log. In dev mode `this.error()` causes
18 * a module-level 500 (the server stays up). Output is written to
19 * `error-dev-result.json`.
20 */
21​
22const toolchain = process.env.E2E_TOOLCHAIN ?? 'vite'
23​
24async function waitForHttpOk(url: string, timeoutMs: number): Promise<void> {
25 const start = Date.now()
26​
27 while (true) {
28 if (Date.now() - start > timeoutMs) {
29 throw new Error(`Timed out waiting for ${url}`)
30 }
31 try {
32 const res = await fetch(url, { signal: AbortSignal.timeout(1000) })
33 if (res.ok) return
34 } catch {
35 // ignore
36 }
37 await new Promise((r) => setTimeout(r, 200))
38 }
40​
41async function killChild(child: ReturnType<typeof spawn>): Promise<void> {
42 if (child.exitCode !== null || child.killed) return
43 await new Promise<void>((resolve) => {
44 let resolved = false
45 const done = () => {
46 if (resolved) return
47 resolved = true
48 resolve()
49 }
50 child.once('exit', done)
51 child.once('error', done)
52 try {
53 child.kill('SIGTERM')
54 } catch {
55 done()
56 return
57 }
58 setTimeout(() => {
59 try {
60 child.kill('SIGKILL')
61 } catch {
62 // ignore
63 }
64 setTimeout(done, 500)
65 }, 3000)
66 })
68​
69function captureBuild(cwd: string): void {
70 const buildCommand =
71 toolchain === 'rsbuild' ? 'pnpm build:rsbuild' : 'pnpm build:vite'
72 const outFile = path.resolve(cwd, 'error-build-result.json')
73 for (const f of ['error-build-result.json', 'error-build.log']) {
74 const p = path.resolve(cwd, f)
75 if (fs.existsSync(p)) fs.unlinkSync(p)
76 }
77​
78 let stdout = ''
79 let stderr = ''
80 let exitCode = 0
81​
82 try {
83 const output = execSync(buildCommand, {
84 cwd,
85 env: { ...process.env, BEHAVIOR: 'error' },
86 encoding: 'utf-8',
87 stdio: ['ignore', 'pipe', 'pipe'],
88 timeout: 120_000,
89 })
90 stdout = output
91 } catch (err: any) {
92 exitCode = err.status ?? 1
93 stdout = err.stdout ?? ''
94 stderr = err.stderr ?? ''
95 }
96​
97 const combined = `${stdout}\n${stderr}`
98 fs.writeFileSync(path.resolve(cwd, 'error-build.log'), combined)
99 fs.writeFileSync(
100 outFile,
101 JSON.stringify({ exitCode, stdout, stderr, combined }, null, 2),
102 )
104​
105const routes = [
106 '/',
107 '/leaky-server-import',
108 '/client-only-violations',
109 '/client-only-jsx',
110 '/beforeload-leak',
111 '/barrel-false-positive',
113​
114async function captureDev(cwd: string): Promise<void> {
115 const outFile = path.resolve(cwd, 'error-dev-result.json')
116 for (const f of ['error-dev-result.json', 'error-dev.log']) {
117 const p = path.resolve(cwd, f)
118 if (fs.existsSync(p)) fs.unlinkSync(p)
119 }
120​
121 const port = 0
122 const logFile = path.resolve(cwd, 'error-dev.log')
123​
124 const out = fs.createWriteStream(logFile)
125 const toolchain = process.env.E2E_TOOLCHAIN ?? 'vite'
126 const command =
127 toolchain === 'rsbuild'
128 ? ['exec', 'rsbuild', 'dev', '--port', String(port)]
129 : ['exec', 'vite', 'dev', '--port', String(port)]
130​
131 const child = spawn('pnpm', command, {
132 cwd,
133 env: {
134 ...process.env,
135 BEHAVIOR: 'error',
136 PORT: String(port),
137 VITE_SERVER_PORT: String(port),
138 VITE_NODE_ENV: 'test',
139 },
140 stdio: ['ignore', 'pipe', 'pipe'],
141 })
142​
143 const logChunks: Array<string> = []
144 const record = (data: Buffer) => {
145 logChunks.push(data.toString())
146 out.write(data)
147 }
148 child.stdout.on('data', record)
149 child.stderr.on('data', record)
150​
151 try {
152 await expect
153 .poll(
154 () =>
155 appServerReadyPattern.exec(
156 stripVTControlCharacters(logChunks.join('')),
157 )?.groups?.E2E_APP_PORT,
158 { timeout: 30_000 },
159 )
160 .toBeTruthy()
161 const port = appServerReadyPattern.exec(
162 stripVTControlCharacters(logChunks.join('')),
163 )!.groups!.E2E_APP_PORT
164 const baseURL = `http://localhost:${port}`
165 await waitForHttpOk(baseURL, 30_000)
166​
167 const browser = await chromium.launch()
168 try {
169 const context = await browser.newContext()
170 const page = await context.newPage()
171 for (const route of routes) {
172 try {
173 await page.goto(`${baseURL}${route}`, {
174 // Vite dev keeps long-lived connections; 'networkidle' can hang.
175 waitUntil: 'load',
176 timeout: 30_000,
177 })
178 } catch {
179 // expected β€” modules fail with 500 in error mode
180 }
181 }
182 await context.close()
183 } finally {
184 await browser.close()
185 }
186​
187 await new Promise((r) => setTimeout(r, 750))
188 } finally {
189 await killChild(child)
190 await new Promise<void>((resolve) => out.end(resolve))
191 }
192​
193 const combined = fs.existsSync(logFile)
194 ? fs.readFileSync(logFile, 'utf-8')
195 : ''
196 fs.writeFileSync(outFile, JSON.stringify({ combined }, null, 2))
198​
199export default async function globalSetup(config: FullConfig) {
200 void config
201 const cwd = path.resolve(import.meta.dirname, '..')
202​
203 captureBuild(cwd)
204 await captureDev(cwd)