@cobola/dsh-geo 0.0.0-stage → 0.2.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,62 @@
1
+ /**
2
+ * Platform evidence registry. Profiles are metadata and source boundaries, not
3
+ * extra score weight. A profile may later add platform-specific checks without
4
+ * contaminating the Core score.
5
+ */
6
+ export const PLATFORM_PROFILES = Object.freeze({
7
+ core: Object.freeze({
8
+ id: 'core', title: '跨平台基础', maturity: 'implemented',
9
+ sources: [],
10
+ scope: 'crawlability, indexability, page structure, duplicate URLs, entity clarity',
11
+ }),
12
+ google: Object.freeze({
13
+ id: 'google', title: 'Google Search / AI features', maturity: 'implemented',
14
+ sources: ['https://developers.google.com/search/docs/fundamentals/ai-optimization-guide'],
15
+ scope: 'Googlebot access, Search technical requirements, people-first content, Google-specific controls',
16
+ }),
17
+ bing: Object.freeze({
18
+ id: 'bing', title: 'Bing / Copilot', maturity: 'source-mapped',
19
+ sources: [
20
+ 'https://www.bing.com/webmasters/help/webmaster-guidelines-30fba23a',
21
+ 'https://www.bing.com/webmasters/help/robots-meta-tags-and-attributes-that-bing-supports-5198d240',
22
+ 'https://www.bing.com/indexnow',
23
+ ],
24
+ scope: 'Bingbot, Copilot grounding, data-nosnippet, AI controls, IndexNow',
25
+ }),
26
+ baidu: Object.freeze({
27
+ id: 'baidu', title: '百度搜索', maturity: 'source-mapped',
28
+ sources: [
29
+ 'https://ziyuan.baidu.com/college/articleinfo?id=193undefinedpage%3D1&page=6',
30
+ 'https://ziyuan.baidu.com/college/courseinfo?id=1399',
31
+ ],
32
+ scope: 'Baiduspider, 百度搜索资源平台, sitemap/submission, Chinese search crawlability',
33
+ limitation: '百度 AI 引用选择标准没有完整公开;不把推测当作规则。',
34
+ }),
35
+ openai: Object.freeze({
36
+ id: 'openai', title: 'OpenAI Search', maturity: 'source-mapped',
37
+ sources: ['https://developers.openai.com/api/docs/bots'],
38
+ scope: 'OAI-SearchBot vs GPTBot access controls',
39
+ limitation: '不推导未公开的 ChatGPT 引用排序公式。',
40
+ }),
41
+ perplexity: Object.freeze({
42
+ id: 'perplexity', title: 'Perplexity', maturity: 'source-mapped',
43
+ sources: ['https://docs.perplexity.ai/docs/resources/perplexity-crawlers'],
44
+ scope: 'Perplexity crawler identity, robots and fetchability',
45
+ limitation: '不推导未公开的引用排序公式。',
46
+ }),
47
+ });
48
+
49
+ export function listProfiles() {
50
+ return Object.values(PLATFORM_PROFILES).map((profile) => ({
51
+ id: profile.id,
52
+ title: profile.title,
53
+ maturity: profile.maturity,
54
+ scope: profile.scope,
55
+ sources: [...profile.sources],
56
+ ...(profile.limitation ? { limitation: profile.limitation } : {}),
57
+ }));
58
+ }
59
+
60
+ export function profileById(id) {
61
+ return PLATFORM_PROFILES[id] ?? null;
62
+ }
package/lib/report.js ADDED
@@ -0,0 +1,353 @@
1
+ /**
2
+ * Human reports, fix plans, and scan-to-scan diffs.
3
+ *
4
+ * Everything here is a pure function of score reports (plus the scan artifact
5
+ * for header facts), so the Markdown and JSON written to `.dsh-geo/` are
6
+ * reproducible for the same input.
7
+ */
8
+
9
+ export const REPORT_FORMAT_VERSION = 1;
10
+
11
+ const DIMENSION_WEIGHTS = {
12
+ discoverability: 25,
13
+ parsability: 20,
14
+ citability: 25,
15
+ trust: 15,
16
+ manifest: 15,
17
+ };
18
+
19
+ const STATUS_LABEL = {
20
+ pass: '通过',
21
+ warn: '部分通过',
22
+ fail: '失败',
23
+ skip: '不适用',
24
+ };
25
+
26
+ const STATUS_FACTOR = { pass: 1, warn: 0.5, fail: 0, skip: 0 };
27
+
28
+ function round1(value) {
29
+ return Math.round(value * 10) / 10;
30
+ }
31
+
32
+ function signed(value) {
33
+ if (value > 0) return `+${value}`;
34
+ return String(value);
35
+ }
36
+
37
+ function siteHost(url) {
38
+ try {
39
+ return new URL(url).hostname.replace(/^www\./, '').toLowerCase();
40
+ } catch {
41
+ return String(url ?? '').toLowerCase();
42
+ }
43
+ }
44
+
45
+ /** Two reports can be compared only when they audit the same site. */
46
+ export function comparableSites(previousUrl, currentUrl) {
47
+ return siteHost(previousUrl) === siteHost(currentUrl);
48
+ }
49
+
50
+ /**
51
+ * Compare a previous score report with the current one.
52
+ * @param {object} previous
53
+ * @param {object} current
54
+ * @returns {object|null} null when either side is missing.
55
+ */
56
+ export function diffReports(previous, current) {
57
+ if (!previous || !current) return null;
58
+
59
+ const before = new Map(previous.findings.map((finding) => [finding.id, finding.status]));
60
+ const fixed = [];
61
+ const regressed = [];
62
+ const changed = [];
63
+ let stillFailing = 0;
64
+
65
+ for (const finding of current.findings) {
66
+ const was = before.get(finding.id);
67
+ if (was === undefined) continue;
68
+ const now = finding.status;
69
+ if (was === now) {
70
+ if (now !== 'pass' && now !== 'skip') stillFailing += 1;
71
+ continue;
72
+ }
73
+ if (now === 'pass') {
74
+ if (was !== 'skip') fixed.push({ ruleId: finding.id, title: finding.title, dimension: finding.dimension, from: was });
75
+ } else if (was === 'pass') {
76
+ regressed.push({ ruleId: finding.id, title: finding.title, dimension: finding.dimension, to: now });
77
+ } else if ((STATUS_FACTOR[now] ?? 0) > (STATUS_FACTOR[was] ?? 0)) {
78
+ changed.push({ ruleId: finding.id, title: finding.title, dimension: finding.dimension, from: was, to: now, direction: 'up' });
79
+ } else {
80
+ changed.push({ ruleId: finding.id, title: finding.title, dimension: finding.dimension, from: was, to: now, direction: 'down' });
81
+ }
82
+ }
83
+
84
+ return {
85
+ previous: {
86
+ startUrl: previous.startUrl,
87
+ scannedAt: previous.scannedAt,
88
+ total: previous.total,
89
+ grade: previous.grade,
90
+ },
91
+ total: {
92
+ before: previous.total,
93
+ after: current.total,
94
+ delta: round1(current.total - previous.total),
95
+ },
96
+ dimensions: current.dimensions.map((dimension) => {
97
+ const old = previous.dimensions.find((entry) => entry.id === dimension.id);
98
+ const beforeScore = old ? old.score : 0;
99
+ return {
100
+ id: dimension.id,
101
+ title: dimension.title,
102
+ before: beforeScore,
103
+ after: dimension.score,
104
+ delta: round1(dimension.score - beforeScore),
105
+ };
106
+ }),
107
+ fixed,
108
+ regressed,
109
+ changed,
110
+ counts: {
111
+ fixed: fixed.length,
112
+ regressed: regressed.length,
113
+ changed: changed.length,
114
+ stillFailing,
115
+ },
116
+ };
117
+ }
118
+
119
+ function escapeInline(value) {
120
+ return String(value ?? '').replace(/\s+/g, ' ').trim();
121
+ }
122
+
123
+ /**
124
+ * A prioritized, grouped repair list derived from every non-pass finding.
125
+ * @param {object} report
126
+ * @param {{scan?: object, diff?: object|null}} [context]
127
+ */
128
+ export function buildFixPlan(report, context = {}) {
129
+ const { scan = null, diff = null } = context;
130
+ const actions = report.findings
131
+ .filter((finding) => finding.status === 'fail' || finding.status === 'warn')
132
+ .map((finding) => {
133
+ const dimensionWeight = DIMENSION_WEIGHTS[finding.dimension] ?? 0;
134
+ const factor = finding.status === 'fail' ? 1 : 0.5;
135
+ return {
136
+ ruleId: finding.id,
137
+ dimension: finding.dimension,
138
+ dimensionTitle: report.dimensions.find((dimension) => dimension.id === finding.dimension)?.title ?? finding.dimension,
139
+ title: finding.title,
140
+ status: finding.status,
141
+ weight: finding.weight,
142
+ impact: round1(factor * finding.weight * dimensionWeight),
143
+ evidence: escapeInline(finding.evidence),
144
+ fix: escapeInline(finding.fix),
145
+ verify: `重新扫描后规则 \`${finding.id}\` 应为 pass`,
146
+ };
147
+ })
148
+ .sort((a, b) => b.impact - a.impact || (a.ruleId < b.ruleId ? -1 : a.ruleId > b.ruleId ? 1 : 0));
149
+
150
+ const dimensionOrder = report.dimensions.map((dimension) => dimension.id);
151
+ actions.sort((a, b) => b.impact - a.impact
152
+ || dimensionOrder.indexOf(a.dimension) - dimensionOrder.indexOf(b.dimension)
153
+ || (a.ruleId < b.ruleId ? -1 : a.ruleId > b.ruleId ? 1 : 0));
154
+
155
+ const generatedAt = scan?.scannedAt ?? report.scannedAt ?? null;
156
+ const payload = {
157
+ formatVersion: REPORT_FORMAT_VERSION,
158
+ generatedAt,
159
+ url: report.startUrl,
160
+ rubricVersion: report.rubricVersion,
161
+ score: { total: report.total, grade: report.grade, gradeLabel: report.gradeLabel },
162
+ previous: diff ? diff.previous : null,
163
+ actionCount: actions.length,
164
+ actions,
165
+ };
166
+
167
+ return {
168
+ actions,
169
+ json: payload,
170
+ markdown: renderFixPlanMarkdown(report, actions, { scan, diff }),
171
+ };
172
+ }
173
+
174
+ function renderFixPlanMarkdown(report, actions, { scan, diff }) {
175
+ const lines = [];
176
+ lines.push(`# GEO 修复清单 — ${report.startUrl}`);
177
+ lines.push('');
178
+ const facts = [
179
+ `总分 **${report.total} / 100**(${report.grade} ${report.gradeLabel})`,
180
+ `规则版本 \`${report.rubricVersion}\``,
181
+ ];
182
+ if (scan?.scannedAt) facts.push(`扫描时间 ${scan.scannedAt}`);
183
+ if (scan?.stats) facts.push(`抓取 ${scan.stats.pages} 页 / ${scan.stats.requested} 个请求`);
184
+ if (diff) facts.push(`对照上次 ${diff.previous.scannedAt} ${diff.previous.total} → ${report.total}(${signed(diff.total.delta)})`);
185
+ lines.push(`> ${facts.join(' · ')}`);
186
+ lines.push('');
187
+ lines.push('按影响力排序,先做前面的项。每项都给出证据与验收条件;改完用同一规则复扫确认。');
188
+ lines.push('');
189
+
190
+ if (diff) {
191
+ lines.push('## 与上次扫描相比');
192
+ lines.push('');
193
+ const fixedList = diff.fixed.length > 0 ? diff.fixed.map((entry) => `\`${entry.ruleId}\``).join('、') : '无';
194
+ const regressedList = diff.regressed.length > 0 ? diff.regressed.map((entry) => `\`${entry.ruleId}\``).join('、') : '无';
195
+ lines.push(`- 已修复:${fixedList}`);
196
+ lines.push(`- 出现回归:${regressedList}`);
197
+ lines.push(`- 仍未通过:${diff.counts.stillFailing} 项`);
198
+ lines.push('');
199
+ }
200
+
201
+ if (actions.length === 0) {
202
+ lines.push('## 结论');
203
+ lines.push('');
204
+ lines.push('所有检查项均已通过,没有需要修复的项。保持当前结构,并在每次内容或模板改动后复扫。');
205
+ lines.push('');
206
+ return `${lines.join('\n')}\n`;
207
+ }
208
+
209
+ lines.push('## 修复顺序');
210
+ lines.push('');
211
+ const top = actions.slice(0, 5);
212
+ top.forEach((action, index) => {
213
+ lines.push(`${index + 1}. **${action.dimensionTitle} / ${action.title}**(${STATUS_LABEL[action.status]},权重 ${action.weight})`);
214
+ lines.push(` - 证据:${action.evidence}`);
215
+ lines.push(` - 做法:${action.fix}`);
216
+ lines.push(` - 验收:${action.verify}`);
217
+ });
218
+ lines.push('');
219
+
220
+ const dimensions = report.dimensions;
221
+ for (const dimension of dimensions) {
222
+ const own = actions.filter((action) => action.dimension === dimension.id);
223
+ if (own.length === 0) continue;
224
+ lines.push(`## ${dimension.title}(${dimension.score} / 100,权重 ${dimension.weight})`);
225
+ lines.push('');
226
+ for (const action of own) {
227
+ lines.push(`### [${action.ruleId}] ${action.title}`);
228
+ lines.push('');
229
+ lines.push(`- 状态:${STATUS_LABEL[action.status]}(权重 ${action.weight})`);
230
+ lines.push(`- 证据:${action.evidence}`);
231
+ lines.push(`- 做法:${action.fix}`);
232
+ lines.push(`- 验收:${action.verify}`);
233
+ lines.push('');
234
+ }
235
+ }
236
+
237
+ lines.push('## 复扫');
238
+ lines.push('');
239
+ lines.push('改完代码后,用同一个站点与同一个参考时间复扫,才能把分数变化归因到改动本身:');
240
+ lines.push('');
241
+ lines.push('```sh');
242
+ lines.push(`dsh-geo scan ${report.startUrl} --save --now ${scan?.scannedAt ?? '<首次扫描时间>'}`);
243
+ lines.push('dsh-geo diff .dsh-geo/history/<改动前>.json .dsh-geo/latest.json');
244
+ lines.push('```');
245
+ lines.push('');
246
+ lines.push('或者在 agent 会话里重新运行 `geo_scan`,报告会自动写入 `.dsh-geo/` 并与上次对比。');
247
+ lines.push('');
248
+ return `${lines.join('\n')}\n`;
249
+ }
250
+
251
+ /**
252
+ * Markdown summary for one audit, written to `.dsh-geo/report.md`.
253
+ * @param {object} report
254
+ * @param {{scan?: object, diff?: object|null}} [context]
255
+ */
256
+ export function renderAuditMarkdown(report, context = {}) {
257
+ const { scan = null, diff = null } = context;
258
+ const lines = [];
259
+ lines.push(`# GEO 体检报告 — ${report.startUrl}`);
260
+ lines.push('');
261
+ lines.push(`> 总分 **${report.total} / 100**(${report.grade} ${report.gradeLabel})· 规则 \`${report.rubricVersion}\`${scan?.scannedAt ? ` · 扫描时间 ${scan.scannedAt}` : ''}`);
262
+ lines.push('');
263
+ if (report.blockedByRobots) {
264
+ lines.push('> **robots.txt 拒绝了扫描 UA**,本次没有抓取任何页面。修复 robots 或经所有者确认后使用 `--no-robots` 重扫。');
265
+ lines.push('');
266
+ }
267
+ lines.push('## 五维得分');
268
+ lines.push('');
269
+ lines.push('| 维度 | 得分 | 权重 | 通过 | 部分 | 失败 | 不适用 |');
270
+ lines.push('|---|---|---|---|---|---|---|');
271
+ for (const dimension of report.dimensions) {
272
+ const { pass, warn, fail, skip } = dimension.counts;
273
+ lines.push(`| ${dimension.title} | ${dimension.score} | ${dimension.weight} | ${pass} | ${warn} | ${fail} | ${skip} |`);
274
+ }
275
+ lines.push('');
276
+ lines.push(`检查项合计:通过 ${report.counts.pass} / 部分 ${report.counts.warn} / 失败 ${report.counts.fail} / 不适用 ${report.counts.skip}`);
277
+ lines.push('');
278
+
279
+ if (diff) {
280
+ lines.push('## 对照上次');
281
+ lines.push('');
282
+ lines.push(`上次 ${diff.previous.scannedAt}:${diff.previous.total} → 本次 ${report.total}(${signed(diff.total.delta)})`);
283
+ lines.push('');
284
+ for (const dimension of diff.dimensions) {
285
+ if (dimension.delta === 0) continue;
286
+ lines.push(`- ${dimension.title}:${dimension.before} → ${dimension.after}(${signed(dimension.delta)})`);
287
+ }
288
+ if (diff.regressed.length > 0) {
289
+ lines.push('');
290
+ lines.push(`**回归项:** ${diff.regressed.map((entry) => `\`${entry.ruleId}\``).join('、')}`);
291
+ }
292
+ lines.push('');
293
+ }
294
+
295
+ const top = report.actions.slice(0, 8);
296
+ if (top.length > 0) {
297
+ lines.push('## 优先修复');
298
+ lines.push('');
299
+ top.forEach((action, index) => {
300
+ lines.push(`${index + 1}. **${action.dimensionTitle} · ${action.title}** — ${action.evidence}`);
301
+ lines.push(` ${action.fix}`);
302
+ });
303
+ lines.push('');
304
+ }
305
+
306
+ if (scan?.stats) {
307
+ lines.push('## 抓取概况');
308
+ lines.push('');
309
+ lines.push(`- 页面:${scan.stats.pages}(请求 ${scan.stats.requested} 次,传输 ${scan.stats.bytes} 字节)`);
310
+ lines.push(`- robots.txt:${scan.robots?.found ? '存在' : '不存在'}`);
311
+ lines.push(`- sitemap:${scan.sitemap?.valid ? `${scan.sitemap.urlCount} 个 URL` : '无可用 sitemap'}`);
312
+ lines.push(`- llms.txt:${scan.llms?.found ? (scan.llms.valid ? '有效' : '存在但结构无效') : '不存在'}`);
313
+ if (scan.errors?.length > 0) {
314
+ lines.push(`- 抓取错误:${scan.errors.length} 条(详见 latest.json 的 \`errors\`)`);
315
+ }
316
+ lines.push('');
317
+ }
318
+
319
+ lines.push('完整的机器可读结果见 `.dsh-geo/latest.json`,修复清单见 `.dsh-geo/fix-plan.md`。');
320
+ lines.push('');
321
+ return lines.join('\n');
322
+ }
323
+
324
+ /**
325
+ * Compact, model-facing summary of a score report.
326
+ * @param {object} report
327
+ * @param {{limit?: number}} [options]
328
+ */
329
+ export function summarizeReport(report, options = {}) {
330
+ const limit = options.limit ?? 5;
331
+ return {
332
+ total: report.total,
333
+ grade: report.grade,
334
+ gradeLabel: report.gradeLabel,
335
+ counts: report.counts,
336
+ dimensions: report.dimensions.map((dimension) => ({
337
+ id: dimension.id,
338
+ title: dimension.title,
339
+ weight: dimension.weight,
340
+ score: dimension.score,
341
+ })),
342
+ topActions: report.actions.slice(0, limit).map((action) => ({
343
+ ruleId: action.ruleId,
344
+ dimension: action.dimension,
345
+ dimensionTitle: action.dimensionTitle,
346
+ title: action.title,
347
+ status: action.status,
348
+ weight: action.weight,
349
+ evidence: action.evidence,
350
+ fix: action.fix,
351
+ })),
352
+ };
353
+ }
package/lib/robots.js ADDED
@@ -0,0 +1,198 @@
1
+ /**
2
+ * Minimal, deterministic robots.txt handling (RFC 9309 semantics).
3
+ *
4
+ * Only what an audit needs: group parsing, UA selection, longest-match path
5
+ * rules, Allow-over-Disallow ties, crawl-delay, sitemap declarations, and a
6
+ * per-crawler verdict for the AI agents a GEO audit cares about.
7
+ */
8
+
9
+ export const AI_CRAWLERS = [
10
+ 'gptbot',
11
+ 'oai-searchbot',
12
+ 'chatgpt-user',
13
+ 'claudebot',
14
+ 'anthropic-ai',
15
+ 'perplexitybot',
16
+ 'google-extended',
17
+ 'ccbot',
18
+ 'bytespider',
19
+ 'applebot-extended',
20
+ ];
21
+
22
+ /**
23
+ * @param {string} text robots.txt body.
24
+ * @returns {{groups: Array<{agents: string[], rules: Array<{allow: boolean, path: string}>, crawlDelay: number|null}>, sitemaps: string[], hasRules: boolean}}
25
+ */
26
+ export function parseRobots(text) {
27
+ const groups = [];
28
+ const sitemaps = [];
29
+ let current = null;
30
+ let seenDirective = false;
31
+
32
+ for (const rawLine of String(text ?? '').split(/\r?\n/)) {
33
+ const line = rawLine.replace(/#.*$/, '').trim();
34
+ if (!line) continue;
35
+ const separator = line.indexOf(':');
36
+ if (separator === -1) continue;
37
+ const field = line.slice(0, separator).trim().toLowerCase();
38
+ const value = line.slice(separator + 1).trim();
39
+
40
+ if (field === 'user-agent') {
41
+ if (!current || seenDirective) {
42
+ current = { agents: [], rules: [], crawlDelay: null };
43
+ groups.push(current);
44
+ seenDirective = false;
45
+ }
46
+ current.agents.push(value.toLowerCase());
47
+ continue;
48
+ }
49
+
50
+ if (field === 'sitemap') {
51
+ if (value) sitemaps.push(value);
52
+ continue;
53
+ }
54
+
55
+ if (field === 'allow' || field === 'disallow') {
56
+ if (!current) {
57
+ current = { agents: ['*'], rules: [], crawlDelay: null };
58
+ groups.push(current);
59
+ }
60
+ seenDirective = true;
61
+ if (value) current.rules.push({ allow: field === 'allow', path: value });
62
+ continue;
63
+ }
64
+
65
+ if (field === 'crawl-delay') {
66
+ if (!current) continue;
67
+ seenDirective = true;
68
+ const delay = Number(value);
69
+ if (Number.isFinite(delay) && delay >= 0) current.crawlDelay = delay;
70
+ }
71
+ }
72
+
73
+ return {
74
+ groups,
75
+ sitemaps,
76
+ hasRules: groups.some((group) => group.rules.length > 0),
77
+ };
78
+ }
79
+
80
+ function uaTokens(userAgent) {
81
+ return String(userAgent ?? '')
82
+ .toLowerCase()
83
+ .split(/[\s/()]+/)
84
+ .filter(Boolean);
85
+ }
86
+
87
+ function selectGroups(robots, userAgent) {
88
+ const tokens = uaTokens(userAgent);
89
+ const matches = (agent) => tokens.some((token) => token === agent || token.startsWith(`${agent}/`));
90
+ let bestLength = -1;
91
+ const matched = [];
92
+ for (const group of robots.groups) {
93
+ for (const agent of group.agents) {
94
+ if (agent === '*') continue;
95
+ if (matches(agent) && agent.length > bestLength) {
96
+ bestLength = agent.length;
97
+ matched.length = 0;
98
+ matched.push(group);
99
+ } else if (matches(agent) && agent.length === bestLength && !matched.includes(group)) {
100
+ matched.push(group);
101
+ }
102
+ }
103
+ }
104
+ if (matched.length > 0) return matched;
105
+ return robots.groups.filter((group) => group.agents.includes('*'));
106
+ }
107
+
108
+ function ruleMatches(pattern, path) {
109
+ if (!pattern) return false;
110
+ const anchored = pattern.endsWith('$');
111
+ const body = anchored ? pattern.slice(0, -1) : pattern;
112
+ const expression = body.replace(/[.+^${}()|[\]\\?]/g, '\\$&').replace(/\*/g, '.*');
113
+ try {
114
+ return new RegExp(`^${expression}${anchored ? '$' : ''}`).test(path);
115
+ } catch {
116
+ return false;
117
+ }
118
+ }
119
+
120
+ function requestPath(url) {
121
+ try {
122
+ const parsed = new URL(url);
123
+ return `${parsed.pathname}${parsed.search}`;
124
+ } catch {
125
+ return String(url ?? '/').startsWith('/') ? String(url) : `/${String(url ?? '')}`;
126
+ }
127
+ }
128
+
129
+ /**
130
+ * Whether `userAgent` may fetch `url` under this robots file.
131
+ * @param {ReturnType<typeof parseRobots>} robots
132
+ * @param {string} url
133
+ * @param {string} userAgent
134
+ */
135
+ export function isAllowed(robots, url, userAgent) {
136
+ const groups = selectGroups(robots, userAgent);
137
+ if (groups.length === 0) return true;
138
+ const path = requestPath(url);
139
+ let best = null;
140
+ for (const group of groups) {
141
+ for (const rule of group.rules) {
142
+ if (!ruleMatches(rule.path, path)) continue;
143
+ const length = rule.path.length;
144
+ if (!best || length > best.length || (length === best.length && rule.allow && !best.allow)) {
145
+ best = { allow: rule.allow, length };
146
+ }
147
+ }
148
+ }
149
+ return best ? best.allow : true;
150
+ }
151
+
152
+ /**
153
+ * Crawl delay in milliseconds for this UA (largest declared value wins).
154
+ * @param {ReturnType<typeof parseRobots>} robots
155
+ * @param {string} userAgent
156
+ */
157
+ export function crawlDelayMs(robots, userAgent) {
158
+ const groups = selectGroups(robots, userAgent);
159
+ let seconds = 0;
160
+ for (const group of groups) {
161
+ if (typeof group.crawlDelay === 'number') seconds = Math.max(seconds, group.crawlDelay);
162
+ }
163
+ return Math.round(seconds * 1000);
164
+ }
165
+
166
+ /**
167
+ * What each major AI crawler is told. `unmentioned` means no group names it,
168
+ * so the `*` group (or no rules at all) decides.
169
+ * @param {ReturnType<typeof parseRobots>} robots
170
+ * @param {string} [path]
171
+ */
172
+ export function aiCrawlerPolicy(robots, path = '/') {
173
+ const normalized = path.startsWith('/') ? path : `/${path}`;
174
+ return AI_CRAWLERS.map((agent) => {
175
+ const named = robots.groups.some((group) => group.agents.includes(agent));
176
+ const status = !named ? 'unmentioned' : isAllowed(robots, normalized, agent) ? 'allow' : 'deny';
177
+ return { agent, status };
178
+ });
179
+ }
180
+
181
+ /**
182
+ * Googlebot access at the site root, plus the image crawler's root access.
183
+ * @param {ReturnType<typeof parseRobots>} robots
184
+ */
185
+ export function googlebotAccess(robots) {
186
+ return {
187
+ allowed: isAllowed(robots, '/', 'Googlebot'),
188
+ imageAllowed: isAllowed(robots, '/', 'Googlebot-Image'),
189
+ };
190
+ }
191
+
192
+ /**
193
+ * True when the file forbids the whole site to everyone.
194
+ * @param {ReturnType<typeof parseRobots>} robots
195
+ */
196
+ export function blocksEverything(robots) {
197
+ return !isAllowed(robots, '/', '*');
198
+ }