@cobola/dsh-geo 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,178 @@
1
+ /**
2
+ * Content generators: llms.txt and FAQPage JSON-LD.
3
+ *
4
+ * Both generate from what the audited pages actually contain. Nothing here
5
+ * invents a section, a question, or an answer: a generator that produced text
6
+ * the site does not have would be a way to misrepresent a site to a model, and
7
+ * the audit's whole premise is that evidence must be traceable.
8
+ *
9
+ * Honest scoping, stated in the output itself:
10
+ * - Google Search does not use llms.txt. It is useful for other agents and
11
+ * tools; it is not a Google ranking mechanism.
12
+ * - Google restricted FAQ rich results to authoritative government and health
13
+ * sites in August 2023, so FAQPage markup no longer earns rich results for
14
+ * most sites. It is still valid, machine-readable structure; it is not a
15
+ * rich-result opportunity.
16
+ */
17
+
18
+ const QUESTION_START = /^(?:how|what|why|when|where|who|which|can|should|do|does|is|are|will)\b|^(?:如何|为何|为什么|怎么|怎样|什么|哪些|哪个|是否|能否)/i;
19
+
20
+ const LLMS_NOTE = 'Note: Google Search does not use this file. It is published for other AI agents and tools that choose to read it.';
21
+ const FAQ_NOTE = 'Note: Google restricted FAQ rich results to authoritative government and health sites in August 2023, so this markup does not earn rich results for most sites. It remains valid, machine-readable structure.';
22
+
23
+ function trimSlash(value) {
24
+ const url = new URL(value);
25
+ url.hash = '';
26
+ let path = url.pathname;
27
+ if (path.length > 1 && path.endsWith('/')) path = path.slice(0, -1);
28
+ return `${url.origin}${path}${url.search}`;
29
+ }
30
+
31
+ function siteName(scan) {
32
+ try {
33
+ const host = new URL(scan.startUrl).hostname.replace(/^\.?www\./, '');
34
+ return host;
35
+ } catch {
36
+ return 'site';
37
+ }
38
+ }
39
+
40
+ function pageTitle(page) {
41
+ const title = page.facts?.title ?? '';
42
+ return title.length > 0 ? title : page.path;
43
+ }
44
+
45
+ function isQuestion(heading) {
46
+ return QUESTION_START.test(heading) || /[??]\s*$/.test(heading);
47
+ }
48
+
49
+ function firstAnswer(section, maxLength = 320) {
50
+ const text = (section.paragraphs ?? []).join(' ').trim();
51
+ if (text.length === 0) return '';
52
+ return text.length > maxLength ? `${text.slice(0, maxLength)}…` : text;
53
+ }
54
+
55
+ /**
56
+ * Build an llms.txt from the audited pages.
57
+ *
58
+ * @param {object} scan - Scan artifact.
59
+ * @param {{maxLinks?: number}} [options]
60
+ * @returns {{content: string, sections: number, links: number, sourcePages: number}}
61
+ */
62
+ export function generateLlmsTxt(scan, options = {}) {
63
+ const maxLinks = options.maxLinks ?? 60;
64
+ const pages = (scan.pages ?? []).filter((page) => page.facts && page.status === 200);
65
+ const lines = [];
66
+ const name = siteName(scan);
67
+
68
+ lines.push(`# ${name}`);
69
+ lines.push('');
70
+ const primary = pages.find((page) => page.depth === 0) ?? pages[0];
71
+ const description = primary?.facts?.description ?? '';
72
+ if (description) {
73
+ lines.push(`> ${description}`);
74
+ } else {
75
+ // Never invent a summary; state the absence instead.
76
+ lines.push(`> ${name} — generated index. No meta description was found on the entry page, so no summary is provided.`);
77
+ }
78
+ lines.push('');
79
+ lines.push(LLMS_NOTE);
80
+ lines.push('');
81
+
82
+ // Core pages: the entry page plus every crawled page that carries real content.
83
+ const withContent = pages.filter((page) => (page.facts.contentLength ?? page.facts.textLength) >= 200);
84
+ const core = (withContent.length > 0 ? withContent : pages).slice(0, maxLinks);
85
+
86
+ lines.push('## Pages');
87
+ lines.push('');
88
+ for (const page of core) {
89
+ lines.push(`- [${pageTitle(page)}](${trimSlash(page.url)})`);
90
+ }
91
+ if (pages.length > core.length) {
92
+ lines.push(`- … ${pages.length - core.length} more page(s) were crawled but not listed`);
93
+ }
94
+ lines.push('');
95
+
96
+ // Section-level index from the entry page: real headings only.
97
+ if (primary && (primary.facts.sections ?? []).length > 0) {
98
+ const headings = primary.facts.sections.filter((section) => section.level >= 2 && section.heading.length > 0);
99
+ if (headings.length > 0) {
100
+ lines.push('## Sections');
101
+ lines.push('');
102
+ for (const section of headings.slice(0, maxLinks)) {
103
+ const anchor = section.id ? `${trimSlash(primary.url)}#${section.id}` : trimSlash(primary.url);
104
+ const answer = firstAnswer(section, 160);
105
+ lines.push(`- [${section.heading}](${anchor})${answer ? ` — ${answer}` : ''}`);
106
+ }
107
+ lines.push('');
108
+ }
109
+ }
110
+
111
+ const sitemap = scan.sitemap?.valid ? scan.sitemap.url : null;
112
+ lines.push('## Machine-readable resources');
113
+ lines.push('');
114
+ if (sitemap) lines.push(`- [sitemap](${trimSlash(sitemap)})`);
115
+ lines.push(`- [robots.txt](${trimSlash(new URL('/robots.txt', scan.origin).href)})`);
116
+ lines.push('');
117
+
118
+ const content = `${lines.join('\n').trimEnd()}\n`;
119
+ return {
120
+ content,
121
+ sections: (content.match(/^## /gm) ?? []).length,
122
+ links: (content.match(/^- \[/gm) ?? []).length,
123
+ sourcePages: core.length,
124
+ };
125
+ }
126
+
127
+ /**
128
+ * Build FAQPage JSON-LD from question-shaped headings that have a real answer.
129
+ *
130
+ * Only headings that already exist on a crawled page are used, and each answer
131
+ * is that section's own prose. A site with no question headings yields no
132
+ * document at all rather than a fabricated FAQ.
133
+ *
134
+ * @param {object} scan - Scan artifact.
135
+ * @param {{maxItems?: number}} [options]
136
+ * @returns {{json: object|null, items: Array<{question: string, answer: string, url: string}>, skipped: string|null}}
137
+ */
138
+ export function generateFaqJsonLd(scan, options = {}) {
139
+ const maxItems = options.maxItems ?? 20;
140
+ const pages = (scan.pages ?? []).filter((page) => page.facts && page.status === 200);
141
+ const items = [];
142
+
143
+ for (const page of pages) {
144
+ for (const section of page.facts.sections ?? []) {
145
+ if (items.length >= maxItems) break;
146
+ if (!isQuestion(section.heading)) continue;
147
+ const answer = firstAnswer(section, 600);
148
+ // A question with no prose is not an FAQ entry; the answer must exist.
149
+ if (answer.length < 30) continue;
150
+ items.push({ question: section.heading, answer, url: trimSlash(page.url) });
151
+ }
152
+ if (items.length >= maxItems) break;
153
+ }
154
+
155
+ if (items.length === 0) {
156
+ return {
157
+ json: null,
158
+ items: [],
159
+ skipped: 'No question-shaped heading with a real answer was found, so no FAQPage document was generated.',
160
+ };
161
+ }
162
+
163
+ return {
164
+ json: {
165
+ '@context': 'https://schema.org',
166
+ '@type': 'FAQPage',
167
+ mainEntity: items.map((item) => ({
168
+ '@type': 'Question',
169
+ name: item.question,
170
+ acceptedAnswer: { '@type': 'Answer', text: item.answer },
171
+ })),
172
+ },
173
+ items,
174
+ skipped: null,
175
+ };
176
+ }
177
+
178
+ export { LLMS_NOTE, FAQ_NOTE, isQuestion };
package/lib/html.js CHANGED
@@ -421,11 +421,16 @@ export function analyzeHtml(html, pageUrl) {
421
421
  const src = attribute(node, 'src');
422
422
  if (!src && !attribute(node, 'srcset')) continue;
423
423
  const alt = attribute(node, 'alt');
424
+ const width = Number(attribute(node, 'width'));
425
+ const height = Number(attribute(node, 'height'));
424
426
  images.push({
425
427
  src: (resolveUrl(src ?? '', baseUrl) ?? src ?? '').slice(0, 2048),
426
428
  alt,
427
429
  hasAlt: typeof alt === 'string',
428
430
  decorative: attribute(node, 'role') === 'presentation' || alt === '',
431
+ lazy: (attribute(node, 'loading') ?? '').toLowerCase() === 'lazy',
432
+ hasDimensions: Number.isFinite(width) && width > 0 && Number.isFinite(height) && height > 0,
433
+ responsive: Boolean(attribute(node, 'srcset')),
429
434
  });
430
435
  }
431
436
 
@@ -434,6 +439,11 @@ export function analyzeHtml(html, pageUrl) {
434
439
  const paragraphs = [];
435
440
  const snippetCandidates = [];
436
441
  const headingIds = [];
442
+ // Sections group a heading with the prose that follows it. They are what the
443
+ // llms.txt and FAQ generators read: both must be able to quote the page, never
444
+ // invent content it does not contain.
445
+ const sections = [];
446
+ let currentSection = null;
437
447
  let pendingHeading = null;
438
448
  for (const node of nodes) {
439
449
  const level = HEADING_LEVEL[node.tag];
@@ -446,6 +456,8 @@ export function analyzeHtml(html, pageUrl) {
446
456
  if (id) headingIds.push(id);
447
457
  lastHeading = level;
448
458
  pendingHeading = headingText;
459
+ currentSection = { level, heading: headingText.slice(0, 300), id, paragraphs: [] };
460
+ sections.push(currentSection);
449
461
  continue;
450
462
  }
451
463
  if (node.tag === 'p') {
@@ -454,19 +466,42 @@ export function analyzeHtml(html, pageUrl) {
454
466
  if (!text) continue;
455
467
  const words = countWords(text);
456
468
  paragraphs.push({ text: text.slice(0, 1000), words, afterHeading: lastHeading });
469
+ if (currentSection) currentSection.paragraphs.push(text.slice(0, 1000));
457
470
  if (pendingHeading !== null && words >= 30 && words <= 140) {
458
471
  snippetCandidates.push({ heading: pendingHeading.slice(0, 200), words });
459
472
  }
460
473
  pendingHeading = null;
461
474
  }
475
+ // A list or table directly under a heading carries answers too.
476
+ if (currentSection && (node.tag === 'ul' || node.tag === 'ol' || node.tag === 'dl' || node.tag === 'table')) {
477
+ const blockText = textOf(node);
478
+ if (blockText) currentSection.paragraphs.push(blockText.slice(0, 1000));
479
+ }
462
480
  }
463
481
 
464
482
  const bodyText = textOf(body ?? doc);
465
- const contentRoot = findFirst(doc, (node) => node.tag === 'article')
466
- ?? findFirst(doc, (node) => node.tag === 'main')
467
- ?? body
468
- ?? doc;
469
- const contentText = textOf(contentRoot);
483
+
484
+ // Picking the first <article>/<main> is wrong on real pages: a card or a
485
+ // decorative wrapper often comes first, which makes a content-rich page look
486
+ // like a JavaScript shell. Take the largest candidate instead, and fall back
487
+ // to the body when no semantic container actually holds the content.
488
+ const containers = [];
489
+ walk(doc, (node) => {
490
+ if (node.tag === 'article' || node.tag === 'main') containers.push(node);
491
+ });
492
+ let contentRoot = null;
493
+ let contentText = '';
494
+ for (const candidate of containers) {
495
+ const text = textOf(candidate);
496
+ if (text.length > contentText.length) {
497
+ contentText = text;
498
+ contentRoot = candidate;
499
+ }
500
+ }
501
+ if (contentText.length < bodyText.length * 0.5) {
502
+ contentRoot = body ?? doc;
503
+ contentText = bodyText;
504
+ }
470
505
  const noscriptText = nodes
471
506
  .filter((node) => node.tag === 'noscript')
472
507
  .map((node) => textOf(node))
@@ -494,12 +529,17 @@ export function analyzeHtml(html, pageUrl) {
494
529
  alternateLinks.push({
495
530
  rel,
496
531
  type: (attribute(node, 'type') ?? '').toLowerCase(),
532
+ hreflang: attribute(node, 'hreflang'),
497
533
  href: (resolveUrl(href, baseUrl) ?? href).slice(0, 2048),
498
534
  });
499
535
  }
500
536
  if (rel.includes('me') && href) relMe.push((resolveUrl(href, baseUrl) ?? href).slice(0, 2048));
501
537
  }
502
538
 
539
+ const hreflangs = alternateLinks
540
+ .filter((link) => link.rel.includes('alternate') && Boolean(link.hreflang))
541
+ .map((link) => link.hreflang);
542
+
503
543
  const times = [];
504
544
  for (const node of nodes) {
505
545
  if (node.tag !== 'time') continue;
@@ -629,6 +669,7 @@ export function analyzeHtml(html, pageUrl) {
629
669
  metasAuthor: meta.author ?? null,
630
670
  bylines: [...new Set(bylines)],
631
671
  alternateLinks,
672
+ hreflangs: [...new Set(hreflangs)],
632
673
  relMe: [...new Set(relMe)],
633
674
  times,
634
675
  scriptBytes,
@@ -638,6 +679,7 @@ export function analyzeHtml(html, pageUrl) {
638
679
  dataNosnippetCount: nodes.filter((node) => node.attrs && 'data-nosnippet' in node.attrs).length,
639
680
  metaBingbot: (meta.bingbot ?? '').toLowerCase(),
640
681
  questionHeadings,
682
+ sections: sections.filter((section) => section.heading.length > 0),
641
683
  snippetBlockCount: snippetCandidates.length,
642
684
  // A shell has scripts but no readable structure at all. This is a
643
685
  // diagnostic; rules score the actual text length and heading structure.
package/lib/mcp.js CHANGED
@@ -56,6 +56,34 @@ export const MCP_TOOLS = [
56
56
  },
57
57
  },
58
58
  },
59
+ {
60
+ name: 'geo_generate_llms',
61
+ description:
62
+ 'Build an llms.txt from the pages that were actually crawled: the page list and section index come from real headings, and nothing is invented. Google Search does not use llms.txt; the generated file says so. A generator, not a fix: review the output before publishing it.',
63
+ inputSchema: {
64
+ type: 'object',
65
+ properties: {
66
+ url: { type: 'string', description: 'Absolute http(s) URL of the site entry page.' },
67
+ max_pages: { type: 'integer', minimum: 1, maximum: 50, description: 'Pages to crawl (default 6).' },
68
+ now: { type: 'string', description: 'ISO-8601 reference time for freshness checks.' },
69
+ },
70
+ required: ['url'],
71
+ },
72
+ },
73
+ {
74
+ name: 'geo_generate_faq',
75
+ description:
76
+ 'Build FAQPage JSON-LD from question-shaped headings that already have a real answer on the page. Returns no document when the site has none, instead of fabricating questions. Google restricted FAQ rich results to authoritative government and health sites in August 2023, so this markup does not earn rich results for most sites.',
77
+ inputSchema: {
78
+ type: 'object',
79
+ properties: {
80
+ url: { type: 'string', description: 'Absolute http(s) URL of the site entry page.' },
81
+ max_pages: { type: 'integer', minimum: 1, maximum: 50, description: 'Pages to crawl (default 6).' },
82
+ now: { type: 'string', description: 'ISO-8601 reference time for freshness checks.' },
83
+ },
84
+ required: ['url'],
85
+ },
86
+ },
59
87
  {
60
88
  name: 'geo_history',
61
89
  description: 'List recent saved audits for this workspace, newest first, with totals and grades.',
@@ -143,6 +171,36 @@ export async function callTool(name, args, context) {
143
171
  return { content: [{ type: 'text', text: lines.join('\n') }] };
144
172
  }
145
173
 
174
+ if (name === 'geo_generate_llms' || name === 'geo_generate_faq') {
175
+ const url = assertString(input.url, 'url');
176
+ const { scan } = await auditSite(url, {
177
+ maxPages: input.max_pages,
178
+ now: input.now ?? undefined,
179
+ allowPrivate: context.allowPrivate === true,
180
+ insecureTls: context.insecureTls === true,
181
+ });
182
+ const { generateLlmsTxt, generateFaqJsonLd, FAQ_NOTE } = await import('./generate.js');
183
+ if (name === 'geo_generate_llms') {
184
+ const llms = generateLlmsTxt(scan);
185
+ return {
186
+ content: [{
187
+ type: 'text',
188
+ text: `${llms.content}\n---\n${llms.links} link(s) from ${llms.sourcePages} crawled page(s). Review before publishing; this tool does not change the site.`,
189
+ }],
190
+ };
191
+ }
192
+ const faq = generateFaqJsonLd(scan);
193
+ if (!faq.json) {
194
+ return { content: [{ type: 'text', text: faq.skipped }] };
195
+ }
196
+ return {
197
+ content: [{
198
+ type: 'text',
199
+ text: `${JSON.stringify(faq.json, null, 2)}\n\n${faq.items.length} item(s). ${FAQ_NOTE}`,
200
+ }],
201
+ };
202
+ }
203
+
146
204
  if (name === 'geo_history') {
147
205
  const limit = input.limit === undefined ? 10 : input.limit;
148
206
  if (!Number.isInteger(limit) || limit < 1 || limit > 50) throw new Error('limit must be an integer between 1 and 50');
package/lib/report.js CHANGED
@@ -291,6 +291,18 @@ export function renderAuditMarkdown(report, context = {}) {
291
291
  lines.push(`检查项合计:通过 ${report.counts.pass} / 部分 ${report.counts.warn} / 失败 ${report.counts.fail} / 不适用 ${report.counts.skip}`);
292
292
  lines.push('');
293
293
 
294
+ if (Array.isArray(report.pillars) && report.pillars.length > 0) {
295
+ lines.push('## 三个支柱(同一批规则的第二个视图)');
296
+ lines.push('');
297
+ lines.push('| 支柱 | 分数 | 检查项 | 通过 | 部分 | 失败 |');
298
+ lines.push('|---|---|---|---|---|---|');
299
+ for (const pillar of report.pillars) {
300
+ const { pass, warn, fail } = pillar.counts;
301
+ lines.push(`| ${pillar.title} | ${pillar.score} | ${pillar.ruleCount} | ${pass} | ${warn} | ${fail} |`);
302
+ }
303
+ lines.push('');
304
+ }
305
+
294
306
  if (Array.isArray(report.platforms) && report.platforms.length > 0) {
295
307
  lines.push('## 平台适配(参考,不计入 Core 总分)');
296
308
  lines.push('');
@@ -381,6 +393,12 @@ export function summarizeReport(report, options = {}) {
381
393
  weight: dimension.weight,
382
394
  score: dimension.score,
383
395
  })),
396
+ pillars: (report.pillars ?? []).map((pillar) => ({
397
+ id: pillar.id,
398
+ title: pillar.title,
399
+ score: pillar.score,
400
+ counts: pillar.counts,
401
+ })),
384
402
  platforms: (report.platforms ?? []).map((platform) => ({
385
403
  id: platform.id,
386
404
  title: platform.title,