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,140 @@
1
+ // @ts-check
2
+ // Saved service keys: where they live, reading and writing them, and asking for one without echoing it.
3
+ import { readFileSync, existsSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { createInterface } from "node:readline/promises";
6
+ import { loginDir, writePrivate } from "../lib/settings-dir.mjs";
7
+ import { Fail, fail, setLine } from "./http.mjs";
8
+ import { SERVICES, serviceOf } from "./services.mjs";
9
+
10
+ export const keyFile = () => join(loginDir(), "keys.json"); // honours SEO_SUPERVISOR_HOME and SEO_SUPERVISOR_CLIENT
11
+ export function savedKeys() {
12
+ const f = keyFile();
13
+ if (!existsSync(f)) return {};
14
+ try {
15
+ return JSON.parse(readFileSync(f, "utf8"));
16
+ } catch {
17
+ fail(`${f} isn't valid JSON. Fix it or delete it, then set the keys again.`);
18
+ }
19
+ }
20
+ // Renamed over the old file, so a crash never leaves half a keys file, and readable by this user only where the
21
+ // system allows; { locked } says whether that held.
22
+ const save = keys => writePrivate(keyFile(), JSON.stringify(keys, null, 2) + "\n");
23
+
24
+ // What set still needs. Piped stdin gives a line each, in order; a terminal asks for the address and ID in plain view
25
+ // (they aren't secret), then for the key without showing it.
26
+ export async function ask(id, missing, needKey) {
27
+ const { stdin, stderr } = process,
28
+ values = {};
29
+ if (!stdin.isTTY) {
30
+ let text = "";
31
+ const n = missing.length + (needKey ? 1 : 0);
32
+ for await (const c of stdin) {
33
+ text += c;
34
+ if (text.split("\n").length > n) break;
35
+ }
36
+ const lines = text.split(/\r?\n/).map(s => s.trim());
37
+ missing.forEach((f, i) => {
38
+ values[f.id] = lines[i];
39
+ });
40
+ return {
41
+ values,
42
+ key: needKey
43
+ ? lines[missing.length] ||
44
+ fail(`no key was given. In your own terminal, run ${setLine(id)} and paste the key when it asks.`)
45
+ : undefined,
46
+ };
47
+ }
48
+ if (missing.length) {
49
+ const rl = createInterface({ input: stdin, output: stderr });
50
+ rl.on("SIGINT", () => rl.close());
51
+ try {
52
+ for (const f of missing) values[f.id] = await rl.question(`${f.ask}: `);
53
+ } catch {
54
+ fail("cancelled, nothing was saved.");
55
+ } finally {
56
+ rl.close();
57
+ }
58
+ }
59
+ return { values, key: needKey ? await readKey(id) : undefined };
60
+ }
61
+ // The key from the terminal, without showing it.
62
+ async function readKey(id) {
63
+ const { stdin, stderr } = process;
64
+ stderr.write(`Paste the ${SERVICES[id].name} ${SERVICES[id].secret || "key"} and press Enter (it isn't shown): `);
65
+ stdin.setRawMode(true);
66
+ stdin.setEncoding("utf8");
67
+ return new Promise((ok, no) => {
68
+ let key = "";
69
+ const done = () => {
70
+ stdin.setRawMode(false);
71
+ stdin.off("data", onData);
72
+ stdin.pause();
73
+ stderr.write("\n");
74
+ };
75
+ const onData = s => {
76
+ for (const ch of s) {
77
+ if (ch === "\r" || ch === "\n") {
78
+ done();
79
+ return ok(key);
80
+ }
81
+ if (ch === "\u0003") {
82
+ done();
83
+ return no(new Fail("connect-keys: cancelled, nothing was saved."));
84
+ }
85
+ if (ch === "\u007f" || ch === "\b") {
86
+ if (key) {
87
+ key = key.slice(0, -1);
88
+ stderr.write("\b \b");
89
+ }
90
+ } else {
91
+ key += ch;
92
+ stderr.write("*");
93
+ }
94
+ }
95
+ };
96
+ stdin.on("data", onData);
97
+ stdin.resume();
98
+ });
99
+ }
100
+ // values: Matomo's or PostHog's address and ID, checked and tidied before anything is saved. Returns { locked }.
101
+ export function setKey(id, key, values = {}) {
102
+ const s = SERVICES[serviceOf(id)];
103
+ key = String(key ?? "").trim();
104
+ if (!key || /\s/.test(key))
105
+ fail(`that doesn't look like a key (it's empty or has spaces). Copy it again from ${s.where}.`);
106
+ if (id === "posthog" && key.startsWith("phc_"))
107
+ fail(
108
+ `that's the project key from your site's tracking code (it starts with phc_), which can only send data to PostHog. Reading needs a personal API key, which starts with phx_. To make one: node connect-keys.mjs guide posthog`,
109
+ );
110
+ // Microsoft: "Access to the API is secured via JWT tokens", three parts joined by dots.
111
+ if (id === "clarity" && !/^[\w-]+\.[\w-]+\.[\w-]+$/.test(key))
112
+ fail(
113
+ `that isn't a Clarity API token: those are long, with two dots in them. A short code like the one in Clarity's tracking code is the project ID, which can't read data. To make a token: node connect-keys.mjs guide clarity`,
114
+ );
115
+ const extra = Object.fromEntries((s.fields || []).map(f => [f.id, f.check(String(values[f.id] ?? "").trim())]));
116
+ return save({ ...savedKeys(), [id]: s.fields ? { ...extra, key } : key });
117
+ }
118
+ export function removeKey(id) {
119
+ serviceOf(id);
120
+ const keys = savedKeys();
121
+ if (!(id in keys)) return false;
122
+ delete keys[id];
123
+ save(keys);
124
+ return true;
125
+ }
126
+ // { bing: { key, from } | null, matomo: { key, from, url, siteId } | null, ... }; an environment variable wins over the
127
+ // saved value. Matomo and PostHog count as set only with their address and ID too.
128
+ export function activeKeys(env = process.env) {
129
+ const saved = savedKeys();
130
+ return Object.fromEntries(
131
+ Object.entries(SERVICES).map(([id, s]) => {
132
+ const v = saved[id],
133
+ savedKey = s.fields ? v?.key : v;
134
+ const k = env[s.env] ? { key: env[s.env], from: s.env } : savedKey ? { key: savedKey, from: keyFile() } : null;
135
+ for (const f of (k && s.fields) || []) k[f.id] = env[f.env] ? f.check(env[f.env].trim()) : v?.[f.id];
136
+ return [id, k && (s.fields || []).every(f => k[f.id]) ? k : null];
137
+ }),
138
+ );
139
+ }
140
+ export const mask = k => (k.length > 8 ? "…" + k.slice(-4) : "…");
@@ -0,0 +1,58 @@
1
+ // @ts-check
2
+ // Shared by the Matomo and PostHog reads: the period, the row cap, the top-10 splits and visits by path.
3
+ import { Refused } from "./http.mjs";
4
+ import { periodOf } from "../google/search-console.mjs";
5
+
6
+ export const ROWS = 25000; // the most pages read from Matomo or PostHog, as google.mjs reads from Google Analytics
7
+ // The same days google.mjs reads Google Analytics for, ending 3 days ago, so the numbers line up.
8
+ export const periodFor = days => {
9
+ const p = periodOf(days);
10
+ return { from: p.startDate, to: p.endDate };
11
+ };
12
+ // [name, visits] pairs to { name: { visits } } for the top 10; a pair without a name or visits is dropped.
13
+ const top10 = pairs => {
14
+ const m = new Map();
15
+ for (const [k, v] of pairs) if (typeof k === "string" && k && Number(v) > 0) m.set(k, (m.get(k) || 0) + Number(v));
16
+ return Object.fromEntries(
17
+ [...m]
18
+ .sort((a, b) => b[1] - a[1])
19
+ .slice(0, 10)
20
+ .map(([k, visits]) => [k, { visits }]),
21
+ );
22
+ };
23
+ const SPLIT_NAME = {
24
+ byDevice: "visits from search engines by device",
25
+ byCountry: "visits from search engines by country",
26
+ byChannel: "visits by channel",
27
+ byEngine: "visits from search engines by search engine",
28
+ byReferrer: "visits by referrer",
29
+ daily: "visits from search engines per day",
30
+ };
31
+ // A split that fails is noted; the visits by landing page stay. once: one read that isn't a top 10 (the daily trend).
32
+ export async function splits(name, fields, read, notes) {
33
+ const out = {};
34
+ for (const [field, what] of Object.entries(fields)) {
35
+ try {
36
+ out[field] = top10(await read(what, field));
37
+ } catch (e) {
38
+ if (!(e instanceof Refused)) throw e;
39
+ notes.push(`${name}'s ${SPLIT_NAME[field]} weren't read: ${e.message}`);
40
+ }
41
+ }
42
+ return out;
43
+ }
44
+ export async function once(name, field, fn, notes) {
45
+ try {
46
+ return { [field]: await fn() };
47
+ } catch (e) {
48
+ if (!(e instanceof Refused)) throw e;
49
+ notes.push(`${name}'s ${SPLIT_NAME[field]} weren't read: ${e.message}`);
50
+ return {};
51
+ }
52
+ }
53
+ // One page's http/https, www/apex and tracking-parameter variants add up, by path as GA4's landing page is.
54
+ export const addVisits = (map, path, n) => {
55
+ map[path] = { visits: (map[path]?.visits || 0) + n };
56
+ };
57
+ export const tooMany = name =>
58
+ `${name} has ${ROWS.toLocaleString("en-US")} or more pages with visits from search engines for this period; only the top ${ROWS.toLocaleString("en-US")} were read.`;
@@ -0,0 +1,84 @@
1
+ // @ts-check
2
+ // YouTube Data API: the key's entry, the videos that rank for the site's topics, and its channel's numbers.
3
+ import { setLine, PASTE, request, isDay } from "./http.mjs";
4
+
5
+ // https://developers.google.com/youtube/v3/determine_quota_cost
6
+ export const youtube = {
7
+ name: "YouTube Data API",
8
+ env: "YOUTUBE_API_KEY",
9
+ endpointEnv: "YOUTUBE_ENDPOINT",
10
+ endpoint: "https://www.googleapis.com/youtube/v3",
11
+ optional: true,
12
+ adds: "the YouTube videos that rank for your topics, and your channel's subscribers, videos and views",
13
+ where: "console.cloud.google.com → APIs & Services → Credentials",
14
+ guide: [
15
+ "The YouTube Data API adds the videos that rank on YouTube for the topics you name, and your own channel's subscribers, videos and views. It needs a Google Cloud project and an API key; Google gives each project a daily quota.",
16
+ "1. Open https://console.cloud.google.com and pick or create a project.",
17
+ '2. Open APIs & Services → Library, search for "YouTube Data API v3" and click Enable.',
18
+ "3. Open APIs & Services → Credentials → Create credentials → API key. Under API restrictions, limit the key to YouTube Data API v3.",
19
+ `4. Copy the key, then in your own terminal run: ${setLine("youtube")}`,
20
+ PASTE,
21
+ 'Then fetch with --topics "topic one, topic two" and --youtube-channel @yourhandle. YouTube allows 100 searches a day, so fetch searches at most 5 topics a run.',
22
+ ],
23
+ };
24
+
25
+ // ---------- YouTube ----------
26
+ // channels.list costs 1 unit of 10,000 a day; search.list has its own bucket of 100 calls a day, so a run makes at
27
+ // most YT_TOPICS searches. The key goes in the X-Goog-Api-Key header, as Google suggests, so it stays out of addresses
28
+ // and logs. Redirects aren't followed, so the key never reaches another address, and it's never printed.
29
+ // https://cloud.google.com/docs/authentication/api-keys-use
30
+ export const YT_TOPICS = 5;
31
+ const CHANNEL_ID = /^UC[\w-]{22}$/;
32
+ export async function fetchYoutube(key, base, { topics, channel }, notes) {
33
+ const get = (path, params) =>
34
+ request("youtube", youtube, `${base}/${path}?${new URLSearchParams(params)}`, {
35
+ redirect: "manual",
36
+ headers: { "x-goog-api-key": key },
37
+ });
38
+ const n = v => (v != null && Number(v) >= 0 ? Number(v) : null),
39
+ out = { channel: null, topics: [] };
40
+ if (channel) {
41
+ const c = (
42
+ await get("channels", {
43
+ part: "snippet,statistics",
44
+ ...(CHANNEL_ID.test(channel) ? { id: channel } : { forHandle: channel }),
45
+ })
46
+ )?.items?.[0],
47
+ st = c?.statistics || {};
48
+ if (c)
49
+ out.channel = {
50
+ id: c.id,
51
+ title: c.snippet?.title ?? null,
52
+ subscribers: st.hiddenSubscriberCount ? null : n(st.subscriberCount),
53
+ videos: n(st.videoCount),
54
+ views: n(st.viewCount),
55
+ };
56
+ else
57
+ notes.push(
58
+ `YouTube has no channel ${channel}. Check the handle (it starts with @) or the channel ID (it starts with UC).`,
59
+ );
60
+ }
61
+ if (topics.length > YT_TOPICS)
62
+ notes.push(
63
+ `YouTube: searched the first ${YT_TOPICS} of ${topics.length} topics. Search allows 100 calls a day; run fetch again another day with the rest.`,
64
+ );
65
+ for (const topic of topics.slice(0, YT_TOPICS)) {
66
+ const items = (await get("search", { part: "snippet", type: "video", maxResults: 10, q: topic }))?.items || [];
67
+ out.topics.push({
68
+ topic,
69
+ videos: items
70
+ .filter(i => typeof i?.id?.videoId === "string")
71
+ .map(({ id: { videoId }, snippet }) =>
72
+ (s => ({
73
+ id: videoId,
74
+ url: `https://www.youtube.com/watch?v=${encodeURIComponent(videoId)}`,
75
+ title: s.title ?? "",
76
+ channel: s.channelTitle ?? "",
77
+ published: isDay(String(s.publishedAt).slice(0, 10)) ? s.publishedAt.slice(0, 10) : null,
78
+ own: !!out.channel && s.channelId === out.channel.id,
79
+ }))(snippet && typeof snippet === "object" ? snippet : {}),
80
+ ),
81
+ });
82
+ }
83
+ return out;
84
+ }
@@ -0,0 +1,316 @@
1
+ #!/usr/bin/env node
2
+ // @ts-check
3
+ // Keyword metrics from DataForSEO or Semrush, and competitor gaps from DataForSEO. Dry run unless --yes.
4
+ import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
5
+ import { dirname, resolve } from "node:path";
6
+ import { isMain } from "./lib/is-main.mjs";
7
+ import { parseArgs } from "./lib/args.mjs";
8
+ import { Fail, runMain, warnProxy } from "./lib/cli.mjs";
9
+ import { SERVICES, activeKeys, keyFile, call, Refused, domainOf } from "./connect-keys.mjs";
10
+ import { dataforseoProblem } from "./keys/dataforseo.mjs";
11
+
12
+ const MAX_KEYWORDS = 200,
13
+ MAX_COMPETITORS = 3,
14
+ GAP_ROWS = 100; // local caps, not API limits
15
+ const DFS_BATCH = 700,
16
+ DFS_TASK = 0.012,
17
+ DFS_ITEM = 0.00012; // dataforseo.com/pricing, Nov 2026
18
+ const SEMRUSH_UNITS = 20; // per request: developer.semrush.com/api/v4/seo/keyword-reports
19
+ const IDEA_GROUPS = ["almostThere", "gaps", "questions", "extra"];
20
+ const USAGE =
21
+ "usage: node keyword-data.mjs --site https://www.example.com (--ideas seo-audit/keyword-ideas.json | --keywords keywords.txt) [--competitors a.com,b.com] [--service dataforseo|semrush] [--country US] [--language en] [--out seo-audit/keyword-data.json] [--yes]";
22
+ const fail = msg => {
23
+ throw new Fail("keyword-data: " + msg);
24
+ };
25
+ const num = v => (typeof v === "number" && Number.isFinite(v) ? v : null);
26
+ const dollars = x => `$${(Math.ceil(x * 100 - 1e-9) / 100).toFixed(2)}`;
27
+ const plural = (n, w) => `${n.toLocaleString("en-US")} ${n === 1 ? w : w + "s"}`;
28
+
29
+ function read(file, what) {
30
+ try {
31
+ return readFileSync(file, "utf8");
32
+ } catch (e) {
33
+ return fail(`can't read ${what} ${file} (${e.code || e.message}).`);
34
+ }
35
+ }
36
+ function keywordsFrom(ideas, list) {
37
+ const out = new Set(),
38
+ add = k => {
39
+ const t = String(k ?? "")
40
+ .trim()
41
+ .replace(/\s+/g, " ")
42
+ .toLowerCase();
43
+ if (t) out.add(t);
44
+ };
45
+ if (ideas) {
46
+ let j;
47
+ try {
48
+ j = JSON.parse(read(ideas, "the keyword ideas"));
49
+ } catch (e) {
50
+ if (e instanceof Fail) throw e;
51
+ fail(`${ideas} isn't keyword-ideas.json (run keyword-ideas.mjs first).`);
52
+ }
53
+ for (const g of IDEA_GROUPS) for (const i of Array.isArray(j?.[g]) ? j[g] : []) add(i?.phrase);
54
+ }
55
+ if (list)
56
+ for (const line of read(list, "the keyword file").split(/\r?\n/)) if (!line.trim().startsWith("#")) add(line);
57
+ return [...out];
58
+ }
59
+
60
+ // Both fill `got`, so what was read before a refusal is kept.
61
+ async function askDataforseo({ keywords, competitors, domain, place, k, endpoint, log, got }) {
62
+ const headers = {
63
+ authorization: "Basic " + Buffer.from(`${k.login}:${k.key}`).toString("base64"),
64
+ "content-type": "application/json",
65
+ };
66
+ const post = async (path, task) => {
67
+ const b = await call("dataforseo", `${endpoint}/dataforseo_labs/google/${path}/live`, {
68
+ method: "POST",
69
+ redirect: "manual",
70
+ headers,
71
+ body: JSON.stringify([task]),
72
+ });
73
+ const problem = dataforseoProblem(b);
74
+ if (problem) throw new Refused(problem);
75
+ got.spent.usd = Math.round((got.spent.usd + (num(b.cost) ?? 0)) * 1e6) / 1e6;
76
+ const items = b.tasks[0].result?.[0]?.items;
77
+ return Array.isArray(items) ? items : [];
78
+ };
79
+ for (let i = 0; i < keywords.length; i += DFS_BATCH) {
80
+ for (const it of await post("keyword_overview", { keywords: keywords.slice(i, i + DFS_BATCH), ...place })) {
81
+ if (typeof it?.keyword !== "string") continue;
82
+ const main = it.search_intent_info?.main_intent;
83
+ got.rows.push({
84
+ keyword: it.keyword.toLowerCase(),
85
+ volume: num(it.keyword_info?.search_volume),
86
+ difficulty: num(it.keyword_properties?.keyword_difficulty),
87
+ cpc: num(it.keyword_info?.cpc),
88
+ intent: typeof main === "string" ? [main] : [],
89
+ });
90
+ }
91
+ log(`keyword metrics: ${Math.min(i + DFS_BATCH, keywords.length)} of ${keywords.length} keywords asked`);
92
+ }
93
+ for (const rival of competitors) {
94
+ const items = await post("domain_intersection", {
95
+ target1: rival,
96
+ target2: domain,
97
+ intersections: false,
98
+ item_types: ["organic"],
99
+ ...place,
100
+ limit: GAP_ROWS,
101
+ });
102
+ got.competitorRows.push({
103
+ domain: rival,
104
+ keywords: items
105
+ .filter(it => typeof it?.keyword_data?.keyword === "string")
106
+ .map(it => ({
107
+ keyword: it.keyword_data.keyword,
108
+ volume: num(it.keyword_data.keyword_info?.search_volume),
109
+ position: num(it.first_domain_serp_element?.rank_group),
110
+ url: typeof it.first_domain_serp_element?.url === "string" ? it.first_domain_serp_element.url : null,
111
+ })),
112
+ });
113
+ }
114
+ }
115
+
116
+ async function askSemrush({ keywords, country, k, endpoint, log, got }) {
117
+ for (const [i, keyword] of keywords.entries()) {
118
+ const b = await call("semrush", `${endpoint}/keywords/v1/metrics?${new URLSearchParams({ keyword, country })}`, {
119
+ redirect: "manual",
120
+ headers: { authorization: `Apikey ${k.key}` },
121
+ });
122
+ got.spent.units += SEMRUSH_UNITS;
123
+ const d = b?.meta?.success === false ? null : b?.data;
124
+ // cpc comes in cents.
125
+ if (d && typeof d === "object")
126
+ got.rows.push({
127
+ keyword,
128
+ volume: num(d.search_volume),
129
+ difficulty: num(d.keyword_difficulty),
130
+ cpc: num(d.cpc) === null ? null : Math.round(d.cpc) / 100,
131
+ intent: (Array.isArray(d.intents) ? d.intents : [])
132
+ .filter(x => typeof x === "string")
133
+ .map(x => x.toLowerCase()),
134
+ });
135
+ if ((i + 1) % 20 === 0) log(`${i + 1} of ${keywords.length} keywords asked`);
136
+ }
137
+ }
138
+
139
+ function main(argv) {
140
+ const args = parseArgs(argv, {
141
+ flags: ["site", "ideas", "keywords", "competitors", "service", "country", "language", "out"],
142
+ booleans: ["yes"],
143
+ aliases: { rivals: "competitors" },
144
+ positionals: 0,
145
+ usage: USAGE,
146
+ });
147
+ const str = k => (typeof args[k] === "string" ? args[k] : null);
148
+ if (!str("site") || !(str("ideas") || str("keywords"))) throw new Fail(USAGE);
149
+ let site;
150
+ try {
151
+ site = new URL(str("site"));
152
+ } catch {}
153
+ if (!site || !/^https?:$/.test(site.protocol))
154
+ fail(`--site must be the site's address, like https://www.example.com (got ${args.site})`);
155
+ const siteUrl = new URL("/", site).href,
156
+ domain = domainOf(siteUrl);
157
+
158
+ const iso = (str("country") || "US").toUpperCase().replace(/^UK$/, "GB");
159
+ const region = /^[A-Z]{2}$/.test(iso) ? new Intl.DisplayNames(["en"], { type: "region" }).of(iso) : null;
160
+ if (!region || region === iso)
161
+ fail(`--country must be a two-letter country code like US or GB (got ${args.country}).`);
162
+ const language = (str("language") || "en").toLowerCase();
163
+ if (!/^[a-z]{2}(-[a-z]+)?$/.test(language))
164
+ fail(`--language must be a language code like en or de (got ${args.language}).`);
165
+ const service = str("service")?.toLowerCase() ?? null;
166
+ if (service && !["dataforseo", "semrush"].includes(service))
167
+ fail(`--service is dataforseo or semrush (got ${args.service}).`);
168
+ const listed = (str("competitors") || "")
169
+ .split(",")
170
+ .map(s => s.trim())
171
+ .filter(Boolean);
172
+ const notes = listed
173
+ .filter(c => !domainOf(c))
174
+ .map(c => `Skipped competitor "${c}": it's not a domain name like rival.com.`);
175
+ const competitors = [...new Set(listed.map(domainOf).filter(d => d && d !== domain))];
176
+ if (competitors.length > MAX_COMPETITORS)
177
+ fail(
178
+ `at most ${MAX_COMPETITORS} competitors a run (our own cap, to keep the cost small; got ${competitors.length}).`,
179
+ );
180
+
181
+ const keys = activeKeys(),
182
+ id = service ?? (keys.dataforseo ? "dataforseo" : keys.semrush ? "semrush" : null);
183
+ let keywords = keywordsFrom(str("ideas"), str("keywords"));
184
+ if (!keywords.length) fail("no keywords to ask about: the ideas and the keyword file are empty.");
185
+ if (id === "dataforseo") {
186
+ const long = keywords.filter(w => w.length > 80 || w.split(" ").length > 10);
187
+ if (long.length)
188
+ notes.push(
189
+ `Left out ${plural(long.length, "keyword")} over DataForSEO's 80 characters or 10 words, e.g. "${long[0]}".`,
190
+ );
191
+ keywords = keywords.filter(w => !long.includes(w));
192
+ }
193
+ if (keywords.length > MAX_KEYWORDS) {
194
+ notes.push(`Asked about the first ${MAX_KEYWORDS} of ${keywords.length} keywords (our own cap).`);
195
+ keywords = keywords.slice(0, MAX_KEYWORDS);
196
+ }
197
+ const k = id && keys[id],
198
+ s = id && SERVICES[id],
199
+ endpoint = id && (process.env[s.endpointEnv] || s.endpoint).replace(/\/+$/, "");
200
+ const gaps = id === "dataforseo" ? competitors : [];
201
+ if (id === "semrush" && competitors.length)
202
+ notes.push(
203
+ `Competitor keywords need DataForSEO, so ${competitors.join(", ")} ${competitors.length === 1 ? "isn't" : "aren't"} asked.`,
204
+ );
205
+
206
+ if (!args.yes) {
207
+ if (!k) {
208
+ console.log(
209
+ `keyword-data: dry run, nothing sent. No ${id ? s.name : "DataForSEO or Semrush"} key is set, so nothing would be sent. To add one: node connect-keys.mjs guide ${id || "dataforseo"}${id ? "" : " (or guide semrush)"}`,
210
+ );
211
+ return 0;
212
+ }
213
+ const saved = k.from === s.env ? `from ${s.env}` : `saved in ${keyFile()}`;
214
+ const lines =
215
+ id === "dataforseo"
216
+ ? [
217
+ `keyword-data: dry run, nothing sent. With --yes it would ask DataForSEO, with the API login ${k.login} and its password ${saved}, for ${region} (${iso}), in ${language}:`,
218
+ ` POST ${endpoint}/dataforseo_labs/google/keyword_overview/live: ${plural(keywords.length, "keyword")}${keywords.length > DFS_BATCH ? `, in ${Math.ceil(keywords.length / DFS_BATCH)} requests` : ""}`,
219
+ ...gaps.map(
220
+ r =>
221
+ ` POST ${endpoint}/dataforseo_labs/google/domain_intersection/live: up to ${GAP_ROWS} keywords ${r} ranks for and ${domain} doesn't`,
222
+ ),
223
+ ` DataForSEO bills your balance: at most ${dollars(Math.ceil(keywords.length / DFS_BATCH) * DFS_TASK + keywords.length * DFS_ITEM + gaps.length * (DFS_TASK + GAP_ROWS * DFS_ITEM))} ($${DFS_TASK} a request and $${DFS_ITEM} a keyword or row, its price list on 25 Nov 2026).`,
224
+ ]
225
+ : [
226
+ `keyword-data: dry run, nothing sent. With --yes it would ask Semrush, with your key ${saved}, for ${region} (${iso}):`,
227
+ ` Semrush: ${plural(keywords.length, "request")} to GET ${endpoint}/keywords/v1/metrics, one per keyword`,
228
+ ` Semrush takes ${SEMRUSH_UNITS} API units a request, ${(keywords.length * SEMRUSH_UNITS).toLocaleString("en-US")} units in all.`,
229
+ ];
230
+ console.log(
231
+ [
232
+ ...lines,
233
+ "The keywords, exactly as they would be sent:",
234
+ ...keywords.map((w, i) => ` ${i + 1}. ${w}`),
235
+ ...notes,
236
+ `Your keywords${gaps.length ? " and the domain names" : ""} go to ${s.name} at your cost, so re-run with --yes once the owner agrees.`,
237
+ ].join("\n"),
238
+ );
239
+ return 0;
240
+ }
241
+ if (!k)
242
+ fail(
243
+ `no ${id ? s.name : "DataForSEO or Semrush"} key is set. To add one: node connect-keys.mjs guide ${id || "dataforseo"}`,
244
+ );
245
+ return run({
246
+ id,
247
+ k,
248
+ endpoint,
249
+ keywords,
250
+ gaps,
251
+ domain,
252
+ siteUrl,
253
+ iso,
254
+ language,
255
+ notes,
256
+ out: resolve(str("out") || "seo-audit/keyword-data.json"),
257
+ });
258
+ }
259
+
260
+ async function run({ id, k, endpoint, keywords, gaps, domain, siteUrl, iso, language, notes, out }) {
261
+ const log = msg => console.error("keyword-data: " + msg);
262
+ const got = { rows: [], competitorRows: [], spent: id === "dataforseo" ? { usd: 0 } : { units: 0 } };
263
+ let error = null;
264
+ try {
265
+ if (id === "dataforseo")
266
+ await askDataforseo({
267
+ keywords,
268
+ competitors: gaps,
269
+ domain,
270
+ place: { location_name: new Intl.DisplayNames(["en"], { type: "region" }).of(iso), language_code: language },
271
+ k,
272
+ endpoint,
273
+ log,
274
+ got,
275
+ });
276
+ else await askSemrush({ keywords, country: iso, k, endpoint, log, got });
277
+ } catch (e) {
278
+ if (!(e instanceof Refused)) throw e;
279
+ error = e.message;
280
+ }
281
+ const found = new Set(got.rows.map(r => r.keyword));
282
+ const result = {
283
+ source: "keyword-data",
284
+ date: new Date().toISOString().slice(0, 10),
285
+ site: siteUrl,
286
+ service: id,
287
+ serviceName: SERVICES[id].name,
288
+ country: iso,
289
+ ...(id === "dataforseo" && { language }),
290
+ keywords: got.rows.sort((a, b) => (b.volume ?? -1) - (a.volume ?? -1)),
291
+ notFound: error ? [] : keywords.filter(w => !found.has(w)),
292
+ competitors: got.competitorRows,
293
+ spent: got.spent,
294
+ ...(error && { error }),
295
+ notes,
296
+ };
297
+ mkdirSync(dirname(out), { recursive: true });
298
+ writeFileSync(out, JSON.stringify(result, null, 2));
299
+ if (error) console.log("keyword-data: " + error);
300
+ console.log(
301
+ `keyword-data: ${got.rows.length} of ${plural(keywords.length, "keyword")} have data, from ${SERVICES[id].name}.`,
302
+ );
303
+ for (const c of got.competitorRows)
304
+ console.log(
305
+ `keyword-data: ${c.domain} ranks for ${plural(c.keywords.length, "keyword")} ${domain} doesn't (the top ${GAP_ROWS} by searches).`,
306
+ );
307
+ for (const n of notes) console.log("keyword-data: " + n);
308
+ console.log(`keyword-data: ${"usd" in got.spent ? `spent ${dollars(got.spent.usd)}` : `used ${got.spent.units.toLocaleString("en-US")} API units`}.
309
+ keyword-data: wrote ${out}`);
310
+ return error ? 1 : 0;
311
+ }
312
+
313
+ if (isMain(import.meta.url)) {
314
+ warnProxy();
315
+ await runMain(() => main(process.argv.slice(2)));
316
+ }