caxton 0.1.4

A secure WebAssembly runtime for multi-agent systems
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
#!/usr/bin/env node

/**
 * SEO Meta Tags and Elements Validator for Caxton Website
 * Validates meta tags, structured data, alt text, and SEO elements
 */

const fs = require('fs');
const path = require('path');

class SeoMetaValidator {
    constructor() {
        // Determine correct site path - look for website directory from current working directory
        let sitePath = path.join(process.cwd(), 'website');

        // If running from validation directory, go up to project root
        if (process.cwd().includes('scripts/validation')) {
            sitePath = path.join(process.cwd(), '..', '..', 'website');
        }

        this.sitePath = sitePath;
        this.results = {
            meta: { total: 0, passed: 0, failed: 0, issues: [] },
            images: { total: 0, withAlt: 0, withoutAlt: 0, issues: [] },
            headings: { files: 0, issues: [] },
            links: { internal: 0, external: 0, issues: [] },
            structured: { found: 0, issues: [] },
            performance: { issues: [] }
        };
    }

    async run() {
        console.log('🔍 Starting SEO Meta Tags Validation...');
        console.log(`Site Path: ${this.sitePath}`);
        console.log(''.repeat(60));

        try {
            await this.validateMetaTags();
            await this.validateImageAltText();
            await this.validateHeadingStructure();
            await this.validateLinks();
            await this.validateStructuredData();
            await this.validatePerformanceElements();
            this.generateReport();
        } catch (error) {
            console.error('❌ Error during SEO validation:', error.message);
            process.exit(1);
        }
    }

    async validateMetaTags() {
        console.log('\n🏷️  Validating Meta Tags...');

        const htmlFiles = this.findFiles(['.html']);
        const mdFiles = this.findFiles(['.md', '.markdown']);
        const allFiles = [...htmlFiles, ...mdFiles];

        this.results.meta.total = allFiles.length;

        for (const file of allFiles) {
            const relativePath = path.relative(this.sitePath, file);
            console.log(`Checking meta tags: ${relativePath}`);

            try {
                const issues = await this.validateFileMetaTags(file);

                if (issues.length === 0) {
                    this.results.meta.passed++;
                    console.log(`   Meta tags valid`);
                } else {
                    this.results.meta.failed++;
                    console.log(`   ${issues.length} meta tag issues`);

                    this.results.meta.issues.push({
                        file: relativePath,
                        issues: issues
                    });
                }

            } catch (error) {
                this.results.meta.failed++;
                console.log(`   Meta validation failed: ${error.message}`);
            }
        }
    }

    async validateFileMetaTags(filePath) {
        const content = fs.readFileSync(filePath, 'utf8');
        const issues = [];
        const isMarkdown = filePath.endsWith('.md') || filePath.endsWith('.markdown');

        if (isMarkdown) {
            // Check Jekyll front matter
            const frontMatterMatch = content.match(/^---\n([\s\S]*?)\n---/);
            if (frontMatterMatch) {
                const frontMatter = frontMatterMatch[1];
                this.validateFrontMatter(frontMatter, issues);
            } else {
                issues.push('Markdown file missing Jekyll front matter');
            }
        } else {
            // Check HTML meta tags
            this.validateHtmlMetaTags(content, issues);
        }

        return issues;
    }

    validateFrontMatter(frontMatter, issues) {
        // Essential front matter fields
        const requiredFields = ['title', 'description'];
        const recommendedFields = ['layout', 'permalink'];

        requiredFields.forEach(field => {
            if (!frontMatter.includes(`${field}:`)) {
                issues.push(`Missing required front matter field: ${field}`);
            }
        });

        // Check title length
        const titleMatch = frontMatter.match(/title:\s*["']?([^"'\n]+)["']?/);
        if (titleMatch) {
            const title = titleMatch[1].trim();
            if (title.length < 10) {
                issues.push(`Title too short: ${title.length} characters (recommend 10-60)`);
            } else if (title.length > 60) {
                issues.push(`Title too long: ${title.length} characters (recommend 10-60)`);
            }
        }

        // Check description length
        const descMatch = frontMatter.match(/description:\s*["']?([^"'\n]+)["']?/);
        if (descMatch) {
            const desc = descMatch[1].trim();
            if (desc.length < 50) {
                issues.push(`Description too short: ${desc.length} characters (recommend 50-160)`);
            } else if (desc.length > 160) {
                issues.push(`Description too long: ${desc.length} characters (recommend 50-160)`);
            }
        }

        // Check for SEO-specific fields
        const seoFields = ['keywords', 'author', 'canonical_url', 'robots'];
        seoFields.forEach(field => {
            if (frontMatter.includes(`${field}:`)) {
                // Field present, could validate content
            }
        });
    }

    validateHtmlMetaTags(content, issues) {
        // Check for essential meta tags
        const essentialTags = [
            { pattern: /<meta[^>]*charset/i, name: 'charset' },
            { pattern: /<meta[^>]*name=["']viewport["']/i, name: 'viewport' },
            { pattern: /<title>/i, name: 'title' },
            { pattern: /<meta[^>]*name=["']description["']/i, name: 'description' }
        ];

        essentialTags.forEach(tag => {
            if (!content.match(tag.pattern)) {
                issues.push(`Missing essential meta tag: ${tag.name}`);
            }
        });

        // Validate title tag
        const titleMatch = content.match(/<title>(.*?)<\/title>/i);
        if (titleMatch) {
            const title = titleMatch[1].trim();
            if (title.length < 10) {
                issues.push(`Title too short: ${title.length} characters`);
            } else if (title.length > 60) {
                issues.push(`Title too long: ${title.length} characters`);
            }
        }

        // Validate description meta tag
        const descMatch = content.match(/<meta[^>]*name=["']description["'][^>]*content=["']([^"']*)["']/i);
        if (descMatch) {
            const desc = descMatch[1].trim();
            if (desc.length < 50) {
                issues.push(`Description too short: ${desc.length} characters`);
            } else if (desc.length > 160) {
                issues.push(`Description too long: ${desc.length} characters`);
            }
        }

        // Check Open Graph tags
        this.validateOpenGraphTags(content, issues);

        // Check Twitter Card tags
        this.validateTwitterCardTags(content, issues);

        // Check other SEO tags
        this.validateOtherSeoTags(content, issues);
    }

    validateOpenGraphTags(content, issues) {
        const ogTags = [
            { pattern: /<meta[^>]*property=["']og:title["']/i, name: 'og:title' },
            { pattern: /<meta[^>]*property=["']og:description["']/i, name: 'og:description' },
            { pattern: /<meta[^>]*property=["']og:url["']/i, name: 'og:url' },
            { pattern: /<meta[^>]*property=["']og:type["']/i, name: 'og:type' }
        ];

        let ogTagsFound = 0;
        ogTags.forEach(tag => {
            if (content.match(tag.pattern)) {
                ogTagsFound++;
            }
        });

        if (ogTagsFound > 0 && ogTagsFound < 4) {
            issues.push(`Incomplete Open Graph tags: ${ogTagsFound}/4 found`);
        } else if (ogTagsFound === 4) {
            // All OG tags found, validate image
            if (!content.match(/<meta[^>]*property=["']og:image["']/i)) {
                issues.push('Open Graph tags found but missing og:image');
            }
        }
    }

    validateTwitterCardTags(content, issues) {
        const twitterTags = [
            { pattern: /<meta[^>]*name=["']twitter:card["']/i, name: 'twitter:card' },
            { pattern: /<meta[^>]*name=["']twitter:title["']/i, name: 'twitter:title' },
            { pattern: /<meta[^>]*name=["']twitter:description["']/i, name: 'twitter:description' }
        ];

        let twitterTagsFound = 0;
        twitterTags.forEach(tag => {
            if (content.match(tag.pattern)) {
                twitterTagsFound++;
            }
        });

        if (twitterTagsFound > 0 && twitterTagsFound < 3) {
            issues.push(`Incomplete Twitter Card tags: ${twitterTagsFound}/3 found`);
        }
    }

    validateOtherSeoTags(content, issues) {
        // Check for canonical URL
        if (!content.match(/<link[^>]*rel=["']canonical["']/i)) {
            issues.push('Missing canonical URL');
        }

        // Check for robots meta tag
        if (content.match(/<meta[^>]*name=["']robots["'][^>]*content=["'][^"']*noindex[^"']*["']/i)) {
            issues.push('Page set to noindex - verify this is intentional');
        }

        // Check for duplicate meta tags
        const metaDescriptions = content.match(/<meta[^>]*name=["']description["']/gi);
        if (metaDescriptions && metaDescriptions.length > 1) {
            issues.push('Multiple description meta tags found');
        }
    }

    async validateImageAltText() {
        console.log('\n🖼️  Validating Image Alt Text...');

        const htmlFiles = this.findFiles(['.html']);
        const mdFiles = this.findFiles(['.md', '.markdown']);
        const allFiles = [...htmlFiles, ...mdFiles];

        for (const file of allFiles) {
            const relativePath = path.relative(this.sitePath, file);
            console.log(`Checking images: ${relativePath}`);

            const content = fs.readFileSync(file, 'utf8');
            const images = this.extractImages(content);

            this.results.images.total += images.length;

            images.forEach(image => {
                if (image.hasAlt) {
                    this.results.images.withAlt++;
                    if (image.altText.trim() === '') {
                        // Empty alt is okay for decorative images
                        if (!image.isDecorative) {
                            this.results.images.issues.push({
                                file: relativePath,
                                issue: 'Empty alt text (consider adding descriptive text)',
                                image: image.src
                            });
                        }
                    }
                } else {
                    this.results.images.withoutAlt++;
                    this.results.images.issues.push({
                        file: relativePath,
                        issue: 'Missing alt attribute',
                        image: image.src
                    });
                }
            });

            if (images.length > 0) {
                console.log(`  Found ${images.length} images, ${images.filter(i => i.hasAlt).length} with alt text`);
            }
        }
    }

    extractImages(content) {
        const images = [];

        // HTML images
        const htmlImages = content.match(/<img[^>]*>/gi) || [];
        htmlImages.forEach(imgTag => {
            const srcMatch = imgTag.match(/src=["']([^"']*)["']/i);
            const altMatch = imgTag.match(/alt=["']([^"']*)["']/i);
            const roleMatch = imgTag.match(/role=["']presentation["']/i);
            const ariaHidden = imgTag.match(/aria-hidden=["']true["']/i);

            if (srcMatch) {
                images.push({
                    src: srcMatch[1],
                    hasAlt: !!altMatch,
                    altText: altMatch ? altMatch[1] : '',
                    isDecorative: !!roleMatch || !!ariaHidden,
                    type: 'html'
                });
            }
        });

        // Markdown images
        const markdownImages = content.match(/!\[([^\]]*)\]\(([^)]+)\)/g) || [];
        markdownImages.forEach(mdImg => {
            const match = mdImg.match(/!\[([^\]]*)\]\(([^)]+)\)/);
            if (match) {
                images.push({
                    src: match[2],
                    hasAlt: true,
                    altText: match[1],
                    isDecorative: false,
                    type: 'markdown'
                });
            }
        });

        return images;
    }

    async validateHeadingStructure() {
        console.log('\n📑 Validating Heading Structure...');

        const htmlFiles = this.findFiles(['.html']);
        const mdFiles = this.findFiles(['.md', '.markdown']);
        const allFiles = [...htmlFiles, ...mdFiles];

        this.results.headings.files = allFiles.length;

        for (const file of allFiles) {
            const relativePath = path.relative(this.sitePath, file);
            console.log(`Checking headings: ${relativePath}`);

            const content = fs.readFileSync(file, 'utf8');
            const issues = this.validateHeadingHierarchy(content);

            if (issues.length > 0) {
                this.results.headings.issues.push({
                    file: relativePath,
                    issues: issues
                });
                console.log(`   ${issues.length} heading issues`);
            } else {
                console.log(`   Heading structure valid`);
            }
        }
    }

    validateHeadingHierarchy(content) {
        const issues = [];
        let headings = [];

        // Extract HTML headings
        const htmlHeadings = content.match(/<h([1-6])[^>]*>(.*?)<\/h[1-6]>/gi) || [];
        htmlHeadings.forEach(heading => {
            const match = heading.match(/<h([1-6])[^>]*>(.*?)<\/h[1-6]>/i);
            if (match) {
                headings.push({
                    level: parseInt(match[1]),
                    text: match[2].replace(/<[^>]*>/g, '').trim(),
                    type: 'html'
                });
            }
        });

        // Extract Markdown headings
        const mdHeadings = content.match(/^#{1,6}\s+.+$/gm) || [];
        mdHeadings.forEach(heading => {
            const match = heading.match(/^(#{1,6})\s+(.+)$/);
            if (match) {
                headings.push({
                    level: match[1].length,
                    text: match[2].trim(),
                    type: 'markdown'
                });
            }
        });

        if (headings.length === 0) {
            issues.push('No headings found');
            return issues;
        }

        // Check for H1
        const h1Count = headings.filter(h => h.level === 1).length;
        if (h1Count === 0) {
            issues.push('No H1 heading found');
        } else if (h1Count > 1) {
            issues.push(`Multiple H1 headings found: ${h1Count}`);
        }

        // Check hierarchy
        let previousLevel = 0;
        headings.forEach((heading, index) => {
            if (heading.level > previousLevel + 1) {
                issues.push(`Heading hierarchy skip: H${previousLevel} to H${heading.level} ("${heading.text.substring(0, 30)}...")`);
            }
            previousLevel = heading.level;
        });

        // Check for empty headings
        headings.forEach(heading => {
            if (heading.text.length === 0) {
                issues.push('Empty heading found');
            }
        });

        return issues;
    }

    async validateLinks() {
        console.log('\n🔗 Validating Links...');

        const htmlFiles = this.findFiles(['.html']);
        const mdFiles = this.findFiles(['.md', '.markdown']);
        const allFiles = [...htmlFiles, ...mdFiles];

        for (const file of allFiles) {
            const relativePath = path.relative(this.sitePath, file);
            const content = fs.readFileSync(file, 'utf8');

            const links = this.extractLinks(content);

            links.forEach(link => {
                if (link.isExternal) {
                    this.results.links.external++;

                    // Check if external links have proper attributes
                    if (!link.hasTargetBlank) {
                        this.results.links.issues.push({
                            file: relativePath,
                            issue: 'External link missing target="_blank"',
                            url: link.href
                        });
                    }

                    if (!link.hasNoOpener) {
                        this.results.links.issues.push({
                            file: relativePath,
                            issue: 'External link missing rel="noopener"',
                            url: link.href
                        });
                    }
                } else {
                    this.results.links.internal++;
                }

                // Check for meaningful link text
                if (link.text && (
                    link.text.toLowerCase() === 'click here' ||
                    link.text.toLowerCase() === 'read more' ||
                    link.text.toLowerCase() === 'here'
                )) {
                    this.results.links.issues.push({
                        file: relativePath,
                        issue: 'Non-descriptive link text',
                        url: link.href,
                        text: link.text
                    });
                }
            });
        }

        console.log(`Found ${this.results.links.internal} internal and ${this.results.links.external} external links`);
    }

    extractLinks(content) {
        const links = [];

        // HTML links
        const htmlLinks = content.match(/<a[^>]*href=["']([^"']*)["'][^>]*>(.*?)<\/a>/gi) || [];
        htmlLinks.forEach(linkTag => {
            const hrefMatch = linkTag.match(/href=["']([^"']*)["']/i);
            const textMatch = linkTag.match(/>([^<]*)</);
            const targetMatch = linkTag.match(/target=["']_blank["']/i);
            const relMatch = linkTag.match(/rel=["']([^"']*)["']/i);

            if (hrefMatch) {
                const href = hrefMatch[1];
                const isExternal = href.startsWith('http://') || href.startsWith('https://');

                links.push({
                    href: href,
                    text: textMatch ? textMatch[1].trim() : '',
                    isExternal: isExternal,
                    hasTargetBlank: !!targetMatch,
                    hasNoOpener: relMatch ? relMatch[1].includes('noopener') : false,
                    type: 'html'
                });
            }
        });

        // Markdown links
        const markdownLinks = content.match(/\[([^\]]*)\]\(([^)]+)\)/g) || [];
        markdownLinks.forEach(mdLink => {
            const match = mdLink.match(/\[([^\]]*)\]\(([^)]+)\)/);
            if (match) {
                const href = match[2];
                const isExternal = href.startsWith('http://') || href.startsWith('https://');

                links.push({
                    href: href,
                    text: match[1],
                    isExternal: isExternal,
                    hasTargetBlank: false, // Markdown doesn't have these attributes
                    hasNoOpener: false,
                    type: 'markdown'
                });
            }
        });

        return links;
    }

    async validateStructuredData() {
        console.log('\n🏗️  Validating Structured Data...');

        const htmlFiles = this.findFiles(['.html']);

        for (const file of htmlFiles) {
            const relativePath = path.relative(this.sitePath, file);
            const content = fs.readFileSync(file, 'utf8');

            // Check for JSON-LD
            const jsonLdMatches = content.match(/<script[^>]*type=["']application\/ld\+json["'][^>]*>(.*?)<\/script>/gis) || [];
            jsonLdMatches.forEach(match => {
                this.results.structured.found++;
                const jsonMatch = match.match(/<script[^>]*type=["']application\/ld\+json["'][^>]*>(.*?)<\/script>/is);
                if (jsonMatch) {
                    try {
                        JSON.parse(jsonMatch[1]);
                    } catch (error) {
                        this.results.structured.issues.push({
                            file: relativePath,
                            issue: `Invalid JSON-LD: ${error.message}`
                        });
                    }
                }
            });

            // Check for microdata
            const microdataElements = content.match(/<[^>]*itemscope[^>]*>/gi) || [];
            if (microdataElements.length > 0) {
                this.results.structured.found += microdataElements.length;
            }

            // Check for RDFa
            const rdfaElements = content.match(/<[^>]*property=["'][^"']*["'][^>]*>/gi) || [];
            if (rdfaElements.length > 0) {
                this.results.structured.found += rdfaElements.length;
            }
        }

        console.log(`Found ${this.results.structured.found} structured data elements`);
    }

    async validatePerformanceElements() {
        console.log('\n⚡ Validating Performance Elements...');

        const htmlFiles = this.findFiles(['.html']);

        for (const file of htmlFiles) {
            const relativePath = path.relative(this.sitePath, file);
            const content = fs.readFileSync(file, 'utf8');

            // Check for lazy loading
            const images = content.match(/<img[^>]*>/gi) || [];
            images.forEach(img => {
                if (!img.includes('loading=') && !img.includes('lazy')) {
                    this.results.performance.issues.push({
                        file: relativePath,
                        issue: 'Image without lazy loading attribute',
                        element: img.substring(0, 50) + '...'
                    });
                }
            });

            // Check for preconnect to external resources
            const externalFonts = content.match(/fonts\.googleapis\.com|fonts\.gstatic\.com/g);
            if (externalFonts && !content.includes('preconnect')) {
                this.results.performance.issues.push({
                    file: relativePath,
                    issue: 'External fonts without preconnect'
                });
            }

            // Check for multiple CSS files (should be minified/combined)
            const cssLinks = content.match(/<link[^>]*rel=["']stylesheet["'][^>]*>/gi) || [];
            if (cssLinks.length > 5) {
                this.results.performance.issues.push({
                    file: relativePath,
                    issue: `Many CSS files (${cssLinks.length}) - consider combining`,
                    count: cssLinks.length
                });
            }
        }
    }

    findFiles(extensions) {
        const files = [];

        const walkDir = (dir) => {
            try {
                const items = fs.readdirSync(dir);

                for (const item of items) {
                    const fullPath = path.join(dir, item);
                    const stat = fs.statSync(fullPath);

                    if (stat.isDirectory() && !item.startsWith('.') && item !== 'node_modules') {
                        walkDir(fullPath);
                    } else if (extensions.some(ext => item.endsWith(ext))) {
                        files.push(fullPath);
                    }
                }
            } catch (error) {
                console.warn(`Warning: Cannot access directory ${dir}: ${error.message}`);
            }
        };

        walkDir(this.sitePath);
        return files;
    }

    generateReport() {
        console.log('\n' + '='.repeat(60));
        console.log('📋 SEO META TAGS VALIDATION REPORT');
        console.log('='.repeat(60));

        // Meta Tags Summary
        console.log('\n🏷️  Meta Tags:');
        console.log(`  Total files: ${this.results.meta.total}`);
        console.log(`   Passed: ${this.results.meta.passed}`);
        console.log(`   Failed: ${this.results.meta.failed}`);

        if (this.results.meta.total > 0) {
            const passRate = ((this.results.meta.passed / this.results.meta.total) * 100).toFixed(1);
            console.log(`  📈 Pass rate: ${passRate}%`);
        }

        // Images Summary
        console.log('\n🖼️  Images:');
        console.log(`  Total images: ${this.results.images.total}`);
        console.log(`   With alt text: ${this.results.images.withAlt}`);
        console.log(`   Missing alt text: ${this.results.images.withoutAlt}`);

        if (this.results.images.total > 0) {
            const altRate = ((this.results.images.withAlt / this.results.images.total) * 100).toFixed(1);
            console.log(`  📈 Alt text coverage: ${altRate}%`);
        }

        // Links Summary
        console.log('\n🔗 Links:');
        console.log(`  Internal links: ${this.results.links.internal}`);
        console.log(`  External links: ${this.results.links.external}`);
        console.log(`  Link issues: ${this.results.links.issues.length}`);

        // Structured Data Summary
        console.log('\n🏗️  Structured Data:');
        console.log(`  Elements found: ${this.results.structured.found}`);
        console.log(`  Issues: ${this.results.structured.issues.length}`);

        // Performance Summary
        console.log('\n⚡ Performance:');
        console.log(`  Issues found: ${this.results.performance.issues.length}`);

        // Detailed Issues
        const allIssues = [
            ...this.results.meta.issues,
            ...this.results.images.issues.map(i => ({file: i.file, issues: [i.issue]})),
            ...this.results.headings.issues,
            ...this.results.links.issues.map(i => ({file: i.file, issues: [i.issue]})),
            ...this.results.structured.issues.map(i => ({file: i.file, issues: [i.issue]})),
            ...this.results.performance.issues.map(i => ({file: i.file, issues: [i.issue]}))
        ];

        if (allIssues.length > 0) {
            console.log('\n🔍 DETAILED ISSUES:');
            console.log('-'.repeat(60));

            const groupedIssues = {};
            allIssues.forEach(item => {
                if (!groupedIssues[item.file]) {
                    groupedIssues[item.file] = [];
                }
                if (Array.isArray(item.issues)) {
                    groupedIssues[item.file].push(...item.issues);
                } else {
                    groupedIssues[item.file].push(item.issues);
                }
            });

            Object.keys(groupedIssues).forEach(file => {
                console.log(`\n📄 ${file}:`);
                groupedIssues[file].forEach(issue => {
                    console.log(`   ${issue}`);
                });
            });
        }

        // SEO Recommendations
        console.log('\n💡 SEO RECOMMENDATIONS:');
        console.log('-'.repeat(60));

        const recommendations = [];

        if (this.results.meta.failed > 0) {
            recommendations.push('• Ensure all pages have title and description meta tags');
        }

        if (this.results.images.withoutAlt > 0) {
            recommendations.push('• Add alt text to all images for accessibility and SEO');
        }

        if (this.results.links.issues.length > 0) {
            recommendations.push('• Use descriptive link text and proper attributes for external links');
        }

        if (this.results.structured.found === 0) {
            recommendations.push('• Consider adding structured data (JSON-LD) for better search results');
        }

        recommendations.push('• Optimize page loading speed with lazy loading and resource preconnection');
        recommendations.push('• Use proper heading hierarchy (H1-H6) for content structure');
        recommendations.push('• Implement canonical URLs to prevent duplicate content issues');

        recommendations.forEach(rec => console.log(rec));

        // Save detailed report
        const reportData = {
            timestamp: new Date().toISOString(),
            summary: {
                metaTags: this.results.meta,
                images: this.results.images,
                headings: this.results.headings,
                links: this.results.links,
                structuredData: this.results.structured,
                performance: this.results.performance
            },
            recommendations: recommendations
        };

        fs.writeFileSync(
            '/workspaces/caxton/scripts/validation/seo-meta-report.json',
            JSON.stringify(reportData, null, 2)
        );

        console.log('\n📁 Detailed report saved to: seo-meta-report.json');

        const hasErrors = this.results.meta.failed > 0 ||
                         this.results.images.withoutAlt > 0 ||
                         this.results.links.issues.length > 0 ||
                         this.results.structured.issues.length > 0;

        if (hasErrors) {
            process.exit(1);
        }
    }
}

// Run if called directly
if (require.main === module) {
    const validator = new SeoMetaValidator();
    validator.run();
}

module.exports = SeoMetaValidator;