seo-supervisor 0.0.0-stage → 2.0.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.
Files changed (218) hide show
  1. package/.claude-plugin/icon.png +0 -0
  2. package/.claude-plugin/marketplace.json +16 -0
  3. package/.claude-plugin/plugin.json +27 -0
  4. package/CHANGELOG.md +461 -0
  5. package/LICENSE +25 -0
  6. package/NOTICE +7 -0
  7. package/README.md +402 -2
  8. package/agents/seo-auditor.md +16 -0
  9. package/agents/seo-reviewer.md +16 -0
  10. package/bin/agents.mjs +230 -0
  11. package/bin/extras.mjs +422 -0
  12. package/bin/prompt.mjs +96 -0
  13. package/bin/seo-supervisor.mjs +477 -0
  14. package/commands/seo-audit.md +33 -0
  15. package/commands/seo-brief.md +28 -0
  16. package/commands/seo-connect.md +27 -0
  17. package/commands/seo-fix.md +34 -0
  18. package/commands/seo-grow.md +26 -0
  19. package/commands/seo-launch.md +21 -0
  20. package/commands/seo-review.md +19 -0
  21. package/commands/seo-rewrite.md +25 -0
  22. package/commands/seo-setup.md +35 -0
  23. package/commands/seo-watch.md +28 -0
  24. package/hooks/hooks.json +117 -0
  25. package/package.json +58 -4
  26. package/skills/seo-supervisor/NOTICE +7 -0
  27. package/skills/seo-supervisor/SKILL.md +480 -0
  28. package/skills/seo-supervisor/audience.md +61 -0
  29. package/skills/seo-supervisor/examples/drafts/security.md +41 -0
  30. package/skills/seo-supervisor/examples/hooks/README.md +28 -0
  31. package/skills/seo-supervisor/examples/hooks/claude-code-settings.json +15 -0
  32. package/skills/seo-supervisor/examples/hooks/codex-hooks.json +17 -0
  33. package/skills/seo-supervisor/examples/hooks/copilot-hooks.json +15 -0
  34. package/skills/seo-supervisor/examples/hooks/cursor-hooks.json +11 -0
  35. package/skills/seo-supervisor/examples/hooks/github-actions.yml +21 -0
  36. package/skills/seo-supervisor/examples/hooks/pre-commit +17 -0
  37. package/skills/seo-supervisor/examples/hooks/reading-ease.yml +24 -0
  38. package/skills/seo-supervisor/examples/sample-audit.json +532 -0
  39. package/skills/seo-supervisor/examples/sample-report.html +704 -0
  40. package/skills/seo-supervisor/examples/sample-report.md +360 -0
  41. package/skills/seo-supervisor/examples/scheduled-runs.md +89 -0
  42. package/skills/seo-supervisor/examples/security-tools-profile.md +73 -0
  43. package/skills/seo-supervisor/examples/snippets.md +781 -0
  44. package/skills/seo-supervisor/frameworks/nextjs.md +98 -0
  45. package/skills/seo-supervisor/frameworks/rails.md +34 -0
  46. package/skills/seo-supervisor/frameworks/spa.md +14 -0
  47. package/skills/seo-supervisor/grow.md +342 -0
  48. package/skills/seo-supervisor/og-images.md +85 -0
  49. package/skills/seo-supervisor/page-types.md +124 -0
  50. package/skills/seo-supervisor/planning.md +157 -0
  51. package/skills/seo-supervisor/profile-template.md +96 -0
  52. package/skills/seo-supervisor/report-format.md +313 -0
  53. package/skills/seo-supervisor/rewrite.md +59 -0
  54. package/skills/seo-supervisor/rules/ai-search.md +93 -0
  55. package/skills/seo-supervisor/rules/content.md +84 -0
  56. package/skills/seo-supervisor/rules/crawl-index.md +92 -0
  57. package/skills/seo-supervisor/rules/internal-linking.md +104 -0
  58. package/skills/seo-supervisor/rules/launch-monitoring.md +57 -0
  59. package/skills/seo-supervisor/rules/media.md +42 -0
  60. package/skills/seo-supervisor/rules/metadata.md +71 -0
  61. package/skills/seo-supervisor/rules/performance.md +78 -0
  62. package/skills/seo-supervisor/rules/rendering.md +79 -0
  63. package/skills/seo-supervisor/rules/search-intent.md +32 -0
  64. package/skills/seo-supervisor/rules/sitemaps-robots.md +49 -0
  65. package/skills/seo-supervisor/rules/structured-data.md +98 -0
  66. package/skills/seo-supervisor/rules/trust-security.md +48 -0
  67. package/skills/seo-supervisor/rules/urls.md +54 -0
  68. package/skills/seo-supervisor/scripts/ai-answers.mjs +314 -0
  69. package/skills/seo-supervisor/scripts/backlinks.mjs +412 -0
  70. package/skills/seo-supervisor/scripts/change-check.mjs +281 -0
  71. package/skills/seo-supervisor/scripts/checks/agents.mjs +488 -0
  72. package/skills/seo-supervisor/scripts/checks/assets.mjs +404 -0
  73. package/skills/seo-supervisor/scripts/checks/bots.mjs +146 -0
  74. package/skills/seo-supervisor/scripts/checks/business-type.mjs +193 -0
  75. package/skills/seo-supervisor/scripts/checks/content.mjs +391 -0
  76. package/skills/seo-supervisor/scripts/checks/coverage.mjs +184 -0
  77. package/skills/seo-supervisor/scripts/checks/crawl.mjs +95 -0
  78. package/skills/seo-supervisor/scripts/checks/hreflang.mjs +396 -0
  79. package/skills/seo-supervisor/scripts/checks/hygiene.mjs +227 -0
  80. package/skills/seo-supervisor/scripts/checks/lighthouse.mjs +271 -0
  81. package/skills/seo-supervisor/scripts/checks/link-strength.mjs +59 -0
  82. package/skills/seo-supervisor/scripts/checks/links.mjs +360 -0
  83. package/skills/seo-supervisor/scripts/checks/local.mjs +101 -0
  84. package/skills/seo-supervisor/scripts/checks/media.mjs +194 -0
  85. package/skills/seo-supervisor/scripts/checks/outbound.mjs +53 -0
  86. package/skills/seo-supervisor/scripts/checks/page.mjs +223 -0
  87. package/skills/seo-supervisor/scripts/checks/probes.mjs +130 -0
  88. package/skills/seo-supervisor/scripts/checks/render.mjs +552 -0
  89. package/skills/seo-supervisor/scripts/checks/robots.mjs +144 -0
  90. package/skills/seo-supervisor/scripts/checks/schema.mjs +206 -0
  91. package/skills/seo-supervisor/scripts/checks/site-agents.mjs +79 -0
  92. package/skills/seo-supervisor/scripts/checks/site-content.mjs +135 -0
  93. package/skills/seo-supervisor/scripts/checks/site-hygiene.mjs +202 -0
  94. package/skills/seo-supervisor/scripts/checks/site-pages.mjs +474 -0
  95. package/skills/seo-supervisor/scripts/checks/site-security.mjs +102 -0
  96. package/skills/seo-supervisor/scripts/checks/sitemap.mjs +473 -0
  97. package/skills/seo-supervisor/scripts/checks/speed.mjs +267 -0
  98. package/skills/seo-supervisor/scripts/checks/technical.mjs +368 -0
  99. package/skills/seo-supervisor/scripts/checks/tls.mjs +297 -0
  100. package/skills/seo-supervisor/scripts/checks/trust.mjs +421 -0
  101. package/skills/seo-supervisor/scripts/checks/visual.mjs +1132 -0
  102. package/skills/seo-supervisor/scripts/checks/writing.mjs +192 -0
  103. package/skills/seo-supervisor/scripts/commoncrawl.mjs +452 -0
  104. package/skills/seo-supervisor/scripts/connect-keys.mjs +422 -0
  105. package/skills/seo-supervisor/scripts/content-scan.mjs +530 -0
  106. package/skills/seo-supervisor/scripts/crawl/catalog.mjs +1248 -0
  107. package/skills/seo-supervisor/scripts/crawl/fetch.mjs +362 -0
  108. package/skills/seo-supervisor/scripts/crawl/page.mjs +741 -0
  109. package/skills/seo-supervisor/scripts/crawl/queue.mjs +190 -0
  110. package/skills/seo-supervisor/scripts/dashboard.mjs +140 -0
  111. package/skills/seo-supervisor/scripts/data/ai-bots.json +38 -0
  112. package/skills/seo-supervisor/scripts/data/build-schema-vocab.mjs +57 -0
  113. package/skills/seo-supervisor/scripts/data/business-types.json +338 -0
  114. package/skills/seo-supervisor/scripts/data/google-rich-results.json +79 -0
  115. package/skills/seo-supervisor/scripts/data/schema-vocab.json +1 -0
  116. package/skills/seo-supervisor/scripts/deploy-check.mjs +462 -0
  117. package/skills/seo-supervisor/scripts/disavow.mjs +176 -0
  118. package/skills/seo-supervisor/scripts/doctor.mjs +174 -0
  119. package/skills/seo-supervisor/scripts/fonts/OFL-BricolageGrotesque.txt +93 -0
  120. package/skills/seo-supervisor/scripts/fonts/OFL-Geist.txt +93 -0
  121. package/skills/seo-supervisor/scripts/fonts/OFL-GeistMono.txt +93 -0
  122. package/skills/seo-supervisor/scripts/fonts/bricolage-grotesque.woff2 +0 -0
  123. package/skills/seo-supervisor/scripts/fonts/geist-mono.woff2 +0 -0
  124. package/skills/seo-supervisor/scripts/fonts/geist.woff2 +0 -0
  125. package/skills/seo-supervisor/scripts/geo-grid.mjs +371 -0
  126. package/skills/seo-supervisor/scripts/google/search-console.mjs +151 -0
  127. package/skills/seo-supervisor/scripts/google/session.mjs +167 -0
  128. package/skills/seo-supervisor/scripts/google-updates.mjs +189 -0
  129. package/skills/seo-supervisor/scripts/google.mjs +1341 -0
  130. package/skills/seo-supervisor/scripts/gsc-import.mjs +298 -0
  131. package/skills/seo-supervisor/scripts/guard/adapters/claude-code.mjs +149 -0
  132. package/skills/seo-supervisor/scripts/guard/adapters/cline.mjs +28 -0
  133. package/skills/seo-supervisor/scripts/guard/adapters/codex.mjs +26 -0
  134. package/skills/seo-supervisor/scripts/guard/adapters/copilot.mjs +36 -0
  135. package/skills/seo-supervisor/scripts/guard/adapters/cursor.mjs +33 -0
  136. package/skills/seo-supervisor/scripts/guard/adapters/devin.mjs +25 -0
  137. package/skills/seo-supervisor/scripts/guard/adapters/edits.mjs +124 -0
  138. package/skills/seo-supervisor/scripts/guard/mode.mjs +37 -0
  139. package/skills/seo-supervisor/scripts/guard/rules.mjs +931 -0
  140. package/skills/seo-supervisor/scripts/guard.mjs +74 -0
  141. package/skills/seo-supervisor/scripts/images.mjs +408 -0
  142. package/skills/seo-supervisor/scripts/indexnow.mjs +300 -0
  143. package/skills/seo-supervisor/scripts/issues.mjs +217 -0
  144. package/skills/seo-supervisor/scripts/keys/authority.mjs +135 -0
  145. package/skills/seo-supervisor/scripts/keys/bing.mjs +239 -0
  146. package/skills/seo-supervisor/scripts/keys/clarity.mjs +137 -0
  147. package/skills/seo-supervisor/scripts/keys/dataforseo.mjs +57 -0
  148. package/skills/seo-supervisor/scripts/keys/googleplaces.mjs +26 -0
  149. package/skills/seo-supervisor/scripts/keys/http.mjs +212 -0
  150. package/skills/seo-supervisor/scripts/keys/matomo.mjs +138 -0
  151. package/skills/seo-supervisor/scripts/keys/openai.mjs +26 -0
  152. package/skills/seo-supervisor/scripts/keys/perplexity.mjs +26 -0
  153. package/skills/seo-supervisor/scripts/keys/posthog.mjs +165 -0
  154. package/skills/seo-supervisor/scripts/keys/semrush.mjs +25 -0
  155. package/skills/seo-supervisor/scripts/keys/services.mjs +41 -0
  156. package/skills/seo-supervisor/scripts/keys/store.mjs +140 -0
  157. package/skills/seo-supervisor/scripts/keys/visits.mjs +58 -0
  158. package/skills/seo-supervisor/scripts/keys/youtube.mjs +84 -0
  159. package/skills/seo-supervisor/scripts/keyword-data.mjs +316 -0
  160. package/skills/seo-supervisor/scripts/keyword-ideas.mjs +503 -0
  161. package/skills/seo-supervisor/scripts/lib/args.mjs +56 -0
  162. package/skills/seo-supervisor/scripts/lib/business.mjs +27 -0
  163. package/skills/seo-supervisor/scripts/lib/cdp.mjs +242 -0
  164. package/skills/seo-supervisor/scripts/lib/cli.mjs +56 -0
  165. package/skills/seo-supervisor/scripts/lib/csv.mjs +38 -0
  166. package/skills/seo-supervisor/scripts/lib/findings.mjs +100 -0
  167. package/skills/seo-supervisor/scripts/lib/google-client.mjs +9 -0
  168. package/skills/seo-supervisor/scripts/lib/html.mjs +146 -0
  169. package/skills/seo-supervisor/scripts/lib/http.mjs +28 -0
  170. package/skills/seo-supervisor/scripts/lib/image-size.mjs +78 -0
  171. package/skills/seo-supervisor/scripts/lib/is-main.mjs +13 -0
  172. package/skills/seo-supervisor/scripts/lib/net.mjs +116 -0
  173. package/skills/seo-supervisor/scripts/lib/proxy.mjs +47 -0
  174. package/skills/seo-supervisor/scripts/lib/recheck.mjs +106 -0
  175. package/skills/seo-supervisor/scripts/lib/redact.mjs +78 -0
  176. package/skills/seo-supervisor/scripts/lib/robots.mjs +73 -0
  177. package/skills/seo-supervisor/scripts/lib/score.mjs +266 -0
  178. package/skills/seo-supervisor/scripts/lib/settings-dir.mjs +81 -0
  179. package/skills/seo-supervisor/scripts/links-import.mjs +603 -0
  180. package/skills/seo-supervisor/scripts/log-scan.mjs +597 -0
  181. package/skills/seo-supervisor/scripts/og-card.mjs +273 -0
  182. package/skills/seo-supervisor/scripts/osm.mjs +359 -0
  183. package/skills/seo-supervisor/scripts/rdap.mjs +164 -0
  184. package/skills/seo-supervisor/scripts/render-report.mjs +340 -0
  185. package/skills/seo-supervisor/scripts/report/client.js +37 -0
  186. package/skills/seo-supervisor/scripts/report/diff.mjs +264 -0
  187. package/skills/seo-supervisor/scripts/report/findings.mjs +165 -0
  188. package/skills/seo-supervisor/scripts/report/format.mjs +111 -0
  189. package/skills/seo-supervisor/scripts/report/markdown.mjs +250 -0
  190. package/skills/seo-supervisor/scripts/report/model.mjs +171 -0
  191. package/skills/seo-supervisor/scripts/report/overview-lines.mjs +158 -0
  192. package/skills/seo-supervisor/scripts/report/overview.mjs +224 -0
  193. package/skills/seo-supervisor/scripts/report/page.mjs +127 -0
  194. package/skills/seo-supervisor/scripts/report/panel.mjs +172 -0
  195. package/skills/seo-supervisor/scripts/report/panels/ai.mjs +211 -0
  196. package/skills/seo-supervisor/scripts/report/panels/connections.mjs +139 -0
  197. package/skills/seo-supervisor/scripts/report/panels/content.mjs +204 -0
  198. package/skills/seo-supervisor/scripts/report/panels/data-search.mjs +379 -0
  199. package/skills/seo-supervisor/scripts/report/panels/data-site.mjs +44 -0
  200. package/skills/seo-supervisor/scripts/report/panels/links.mjs +380 -0
  201. package/skills/seo-supervisor/scripts/report/panels/local.mjs +221 -0
  202. package/skills/seo-supervisor/scripts/report/panels/site.mjs +359 -0
  203. package/skills/seo-supervisor/scripts/report/panels/speed-media.mjs +267 -0
  204. package/skills/seo-supervisor/scripts/report/sources.mjs +163 -0
  205. package/skills/seo-supervisor/scripts/report/styles.css +223 -0
  206. package/skills/seo-supervisor/scripts/report/traffic.mjs +264 -0
  207. package/skills/seo-supervisor/scripts/report-plan.mjs +241 -0
  208. package/skills/seo-supervisor/scripts/schema-check.mjs +717 -0
  209. package/skills/seo-supervisor/scripts/seo-crawl.mjs +1151 -0
  210. package/skills/seo-supervisor/scripts/seo-diff.mjs +584 -0
  211. package/skills/seo-supervisor/scripts/update-check.mjs +82 -0
  212. package/skills/seo-supervisor/site-types/content.md +55 -0
  213. package/skills/seo-supervisor/site-types/ecommerce.md +64 -0
  214. package/skills/seo-supervisor/site-types/local-business.md +118 -0
  215. package/skills/seo-supervisor/site-types/services.md +68 -0
  216. package/skills/seo-supervisor/site-types/tools.md +127 -0
  217. package/skills/seo-supervisor/strategy.md +232 -0
  218. package/skills/seo-supervisor/troubleshooting.md +56 -0
@@ -0,0 +1,362 @@
1
+ // @ts-check
2
+ // The crawler's HTTP layer: the private-address guard, the 429/503 brake and URL helpers.
3
+ import { lookup } from "node:dns";
4
+ import { get as httpGet, request as httpRequest } from "node:http";
5
+ import { get as httpsGet, request as httpsRequest } from "node:https";
6
+ import { Readable, pipeline } from "node:stream";
7
+ import { promisify } from "node:util";
8
+ import { createBrotliDecompress, createGunzip, createInflate } from "node:zlib";
9
+ import { guarded, isPublic, loopback } from "../lib/net.mjs";
10
+ import { bodyUpTo, retryAfter } from "../lib/http.mjs";
11
+ import { brake, sleep } from "../checks/crawl.mjs";
12
+
13
+ export const TEMPORARY = new Set([302, 303, 307]); // redirects that tell search engines the old URL may come back
14
+ // A redirect between URLs that differ only by a trailing slash counts under URL-02.
15
+ export const slashOnly = (a, b) => {
16
+ const x = new URL(a),
17
+ y = new URL(b);
18
+ return (
19
+ x.origin === y.origin && x.search === y.search && x.pathname.replace(/\/$/, "") === y.pathname.replace(/\/$/, "")
20
+ );
21
+ };
22
+ const SITEMAP_MAX = 50 * 1024 * 1024; // the sitemap protocol's limit per file, uncompressed
23
+ // Local cap on an unpacked page body, which also stops a small gzip that unpacks huge.
24
+ export const PAGE_MAX = 10 * 1024 * 1024;
25
+ // Reads one chunk past max when there's more, so callers can tell the body was cut.
26
+ export async function upTo(stream, max) {
27
+ const chunks = [];
28
+ let n = 0;
29
+ for await (const c of stream) {
30
+ chunks.push(c);
31
+ if ((n += c.length) > max) break;
32
+ }
33
+ return Buffer.concat(chunks);
34
+ }
35
+
36
+ // A local dev server, for notes. Narrower than the private-address test on purpose: tests run a "staging" server on
37
+ // 127.0.0.2.
38
+ export const isLocal = o => /^https?:\/\/(localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\])(:\d+)?$/i.test(o);
39
+ // Only a public host may be sent to an outside service.
40
+ export { isPublic };
41
+ export const urlOr = (u, base) => {
42
+ try {
43
+ return new URL(u, base);
44
+ } catch {
45
+ return null;
46
+ }
47
+ }; // template bugs produce invalid URLs
48
+ // Backs toCrawl: rewrites public-origin URLs onto the crawled origin.
49
+ export function mapOrigin(u, SITE_ORIGIN, START_ORIGIN) {
50
+ try {
51
+ const x = new URL(u);
52
+ if (SITE_ORIGIN && x.origin === SITE_ORIGIN && SITE_ORIGIN !== START_ORIGIN)
53
+ return START_ORIGIN + x.pathname + x.search;
54
+ return x.href;
55
+ } catch {
56
+ return u;
57
+ }
58
+ }
59
+ export function clean(u, base) {
60
+ try {
61
+ const x = new URL(u, base);
62
+ x.hash = "";
63
+ return x.href;
64
+ } catch {
65
+ return null;
66
+ }
67
+ }
68
+ export const pathKey = u => {
69
+ const x = new URL(u);
70
+ return x.pathname + x.search;
71
+ };
72
+
73
+ // fetch() for off-site URLs, connecting through guarded() so the address connected to is the one checked. The body is
74
+ // unpacked through pipeline(), not pipe(), so a timeout or dropped connection errors instead of hanging the unpacker.
75
+ // Exported for tests.
76
+ const UNPACK = { gzip: createGunzip, "x-gzip": createGunzip, deflate: createInflate, br: createBrotliDecompress };
77
+ export const pinnedFetch = (url, { headers, signal }, dns) =>
78
+ new Promise((ok, ko) => {
79
+ (url.startsWith("https:") ? httpsRequest : httpRequest)(
80
+ url,
81
+ { headers: { ...headers, "accept-encoding": "gzip, deflate, br" }, signal, lookup: guarded(dns) },
82
+ res => {
83
+ try {
84
+ const h = new Headers();
85
+ for (let i = 0; i < res.rawHeaders.length; i += 2) h.append(res.rawHeaders[i], res.rawHeaders[i + 1]);
86
+ const unpack = UNPACK[(h.get("content-encoding") || "").trim().toLowerCase()];
87
+ ok(
88
+ new Response(
89
+ [204, 205, 304].includes(res.statusCode)
90
+ ? null
91
+ : /** @type {ReadableStream} */ (Readable.toWeb(unpack ? pipeline(res, unpack(), () => {}) : res)),
92
+ { status: res.statusCode, headers: h },
93
+ ),
94
+ );
95
+ } catch (e) {
96
+ res.destroy();
97
+ ko(e);
98
+ }
99
+ },
100
+ )
101
+ .on("error", ko)
102
+ .end();
103
+ });
104
+
105
+ // One crawl's request state. toCrawl is a function because seo-crawl.mjs may learn the public origin mid-crawl (from
106
+ // robots.txt, the sitemap or the home page's canonical). Tests pass their own dns.
107
+ export function createFetcher({ startOrigin: START_ORIGIN, ua: UA, toCrawl, dns = lookup }) {
108
+ const blocked = new Map(); // URL -> why it wasn't fetched
109
+ const publicLookup = /** @type {(host: string, opts: { all: boolean }) => Promise<unknown>} */ (
110
+ promisify(guarded(dns))
111
+ );
112
+ // The crawled origin is never guarded, so a localhost or LAN site can be crawled, and a localhost crawl may reach
113
+ // other local ports (a dev server redirecting to its API). Anything else on a private, reserved or cloud-metadata
114
+ // address is blocked.
115
+ const onSite = x => x.origin === START_ORIGIN || (loopback(new URL(START_ORIGIN).hostname) && loopback(x.hostname));
116
+ async function offLimits(u) {
117
+ let x;
118
+ try {
119
+ x = new URL(u);
120
+ } catch {
121
+ return null;
122
+ }
123
+ if (onSite(x)) return null;
124
+ const why = !isPublic(u)
125
+ ? `${x.host} isn't a public address`
126
+ : await publicLookup(x.hostname, { all: true }).then(
127
+ () => null,
128
+ e => (e.code === "ENOTPUBLIC" ? e.message : null),
129
+ );
130
+ if (why) blocked.set(u, why);
131
+ return why;
132
+ }
133
+ // Off-site requests connect to the address the guard checked, so a name can't resolve differently the second time
134
+ // (DNS rebinding).
135
+ const request = (url, init) => (onSite(new URL(url)) ? fetch(url, init) : pinnedFetch(url, init, dns));
136
+ // A 429 pauses every request to the site for its Retry-After (local cap 30 s, 2 s when absent), then retries once.
137
+ // Own-site requests also pause on a 503, Google's other temporary brake, and for 2 s on no answer. Bot comparisons
138
+ // retry busy answers themselves, and a 503 to a bot may be a firewall, so only a 429 pauses them. brake() caps the
139
+ // pauses at 2 minutes in all.
140
+ // https://developers.google.com/search/docs/crawling-indexing/http-network-errors
141
+ const slow = brake();
142
+ const slowDown = res => {
143
+ slow.busy++;
144
+ slow.pause(Math.min(retryAfter(res.headers.get("retry-after")) ?? 2000, 30000));
145
+ };
146
+ // manual: false goes through follow(), so each hop passes the guard. text is the content-type pattern of 2xx bodies
147
+ // to read (true: HTML, XML, plain text). A body over max comes back empty and marked `over`, and an unread body is
148
+ // drained only up to PAGE_MAX, so no endless answer can fill memory.
149
+ async function get(
150
+ url,
151
+ {
152
+ manual = true,
153
+ text = /** @type {boolean | RegExp} */ (true),
154
+ ua = UA,
155
+ accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
156
+ max = PAGE_MAX,
157
+ } = {},
158
+ ) {
159
+ if (!manual) return follow(url, ua);
160
+ const own = ua === UA && urlOr(url)?.origin === START_ORIGIN;
161
+ let waited = false;
162
+ for (let attempt = 0; attempt < 2; attempt++) {
163
+ try {
164
+ if (slow.until > Date.now()) await sleep(slow.until - Date.now());
165
+ const t = performance.now(); // time to the response headers, in ms
166
+ const res = await request(url, {
167
+ redirect: "manual",
168
+ headers: { "user-agent": ua, accept },
169
+ signal: AbortSignal.timeout(20000),
170
+ });
171
+ if ((res.status === 429 || (res.status === 503 && own)) && !waited) {
172
+ waited = true;
173
+ attempt--;
174
+ slowDown(res);
175
+ await bodyUpTo(res, PAGE_MAX).catch(() => {});
176
+ continue;
177
+ }
178
+ const ms = Math.round(performance.now() - t),
179
+ ct = res.headers.get("content-type") || "";
180
+ const want = text === true ? /html|xml|text\/plain/ : text;
181
+ let body = "",
182
+ over = false;
183
+ if (want && res.status < 300 && want.test(ct)) {
184
+ const b = await bodyUpTo(res, max);
185
+ if (!(over = !b)) body = new TextDecoder().decode(b);
186
+ } else await bodyUpTo(res, PAGE_MAX).catch(() => {});
187
+ return { status: res.status, headers: res.headers, ct, body, location: res.headers.get("location"), ms, over };
188
+ } catch (e) {
189
+ // The guard refused the resolved address at connect time, so a retry would fail the same way.
190
+ if (e.code === "ENOTPUBLIC")
191
+ return { status: 0, error: e.message, refused: true, headers: new Headers(), ct: "", body: "" };
192
+ if (attempt === 1)
193
+ return { status: 0, error: String(e.message || e), headers: new Headers(), ct: "", body: "" };
194
+ if (own) {
195
+ slow.silent++;
196
+ slow.pause(2000);
197
+ } else await sleep(500);
198
+ }
199
+ }
200
+ }
201
+ // A blocked redirect ends the chain at the redirect itself, which is what the server answered. Google follows 10 hops
202
+ // for pages and 5 for robots.txt, so seo-crawl.mjs passes 5 there.
203
+ // https://developers.google.com/search/docs/crawling-indexing/http-network-errors
204
+ // https://developers.google.com/search/docs/crawling-indexing/robots/robots_txt
205
+ async function follow(url, ua, hops = 10) {
206
+ const chain = [];
207
+ let cur = url,
208
+ why = await offLimits(cur),
209
+ last = null;
210
+ if (why) return { status: 0, error: why, chain, finalUrl: cur, headers: new Headers(), ct: "", body: "" };
211
+ for (let i = 0; i <= hops; i++) {
212
+ const r = await get(cur, { ua });
213
+ if (r.refused) {
214
+ blocked.set(cur, r.error);
215
+ return last ? { ...last, chain, finalUrl: chain.at(-1).url } : { ...r, chain, finalUrl: cur };
216
+ }
217
+ chain.push({ url: cur, status: r.status });
218
+ if (r.status >= 300 && r.status < 400 && r.location) {
219
+ const next = new URL(r.location, cur).href;
220
+ if ((why = await offLimits(next))) return { ...r, chain, finalUrl: cur };
221
+ last = r;
222
+ cur = next;
223
+ continue;
224
+ }
225
+ return { ...r, chain, finalUrl: cur };
226
+ }
227
+ return { status: 0, error: "too many redirects", chain, finalUrl: cur, headers: new Headers(), ct: "", body: "" };
228
+ }
229
+ // The start of an own-site file by Range request, read no further if the range is ignored. A redirect off the site
230
+ // returns null, so no third party is contacted, as does one that maps back onto the same URL, which would loop.
231
+ // size is the whole file: Content-Range's total, or Content-Length when the range is ignored. Answers are cached per
232
+ // URL and max, since several checks read the same file, and a 429 or 503 slows the crawl and retries once.
233
+ const starts = new Map();
234
+ const firstBytes = (url, max = 65536) => {
235
+ const k = `${max} ${url}`;
236
+ return starts.get(k) ?? starts.set(k, readStart(url, max)).get(k);
237
+ };
238
+ async function readStart(url, max) {
239
+ try {
240
+ let waited = false;
241
+ for (let hop = 0; hop < 5; hop++) {
242
+ if (slow.until > Date.now()) await sleep(slow.until - Date.now());
243
+ const r = await fetch(url, {
244
+ redirect: "manual",
245
+ headers: { "user-agent": UA, range: `bytes=0-${max - 1}`, accept: "image/avif,image/webp,image/*,*/*;q=0.8" },
246
+ signal: AbortSignal.timeout(15000),
247
+ });
248
+ if ((r.status === 429 || r.status === 503) && !waited) {
249
+ waited = true;
250
+ hop--;
251
+ slowDown(r);
252
+ await r.body?.cancel();
253
+ continue;
254
+ }
255
+ const loc = r.headers.get("location");
256
+ if (r.status >= 300 && r.status < 400 && loc) {
257
+ await r.body?.cancel();
258
+ const next = clean(toCrawl(new URL(loc, url).href));
259
+ if (!next || next === url || new URL(next).origin !== START_ORIGIN) return null;
260
+ url = next;
261
+ continue;
262
+ }
263
+ const chunks = [];
264
+ let n = 0;
265
+ if (r.body)
266
+ for await (const c of r.body) {
267
+ chunks.push(c);
268
+ if ((n += c.length) >= max) break;
269
+ }
270
+ return {
271
+ status: r.status,
272
+ type: r.headers.get("content-type") || "",
273
+ headers: r.headers,
274
+ bytes: Buffer.concat(chunks),
275
+ size:
276
+ Number(
277
+ r.status === 206
278
+ ? r.headers.get("content-range")?.match(/\/(\d+)$/)?.[1]
279
+ : r.headers.get("content-length"),
280
+ ) || 0,
281
+ };
282
+ }
283
+ return { status: 0, error: "too many redirects" };
284
+ } catch (e) {
285
+ return { status: 0, error: String(e.message || e) };
286
+ }
287
+ }
288
+ // Gunzips by the magic bytes, whatever the content type says: fetch undoes only Content-Encoding, and a .gz file may
289
+ // be compressed twice. Redirects are followed by hand, 5 at most, so each hop passes the guard.
290
+ async function fetchSitemap(url, retry = true) {
291
+ try {
292
+ let res,
293
+ waited = false;
294
+ for (let hop = 0; ; hop++) {
295
+ const why = await offLimits(url);
296
+ if (why) return { status: 0, error: why };
297
+ if (slow.until > Date.now()) await sleep(slow.until - Date.now());
298
+ res = await request(url, {
299
+ redirect: "manual",
300
+ headers: { "user-agent": UA, accept: "application/xml,text/xml;q=0.9,*/*;q=0.8" },
301
+ signal: AbortSignal.timeout(60000),
302
+ });
303
+ if ((res.status === 429 || (res.status === 503 && urlOr(url)?.origin === START_ORIGIN)) && !waited) {
304
+ waited = true;
305
+ hop--;
306
+ slowDown(res);
307
+ await res.body?.cancel();
308
+ continue;
309
+ }
310
+ const loc = res.headers.get("location");
311
+ if (res.status < 300 || res.status > 399 || !loc || hop === 5) break;
312
+ await res.body?.cancel();
313
+ url = new URL(loc, url).href;
314
+ }
315
+ if (res.status !== 200 || !res.body) {
316
+ await res.body?.cancel();
317
+ return { status: res.status };
318
+ }
319
+ let buf = await upTo(res.body, SITEMAP_MAX);
320
+ if (buf[0] === 0x1f && buf[1] === 0x8b) {
321
+ const gz = createGunzip();
322
+ gz.end(buf);
323
+ buf = await upTo(gz, SITEMAP_MAX).catch(() => null);
324
+ if (!buf) return { status: 200, body: "", broken: "it's a gzip file that doesn't unzip" };
325
+ }
326
+ const bom = buf[0] === 0xef && buf[1] === 0xbb && buf[2] === 0xbf ? 3 : 0;
327
+ return { status: 200, body: buf.toString("utf8", bom, SITEMAP_MAX), tooBig: buf.length > SITEMAP_MAX };
328
+ } catch (e) {
329
+ if (e.code === "ENOTPUBLIC") {
330
+ blocked.set(url, e.message);
331
+ return { status: 0, error: e.message };
332
+ }
333
+ if (retry) {
334
+ await sleep(500);
335
+ return fetchSitemap(url, false);
336
+ }
337
+ return { status: 0, error: String(e.message || e) };
338
+ }
339
+ }
340
+ // Raw header lines, since fetch joins repeated headers with commas: "bingbot: noarchive" then "noindex" would read as
341
+ // one value whose noindex is Bing's.
342
+ const xRobotsLines = url =>
343
+ new Promise(ok => {
344
+ const req = (url.startsWith("https:") ? httpsGet : httpGet)(
345
+ url,
346
+ {
347
+ headers: { "user-agent": UA, accept: "text/html" },
348
+ timeout: 15000,
349
+ ...(onSite(new URL(url)) ? {} : { lookup: guarded(dns) }),
350
+ },
351
+ res => {
352
+ const lines = [];
353
+ for (let i = 0; i < res.rawHeaders.length; i += 2)
354
+ if (res.rawHeaders[i].toLowerCase() === "x-robots-tag") lines.push(res.rawHeaders[i + 1]);
355
+ res.destroy();
356
+ ok(res.statusCode === 200 ? lines : null);
357
+ },
358
+ );
359
+ req.on("timeout", () => req.destroy(new Error("timeout"))).on("error", () => ok(null));
360
+ });
361
+ return { get, follow, firstBytes, fetchSitemap, xRobotsLines, blocked, slow };
362
+ }