seo-supervisor 1.2.0 → 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 (207) hide show
  1. package/.claude-plugin/icon.png +0 -0
  2. package/.claude-plugin/marketplace.json +2 -2
  3. package/.claude-plugin/plugin.json +16 -3
  4. package/CHANGELOG.md +430 -0
  5. package/NOTICE +7 -0
  6. package/README.md +230 -25
  7. package/agents/seo-auditor.md +16 -0
  8. package/agents/seo-reviewer.md +16 -0
  9. package/bin/agents.mjs +194 -29
  10. package/bin/extras.mjs +422 -0
  11. package/bin/prompt.mjs +34 -14
  12. package/bin/seo-supervisor.mjs +386 -53
  13. package/commands/seo-audit.md +29 -3
  14. package/commands/seo-brief.md +28 -0
  15. package/commands/seo-connect.md +27 -0
  16. package/commands/seo-fix.md +24 -3
  17. package/commands/seo-grow.md +26 -0
  18. package/commands/seo-launch.md +17 -3
  19. package/commands/seo-review.md +13 -1
  20. package/commands/seo-rewrite.md +25 -0
  21. package/commands/seo-setup.md +17 -1
  22. package/commands/seo-watch.md +28 -0
  23. package/hooks/hooks.json +117 -0
  24. package/package.json +20 -7
  25. package/skills/seo-supervisor/NOTICE +7 -0
  26. package/skills/seo-supervisor/SKILL.md +302 -21
  27. package/skills/seo-supervisor/audience.md +61 -0
  28. package/skills/seo-supervisor/examples/drafts/security.md +41 -0
  29. package/skills/seo-supervisor/examples/hooks/README.md +28 -0
  30. package/skills/seo-supervisor/examples/hooks/claude-code-settings.json +15 -0
  31. package/skills/seo-supervisor/examples/hooks/codex-hooks.json +17 -0
  32. package/skills/seo-supervisor/examples/hooks/copilot-hooks.json +15 -0
  33. package/skills/seo-supervisor/examples/hooks/cursor-hooks.json +11 -0
  34. package/skills/seo-supervisor/examples/hooks/github-actions.yml +21 -0
  35. package/skills/seo-supervisor/examples/hooks/pre-commit +17 -0
  36. package/skills/seo-supervisor/examples/hooks/reading-ease.yml +24 -0
  37. package/skills/seo-supervisor/examples/sample-audit.json +94 -2
  38. package/skills/seo-supervisor/examples/sample-report.html +111 -61
  39. package/skills/seo-supervisor/examples/sample-report.md +147 -44
  40. package/skills/seo-supervisor/examples/scheduled-runs.md +89 -0
  41. package/skills/seo-supervisor/examples/snippets.md +648 -1
  42. package/skills/seo-supervisor/grow.md +342 -0
  43. package/skills/seo-supervisor/og-images.md +85 -0
  44. package/skills/seo-supervisor/page-types.md +124 -0
  45. package/skills/seo-supervisor/planning.md +19 -7
  46. package/skills/seo-supervisor/profile-template.md +41 -0
  47. package/skills/seo-supervisor/report-format.md +177 -10
  48. package/skills/seo-supervisor/rewrite.md +59 -0
  49. package/skills/seo-supervisor/rules/ai-search.md +65 -12
  50. package/skills/seo-supervisor/rules/content.md +33 -9
  51. package/skills/seo-supervisor/rules/crawl-index.md +33 -6
  52. package/skills/seo-supervisor/rules/internal-linking.md +49 -6
  53. package/skills/seo-supervisor/rules/launch-monitoring.md +17 -8
  54. package/skills/seo-supervisor/rules/media.md +13 -1
  55. package/skills/seo-supervisor/rules/metadata.md +41 -9
  56. package/skills/seo-supervisor/rules/performance.md +50 -5
  57. package/skills/seo-supervisor/rules/rendering.md +39 -2
  58. package/skills/seo-supervisor/rules/search-intent.md +32 -0
  59. package/skills/seo-supervisor/rules/sitemaps-robots.md +24 -12
  60. package/skills/seo-supervisor/rules/structured-data.md +37 -14
  61. package/skills/seo-supervisor/rules/trust-security.md +25 -2
  62. package/skills/seo-supervisor/rules/urls.md +10 -2
  63. package/skills/seo-supervisor/scripts/ai-answers.mjs +314 -0
  64. package/skills/seo-supervisor/scripts/backlinks.mjs +412 -0
  65. package/skills/seo-supervisor/scripts/change-check.mjs +281 -0
  66. package/skills/seo-supervisor/scripts/checks/agents.mjs +488 -0
  67. package/skills/seo-supervisor/scripts/checks/assets.mjs +404 -0
  68. package/skills/seo-supervisor/scripts/checks/bots.mjs +146 -0
  69. package/skills/seo-supervisor/scripts/checks/business-type.mjs +193 -0
  70. package/skills/seo-supervisor/scripts/checks/content.mjs +391 -0
  71. package/skills/seo-supervisor/scripts/checks/coverage.mjs +184 -0
  72. package/skills/seo-supervisor/scripts/checks/crawl.mjs +95 -0
  73. package/skills/seo-supervisor/scripts/checks/hreflang.mjs +396 -0
  74. package/skills/seo-supervisor/scripts/checks/hygiene.mjs +227 -0
  75. package/skills/seo-supervisor/scripts/checks/lighthouse.mjs +271 -0
  76. package/skills/seo-supervisor/scripts/checks/link-strength.mjs +59 -0
  77. package/skills/seo-supervisor/scripts/checks/links.mjs +360 -0
  78. package/skills/seo-supervisor/scripts/checks/local.mjs +101 -0
  79. package/skills/seo-supervisor/scripts/checks/media.mjs +194 -0
  80. package/skills/seo-supervisor/scripts/checks/outbound.mjs +53 -0
  81. package/skills/seo-supervisor/scripts/checks/page.mjs +223 -0
  82. package/skills/seo-supervisor/scripts/checks/probes.mjs +130 -0
  83. package/skills/seo-supervisor/scripts/checks/render.mjs +552 -0
  84. package/skills/seo-supervisor/scripts/checks/robots.mjs +144 -0
  85. package/skills/seo-supervisor/scripts/checks/schema.mjs +206 -0
  86. package/skills/seo-supervisor/scripts/checks/site-agents.mjs +79 -0
  87. package/skills/seo-supervisor/scripts/checks/site-content.mjs +135 -0
  88. package/skills/seo-supervisor/scripts/checks/site-hygiene.mjs +202 -0
  89. package/skills/seo-supervisor/scripts/checks/site-pages.mjs +474 -0
  90. package/skills/seo-supervisor/scripts/checks/site-security.mjs +102 -0
  91. package/skills/seo-supervisor/scripts/checks/sitemap.mjs +473 -0
  92. package/skills/seo-supervisor/scripts/checks/speed.mjs +267 -0
  93. package/skills/seo-supervisor/scripts/checks/technical.mjs +368 -0
  94. package/skills/seo-supervisor/scripts/checks/tls.mjs +297 -0
  95. package/skills/seo-supervisor/scripts/checks/trust.mjs +421 -0
  96. package/skills/seo-supervisor/scripts/checks/visual.mjs +1132 -0
  97. package/skills/seo-supervisor/scripts/checks/writing.mjs +192 -0
  98. package/skills/seo-supervisor/scripts/commoncrawl.mjs +452 -0
  99. package/skills/seo-supervisor/scripts/connect-keys.mjs +422 -0
  100. package/skills/seo-supervisor/scripts/content-scan.mjs +515 -158
  101. package/skills/seo-supervisor/scripts/crawl/catalog.mjs +1248 -0
  102. package/skills/seo-supervisor/scripts/crawl/fetch.mjs +362 -0
  103. package/skills/seo-supervisor/scripts/crawl/page.mjs +741 -0
  104. package/skills/seo-supervisor/scripts/crawl/queue.mjs +190 -0
  105. package/skills/seo-supervisor/scripts/dashboard.mjs +140 -0
  106. package/skills/seo-supervisor/scripts/data/ai-bots.json +38 -0
  107. package/skills/seo-supervisor/scripts/data/build-schema-vocab.mjs +57 -0
  108. package/skills/seo-supervisor/scripts/data/business-types.json +338 -0
  109. package/skills/seo-supervisor/scripts/data/google-rich-results.json +79 -0
  110. package/skills/seo-supervisor/scripts/data/schema-vocab.json +1 -0
  111. package/skills/seo-supervisor/scripts/deploy-check.mjs +462 -0
  112. package/skills/seo-supervisor/scripts/disavow.mjs +176 -0
  113. package/skills/seo-supervisor/scripts/doctor.mjs +174 -0
  114. package/skills/seo-supervisor/scripts/geo-grid.mjs +371 -0
  115. package/skills/seo-supervisor/scripts/google/search-console.mjs +151 -0
  116. package/skills/seo-supervisor/scripts/google/session.mjs +167 -0
  117. package/skills/seo-supervisor/scripts/google-updates.mjs +189 -0
  118. package/skills/seo-supervisor/scripts/google.mjs +1341 -0
  119. package/skills/seo-supervisor/scripts/gsc-import.mjs +298 -0
  120. package/skills/seo-supervisor/scripts/guard/adapters/claude-code.mjs +149 -0
  121. package/skills/seo-supervisor/scripts/guard/adapters/cline.mjs +28 -0
  122. package/skills/seo-supervisor/scripts/guard/adapters/codex.mjs +26 -0
  123. package/skills/seo-supervisor/scripts/guard/adapters/copilot.mjs +36 -0
  124. package/skills/seo-supervisor/scripts/guard/adapters/cursor.mjs +33 -0
  125. package/skills/seo-supervisor/scripts/guard/adapters/devin.mjs +25 -0
  126. package/skills/seo-supervisor/scripts/guard/adapters/edits.mjs +124 -0
  127. package/skills/seo-supervisor/scripts/guard/mode.mjs +37 -0
  128. package/skills/seo-supervisor/scripts/guard/rules.mjs +931 -0
  129. package/skills/seo-supervisor/scripts/guard.mjs +74 -0
  130. package/skills/seo-supervisor/scripts/images.mjs +408 -0
  131. package/skills/seo-supervisor/scripts/indexnow.mjs +300 -0
  132. package/skills/seo-supervisor/scripts/issues.mjs +217 -0
  133. package/skills/seo-supervisor/scripts/keys/authority.mjs +135 -0
  134. package/skills/seo-supervisor/scripts/keys/bing.mjs +239 -0
  135. package/skills/seo-supervisor/scripts/keys/clarity.mjs +137 -0
  136. package/skills/seo-supervisor/scripts/keys/dataforseo.mjs +57 -0
  137. package/skills/seo-supervisor/scripts/keys/googleplaces.mjs +26 -0
  138. package/skills/seo-supervisor/scripts/keys/http.mjs +212 -0
  139. package/skills/seo-supervisor/scripts/keys/matomo.mjs +138 -0
  140. package/skills/seo-supervisor/scripts/keys/openai.mjs +26 -0
  141. package/skills/seo-supervisor/scripts/keys/perplexity.mjs +26 -0
  142. package/skills/seo-supervisor/scripts/keys/posthog.mjs +165 -0
  143. package/skills/seo-supervisor/scripts/keys/semrush.mjs +25 -0
  144. package/skills/seo-supervisor/scripts/keys/services.mjs +41 -0
  145. package/skills/seo-supervisor/scripts/keys/store.mjs +140 -0
  146. package/skills/seo-supervisor/scripts/keys/visits.mjs +58 -0
  147. package/skills/seo-supervisor/scripts/keys/youtube.mjs +84 -0
  148. package/skills/seo-supervisor/scripts/keyword-data.mjs +316 -0
  149. package/skills/seo-supervisor/scripts/keyword-ideas.mjs +503 -0
  150. package/skills/seo-supervisor/scripts/lib/args.mjs +56 -0
  151. package/skills/seo-supervisor/scripts/lib/business.mjs +27 -0
  152. package/skills/seo-supervisor/scripts/lib/cdp.mjs +242 -0
  153. package/skills/seo-supervisor/scripts/lib/cli.mjs +56 -0
  154. package/skills/seo-supervisor/scripts/lib/csv.mjs +38 -0
  155. package/skills/seo-supervisor/scripts/lib/findings.mjs +100 -0
  156. package/skills/seo-supervisor/scripts/lib/google-client.mjs +9 -0
  157. package/skills/seo-supervisor/scripts/lib/html.mjs +146 -0
  158. package/skills/seo-supervisor/scripts/lib/http.mjs +28 -0
  159. package/skills/seo-supervisor/scripts/lib/image-size.mjs +78 -0
  160. package/skills/seo-supervisor/scripts/lib/is-main.mjs +13 -0
  161. package/skills/seo-supervisor/scripts/lib/net.mjs +116 -0
  162. package/skills/seo-supervisor/scripts/lib/proxy.mjs +47 -0
  163. package/skills/seo-supervisor/scripts/lib/recheck.mjs +106 -0
  164. package/skills/seo-supervisor/scripts/lib/redact.mjs +78 -0
  165. package/skills/seo-supervisor/scripts/lib/robots.mjs +73 -0
  166. package/skills/seo-supervisor/scripts/lib/score.mjs +266 -0
  167. package/skills/seo-supervisor/scripts/lib/settings-dir.mjs +81 -0
  168. package/skills/seo-supervisor/scripts/links-import.mjs +603 -0
  169. package/skills/seo-supervisor/scripts/log-scan.mjs +597 -0
  170. package/skills/seo-supervisor/scripts/og-card.mjs +273 -0
  171. package/skills/seo-supervisor/scripts/osm.mjs +359 -0
  172. package/skills/seo-supervisor/scripts/rdap.mjs +164 -0
  173. package/skills/seo-supervisor/scripts/render-report.mjs +324 -690
  174. package/skills/seo-supervisor/scripts/report/client.js +37 -0
  175. package/skills/seo-supervisor/scripts/report/diff.mjs +264 -0
  176. package/skills/seo-supervisor/scripts/report/findings.mjs +165 -0
  177. package/skills/seo-supervisor/scripts/report/format.mjs +111 -0
  178. package/skills/seo-supervisor/scripts/report/markdown.mjs +250 -0
  179. package/skills/seo-supervisor/scripts/report/model.mjs +171 -0
  180. package/skills/seo-supervisor/scripts/report/overview-lines.mjs +158 -0
  181. package/skills/seo-supervisor/scripts/report/overview.mjs +224 -0
  182. package/skills/seo-supervisor/scripts/report/page.mjs +127 -0
  183. package/skills/seo-supervisor/scripts/report/panel.mjs +172 -0
  184. package/skills/seo-supervisor/scripts/report/panels/ai.mjs +211 -0
  185. package/skills/seo-supervisor/scripts/report/panels/connections.mjs +139 -0
  186. package/skills/seo-supervisor/scripts/report/panels/content.mjs +204 -0
  187. package/skills/seo-supervisor/scripts/report/panels/data-search.mjs +379 -0
  188. package/skills/seo-supervisor/scripts/report/panels/data-site.mjs +44 -0
  189. package/skills/seo-supervisor/scripts/report/panels/links.mjs +380 -0
  190. package/skills/seo-supervisor/scripts/report/panels/local.mjs +221 -0
  191. package/skills/seo-supervisor/scripts/report/panels/site.mjs +359 -0
  192. package/skills/seo-supervisor/scripts/report/panels/speed-media.mjs +267 -0
  193. package/skills/seo-supervisor/scripts/report/sources.mjs +163 -0
  194. package/skills/seo-supervisor/scripts/report/styles.css +223 -0
  195. package/skills/seo-supervisor/scripts/report/traffic.mjs +264 -0
  196. package/skills/seo-supervisor/scripts/report-plan.mjs +112 -33
  197. package/skills/seo-supervisor/scripts/schema-check.mjs +717 -0
  198. package/skills/seo-supervisor/scripts/seo-crawl.mjs +1086 -638
  199. package/skills/seo-supervisor/scripts/seo-diff.mjs +584 -0
  200. package/skills/seo-supervisor/scripts/update-check.mjs +82 -0
  201. package/skills/seo-supervisor/site-types/content.md +34 -1
  202. package/skills/seo-supervisor/site-types/ecommerce.md +38 -1
  203. package/skills/seo-supervisor/site-types/local-business.md +96 -6
  204. package/skills/seo-supervisor/site-types/services.md +46 -0
  205. package/skills/seo-supervisor/site-types/tools.md +3 -3
  206. package/skills/seo-supervisor/strategy.md +232 -0
  207. package/skills/seo-supervisor/troubleshooting.md +56 -0
@@ -0,0 +1,242 @@
1
+ // @ts-check
2
+ // Chrome or Edge over the DevTools protocol, with no dependencies. Each launch gets a throwaway profile, removed on
3
+ // close; the browser is killed on any failure and when this process exits or gets SIGINT or SIGTERM.
4
+ import { spawn } from "node:child_process";
5
+ import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
6
+ import { tmpdir } from "node:os";
7
+ import { join } from "node:path";
8
+ import { chromeProxyArgs } from "./proxy.mjs";
9
+
10
+ // Chrome's sandbox won't start as root on Linux or in most containers, and a container's /dev/shm is often too small,
11
+ // so there both are turned off and the page's scripts run with fewer protections. Container hints: /.dockerenv,
12
+ // /run/.containerenv (Podman) and KUBERNETES_SERVICE_HOST (set in every pod).
13
+ // https://docs.podman.io/en/latest/markdown/podman-run.1.html
14
+ // https://kubernetes.io/docs/tasks/run-application/access-api-from-pod/
15
+ export function containerArgs({
16
+ platform = process.platform,
17
+ uid = process.getuid?.(),
18
+ env = process.env,
19
+ exists = existsSync,
20
+ } = {}) {
21
+ const inContainer =
22
+ uid === 0 || exists("/.dockerenv") || exists("/run/.containerenv") || !!env.KUBERNETES_SERVICE_HOST;
23
+ return platform === "linux" && inContainer ? ["--no-sandbox", "--disable-dev-shm-usage"] : [];
24
+ }
25
+
26
+ // Chrome's own background traffic, off: without these, headless Chrome contacts Google unasked. Every Chrome this skill
27
+ // starts gets them (launchChrome, checks/render.mjs, og-card.mjs, checks/lighthouse.mjs). Names come from Chromium's
28
+ // chrome_switches.h, command_line_switches.h and BASE_FEATURE lines. What each feature reached for behind a refusing
29
+ // proxy (Chrome 157): OptimizationHints, Translate and MediaRouter (their services), NetworkTimeServiceQuerying
30
+ // (clients2.google.com/time), AutofillServerCommunication (content-autofill.googleapis.com, for a page's forms),
31
+ // SafeBrowsingHashPrefixRealTimeLookups (www.gstatic.com/ohttp_gateway), AimEnabled (www.google.com/async/folae) and
32
+ // PreconnectToSearch (www.google.com); SkipListAccountsWithoutGaiaCookies skips accounts.google.com/ListAccounts.
33
+ // Chrome reads only the last --disable-features, --enable-features and --host-resolver-rules, so a caller's own list
34
+ // must include these.
35
+ // update.googleapis.com resolves to ^NOTFOUND: Chrome 157 pings it on close after a page got real input, and no switch
36
+ // or feature stops that (newer Chromium skips it headless). The guard's proxy sends that host here too
37
+ // (startGuard in checks/render.mjs). No page loads anything from it.
38
+ export const CHROME_FLAGS = [
39
+ "--disable-background-networking",
40
+ "--disable-component-update",
41
+ "--disable-sync",
42
+ "--disable-default-apps",
43
+ "--no-pings",
44
+ "--disable-domain-reliability",
45
+ "--disable-features=OptimizationHints,Translate,MediaRouter,NetworkTimeServiceQuerying,AutofillServerCommunication,SafeBrowsingHashPrefixRealTimeLookups,AimEnabled,PreconnectToSearch",
46
+ "--enable-features=SkipListAccountsWithoutGaiaCookies",
47
+ "--host-resolver-rules=MAP update.googleapis.com ^NOTFOUND",
48
+ ];
49
+ // The configured proxy's flags (chromeProxyArgs), with update.googleapis.com sent direct to the rule above so it
50
+ // doesn't leave through that proxy either. The guard's flags do the same.
51
+ export function ownProxyArgs(env = process.env) {
52
+ const args = chromeProxyArgs(env),
53
+ skip = "update.googleapis.com";
54
+ if (!args.length) return args;
55
+ return args.some(a => a.startsWith("--proxy-bypass-list="))
56
+ ? args.map(a => (a.startsWith("--proxy-bypass-list=") ? `${a};${skip}` : a))
57
+ : [...args, `--proxy-bypass-list=${skip}`];
58
+ }
59
+ // A throwaway profile whose Local State turns metrics reporting off (pref names from Chromium's metrics_pref_names.h).
60
+ // Where Chrome was installed with usage statistics on, a fresh profile otherwise uploads metrics
61
+ // (clientservices.googleapis.com/uma/v2). Every launch site uses it.
62
+ /** @param {string} dir */
63
+ export function quietProfile(dir) {
64
+ mkdirSync(dir, { recursive: true });
65
+ writeFileSync(join(dir, "Local State"), JSON.stringify({ user_experience_metrics: { reporting_enabled: false } }));
66
+ return dir;
67
+ }
68
+
69
+ // args: extra Chrome flags, added after the standard ones (none by default).
70
+ export async function launchChrome(browserPath, { headless = true, timeoutMs = 30000, args: extra = [] } = {}) {
71
+ const profile = quietProfile(mkdtempSync(join(tmpdir(), "seo-supervisor-cdp-")));
72
+ const args = [
73
+ headless && "--headless=new",
74
+ "--disable-gpu",
75
+ "--no-first-run",
76
+ "--no-default-browser-check",
77
+ "--disable-extensions",
78
+ "--hide-scrollbars",
79
+ "--mute-audio",
80
+ ...CHROME_FLAGS,
81
+ ...containerArgs(),
82
+ ...ownProxyArgs(),
83
+ `--user-data-dir=${profile}`,
84
+ "--remote-debugging-pipe",
85
+ ...extra,
86
+ "about:blank",
87
+ ].filter(Boolean);
88
+ const proc = spawn(browserPath, args, { stdio: ["ignore", "ignore", "pipe", "pipe", "pipe"] });
89
+ const pending = new Map(),
90
+ listeners = new Set();
91
+ let nextId = 0,
92
+ buf = "",
93
+ stderr = "",
94
+ dead = null;
95
+ const exited = new Promise(ok => {
96
+ proc.once("exit", ok);
97
+ proc.once("error", ok);
98
+ });
99
+ const kill = () => {
100
+ try {
101
+ proc.kill("SIGKILL");
102
+ } catch {}
103
+ };
104
+ const die = err => {
105
+ dead ||= err;
106
+ for (const p of pending.values()) p.fail(dead);
107
+ pending.clear();
108
+ };
109
+ const onExit = () => {
110
+ kill();
111
+ try {
112
+ rmSync(profile, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
113
+ } catch {}
114
+ };
115
+ // Ctrl+C or a kill: close as usual, then let the signal end the process as it would have, unless the caller handles
116
+ // it. A second Ctrl+C meanwhile exits at once, and the exit handler still cleans up.
117
+ const onSignal = sig => {
118
+ unhookSignals();
119
+ close().then(() => {
120
+ if (!process.listenerCount(sig)) process.kill(process.pid, sig);
121
+ });
122
+ };
123
+ const unhookSignals = () => {
124
+ process.off("SIGINT", onSignal);
125
+ process.off("SIGTERM", onSignal);
126
+ };
127
+ process.once("exit", onExit); // the caller crashed or forgot close()
128
+ process.on("SIGINT", onSignal);
129
+ process.on("SIGTERM", onSignal);
130
+ proc.once("error", die);
131
+ proc.once("exit", code =>
132
+ die(
133
+ new Error(`browser exited (${code})${stderr.trim() ? `: ${stderr.trim().split("\n").slice(-3).join(" ")}` : ""}`),
134
+ ),
135
+ );
136
+ proc.stderr.on("data", d => {
137
+ stderr = (stderr + d).slice(-2000);
138
+ });
139
+ // --remote-debugging-pipe: fd 3 carries commands, fd 4 the replies, each JSON message ending in a NUL byte.
140
+ const toBrowser = /** @type {import("node:stream").Writable} */ (proc.stdio[3]),
141
+ fromBrowser = /** @type {import("node:stream").Readable} */ (proc.stdio[4]);
142
+ toBrowser.on("error", () => {}); // EPIPE once the browser is gone; die() reports it
143
+ fromBrowser.setEncoding("utf8"); // a multi-byte character can straddle two reads
144
+ fromBrowser.on("data", d => {
145
+ buf += d;
146
+ for (let k; (k = buf.indexOf("\0")) >= 0; buf = buf.slice(k + 1)) {
147
+ const msg = JSON.parse(buf.slice(0, k)),
148
+ p = pending.get(msg.id);
149
+ if (msg.method) {
150
+ for (const l of listeners) l(msg);
151
+ continue;
152
+ }
153
+ if (!p) continue; // replies that already timed out
154
+ pending.delete(msg.id);
155
+ if (msg.error) p.fail(new Error(`${p.method}: ${msg.error.message}`));
156
+ else p.ok(msg.result);
157
+ }
158
+ });
159
+
160
+ const send = (method, params = {}, sessionId) =>
161
+ new Promise((ok, fail) => {
162
+ if (dead) return fail(dead);
163
+ const id = ++nextId,
164
+ timer = setTimeout(() => {
165
+ pending.delete(id);
166
+ fail(new Error(`${method} timed out after ${timeoutMs / 1000} s`));
167
+ }, timeoutMs);
168
+ pending.set(id, {
169
+ method,
170
+ ok: v => {
171
+ clearTimeout(timer);
172
+ ok(v);
173
+ },
174
+ fail: e => {
175
+ clearTimeout(timer);
176
+ fail(e);
177
+ },
178
+ });
179
+ toBrowser.write(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) }) + "\0");
180
+ });
181
+ const close = async () => {
182
+ if (!dead) await send("Browser.close").catch(() => {});
183
+ let grace; // 5 s for the browser to exit by itself, then it's killed; cleared so a quick exit doesn't hold this process
184
+ const gone = await Promise.race([
185
+ exited.then(() => true),
186
+ new Promise(ok => {
187
+ grace = setTimeout(ok, 5000, false);
188
+ }),
189
+ ]);
190
+ clearTimeout(grace);
191
+ if (!gone) {
192
+ kill();
193
+ await exited;
194
+ }
195
+ process.off("exit", onExit);
196
+ unhookSignals();
197
+ try {
198
+ rmSync(profile, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 });
199
+ } catch {} // Windows keeps files locked for a moment
200
+ };
201
+ try {
202
+ await send("Browser.getVersion");
203
+ } catch (e) {
204
+ kill();
205
+ await close();
206
+ throw e;
207
+ }
208
+
209
+ return {
210
+ pid: proc.pid,
211
+ profile,
212
+ send,
213
+ close,
214
+ // A new tab on a flat session, its commands tagged with the session id over the same pipe. on(event, fn) gets the
215
+ // tab's events until it closes. isolated: its own browser context (cookies, storage, cache), removed with the tab.
216
+ async newPage({ isolated = false } = {}) {
217
+ const context = isolated ? (await send("Target.createBrowserContext")).browserContextId : null;
218
+ const { targetId } = await send("Target.createTarget", {
219
+ url: "about:blank",
220
+ ...(context ? { browserContextId: context } : {}),
221
+ });
222
+ const { sessionId } = await send("Target.attachToTarget", { targetId, flatten: true });
223
+ const mine = new Set();
224
+ return {
225
+ sessionId,
226
+ send: (method, params) => send(method, params, sessionId),
227
+ on: (method, fn) => {
228
+ const l = m => m.sessionId === sessionId && m.method === method && fn(m.params);
229
+ listeners.add(l);
230
+ mine.add(l);
231
+ },
232
+ // Removing the context closes its tab too.
233
+ close: () => {
234
+ for (const l of mine) listeners.delete(l);
235
+ return context
236
+ ? send("Target.disposeBrowserContext", { browserContextId: context })
237
+ : send("Target.closeTarget", { targetId });
238
+ },
239
+ };
240
+ },
241
+ };
242
+ }
@@ -0,0 +1,56 @@
1
+ // @ts-check
2
+ // How a script stops. Exit codes unless its help says otherwise: 0 done, 1 the check found a problem or a service said
3
+ // no, 2 it couldn't run (bad input, a missing file, a bad settings folder).
4
+ import { basename } from "node:path";
5
+ import { proxyNote } from "./proxy.mjs";
6
+
7
+ /** Input the user can fix: the message is shown as it is, and the script exits with code (2 unless given). */
8
+ export class Fail extends Error {
9
+ /** @param {string} msg @param {number} [code] */
10
+ constructor(msg, code = 2) {
11
+ super(msg);
12
+ this.exitCode = code;
13
+ }
14
+ }
15
+ /** A service said no (a refused key, a quota): shown on stdout after the script's name, and the script exits 1. */
16
+ export class Refused extends Error {}
17
+
18
+ const NAME = () => basename(process.argv[1] || "script", ".mjs");
19
+ // Why a named file can't be opened, in a few words.
20
+ const FILE = {
21
+ ENOENT: "it isn't there",
22
+ EISDIR: "it's a folder, not a file",
23
+ ENOTDIR: "part of the path isn't a folder",
24
+ EACCES: "permission denied",
25
+ EPERM: "permission denied",
26
+ };
27
+
28
+ /** The proxy note, once, before a script's first request to another site. */
29
+ export function warnProxy() {
30
+ const n = proxyNote();
31
+ if (n) console.error("note: " + n);
32
+ }
33
+
34
+ /** Runs main (sync or async) and sets process.exitCode to what it returns, 0 when nothing. Fail, Refused, a file that
35
+ * can't be opened and a bad settings folder (code SEO_SETTINGS) become one plain line; anything else is a bug and keeps
36
+ * its stack trace. It never calls process.exit(): exiting while sockets close crashes Node on Windows.
37
+ * @param {() => any} main */
38
+ export async function runMain(main) {
39
+ try {
40
+ process.exitCode = (await main()) ?? 0;
41
+ } catch (e) {
42
+ // By class name too, so scripts that define their own Fail and Refused classes are read the same way.
43
+ const kind = e instanceof Refused ? "Refused" : e instanceof Fail ? "Fail" : e?.constructor?.name;
44
+ if (kind === "Refused") {
45
+ console.log(`${NAME()}: ${e.message}`);
46
+ process.exitCode = 1;
47
+ } else if (kind === "Fail" || e?.code === "SEO_SETTINGS") {
48
+ (e.exitCode === 0 ? console.log : console.error)(e.message);
49
+ process.exitCode = typeof e.exitCode === "number" ? e.exitCode : 2;
50
+ } // exit 0: --help's usage
51
+ else if (Object.hasOwn(FILE, e?.code) && e.path) {
52
+ console.error(`${NAME()}: can't open ${e.path} (${FILE[e.code]}).`);
53
+ process.exitCode = 2;
54
+ } else throw e;
55
+ }
56
+ }
@@ -0,0 +1,38 @@
1
+ // @ts-check
2
+ // CSV to an array of objects keyed by the first row. Handles quotes, doubled quotes, CRLF and a leading BOM.
3
+ export function parseCsv(txt) {
4
+ txt = txt.replace(/^/, "");
5
+ const rows = [];
6
+ let row = [],
7
+ cell = "",
8
+ q = false;
9
+ for (let i = 0; i < txt.length; i++) {
10
+ const c = txt[i];
11
+ if (q) {
12
+ if (c === '"' && txt[i + 1] === '"') {
13
+ cell += '"';
14
+ i++;
15
+ } else if (c === '"') q = false;
16
+ else cell += c;
17
+ continue;
18
+ }
19
+ if (c === '"') q = true;
20
+ else if (c === ",") {
21
+ row.push(cell);
22
+ cell = "";
23
+ } else if (c === "\n" || c === "\r") {
24
+ if (c === "\r" && txt[i + 1] === "\n") i++;
25
+ row.push(cell);
26
+ rows.push(row);
27
+ row = [];
28
+ cell = "";
29
+ } else cell += c;
30
+ }
31
+ if (cell || row.length) {
32
+ row.push(cell);
33
+ rows.push(row);
34
+ }
35
+ const [head, ...body] = rows.filter(r => r.some(x => x.trim()));
36
+ if (!head) return [];
37
+ return body.map(r => Object.fromEntries(head.map((h, i) => [h.trim(), (r[i] ?? "").trim()])));
38
+ }
@@ -0,0 +1,100 @@
1
+ // @ts-check
2
+ // The finding store for the crawler and content-scan.mjs; other scripts build findings with findingOf and foundOn. Per
3
+ // check key: a count and the first 100 evidence lines ({ url, detail? }), plus the rules evaluated and those that
4
+ // couldn't be checked. scrub(text) runs on every URL and detail on the way in, so the crawler's masking of secret keys
5
+ // and home folders covers every check's evidence.
6
+
7
+ const ORDER = { blocker: 0, high: 1, "needs-decision": 2, medium: 3, low: 4 };
8
+
9
+ /**
10
+ * @param {Record<string, any[]>} checks the catalog, key -> [rule, severity, title(n), why, fix]; an unknown key throws
11
+ * @param {(text: string) => string} [scrub]
12
+ * @param {Record<string, string[]>} [rules] rule id -> [title, category]: skip's area and list's category
13
+ */
14
+ export function createFindings(checks, scrub = s => s, rules = {}) {
15
+ const findings = new Map(); // key -> {evidence:[], count}
16
+ function add(key, url, detail) {
17
+ if (!checks[key]) throw new Error("unknown check " + key);
18
+ url = url && scrub(url);
19
+ if (detail != null) detail = scrub(String(detail));
20
+ let f = findings.get(key);
21
+ if (!f) findings.set(key, (f = { evidence: [], count: 0 }));
22
+ f.count++;
23
+ if (f.evidence.length < 100) f.evidence.push(detail ? { url, detail } : { url });
24
+ }
25
+ // A check that counts something other than its evidence lines (pairs, distinct texts) sets its own total.
26
+ const setCount = (key, n) => {
27
+ const f = findings.get(key);
28
+ if (f) f.count = n;
29
+ };
30
+ const evaluated = new Set();
31
+ const evalRules = (...ids) => ids.forEach(r => evaluated.add(r));
32
+ // A rule this run couldn't check and why; the area is the rule and its title unless one is given.
33
+ const notChecked = [];
34
+ const skip = (rule, reason, area = `${rule} ${rules[rule]?.[0] ?? ""}`.trim()) => {
35
+ notChecked.push({ rule, area, reason });
36
+ };
37
+ // The findings to write: worst first, then the most cases, numbered <prefix>-001 on. category: the area they all go
38
+ // under, by default their rule's.
39
+ /** @param {{ source: string, prefix: string, category?: string }} o */
40
+ function list({ source, prefix, category }) {
41
+ const out = [...findings].map(([key, f]) =>
42
+ findingOf(key, checks[key], f, { source, category: category ?? rules[checks[key][0]][1] }),
43
+ );
44
+ return numbered(
45
+ out.sort((a, b) => ORDER[a.severity] - ORDER[b.severity] || b.count - a.count),
46
+ prefix,
47
+ );
48
+ }
49
+ return { findings, add, setCount, evaluated, evalRules, notChecked, skip, list };
50
+ }
51
+
52
+ /**
53
+ * One finding as every script writes it, from its catalog entry and its evidence.
54
+ * @param {string} check @param {any[]} entry [rule, severity, title(n), why, fix]
55
+ * @param {{ count: number, evidence: any[] }} found @param {{ source: string, category: string }} where
56
+ */
57
+ export function findingOf(check, entry, { count, evidence }, { source, category }) {
58
+ const [rule, severity, title, why, fix] = entry;
59
+ return {
60
+ check,
61
+ rule,
62
+ severity,
63
+ category,
64
+ title: title(count),
65
+ what: foundOn(count, evidence[0]),
66
+ why,
67
+ fix,
68
+ count,
69
+ evidence,
70
+ source,
71
+ status: severity === "needs-decision" ? "needs-decision" : "open",
72
+ };
73
+ }
74
+
75
+ /** Gives each finding its id in list order, <prefix>-001 on (C- for the crawler, D- content-scan, L- log-scan). */
76
+ export function numbered(list, prefix) {
77
+ list.forEach((f, i) => {
78
+ f.id = `${prefix}-${String(i + 1).padStart(3, "0")}`;
79
+ });
80
+ return list;
81
+ }
82
+
83
+ // Site text quoted in a note the agent reads on stdout: JSON-escaped in double quotes, so a line break or quote can't
84
+ // pass as the tool's own words, and cut to 80 characters, so a hidden instruction can't come through whole. This
85
+ // guards the agent's reading, not HTML; the report escapes notes itself.
86
+ export const quote = (text, max = 80) => {
87
+ const c = [...String(text)];
88
+ return JSON.stringify(c.length > max ? c.slice(0, max - 1).join("") + "…" : c.join(""));
89
+ };
90
+
91
+ // A finding's `what`: "Found on <url> (<detail>)." for one case, "<n> cases, for example <url> (<detail>)." for more.
92
+ // The evidence URL and each bare web address in the detail go in a code span, backticks written %60 so the span can't
93
+ // end early, so the report shows them as code, never links. The rest is left to the report's own escaping.
94
+ const codeSpan = u => "`" + String(u).replace(/`/g, "%60") + "`";
95
+ const WEB_ADDRESS = /(?<!`)https?:\/\/[^\s<>"`]*[^\s<>"`.,;:!?)']/g;
96
+ /** @param {number} count @param {{ url?: string, detail?: any }} [example] the first evidence item */
97
+ export function foundOn(count, { url, detail } = {}) {
98
+ const more = detail != null && detail !== "" ? ` (${String(detail).replace(WEB_ADDRESS, codeSpan)})` : "";
99
+ return `${count === 1 ? "Found on" : `${count} cases, for example`} ${url ? codeSpan(url) : "the site"}${more}.`;
100
+ }
@@ -0,0 +1,9 @@
1
+ // @ts-check
2
+ // The project's shared Google OAuth client ("Desktop app" type) for `node google.mjs connect`. Google treats a desktop
3
+ // client's secret as non-confidential, since it ships inside every installed app, so it lives in the code. Registered
4
+ // in Google Cloud project seo-supervisor-515208; SEO_GOOGLE_SHARED_CLIENT_ID and _SECRET override it.
5
+ // https://developers.google.com/identity/protocols/oauth2/native-app
6
+ export const SHARED_CLIENT = {
7
+ id: "1026738630972-lmevuu45dvqomm8acfumcm592tjvofkb.apps.googleusercontent.com",
8
+ secret: "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",
9
+ };
@@ -0,0 +1,146 @@
1
+ // @ts-check
2
+ // The crawler's HTML helpers, string in, value out: entities, tag attributes, visible text and words, JSON-LD nodes.
3
+ // Regex HTML parsing is enough for audit evidence. Swap in a real parser if a site breaks it.
4
+
5
+ // Named references: the Latin-1 set &nbsp; to &yuml; (U+00A0 to U+00FF in order) and the other HTML 4 punctuation and
6
+ // symbols titles use. Names are case-sensitive (&Eacute; is É), with a lowercase fallback for &AMP; and the like.
7
+ // &nbsp; reads as a plain space; a numeric reference past U+10FFFF stays as written.
8
+ // https://html.spec.whatwg.org/multipage/named-characters.html
9
+ const LATIN1 =
10
+ "nbsp iexcl cent pound curren yen brvbar sect uml copy ordf laquo not shy reg macr deg plusmn sup2 sup3 acute micro para middot cedil sup1 ordm raquo frac14 frac12 frac34 iquest Agrave Aacute Acirc Atilde Auml Aring AElig Ccedil Egrave Eacute Ecirc Euml Igrave Iacute Icirc Iuml ETH Ntilde Ograve Oacute Ocirc Otilde Ouml times Oslash Ugrave Uacute Ucirc Uuml Yacute THORN szlig agrave aacute acirc atilde auml aring aelig ccedil egrave eacute ecirc euml igrave iacute icirc iuml eth ntilde ograve oacute ocirc otilde ouml divide oslash ugrave uacute ucirc uuml yacute thorn yuml".split(
11
+ " ",
12
+ );
13
+ const MORE =
14
+ "OElig 338 oelig 339 Scaron 352 scaron 353 Yuml 376 fnof 402 circ 710 tilde 732 ensp 8194 emsp 8195 thinsp 8201 zwnj 8204 zwj 8205 lrm 8206 rlm 8207 ndash 8211 mdash 8212 lsquo 8216 rsquo 8217 sbquo 8218 ldquo 8220 rdquo 8221 bdquo 8222 dagger 8224 Dagger 8225 bull 8226 hellip 8230 permil 8240 prime 8242 Prime 8243 lsaquo 8249 rsaquo 8250 euro 8364 trade 8482".split(
15
+ " ",
16
+ );
17
+ /** @type {Record<string, string>} */
18
+ const NAMED = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" };
19
+ LATIN1.forEach((n, i) => {
20
+ NAMED[n] = String.fromCodePoint(0xa0 + i);
21
+ });
22
+ for (let i = 0; i < MORE.length; i += 2) NAMED[MORE[i]] = String.fromCodePoint(+MORE[i + 1]);
23
+ NAMED.nbsp = " ";
24
+ export const decode = s =>
25
+ !s.includes("&")
26
+ ? s
27
+ : s.replace(/&(#x[0-9a-f]+|#\d+|\w+);/gi, (m, e) => {
28
+ if (e[0] !== "#") return NAMED[e] ?? NAMED[e.toLowerCase()] ?? m;
29
+ const n = e[1].toLowerCase() === "x" ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10);
30
+ return n <= 0x10ffff ? String.fromCodePoint(n) : m;
31
+ });
32
+ // A tag's attributes by lowercased name, values decoded; a repeated name keeps its first value, as browsers do. An
33
+ // unquoted value keeps a slash before ">" (<a href=/blog/> is "/blog/"); after a quote or space it's no value. The tag
34
+ // is copied first: V8 keeps a substring as a view of its parent, so a cut value would pin the whole page in memory.
35
+ export function attrs(tag) {
36
+ const out = {};
37
+ const inner = (" " + tag.replace(/^<[\w-]+/, "").replace(/>$/, "")).slice(1);
38
+ const re = /([^\s=\/>"']+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+)))?/g;
39
+ let m;
40
+ while ((m = re.exec(inner))) {
41
+ const k = m[1].toLowerCase();
42
+ if (!Object.hasOwn(out, k)) out[k] = decode(m[2] ?? m[3] ?? m[4] ?? "");
43
+ }
44
+ return out;
45
+ }
46
+ // Where Google stops reading the head: </head>, <body> or the first element other than title, meta, link, script,
47
+ // style, base, noscript or template. What a script, style, template, noscript or title holds, and comments, don't
48
+ // count. Returns the index and the tag that ended it ("</head>", "<body>", "<img>"), or { at: -1, by: null }.
49
+ // https://developers.google.com/search/docs/crawling-indexing/valid-page-metadata
50
+ const HEAD_OK = /^(html|head|title|meta|link|script|style|base|noscript|template)$/,
51
+ RAW = /^(script|style|template|noscript|title)$/;
52
+ export function headEndOf(html) {
53
+ const tag = /<!--[\s\S]*?-->|<(\/?)([a-z][\w-]*)[^>]*>/gi;
54
+ for (let m; (m = tag.exec(html));) {
55
+ if (!m[2]) continue;
56
+ const t = m[2].toLowerCase();
57
+ if (m[1] ? t === "head" : !HEAD_OK.test(t)) return { at: m.index, by: `<${m[1]}${t}>` };
58
+ if (!m[1] && RAW.test(t)) {
59
+ const end = new RegExp(`</${t}\\s*>`, "gi");
60
+ end.lastIndex = tag.lastIndex;
61
+ tag.lastIndex = end.exec(html) ? end.lastIndex : html.length;
62
+ }
63
+ }
64
+ return { at: -1, by: null };
65
+ }
66
+ export const tagsOf = (html, name) => [...html.matchAll(new RegExp(`<${name}\\b[^>]*>`, "gi"))].map(m => attrs(m[0]));
67
+ export const stripNonContent = h =>
68
+ h
69
+ .replace(/<script\b[\s\S]*?<\/script>/gi, " ")
70
+ .replace(/<style\b[\s\S]*?<\/style>/gi, " ")
71
+ .replace(/<noscript\b[\s\S]*?<\/noscript>/gi, " ")
72
+ .replace(/<template\b[\s\S]*?<\/template>/gi, " ")
73
+ .replace(/<svg\b[\s\S]*?<\/svg>/gi, " ")
74
+ .replace(/<!--[\s\S]*?-->/g, " ");
75
+ export const textOf = h =>
76
+ decode(h.replace(/<[^>]+>/g, " "))
77
+ .replace(/\s+/g, " ")
78
+ .trim();
79
+ // Scripts written without spaces between words (Chinese, Japanese, Thai, Lao, Khmer, Burmese): Intl.Segmenter splits
80
+ // them into words, and norm() sets them apart from Latin words next to them ("のBoilerの" holds the word "boiler").
81
+ const NOSPACE_CHARS = String.raw`\p{scx=Han}\p{scx=Hira}\p{scx=Kana}\p{scx=Thai}\p{scx=Laoo}\p{scx=Khmr}\p{scx=Mymr}`;
82
+ export const NOSPACE = new RegExp(`[${NOSPACE_CHARS}]`, "u"),
83
+ NOSPACE_RUN = new RegExp(`[${NOSPACE_CHARS}]+`, "gu");
84
+ const SEGMENTER = new Intl.Segmenter(undefined, { granularity: "word" });
85
+ export const wordsOf = t =>
86
+ NOSPACE.test(t)
87
+ ? [...SEGMENTER.segment(t)].filter(s => s.isWordLike).map(s => s.segment)
88
+ : t.split(" ").filter(w => /[\p{L}\p{N}]/u.test(w));
89
+ export const norm = s =>
90
+ s
91
+ .toLowerCase()
92
+ .replace(NOSPACE_RUN, " $& ")
93
+ .replace(/[^\p{L}\p{N}]+/gu, " ")
94
+ .trim();
95
+ // Words written in capitals (FAQ, SEO, HVAC; a plural's s dropped), lowercased: the acronyms a text shows.
96
+ export const capsOf = s =>
97
+ new Set(
98
+ s
99
+ .split(/[^\p{L}\p{N}]+/u)
100
+ .map(w => /^(\p{Lu}{2,})s?$/u.exec(w)?.[1].toLowerCase())
101
+ .filter(Boolean),
102
+ );
103
+ // Frameworks whose router loads the next page itself, without a new document, so speculation rules add little:
104
+ // Next.js, Nuxt, Gatsby, SvelteKit, Remix, Astro prefetch, Turbo (Rails), React Router 7, Angular, Docusaurus, Inertia.
105
+ export const CLIENT_ROUTER =
106
+ /\/_next\/static\/|\/_nuxt\/|id=["']?___gatsby\b|data-sveltekit-|__remixContext|data-astro-prefetch|data-turbo-track|@hotwired\/turbo|__reactRouterContext|\sng-version=|id=["']?__docusaurus\b|\sdata-page=["'](?:\{|app["'])/;
107
+ export const FILE_EXT =
108
+ /\.(pdf|png|jpe?g|gif|webp|avif|svg|ico|css|js|mjs|json|xml|txt|zip|gz|mp4|webm|mp3|woff2?|ttf|otf|csv|xlsx?|docx?|pptx?)$/i;
109
+
110
+ export function jsonLdNodes(html) {
111
+ const nodes = [],
112
+ errors = [];
113
+ for (const m of html.matchAll(
114
+ /<script\b[^>]*type\s*=\s*["']?application\/ld\+json["']?[^>]*>([\s\S]*?)<\/script>/gi,
115
+ )) {
116
+ let data;
117
+ try {
118
+ data = JSON.parse(m[1].trim());
119
+ } catch (e) {
120
+ errors.push(String(e.message).slice(0, 120));
121
+ continue;
122
+ }
123
+ const walk = d => {
124
+ if (Array.isArray(d)) d.forEach(walk);
125
+ else if (d && typeof d === "object") {
126
+ if (Array.isArray(d["@graph"])) d["@graph"].forEach(walk);
127
+ if (d["@type"]) nodes.push(d);
128
+ }
129
+ };
130
+ walk(data);
131
+ }
132
+ return { nodes, errors };
133
+ }
134
+ export const typesOf = n => [].concat(n["@type"] || []);
135
+ export function deepHas(obj, pred, depth = 0) {
136
+ if (!obj || typeof obj !== "object" || depth > 12) return false;
137
+ if (pred(obj)) return true;
138
+ return Object.values(obj).some(v => deepHas(v, pred, depth + 1));
139
+ }
140
+ export function ctx(text, re) {
141
+ const m = re.exec(text);
142
+ if (!m) return null;
143
+ const s = Math.max(0, m.index - 60),
144
+ e = Math.min(text.length, m.index + m[0].length + 60);
145
+ return { match: m[0], snippet: (s ? "…" : "") + text.slice(s, e) + (e < text.length ? "…" : "") };
146
+ }
@@ -0,0 +1,28 @@
1
+ // @ts-check
2
+ // Small HTTP helpers the scripts share.
3
+
4
+ // Retry-After is an HTTP-date or delay-seconds, and a recipient must accept all three date formats (IMF-fixdate,
5
+ // RFC 850 and asctime, which is UTC). Each starts with the day's name.
6
+ // https://www.rfc-editor.org/rfc/rfc9110#section-10.2.3
7
+ /** How long to wait, in ms (0 for a date already past), or null when the value is missing or isn't one of those.
8
+ * Callers cap it. @param {unknown} value @param {number} [now] */
9
+ export function retryAfter(value, now = Date.now()) {
10
+ const s = String(value ?? "").trim();
11
+ if (/^\d+$/.test(s)) return Number(s) * 1000;
12
+ if (!/^[A-Za-z]{3}/.test(s)) return null;
13
+ const t = Date.parse(/\bGMT$/.test(s) ? s : s + " GMT");
14
+ return Number.isNaN(t) ? null : Math.max(0, t - now);
15
+ }
16
+
17
+ /** A fetch() body, already decompressed, read up to cap bytes: a Buffer, or null as soon as it passes cap, the rest
18
+ * left unread, so a huge or endless answer can't fill memory.
19
+ * @param {Response} res @param {number} cap */
20
+ export async function bodyUpTo(res, cap) {
21
+ const chunks = [];
22
+ let n = 0;
23
+ for await (const c of res.body ?? []) {
24
+ if ((n += c.length) > cap) return null;
25
+ chunks.push(c);
26
+ }
27
+ return Buffer.concat(chunks);
28
+ }