@cobola/dsh-geo 0.0.0-stage → 0.3.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.
package/bin/dsh-geo.js ADDED
@@ -0,0 +1,381 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * dsh-geo CLI — the same engine and storage the plugin tools use.
4
+ *
5
+ * Commands:
6
+ * scan <url> audit a site; optionally persist and diff
7
+ * fix-plan turn the latest (or named) report into a fix list
8
+ * history list saved audits in .dsh-geo/history
9
+ * diff <a> <b> compare two saved reports
10
+ */
11
+
12
+ import { createRequire } from 'node:module';
13
+ import fs from 'node:fs/promises';
14
+ import path from 'node:path';
15
+
16
+ import { auditSite, persistAudit, planFromReport } from '../lib/audit.js';
17
+ import { diffReports } from '../lib/report.js';
18
+ import { listAudits, resolveStoreDir } from '../lib/store.js';
19
+
20
+ const require = createRequire(import.meta.url);
21
+ const { version } = require('../package.json');
22
+
23
+ const HELP = `dsh-geo ${version} — deterministic GEO/SEO audit
24
+
25
+ Usage:
26
+ dsh-geo scan <url> [options]
27
+ dsh-geo fix-plan [options]
28
+ dsh-geo history [options]
29
+ dsh-geo diff <before.json> <after.json> [--json]
30
+ dsh-geo --help | --version
31
+
32
+ scan options:
33
+ --json Print { scan, score } as JSON.
34
+ --save Write .dsh-geo/latest.json, history/, report.md and diff.
35
+ --dir <path> Report directory inside .dsh-geo/ (default .dsh-geo).
36
+ --fail-under <score> Exit 3 when the total is below this score (0–100).
37
+ --max-pages <n> Pages to crawl (default 6).
38
+ --now <iso> Reference time for freshness; reuse it to isolate code changes.
39
+ --no-robots Ignore robots.txt (opt-in; only for sites you own).
40
+ --allow-private Allow loopback/private targets (local audits only).
41
+ --insecure-tls Skip TLS verification (local/test only).
42
+ --timeout <ms> Per-request timeout (default 10000).
43
+ --rate-limit <ms> Per-host minimum interval (default 250).
44
+ --user-agent <ua> Crawler User-Agent.
45
+
46
+ fix-plan options:
47
+ --dir <path> Report directory (default .dsh-geo).
48
+ --report <path> Use a specific report instead of .dsh-geo/latest.json.
49
+ --json Print the plan payload as JSON.
50
+
51
+ history options:
52
+ --dir <path> Report directory (default .dsh-geo).
53
+ --limit <n> Entries to show (default 10).
54
+ --json Print entries as JSON.
55
+
56
+ Exit codes: 0 completed, 1 error, 2 usage, 3 score below --fail-under.
57
+
58
+ Reports stay inside <cwd>/.dsh-geo/. The scanner honors robots.txt, refuses
59
+ private destinations, and rate-limits requests by default.`;
60
+
61
+ function defaults() {
62
+ return {
63
+ json: false,
64
+ save: false,
65
+ dir: '.dsh-geo',
66
+ failUnder: null,
67
+ maxPages: 6,
68
+ now: null,
69
+ respectRobots: true,
70
+ allowPrivate: false,
71
+ insecureTls: false,
72
+ timeoutMs: 10_000,
73
+ rateLimitMs: 250,
74
+ userAgent: undefined,
75
+ report: null,
76
+ limit: 10,
77
+ };
78
+ }
79
+
80
+ const VALUE_OPTIONS = new Set([
81
+ 'dir', 'fail-under', 'max-pages', 'now', 'timeout', 'rate-limit',
82
+ 'user-agent', 'report', 'limit',
83
+ ]);
84
+
85
+ function parseArgs(argv) {
86
+ const command = [];
87
+ const options = defaults();
88
+ const queue = [...argv];
89
+ while (queue.length > 0) {
90
+ const token = queue.shift();
91
+ if (!token.startsWith('--')) {
92
+ command.push(token);
93
+ continue;
94
+ }
95
+ const withoutPrefix = token.slice(2);
96
+ const equals = withoutPrefix.indexOf('=');
97
+ const key = (equals === -1 ? withoutPrefix : withoutPrefix.slice(0, equals));
98
+ const inline = equals === -1 ? undefined : withoutPrefix.slice(equals + 1);
99
+ if (key === 'help') { options.help = true; continue; }
100
+ if (key === 'version') { options.version = true; continue; }
101
+ if (!VALUE_OPTIONS.has(key)) {
102
+ if (!['json', 'save', 'no-robots', 'allow-private', 'insecure-tls'].includes(key)) {
103
+ throw new Error(`Unknown option: --${key}`);
104
+ }
105
+ }
106
+ const value = VALUE_OPTIONS.has(key) ? (inline ?? queue.shift()) : true;
107
+ if (VALUE_OPTIONS.has(key) && value === undefined) throw new Error(`Missing value for --${key}`);
108
+ switch (key) {
109
+ case 'json': options.json = true; break;
110
+ case 'save': options.save = true; break;
111
+ case 'no-robots': options.respectRobots = false; break;
112
+ case 'allow-private': options.allowPrivate = true; break;
113
+ case 'insecure-tls': options.insecureTls = true; break;
114
+ case 'dir': options.dir = value; break;
115
+ case 'now': options.now = value; break;
116
+ case 'report': options.report = value; break;
117
+ case 'user-agent': options.userAgent = value; break;
118
+ case 'fail-under': options.failUnder = Number(value); break;
119
+ case 'max-pages': options.maxPages = Number(value); break;
120
+ case 'timeout': options.timeoutMs = Number(value); break;
121
+ case 'rate-limit': options.rateLimitMs = Number(value); break;
122
+ case 'limit': options.limit = Number(value); break;
123
+ default: throw new Error(`Unknown option: --${key}`);
124
+ }
125
+ }
126
+ return { command, options };
127
+ }
128
+
129
+ function validate(options, commandName) {
130
+ if (!Number.isInteger(options.maxPages) || options.maxPages < 1) throw new Error('--max-pages must be a positive integer');
131
+ if (!Number.isFinite(options.timeoutMs) || options.timeoutMs <= 0) throw new Error('--timeout must be positive');
132
+ if (!Number.isFinite(options.rateLimitMs) || options.rateLimitMs < 0) throw new Error('--rate-limit must be zero or positive');
133
+ if (options.failUnder !== null && (!Number.isFinite(options.failUnder) || options.failUnder < 0 || options.failUnder > 100)) {
134
+ throw new Error('--fail-under must be between 0 and 100');
135
+ }
136
+ if (options.now !== null && !Number.isFinite(Date.parse(options.now))) throw new Error(`--now is not a valid ISO time: ${options.now}`);
137
+ if (!Number.isInteger(options.limit) || options.limit < 1) throw new Error('--limit must be a positive integer');
138
+ if (commandName !== 'scan' && (options.maxPages !== 6 || options.now !== null || !options.respectRobots
139
+ || options.allowPrivate || options.insecureTls || options.timeoutMs !== 10_000 || options.rateLimitMs !== 250)) {
140
+ throw new Error(`Scan-only options are not accepted by "${commandName}"`);
141
+ }
142
+ }
143
+
144
+ function bar(score) {
145
+ const filled = Math.round(Math.max(0, Math.min(100, score)) / 10);
146
+ return `${'█'.repeat(filled)}${'░'.repeat(10 - filled)}`;
147
+ }
148
+
149
+ function signed(value) {
150
+ return value > 0 ? `+${value}` : String(value);
151
+ }
152
+
153
+ function renderScan(report, scan, extras = {}) {
154
+ const lines = [];
155
+ lines.push(`GEO 体检 ${report.startUrl}`);
156
+ lines.push(`总分 ${report.total} / 100 ${bar(report.total)} ${report.grade}(${report.gradeLabel})`);
157
+ lines.push(`${scan.stats.pages} 个页面 · ${report.findings.length} 项检查 · 通过 ${report.counts.pass} / 部分 ${report.counts.warn} / 失败 ${report.counts.fail} / 不适用 ${report.counts.skip}`);
158
+ lines.push('');
159
+ for (const dimension of report.dimensions) {
160
+ lines.push(`${dimension.title.padEnd(6, ' ')} ${String(dimension.score).padStart(5, ' ')} ${bar(dimension.score)} 权重 ${dimension.weight}`);
161
+ }
162
+ for (const platform of report.platforms ?? []) {
163
+ lines.push(`${platform.title.padEnd(14, ' ')} ${String(platform.total).padStart(5, ' ')} ${bar(platform.total)} 平台参考分(不计入总分)`);
164
+ }
165
+ if (report.blockedByRobots) {
166
+ lines.push('');
167
+ lines.push('robots.txt 拒绝了扫描 UA,未抓取任何页面。用 --no-robots 可在本地显式绕过。');
168
+ }
169
+ if (extras.diff) {
170
+ lines.push('');
171
+ lines.push(`对照上次 ${extras.diff.previous.scannedAt}:${extras.diff.total.before} → ${extras.diff.total.after}(${signed(extras.diff.total.delta)})`);
172
+ if (extras.diff.fixed.length > 0) lines.push(`已修复:${extras.diff.fixed.map((entry) => entry.ruleId).join(', ')}`);
173
+ if (extras.diff.regressed.length > 0) lines.push(`出现回归:${extras.diff.regressed.map((entry) => entry.ruleId).join(', ')}`);
174
+ }
175
+ if (report.actions.length > 0) {
176
+ lines.push('');
177
+ lines.push('优先修复(按影响力排序):');
178
+ report.actions.forEach((action, index) => {
179
+ lines.push(`${index + 1}. [${action.dimensionTitle} ${action.weight}分] ${action.title} — ${action.evidence}`);
180
+ lines.push(` → ${action.fix}`);
181
+ });
182
+ }
183
+ if (extras.paths) {
184
+ lines.push('');
185
+ lines.push(`已保存:${extras.paths.latest} · ${extras.paths.report}`);
186
+ lines.push(`生成修复清单:dsh-geo fix-plan --dir ${extras.dir ?? '.dsh-geo'}`);
187
+ } else {
188
+ lines.push('');
189
+ lines.push('加 --save 可把完整报告写入 .dsh-geo/,并与上次扫描对比。');
190
+ }
191
+ return lines.join('\n');
192
+ }
193
+
194
+ async function loadPayload(file) {
195
+ let raw;
196
+ try {
197
+ raw = JSON.parse(await fs.readFile(file, 'utf8'));
198
+ } catch (error) {
199
+ throw new Error(`Cannot read report ${file}: ${error.message}`);
200
+ }
201
+ if (raw?.score?.findings) return raw;
202
+ if (raw?.findings && typeof raw.total === 'number') return { score: raw, url: raw.startUrl ?? null, scan: null };
203
+ throw new Error(`Not an audit report: ${file}`);
204
+ }
205
+
206
+ async function commandScan(positionals, options) {
207
+ const url = positionals[0];
208
+ if (!url) throw new Error('Missing <url>');
209
+ if (positionals.length > 1) throw new Error(`Unexpected argument: ${positionals[1]}`);
210
+ const cwd = process.cwd();
211
+
212
+ const { scan, report } = await auditSite(url, {
213
+ maxPages: options.maxPages,
214
+ respectRobots: options.respectRobots,
215
+ allowPrivate: options.allowPrivate,
216
+ insecureTls: options.insecureTls,
217
+ timeoutMs: options.timeoutMs,
218
+ rateLimitMs: options.rateLimitMs,
219
+ userAgent: options.userAgent,
220
+ now: options.now ?? undefined,
221
+ });
222
+
223
+ let persisted = null;
224
+ if (options.save) {
225
+ persisted = await persistAudit(cwd, { scan, report, reportDir: options.dir });
226
+ }
227
+
228
+ if (options.json) {
229
+ const payload = { scan, score: report };
230
+ if (persisted) {
231
+ payload.saved = {
232
+ latest: path.relative(cwd, persisted.paths.latestPath),
233
+ history: path.relative(cwd, persisted.paths.historyPath),
234
+ report: path.relative(cwd, persisted.paths.reportPath),
235
+ };
236
+ payload.diff = persisted.diff;
237
+ }
238
+ process.stdout.write(`${JSON.stringify(payload, null, 2)}\n`);
239
+ } else {
240
+ const extras = {};
241
+ if (persisted) {
242
+ extras.paths = {
243
+ latest: path.relative(cwd, persisted.paths.latestPath),
244
+ report: path.relative(cwd, persisted.paths.reportPath),
245
+ };
246
+ extras.dir = options.dir;
247
+ extras.diff = persisted.diff;
248
+ }
249
+ process.stdout.write(`${renderScan(report, scan, extras)}\n`);
250
+ }
251
+
252
+ if (options.failUnder !== null && report.total < options.failUnder) {
253
+ process.stderr.write(`GEO score ${report.total} is below --fail-under ${options.failUnder}\n`);
254
+ return 3;
255
+ }
256
+ return 0;
257
+ }
258
+
259
+ async function commandFixPlan(positionals, options) {
260
+ if (positionals.length > 0) throw new Error(`Unexpected argument: ${positionals[0]}`);
261
+ const cwd = process.cwd();
262
+ const { payload, plan, paths } = await planFromReport(cwd, { reportPath: options.report, reportDir: options.dir });
263
+ if (options.json) {
264
+ process.stdout.write(`${JSON.stringify(plan.json, null, 2)}\n`);
265
+ return 0;
266
+ }
267
+ const lines = [];
268
+ lines.push(`修复清单:${path.relative(cwd, paths.planPath)}(${plan.actions.length} 项)`);
269
+ lines.push(`目标:${payload.url ?? payload.score.startUrl} · ${payload.score.total} / 100 ${payload.score.grade}`);
270
+ if (payload.diff) {
271
+ lines.push(`对照上次 ${payload.diff.previous.scannedAt}:${payload.diff.total.before} → ${payload.diff.total.after}(${signed(payload.diff.total.delta)})`);
272
+ }
273
+ if (plan.actions.length === 0) {
274
+ lines.push('所有检查项均已通过,没有需要修复的项。');
275
+ } else {
276
+ lines.push('');
277
+ plan.actions.slice(0, 8).forEach((action, index) => {
278
+ lines.push(`${index + 1}. [${action.dimensionTitle} ${action.weight}分] ${action.title} — ${action.evidence}`);
279
+ lines.push(` → ${action.fix}`);
280
+ });
281
+ if (plan.actions.length > 8) lines.push(`… 其余 ${plan.actions.length - 8} 项见清单文件`);
282
+ }
283
+ process.stdout.write(`${lines.join('\n')}\n`);
284
+ return 0;
285
+ }
286
+
287
+ async function commandHistory(positionals, options) {
288
+ if (positionals.length > 0) throw new Error(`Unexpected argument: ${positionals[0]}`);
289
+ const cwd = process.cwd();
290
+ const storeDir = resolveStoreDir(cwd, options.dir);
291
+ const entries = await listAudits(storeDir, options.limit);
292
+ if (options.json) {
293
+ process.stdout.write(`${JSON.stringify(entries, null, 2)}\n`);
294
+ return 0;
295
+ }
296
+ if (entries.length === 0) {
297
+ process.stdout.write(`No saved audits in ${path.relative(cwd, storeDir)}/history\n`);
298
+ return 0;
299
+ }
300
+ const lines = [`最近 ${entries.length} 次扫描(${path.relative(cwd, storeDir)}/history):`, ''];
301
+ for (const entry of entries) {
302
+ lines.push(`${entry.savedAt ?? '未知时间'} ${String(entry.total).padStart(5, ' ')} ${entry.grade} ${entry.url ?? ''}`);
303
+ lines.push(` ${path.relative(cwd, entry.path)}`);
304
+ }
305
+ process.stdout.write(`${lines.join('\n')}\n`);
306
+ return 0;
307
+ }
308
+
309
+ async function commandDiff(positionals, options) {
310
+ if (positionals.length !== 2) throw new Error('diff needs exactly two report paths');
311
+ const before = await loadPayload(positionals[0]);
312
+ const after = await loadPayload(positionals[1]);
313
+ const diff = diffReports(before.score, after.score);
314
+ if (options.json) {
315
+ process.stdout.write(`${JSON.stringify(diff, null, 2)}\n`);
316
+ return 0;
317
+ }
318
+ const lines = [];
319
+ lines.push(`${before.score.startUrl ?? '<before>'} ${diff.total.before} → ${diff.total.after}(${signed(diff.total.delta)})`);
320
+ lines.push('');
321
+ for (const dimension of diff.dimensions) {
322
+ if (dimension.delta === 0) continue;
323
+ lines.push(`${dimension.title}:${dimension.before} → ${dimension.after}(${signed(dimension.delta)})`);
324
+ }
325
+ lines.push('');
326
+ lines.push(`已修复 ${diff.counts.fixed} 项${diff.fixed.length > 0 ? `:${diff.fixed.map((entry) => entry.ruleId).join(', ')}` : ''}`);
327
+ lines.push(`回归 ${diff.counts.regressed} 项${diff.regressed.length > 0 ? `:${diff.regressed.map((entry) => entry.ruleId).join(', ')}` : ''}`);
328
+ lines.push(`仍未通过 ${diff.counts.stillFailing} 项`);
329
+ process.stdout.write(`${lines.join('\n')}\n`);
330
+ return 0;
331
+ }
332
+
333
+ const COMMANDS = {
334
+ scan: commandScan,
335
+ 'fix-plan': commandFixPlan,
336
+ history: commandHistory,
337
+ diff: commandDiff,
338
+ };
339
+
340
+ async function main(argv) {
341
+ let parsed;
342
+ try {
343
+ parsed = parseArgs(argv);
344
+ } catch (error) {
345
+ process.stderr.write(`dsh-geo: ${error.message}\n\n${HELP}\n`);
346
+ return 2;
347
+ }
348
+ if (parsed.options.help) {
349
+ process.stdout.write(`${HELP}\n`);
350
+ return 0;
351
+ }
352
+ if (parsed.options.version) {
353
+ process.stdout.write(`${version}\n`);
354
+ return 0;
355
+ }
356
+ const [name, ...positionals] = parsed.command;
357
+ if (!name) {
358
+ process.stderr.write(`dsh-geo: missing command\n\n${HELP}\n`);
359
+ return 2;
360
+ }
361
+ const handler = COMMANDS[name];
362
+ if (!handler) {
363
+ process.stderr.write(`dsh-geo: unknown command "${name}"\n\n${HELP}\n`);
364
+ return 2;
365
+ }
366
+ try {
367
+ validate(parsed.options, name);
368
+ return await handler(positionals, parsed.options);
369
+ } catch (error) {
370
+ const usageError = /Missing <url>|Unexpected argument|Scan-only options|diff needs exactly/.test(error.message);
371
+ process.stderr.write(`dsh-geo: ${error.message}\n`);
372
+ return usageError ? 2 : 1;
373
+ }
374
+ }
375
+
376
+ main(process.argv.slice(2))
377
+ .then((code) => { process.exitCode = code; })
378
+ .catch((error) => {
379
+ process.stderr.write(`dsh-geo: ${error.message}\n`);
380
+ process.exitCode = 1;
381
+ });