import * as fs from 'fs'; import * as path from 'path'; import { fileURLToPath } from 'url'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); async function globalSetup() { // Read env vars written by scripts/test-env.sh (make test-up calls it first) const envFile = path.resolve(__dirname, '../../data/test/.env'); if (!fs.existsSync(envFile)) { throw new Error('data/test/.env not found — run "make test-up" first'); } for (const line of fs.readFileSync(envFile, 'utf-8').split('\n')) { const eq = line.indexOf('='); if (eq > 0) process.env[line.slice(0, eq).trim()] = line.slice(eq + 1).trim(); } const baseURL = process.env.TT_BASE_URL!; // Obtain admin JWT via the login API const res = await fetch(`${baseURL}/api/auth/login`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email: 'admin@tutortool.com', password: 'admin' }), }); if (!res.ok) throw new Error(`Login failed: ${res.status} ${await res.text()}`); // Extract cookies from Set-Cookie headers // Note: Use getSetCookie() in newer Node versions or handle joined string const setCookies = (res.headers as unknown as { getSetCookie?: () => string[] }).getSetCookie?.() || res.headers.get('set-cookie')?.split(',') || []; const cookies = setCookies.map((s: string) => { const parts = s.split(';').map(p => p.trim()); const [nameValue] = parts; if (!nameValue) return null; const [name, value] = nameValue.split('='); if (!name || !value) return null; const pathPart = parts.find(p => p.toLowerCase().startsWith('path=')); const path = pathPart ? pathPart.split('=')[1] : '/'; return { name, value, domain: new URL(baseURL).hostname, path: path || '/', httpOnly: s.toLowerCase().includes('httponly'), secure: s.toLowerCase().includes('secure'), sameSite: 'Strict' as const, }; }).filter(Boolean); // Write Playwright storage state with cookies pre-populated const authDir = path.resolve(__dirname, '.auth'); fs.mkdirSync(authDir, { recursive: true }); const storageState = { cookies, origins: [ { origin: baseURL, localStorage: [], }, ], }; fs.writeFileSync(path.join(authDir, 'admin.json'), JSON.stringify(storageState, null, 2)); } export default globalSetup;