import express from 'express';
import path from 'path';
import { fileURLToPath } from 'url';
import { AccessibilityTester } from '../accessibility/tester.js';
import { URLValidator } from '../utils/validation.js';
import { AccessibilityTestOptions, ViolationSummary } from '../types/index.js';
import { Result, NodeResult } from 'axe-core';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
const port = process.env.PORT || 3000;
app.use(express.json());
// Add headers to prevent caching
app.use((req, res, next) => {
res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate');
res.setHeader('Pragma', 'no-cache');
res.setHeader('Expires', '0');
res.setHeader('Surrogate-Control', 'no-store');
next();
});
app.use(express.static(path.join(__dirname, '..', '..', 'public')));
app.post('/api/test', async (req, res) => {
const { url, wcagLevel, criticality } = req.body;
const validation = URLValidator.validate(url);
if (!validation.isValid) {
return res.status(400).json({ message: validation.error || 'Invalid or disallowed URL provided.' });
}
const tester = new AccessibilityTester();
try {
await tester.initialize();
const results = await tester.run(url, wcagLevel, criticality);
const violations: ViolationSummary[] = results.violations.map((v: Result) => ({
id: v.id,
impact: v.impact!,
description: v.description,
help: v.help,
helpUrl: v.helpUrl,
tags: v.tags,
nodes: v.nodes.map((node: NodeResult) => ({
html: node.html,
target: node.target,
failureSummary: node.failureSummary || '',
})),
}));
res.json({ violations });
} catch (error) {
console.error('Error during accessibility test:', error);
res.status(500).json({ message: 'An error occurred during the accessibility test.' });
} finally {
await tester.cleanup(); // Ensure browser is closed
}
});
export function startWebServer() {
app.listen(port, () => {
console.log(`🚀 Web server started at http://localhost:${port}`);
});
}