webguardx 0.1.0

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/index.cjs ADDED
@@ -0,0 +1,1641 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ }
19
+ return to;
20
+ };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
26
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
+ mod
28
+ ));
29
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
+
31
+ // src/index.ts
32
+ var src_exports = {};
33
+ __export(src_exports, {
34
+ AccessibilityAudit: () => AccessibilityAudit,
35
+ BrokenLinksAudit: () => BrokenLinksAudit,
36
+ ConsoleErrorsAudit: () => ConsoleErrorsAudit,
37
+ ContentVisibilityAudit: () => ContentVisibilityAudit,
38
+ HttpStatusAudit: () => HttpStatusAudit,
39
+ LighthouseAudit: () => LighthouseAudit,
40
+ PluginRegistry: () => PluginRegistry,
41
+ compareRuns: () => compareRuns,
42
+ createSlackNotifier: () => createSlackNotifier,
43
+ createWebhookNotifier: () => createWebhookNotifier,
44
+ defineConfig: () => defineConfig,
45
+ loadBaseline: () => loadBaseline,
46
+ loadConfig: () => loadConfig,
47
+ loadPlugins: () => loadPlugins,
48
+ run: () => run,
49
+ saveBaseline: () => saveBaseline,
50
+ sendNotifications: () => sendNotifications
51
+ });
52
+ module.exports = __toCommonJS(src_exports);
53
+
54
+ // node_modules/tsup/assets/cjs_shims.js
55
+ var getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${__filename}`).href : document.currentScript && document.currentScript.tagName.toUpperCase() === "SCRIPT" ? document.currentScript.src : new URL("main.js", document.baseURI).href;
56
+ var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
57
+
58
+ // src/config/schema.ts
59
+ var import_zod = require("zod");
60
+ var AuthApiLoginSchema = import_zod.z.object({
61
+ method: import_zod.z.literal("api-login"),
62
+ loginUrl: import_zod.z.string().url(),
63
+ payload: import_zod.z.record(import_zod.z.string()),
64
+ headers: import_zod.z.record(import_zod.z.string()).optional()
65
+ });
66
+ var AuthFormLoginSchema = import_zod.z.object({
67
+ method: import_zod.z.literal("form-login"),
68
+ loginUrl: import_zod.z.string().url(),
69
+ fields: import_zod.z.array(
70
+ import_zod.z.object({
71
+ selector: import_zod.z.string(),
72
+ value: import_zod.z.string()
73
+ })
74
+ ),
75
+ submitSelector: import_zod.z.string(),
76
+ waitAfterLogin: import_zod.z.string().optional()
77
+ });
78
+ var AuthCookieSchema = import_zod.z.object({
79
+ method: import_zod.z.literal("cookie"),
80
+ cookies: import_zod.z.array(
81
+ import_zod.z.object({
82
+ name: import_zod.z.string(),
83
+ value: import_zod.z.string(),
84
+ domain: import_zod.z.string(),
85
+ path: import_zod.z.string().default("/")
86
+ })
87
+ )
88
+ });
89
+ var AuthBearerSchema = import_zod.z.object({
90
+ method: import_zod.z.literal("bearer-token"),
91
+ token: import_zod.z.string()
92
+ });
93
+ var AuthNoneSchema = import_zod.z.object({
94
+ method: import_zod.z.literal("none")
95
+ });
96
+ var AuthSchema = import_zod.z.discriminatedUnion("method", [
97
+ AuthApiLoginSchema,
98
+ AuthFormLoginSchema,
99
+ AuthCookieSchema,
100
+ AuthBearerSchema,
101
+ AuthNoneSchema
102
+ ]);
103
+ var PageSchema = import_zod.z.object({
104
+ name: import_zod.z.string(),
105
+ path: import_zod.z.string(),
106
+ expectedStatus: import_zod.z.number().default(200),
107
+ skipAudits: import_zod.z.array(import_zod.z.string()).optional()
108
+ });
109
+ var LighthouseThresholdsSchema = import_zod.z.object({
110
+ performance: import_zod.z.number().min(0).max(100).default(50),
111
+ accessibility: import_zod.z.number().min(0).max(100).default(90),
112
+ bestPractices: import_zod.z.number().min(0).max(100).default(80),
113
+ seo: import_zod.z.number().min(0).max(100).default(80)
114
+ }).partial();
115
+ var WebguardConfigSchema = import_zod.z.object({
116
+ baseURL: import_zod.z.string().url(),
117
+ pages: import_zod.z.array(PageSchema).min(1),
118
+ auth: AuthSchema.default({ method: "none" }),
119
+ // Open record — built-in keys have defaults, custom audit keys are allowed
120
+ audits: import_zod.z.record(import_zod.z.string(), import_zod.z.boolean()).default({
121
+ httpStatus: true,
122
+ contentVisibility: true,
123
+ accessibility: true,
124
+ lighthouse: false,
125
+ brokenLinks: false,
126
+ consoleErrors: true
127
+ }),
128
+ // Custom audits defined inline in config
129
+ customAudits: import_zod.z.array(import_zod.z.any()).default([]),
130
+ // Plugins — objects or string paths to npm packages / local files
131
+ plugins: import_zod.z.array(import_zod.z.any()).default([]),
132
+ wcagTags: import_zod.z.array(import_zod.z.string()).default(["wcag2a", "wcag2aa", "wcag21a", "wcag21aa"]),
133
+ lighthouseThresholds: LighthouseThresholdsSchema.default({}),
134
+ retry: import_zod.z.object({
135
+ maxRetries: import_zod.z.number().min(1).default(3),
136
+ delayMs: import_zod.z.number().min(0).default(5e3)
137
+ }).default({}),
138
+ runner: import_zod.z.object({
139
+ concurrency: import_zod.z.number().min(1).default(1),
140
+ failFast: import_zod.z.boolean().default(false)
141
+ }).default({}),
142
+ browser: import_zod.z.object({
143
+ headless: import_zod.z.boolean().default(true),
144
+ timeout: import_zod.z.number().default(6e4),
145
+ viewport: import_zod.z.object({
146
+ width: import_zod.z.number().default(1280),
147
+ height: import_zod.z.number().default(720)
148
+ }).default({})
149
+ }).default({}),
150
+ output: import_zod.z.object({
151
+ dir: import_zod.z.string().default("./webguard-results"),
152
+ formats: import_zod.z.array(import_zod.z.enum(["terminal", "html", "json", "junit"])).default(["terminal", "html", "json"]),
153
+ screenshots: import_zod.z.boolean().default(true),
154
+ screenshotOnFailOnly: import_zod.z.boolean().default(false)
155
+ }).default({}),
156
+ baseline: import_zod.z.object({
157
+ enabled: import_zod.z.boolean().default(false),
158
+ updateOnPass: import_zod.z.boolean().default(true)
159
+ }).default({}),
160
+ notifications: import_zod.z.array(import_zod.z.any()).default([])
161
+ });
162
+
163
+ // src/config/defaults.ts
164
+ function defineConfig(config) {
165
+ return WebguardConfigSchema.parse(config);
166
+ }
167
+
168
+ // src/config/loader.ts
169
+ var import_path = __toESM(require("path"), 1);
170
+ var import_fs = __toESM(require("fs"), 1);
171
+
172
+ // src/utils/logger.ts
173
+ var import_chalk = __toESM(require("chalk"), 1);
174
+ var log = {
175
+ info(msg) {
176
+ console.log(import_chalk.default.blue("i"), msg);
177
+ },
178
+ success(msg) {
179
+ console.log(import_chalk.default.green("\u2713"), msg);
180
+ },
181
+ warn(msg) {
182
+ console.log(import_chalk.default.yellow("\u26A0"), msg);
183
+ },
184
+ error(msg) {
185
+ console.log(import_chalk.default.red("\u2717"), msg);
186
+ },
187
+ dim(msg) {
188
+ console.log(import_chalk.default.dim(msg));
189
+ },
190
+ plain(msg) {
191
+ console.log(msg);
192
+ }
193
+ };
194
+
195
+ // src/config/loader.ts
196
+ var CONFIG_NAMES = [
197
+ "webguard.config.ts",
198
+ "webguard.config.js",
199
+ "webguard.config.mjs",
200
+ "webguard.config.json"
201
+ ];
202
+ async function loadConfig(configPath) {
203
+ const resolvedPath = configPath ? import_path.default.resolve(configPath) : findConfigFile();
204
+ if (!resolvedPath) {
205
+ throw new Error(
206
+ `No webguard config found. Run "webguardx init" to create one, or specify --config <path>.`
207
+ );
208
+ }
209
+ log.info(`Loading config from ${import_path.default.relative(process.cwd(), resolvedPath)}`);
210
+ let rawConfig;
211
+ if (resolvedPath.endsWith(".json")) {
212
+ const content = import_fs.default.readFileSync(resolvedPath, "utf-8");
213
+ rawConfig = JSON.parse(content);
214
+ } else {
215
+ const { createJiti } = await import("jiti");
216
+ const jiti = createJiti(importMetaUrl);
217
+ const mod = await jiti.import(resolvedPath);
218
+ rawConfig = mod.default ?? mod;
219
+ }
220
+ const result = WebguardConfigSchema.safeParse(rawConfig);
221
+ if (!result.success) {
222
+ const errors = result.error.issues.map((i) => ` - ${i.path.join(".")}: ${i.message}`).join("\n");
223
+ throw new Error(`Invalid webguard config:
224
+ ${errors}`);
225
+ }
226
+ return result.data;
227
+ }
228
+ function findConfigFile() {
229
+ const cwd = process.cwd();
230
+ for (const name of CONFIG_NAMES) {
231
+ const fullPath = import_path.default.join(cwd, name);
232
+ if (import_fs.default.existsSync(fullPath)) {
233
+ return fullPath;
234
+ }
235
+ }
236
+ return null;
237
+ }
238
+
239
+ // src/runner/index.ts
240
+ var import_playwright4 = require("playwright");
241
+
242
+ // src/auth/strategies/api-login.ts
243
+ var import_playwright = require("playwright");
244
+ var import_path3 = __toESM(require("path"), 1);
245
+
246
+ // src/utils/fs.ts
247
+ var import_fs2 = __toESM(require("fs"), 1);
248
+ var import_path2 = __toESM(require("path"), 1);
249
+ function ensureDir(dir) {
250
+ if (!import_fs2.default.existsSync(dir)) {
251
+ import_fs2.default.mkdirSync(dir, { recursive: true });
252
+ }
253
+ }
254
+ function cleanDir(dir) {
255
+ if (import_fs2.default.existsSync(dir)) {
256
+ import_fs2.default.rmSync(dir, { recursive: true, force: true });
257
+ }
258
+ }
259
+ function writeJson(filePath, data) {
260
+ ensureDir(import_path2.default.dirname(filePath));
261
+ import_fs2.default.writeFileSync(filePath, JSON.stringify(data, null, 2));
262
+ }
263
+
264
+ // src/auth/strategies/api-login.ts
265
+ async function apiLogin(config, outputDir) {
266
+ const authDir = import_path3.default.join(outputDir, ".auth");
267
+ ensureDir(authDir);
268
+ const storagePath = import_path3.default.join(authDir, "storageState.json");
269
+ const origin = new URL(config.loginUrl).origin;
270
+ const context = await import_playwright.request.newContext({ baseURL: origin });
271
+ const response = await context.post(config.loginUrl, {
272
+ data: config.payload,
273
+ headers: {
274
+ "content-type": "application/json",
275
+ accept: "application/json",
276
+ ...config.headers
277
+ }
278
+ });
279
+ if (!response.ok()) {
280
+ const body = await response.text();
281
+ await context.dispose();
282
+ throw new Error(`Login failed (HTTP ${response.status()}): ${body}`);
283
+ }
284
+ await context.storageState({ path: storagePath });
285
+ await context.dispose();
286
+ return { storageStatePath: storagePath };
287
+ }
288
+
289
+ // src/auth/strategies/form-login.ts
290
+ var import_playwright2 = require("playwright");
291
+ var import_path4 = __toESM(require("path"), 1);
292
+ async function formLogin(config, outputDir) {
293
+ const authDir = import_path4.default.join(outputDir, ".auth");
294
+ ensureDir(authDir);
295
+ const storagePath = import_path4.default.join(authDir, "storageState.json");
296
+ const browser = await import_playwright2.chromium.launch({ headless: true });
297
+ const context = await browser.newContext();
298
+ const page = await context.newPage();
299
+ await page.goto(config.loginUrl);
300
+ for (const field of config.fields) {
301
+ await page.fill(field.selector, field.value);
302
+ }
303
+ await page.click(config.submitSelector);
304
+ if (config.waitAfterLogin) {
305
+ if (config.waitAfterLogin.startsWith("http")) {
306
+ await page.waitForURL(config.waitAfterLogin);
307
+ } else {
308
+ await page.waitForSelector(config.waitAfterLogin);
309
+ }
310
+ } else {
311
+ await page.waitForLoadState("networkidle");
312
+ }
313
+ await context.storageState({ path: storagePath });
314
+ await browser.close();
315
+ return { storageStatePath: storagePath };
316
+ }
317
+
318
+ // src/auth/strategies/cookie-inject.ts
319
+ var import_fs5 = __toESM(require("fs"), 1);
320
+ var import_path5 = __toESM(require("path"), 1);
321
+ async function cookieInject(config, outputDir) {
322
+ const authDir = import_path5.default.join(outputDir, ".auth");
323
+ ensureDir(authDir);
324
+ const storagePath = import_path5.default.join(authDir, "storageState.json");
325
+ const storageState = {
326
+ cookies: config.cookies.map((c) => ({
327
+ name: c.name,
328
+ value: c.value,
329
+ domain: c.domain,
330
+ path: c.path || "/",
331
+ expires: -1,
332
+ httpOnly: false,
333
+ secure: true,
334
+ sameSite: "Lax"
335
+ })),
336
+ origins: []
337
+ };
338
+ import_fs5.default.writeFileSync(storagePath, JSON.stringify(storageState, null, 2));
339
+ return { storageStatePath: storagePath };
340
+ }
341
+
342
+ // src/auth/strategies/bearer-token.ts
343
+ var import_fs7 = __toESM(require("fs"), 1);
344
+ var import_path6 = __toESM(require("path"), 1);
345
+ async function bearerToken(config, outputDir) {
346
+ const authDir = import_path6.default.join(outputDir, ".auth");
347
+ ensureDir(authDir);
348
+ const storagePath = import_path6.default.join(authDir, "storageState.json");
349
+ import_fs7.default.writeFileSync(
350
+ storagePath,
351
+ JSON.stringify({ cookies: [], origins: [] })
352
+ );
353
+ return {
354
+ storageStatePath: storagePath,
355
+ extraHeaders: { Authorization: `Bearer ${config.token}` }
356
+ };
357
+ }
358
+
359
+ // src/auth/index.ts
360
+ async function authenticate(authConfig, outputDir) {
361
+ if (authConfig.method === "none") {
362
+ return null;
363
+ }
364
+ log.info(`Authenticating via ${authConfig.method}...`);
365
+ let result;
366
+ switch (authConfig.method) {
367
+ case "api-login":
368
+ result = await apiLogin(authConfig, outputDir);
369
+ break;
370
+ case "form-login":
371
+ result = await formLogin(authConfig, outputDir);
372
+ break;
373
+ case "cookie":
374
+ result = await cookieInject(authConfig, outputDir);
375
+ break;
376
+ case "bearer-token":
377
+ result = await bearerToken(authConfig, outputDir);
378
+ break;
379
+ }
380
+ log.success("Authenticated successfully");
381
+ return result;
382
+ }
383
+
384
+ // src/audits/http-status.ts
385
+ var HttpStatusAudit = {
386
+ name: "httpStatus",
387
+ description: "Verify the page returns the expected HTTP status code",
388
+ async run(ctx) {
389
+ const status = ctx.navigationResponse?.status() ?? 0;
390
+ const expected = ctx.pageEntry.expectedStatus ?? 200;
391
+ return {
392
+ audit: this.name,
393
+ page: ctx.pageEntry.name,
394
+ passed: status === expected,
395
+ severity: status === expected ? "pass" : "fail",
396
+ message: status === expected ? `HTTP ${status} OK` : `Expected HTTP ${expected}, got ${status}`,
397
+ details: { status, expected }
398
+ };
399
+ }
400
+ };
401
+
402
+ // src/audits/content-visibility.ts
403
+ var ContentVisibilityAudit = {
404
+ name: "contentVisibility",
405
+ description: "Verify the page has visible rendered content",
406
+ async run(ctx) {
407
+ const { page } = ctx;
408
+ const bodyVisible = await page.locator("body").isVisible().catch(() => false);
409
+ if (!bodyVisible) {
410
+ return {
411
+ audit: this.name,
412
+ page: ctx.pageEntry.name,
413
+ passed: false,
414
+ severity: "fail",
415
+ message: "Page body is not visible",
416
+ details: { bodyVisible: false, textLength: 0, elementCount: 0 }
417
+ };
418
+ }
419
+ const bodyText = await page.locator("body").innerText().catch(() => "");
420
+ const textLength = bodyText.trim().length;
421
+ const elementCount = await page.locator(
422
+ "body h1, body h2, body p, body main, body div, body section, body nav, body header"
423
+ ).count();
424
+ const passed = textLength > 0 && elementCount > 0;
425
+ return {
426
+ audit: this.name,
427
+ page: ctx.pageEntry.name,
428
+ passed,
429
+ severity: passed ? "pass" : "fail",
430
+ message: passed ? `${elementCount} elements visible` : `Content check failed (text: ${textLength} chars, elements: ${elementCount})`,
431
+ details: { bodyVisible: true, textLength, elementCount }
432
+ };
433
+ }
434
+ };
435
+
436
+ // src/audits/accessibility.ts
437
+ var import_playwright3 = __toESM(require("@axe-core/playwright"), 1);
438
+ var import_path7 = __toESM(require("path"), 1);
439
+
440
+ // src/utils/sanitize.ts
441
+ function sanitize(name) {
442
+ return name.replace(/[^a-zA-Z0-9_-]/g, "_");
443
+ }
444
+
445
+ // src/audits/accessibility.ts
446
+ var AccessibilityAudit = {
447
+ name: "accessibility",
448
+ description: "WCAG accessibility audit via axe-core",
449
+ async run(ctx) {
450
+ const results = await new import_playwright3.default({ page: ctx.page }).withTags(ctx.config.wcagTags).analyze();
451
+ const violations = results.violations;
452
+ if (violations.length > 0) {
453
+ const summary = violations.map((v) => ({
454
+ rule: v.id,
455
+ impact: v.impact,
456
+ description: v.description,
457
+ helpUrl: v.helpUrl,
458
+ elements: v.nodes.length
459
+ }));
460
+ const pageDir = import_path7.default.join(
461
+ ctx.runDir,
462
+ "screenshots",
463
+ sanitize(ctx.pageEntry.name)
464
+ );
465
+ writeJson(import_path7.default.join(pageDir, "a11y-violations.json"), summary);
466
+ }
467
+ return {
468
+ audit: this.name,
469
+ page: ctx.pageEntry.name,
470
+ passed: violations.length === 0,
471
+ severity: violations.length === 0 ? "pass" : "warning",
472
+ message: violations.length === 0 ? "0 violations" : `${violations.length} violation(s)`,
473
+ details: {
474
+ violationCount: violations.length,
475
+ violations: violations.map((v) => ({
476
+ rule: v.id,
477
+ impact: v.impact,
478
+ description: v.description,
479
+ elements: v.nodes.length
480
+ }))
481
+ }
482
+ };
483
+ }
484
+ };
485
+
486
+ // src/audits/lighthouse.ts
487
+ var import_path8 = __toESM(require("path"), 1);
488
+ var LighthouseAudit = {
489
+ name: "lighthouse",
490
+ description: "Lighthouse performance, accessibility, best practices, and SEO audit",
491
+ async run(ctx) {
492
+ let lighthouse;
493
+ let chromeLauncher;
494
+ try {
495
+ lighthouse = await import("lighthouse");
496
+ chromeLauncher = await import("chrome-launcher");
497
+ } catch {
498
+ return {
499
+ audit: this.name,
500
+ page: ctx.pageEntry.name,
501
+ passed: false,
502
+ severity: "skip",
503
+ message: "Lighthouse not installed. Run: npm install lighthouse chrome-launcher"
504
+ };
505
+ }
506
+ const chrome = await chromeLauncher.launch({
507
+ chromeFlags: ["--headless", "--no-sandbox"]
508
+ });
509
+ const url = `${ctx.config.baseURL}${ctx.pageEntry.path}`;
510
+ const thresholds = ctx.config.lighthouseThresholds;
511
+ try {
512
+ const result = await lighthouse.default(url, {
513
+ port: chrome.port,
514
+ output: "json",
515
+ logLevel: "error",
516
+ onlyCategories: [
517
+ "performance",
518
+ "accessibility",
519
+ "best-practices",
520
+ "seo"
521
+ ]
522
+ });
523
+ await chrome.kill();
524
+ if (!result?.lhr) {
525
+ return {
526
+ audit: this.name,
527
+ page: ctx.pageEntry.name,
528
+ passed: false,
529
+ severity: "fail",
530
+ message: "Lighthouse failed to produce results"
531
+ };
532
+ }
533
+ const scores = {
534
+ performance: Math.round(
535
+ (result.lhr.categories.performance?.score ?? 0) * 100
536
+ ),
537
+ accessibility: Math.round(
538
+ (result.lhr.categories.accessibility?.score ?? 0) * 100
539
+ ),
540
+ bestPractices: Math.round(
541
+ (result.lhr.categories["best-practices"]?.score ?? 0) * 100
542
+ ),
543
+ seo: Math.round((result.lhr.categories.seo?.score ?? 0) * 100)
544
+ };
545
+ const failures = [];
546
+ if (thresholds.performance && scores.performance < thresholds.performance)
547
+ failures.push(
548
+ `Performance: ${scores.performance} < ${thresholds.performance}`
549
+ );
550
+ if (thresholds.accessibility && scores.accessibility < thresholds.accessibility)
551
+ failures.push(
552
+ `Accessibility: ${scores.accessibility} < ${thresholds.accessibility}`
553
+ );
554
+ if (thresholds.bestPractices && scores.bestPractices < thresholds.bestPractices)
555
+ failures.push(
556
+ `Best Practices: ${scores.bestPractices} < ${thresholds.bestPractices}`
557
+ );
558
+ if (thresholds.seo && scores.seo < thresholds.seo)
559
+ failures.push(`SEO: ${scores.seo} < ${thresholds.seo}`);
560
+ const pageDir = import_path8.default.join(
561
+ ctx.runDir,
562
+ "screenshots",
563
+ sanitize(ctx.pageEntry.name)
564
+ );
565
+ ensureDir(pageDir);
566
+ writeJson(import_path8.default.join(pageDir, "lighthouse-report.json"), result.lhr);
567
+ return {
568
+ audit: this.name,
569
+ page: ctx.pageEntry.name,
570
+ passed: failures.length === 0,
571
+ severity: failures.length > 0 ? "fail" : "pass",
572
+ message: failures.length > 0 ? `Failed: ${failures.join("; ")}` : `perf=${scores.performance} a11y=${scores.accessibility} bp=${scores.bestPractices} seo=${scores.seo}`,
573
+ details: { scores, thresholds, failures }
574
+ };
575
+ } catch (err) {
576
+ await chrome.kill().catch(() => {
577
+ });
578
+ return {
579
+ audit: this.name,
580
+ page: ctx.pageEntry.name,
581
+ passed: false,
582
+ severity: "fail",
583
+ message: `Lighthouse error: ${err.message}`
584
+ };
585
+ }
586
+ }
587
+ };
588
+
589
+ // src/audits/broken-links.ts
590
+ var BrokenLinksAudit = {
591
+ name: "brokenLinks",
592
+ description: "Find broken links (4xx/5xx) on the page",
593
+ async run(ctx) {
594
+ const links = await ctx.page.$$eval(
595
+ "a[href]",
596
+ (anchors) => anchors.map((a) => a.getAttribute("href")).filter((href) => !!href)
597
+ );
598
+ const baseOrigin = new URL(ctx.config.baseURL).origin;
599
+ const uniqueLinks = [
600
+ ...new Set(
601
+ links.map((href) => {
602
+ try {
603
+ return new URL(href, ctx.config.baseURL).href;
604
+ } catch {
605
+ return null;
606
+ }
607
+ }).filter(
608
+ (url) => !!url && (url.startsWith("http://") || url.startsWith("https://"))
609
+ )
610
+ )
611
+ ];
612
+ const broken = [];
613
+ for (const url of uniqueLinks) {
614
+ try {
615
+ const response = await ctx.page.request.head(url, { timeout: 1e4 });
616
+ if (response.status() >= 400) {
617
+ broken.push({ url, status: response.status() });
618
+ }
619
+ } catch {
620
+ broken.push({ url, status: 0 });
621
+ }
622
+ }
623
+ return {
624
+ audit: this.name,
625
+ page: ctx.pageEntry.name,
626
+ passed: broken.length === 0,
627
+ severity: broken.length > 0 ? "warning" : "pass",
628
+ message: broken.length === 0 ? `All ${uniqueLinks.length} links valid` : `${broken.length} broken link(s) of ${uniqueLinks.length}`,
629
+ details: { totalLinks: uniqueLinks.length, broken }
630
+ };
631
+ }
632
+ };
633
+
634
+ // src/audits/console-errors.ts
635
+ var ConsoleErrorsAudit = {
636
+ name: "consoleErrors",
637
+ description: "Capture browser console errors and warnings",
638
+ async run(ctx) {
639
+ const messages = ctx.consoleMessages;
640
+ const errors = messages.filter((m) => m.type === "error");
641
+ const warnings = messages.filter((m) => m.type === "warning");
642
+ return {
643
+ audit: this.name,
644
+ page: ctx.pageEntry.name,
645
+ passed: errors.length === 0,
646
+ severity: errors.length > 0 ? "fail" : warnings.length > 0 ? "warning" : "pass",
647
+ message: errors.length === 0 && warnings.length === 0 ? "0 errors" : `${errors.length} error(s), ${warnings.length} warning(s)`,
648
+ details: {
649
+ errors: errors.map((e) => e.text),
650
+ warnings: warnings.map((w) => w.text)
651
+ }
652
+ };
653
+ }
654
+ };
655
+
656
+ // src/audits/index.ts
657
+ var BUILTIN_AUDITS = {
658
+ httpStatus: HttpStatusAudit,
659
+ contentVisibility: ContentVisibilityAudit,
660
+ accessibility: AccessibilityAudit,
661
+ lighthouse: LighthouseAudit,
662
+ brokenLinks: BrokenLinksAudit,
663
+ consoleErrors: ConsoleErrorsAudit
664
+ };
665
+ function getEnabledAudits(auditsConfig, pluginAudits = [], customAudits = []) {
666
+ const allAudits = { ...BUILTIN_AUDITS };
667
+ for (const audit of [...pluginAudits, ...customAudits]) {
668
+ allAudits[audit.name] = audit;
669
+ }
670
+ const enabled = [];
671
+ for (const [name, audit] of Object.entries(allAudits)) {
672
+ const isEnabled = auditsConfig[name] ?? true;
673
+ if (isEnabled) {
674
+ enabled.push(audit);
675
+ }
676
+ }
677
+ return enabled;
678
+ }
679
+
680
+ // src/runner/page-runner.ts
681
+ var import_path9 = __toESM(require("path"), 1);
682
+
683
+ // src/utils/sleep.ts
684
+ function sleep(ms) {
685
+ return new Promise((resolve) => setTimeout(resolve, ms));
686
+ }
687
+
688
+ // src/runner/retry.ts
689
+ async function navigateWithRetry(page, url, retry, waitUntil = "domcontentloaded") {
690
+ let lastError = null;
691
+ for (let attempt = 1; attempt <= retry.maxRetries; attempt++) {
692
+ try {
693
+ const response = await page.goto(url, {
694
+ waitUntil,
695
+ timeout: 3e4
696
+ });
697
+ if (response && response.ok()) {
698
+ return response;
699
+ }
700
+ if (attempt < retry.maxRetries) {
701
+ log.warn(
702
+ `Attempt ${attempt}/${retry.maxRetries} for ${url} returned ${response?.status()}. Retrying in ${retry.delayMs / 1e3}s...`
703
+ );
704
+ await sleep(retry.delayMs);
705
+ }
706
+ if (attempt === retry.maxRetries) return response;
707
+ } catch (error) {
708
+ lastError = error;
709
+ if (attempt < retry.maxRetries) {
710
+ log.warn(
711
+ `Attempt ${attempt}/${retry.maxRetries} for ${url} failed. Retrying in ${retry.delayMs / 1e3}s...`
712
+ );
713
+ await sleep(retry.delayMs);
714
+ }
715
+ }
716
+ }
717
+ throw lastError ?? new Error(`Failed to load ${url} after ${retry.maxRetries} attempts`);
718
+ }
719
+
720
+ // src/runner/page-runner.ts
721
+ async function runPageAudits(pageEntry, config, browserContext, audits, runDir, registry) {
722
+ const start = Date.now();
723
+ const url = `${config.baseURL}${pageEntry.path}`;
724
+ const page = await browserContext.newPage();
725
+ if (registry) {
726
+ await registry.runHook("beforePage", { config, pageEntry, page });
727
+ }
728
+ const consoleMessages = [];
729
+ page.on("console", (msg) => {
730
+ consoleMessages.push({ type: msg.type(), text: msg.text() });
731
+ });
732
+ let navigationResponse = null;
733
+ try {
734
+ navigationResponse = await navigateWithRetry(
735
+ page,
736
+ url,
737
+ config.retry,
738
+ "domcontentloaded"
739
+ );
740
+ } catch (err) {
741
+ log.error(`Failed to navigate to ${url}: ${err.message}`);
742
+ }
743
+ const ctx = {
744
+ page,
745
+ browserContext,
746
+ pageEntry,
747
+ config,
748
+ runDir,
749
+ navigationResponse,
750
+ consoleMessages
751
+ };
752
+ const pageAudits = audits.filter(
753
+ (a) => !pageEntry.skipAudits?.includes(a.name)
754
+ );
755
+ const auditResults = [];
756
+ for (const audit of pageAudits) {
757
+ if (registry) {
758
+ await registry.runHook("beforeAudit", { audit, auditContext: ctx });
759
+ }
760
+ const auditStart = Date.now();
761
+ let result;
762
+ try {
763
+ result = await audit.run(ctx);
764
+ result.duration = Date.now() - auditStart;
765
+ } catch (err) {
766
+ result = {
767
+ audit: audit.name,
768
+ page: pageEntry.name,
769
+ passed: false,
770
+ severity: "fail",
771
+ message: `Audit error: ${err.message}`,
772
+ duration: Date.now() - auditStart
773
+ };
774
+ }
775
+ auditResults.push(result);
776
+ if (registry) {
777
+ await registry.runHook("afterAudit", { audit, result });
778
+ }
779
+ }
780
+ let screenshotPath;
781
+ if (config.output.screenshots) {
782
+ const anyFailed = auditResults.some((r) => !r.passed);
783
+ if (!config.output.screenshotOnFailOnly || anyFailed) {
784
+ try {
785
+ const pageDir = import_path9.default.join(runDir, "screenshots", sanitize(pageEntry.name));
786
+ ensureDir(pageDir);
787
+ const status = anyFailed ? "fail" : "pass";
788
+ screenshotPath = import_path9.default.join(pageDir, `page-${status}.png`);
789
+ await page.screenshot({ path: screenshotPath, fullPage: true });
790
+ } catch {
791
+ }
792
+ }
793
+ }
794
+ const pageResult = {
795
+ page: pageEntry.name,
796
+ path: pageEntry.path,
797
+ url,
798
+ audits: auditResults,
799
+ screenshotPath,
800
+ duration: Date.now() - start
801
+ };
802
+ if (registry) {
803
+ await registry.runHook("afterPage", { config, pageEntry, pageResult });
804
+ }
805
+ await page.close();
806
+ return pageResult;
807
+ }
808
+
809
+ // src/runner/parallel.ts
810
+ async function runPagesParallel(pages, config, browserContext, audits, runDir, registry, concurrency, failFast) {
811
+ const results = new Array(pages.length);
812
+ let currentIndex = 0;
813
+ let aborted = false;
814
+ async function worker() {
815
+ while (!aborted) {
816
+ const index = currentIndex++;
817
+ if (index >= pages.length) break;
818
+ const pageEntry = pages[index];
819
+ log.plain(` [${index + 1}/${pages.length}] ${pageEntry.name} (${pageEntry.path})`);
820
+ const result = await runPageAudits(
821
+ pageEntry,
822
+ config,
823
+ browserContext,
824
+ audits,
825
+ runDir,
826
+ registry
827
+ );
828
+ results[index] = result;
829
+ for (const audit of result.audits) {
830
+ const icon = audit.passed ? " \u2713" : audit.severity === "warning" ? " \u26A0" : " \u2717";
831
+ const duration = audit.duration ? `${audit.duration}ms` : "";
832
+ log.plain(
833
+ `${icon} ${audit.audit.padEnd(20)} ${audit.message.padEnd(30)} ${duration}`
834
+ );
835
+ }
836
+ log.plain("");
837
+ if (failFast && result.audits.some((a) => a.severity === "fail")) {
838
+ log.warn("Fail fast enabled \u2014 stopping after first failure");
839
+ aborted = true;
840
+ }
841
+ }
842
+ }
843
+ const workerCount = Math.min(concurrency, pages.length);
844
+ const workers = Array.from({ length: workerCount }, () => worker());
845
+ await Promise.all(workers);
846
+ return results.filter(Boolean);
847
+ }
848
+
849
+ // src/runner/setup.ts
850
+ var import_path10 = __toESM(require("path"), 1);
851
+ function setupRunDirectory(outputBaseDir) {
852
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
853
+ const runDir = import_path10.default.join(outputBaseDir, `run-${timestamp}`);
854
+ const screenshotsDir = import_path10.default.join(runDir, "screenshots");
855
+ cleanDir(outputBaseDir);
856
+ ensureDir(screenshotsDir);
857
+ return { runDir, screenshotsDir };
858
+ }
859
+
860
+ // src/reporters/json.ts
861
+ var import_path11 = __toESM(require("path"), 1);
862
+ function reportJson(result, runDir) {
863
+ const filePath = import_path11.default.join(runDir, "results.json");
864
+ writeJson(filePath, result);
865
+ log.dim(` JSON report: ${filePath}`);
866
+ }
867
+
868
+ // src/reporters/terminal.ts
869
+ var import_chalk2 = __toESM(require("chalk"), 1);
870
+ function reportTerminal(result) {
871
+ const { summary } = result;
872
+ console.log("");
873
+ console.log(import_chalk2.default.bold("\u2500".repeat(60)));
874
+ console.log(import_chalk2.default.bold(" Summary"));
875
+ console.log(import_chalk2.default.bold("\u2500".repeat(60)));
876
+ console.log("");
877
+ console.log(` Total audits: ${summary.totalAudits}`);
878
+ console.log(
879
+ ` ${import_chalk2.default.green("\u2713 Passed:")} ${summary.passed}`
880
+ );
881
+ if (summary.failed > 0) {
882
+ console.log(
883
+ ` ${import_chalk2.default.red("\u2717 Failed:")} ${summary.failed}`
884
+ );
885
+ }
886
+ if (summary.warnings > 0) {
887
+ console.log(
888
+ ` ${import_chalk2.default.yellow("\u26A0 Warnings:")} ${summary.warnings}`
889
+ );
890
+ }
891
+ if (summary.skipped > 0) {
892
+ console.log(
893
+ ` ${import_chalk2.default.dim("\u25CB Skipped:")} ${summary.skipped}`
894
+ );
895
+ }
896
+ console.log(
897
+ ` Duration: ${(summary.duration / 1e3).toFixed(1)}s`
898
+ );
899
+ console.log("");
900
+ const failedAudits = result.pages.flatMap(
901
+ (p) => p.audits.filter((a) => a.severity === "fail")
902
+ );
903
+ if (failedAudits.length > 0) {
904
+ console.log(import_chalk2.default.red.bold(" Failed Audits:"));
905
+ for (const audit of failedAudits) {
906
+ console.log(
907
+ import_chalk2.default.red(` \u2717 ${audit.page} \u2192 ${audit.audit}: ${audit.message}`)
908
+ );
909
+ }
910
+ console.log("");
911
+ }
912
+ if (summary.failed > 0) {
913
+ console.log(
914
+ import_chalk2.default.red.bold(` Result: FAIL (${summary.failed} failure(s))`)
915
+ );
916
+ } else if (summary.warnings > 0) {
917
+ console.log(
918
+ import_chalk2.default.yellow.bold(` Result: PASS with ${summary.warnings} warning(s)`)
919
+ );
920
+ } else {
921
+ console.log(import_chalk2.default.green.bold(" Result: PASS"));
922
+ }
923
+ console.log("");
924
+ }
925
+
926
+ // src/reporters/html.ts
927
+ var import_fs14 = __toESM(require("fs"), 1);
928
+ var import_path12 = __toESM(require("path"), 1);
929
+ function escapeHtml(str) {
930
+ return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
931
+ }
932
+ function severityIcon(severity) {
933
+ switch (severity) {
934
+ case "pass":
935
+ return "&#x2713;";
936
+ case "fail":
937
+ return "&#x2717;";
938
+ case "warning":
939
+ return "&#x26A0;";
940
+ case "skip":
941
+ return "&#x25CB;";
942
+ default:
943
+ return "?";
944
+ }
945
+ }
946
+ function severityClass(severity) {
947
+ return `severity-${severity}`;
948
+ }
949
+ function renderAuditRow(audit) {
950
+ return `
951
+ <tr class="${severityClass(audit.severity)}">
952
+ <td class="icon">${severityIcon(audit.severity)}</td>
953
+ <td>${escapeHtml(audit.audit)}</td>
954
+ <td>${escapeHtml(audit.message)}</td>
955
+ <td class="duration">${audit.duration ? `${audit.duration}ms` : "\u2014"}</td>
956
+ </tr>`;
957
+ }
958
+ function renderPageSection(page) {
959
+ const failCount = page.audits.filter((a) => a.severity === "fail").length;
960
+ const status = failCount > 0 ? "fail" : "pass";
961
+ return `
962
+ <div class="page-section">
963
+ <h2 class="page-header ${status}">
964
+ <span class="page-name">${escapeHtml(page.page)}</span>
965
+ <span class="page-path">${escapeHtml(page.path)}</span>
966
+ <span class="page-duration">${(page.duration / 1e3).toFixed(1)}s</span>
967
+ </h2>
968
+ <table class="audit-table">
969
+ <thead>
970
+ <tr>
971
+ <th class="icon-col"></th>
972
+ <th>Audit</th>
973
+ <th>Result</th>
974
+ <th>Duration</th>
975
+ </tr>
976
+ </thead>
977
+ <tbody>
978
+ ${page.audits.map(renderAuditRow).join("")}
979
+ </tbody>
980
+ </table>
981
+ </div>`;
982
+ }
983
+ function buildHtml(result) {
984
+ const { summary } = result;
985
+ const overallStatus = summary.failed > 0 ? "FAIL" : summary.warnings > 0 ? "PASS (with warnings)" : "PASS";
986
+ const statusClass = summary.failed > 0 ? "fail" : summary.warnings > 0 ? "warning" : "pass";
987
+ return `<!DOCTYPE html>
988
+ <html lang="en">
989
+ <head>
990
+ <meta charset="UTF-8">
991
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
992
+ <title>Webguardx Report \u2014 ${escapeHtml(result.config.baseURL)}</title>
993
+ <style>
994
+ :root {
995
+ --pass: #22c55e;
996
+ --fail: #ef4444;
997
+ --warning: #f59e0b;
998
+ --skip: #94a3b8;
999
+ --bg: #0f172a;
1000
+ --surface: #1e293b;
1001
+ --text: #e2e8f0;
1002
+ --text-dim: #94a3b8;
1003
+ --border: #334155;
1004
+ }
1005
+
1006
+ * { box-sizing: border-box; margin: 0; padding: 0; }
1007
+
1008
+ body {
1009
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
1010
+ background: var(--bg);
1011
+ color: var(--text);
1012
+ line-height: 1.6;
1013
+ padding: 2rem;
1014
+ }
1015
+
1016
+ .container { max-width: 900px; margin: 0 auto; }
1017
+
1018
+ header {
1019
+ text-align: center;
1020
+ margin-bottom: 2rem;
1021
+ padding-bottom: 1.5rem;
1022
+ border-bottom: 1px solid var(--border);
1023
+ }
1024
+
1025
+ header h1 {
1026
+ font-size: 1.75rem;
1027
+ font-weight: 700;
1028
+ margin-bottom: 0.5rem;
1029
+ }
1030
+
1031
+ header .meta {
1032
+ color: var(--text-dim);
1033
+ font-size: 0.875rem;
1034
+ }
1035
+
1036
+ .summary-grid {
1037
+ display: grid;
1038
+ grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
1039
+ gap: 1rem;
1040
+ margin-bottom: 2rem;
1041
+ }
1042
+
1043
+ .summary-card {
1044
+ background: var(--surface);
1045
+ border-radius: 8px;
1046
+ padding: 1rem;
1047
+ text-align: center;
1048
+ border: 1px solid var(--border);
1049
+ }
1050
+
1051
+ .summary-card .value {
1052
+ font-size: 2rem;
1053
+ font-weight: 700;
1054
+ }
1055
+
1056
+ .summary-card .label {
1057
+ font-size: 0.75rem;
1058
+ color: var(--text-dim);
1059
+ text-transform: uppercase;
1060
+ letter-spacing: 0.05em;
1061
+ }
1062
+
1063
+ .summary-card.pass .value { color: var(--pass); }
1064
+ .summary-card.fail .value { color: var(--fail); }
1065
+ .summary-card.warning .value { color: var(--warning); }
1066
+ .summary-card.skip .value { color: var(--skip); }
1067
+
1068
+ .overall-status {
1069
+ text-align: center;
1070
+ font-size: 1.25rem;
1071
+ font-weight: 700;
1072
+ padding: 0.75rem;
1073
+ border-radius: 8px;
1074
+ margin-bottom: 2rem;
1075
+ }
1076
+
1077
+ .overall-status.pass { background: rgba(34,197,94,0.15); color: var(--pass); }
1078
+ .overall-status.fail { background: rgba(239,68,68,0.15); color: var(--fail); }
1079
+ .overall-status.warning { background: rgba(245,158,11,0.15); color: var(--warning); }
1080
+
1081
+ .page-section {
1082
+ background: var(--surface);
1083
+ border-radius: 8px;
1084
+ margin-bottom: 1.5rem;
1085
+ border: 1px solid var(--border);
1086
+ overflow: hidden;
1087
+ }
1088
+
1089
+ .page-header {
1090
+ padding: 1rem 1.25rem;
1091
+ display: flex;
1092
+ align-items: center;
1093
+ gap: 0.75rem;
1094
+ border-bottom: 1px solid var(--border);
1095
+ }
1096
+
1097
+ .page-header.fail { border-left: 4px solid var(--fail); }
1098
+ .page-header.pass { border-left: 4px solid var(--pass); }
1099
+
1100
+ .page-name { font-weight: 600; }
1101
+ .page-path { color: var(--text-dim); font-size: 0.875rem; }
1102
+ .page-duration { margin-left: auto; color: var(--text-dim); font-size: 0.875rem; }
1103
+
1104
+ .audit-table {
1105
+ width: 100%;
1106
+ border-collapse: collapse;
1107
+ }
1108
+
1109
+ .audit-table th {
1110
+ text-align: left;
1111
+ padding: 0.5rem 1rem;
1112
+ font-size: 0.75rem;
1113
+ text-transform: uppercase;
1114
+ color: var(--text-dim);
1115
+ border-bottom: 1px solid var(--border);
1116
+ }
1117
+
1118
+ .audit-table td {
1119
+ padding: 0.6rem 1rem;
1120
+ border-bottom: 1px solid var(--border);
1121
+ }
1122
+
1123
+ .audit-table tr:last-child td { border-bottom: none; }
1124
+
1125
+ .icon-col { width: 40px; }
1126
+ .icon { text-align: center; font-size: 1.1rem; }
1127
+ .duration { color: var(--text-dim); font-size: 0.875rem; }
1128
+
1129
+ .severity-pass .icon { color: var(--pass); }
1130
+ .severity-fail .icon { color: var(--fail); }
1131
+ .severity-warning .icon { color: var(--warning); }
1132
+ .severity-skip .icon { color: var(--skip); }
1133
+
1134
+ footer {
1135
+ text-align: center;
1136
+ margin-top: 2rem;
1137
+ padding-top: 1rem;
1138
+ border-top: 1px solid var(--border);
1139
+ color: var(--text-dim);
1140
+ font-size: 0.75rem;
1141
+ }
1142
+
1143
+ footer a { color: var(--text-dim); }
1144
+ </style>
1145
+ </head>
1146
+ <body>
1147
+ <div class="container">
1148
+ <header>
1149
+ <h1>Webguardx Report</h1>
1150
+ <div class="meta">
1151
+ ${escapeHtml(result.config.baseURL)} &bull;
1152
+ ${escapeHtml(result.timestamp)} &bull;
1153
+ ${result.config.auditsEnabled.join(", ")}
1154
+ </div>
1155
+ </header>
1156
+
1157
+ <div class="overall-status ${statusClass}">${overallStatus}</div>
1158
+
1159
+ <div class="summary-grid">
1160
+ <div class="summary-card">
1161
+ <div class="value">${summary.totalAudits}</div>
1162
+ <div class="label">Total</div>
1163
+ </div>
1164
+ <div class="summary-card pass">
1165
+ <div class="value">${summary.passed}</div>
1166
+ <div class="label">Passed</div>
1167
+ </div>
1168
+ <div class="summary-card fail">
1169
+ <div class="value">${summary.failed}</div>
1170
+ <div class="label">Failed</div>
1171
+ </div>
1172
+ <div class="summary-card warning">
1173
+ <div class="value">${summary.warnings}</div>
1174
+ <div class="label">Warnings</div>
1175
+ </div>
1176
+ <div class="summary-card skip">
1177
+ <div class="value">${summary.skipped}</div>
1178
+ <div class="label">Skipped</div>
1179
+ </div>
1180
+ <div class="summary-card">
1181
+ <div class="value">${(summary.duration / 1e3).toFixed(1)}s</div>
1182
+ <div class="label">Duration</div>
1183
+ </div>
1184
+ </div>
1185
+
1186
+ ${result.pages.map(renderPageSection).join("")}
1187
+
1188
+ <footer>
1189
+ Generated by <a href="https://github.com/user/webguardx">webguardx</a>
1190
+ </footer>
1191
+ </div>
1192
+ </body>
1193
+ </html>`;
1194
+ }
1195
+ function reportHtml(result, runDir) {
1196
+ const filePath = import_path12.default.join(runDir, "report.html");
1197
+ ensureDir(runDir);
1198
+ import_fs14.default.writeFileSync(filePath, buildHtml(result), "utf-8");
1199
+ log.dim(` HTML report: ${filePath}`);
1200
+ }
1201
+
1202
+ // src/reporters/junit.ts
1203
+ var import_fs16 = __toESM(require("fs"), 1);
1204
+ var import_path13 = __toESM(require("path"), 1);
1205
+ function escapeXml(str) {
1206
+ return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
1207
+ }
1208
+ function buildTestCase(audit) {
1209
+ const name = escapeXml(`${audit.page} - ${audit.audit}`);
1210
+ const time = audit.duration ? (audit.duration / 1e3).toFixed(3) : "0.000";
1211
+ if (audit.severity === "pass") {
1212
+ return ` <testcase name="${name}" classname="${escapeXml(audit.page)}" time="${time}" />
1213
+ `;
1214
+ }
1215
+ if (audit.severity === "skip") {
1216
+ return ` <testcase name="${name}" classname="${escapeXml(audit.page)}" time="${time}">
1217
+ <skipped message="${escapeXml(audit.message)}" />
1218
+ </testcase>
1219
+ `;
1220
+ }
1221
+ const tag = audit.severity === "fail" ? "failure" : "failure";
1222
+ return ` <testcase name="${name}" classname="${escapeXml(audit.page)}" time="${time}">
1223
+ <${tag} message="${escapeXml(audit.message)}" type="${escapeXml(audit.severity)}">${escapeXml(audit.message)}</${tag}>
1224
+ </testcase>
1225
+ `;
1226
+ }
1227
+ function buildTestSuite(page, index) {
1228
+ const tests = page.audits.length;
1229
+ const failures = page.audits.filter((a) => a.severity === "fail").length;
1230
+ const skipped = page.audits.filter((a) => a.severity === "skip").length;
1231
+ const time = (page.duration / 1e3).toFixed(3);
1232
+ let xml = ` <testsuite name="${escapeXml(page.page)}" tests="${tests}" failures="${failures}" skipped="${skipped}" time="${time}" id="${index}">
1233
+ `;
1234
+ for (const audit of page.audits) {
1235
+ xml += buildTestCase(audit);
1236
+ }
1237
+ xml += ` </testsuite>
1238
+ `;
1239
+ return xml;
1240
+ }
1241
+ function reportJunit(result, runDir) {
1242
+ const { summary } = result;
1243
+ const time = (summary.duration / 1e3).toFixed(3);
1244
+ let xml = `<?xml version="1.0" encoding="UTF-8"?>
1245
+ `;
1246
+ xml += `<testsuites name="webguardx" tests="${summary.totalAudits}" failures="${summary.failed}" skipped="${summary.skipped}" time="${time}">
1247
+ `;
1248
+ result.pages.forEach((page, i) => {
1249
+ xml += buildTestSuite(page, i);
1250
+ });
1251
+ xml += `</testsuites>
1252
+ `;
1253
+ const filePath = import_path13.default.join(runDir, "results.xml");
1254
+ ensureDir(runDir);
1255
+ import_fs16.default.writeFileSync(filePath, xml, "utf-8");
1256
+ log.dim(` JUnit report: ${filePath}`);
1257
+ }
1258
+
1259
+ // src/reporters/screenshot.ts
1260
+ function reportScreenshots(result) {
1261
+ const captured = result.pages.filter((p) => p.screenshotPath);
1262
+ if (captured.length > 0) {
1263
+ log.dim(` Screenshots: ${captured.length} page(s) captured`);
1264
+ }
1265
+ }
1266
+
1267
+ // src/reporters/index.ts
1268
+ async function runReporters(result, config, runDir, pluginReporters = []) {
1269
+ const formats = config.output.formats;
1270
+ if (formats.includes("terminal")) {
1271
+ reportTerminal(result);
1272
+ }
1273
+ log.dim(" Output:");
1274
+ if (formats.includes("json")) {
1275
+ reportJson(result, runDir);
1276
+ }
1277
+ if (formats.includes("html")) {
1278
+ reportHtml(result, runDir);
1279
+ }
1280
+ if (formats.includes("junit")) {
1281
+ reportJunit(result, runDir);
1282
+ }
1283
+ if (config.output.screenshots) {
1284
+ reportScreenshots(result);
1285
+ }
1286
+ for (const reporter of pluginReporters) {
1287
+ try {
1288
+ await reporter.run(result, runDir, config);
1289
+ log.dim(` ${reporter.name}: done`);
1290
+ } catch (err) {
1291
+ log.warn(`Reporter '${reporter.name}' failed: ${err.message}`);
1292
+ }
1293
+ }
1294
+ log.plain("");
1295
+ }
1296
+
1297
+ // src/plugins/registry.ts
1298
+ var PluginRegistry = class {
1299
+ plugins = [];
1300
+ register(plugin) {
1301
+ this.plugins.push(plugin);
1302
+ }
1303
+ getPluginAudits() {
1304
+ return this.plugins.flatMap((p) => p.audits ?? []);
1305
+ }
1306
+ getPluginReporters() {
1307
+ return this.plugins.flatMap((p) => p.reporters ?? []);
1308
+ }
1309
+ async runHook(hookName, ctx) {
1310
+ for (const plugin of this.plugins) {
1311
+ const hook = plugin.hooks?.[hookName];
1312
+ if (hook) {
1313
+ try {
1314
+ await hook(ctx);
1315
+ } catch (err) {
1316
+ log.warn(
1317
+ `Plugin '${plugin.name}' hook '${hookName}' failed: ${err.message}`
1318
+ );
1319
+ }
1320
+ }
1321
+ }
1322
+ }
1323
+ };
1324
+
1325
+ // src/plugins/loader.ts
1326
+ async function loadPlugins(pluginEntries) {
1327
+ const plugins = [];
1328
+ for (const entry of pluginEntries) {
1329
+ if (typeof entry === "string") {
1330
+ try {
1331
+ const { createJiti } = await import("jiti");
1332
+ const jiti = createJiti(importMetaUrl);
1333
+ const mod = await jiti.import(entry);
1334
+ const plugin = mod.default ?? mod;
1335
+ plugins.push(plugin);
1336
+ log.dim(` Loaded plugin: ${plugin.name ?? entry}`);
1337
+ } catch (err) {
1338
+ log.warn(`Failed to load plugin '${entry}': ${err.message}`);
1339
+ }
1340
+ } else {
1341
+ plugins.push(entry);
1342
+ }
1343
+ }
1344
+ return plugins;
1345
+ }
1346
+
1347
+ // src/runner/index.ts
1348
+ async function run(config, options = {}) {
1349
+ const start = Date.now();
1350
+ if (options.headed !== void 0) {
1351
+ config.browser.headless = !options.headed;
1352
+ }
1353
+ const registry = new PluginRegistry();
1354
+ if (config.plugins.length > 0) {
1355
+ const plugins = await loadPlugins(config.plugins);
1356
+ for (const plugin of plugins) {
1357
+ registry.register(plugin);
1358
+ }
1359
+ }
1360
+ const { runDir } = setupRunDirectory(config.output.dir);
1361
+ const authResult = await authenticate(config.auth, runDir);
1362
+ const browser = await import_playwright4.chromium.launch({
1363
+ headless: config.browser.headless
1364
+ });
1365
+ const contextOptions = {
1366
+ viewport: config.browser.viewport
1367
+ };
1368
+ if (authResult?.storageStatePath) {
1369
+ contextOptions.storageState = authResult.storageStatePath;
1370
+ }
1371
+ if (authResult?.extraHeaders) {
1372
+ contextOptions.extraHTTPHeaders = authResult.extraHeaders;
1373
+ }
1374
+ const browserContext = await browser.newContext(contextOptions);
1375
+ await registry.runHook("beforeAll", { config, browserContext });
1376
+ let audits = getEnabledAudits(
1377
+ config.audits,
1378
+ registry.getPluginAudits(),
1379
+ config.customAudits
1380
+ );
1381
+ if (options.auditsFilter?.length) {
1382
+ audits = audits.filter((a) => options.auditsFilter.includes(a.name));
1383
+ }
1384
+ const enabledAuditNames = audits.map((a) => a.name);
1385
+ let pages = config.pages;
1386
+ if (options.pagesFilter?.length) {
1387
+ pages = pages.filter((p) => options.pagesFilter.includes(p.name));
1388
+ }
1389
+ log.plain("");
1390
+ log.info(`Base URL: ${config.baseURL}`);
1391
+ log.info(`Pages: ${pages.length}`);
1392
+ log.info(`Audits: ${enabledAuditNames.join(", ")}`);
1393
+ if (config.plugins.length > 0) {
1394
+ log.info(`Plugins: ${config.plugins.length}`);
1395
+ }
1396
+ if (config.runner.concurrency > 1) {
1397
+ log.info(`Workers: ${config.runner.concurrency}`);
1398
+ }
1399
+ log.plain("");
1400
+ let pageResults;
1401
+ if (config.runner.concurrency > 1) {
1402
+ pageResults = await runPagesParallel(
1403
+ pages,
1404
+ config,
1405
+ browserContext,
1406
+ audits,
1407
+ runDir,
1408
+ registry,
1409
+ config.runner.concurrency,
1410
+ config.runner.failFast
1411
+ );
1412
+ } else {
1413
+ pageResults = [];
1414
+ for (let i = 0; i < pages.length; i++) {
1415
+ const pageEntry = pages[i];
1416
+ log.plain(` [${i + 1}/${pages.length}] ${pageEntry.name} (${pageEntry.path})`);
1417
+ const result = await runPageAudits(
1418
+ pageEntry,
1419
+ config,
1420
+ browserContext,
1421
+ audits,
1422
+ runDir,
1423
+ registry
1424
+ );
1425
+ pageResults.push(result);
1426
+ for (const audit of result.audits) {
1427
+ const icon = audit.passed ? " \u2713" : audit.severity === "warning" ? " \u26A0" : " \u2717";
1428
+ const duration = audit.duration ? `${audit.duration}ms` : "";
1429
+ log.plain(`${icon} ${audit.audit.padEnd(20)} ${audit.message.padEnd(30)} ${duration}`);
1430
+ }
1431
+ log.plain("");
1432
+ if (config.runner.failFast && result.audits.some((a) => a.severity === "fail")) {
1433
+ log.warn("Fail fast enabled \u2014 stopping after first failure");
1434
+ break;
1435
+ }
1436
+ }
1437
+ }
1438
+ await browserContext.close();
1439
+ await browser.close();
1440
+ const allAudits = pageResults.flatMap((p) => p.audits);
1441
+ const runResult = {
1442
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1443
+ config: {
1444
+ baseURL: config.baseURL,
1445
+ totalPages: pages.length,
1446
+ auditsEnabled: enabledAuditNames
1447
+ },
1448
+ pages: pageResults,
1449
+ summary: {
1450
+ totalAudits: allAudits.length,
1451
+ passed: allAudits.filter((a) => a.severity === "pass").length,
1452
+ failed: allAudits.filter((a) => a.severity === "fail").length,
1453
+ warnings: allAudits.filter((a) => a.severity === "warning").length,
1454
+ skipped: allAudits.filter((a) => a.severity === "skip").length,
1455
+ duration: Date.now() - start
1456
+ }
1457
+ };
1458
+ await registry.runHook("afterAll", { config, result: runResult });
1459
+ await runReporters(runResult, config, runDir, registry.getPluginReporters());
1460
+ return runResult;
1461
+ }
1462
+
1463
+ // src/notifications/webhook.ts
1464
+ function createWebhookNotifier(url, options = {}) {
1465
+ return {
1466
+ name: `webhook:${new URL(url).hostname}`,
1467
+ async send(result, config) {
1468
+ if (options.onlyOnFailure && result.summary.failed === 0) return;
1469
+ await fetch(url, {
1470
+ method: options.method ?? "POST",
1471
+ headers: {
1472
+ "Content-Type": "application/json",
1473
+ ...options.headers
1474
+ },
1475
+ body: JSON.stringify({
1476
+ tool: "webguardx",
1477
+ status: result.summary.failed > 0 ? "fail" : "pass",
1478
+ baseURL: config.baseURL,
1479
+ timestamp: result.timestamp,
1480
+ summary: result.summary
1481
+ })
1482
+ });
1483
+ }
1484
+ };
1485
+ }
1486
+
1487
+ // src/notifications/slack.ts
1488
+ function createSlackNotifier(webhookUrl, options = {}) {
1489
+ return {
1490
+ name: "slack",
1491
+ async send(result, config) {
1492
+ if (options.onlyOnFailure && result.summary.failed === 0) return;
1493
+ const color = result.summary.failed > 0 ? "#ef4444" : "#22c55e";
1494
+ const status = result.summary.failed > 0 ? "FAIL" : "PASS";
1495
+ const { summary } = result;
1496
+ await fetch(webhookUrl, {
1497
+ method: "POST",
1498
+ headers: { "Content-Type": "application/json" },
1499
+ body: JSON.stringify({
1500
+ channel: options.channel,
1501
+ attachments: [
1502
+ {
1503
+ color,
1504
+ title: `Webguardx: ${status}`,
1505
+ title_link: config.baseURL,
1506
+ text: `${summary.passed} passed, ${summary.failed} failed, ${summary.warnings} warnings`,
1507
+ fields: [
1508
+ { title: "Base URL", value: config.baseURL, short: true },
1509
+ { title: "Pages", value: `${config.pages.length}`, short: true },
1510
+ { title: "Duration", value: `${(summary.duration / 1e3).toFixed(1)}s`, short: true }
1511
+ ],
1512
+ footer: "webguardx",
1513
+ ts: Math.floor(Date.now() / 1e3)
1514
+ }
1515
+ ]
1516
+ })
1517
+ });
1518
+ }
1519
+ };
1520
+ }
1521
+
1522
+ // src/notifications/index.ts
1523
+ async function sendNotifications(channels, result, config) {
1524
+ for (const channel of channels) {
1525
+ try {
1526
+ await channel.send(result, config);
1527
+ log.dim(` Notification sent: ${channel.name}`);
1528
+ } catch (err) {
1529
+ log.warn(
1530
+ `Notification '${channel.name}' failed: ${err.message}`
1531
+ );
1532
+ }
1533
+ }
1534
+ }
1535
+
1536
+ // src/baseline/storage.ts
1537
+ var import_path14 = __toESM(require("path"), 1);
1538
+ var import_fs18 = __toESM(require("fs"), 1);
1539
+ var BASELINE_FILENAME = "baseline.json";
1540
+ function saveBaseline(result, outputDir) {
1541
+ const baselinePath = import_path14.default.join(outputDir, BASELINE_FILENAME);
1542
+ import_fs18.default.writeFileSync(baselinePath, JSON.stringify(result, null, 2));
1543
+ log.success(`Baseline saved: ${baselinePath}`);
1544
+ }
1545
+ function loadBaseline(outputDir) {
1546
+ const baselinePath = import_path14.default.join(outputDir, BASELINE_FILENAME);
1547
+ if (!import_fs18.default.existsSync(baselinePath)) return null;
1548
+ try {
1549
+ return JSON.parse(import_fs18.default.readFileSync(baselinePath, "utf-8"));
1550
+ } catch {
1551
+ log.warn("Failed to parse baseline file");
1552
+ return null;
1553
+ }
1554
+ }
1555
+
1556
+ // src/baseline/diff.ts
1557
+ function compareRuns(baseline, current) {
1558
+ const changes = [];
1559
+ const baselineMap = /* @__PURE__ */ new Map();
1560
+ for (const page of baseline.pages) {
1561
+ for (const audit of page.audits) {
1562
+ baselineMap.set(`${page.page}::${audit.audit}`, {
1563
+ severity: audit.severity,
1564
+ message: audit.message
1565
+ });
1566
+ }
1567
+ }
1568
+ const currentMap = /* @__PURE__ */ new Map();
1569
+ for (const page of current.pages) {
1570
+ for (const audit of page.audits) {
1571
+ const key = `${page.page}::${audit.audit}`;
1572
+ const entry = { severity: audit.severity, message: audit.message };
1573
+ currentMap.set(key, entry);
1574
+ const prev = baselineMap.get(key);
1575
+ if (!prev) {
1576
+ changes.push({
1577
+ page: page.page,
1578
+ audit: audit.audit,
1579
+ type: "new",
1580
+ current: entry
1581
+ });
1582
+ } else if (prev.severity !== audit.severity) {
1583
+ const type = audit.severity === "pass" || audit.severity === "skip" ? "improvement" : "regression";
1584
+ changes.push({
1585
+ page: page.page,
1586
+ audit: audit.audit,
1587
+ type,
1588
+ baseline: prev,
1589
+ current: entry
1590
+ });
1591
+ } else {
1592
+ changes.push({
1593
+ page: page.page,
1594
+ audit: audit.audit,
1595
+ type: "unchanged",
1596
+ baseline: prev,
1597
+ current: entry
1598
+ });
1599
+ }
1600
+ }
1601
+ }
1602
+ for (const [key, val] of baselineMap) {
1603
+ if (!currentMap.has(key)) {
1604
+ const [page, audit] = key.split("::");
1605
+ changes.push({ page, audit, type: "removed", baseline: val });
1606
+ }
1607
+ }
1608
+ return {
1609
+ baselineTimestamp: baseline.timestamp,
1610
+ currentTimestamp: current.timestamp,
1611
+ changes,
1612
+ summary: {
1613
+ regressions: changes.filter((c) => c.type === "regression").length,
1614
+ improvements: changes.filter((c) => c.type === "improvement").length,
1615
+ unchanged: changes.filter((c) => c.type === "unchanged").length,
1616
+ newAudits: changes.filter((c) => c.type === "new").length,
1617
+ removedAudits: changes.filter((c) => c.type === "removed").length
1618
+ }
1619
+ };
1620
+ }
1621
+ // Annotate the CommonJS export names for ESM import in node:
1622
+ 0 && (module.exports = {
1623
+ AccessibilityAudit,
1624
+ BrokenLinksAudit,
1625
+ ConsoleErrorsAudit,
1626
+ ContentVisibilityAudit,
1627
+ HttpStatusAudit,
1628
+ LighthouseAudit,
1629
+ PluginRegistry,
1630
+ compareRuns,
1631
+ createSlackNotifier,
1632
+ createWebhookNotifier,
1633
+ defineConfig,
1634
+ loadBaseline,
1635
+ loadConfig,
1636
+ loadPlugins,
1637
+ run,
1638
+ saveBaseline,
1639
+ sendNotifications
1640
+ });
1641
+ //# sourceMappingURL=index.cjs.map