@codepulse-oss/core 3.1.4 → 3.1.6

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.
Files changed (51) hide show
  1. package/dist/__tests__/v3.1.5-power.test.d.ts +2 -0
  2. package/dist/__tests__/v3.1.5-power.test.d.ts.map +1 -0
  3. package/dist/__tests__/v3.1.5-power.test.js +168 -0
  4. package/dist/__tests__/v3.1.5-power.test.js.map +1 -0
  5. package/dist/__tests__/v3.1.6-telemetry-crash.test.d.ts +2 -0
  6. package/dist/__tests__/v3.1.6-telemetry-crash.test.d.ts.map +1 -0
  7. package/dist/__tests__/v3.1.6-telemetry-crash.test.js +90 -0
  8. package/dist/__tests__/v3.1.6-telemetry-crash.test.js.map +1 -0
  9. package/dist/audit/explain-simple.d.ts +21 -0
  10. package/dist/audit/explain-simple.d.ts.map +1 -0
  11. package/dist/audit/explain-simple.js +91 -0
  12. package/dist/audit/explain-simple.js.map +1 -0
  13. package/dist/audit/ignore-manager.d.ts +10 -0
  14. package/dist/audit/ignore-manager.d.ts.map +1 -0
  15. package/dist/audit/ignore-manager.js +86 -0
  16. package/dist/audit/ignore-manager.js.map +1 -0
  17. package/dist/audit/live-accessibility.d.ts +101 -3
  18. package/dist/audit/live-accessibility.d.ts.map +1 -1
  19. package/dist/audit/live-accessibility.js +764 -257
  20. package/dist/audit/live-accessibility.js.map +1 -1
  21. package/dist/audit/seo-geo-scanner.d.ts +12 -0
  22. package/dist/audit/seo-geo-scanner.d.ts.map +1 -1
  23. package/dist/audit/seo-geo-scanner.js +150 -0
  24. package/dist/audit/seo-geo-scanner.js.map +1 -1
  25. package/dist/db/database.d.ts +93 -0
  26. package/dist/db/database.d.ts.map +1 -1
  27. package/dist/db/database.js +223 -0
  28. package/dist/db/database.js.map +1 -1
  29. package/dist/db/schema.d.ts +1 -1
  30. package/dist/db/schema.d.ts.map +1 -1
  31. package/dist/db/schema.js +31 -0
  32. package/dist/db/schema.js.map +1 -1
  33. package/dist/index.d.ts +4 -0
  34. package/dist/index.d.ts.map +1 -1
  35. package/dist/index.js +4 -0
  36. package/dist/index.js.map +1 -1
  37. package/dist/output/html-report-writer.d.ts +38 -0
  38. package/dist/output/html-report-writer.d.ts.map +1 -0
  39. package/dist/output/html-report-writer.js +150 -0
  40. package/dist/output/html-report-writer.js.map +1 -0
  41. package/dist/output/sarif-writer.js +1 -1
  42. package/dist/sast/sbom-generator.js +2 -2
  43. package/dist/telemetry/crash-reporter.d.ts +48 -0
  44. package/dist/telemetry/crash-reporter.d.ts.map +1 -0
  45. package/dist/telemetry/crash-reporter.js +158 -0
  46. package/dist/telemetry/crash-reporter.js.map +1 -0
  47. package/dist/telemetry/optin-telemetry.d.ts +62 -2
  48. package/dist/telemetry/optin-telemetry.d.ts.map +1 -1
  49. package/dist/telemetry/optin-telemetry.js +95 -11
  50. package/dist/telemetry/optin-telemetry.js.map +1 -1
  51. package/package.json +1 -1
@@ -4,6 +4,209 @@ import { createRequire } from 'node:module';
4
4
  import path from 'node:path';
5
5
  import { mapSeverityToTier } from '../types/review.js';
6
6
  import { maskSecrets } from '../utils/platform.js';
7
+ const LIVE_AI_BOTS = [
8
+ 'GPTBot',
9
+ 'OAI-SearchBot',
10
+ 'ChatGPT-User',
11
+ 'ClaudeBot',
12
+ 'PerplexityBot',
13
+ 'Google-Extended',
14
+ 'CCBot',
15
+ 'Applebot-Extended'
16
+ ];
17
+ /**
18
+ * Strictly validates URLs for Live Audit + Page Vitals (`http`/`https` only; blocks cloud metadata SSRF IPs).
19
+ * Explicitly permits `localhost` / `127.0.0.1` for local dev server verification.
20
+ */
21
+ export function validateSafeLiveAuditUrl(rawUrl) {
22
+ let parsed;
23
+ try {
24
+ parsed = new URL(String(rawUrl || '').trim());
25
+ }
26
+ catch {
27
+ throw new Error('Invalid website URL. Provide a full http:// or https:// URL.');
28
+ }
29
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
30
+ throw new Error(`Unsupported live URL protocol "${parsed.protocol}". Only http: and https: are allowed.`);
31
+ }
32
+ if (parsed.username || parsed.password) {
33
+ throw new Error('URL credentials (user:pass@) are blocked for security.');
34
+ }
35
+ const host = parsed.hostname.toLowerCase().replace(/^\[|\]$/g, '');
36
+ if (!host ||
37
+ host === '169.254.169.254' ||
38
+ host.startsWith('169.254.') ||
39
+ host === 'metadata.google.internal' ||
40
+ host === 'metadata.azure.internal' ||
41
+ host === '100.100.100.200' ||
42
+ host === '0.0.0.0' ||
43
+ host === '::' ||
44
+ host.startsWith('fe80:')) {
45
+ throw new Error(`Blocked internal/cloud metadata host "${host}" for SSRF safety.`);
46
+ }
47
+ return parsed;
48
+ }
49
+ function rateMetric(val, goodMax, needsMax) {
50
+ if (val === null || !Number.isFinite(val))
51
+ return 'good';
52
+ if (val <= goodMax)
53
+ return 'good';
54
+ if (val <= needsMax)
55
+ return 'needs-improvement';
56
+ return 'poor';
57
+ }
58
+ function computeVitalsScore(m) {
59
+ let score = 100;
60
+ if (m.lcpMs !== null) {
61
+ if (m.lcpMs > 4000)
62
+ score -= 30;
63
+ else if (m.lcpMs > 2500)
64
+ score -= 14;
65
+ }
66
+ if (m.clsScore !== null) {
67
+ if (m.clsScore > 0.25)
68
+ score -= 24;
69
+ else if (m.clsScore > 0.1)
70
+ score -= 10;
71
+ }
72
+ if (m.inpOrTbtMs !== null) {
73
+ if (m.inpOrTbtMs > 500)
74
+ score -= 22;
75
+ else if (m.inpOrTbtMs > 200)
76
+ score -= 10;
77
+ }
78
+ if (m.fcpMs !== null && m.fcpMs > 3000)
79
+ score -= 12;
80
+ else if (m.fcpMs !== null && m.fcpMs > 1800)
81
+ score -= 5;
82
+ if (m.ttfbMs !== null && m.ttfbMs > 1800)
83
+ score -= 12;
84
+ else if (m.ttfbMs !== null && m.ttfbMs > 800)
85
+ score -= 5;
86
+ return Math.max(0, Math.min(100, score));
87
+ }
88
+ function parseAiBotMatrix(robotsText) {
89
+ const blocks = [];
90
+ let activeAgent = '';
91
+ let disallowAll = false;
92
+ let allowRoot = false;
93
+ const flush = () => {
94
+ if (activeAgent)
95
+ blocks.push({ agent: activeAgent, disallowAll, allowRoot });
96
+ disallowAll = false;
97
+ allowRoot = false;
98
+ };
99
+ for (const rawLine of robotsText.split(/\r?\n/)) {
100
+ const line = rawLine.split('#')[0]?.trim() || '';
101
+ if (!line)
102
+ continue;
103
+ const ua = /^User-agent:\s*(.+)$/i.exec(line);
104
+ if (ua?.[1]) {
105
+ flush();
106
+ activeAgent = ua[1].trim();
107
+ continue;
108
+ }
109
+ if (/^Disallow:\s*\/\s*$/i.test(line))
110
+ disallowAll = true;
111
+ if (/^Allow:\s*\/\s*$/i.test(line))
112
+ allowRoot = true;
113
+ }
114
+ flush();
115
+ const wildcard = blocks.find((b) => b.agent === '*');
116
+ return LIVE_AI_BOTS.map((bot) => {
117
+ const specific = blocks.find((b) => b.agent.toLowerCase() === bot.toLowerCase());
118
+ if (specific) {
119
+ return { bot, status: specific.disallowAll && !specific.allowRoot ? 'Blocked' : 'Allowed' };
120
+ }
121
+ if (wildcard?.disallowAll && !wildcard.allowRoot) {
122
+ return { bot, status: 'Blocked' };
123
+ }
124
+ return { bot, status: robotsText ? 'Default' : 'Default' };
125
+ });
126
+ }
127
+ function stripHtmlToPlainText(html) {
128
+ return html
129
+ .replace(/<script[\s\S]*?<\/script>/gi, ' ')
130
+ .replace(/<style[\s\S]*?<\/style>/gi, ' ')
131
+ .replace(/<noscript[\s\S]*?<\/noscript>/gi, ' ')
132
+ .replace(/<[^>]+>/g, ' ')
133
+ .replace(/\s+/g, ' ')
134
+ .trim();
135
+ }
136
+ function parseRawHtmlFallback(rawHtml, pageUrl) {
137
+ const title = (/<title[^>]*>([\s\S]*?)<\/title>/i.exec(rawHtml)?.[1] || '').replace(/\s+/g, ' ').trim();
138
+ const getMeta = (attr, val) => {
139
+ const re = new RegExp(`<meta[^>]+${attr}=["']${val}["'][^>]*content=["']([^"']*)["']`, 'i');
140
+ const reRev = new RegExp(`<meta[^>]+content=["']([^"']*)["'][^>]*${attr}=["']${val}["']`, 'i');
141
+ return (re.exec(rawHtml)?.[1] || reRev.exec(rawHtml)?.[1] || '').trim();
142
+ };
143
+ const metaDesc = getMeta('name', 'description');
144
+ const canonical = (/<link[^>]+rel=["']canonical["'][^>]*href=["']([^"']*)["']/i.exec(rawHtml)?.[1] || '').trim();
145
+ const lang = (/<html[^>]+lang=["']([^"']+)["']/i.exec(rawHtml)?.[1] || '').trim();
146
+ const h1Count = (rawHtml.match(/<h1\b/gi) || []).length;
147
+ const headingTree = Array.from(rawHtml.matchAll(/<h([1-6])\b[^>]*>([\s\S]*?)<\/h\1>/gi))
148
+ .slice(0, 20)
149
+ .map((m) => ({
150
+ level: Number(m[1] || 1),
151
+ text: stripHtmlToPlainText(m[2] || '').slice(0, 80)
152
+ }));
153
+ const hreflangs = Array.from(rawHtml.matchAll(/<link[^>]+rel=["']alternate["'][^>]*hreflang=["']([^"']+)["'][^>]*href=["']([^"']+)["']/gi)).map((m) => ({ lang: m[1] || '', href: m[2] || '' }));
154
+ const ldScripts = Array.from(rawHtml.matchAll(/<script[^>]+type=["']application\/ld\+json["'][^>]*>([\s\S]*?)<\/script>/gi));
155
+ const jsonLdTypes = [];
156
+ for (const s of ldScripts) {
157
+ try {
158
+ const parsed = JSON.parse((s[1] || '').trim());
159
+ if (parsed['@type'])
160
+ jsonLdTypes.push(parsed['@type']);
161
+ if (Array.isArray(parsed['@graph'])) {
162
+ for (const item of parsed['@graph']) {
163
+ if (item['@type'])
164
+ jsonLdTypes.push(item['@type']);
165
+ }
166
+ }
167
+ }
168
+ catch {
169
+ // ignore invalid ld+json
170
+ }
171
+ }
172
+ const internalLinks = Array.from(rawHtml.matchAll(/<a[^>]+href=["']([^"'#]+)["']/gi))
173
+ .map((m) => m[1] || '')
174
+ .filter((h) => h && !h.startsWith('mailto:') && !h.startsWith('javascript:'))
175
+ .slice(0, 15);
176
+ const imgsWithoutAlt = Array.from(rawHtml.matchAll(/<img\b([^>]*)>/gi)).filter((m) => !/\balt\s*=/i.test(m[1] || '') && !/aria-hidden=["']true["']/i.test(m[1] || '')).length;
177
+ const unnamedButtons = Array.from(rawHtml.matchAll(/<button\b([^>]*)>([\s\S]*?)<\/button>/gi)).filter((m) => {
178
+ const attrs = m[1] || '';
179
+ const inner = stripHtmlToPlainText(m[2] || '');
180
+ const hasAria = /\b(?:aria-label|title)\s*=\s*["'][^"']+["']/i.test(attrs);
181
+ return !inner && !hasAria;
182
+ }).length;
183
+ const bodyTextLen = stripHtmlToPlainText(rawHtml).length;
184
+ return {
185
+ title,
186
+ metaDesc,
187
+ canonical,
188
+ lang,
189
+ h1Count,
190
+ headingTree,
191
+ hreflangs,
192
+ jsonLdCount: ldScripts.length,
193
+ jsonLdTypes,
194
+ bodyTextLen,
195
+ domNodeCount: (rawHtml.match(/<[a-zA-Z][a-zA-Z0-9-]*/g) || []).length,
196
+ imgsWithoutAlt,
197
+ unnamedButtons,
198
+ unlabeledInputs: 0,
199
+ hasMainLandmark: /<main\b|role=["']main["']/i.test(rawHtml),
200
+ socialCard: {
201
+ ogTitle: getMeta('property', 'og:title') || title,
202
+ ogDescription: getMeta('property', 'og:description') || metaDesc,
203
+ ogImage: getMeta('property', 'og:image'),
204
+ twitterCard: getMeta('name', 'twitter:card')
205
+ },
206
+ internalLinks,
207
+ url: pageUrl
208
+ };
209
+ }
7
210
  async function resolvePlaywright() {
8
211
  const dynamicImport = (name) => import(/* @vite-ignore */ name);
9
212
  try {
@@ -12,7 +215,7 @@ async function resolvePlaywright() {
12
215
  return mod;
13
216
  }
14
217
  catch {
15
- // try @playwright/test or cwd require fallback
218
+ // fallback
16
219
  }
17
220
  try {
18
221
  const mod = (await dynamicImport('@playwright/test'));
@@ -82,63 +285,103 @@ function makeLiveHit(input) {
82
285
  return { finding, diag };
83
286
  }
84
287
  /**
85
- * Live headless browser runtime auditor for WCAG 2.1 AA accessibility + hydrated DOM SEO/GEO checks.
86
- * Uses Playwright when installed (`MIT`/`Apache-2.0`), runs pure-TypeScript WCAG DOM checks cleanly,
87
- * and optionally leverages user-installed `axe-core` when present in the target workspace without bundling MPL deps.
288
+ * Dual-Engine Live Website URL, Technical SEO, GEO AI Visibility & Core Web Vitals (Desktop + Mobile) Auditor.
88
289
  */
89
290
  export async function runLiveRuntimeAccessibilityAndSeoAudit(options) {
90
- const parsedUrl = new URL(options.url);
91
- if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') {
92
- throw new Error(`Unsupported live URL protocol "${parsedUrl.protocol}". Only http: and https: are allowed.`);
93
- }
94
- const pw = await resolvePlaywright();
95
- if (!pw?.chromium?.launch) {
96
- const missing = makeLiveHit({
97
- ruleId: 'CP-LIVE-PLAYWRIGHT',
98
- category: 'reliability',
99
- severity: 'low',
100
- url: options.url,
101
- title: 'Playwright browser runtime is not available in this environment',
102
- body: 'Install Playwright (`npm i -D playwright` and `npx playwright install chromium`) to run live hydrated WCAG 2.1 AA & SEO/GEO browser audits.',
103
- rec: 'Install Playwright Chromium in devDependencies or run from a Playwright-enabled CI runner.'
104
- });
105
- return {
106
- url: options.url,
107
- reachable: false,
108
- hydratedTitle: '',
109
- metaDescription: '',
110
- jsonLdCount: 0,
111
- ssrTextLength: 0,
112
- consoleErrors: [],
113
- networkErrors: [],
114
- axeUsed: false,
115
- findings: [missing.finding],
116
- diagnostics: [missing.diag],
117
- a11yScore: 0,
118
- liveSeoScore: 0
119
- };
120
- }
291
+ const parsedUrl = validateSafeLiveAuditUrl(options.url);
292
+ const timeoutMs = options.timeoutMs ?? 20_000;
121
293
  const consoleErrors = [];
122
294
  const networkErrors = [];
123
295
  const findings = [];
124
296
  const diagnostics = [];
125
297
  let axeUsed = false;
126
- let browser = null;
298
+ const pushCheck = (cond, item) => {
299
+ if (!cond)
300
+ return;
301
+ const hit = makeLiveHit(item);
302
+ findings.push(hit.finding);
303
+ diagnostics.push(hit.diag);
304
+ };
305
+ // 1. Raw HTTP SSR + Headers + Redirects probe
306
+ const redirectChain = [];
307
+ let httpStatus = 200;
308
+ let rawHtml = '';
309
+ let headerMap = {};
310
+ let rawTtfbMs = null;
311
+ let reachable = false;
127
312
  try {
128
- browser = await pw.chromium.launch({ headless: true });
129
- const page = await browser.newPage();
130
- page.on('console', (msg) => {
131
- const m = msg;
132
- if (m.type?.() === 'error' && m.text)
133
- consoleErrors.push(maskSecrets(m.text().slice(0, 240)));
313
+ const t0 = Date.now();
314
+ const res = await fetch(parsedUrl.href, {
315
+ method: 'GET',
316
+ redirect: 'follow',
317
+ signal: AbortSignal.timeout(Math.min(12_000, timeoutMs))
134
318
  });
135
- page.on('requestfailed', (req) => {
136
- const r = req;
137
- networkErrors.push(`${r.url?.() ?? 'asset'}: ${r.failure?.()?.errorText ?? 'failed'}`);
319
+ rawTtfbMs = Date.now() - t0;
320
+ httpStatus = res.status;
321
+ reachable = res.status > 0 && res.status < 600;
322
+ if (res.url && res.url !== parsedUrl.href) {
323
+ validateSafeLiveAuditUrl(res.url);
324
+ redirectChain.push({ url: parsedUrl.href, status: 301 }, { url: res.url, status: res.status });
325
+ }
326
+ res.headers.forEach((v, k) => {
327
+ headerMap[k.toLowerCase()] = v;
138
328
  });
139
- await page.goto(options.url, { waitUntil: 'networkidle', timeout: options.timeoutMs ?? 20_000 });
140
- const domAudit = await page.evaluate(() => {
141
- // Runs inside Chromium browser context
329
+ rawHtml = await res.text();
330
+ }
331
+ catch (err) {
332
+ networkErrors.push(err.message);
333
+ }
334
+ const ssrParsed = parseRawHtmlFallback(rawHtml, parsedUrl.href);
335
+ const ssrHtmlTextLength = ssrParsed.bodyTextLen;
336
+ // 2. Parallel /robots.txt, /sitemap.xml, /llms.txt, /llms-full.txt live probes
337
+ const origin = parsedUrl.origin;
338
+ const fetchOptionalText = async (rel) => {
339
+ try {
340
+ const r = await fetch(`${origin}${rel}`, { signal: AbortSignal.timeout(4500) });
341
+ if (!r.ok)
342
+ return { ok: false, text: '' };
343
+ return { ok: true, text: await r.text() };
344
+ }
345
+ catch {
346
+ return { ok: false, text: '' };
347
+ }
348
+ };
349
+ const [robotsRes, sitemapRes, llmsRes, llmsFullRes] = await Promise.all([
350
+ fetchOptionalText('/robots.txt'),
351
+ fetchOptionalText('/sitemap.xml'),
352
+ fetchOptionalText('/llms.txt'),
353
+ fetchOptionalText('/llms-full.txt')
354
+ ]);
355
+ const aiBotMatrix = parseAiBotMatrix(robotsRes.text);
356
+ const sitemapLocMatches = Array.from(sitemapRes.text.matchAll(/<loc>\s*([^<\s]+)\s*<\/loc>/gi)).map((m) => m[1] || '');
357
+ const validSitemapXml = sitemapRes.ok && (/<urlset\b/i.test(sitemapRes.text) || /<sitemapindex\b/i.test(sitemapRes.text));
358
+ const sampledPages = [];
359
+ if (options.crawlSitemap && sitemapLocMatches.length > 0) {
360
+ for (const loc of sitemapLocMatches.slice(0, 5)) {
361
+ try {
362
+ const subUrl = validateSafeLiveAuditUrl(loc);
363
+ if (subUrl.origin !== origin)
364
+ continue;
365
+ const tStart = Date.now();
366
+ const r = await fetch(subUrl.href, { signal: AbortSignal.timeout(4500) });
367
+ const html = r.ok ? await r.text() : '';
368
+ const t = (/<title[^>]*>([^<]*)<\/title>/i.exec(html)?.[1] || '').trim();
369
+ sampledPages.push({ url: subUrl.pathname || '/', status: r.status, title: t || '(no title)', loadMs: Date.now() - tStart });
370
+ }
371
+ catch {
372
+ sampledPages.push({ url: loc, status: 0, title: 'Timeout / Error', loadMs: 0 });
373
+ }
374
+ }
375
+ }
376
+ // 3. Headless Playwright Dual Emulation (Desktop 1440x900 + Mobile 390x844) + Core Web Vitals
377
+ let desktopVitals;
378
+ let mobileVitals;
379
+ let domAudit = ssrParsed;
380
+ const collectViewportMetrics = async (page, viewport, compHdr, ccHdr) => {
381
+ const t0 = Date.now();
382
+ await page.goto(parsedUrl.href, { waitUntil: 'networkidle', timeout: timeoutMs });
383
+ const navElapsed = Date.now() - t0;
384
+ return page.evaluate(() => {
142
385
  const g = globalThis;
143
386
  const doc = g.document;
144
387
  const esc = (v) => (g.CSS?.escape ? g.CSS.escape(v) : v.replace(/"/g, '\\"'));
@@ -147,9 +390,37 @@ export async function runLiveRuntimeAccessibilityAndSeoAudit(options) {
147
390
  const canonical = doc.querySelector('link[rel="canonical"]')?.getAttribute('href')?.trim() ?? '';
148
391
  const lang = doc.documentElement.getAttribute('lang')?.trim() ?? '';
149
392
  const h1Count = doc.querySelectorAll('h1').length;
150
- const jsonLdCount = doc.querySelectorAll('script[type="application/ld+json"]').length;
393
+ const jsonLdEls = Array.from(doc.querySelectorAll('script[type="application/ld+json"]'));
394
+ const jsonLdTypes = [];
395
+ for (const el of jsonLdEls) {
396
+ try {
397
+ const obj = JSON.parse((el.textContent || '').trim());
398
+ if (obj['@type'])
399
+ jsonLdTypes.push(obj['@type']);
400
+ if (Array.isArray(obj['@graph'])) {
401
+ for (const x of obj['@graph'])
402
+ if (x['@type'])
403
+ jsonLdTypes.push(x['@type']);
404
+ }
405
+ }
406
+ catch {
407
+ // ignore
408
+ }
409
+ }
410
+ const headingTree = Array.from(doc.querySelectorAll('h1,h2,h3,h4'))
411
+ .slice(0, 20)
412
+ .map((h) => ({
413
+ level: Number(String(h.tagName || 'H1').replace(/\D/g, '') || 1),
414
+ text: String(h.textContent || '').trim().slice(0, 80)
415
+ }));
416
+ const hreflangs = Array.from(doc.querySelectorAll('link[rel="alternate"][hreflang]')).map((el) => ({
417
+ lang: String(el.getAttribute('hreflang') || ''),
418
+ href: String(el.getAttribute('href') || '')
419
+ }));
151
420
  const bodyTextLen = (doc.body?.innerText ?? '').trim().length;
152
- const imgsWithoutAlt = Array.from(doc.querySelectorAll('img')).filter((img) => img.getAttribute('alt') === null && img.getAttribute('aria-hidden') !== 'true').length;
421
+ const imgs = Array.from(doc.querySelectorAll('img'));
422
+ const imgsWithoutAlt = imgs.filter((img) => img.getAttribute('alt') === null && img.getAttribute('aria-hidden') !== 'true').length;
423
+ const oversizedImagesCount = imgs.filter((img) => (img.naturalWidth || 0) > 0 && (img.clientWidth || 0) > 0 && (img.naturalWidth || 0) > (img.clientWidth || 1) * 2).length;
153
424
  const unnamedButtons = Array.from(doc.querySelectorAll('button, [role="button"]')).filter((btn) => {
154
425
  const text = (btn.textContent ?? '').trim();
155
426
  const aria = (btn.getAttribute('aria-label') ?? btn.getAttribute('title') ?? '').trim();
@@ -164,78 +435,207 @@ export async function runLiveRuntimeAccessibilityAndSeoAudit(options) {
164
435
  }).length;
165
436
  const hasMainLandmark = Boolean(doc.querySelector('main, [role="main"]'));
166
437
  const domNodeCount = doc.querySelectorAll('*').length;
438
+ const renderBlockingCount = doc.querySelectorAll('head script:not([async]):not([defer]):not([type="module"]):not([type="application/ld+json"])').length +
439
+ doc.querySelectorAll('head link[rel="stylesheet"]:not([media="print"])').length;
167
440
  const internalLinks = Array.from(doc.querySelectorAll('a[href]'))
168
441
  .map((a) => String(a.getAttribute('href') || '').trim())
169
442
  .filter((h) => h && !h.startsWith('#') && !h.startsWith('mailto:') && !h.startsWith('javascript:'))
170
443
  .slice(0, 20);
171
- let lcpMs = null;
172
- let clsScore = null;
173
- try {
174
- const perf = g.performance;
175
- if (perf?.getEntriesByType) {
176
- const lcpEntries = perf.getEntriesByType('largest-contentful-paint');
177
- if (lcpEntries.length > 0) {
178
- lcpMs = Math.round(Number(lcpEntries[lcpEntries.length - 1]?.startTime ?? 0));
179
- }
180
- const shiftEntries = perf.getEntriesByType('layout-shift');
181
- if (shiftEntries.length > 0) {
182
- clsScore = Number(shiftEntries
183
- .filter((e) => !e.hadRecentInput)
184
- .reduce((acc, e) => acc + Number(e.value ?? 0), 0)
185
- .toFixed(3));
186
- }
444
+ let maxDomDepth = 0;
445
+ const allEls = Array.from(doc.querySelectorAll('*')).slice(0, 400);
446
+ for (const el of allEls) {
447
+ let d = 0;
448
+ let cur = el;
449
+ while (cur?.parentElement && d < 40) {
450
+ d++;
451
+ cur = cur.parentElement;
187
452
  }
453
+ if (d > maxDomDepth)
454
+ maxDomDepth = d;
188
455
  }
189
- catch {
190
- // Optional PerformanceTimeline
456
+ let lcpMs = null;
457
+ let lcpElement = '';
458
+ let lcpUrl = '';
459
+ let clsScore = 0;
460
+ let fcpMs = null;
461
+ let ttfbMs = null;
462
+ let inpOrTbtMs = 0;
463
+ let jsBytes = 0;
464
+ let cssBytes = 0;
465
+ let imgBytes = 0;
466
+ let fontBytes = 0;
467
+ let htmlBytes = 0;
468
+ const perf = g.performance;
469
+ if (perf?.getEntriesByType) {
470
+ const lcpEntries = perf.getEntriesByType('largest-contentful-paint');
471
+ if (lcpEntries.length > 0) {
472
+ const lastLcp = lcpEntries[lcpEntries.length - 1];
473
+ lcpMs = Math.round(Number(lastLcp.startTime ?? 0));
474
+ lcpElement = lastLcp.element?.tagName ? `${lastLcp.element.tagName}${lastLcp.element.id ? `#${lastLcp.element.id}` : ''}` : '';
475
+ lcpUrl = String(lastLcp.url || lastLcp.element?.src || '');
476
+ }
477
+ const shiftEntries = perf.getEntriesByType('layout-shift');
478
+ clsScore = Number(shiftEntries
479
+ .filter((e) => !e.hadRecentInput)
480
+ .reduce((acc, e) => acc + Number(e.value ?? 0), 0)
481
+ .toFixed(3));
482
+ const paints = perf.getEntriesByType('paint');
483
+ const fcp = paints.find((p) => p.name === 'first-contentful-paint');
484
+ if (fcp)
485
+ fcpMs = Math.round(Number(fcp.startTime ?? 0));
486
+ const navs = perf.getEntriesByType('navigation');
487
+ if (navs[0]) {
488
+ const n = navs[0];
489
+ ttfbMs = Math.max(0, Math.round(Number((n.responseStart ?? 0) - (n.requestStart ?? 0))));
490
+ htmlBytes = Number(n.transferSize ?? 0);
491
+ }
492
+ const longTasks = perf.getEntriesByType('longtask');
493
+ inpOrTbtMs = Math.round(longTasks.reduce((sum, lt) => sum + Math.max(0, Number(lt.duration ?? 0) - 50), 0));
494
+ for (const r of perf.getEntriesByType('resource')) {
495
+ const sz = Number(r.transferSize ?? 0);
496
+ const nm = String(r.name || '').toLowerCase();
497
+ if (r.initiatorType === 'script' || /\.m?js(\?|$)/.test(nm))
498
+ jsBytes += sz;
499
+ else if (r.initiatorType === 'css' || r.initiatorType === 'link' || /\.css(\?|$)/.test(nm))
500
+ cssBytes += sz;
501
+ else if (r.initiatorType === 'img' || /\.(png|jpe?g|webp|avif|gif|svg)(\?|$)/.test(nm))
502
+ imgBytes += sz;
503
+ else if (/\.woff2?|ttf|otf(\?|$)/.test(nm))
504
+ fontBytes += sz;
505
+ }
191
506
  }
507
+ const ogTitle = doc.querySelector('meta[property="og:title"]')?.getAttribute('content')?.trim() || title;
508
+ const ogDesc = doc.querySelector('meta[property="og:description"]')?.getAttribute('content')?.trim() || metaDesc;
509
+ const ogImg = doc.querySelector('meta[property="og:image"]')?.getAttribute('content')?.trim() || '';
510
+ const twCard = doc.querySelector('meta[name="twitter:card"]')?.getAttribute('content')?.trim() || '';
192
511
  return {
193
512
  title,
194
513
  metaDesc,
195
514
  canonical,
196
515
  lang,
197
516
  h1Count,
198
- jsonLdCount,
517
+ headingTree,
518
+ hreflangs,
519
+ jsonLdCount: jsonLdEls.length,
520
+ jsonLdTypes,
199
521
  bodyTextLen,
200
522
  domNodeCount,
523
+ maxDomDepth,
524
+ renderBlockingCount,
525
+ oversizedImagesCount,
201
526
  lcpMs,
527
+ lcpElement,
528
+ lcpUrl,
202
529
  clsScore,
530
+ inpOrTbtMs,
531
+ fcpMs,
532
+ ttfbMs,
533
+ payload: {
534
+ totalKb: Math.round((htmlBytes + jsBytes + cssBytes + imgBytes + fontBytes) / 1024),
535
+ jsKb: Math.round(jsBytes / 1024),
536
+ cssKb: Math.round(cssBytes / 1024),
537
+ imagesKb: Math.round(imgBytes / 1024),
538
+ fontsKb: Math.round(fontBytes / 1024),
539
+ htmlKb: Math.round(htmlBytes / 1024)
540
+ },
541
+ socialCard: { ogTitle, ogDescription: ogDesc, ogImage: ogImg, twitterCard: twCard },
203
542
  internalLinks,
204
543
  imgsWithoutAlt,
205
544
  unnamedButtons,
206
545
  unlabeledInputs,
207
546
  hasMainLandmark
208
547
  };
209
- });
210
- // Probe up to 15 same-origin internal links for broken 4xx/5xx targets
211
- const brokenInternalLinks = [];
212
- const checkedHrefSet = new Set();
213
- for (const rawHref of domAudit.internalLinks || []) {
214
- try {
215
- const resolved = new URL(rawHref, options.url);
216
- if (resolved.origin !== parsedUrl.origin || checkedHrefSet.has(resolved.href))
217
- continue;
218
- checkedHrefSet.add(resolved.href);
219
- const linkRes = await fetch(resolved.href, { method: 'HEAD', signal: AbortSignal.timeout(2500) });
220
- if (linkRes.status >= 400) {
221
- brokenInternalLinks.push({ url: resolved.pathname, status: linkRes.status });
222
- }
223
- if (checkedHrefSet.size >= 15)
224
- break;
225
- }
226
- catch {
227
- // Ignore transient timeout during link check
548
+ }).then((d) => ({
549
+ dom: d,
550
+ vitals: {
551
+ viewport,
552
+ lcpMs: d.lcpMs ?? navElapsed,
553
+ lcpRating: rateMetric(d.lcpMs ?? navElapsed, 2500, 4000),
554
+ lcpElement: d.lcpElement,
555
+ lcpUrl: d.lcpUrl,
556
+ clsScore: d.clsScore ?? 0,
557
+ clsRating: rateMetric(d.clsScore ?? 0, 0.1, 0.25),
558
+ inpOrTbtMs: d.inpOrTbtMs ?? 0,
559
+ inpRating: rateMetric(d.inpOrTbtMs ?? 0, 200, 500),
560
+ fcpMs: d.fcpMs ?? Math.round(navElapsed * 0.6),
561
+ fcpRating: rateMetric(d.fcpMs ?? Math.round(navElapsed * 0.6), 1800, 3000),
562
+ ttfbMs: d.ttfbMs ?? rawTtfbMs,
563
+ ttfbRating: rateMetric(d.ttfbMs ?? rawTtfbMs, 800, 1800),
564
+ vitalsScore: computeVitalsScore({
565
+ lcpMs: d.lcpMs ?? navElapsed,
566
+ clsScore: d.clsScore ?? 0,
567
+ inpOrTbtMs: d.inpOrTbtMs ?? 0,
568
+ fcpMs: d.fcpMs ?? Math.round(navElapsed * 0.6),
569
+ ttfbMs: d.ttfbMs ?? rawTtfbMs
570
+ }),
571
+ domNodeCount: d.domNodeCount,
572
+ maxDomDepth: d.maxDomDepth,
573
+ renderBlockingCount: d.renderBlockingCount,
574
+ oversizedImagesCount: d.oversizedImagesCount,
575
+ payload: d.payload,
576
+ compressionHeader: compHdr || 'none',
577
+ cacheControlHeader: ccHdr || 'not-set'
228
578
  }
229
- }
230
- // Optional user-installed axe-core enhancement (never bundled in CodePulse)
231
- const userAxePath = resolveOptionalUserAxeScript();
232
- if (userAxePath) {
233
- try {
234
- const axeSource = await fs.readFile(userAxePath, 'utf8');
235
- const pageAny = page;
236
- if (typeof pageAny.addScriptTag === 'function') {
237
- await pageAny.addScriptTag({ content: axeSource });
238
- const axeViolations = await page.evaluate(async () => {
579
+ }));
580
+ };
581
+ const pw = await resolvePlaywright();
582
+ const compHdr = headerMap['content-encoding'] || '';
583
+ const ccHdr = headerMap['cache-control'] || '';
584
+ const htmlKb = Math.round(Buffer.byteLength(rawHtml, 'utf8') / 1024);
585
+ const makeHttpVitals = (vp) => {
586
+ const estTtfb = rawTtfbMs ?? 120;
587
+ const mult = vp === 'mobile' ? 1.35 : 1;
588
+ const estLcp = Math.round(estTtfb * 1.8 * mult);
589
+ return {
590
+ viewport: vp,
591
+ lcpMs: estLcp,
592
+ lcpRating: rateMetric(estLcp, 2500, 4000),
593
+ lcpElement: '',
594
+ lcpUrl: '',
595
+ clsScore: 0,
596
+ clsRating: 'good',
597
+ inpOrTbtMs: 0,
598
+ inpRating: 'good',
599
+ fcpMs: Math.round(estTtfb * 1.2 * mult),
600
+ fcpRating: rateMetric(Math.round(estTtfb * 1.2 * mult), 1800, 3000),
601
+ ttfbMs: estTtfb,
602
+ ttfbRating: rateMetric(estTtfb, 800, 1800),
603
+ vitalsScore: computeVitalsScore({ lcpMs: estLcp, clsScore: 0, inpOrTbtMs: 0, fcpMs: estTtfb, ttfbMs: estTtfb }),
604
+ domNodeCount: domAudit.domNodeCount,
605
+ maxDomDepth: 8,
606
+ renderBlockingCount: 0,
607
+ oversizedImagesCount: 0,
608
+ payload: { totalKb: htmlKb, jsKb: 0, cssKb: 0, imagesKb: 0, fontsKb: 0, htmlKb },
609
+ compressionHeader: compHdr || 'none',
610
+ cacheControlHeader: ccHdr || 'not-set'
611
+ };
612
+ };
613
+ if (pw?.chromium?.launch) {
614
+ let browser = null;
615
+ try {
616
+ browser = await pw.chromium.launch({ headless: true });
617
+ const desktopPage = await browser.newPage();
618
+ await desktopPage.setViewportSize?.({ width: 1440, height: 900 });
619
+ desktopPage.on('console', (msg) => {
620
+ const m = msg;
621
+ if (m.type?.() === 'error' && m.text)
622
+ consoleErrors.push(maskSecrets(m.text().slice(0, 240)));
623
+ });
624
+ desktopPage.on('requestfailed', (req) => {
625
+ const r = req;
626
+ networkErrors.push(`${r.url?.() ?? 'asset'}: ${r.failure?.()?.errorText ?? 'failed'}`);
627
+ });
628
+ const dRes = await collectViewportMetrics(desktopPage, 'desktop', compHdr, ccHdr);
629
+ desktopVitals = dRes.vitals;
630
+ domAudit = { ...dRes.dom, url: parsedUrl.href };
631
+ reachable = true;
632
+ // Optional user-installed axe-core enhancement
633
+ const userAxePath = resolveOptionalUserAxeScript();
634
+ if (userAxePath && typeof desktopPage.addScriptTag === 'function') {
635
+ try {
636
+ const axeSource = await fs.readFile(userAxePath, 'utf8');
637
+ await desktopPage.addScriptTag({ content: axeSource });
638
+ const axeViolations = await desktopPage.evaluate(async () => {
239
639
  const win = globalThis;
240
640
  if (!win.axe)
241
641
  return [];
@@ -265,168 +665,275 @@ export async function runLiveRuntimeAccessibilityAndSeoAudit(options) {
265
665
  diagnostics.push(hit.diag);
266
666
  }
267
667
  }
668
+ catch {
669
+ // Graceful fallback
670
+ }
268
671
  }
269
- catch {
270
- // Fallback smoothly to built-in WCAG checks
271
- }
672
+ await desktopPage.close();
673
+ const mobilePage = await browser.newPage();
674
+ await mobilePage.setViewportSize?.({ width: 390, height: 844 });
675
+ const mRes = await collectViewportMetrics(mobilePage, 'mobile', compHdr, ccHdr);
676
+ mobileVitals = mRes.vitals;
677
+ await mobilePage.close();
678
+ }
679
+ catch (err) {
680
+ networkErrors.push(err.message);
681
+ }
682
+ finally {
683
+ await browser?.close().catch(() => undefined);
272
684
  }
273
- const pushCheck = (cond, item) => {
274
- if (!cond)
275
- return;
276
- const hit = makeLiveHit(item);
277
- findings.push(hit.finding);
278
- diagnostics.push(hit.diag);
279
- };
280
- pushCheck(!domAudit.lang, {
281
- ruleId: 'CP-A11Y-LANG',
282
- category: 'accessibility',
283
- severity: 'medium',
284
- url: options.url,
285
- title: 'Rendered HTML root missing `lang` attribute',
286
- body: 'Screen readers rely on `<html lang="...">` to select accurate pronunciation rules.',
287
- rec: 'Set `lang` dynamically (e.g., `<html lang="en">` or `<html lang="ar" dir="rtl">`).'
288
- });
289
- pushCheck(domAudit.imgsWithoutAlt > 0, {
290
- ruleId: 'CP-A11Y-IMG-ALT',
291
- category: 'accessibility',
292
- severity: 'high',
293
- url: options.url,
294
- title: `${domAudit.imgsWithoutAlt} rendered <img> element(s) missing alt text`,
295
- body: 'Images without `alt` attributes are inaccessible to screen readers and blind/low-vision users.',
296
- rec: 'Provide descriptive `alt="..."` attributes or `alt=""` + `aria-hidden="true"` for decorative icons.'
297
- });
298
- pushCheck(domAudit.unnamedButtons > 0, {
299
- ruleId: 'CP-A11Y-BUTTON-NAME',
300
- category: 'accessibility',
301
- severity: 'high',
302
- url: options.url,
303
- title: `${domAudit.unnamedButtons} interactive button(s) have no accessible label`,
304
- body: 'Icon-only buttons without text or `aria-label` announce as empty "button" to assistive tech.',
305
- rec: 'Add concise `aria-label="..."` or visible text content to every button.'
306
- });
307
- pushCheck(domAudit.unlabeledInputs > 0, {
308
- ruleId: 'CP-A11Y-FORM-LABEL',
309
- category: 'accessibility',
310
- severity: 'medium',
311
- url: options.url,
312
- title: `${domAudit.unlabeledInputs} form input(s) lack associated label or aria-label`,
313
- body: 'Form fields without programmatic labels hurt WCAG 2.1 A/AA compliance and keyboard navigation.',
314
- rec: 'Associate `<label for="...">` or `aria-label` with each form field.'
315
- });
316
- pushCheck(!domAudit.hasMainLandmark, {
317
- ruleId: 'CP-A11Y-MAIN-LANDMARK',
318
- category: 'accessibility',
319
- severity: 'low',
320
- url: options.url,
321
- title: 'Rendered document lacks a `<main>` landmark region',
322
- body: 'WCAG landmark regions let keyboard/screen-reader users skip directly to primary content.',
323
- rec: 'Wrap primary view content in a semantic `<main>` element.'
324
- });
325
- pushCheck(!domAudit.title || !domAudit.metaDesc, {
326
- ruleId: 'CP-SEO-LIVE-META',
327
- category: 'seo',
328
- severity: 'medium',
329
- url: options.url,
330
- title: 'Hydrated page missing <title> or <meta name="description">',
331
- body: `Post-JS DOM title="${domAudit.title || 'missing'}", description=${domAudit.metaDesc ? 'present' : 'missing'}.`,
332
- rec: 'Ensure SSR/hydrated HTML outputs unique descriptive <title> and <meta name="description"> tags.'
333
- });
334
- pushCheck(domAudit.h1Count !== 1, {
335
- ruleId: 'CP-SEO-LIVE-H1',
336
- category: 'seo',
337
- severity: 'low',
338
- url: options.url,
339
- title: `Rendered page has ${domAudit.h1Count} <h1> heading(s) (recommended: 1)`,
340
- body: 'Search crawlers and AI extractors rely on a single primary <h1> to identify page topic.',
341
- rec: 'Render exactly one primary `<h1>` per route.'
342
- });
343
- pushCheck(domAudit.jsonLdCount === 0, {
344
- ruleId: 'CP-GEO-LIVE-JSONLD',
345
- category: 'geo',
346
- severity: 'medium',
347
- url: options.url,
348
- title: 'No rendered JSON-LD structured data detected on live URL',
349
- body: 'AI answer engines (ChatGPT Search, Perplexity, Gemini) extract entity facts reliably from schema.org JSON-LD.',
350
- rec: 'Include a valid `<script type="application/ld+json">` schema block.'
351
- });
352
- pushCheck(consoleErrors.length > 0 || networkErrors.length > 0, {
353
- ruleId: 'CP-LIVE-RUNTIME-ERRORS',
354
- category: 'reliability',
355
- severity: 'high',
356
- url: options.url,
357
- title: `Live runtime emitted ${consoleErrors.length} console error(s) and ${networkErrors.length} failed request(s)`,
358
- body: [...consoleErrors.slice(0, 3), ...networkErrors.slice(0, 3)].join(' | ') || 'Runtime errors recorded.',
359
- rec: 'Inspect browser console/network logs and fix broken assets or unhandled frontend exceptions.'
360
- });
361
- pushCheck(brokenInternalLinks.length > 0, {
362
- ruleId: 'CP-SEO-BROKEN-LINK',
363
- category: 'seo',
364
- severity: 'high',
365
- url: options.url,
366
- title: `${brokenInternalLinks.length} broken internal link(s) returned HTTP >= 400`,
367
- body: brokenInternalLinks.map((b) => `${b.url} (${b.status})`).join(', '),
368
- rec: 'Repair or redirect broken internal `<a href>` targets.'
369
- });
370
- pushCheck(Boolean(domAudit.lcpMs && domAudit.lcpMs > 2500), {
371
- ruleId: 'CP-PERF-LIVE-LCP',
372
- category: 'performance',
373
- severity: 'medium',
374
- url: options.url,
375
- title: `Slow Largest Contentful Paint (LCP ${domAudit.lcpMs}ms > 2500ms)`,
376
- body: `Measured LCP=${domAudit.lcpMs}ms, DOM nodes=${domAudit.domNodeCount ?? 'n/a'}.`,
377
- rec: 'Preload hero assets and eliminate render-blocking bundles.'
378
- });
379
- const a11yPenalty = findings.filter((f) => f.category === 'accessibility').length * 14;
380
- const seoPenalty = findings.filter((f) => f.category === 'seo' || f.category === 'geo').length * 16;
381
- return {
382
- url: options.url,
383
- reachable: true,
384
- hydratedTitle: domAudit.title,
385
- metaDescription: domAudit.metaDesc,
386
- jsonLdCount: domAudit.jsonLdCount,
387
- ssrTextLength: domAudit.bodyTextLen,
388
- domNodeCount: domAudit.domNodeCount,
389
- lcpMs: domAudit.lcpMs,
390
- clsScore: domAudit.clsScore,
391
- brokenInternalLinks,
392
- consoleErrors,
393
- networkErrors,
394
- axeUsed,
395
- findings,
396
- diagnostics,
397
- a11yScore: Math.max(0, 100 - a11yPenalty),
398
- liveSeoScore: Math.max(0, 100 - seoPenalty)
399
- };
400
- }
401
- catch (err) {
402
- const unavailable = makeLiveHit({
403
- ruleId: 'CP-LIVE-PLAYWRIGHT',
404
- category: 'reliability',
405
- severity: 'low',
406
- url: options.url,
407
- title: 'Live browser runtime unavailable or target unreachable',
408
- body: maskSecrets(err.message || 'Failed to launch Chromium or load target URL.'),
409
- rec: 'Ensure Playwright Chromium is installed (`npx playwright install chromium`) and the target URL is reachable.'
410
- });
411
- return {
412
- url: options.url,
413
- reachable: false,
414
- hydratedTitle: '',
415
- metaDescription: '',
416
- jsonLdCount: 0,
417
- ssrTextLength: 0,
418
- consoleErrors,
419
- networkErrors,
420
- axeUsed: false,
421
- findings: [unavailable.finding],
422
- diagnostics: [unavailable.diag],
423
- a11yScore: 0,
424
- liveSeoScore: 0
425
- };
426
685
  }
427
- finally {
428
- if (browser)
429
- await browser.close();
686
+ if (!desktopVitals)
687
+ desktopVitals = makeHttpVitals('desktop');
688
+ if (!mobileVitals)
689
+ mobileVitals = makeHttpVitals('mobile');
690
+ // 4. Probe up to 15 same-origin internal links cleanly
691
+ const brokenInternalLinks = [];
692
+ const checkedHrefSet = new Set();
693
+ for (const rawHref of domAudit.internalLinks || []) {
694
+ try {
695
+ const resolved = validateSafeLiveAuditUrl(new URL(rawHref, parsedUrl.href).href);
696
+ if (resolved.origin !== origin || checkedHrefSet.has(resolved.href))
697
+ continue;
698
+ checkedHrefSet.add(resolved.href);
699
+ const linkRes = await fetch(resolved.href, { method: 'HEAD', signal: AbortSignal.timeout(2500) });
700
+ if (linkRes.status >= 400) {
701
+ brokenInternalLinks.push({ url: resolved.pathname, status: linkRes.status });
702
+ }
703
+ if (checkedHrefSet.size >= 15)
704
+ break;
705
+ }
706
+ catch {
707
+ // Ignore link timeout
708
+ }
430
709
  }
710
+ // 5. Evaluate runtime checks
711
+ const hydratedTextLength = domAudit.bodyTextLen;
712
+ const ssrVsHydratedDeltaPercent = hydratedTextLength > 0 ? Math.max(0, Math.round(((hydratedTextLength - ssrHtmlTextLength) / hydratedTextLength) * 100)) : 0;
713
+ pushCheck(!domAudit.lang, {
714
+ ruleId: 'CP-A11Y-LANG',
715
+ category: 'accessibility',
716
+ severity: 'medium',
717
+ url: options.url,
718
+ title: 'Rendered HTML root missing `lang` attribute',
719
+ body: 'Screen readers rely on `<html lang="...">` to select accurate pronunciation rules.',
720
+ rec: 'Set `lang` dynamically (e.g., `<html lang="en">` or `<html lang="ar" dir="rtl">`).'
721
+ });
722
+ pushCheck(domAudit.imgsWithoutAlt > 0, {
723
+ ruleId: 'CP-A11Y-IMG-ALT',
724
+ category: 'accessibility',
725
+ severity: 'high',
726
+ url: options.url,
727
+ title: `${domAudit.imgsWithoutAlt} rendered <img> element(s) missing alt text`,
728
+ body: 'Images without `alt` attributes are inaccessible to screen readers and image crawlers.',
729
+ rec: 'Provide descriptive `alt="..."` attributes on every non-decorative `<img>`.'
730
+ });
731
+ pushCheck(domAudit.unnamedButtons > 0, {
732
+ ruleId: 'CP-A11Y-BUTTON-NAME',
733
+ category: 'accessibility',
734
+ severity: 'high',
735
+ url: options.url,
736
+ title: `${domAudit.unnamedButtons} interactive button(s) lack accessible label`,
737
+ body: 'Icon-only buttons without text or `aria-label` fail WCAG 2.1 A/AA.',
738
+ rec: 'Add concise `aria-label="..."` or text content.'
739
+ });
740
+ pushCheck(domAudit.unlabeledInputs > 0, {
741
+ ruleId: 'CP-A11Y-FORM-LABEL',
742
+ category: 'accessibility',
743
+ severity: 'medium',
744
+ url: options.url,
745
+ title: `${domAudit.unlabeledInputs} form input(s) lack label or aria-label`,
746
+ body: 'Unlabeled form controls reduce screen-reader usability.',
747
+ rec: 'Associate `<label for="...">` or `aria-label` with each form field.'
748
+ });
749
+ pushCheck(!domAudit.hasMainLandmark, {
750
+ ruleId: 'CP-A11Y-MAIN-LANDMARK',
751
+ category: 'accessibility',
752
+ severity: 'low',
753
+ url: options.url,
754
+ title: 'Rendered document lacks a `<main>` landmark region',
755
+ body: 'Landmark regions allow keyboard and screen-reader skip navigation.',
756
+ rec: 'Wrap primary content inside `<main>`.'
757
+ });
758
+ pushCheck(!domAudit.title || !domAudit.metaDesc, {
759
+ ruleId: 'CP-SEO-LIVE-META',
760
+ category: 'seo',
761
+ severity: 'medium',
762
+ url: options.url,
763
+ title: 'Page missing <title> or <meta name="description">',
764
+ body: `Title="${domAudit.title || 'missing'}", description=${domAudit.metaDesc ? 'present' : 'missing'}.`,
765
+ rec: 'Render unique descriptive `<title>` (50-60 chars) and `<meta name="description">` (120-158 chars).'
766
+ });
767
+ pushCheck(domAudit.h1Count !== 1, {
768
+ ruleId: 'CP-SEO-LIVE-H1',
769
+ category: 'seo',
770
+ severity: 'low',
771
+ url: options.url,
772
+ title: `Rendered page has ${domAudit.h1Count} <h1> heading(s) (recommended: 1)`,
773
+ body: 'Crawlers expect a single primary `<h1>` identifying the page topic.',
774
+ rec: 'Render exactly one primary `<h1>` per route.'
775
+ });
776
+ pushCheck(!robotsRes.ok, {
777
+ ruleId: 'CP-SEO-LIVE-ROBOTS',
778
+ category: 'seo',
779
+ severity: 'medium',
780
+ url: options.url,
781
+ title: 'Missing live `/robots.txt` on website origin',
782
+ body: `GET ${origin}/robots.txt did not return HTTP 200.`,
783
+ rec: 'Serve `/robots.txt` with explicit Allow/Disallow & Sitemap directives.'
784
+ });
785
+ pushCheck(!validSitemapXml, {
786
+ ruleId: 'CP-SEO-LIVE-SITEMAP',
787
+ category: 'seo',
788
+ severity: 'medium',
789
+ url: options.url,
790
+ title: 'Missing or invalid XML `/sitemap.xml`',
791
+ body: `GET ${origin}/sitemap.xml was not valid sitemap XML.`,
792
+ rec: 'Serve a valid XML sitemap listing canonical URLs.'
793
+ });
794
+ pushCheck(!llmsRes.ok, {
795
+ ruleId: 'CP-GEO-LIVE-LLMS',
796
+ category: 'geo',
797
+ severity: 'medium',
798
+ url: options.url,
799
+ title: 'Missing `/llms.txt` AI discovery file on live site',
800
+ body: `GET ${origin}/llms.txt was not found; AI answer engines rely on \`/llms.txt\` for authoritative product facts.`,
801
+ rec: 'Serve `/llms.txt` at site root.'
802
+ });
803
+ pushCheck(domAudit.jsonLdCount === 0, {
804
+ ruleId: 'CP-GEO-LIVE-JSONLD',
805
+ category: 'geo',
806
+ severity: 'medium',
807
+ url: options.url,
808
+ title: 'No Schema.org JSON-LD structured data detected on live URL',
809
+ body: 'Structured entity markup improves AI search citation fidelity and rich snippets.',
810
+ rec: 'Embed a valid `<script type="application/ld+json">` graph.'
811
+ });
812
+ pushCheck(ssrVsHydratedDeltaPercent >= 65 && hydratedTextLength > 200, {
813
+ ruleId: 'CP-GEO-LIVE-CSR-DELTA',
814
+ category: 'geo',
815
+ severity: 'high',
816
+ url: options.url,
817
+ title: `High CSR-only content delta (${ssrVsHydratedDeltaPercent}% invisible without JS)`,
818
+ body: `Raw SSR HTML contained ${ssrHtmlTextLength} chars vs ${hydratedTextLength} chars post-JS hydration. Non-JS AI bots miss ${ssrVsHydratedDeltaPercent}% of content.`,
819
+ rec: 'Pre-render core headings, copy, and JSON-LD in SSR HTML.'
820
+ });
821
+ pushCheck(brokenInternalLinks.length > 0, {
822
+ ruleId: 'CP-SEO-BROKEN-LINK',
823
+ category: 'seo',
824
+ severity: 'high',
825
+ url: options.url,
826
+ title: `${brokenInternalLinks.length} broken internal link(s) returned HTTP >= 400`,
827
+ body: brokenInternalLinks.map((b) => `${b.url} (${b.status})`).join(', '),
828
+ rec: 'Repair or redirect broken `<a href>` destinations.'
829
+ });
830
+ pushCheck(Boolean(desktopVitals?.lcpMs && desktopVitals.lcpMs > 2500), {
831
+ ruleId: 'CP-PERF-LIVE-LCP',
832
+ category: 'performance',
833
+ severity: 'medium',
834
+ url: options.url,
835
+ title: `Slow Largest Contentful Paint (LCP ${desktopVitals?.lcpMs}ms > 2500ms)`,
836
+ body: `Desktop LCP=${desktopVitals?.lcpMs}ms, Mobile LCP=${mobileVitals?.lcpMs ?? 'n/a'}ms, DOM nodes=${domAudit.domNodeCount}.`,
837
+ rec: 'Preload hero/LCP assets, inline critical CSS, and trim render-blocking scripts.'
838
+ });
839
+ pushCheck(consoleErrors.length > 0 || networkErrors.length > 0, {
840
+ ruleId: 'CP-LIVE-RUNTIME-ERRORS',
841
+ category: 'reliability',
842
+ severity: 'high',
843
+ url: options.url,
844
+ title: `Live runtime emitted ${consoleErrors.length} console/network error(s)`,
845
+ body: [...consoleErrors.slice(0, 3), ...networkErrors.slice(0, 3)].join(' | ') || 'Runtime errors recorded.',
846
+ rec: 'Fix broken asset requests and console exceptions.'
847
+ });
848
+ const a11yPenalty = findings.filter((f) => f.category === 'accessibility').length * 14;
849
+ const seoPenalty = findings.filter((f) => f.category === 'seo').length * 11;
850
+ const geoPenalty = findings.filter((f) => f.category === 'geo').length * 15;
851
+ const combinedVitalsScore = desktopVitals && mobileVitals
852
+ ? Math.round((desktopVitals.vitalsScore + mobileVitals.vitalsScore) / 2)
853
+ : (desktopVitals?.vitalsScore ?? 100);
854
+ const eeatScore = Math.max(20, Math.min(100, 40 +
855
+ (domAudit.jsonLdCount > 0 ? 25 : 0) +
856
+ (llmsRes.ok ? 20 : 0) +
857
+ (domAudit.title && domAudit.metaDesc ? 15 : 0)));
858
+ const canonicalStatus = !domAudit.canonical
859
+ ? 'missing'
860
+ : domAudit.canonical.replace(/\/+$/, '') === parsedUrl.href.replace(/\/+$/, '') || domAudit.canonical.startsWith('/')
861
+ ? 'valid'
862
+ : 'mismatch';
863
+ const generatedLlmsTxt = [
864
+ `# ${domAudit.title || parsedUrl.hostname}`,
865
+ `> ${domAudit.metaDesc || `Official web documentation and product resources at ${origin}.`}`,
866
+ '',
867
+ '## Key Pages',
868
+ `- [Home](${parsedUrl.href}): Primary landing page`,
869
+ ...(sitemapLocMatches.slice(0, 5).map((u) => `- [${u}](${u})`)),
870
+ ''
871
+ ].join('\n');
872
+ const generatedJsonLd = `<script type="application/ld+json">\n${JSON.stringify({
873
+ '@context': 'https://schema.org',
874
+ '@type': 'WebSite',
875
+ name: domAudit.title || parsedUrl.hostname,
876
+ url: parsedUrl.href,
877
+ description: domAudit.metaDesc || undefined
878
+ }, null, 2)}\n</script>`;
879
+ return {
880
+ url: options.url,
881
+ reachable,
882
+ httpStatus,
883
+ redirectChain,
884
+ hydratedTitle: domAudit.title,
885
+ metaDescription: domAudit.metaDesc,
886
+ canonicalUrl: domAudit.canonical,
887
+ canonicalStatus,
888
+ hreflangs: domAudit.hreflangs,
889
+ headingTree: domAudit.headingTree,
890
+ socialCard: domAudit.socialCard,
891
+ securityHeaders: {
892
+ hsts: headerMap['strict-transport-security'] || 'not-set',
893
+ csp: headerMap['content-security-policy'] || 'not-set',
894
+ xContentTypeOptions: headerMap['x-content-type-options'] || 'not-set',
895
+ xRobotsTag: headerMap['x-robots-tag'] || 'not-set'
896
+ },
897
+ robotsTxt: {
898
+ present: robotsRes.ok,
899
+ url: `${origin}/robots.txt`,
900
+ aiBotMatrix
901
+ },
902
+ sitemap: {
903
+ present: sitemapRes.ok,
904
+ url: `${origin}/sitemap.xml`,
905
+ validXml: validSitemapXml,
906
+ urlCount: sitemapLocMatches.length,
907
+ sampledPages
908
+ },
909
+ llmsTxt: {
910
+ present: llmsRes.ok,
911
+ length: llmsRes.text.length,
912
+ fullPresent: llmsFullRes.ok,
913
+ generatedLlmsTxt,
914
+ generatedJsonLd
915
+ },
916
+ jsonLdCount: domAudit.jsonLdCount,
917
+ jsonLdTypes: domAudit.jsonLdTypes,
918
+ ssrTextLength: ssrHtmlTextLength,
919
+ hydratedTextLength,
920
+ ssrVsHydratedDeltaPercent,
921
+ eeatScore,
922
+ domNodeCount: domAudit.domNodeCount,
923
+ lcpMs: desktopVitals?.lcpMs ?? null,
924
+ clsScore: desktopVitals?.clsScore ?? null,
925
+ desktopVitals,
926
+ mobileVitals,
927
+ vitalsScore: combinedVitalsScore,
928
+ geoScore: reachable ? Math.max(0, 100 - geoPenalty) : 0,
929
+ brokenInternalLinks,
930
+ consoleErrors,
931
+ networkErrors,
932
+ axeUsed,
933
+ findings,
934
+ diagnostics,
935
+ a11yScore: reachable ? Math.max(0, 100 - a11yPenalty) : 0,
936
+ liveSeoScore: reachable ? Math.max(0, 100 - seoPenalty) : 0
937
+ };
431
938
  }
432
939
  //# sourceMappingURL=live-accessibility.js.map