sitecheckultra 0.0.0-stage → 2.0.2

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 (44) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +161 -2
  3. package/bin/sitecheckultra.js +360 -0
  4. package/lib/analyzer.js +729 -0
  5. package/lib/branding.js +31 -0
  6. package/lib/crawler.js +961 -0
  7. package/lib/exporter.js +533 -0
  8. package/lib/http-client.js +62 -0
  9. package/lib/parse-worker.js +13 -0
  10. package/lib/renderer.js +114 -0
  11. package/lib/scorer.js +520 -0
  12. package/lib/sitemap.js +244 -0
  13. package/lib/store.js +110 -0
  14. package/lib/trackers-db.json +1 -0
  15. package/lib/trackers.js +343 -0
  16. package/lib/worker-pool.js +124 -0
  17. package/package.json +52 -4
  18. package/public/app.js +3615 -0
  19. package/public/brand/site-check-ultra.png +0 -0
  20. package/public/index.html +658 -0
  21. package/public/styles.css +3734 -0
  22. package/public/trackers/bing.svg +1 -0
  23. package/public/trackers/cloudflare.svg +1 -0
  24. package/public/trackers/cookiebot.svg +1 -0
  25. package/public/trackers/crisp.svg +1 -0
  26. package/public/trackers/googleads.svg +1 -0
  27. package/public/trackers/googleanalytics.svg +1 -0
  28. package/public/trackers/googletagmanager.svg +1 -0
  29. package/public/trackers/hotjar.svg +1 -0
  30. package/public/trackers/hubspot.svg +1 -0
  31. package/public/trackers/intercom.svg +1 -0
  32. package/public/trackers/linkedin.svg +1 -0
  33. package/public/trackers/matomo.svg +1 -0
  34. package/public/trackers/meta.svg +1 -0
  35. package/public/trackers/microsoftclarify.svg +1 -0
  36. package/public/trackers/pinterest.svg +1 -0
  37. package/public/trackers/plausibleanalytics.svg +1 -0
  38. package/public/trackers/quantcast.svg +1 -0
  39. package/public/trackers/snapchat.svg +1 -0
  40. package/public/trackers/tiktok.svg +1 -0
  41. package/public/trackers/usercentrics.svg +1 -0
  42. package/public/trackers/x.svg +1 -0
  43. package/public/trackers/zendesk.svg +1 -0
  44. package/server.js +421 -0
@@ -0,0 +1,729 @@
1
+ import { Parser } from 'htmlparser2';
2
+ import { fastFetch } from './http-client.js';
3
+ import { scorePage } from './scorer.js';
4
+ import { buildAuthHeaders, canonicalCompareKey, normalizeUrl } from './sitemap.js';
5
+ import { detectTrackers } from './trackers.js';
6
+
7
+ const SPA_HINT_REGEX = /id=["'](?:root|app|__next|__nuxt)["']|data-reactroot|type=["']module["']|_next\/static|_nuxt\/|chunk|bundle/i;
8
+ const H_TAG_REGEX = /^h([1-9]\d*)$/i;
9
+ const WS_COLLAPSE_REGEX = /\s+/g;
10
+ // Link texts that give screen readers no clue about the destination (WCAG 2.4.4)
11
+ const GENERIC_LINK_TEXT_REGEX = /^(hier|mehr|weiter|weiterlesen|mehr erfahren|mehr info|infos|info|details|click|klick|link|lesen|hier klicken|hier gehts|hier geht's|hier!\.?|mehr…|…|\*|→|»|>\s*$)$/i;
12
+
13
+ export async function fetchWithRedirects(url, auth = null, timeoutMs = 25000, maxHops = 10) {
14
+ const started = Date.now();
15
+ const redirectChain = [];
16
+ let currentUrl = url;
17
+ const headers = buildAuthHeaders(auth);
18
+
19
+ try {
20
+ let response = null;
21
+ for (let hop = 0; hop <= maxHops; hop++) {
22
+ response = await fastFetch(currentUrl, {
23
+ method: 'GET',
24
+ headers,
25
+ redirect: 'manual',
26
+ signal: AbortSignal.timeout(timeoutMs)
27
+ });
28
+
29
+ const status = response.status;
30
+ const location = response.headers.get('location');
31
+
32
+ if (status >= 300 && status < 400 && location) {
33
+ const nextUrl = new URL(location, currentUrl).toString();
34
+ redirectChain.push({
35
+ url: currentUrl,
36
+ status,
37
+ location: nextUrl
38
+ });
39
+ await response.body?.cancel().catch(() => {});
40
+ currentUrl = nextUrl;
41
+ continue;
42
+ }
43
+ break;
44
+ }
45
+
46
+ const finalStatus = response ? response.status : 0;
47
+ const initialStatus = redirectChain.length > 0 ? redirectChain[0].status : finalStatus;
48
+ const contentType = response?.headers.get('content-type') || '';
49
+
50
+ const rawHeaders = {
51
+ 'x-robots-tag': response?.headers.get('x-robots-tag') || '',
52
+ link: response?.headers.get('link') || '',
53
+ 'last-modified': response?.headers.get('last-modified') || '',
54
+ 'retry-after': response?.headers.get('retry-after') || ''
55
+ };
56
+
57
+ let html = '';
58
+ if (contentType.includes('text/html') || contentType.includes('application/xhtml+xml') || contentType === '') {
59
+ html = await response.text();
60
+ } else {
61
+ await response.body?.cancel().catch(() => {});
62
+ }
63
+
64
+ return {
65
+ initialUrl: url,
66
+ finalUrl: currentUrl,
67
+ initialStatus,
68
+ finalStatus,
69
+ redirectChain,
70
+ contentType,
71
+ headers: rawHeaders,
72
+ html,
73
+ responseTimeMs: Date.now() - started,
74
+ error: null
75
+ };
76
+ } catch (err) {
77
+ return {
78
+ initialUrl: url,
79
+ finalUrl: currentUrl,
80
+ initialStatus: redirectChain.length > 0 ? redirectChain[0].status : 0,
81
+ finalStatus: 0,
82
+ redirectChain,
83
+ contentType: '',
84
+ headers: {},
85
+ html: '',
86
+ responseTimeMs: Date.now() - started,
87
+ error: err.name === 'TimeoutError' ? 'Timeout' : (err.message || 'Netzwerkfehler')
88
+ };
89
+ }
90
+ }
91
+
92
+ export function needsJsRender(pageData, html) {
93
+ if (!html || html.length < 50) return false;
94
+ if (pageData.headingCounts?.total === 0 && pageData.wordCount < 30 && SPA_HINT_REGEX.test(html)) {
95
+ return true;
96
+ }
97
+ if (pageData.headingCounts?.h1 === 0 && pageData.wordCount < 50 && SPA_HINT_REGEX.test(html)) {
98
+ return true;
99
+ }
100
+ return false;
101
+ }
102
+
103
+ function parseRobotsDirectives(metaContents = [], xRobotsHeader = '') {
104
+ const parts = [];
105
+ for (let i = 0; i < metaContents.length; i++) {
106
+ if (metaContents[i]) parts.push(metaContents[i]);
107
+ }
108
+ if (xRobotsHeader) parts.push(xRobotsHeader);
109
+ if (parts.length === 0) {
110
+ return { indexable: true, followable: true, raw: 'index, follow' };
111
+ }
112
+
113
+ const combined = parts.join(', ').toLowerCase();
114
+ const tokens = combined.split(/[\s,;]+/);
115
+
116
+ let indexable = true;
117
+ let followable = true;
118
+
119
+ for (let i = 0; i < tokens.length; i++) {
120
+ const t = tokens[i];
121
+ if (t === 'none') {
122
+ indexable = false;
123
+ followable = false;
124
+ } else if (t === 'noindex') {
125
+ indexable = false;
126
+ } else if (t === 'nofollow') {
127
+ followable = false;
128
+ }
129
+ }
130
+
131
+ return {
132
+ indexable,
133
+ followable,
134
+ raw: parts.join(' | ')
135
+ };
136
+ }
137
+
138
+ function extractLinkHeaderCanonical(linkHeader) {
139
+ if (!linkHeader) return null;
140
+ const match = linkHeader.match(/<([^>]+)>\s*;\s*rel=["']?canonical["']?/i);
141
+ return match ? match[1].trim() : null;
142
+ }
143
+
144
+ function parseJsonLdBlocks(rawBlocks) {
145
+ const schemas = [];
146
+ const typeSet = new Set();
147
+
148
+ for (let b = 0; b < rawBlocks.length; b++) {
149
+ const rawText = rawBlocks[b].trim();
150
+ if (!rawText) continue;
151
+ try {
152
+ const parsed = JSON.parse(rawText);
153
+ const foundTypes = [];
154
+ const collectTypes = (node) => {
155
+ if (!node || typeof node !== 'object') return;
156
+ if (Array.isArray(node)) {
157
+ for (let i = 0; i < node.length; i++) collectTypes(node[i]);
158
+ return;
159
+ }
160
+ if (node['@type']) {
161
+ const types = Array.isArray(node['@type']) ? node['@type'] : [node['@type']];
162
+ for (let i = 0; i < types.length; i++) {
163
+ const t = types[i];
164
+ if (typeof t === 'string') {
165
+ foundTypes.push(t);
166
+ typeSet.add(t);
167
+ }
168
+ }
169
+ }
170
+ if (Array.isArray(node['@graph'])) {
171
+ for (let i = 0; i < node['@graph'].length; i++) collectTypes(node['@graph'][i]);
172
+ }
173
+ };
174
+ collectTypes(parsed);
175
+ schemas.push({
176
+ types: [...new Set(foundTypes)],
177
+ raw: parsed,
178
+ valid: true
179
+ });
180
+ } catch (err) {
181
+ schemas.push({
182
+ types: ['Ungültiges JSON-LD'],
183
+ raw: rawText,
184
+ valid: false,
185
+ error: err.message
186
+ });
187
+ }
188
+ }
189
+
190
+ return { schemas, schemaTypes: [...typeSet] };
191
+ }
192
+
193
+ // Single-pass Zero-DOM SAX HTML Extractor (5x-10x faster than cheerio.load + CSS selectors!)
194
+ function parseHtmlSax(html, finalUrl, origin) {
195
+ let title = '';
196
+ let titleCaptured = false;
197
+ let inTitle = false;
198
+ let metaDescription = '';
199
+ let lang = '';
200
+ let viewport = '';
201
+ let htmlCanonical = '';
202
+ const robotsMetaContents = [];
203
+ const og = { title: '', description: '', image: '', type: '' };
204
+
205
+ // Depth counters for ignored subtrees
206
+ let ignoreHeadingDepth = 0; // template, noscript
207
+ let nonTextDepth = 0; // script, style, noscript, template, svg
208
+ let inBody = false;
209
+ let wordCount = 0;
210
+
211
+ // JSON-LD capture
212
+ let inJsonLd = false;
213
+ let currentJsonLd = '';
214
+ const rawJsonLdBlocks = [];
215
+
216
+ // Heading stack (supports arbitrary nesting & unlimited H1..H99 + ARIA role="heading")
217
+ const headingStack = [];
218
+ const headings = [];
219
+ const headingCounts = { h1: 0, h2: 0, h3: 0, h4: 0, h5: 0, h6: 0, total: 0 };
220
+ let maxHeadingLevel = 0;
221
+
222
+ // Link capture
223
+ const internalMap = new Map();
224
+ const externalMap = new Map();
225
+ let activeLink = null;
226
+ let activeLinkDepth = 0;
227
+
228
+ /* Link-Kontext: die zuletzt gesehene Überschrift vor dem <a> ist die
229
+ * Sektion, aus der der Link stammt (z. B. Button "Mehr erfahren" unter H2 "Preise"). */
230
+ let currentSectionHeading = '';
231
+ let currentSectionTag = '';
232
+
233
+ // Scripts & Images
234
+ const scriptSet = new Set();
235
+ let imageCount = 0;
236
+ const imagesMissingAlt = [];
237
+ let srcsetImgCount = 0;
238
+ let appleTouchIcon = false;
239
+ let siteIcon = '';
240
+ let siteLogo = '';
241
+ let genericLinkTextCount = 0;
242
+
243
+ const countWordsInChunk = (txt) => {
244
+ let inWord = false;
245
+ for (let i = 0; i < txt.length; i++) {
246
+ const ch = txt.charCodeAt(i);
247
+ const isSpace = ch === 32 || ch === 10 || ch === 13 || ch === 9 || ch === 160;
248
+ if (isSpace) {
249
+ inWord = false;
250
+ } else if (!inWord) {
251
+ inWord = true;
252
+ wordCount += 1;
253
+ }
254
+ }
255
+ };
256
+
257
+ const parser = new Parser(
258
+ {
259
+ onopentag(name, attribs) {
260
+ // Track ignored subtrees
261
+ if (name === 'template' || name === 'noscript') {
262
+ ignoreHeadingDepth += 1;
263
+ nonTextDepth += 1;
264
+ } else if (name === 'script' || name === 'style' || name === 'svg') {
265
+ nonTextDepth += 1;
266
+ }
267
+
268
+ if (name === 'html' && !lang && attribs.lang) {
269
+ lang = attribs.lang.trim();
270
+ } else if (name === 'body') {
271
+ inBody = true;
272
+ } else if (name === 'title' && !titleCaptured && nonTextDepth === 0) {
273
+ inTitle = true;
274
+ } else if (name === 'meta') {
275
+ const content = attribs.content?.trim();
276
+ if (content) {
277
+ const mName = (attribs.name || '').toLowerCase();
278
+ const mProp = (attribs.property || '').toLowerCase();
279
+ if (mName === 'description' && !metaDescription) metaDescription = content;
280
+ else if (mName === 'viewport' && !viewport) viewport = content;
281
+ else if (mName === 'robots' || mName === 'googlebot') robotsMetaContents.push(content);
282
+ else if (mProp === 'og:title' && !og.title) og.title = content;
283
+ else if (mProp === 'og:description' && !og.description) og.description = content;
284
+ else if (mProp === 'og:image' && !og.image) og.image = content;
285
+ else if (mProp === 'og:type' && !og.type) og.type = content;
286
+ }
287
+ } else if (name === 'link') {
288
+ const rel = (attribs.rel || '').toLowerCase().split(/\s+/);
289
+ if (!htmlCanonical && rel.includes('canonical') && attribs.href) {
290
+ htmlCanonical = attribs.href.trim();
291
+ }
292
+ if (rel.includes('apple-touch-icon') && attribs.href) {
293
+ appleTouchIcon = true;
294
+ }
295
+ if (attribs.href && rel.some((r) => ['icon', 'shortcut', 'apple-touch-icon', 'apple-touch-icon-precomposed', 'mask-icon'].includes(r))) {
296
+ try { siteIcon = new URL(attribs.href, finalUrl).href; } catch { /* Invalid asset URL: keep fallback. */ }
297
+ }
298
+ } else if (name === 'script') {
299
+ const type = (attribs.type || '').toLowerCase();
300
+ if (type === 'application/ld+json') {
301
+ inJsonLd = true;
302
+ currentJsonLd = '';
303
+ } else if (attribs.src) {
304
+ const src = attribs.src.trim();
305
+ if (src) {
306
+ try { scriptSet.add(new URL(src, finalUrl).toString()); } catch { scriptSet.add(src); }
307
+ }
308
+ }
309
+ } else if (name === 'img') {
310
+ imageCount += 1;
311
+ const classAndId = `${attribs.class || ''} ${attribs.id || ''}`;
312
+ if (!siteLogo && (/(?:^|[\s_-])logo(?:$|[\s_-])/i.test(classAndId) || /\blogo\b/i.test(attribs.alt || ''))) {
313
+ const logoSrc = attribs.src || attribs['data-src'] || (attribs.srcset || '').split(',')[0].trim().split(/\s+/)[0];
314
+ if (logoSrc) {
315
+ try { siteLogo = new URL(logoSrc, finalUrl).href; } catch { /* Invalid asset URL: keep fallback. */ }
316
+ }
317
+ }
318
+ if (attribs.srcset || attribs.sourceset) srcsetImgCount += 1;
319
+ const alt = attribs.alt;
320
+ if (alt === undefined) {
321
+ if (imagesMissingAlt.length < 50) {
322
+ imagesMissingAlt.push({ src: attribs.src || attribs['data-src'] || '', reason: 'missing' });
323
+ }
324
+ } else if (alt.trim() === '') {
325
+ if (imagesMissingAlt.length < 50) {
326
+ imagesMissingAlt.push({ src: attribs.src || attribs['data-src'] || '', reason: 'empty' });
327
+ }
328
+ }
329
+ // Fallback alt text for headings that wrap an <img>
330
+ if (headingStack.length > 0 && alt && alt.trim()) {
331
+ const top = headingStack[headingStack.length - 1];
332
+ if (!top.fallback) top.fallback = alt.trim();
333
+ }
334
+ } else if (name === 'br') {
335
+ if (headingStack.length > 0) {
336
+ headingStack[headingStack.length - 1].text += ' ';
337
+ }
338
+ } else if (name === 'a' && attribs.href && ignoreHeadingDepth === 0) {
339
+ const rawHref = attribs.href.trim();
340
+ if (rawHref && rawHref.charCodeAt(0) !== 35 /* # */) {
341
+ const lowerPrefix = rawHref.slice(0, 11).toLowerCase();
342
+ if (!lowerPrefix.startsWith('mailto:') && !lowerPrefix.startsWith('tel:') && !lowerPrefix.startsWith('javascript:')) {
343
+ const normalized = normalizeUrl(rawHref, finalUrl);
344
+ if (normalized) {
345
+ const isSameOrigin =
346
+ normalized.startsWith(origin) &&
347
+ (normalized.length === origin.length || normalized[origin.length] === '/' || normalized[origin.length] === '?');
348
+ const nofollow = (attribs.rel || '').toLowerCase().includes('nofollow');
349
+ const map = isSameOrigin ? internalMap : externalMap;
350
+ if (!map.has(normalized)) {
351
+ const linkEntry = isSameOrigin
352
+ ? { url: normalized, path: normalized.slice(origin.length) || '/', text: '', nofollow, fromSection: currentSectionHeading, sectionTag: currentSectionTag }
353
+ : { url: normalized, host: '', text: '', nofollow, fromSection: currentSectionHeading, sectionTag: currentSectionTag };
354
+ if (!isSameOrigin) {
355
+ try { linkEntry.host = new URL(normalized).host; } catch { linkEntry.host = ''; }
356
+ }
357
+ map.set(normalized, linkEntry);
358
+ activeLink = linkEntry;
359
+ activeLinkDepth = 1;
360
+ }
361
+ }
362
+ }
363
+ }
364
+ } else if (activeLink && name === 'a') {
365
+ activeLinkDepth += 1;
366
+ }
367
+
368
+ // Heading detection (unlimited H1..H99 + ARIA role="heading" aria-level="1..99")
369
+ if (ignoreHeadingDepth === 0) {
370
+ let level = 0;
371
+ let isAria = false;
372
+ const hm = H_TAG_REGEX.exec(name);
373
+ if (hm) {
374
+ level = Number(hm[1]);
375
+ } else if (attribs.role === 'heading' && attribs['aria-level']) {
376
+ const al = Number(attribs['aria-level']);
377
+ if (Number.isInteger(al) && al >= 1 && al <= 99) {
378
+ level = al;
379
+ isAria = true;
380
+ }
381
+ }
382
+ if (level >= 1) {
383
+ headingStack.push({
384
+ tagName: name,
385
+ depth: 1,
386
+ level,
387
+ isAria,
388
+ text: '',
389
+ fallback: (attribs['aria-label'] || '').trim()
390
+ });
391
+ } else if (headingStack.length > 0) {
392
+ const top = headingStack[headingStack.length - 1];
393
+ if (name === top.tagName) top.depth += 1;
394
+ if (!top.fallback && attribs['aria-label']) {
395
+ top.fallback = attribs['aria-label'].trim();
396
+ }
397
+ }
398
+ }
399
+ },
400
+
401
+ ontext(text) {
402
+ if (inJsonLd) {
403
+ currentJsonLd += text;
404
+ return;
405
+ }
406
+ if (inTitle) {
407
+ title += text;
408
+ }
409
+ if (nonTextDepth === 0) {
410
+ if (inBody) countWordsInChunk(text);
411
+ if (headingStack.length > 0) {
412
+ for (let i = 0; i < headingStack.length; i++) {
413
+ headingStack[i].text += text;
414
+ }
415
+ }
416
+ if (activeLink && activeLink.text.length < 130) {
417
+ activeLink.text += text;
418
+ }
419
+ }
420
+ },
421
+
422
+ onclosetag(name) {
423
+ if (name === 'title' && inTitle) {
424
+ inTitle = false;
425
+ titleCaptured = true;
426
+ } else if (name === 'body') {
427
+ inBody = false;
428
+ } else if (name === 'script' && inJsonLd) {
429
+ inJsonLd = false;
430
+ if (currentJsonLd) rawJsonLdBlocks.push(currentJsonLd);
431
+ currentJsonLd = '';
432
+ }
433
+
434
+ if (activeLink && name === 'a') {
435
+ activeLinkDepth -= 1;
436
+ if (activeLinkDepth <= 0) {
437
+ activeLink.text = activeLink.text.replace(WS_COLLAPSE_REGEX, ' ').trim().slice(0, 120);
438
+ if (GENERIC_LINK_TEXT_REGEX.test(activeLink.text)) {
439
+ genericLinkTextCount += 1;
440
+ }
441
+ activeLink = null;
442
+ activeLinkDepth = 0;
443
+ }
444
+ }
445
+
446
+ if (headingStack.length > 0) {
447
+ const top = headingStack[headingStack.length - 1];
448
+ if (name === top.tagName) {
449
+ top.depth -= 1;
450
+ if (top.depth <= 0) {
451
+ headingStack.pop();
452
+ const cleanText = (top.text.replace(WS_COLLAPSE_REGEX, ' ').trim()) || top.fallback || '';
453
+ const tagKey = `h${top.level}`;
454
+ headings.push({
455
+ level: top.level,
456
+ tag: tagKey.toUpperCase(),
457
+ text: cleanText,
458
+ empty: cleanText.length === 0,
459
+ aria: top.isAria
460
+ });
461
+ headingCounts[tagKey] = (headingCounts[tagKey] || 0) + 1;
462
+ headingCounts.total += 1;
463
+ if (top.level > maxHeadingLevel) maxHeadingLevel = top.level;
464
+ /* Sektions-Kontext für Link-Herkunft: die zuletzt geschlossene
465
+ * Überschrift mit Text ist die nächste Sektion über dem Link.
466
+ * Leere H-Tags lassen den bisherigen Kontext bestehen. */
467
+ if (cleanText && top.level <= 6) {
468
+ currentSectionHeading = cleanText.slice(0, 120);
469
+ currentSectionTag = tagKey;
470
+ }
471
+ }
472
+ }
473
+ }
474
+
475
+ if (name === 'template' || name === 'noscript') {
476
+ ignoreHeadingDepth = Math.max(0, ignoreHeadingDepth - 1);
477
+ nonTextDepth = Math.max(0, nonTextDepth - 1);
478
+ } else if (name === 'script' || name === 'style' || name === 'svg') {
479
+ nonTextDepth = Math.max(0, nonTextDepth - 1);
480
+ }
481
+ }
482
+ },
483
+ { decodeEntities: true, lowerCaseTags: true, lowerCaseAttributeNames: true }
484
+ );
485
+
486
+ parser.write(html);
487
+ parser.end();
488
+
489
+ // Compute heading audit issues
490
+ const skippedLevels = [];
491
+ let prevLevel = 0;
492
+ let emptyCount = 0;
493
+ let firstH1Text = '';
494
+
495
+ for (let i = 0; i < headings.length; i++) {
496
+ const h = headings[i];
497
+ if (h.empty) emptyCount += 1;
498
+ if (!firstH1Text && h.level === 1 && !h.empty) firstH1Text = h.text;
499
+ if (prevLevel > 0 && h.level > prevLevel + 1) {
500
+ skippedLevels.push({ from: `H${prevLevel}`, to: h.tag, index: i, text: h.text });
501
+ }
502
+ prevLevel = h.level;
503
+ }
504
+
505
+ const missingH1 = headingCounts.h1 === 0;
506
+ const multipleH1 = headingCounts.h1 > 1;
507
+ const firstNotH1 = headings.length > 0 && headings[0].level !== 1;
508
+ const hasIssues = missingH1 || multipleH1 || skippedLevels.length > 0 || emptyCount > 0 || firstNotH1;
509
+
510
+ const schemaData = parseJsonLdBlocks(rawJsonLdBlocks);
511
+
512
+ return {
513
+ title: title.replace(WS_COLLAPSE_REGEX, ' ').trim(),
514
+ metaDescription,
515
+ lang,
516
+ viewport,
517
+ og,
518
+ robotsMetaContents,
519
+ htmlCanonical,
520
+ headingData: {
521
+ headings,
522
+ headingCounts,
523
+ maxHeadingLevel,
524
+ h1Text: firstH1Text,
525
+ headingIssues: { missingH1, multipleH1, emptyCount, skippedLevels, firstNotH1, hasIssues }
526
+ },
527
+ schemaData,
528
+ externalScripts: [...scriptSet],
529
+ internalLinks: [...internalMap.values()],
530
+ externalLinks: [...externalMap.values()],
531
+ imageCount,
532
+ imagesMissingAlt,
533
+ srcsetImgCount,
534
+ appleTouchIcon,
535
+ siteIcon,
536
+ siteLogo,
537
+ genericLinkTextCount,
538
+ wordCount
539
+ };
540
+ }
541
+
542
+ export function analyzePage({
543
+ initialUrl,
544
+ finalUrl,
545
+ initialStatus,
546
+ finalStatus,
547
+ redirectChain = [],
548
+ contentType = '',
549
+ headers = {},
550
+ html = '',
551
+ responseTimeMs = 0,
552
+ error = null,
553
+ origin,
554
+ sitemapEntry = null,
555
+ sitemapInfo = null,
556
+ blockedByRobotsTxt = null,
557
+ robotsTxtStatus = null,
558
+ robotsDisallowRule = null,
559
+ robotsInfo = null,
560
+ trackersConfig = null,
561
+ renderedWithJs = false
562
+ }) {
563
+ const parsedUrl = new URL(finalUrl || initialUrl);
564
+ const initialParsed = new URL(initialUrl);
565
+ const realPath = `${initialParsed.pathname}${initialParsed.search}`;
566
+ const finalPath = `${parsedUrl.pathname}${parsedUrl.search}`;
567
+
568
+ const resolvedSitemapEntry = sitemapEntry || (sitemapInfo
569
+ ? (sitemapInfo.lookup(initialUrl) || sitemapInfo.lookup(finalUrl))
570
+ : null);
571
+ const inSitemap = Boolean(resolvedSitemapEntry);
572
+
573
+ const matchedRule = robotsDisallowRule !== null
574
+ ? robotsDisallowRule
575
+ : (robotsInfo?.matchDisallow ? robotsInfo.matchDisallow(initialParsed.pathname) : null);
576
+ const isBlockedByRobots = blockedByRobotsTxt !== null
577
+ ? Boolean(blockedByRobotsTxt)
578
+ : (robotsInfo ? robotsInfo.isDisallowed(initialParsed.pathname) : Boolean(matchedRule));
579
+ const resolvedRobotsTxtStatus = robotsTxtStatus !== null ? robotsTxtStatus : (robotsInfo?.status ?? null);
580
+
581
+ const isHtml = Boolean(html) && (contentType.includes('text/html') || contentType.includes('xhtml') || contentType === '' || renderedWithJs);
582
+
583
+ let title = '';
584
+ let metaDescription = '';
585
+ let robots = parseRobotsDirectives([], headers['x-robots-tag'] || '');
586
+ let canonical = extractLinkHeaderCanonical(headers.link);
587
+ let canonicalType = 'none';
588
+ let og = { title: '', description: '', image: '', type: '' };
589
+ let lang = '';
590
+ let viewport = '';
591
+ let headingData = {
592
+ headings: [],
593
+ headingCounts: { h1: 0, h2: 0, h3: 0, h4: 0, h5: 0, h6: 0, total: 0 },
594
+ maxHeadingLevel: 0,
595
+ h1Text: '',
596
+ headingIssues: {
597
+ missingH1: false,
598
+ multipleH1: false,
599
+ emptyCount: 0,
600
+ skippedLevels: [],
601
+ firstNotH1: false,
602
+ hasIssues: false
603
+ }
604
+ };
605
+ let schemaData = { schemas: [], schemaTypes: [] };
606
+ let externalScripts = [];
607
+ let tracking = detectTrackers('', [], trackersConfig);
608
+ let internalLinks = [];
609
+ let externalLinks = [];
610
+ let imageCount = 0;
611
+ let imagesMissingAlt = [];
612
+ let srcsetImgCount = 0;
613
+ let appleTouchIcon = false;
614
+ let siteIcon = '';
615
+ let siteLogo = '';
616
+ let genericLinkTextCount = 0;
617
+ let wordCount = 0;
618
+
619
+ if (isHtml && html) {
620
+ const parsed = parseHtmlSax(html, finalUrl, origin);
621
+ title = parsed.title;
622
+ metaDescription = parsed.metaDescription;
623
+ lang = parsed.lang;
624
+ viewport = parsed.viewport;
625
+ og = parsed.og;
626
+ robots = parseRobotsDirectives(parsed.robotsMetaContents, headers['x-robots-tag'] || '');
627
+
628
+ if (parsed.htmlCanonical) {
629
+ canonical = normalizeUrl(parsed.htmlCanonical, finalUrl) || parsed.htmlCanonical;
630
+ } else if (canonical) {
631
+ canonical = normalizeUrl(canonical, finalUrl) || canonical;
632
+ }
633
+
634
+ if (canonical) {
635
+ canonicalType = canonicalCompareKey(canonical) === canonicalCompareKey(finalUrl) ? 'self' : 'other';
636
+ } else {
637
+ canonicalType = 'none';
638
+ }
639
+
640
+ headingData = parsed.headingData;
641
+ schemaData = parsed.schemaData;
642
+ externalScripts = parsed.externalScripts;
643
+ tracking = detectTrackers(html, externalScripts, trackersConfig);
644
+ internalLinks = parsed.internalLinks;
645
+ externalLinks = parsed.externalLinks;
646
+ imageCount = parsed.imageCount;
647
+ imagesMissingAlt = parsed.imagesMissingAlt;
648
+ srcsetImgCount = parsed.srcsetImgCount;
649
+ appleTouchIcon = parsed.appleTouchIcon;
650
+ siteIcon = parsed.siteIcon;
651
+ siteLogo = parsed.siteLogo;
652
+ genericLinkTextCount = parsed.genericLinkTextCount;
653
+ wordCount = parsed.wordCount;
654
+ }
655
+
656
+ // Raw HTML payload size in bytes (page-weight proxy for the Speed score)
657
+ const contentSizeBytes = html ? Buffer.byteLength(html, 'utf8') : 0;
658
+
659
+ const hasRedirect = redirectChain.length > 0;
660
+ const redirectStatus = hasRedirect ? redirectChain[0].status : null;
661
+ const redirectTarget = hasRedirect ? finalUrl : null;
662
+ const lastModified = resolvedSitemapEntry?.lastmod || headers['last-modified'] || null;
663
+
664
+ const pageResult = {
665
+ url: initialUrl,
666
+ finalUrl,
667
+ path: realPath,
668
+ finalPath,
669
+ initialStatus,
670
+ finalStatus,
671
+ status: finalStatus || initialStatus,
672
+ error,
673
+ responseTimeMs,
674
+ renderedWithJs,
675
+ contentType,
676
+ title,
677
+ titleLength: title.length,
678
+ metaDescription,
679
+ metaDescriptionLength: metaDescription.length,
680
+ lang,
681
+ viewport,
682
+ og,
683
+ indexable: robots.indexable,
684
+ followable: robots.followable,
685
+ robotsRaw: robots.raw,
686
+ blockedByRobotsTxt: isBlockedByRobots,
687
+ robotsTxtStatus: resolvedRobotsTxtStatus,
688
+ robotsDisallowRule: matchedRule || null,
689
+ inSitemap,
690
+ sitemapLastmod: resolvedSitemapEntry?.lastmod || null,
691
+ sitemapLastmodStatus: !inSitemap ? 'not_in_sitemap' : (resolvedSitemapEntry?.lastmod ? 'ok' : 'missing'),
692
+ lastModified,
693
+ canonical: canonical || null,
694
+ canonicalType,
695
+ hasRedirect,
696
+ redirectStatus,
697
+ redirectTarget,
698
+ redirectChain,
699
+ headings: headingData.headings,
700
+ headingCounts: headingData.headingCounts,
701
+ maxHeadingLevel: headingData.maxHeadingLevel || 0,
702
+ h1Text: headingData.h1Text,
703
+ headingIssues: headingData.headingIssues,
704
+ schemas: schemaData.schemas,
705
+ schemaTypes: schemaData.schemaTypes,
706
+ externalScripts,
707
+ tracking,
708
+ internalLinks,
709
+ externalLinks,
710
+ internalLinkCount: internalLinks.length,
711
+ externalLinkCount: externalLinks.length,
712
+ linkCount: internalLinks.length + externalLinks.length,
713
+ brokenLinksCount: 0,
714
+ imageCount,
715
+ imagesMissingAltCount: imagesMissingAlt.length,
716
+ imagesMissingAlt,
717
+ srcsetImgCount,
718
+ appleTouchIcon,
719
+ siteIcon,
720
+ siteLogo,
721
+ genericLinkTextCount,
722
+ contentSizeBytes,
723
+ wordCount,
724
+ note: ''
725
+ };
726
+
727
+ pageResult.audit = scorePage(pageResult);
728
+ return pageResult;
729
+ }