@a2f0/agent-tool 0.1.69 → 0.1.71
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/README.md +3 -2
- package/package.json +1 -1
- package/skills/app-store-readiness/SKILL.md +148 -0
- package/skills/app-store-readiness/agents/openai.yaml +4 -0
- package/skills/app-store-readiness/references/android.md +53 -0
- package/skills/app-store-readiness/references/ios.md +82 -0
- package/skills/app-store-readiness/references/web.md +38 -0
- package/skills/audit-trails/SKILL.md +129 -0
- package/skills/audit-trails/agents/openai.yaml +4 -0
- package/skills/audit-trails/references/report-template.md +78 -0
- package/skills/audit-trails/references/usage-receipts.md +196 -0
- package/skills/seo-optimization/SKILL.md +162 -0
- package/skills/seo-optimization/agents/openai.yaml +4 -0
- package/skills/seo-optimization/references/cloudflare-workers.md +211 -0
- package/skills/seo-optimization/references/frameworks.md +144 -0
- package/skills/seo-optimization/references/standard.md +219 -0
- package/src/cli.ts +4 -21
- package/src/config.ts +1 -8
- package/src/permissions/catalog.ts +3 -4
- package/src/seo/html.ts +138 -0
- package/src/seo/http.ts +124 -0
- package/src/seo/probe.ts +250 -0
- package/src/skills/bundled.ts +22 -2
- package/src/skills/link.ts +0 -320
package/src/seo/http.ts
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The requests `seo probe` makes: one GET at a time with Bun's `fetch`, which
|
|
3
|
+
* honors the proxy variables a sandboxed harness sets. Only `http:` and `https:`
|
|
4
|
+
* URLs are ever requested, including redirect targets, because URLs come from
|
|
5
|
+
* remote markup (`og:image`, sitemap entries, links, `Location`), and `fetch`
|
|
6
|
+
* itself would also read `file:` and `s3:` URLs. Redirects are followed by hand
|
|
7
|
+
* so each hop is checked and the first one can be reported.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
export interface Reply {
|
|
11
|
+
/** The URL requested. */
|
|
12
|
+
url: string;
|
|
13
|
+
/** The three-digit status, or "000" when no response arrived (curl's `%{http_code}`). */
|
|
14
|
+
code: string;
|
|
15
|
+
/** For a 3xx with a `Location`, the absolute URL it names (curl's `%{redirect_url}`); otherwise "". */
|
|
16
|
+
location: string;
|
|
17
|
+
/** The `Content-Type` header as sent, or "". */
|
|
18
|
+
contentType: string;
|
|
19
|
+
/** Every `X-Robots-Tag` value; HTTP joins repeated header lines with ", ". */
|
|
20
|
+
robotsTag: string;
|
|
21
|
+
body: Uint8Array;
|
|
22
|
+
/** Why no response arrived, for an unreachable host. */
|
|
23
|
+
error?: string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface Followed { first: Reply; final: Reply }
|
|
27
|
+
|
|
28
|
+
export interface RequestOptions {
|
|
29
|
+
userAgent: string;
|
|
30
|
+
/** Seconds for the whole request, every redirect included, like curl's `-m`. */
|
|
31
|
+
seconds: number;
|
|
32
|
+
/** Read the body; false cancels it once the headers arrive. */
|
|
33
|
+
body?: boolean;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** curl's default `--max-redirs` with `-L`. */
|
|
37
|
+
const MAX_REDIRECTS = 50;
|
|
38
|
+
/** A body is cut here, so a hostile URL cannot exhaust memory; a sitemap may be 50 MB. */
|
|
39
|
+
const MAX_BODY_BYTES = 64 * 1024 * 1024;
|
|
40
|
+
|
|
41
|
+
const EMPTY: Uint8Array = new Uint8Array();
|
|
42
|
+
const failed = (url: string, error: string): Reply => ({ url, code: "000", location: "", contentType: "", robotsTag: "", body: EMPTY, error });
|
|
43
|
+
|
|
44
|
+
/** The URL when it is HTTP or HTTPS, else null. */
|
|
45
|
+
function webUrl(target: string): URL | null {
|
|
46
|
+
try {
|
|
47
|
+
const url = new URL(target);
|
|
48
|
+
return url.protocol === "http:" || url.protocol === "https:" ? url : null;
|
|
49
|
+
} catch { return null; }
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async function readBody(response: Response): Promise<Uint8Array> {
|
|
53
|
+
const reader = response.body?.getReader();
|
|
54
|
+
if (!reader) return EMPTY;
|
|
55
|
+
const chunks: Uint8Array[] = [];
|
|
56
|
+
let size = 0;
|
|
57
|
+
try {
|
|
58
|
+
for (;;) {
|
|
59
|
+
const { done, value } = await reader.read();
|
|
60
|
+
if (done) break;
|
|
61
|
+
chunks.push(value);
|
|
62
|
+
size += value.byteLength;
|
|
63
|
+
if (size >= MAX_BODY_BYTES) { await reader.cancel(); break; }
|
|
64
|
+
}
|
|
65
|
+
} catch {
|
|
66
|
+
// A timeout or reset mid-body keeps what arrived, as curl's output file does.
|
|
67
|
+
}
|
|
68
|
+
const body = new Uint8Array(Math.min(size, MAX_BODY_BYTES));
|
|
69
|
+
let offset = 0;
|
|
70
|
+
for (const chunk of chunks) {
|
|
71
|
+
const part = chunk.subarray(0, body.length - offset);
|
|
72
|
+
body.set(part, offset);
|
|
73
|
+
offset += part.length;
|
|
74
|
+
if (offset === body.length) break;
|
|
75
|
+
}
|
|
76
|
+
return body;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async function get(target: string, options: RequestOptions, deadline: number): Promise<Reply> {
|
|
80
|
+
const url = webUrl(target);
|
|
81
|
+
if (!url) return failed(target, `refused a URL that is not HTTP or HTTPS: ${target}`);
|
|
82
|
+
const remaining = deadline - performance.now();
|
|
83
|
+
if (remaining <= 0) return failed(target, `timed out after ${options.seconds} seconds`);
|
|
84
|
+
try {
|
|
85
|
+
const response = await fetch(url, {
|
|
86
|
+
redirect: "manual",
|
|
87
|
+
// curl's defaults: no compression, any type.
|
|
88
|
+
headers: { "user-agent": options.userAgent, accept: "*/*", "accept-encoding": "identity" },
|
|
89
|
+
signal: AbortSignal.timeout(remaining),
|
|
90
|
+
});
|
|
91
|
+
const code = String(response.status).padStart(3, "0");
|
|
92
|
+
const raw = response.headers.get("location");
|
|
93
|
+
let location = "";
|
|
94
|
+
if (raw !== null && response.status >= 300 && response.status < 400) {
|
|
95
|
+
try { location = new URL(raw, url).href; } catch { location = raw; }
|
|
96
|
+
}
|
|
97
|
+
let body: Uint8Array = EMPTY;
|
|
98
|
+
if (options.body === false) await response.body?.cancel();
|
|
99
|
+
else body = await readBody(response);
|
|
100
|
+
return { url: target, code, location, contentType: response.headers.get("content-type") ?? "", robotsTag: response.headers.get("x-robots-tag") ?? "", body };
|
|
101
|
+
} catch (error) {
|
|
102
|
+
return failed(target, error instanceof Error ? error.message : String(error));
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** One request; redirects are reported, not followed. */
|
|
107
|
+
export function request(target: string, options: RequestOptions): Promise<Reply> {
|
|
108
|
+
return get(target, options, performance.now() + options.seconds * 1000);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Follow redirects (not 304) up to curl's limit within one deadline. The final
|
|
113
|
+
* reply is the last response received; a redirect to a refused scheme ends the
|
|
114
|
+
* chain at that redirect, and a hop that gets no response ends it with "000".
|
|
115
|
+
*/
|
|
116
|
+
export async function follow(target: string, options: RequestOptions): Promise<Followed> {
|
|
117
|
+
const deadline = performance.now() + options.seconds * 1000;
|
|
118
|
+
const first = await get(target, options, deadline);
|
|
119
|
+
let final = first;
|
|
120
|
+
for (let hops = 0; hops < MAX_REDIRECTS && final.location && final.code !== "304" && webUrl(final.location); hops++) {
|
|
121
|
+
final = await get(final.location, options, deadline);
|
|
122
|
+
}
|
|
123
|
+
return { first, final };
|
|
124
|
+
}
|
package/src/seo/probe.ts
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `agent-tool seo probe`: a host's live search and preview metadata, for the
|
|
3
|
+
* seo-optimization skill. It reports what the deployed site serves before
|
|
4
|
+
* JavaScript runs; it changes nothing, but it requests whatever URLs its
|
|
5
|
+
* arguments and the fetched pages name.
|
|
6
|
+
*/
|
|
7
|
+
import { writeSync } from "node:fs";
|
|
8
|
+
import {
|
|
9
|
+
attr, attrValues, canonicalOf, clip, collapse, contentOf, first, internalLinks, isSitemapDocument,
|
|
10
|
+
length, lines, locs, matches, names, pngSize, robotsMeta, titleOf,
|
|
11
|
+
} from "./html";
|
|
12
|
+
import { follow, request, type Followed, type Reply, type RequestOptions } from "./http";
|
|
13
|
+
|
|
14
|
+
export const USAGE = `Usage: agent-tool seo probe [--page|--headers|--links|--sitemap] <host> [path...]
|
|
15
|
+
|
|
16
|
+
seo probe <host> [path] page report, then site files
|
|
17
|
+
seo probe --page <host> [path] page report only
|
|
18
|
+
seo probe --headers <host> <path>... one line per path, redirects not
|
|
19
|
+
followed: status, X-Robots-Tag,
|
|
20
|
+
type, Location
|
|
21
|
+
seo probe --links <host> [path] internal links on the page that do
|
|
22
|
+
not answer 200 directly; resolved
|
|
23
|
+
against the final URL, not <base>
|
|
24
|
+
seo probe --sitemap <host> every sitemap URL: status, canonical,
|
|
25
|
+
robots, duplicate titles/descriptions;
|
|
26
|
+
follows one level of sitemap index
|
|
27
|
+
|
|
28
|
+
The host is a hostname with an optional port, and each path starts with /.
|
|
29
|
+
--links and --sitemap exit 1 when they find a problem. An unreachable host
|
|
30
|
+
exits 1 and a usage error exits 2. Set SEO_PROBE_USER_AGENT to send a browser
|
|
31
|
+
user agent; SEO_PROBE_SCHEME (default https) exists for tests.`;
|
|
32
|
+
|
|
33
|
+
type Mode = "full" | "page" | "headers" | "links" | "sitemap";
|
|
34
|
+
const MODES: Record<string, Mode> = { "--page": "page", "--headers": "headers", "--links": "links", "--sitemap": "sitemap" };
|
|
35
|
+
|
|
36
|
+
export interface ProbeOptions {
|
|
37
|
+
mode: Mode;
|
|
38
|
+
host: string;
|
|
39
|
+
paths: string[];
|
|
40
|
+
scheme: "http" | "https";
|
|
41
|
+
userAgent: string;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
class UsageError extends Error {}
|
|
45
|
+
|
|
46
|
+
/** Bun before 1.4 keeps only the last of repeated response headers, which can hide an X-Robots-Tag noindex. */
|
|
47
|
+
export function keepsRepeatedHeaders(version: string): boolean {
|
|
48
|
+
const [major = 0, minor = 0] = version.split(".").map(Number);
|
|
49
|
+
return major > 1 || (major === 1 && minor >= 4);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function parseProbe(args: string[], env: NodeJS.ProcessEnv): ProbeOptions {
|
|
53
|
+
const rest = [...args];
|
|
54
|
+
const mode = rest[0] !== undefined && Object.hasOwn(MODES, rest[0]) ? MODES[rest.shift()!]! : "full";
|
|
55
|
+
const host = rest.shift();
|
|
56
|
+
if (!host || host.startsWith("-")) throw new UsageError(host ? `Unknown option '${host}'.` : "A host is required.");
|
|
57
|
+
// A host with a path, query, or user info could send the probe somewhere else entirely.
|
|
58
|
+
if (/[/?#@\\\s]/.test(host) || !URL.canParse(`http://${host}/`)) throw new UsageError(`'${host}' is not a hostname with an optional port.`);
|
|
59
|
+
for (const value of rest) {
|
|
60
|
+
if (value.startsWith("-")) throw new UsageError(`Unknown option '${value}'; the mode flag comes first.`);
|
|
61
|
+
if (!value.startsWith("/")) throw new UsageError(`Path '${value}' must start with /.`);
|
|
62
|
+
}
|
|
63
|
+
if (mode === "headers" && rest.length === 0) throw new UsageError("--headers needs at least one path.");
|
|
64
|
+
if (mode === "sitemap" && rest.length > 0) throw new UsageError("--sitemap takes no path.");
|
|
65
|
+
if (mode !== "headers" && rest.length > 1) throw new UsageError("Only --headers takes more than one path.");
|
|
66
|
+
const scheme = env.SEO_PROBE_SCHEME || "https";
|
|
67
|
+
if (scheme !== "http" && scheme !== "https") throw new UsageError("SEO_PROBE_SCHEME must be http or https.");
|
|
68
|
+
return { mode, host, paths: rest, scheme, userAgent: env.SEO_PROBE_USER_AGENT || "seo-probe" };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const decode = (bytes: Uint8Array) => new TextDecoder().decode(bytes);
|
|
72
|
+
/** "first-status [-> location] => final-status content-type", or just the final part without a redirect. */
|
|
73
|
+
function describe({ first: hop, final }: Followed): string {
|
|
74
|
+
const result = `${final.code} ${final.contentType}`;
|
|
75
|
+
return hop.location ? `${hop.code} -> ${hop.location} => ${result}` : result;
|
|
76
|
+
}
|
|
77
|
+
const okHtml = (result: string) => result.startsWith("200 text/html") || result.includes("=> 200 text/html");
|
|
78
|
+
const okStatus = (result: string) => result.startsWith("200 ") || result.includes("=> 200 ");
|
|
79
|
+
const tag = (reply: Reply) => reply.robotsTag || "(absent)";
|
|
80
|
+
|
|
81
|
+
/** Run one probe, printing each line as it is known; resolves to the exit status. */
|
|
82
|
+
export async function probe(options: ProbeOptions, print: (line: string) => void): Promise<number> {
|
|
83
|
+
const { host, paths, mode } = options;
|
|
84
|
+
const origin = `${options.scheme}://${host}`;
|
|
85
|
+
const bust = `seo-probe=${Math.floor(Date.now() / 1000)}`;
|
|
86
|
+
const withBust = (url: string) => `${url}${url.includes("?") ? "&" : "?"}${bust}`;
|
|
87
|
+
const unbust = (url: string) => url.replace(new RegExp(`[?&]${bust}`), "");
|
|
88
|
+
const web = (seconds: number, body = true): RequestOptions => ({ userAgent: options.userAgent, seconds, body });
|
|
89
|
+
|
|
90
|
+
const reachable = await request(`${origin}/`, web(15, false));
|
|
91
|
+
if (reachable.code === "000") { print(`### ${host} does not respond: ${reachable.error ?? ""}`); return 1; }
|
|
92
|
+
|
|
93
|
+
if (mode === "headers") {
|
|
94
|
+
for (const path of paths) {
|
|
95
|
+
const reply = await request(withBust(origin + path), web(20, false));
|
|
96
|
+
const location = unbust(reply.location);
|
|
97
|
+
print(`${host}${path} ${reply.code} x-robots-tag: ${tag(reply)} type: ${reply.contentType || "-"}${location ? ` -> ${location}` : ""}`);
|
|
98
|
+
}
|
|
99
|
+
return 0;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
if (mode === "links") {
|
|
103
|
+
const path = paths[0] ?? "/";
|
|
104
|
+
const page = await follow(withBust(origin + path), web(20));
|
|
105
|
+
const pageResult = describe(page);
|
|
106
|
+
if (!okHtml(pageResult)) { print(`### ${host}${path} page: ${pageResult} (cannot audit its links)`); return 1; }
|
|
107
|
+
const finalUrl = new URL(page.final.url);
|
|
108
|
+
const finalOrigin = `${finalUrl.protocol}//${finalUrl.host}`;
|
|
109
|
+
const links = internalLinks(collapse(decode(page.final.body)), finalUrl);
|
|
110
|
+
let bad = 0;
|
|
111
|
+
for (const link of links) {
|
|
112
|
+
const reply = await request(withBust(link), web(20, false));
|
|
113
|
+
if (reply.code === "200") continue;
|
|
114
|
+
bad++;
|
|
115
|
+
print(` ${link.startsWith(finalOrigin) ? link.slice(finalOrigin.length) : link} ${reply.code}${reply.location ? ` -> ${reply.location}` : ""}`);
|
|
116
|
+
}
|
|
117
|
+
if (finalUrl.host !== new URL(origin).host) print(` (links resolved against ${finalOrigin} after a redirect)`);
|
|
118
|
+
print(`### ${host}${path} internal links in the static HTML: ${links.length}, not a direct 200: ${bad}`);
|
|
119
|
+
if (links.length === 0) print(" (no links in the static HTML; a client-rendered page needs a browser check)");
|
|
120
|
+
return bad === 0 ? 0 : 1;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
if (mode === "sitemap") return sitemap(host, origin, withBust, web, print);
|
|
124
|
+
|
|
125
|
+
const path = paths[0] ?? "/";
|
|
126
|
+
const page = await follow(withBust(origin + path), web(20));
|
|
127
|
+
const body = collapse(decode(page.final.body));
|
|
128
|
+
const title = titleOf(body);
|
|
129
|
+
const description = contentOf(body, "description");
|
|
130
|
+
print(`### ${host}${path} [${describe(page)}]`);
|
|
131
|
+
print(` x-robots-tag: ${tag(page.final)}`);
|
|
132
|
+
print(` title (${length(title)} chars): ${title}`);
|
|
133
|
+
print(` description (${length(description)} chars): ${clip(description)}`);
|
|
134
|
+
print(` canonical: ${canonicalOf(body)}`);
|
|
135
|
+
print(` robots meta: ${robotsMeta(body)}`);
|
|
136
|
+
print(` lang: ${attr(first(body, '<html[^>]*lang="[^"]*"'), "lang")}`);
|
|
137
|
+
print(` theme-color: ${matches(body, '<meta[^>]+name="theme-color"[^>]*>').flatMap(meta => attrValues(meta, "content")).map(value => `${value} `).join("")}`);
|
|
138
|
+
print(` og: ${names(body, 'property="og:[a-z_:]+"').replace(/property=/g, "")}`);
|
|
139
|
+
print(` og:url: ${contentOf(body, "og:url")}`);
|
|
140
|
+
print(` twitter:card: ${contentOf(body, "twitter:card")}`);
|
|
141
|
+
print(` json-ld blocks: ${matches(body, "application/ld\\+json").length}`);
|
|
142
|
+
print(` json-ld types (including nested): ${names(body, '"@type": *("[A-Za-z]+"|\\[[^\\]]*\\])').replace(/"@type": */g, "")}`);
|
|
143
|
+
print(` h1 count (static HTML, before JavaScript): ${matches(body, "<h1[ >]").length}`);
|
|
144
|
+
const image = contentOf(body, "og:image");
|
|
145
|
+
if (image) {
|
|
146
|
+
const fetched = await follow(withBust(image), web(20));
|
|
147
|
+
const size = pngSize(fetched.final.body);
|
|
148
|
+
print(` og:image: ${image} [${describe(fetched)}] ${size ? `size ${size}` : ""} x-robots-tag: ${tag(fetched.final)}`);
|
|
149
|
+
} else {
|
|
150
|
+
print(" og:image: none");
|
|
151
|
+
}
|
|
152
|
+
if (mode === "page") return 0;
|
|
153
|
+
|
|
154
|
+
const robots = await follow(withBust(`${origin}/robots.txt`), web(20));
|
|
155
|
+
const robotsText = decode(robots.final.body);
|
|
156
|
+
const robotsLines = lines(robotsText);
|
|
157
|
+
let robotsResult = describe(robots);
|
|
158
|
+
if (robotsResult.includes("text/html")) robotsResult += " (HTML, not a robots file)";
|
|
159
|
+
if (robotsText.includes("BEGIN Cloudflare Managed")) robotsResult += " (includes Cloudflare managed content)";
|
|
160
|
+
else if (robotsLines.some(line => /^#.*content signals/i.test(line))) robotsResult += " (Cloudflare content-signals file)";
|
|
161
|
+
const directives = robotsLines.filter(line => !/^#|^\s*$/.test(line));
|
|
162
|
+
if (robotsLines.some(line => !line.startsWith("#") && /^content-signal:/i.test(line))) robotsResult += " (has Content-Signal directives)";
|
|
163
|
+
else if (robots.final.body.length > 0 && directives.length === 0) robotsResult += " (comments only: no directives)";
|
|
164
|
+
print(` robots.txt: ${robotsResult} x-robots-tag: ${tag(robots.final)}`);
|
|
165
|
+
if (!robotsResult.includes("HTML")) {
|
|
166
|
+
for (const line of directives.slice(0, 15)) print(` | ${line}`);
|
|
167
|
+
if (directives.length > 15) {
|
|
168
|
+
const sitemaps = directives.filter(line => /^sitemap:/i.test(line));
|
|
169
|
+
print(` | ... ${sitemaps.length} Sitemap line(s):`);
|
|
170
|
+
for (const line of sitemaps) print(` | ${line.replace(/\r/g, "")}`);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
const sitemapReply = await follow(withBust(`${origin}/sitemap.xml`), web(20));
|
|
174
|
+
let sitemapResult = describe(sitemapReply);
|
|
175
|
+
if (sitemapResult.includes("text/html")) sitemapResult += " (HTML, not a sitemap)";
|
|
176
|
+
print(` sitemap.xml: ${sitemapResult} urls: ${decode(sitemapReply.final.body).split("<loc>").length - 1}`);
|
|
177
|
+
const missing = await follow(withBust(`${origin}/seo-probe-missing-page`), web(20));
|
|
178
|
+
print(` missing path: ${describe(missing)} body: ${missing.final.body.length} bytes title: ${titleOf(collapse(decode(missing.final.body)))}`);
|
|
179
|
+
const nested = await follow(withBust(`${origin}/seo-probe/missing/page`), web(20));
|
|
180
|
+
print(` nested missing path: ${describe(nested)} body: ${nested.final.body.length} bytes`);
|
|
181
|
+
const error = await follow(withBust(`${origin}/404`), web(20));
|
|
182
|
+
print(` /404: ${describe(error)} robots meta: ${robotsMeta(collapse(decode(error.final.body)))} x-robots-tag: ${tag(error.final)}`);
|
|
183
|
+
const http = await request(withBust(`http://${host}/`), web(15, false));
|
|
184
|
+
const httpResult = unbust(`${http.code} ${http.location}`);
|
|
185
|
+
const httpNote = /^30[178] https:\/\//.test(httpResult) ? "redirects to HTTPS" : "does not redirect to HTTPS";
|
|
186
|
+
print(` http:// root: ${httpResult} (${httpNote}) x-robots-tag: ${tag(http)}`);
|
|
187
|
+
return 0;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** Every URL in the sitemap, through one level of sitemap index, without following redirects. */
|
|
191
|
+
async function sitemap(host: string, origin: string, withBust: (url: string) => string, web: (seconds: number, body?: boolean) => RequestOptions, print: (line: string) => void): Promise<number> {
|
|
192
|
+
const index = await follow(withBust(`${origin}/sitemap.xml`), web(20));
|
|
193
|
+
const indexResult = describe(index);
|
|
194
|
+
const indexBody = decode(index.final.body);
|
|
195
|
+
if (!okStatus(indexResult) || !isSitemapDocument(indexBody)) { print(`### ${host} sitemap.xml: ${indexResult} (not a sitemap document)`); return 1; }
|
|
196
|
+
let urls = locs(indexBody);
|
|
197
|
+
let problems = 0;
|
|
198
|
+
if (indexBody.includes("<sitemapindex")) {
|
|
199
|
+
const children: string[] = [];
|
|
200
|
+
for (const child of urls) {
|
|
201
|
+
const reply = await follow(withBust(child), web(20));
|
|
202
|
+
const result = describe(reply);
|
|
203
|
+
const body = decode(reply.final.body);
|
|
204
|
+
if (okStatus(result) && isSitemapDocument(body) && body.includes("<urlset")) children.push(...locs(body));
|
|
205
|
+
else { problems++; print(` ${child}: child sitemap ${result}, not a urlset;`); }
|
|
206
|
+
}
|
|
207
|
+
urls = children;
|
|
208
|
+
}
|
|
209
|
+
const titles: string[] = [], descriptions: string[] = [];
|
|
210
|
+
for (const url of urls) {
|
|
211
|
+
const reply = await request(withBust(url), web(20));
|
|
212
|
+
const body = collapse(decode(reply.body));
|
|
213
|
+
const canonical = canonicalOf(body);
|
|
214
|
+
const robots = ` ${`${reply.robotsTag} ${robotsMeta(body)}`.toLowerCase()} `;
|
|
215
|
+
let note = "";
|
|
216
|
+
if (reply.code !== "200") note += ` status ${reply.code};`;
|
|
217
|
+
if (canonical !== url) note += ` canonical ${canonical || "missing"};`;
|
|
218
|
+
if (robots.includes("noindex") || /[ ,:]none[ ,]/.test(robots)) note += " noindex;";
|
|
219
|
+
if (note) { problems++; print(` ${url}:${note}`); }
|
|
220
|
+
titles.push(titleOf(body));
|
|
221
|
+
descriptions.push(contentOf(body, "description"));
|
|
222
|
+
}
|
|
223
|
+
for (const [kind, values] of [["titles", titles], ["descriptions", descriptions]] as const) {
|
|
224
|
+
const counts = new Map<string, number>();
|
|
225
|
+
for (const value of values) if (value) counts.set(value, (counts.get(value) ?? 0) + 1);
|
|
226
|
+
const duplicates = [...counts].filter(([, count]) => count > 1).sort(([a, x], [b, y]) => y - x || (a < b ? 1 : a > b ? -1 : 0));
|
|
227
|
+
problems += duplicates.length;
|
|
228
|
+
for (const [value, count] of duplicates.slice(0, 5)) print(` duplicate ${kind} (count, text): ${count} ${value}`);
|
|
229
|
+
}
|
|
230
|
+
if (urls.length === 0) { problems++; print(" (the sitemap lists no URLs)"); }
|
|
231
|
+
print(`### ${host} sitemap URLs: ${urls.length}, with problems: ${problems}`);
|
|
232
|
+
return problems === 0 ? 0 : 1;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** `agent-tool seo <action>`: exit 0, 1 for a found problem or an unreachable host, 2 for usage. */
|
|
236
|
+
export async function seoCommand(args: string[], env: NodeJS.ProcessEnv = process.env, print = (line: string) => { writeSync(1, `${line}\n`); }, version = Bun.version): Promise<number> {
|
|
237
|
+
const [action, ...rest] = args;
|
|
238
|
+
if (action === "probe" && (rest[0] === "--help" || rest[0] === "-h") && rest.length === 1) { print(USAGE); return 0; }
|
|
239
|
+
let options: ProbeOptions;
|
|
240
|
+
try {
|
|
241
|
+
if (action !== "probe") throw new UsageError(action ? `Unknown seo command '${action}'.` : "An seo command is required.");
|
|
242
|
+
options = parseProbe(rest, env);
|
|
243
|
+
} catch (error) {
|
|
244
|
+
if (!(error instanceof UsageError)) throw error;
|
|
245
|
+
writeSync(2, `${error.message}\n\n${USAGE}\n`);
|
|
246
|
+
return 2;
|
|
247
|
+
}
|
|
248
|
+
if (!keepsRepeatedHeaders(version)) throw new Error(`seo probe needs Bun 1.4 or newer, which keeps every repeated response header such as X-Robots-Tag; this is Bun ${version}.`);
|
|
249
|
+
return probe(options, print);
|
|
250
|
+
}
|