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,422 @@
1
+ #!/usr/bin/env node
2
+ // @ts-check
3
+ // Services connected by an API key alone, and the key store the other scripts share. Keys are saved in
4
+ // ~/.seo-supervisor/keys.json, never in the project; a service's environment variable wins over its saved key.
5
+ // Exits 0 when done, 1 when a service refuses or can't be reached (or status finds no key), 2 on bad input.
6
+ import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
7
+ import { dirname, resolve } from "node:path";
8
+ import { isMain } from "./lib/is-main.mjs";
9
+ import { isHelp, parseArgs } from "./lib/args.mjs";
10
+ import { runMain, warnProxy } from "./lib/cli.mjs";
11
+ import { privacyOf } from "./lib/settings-dir.mjs";
12
+ import { changedPages } from "./seo-diff.mjs";
13
+ import { Fail, Refused, fail, setLine, domainOf, domainsFor, num } from "./keys/http.mjs";
14
+ import { SERVICES, serviceOf, call } from "./keys/services.mjs";
15
+ import { keyFile, savedKeys, ask, setKey, removeKey, activeKeys, mask } from "./keys/store.mjs";
16
+ import { fetchBing, BATCH, submitBing } from "./keys/bing.mjs";
17
+ import { MOZ_MAX, fetchAuthority } from "./keys/authority.mjs";
18
+ import { periodFor } from "./keys/visits.mjs";
19
+ import { daysOf } from "./google/search-console.mjs";
20
+ import { MATOMO_SPLITS, MATOMO_DAILY, matomoUrl, fetchMatomo, testMatomo } from "./keys/matomo.mjs";
21
+ import {
22
+ posthogQuery,
23
+ POSTHOG_SPLITS,
24
+ posthogDaily,
25
+ POSTHOG_TEST,
26
+ posthogUrl,
27
+ fetchPosthog,
28
+ testPosthog,
29
+ } from "./keys/posthog.mjs";
30
+ import { CLARITY_DAYS, fetchClarity } from "./keys/clarity.mjs";
31
+ import { YT_TOPICS, fetchYoutube } from "./keys/youtube.mjs";
32
+ import { foundOn } from "./lib/findings.mjs";
33
+
34
+ // Re-exported for the other scripts and the tests.
35
+ export { Fail, Refused, domainOf, submitBing, SERVICES, call, keyFile, savedKeys, setKey, removeKey, activeKeys };
36
+ const USAGE = `usage: node connect-keys.mjs set bing|openpagerank|ahrefs|matomo|posthog|moz|youtube|clarity|perplexity|openai|googleplaces|dataforseo|semrush [<key>] (no key: it asks, hidden)
37
+ node connect-keys.mjs set matomo [--url <address>] [--site-id <id>] | set posthog [--host us|eu|<address>] [--project-id <id>] | set dataforseo [--login <email>]
38
+ node connect-keys.mjs status | remove <service> | guide <service> | test matomo|posthog [--yes]
39
+ node connect-keys.mjs fetch --site https://www.example.com [--competitors a.com,b.com] [--days 90] [--out seo-audit/keys.json] [--yes]
40
+ [--topics "topic one, topic two"] [--youtube-channel @handle] [--bing-pages /a,/b] [--bing-sister https://sister.example]
41
+ node connect-keys.mjs submit-bing --site https://www.example.com (--urls changed.txt | --from-diff seo-audit/seo-diff.json) [--yes]`;
42
+ function siteOf(s, flag = "--site") {
43
+ let u;
44
+ try {
45
+ u = new URL(s);
46
+ } catch {}
47
+ return u && /^https?:$/.test(u.protocol)
48
+ ? u
49
+ : fail(`${flag} must be the site's address, like https://www.example.com (got ${s})`);
50
+ }
51
+
52
+ // Kept here rather than in keys/bing.mjs: knownChecks() in lib/score.mjs and the rule-ID test scan only scripts/ and
53
+ // scripts/checks/ for check names.
54
+ function crawlFinding(bing) {
55
+ // Bing lists redirects as issues too, but on their own they're normal.
56
+ const evidence = (bing?.crawlIssues || [])
57
+ .map(c => ({ c, problems: c.issues.filter(w => !w.includes("redirect")) }))
58
+ .filter(x => x.problems.length)
59
+ .map(({ c, problems }) => ({
60
+ url: c.url,
61
+ detail: `${problems.join(", ")}, Bing got HTTP ${c.httpCode ?? "?"}${c.inLinks ? `, ${c.inLinks} links point here` : ""}`,
62
+ }));
63
+ if (!evidence.length) return [];
64
+ const ex = evidence[0];
65
+ return [
66
+ {
67
+ id: "K-001",
68
+ check: "bing-crawl-issues",
69
+ rule: "CRAWL-05",
70
+ severity: "medium",
71
+ category: "Crawling & indexing",
72
+ title: `Bing reports crawl problems on ${evidence.length} URL(s)`,
73
+ what: foundOn(evidence.length, ex),
74
+ why: "Bing Webmaster Tools lists these URLs as failing when Bing crawled them. Pages that error, time out or are blocked can drop out of Bing, and out of AI answers built on Bing's index such as Copilot.",
75
+ fix: "Open each URL. Fix pages that should work (server errors, timeouts, DNS), redirect or stop linking to pages that are gone, and unblock important pages in robots.txt. Bing's list takes a few days to clear after a fix.",
76
+ count: evidence.length,
77
+ evidence: evidence.slice(0, 100),
78
+ source: "bing-webmaster",
79
+ status: "open",
80
+ },
81
+ ];
82
+ }
83
+
84
+ // Each service runs only when its key is set. problems holds the refusals, also kept in result.notes.
85
+ // bingPages and bingSister add Bing's links to chosen pages and to a sister site in the same account.
86
+ export async function fetchKeys({
87
+ site,
88
+ competitors = [],
89
+ keys = activeKeys(),
90
+ endpoints = {},
91
+ days = 90,
92
+ topics = [],
93
+ channel = null,
94
+ bingPages = [],
95
+ bingSister = null,
96
+ }) {
97
+ const siteUrl = new URL("/", site).href,
98
+ notes = [],
99
+ problems = [],
100
+ notChecked = [];
101
+ const domains = domainsFor(siteUrl, competitors);
102
+ const end = id => endpoints[id] || SERVICES[id].endpoint;
103
+ let bing = null,
104
+ matomo = null,
105
+ posthog = null,
106
+ youtube = null,
107
+ clarity = null;
108
+ const run = async (id, fn) => {
109
+ const s = SERVICES[id];
110
+ // Analytics services (those with fields) go under Limits only when the site uses one, which SKILL.md decides.
111
+ // Optional extras never do.
112
+ if (!keys[id]) {
113
+ if (!s.fields && !s.optional)
114
+ notChecked.push({
115
+ area: `${s.name}: ${s.adds}`,
116
+ reason: `No key set. To connect it: node connect-keys.mjs guide ${id}`,
117
+ });
118
+ return;
119
+ }
120
+ try {
121
+ await fn(s.fields ? keys[id] : (keys[id].key ?? keys[id]));
122
+ } catch (e) {
123
+ if (!(e instanceof Refused)) throw e;
124
+ problems.push(e.message);
125
+ notes.push(e.message);
126
+ notChecked.push({ area: `${s.name}: ${s.adds}`, reason: e.message });
127
+ }
128
+ };
129
+ await run("bing", async key => {
130
+ bing = await fetchBing(key, siteUrl, end("bing"), notes, { pages: bingPages, sister: bingSister });
131
+ });
132
+ const { authority, attribution, moz } = await fetchAuthority(run, keys, domains, end, notes);
133
+ await run("youtube", async key => {
134
+ if (!topics.length && !channel) {
135
+ notes.push(
136
+ "A YouTube key is set, but fetch got no --topics or --youtube-channel, so YouTube wasn't asked anything.",
137
+ );
138
+ return;
139
+ }
140
+ youtube = await fetchYoutube(key, end("youtube"), { topics, channel }, notes);
141
+ });
142
+ const period = periodFor(days);
143
+ await run("matomo", async k => {
144
+ matomo = await fetchMatomo(k, siteUrl, period, notes);
145
+ });
146
+ await run("posthog", async k => {
147
+ posthog = await fetchPosthog(k, siteUrl, period, notes);
148
+ });
149
+ await run("clarity", async key => {
150
+ clarity = await fetchClarity(key, end("clarity"), siteUrl, notes);
151
+ });
152
+ return {
153
+ result: {
154
+ source: "keys",
155
+ when: new Date().toISOString(),
156
+ site: siteUrl,
157
+ bing,
158
+ authority,
159
+ attribution,
160
+ moz,
161
+ youtube,
162
+ matomo,
163
+ posthog,
164
+ clarity,
165
+ findings: crawlFinding(bing),
166
+ notChecked,
167
+ notes,
168
+ },
169
+ problems,
170
+ };
171
+ }
172
+
173
+ // Positional words per command: set <service> [<key>], remove|guide|test <service>.
174
+ const WORDS = { set: 2, remove: 1, guide: 1, test: 1 };
175
+ const FLAGS = [
176
+ "site",
177
+ "competitors",
178
+ "days",
179
+ "out",
180
+ "topics",
181
+ "youtube-channel",
182
+ "bing-pages",
183
+ "bing-sister",
184
+ "urls",
185
+ "from-diff",
186
+ ...Object.values(SERVICES).flatMap(s => (s.fields || []).map(f => f.flag)),
187
+ ];
188
+ async function main(argv) {
189
+ const [cmd, ...rest] = argv;
190
+ const { _: pos, ...args } = parseArgs(rest, {
191
+ flags: FLAGS,
192
+ booleans: ["yes"],
193
+ positionals: Object.hasOwn(WORDS, cmd) ? WORDS[cmd] : 0,
194
+ usage: USAGE,
195
+ });
196
+ const str = k => (typeof args[k] === "string" ? args[k] : null);
197
+
198
+ if (cmd === "set") {
199
+ if (!pos[0]) throw new Fail(USAGE);
200
+ const id = serviceOf(pos[0]),
201
+ fields = SERVICES[id].fields || [];
202
+ const values = Object.fromEntries(fields.map(f => [f.id, str(f.flag)])),
203
+ missing = fields.filter(f => !values[f.id]);
204
+ let key = pos[1];
205
+ if (key != null)
206
+ console.error(
207
+ `connect-keys: note: a key typed on the command line stays in your shell's history. Next time, run ${setLine(id)} without the key and paste it at the hidden prompt.`,
208
+ );
209
+ if (key == null || missing.length) {
210
+ const got = await ask(id, missing, key == null);
211
+ Object.assign(values, got.values);
212
+ key ??= got.key;
213
+ }
214
+ const saved = setKey(id, key, values);
215
+ console.log(
216
+ `connect-keys: saved the ${SERVICES[id].name} key in ${keyFile()} (${privacyOf(saved)}). ${process.env[SERVICES[id].env] ? `Note: ${SERVICES[id].env} is also set and wins over the saved key.` : ""}`.trim(),
217
+ );
218
+ } else if (cmd === "remove") {
219
+ if (!pos[0]) throw new Fail(USAGE);
220
+ console.log(
221
+ removeKey(pos[0])
222
+ ? `connect-keys: removed the ${SERVICES[pos[0]].name} key.`
223
+ : `connect-keys: no saved ${SERVICES[pos[0]].name} key to remove.`,
224
+ );
225
+ } else if (cmd === "guide") {
226
+ if (!pos[0]) throw new Fail(USAGE);
227
+ console.log(SERVICES[serviceOf(pos[0])].guide.join("\n"));
228
+ } else if (cmd === "test") {
229
+ const id = pos[0] && serviceOf(pos[0]);
230
+ if (id !== "matomo" && id !== "posthog")
231
+ fail("test works for matomo or posthog: node connect-keys.mjs test matomo|posthog [--yes]");
232
+ const k = activeKeys()[id];
233
+ if (!k) fail(`${SERVICES[id].name} isn't set up yet. To connect it: node connect-keys.mjs guide ${id}`);
234
+ if (args.yes !== true) {
235
+ console.log(
236
+ `connect-keys: dry run, nothing sent. With --yes it would send your ${id === "matomo" ? `token to ${new URL(k.url).host} and ask for Matomo's version (API.getMatomoVersion)` : `key to ${new URL(k.host).host} and count project ${k.projectId}'s pageviews in the last 7 days (the query: ${POSTHOG_TEST})`}. Re-run with --yes once the owner agrees.`,
237
+ );
238
+ return 0;
239
+ }
240
+ console.log("connect-keys: " + (await (id === "matomo" ? testMatomo(k) : testPosthog(k)))); // runMain prints a refusal and exits 1
241
+ } else if (cmd === "status") {
242
+ const keys = activeKeys();
243
+ for (const [id, s] of Object.entries(SERVICES)) {
244
+ const k = keys[id];
245
+ console.log(
246
+ k
247
+ ? `${s.name}: set (${mask(k.key)}, ${k.from === s.env ? `from ${s.env}` : `saved in ${k.from}`})${s.about ? ` for ${s.about(k)}` : ""}`
248
+ : `${s.name}: not set. It adds ${s.adds}. To get a key: node connect-keys.mjs guide ${id}`,
249
+ );
250
+ }
251
+ if (!Object.values(keys).some(Boolean)) return 1; // as google.mjs status does
252
+ } else if (cmd === "fetch") {
253
+ if (!str("site")) throw new Fail(USAGE);
254
+ const site = siteOf(args.site);
255
+ const days = daysOf(args.days ?? 90, "connect-keys"),
256
+ period = periodFor(days);
257
+ const listed = (str("competitors") || "")
258
+ .split(",")
259
+ .map(s => s.trim())
260
+ .filter(Boolean);
261
+ const skipped = listed.filter(c => !domainOf(c));
262
+ const competitors = listed.filter(c => domainOf(c));
263
+ const keys = activeKeys(),
264
+ siteUrl = new URL("/", site).href;
265
+ // *_ENDPOINT variables point services at the tests' fakes; Matomo and PostHog use the saved address instead.
266
+ const endpoints = Object.fromEntries(
267
+ Object.entries(SERVICES).map(([id, s]) => [id, process.env[s.endpointEnv] || s.endpoint]),
268
+ );
269
+ const domains = domainsFor(siteUrl, competitors);
270
+ const skipNote = skipped.map(c => `Skipped competitor "${c}": it's not a domain name like rival.com.`);
271
+ const listOf = s =>
272
+ (s || "")
273
+ .split(",")
274
+ .map(x => x.trim())
275
+ .filter(Boolean);
276
+ const topics = listOf(str("topics")),
277
+ channel = str("youtube-channel"),
278
+ bingPages = listOf(str("bing-pages"));
279
+ const bingSister = str("bing-sister") && siteOf(args["bing-sister"], "--bing-sister").href;
280
+
281
+ if (args.yes !== true) {
282
+ const list = ds => ds.slice(0, 10).join(", ") + (ds.length > 10 ? ` … and ${ds.length - 10} more` : "");
283
+ const { matomo: m, posthog: p } = keys;
284
+ const yt =
285
+ topics.length || channel
286
+ ? `your key, ${Math.min(topics.length, YT_TOPICS)} topic search(es)${topics.length ? ` (${topics.slice(0, YT_TOPICS).join(", ")})` : ""}${channel ? ` and the channel ${channel}` : ""}`
287
+ : "nothing (no --topics or --youtube-channel given)";
288
+ const bingWhat = `your site's address (${siteUrl})${bingPages.length ? `, ${bingPages.length} chosen page(s) for their links` : ""}${bingSister ? `, the sister site ${bingSister}` : ""}`;
289
+ const lines = Object.entries(SERVICES)
290
+ .filter(([, s]) => !s.answers && !s.script)
291
+ .map(([id, s]) =>
292
+ !keys[id]
293
+ ? ` ${s.name}: not set, skipped (to add it: node connect-keys.mjs guide ${id})`
294
+ : id === "matomo"
295
+ ? ` Matomo: your token (in the request body, never in the address) and site ID ${m.siteId}, to ${new URL(m.url).host}:${[undefined, ...Object.values(MATOMO_SPLITS), MATOMO_DAILY].map(method => `\n POST ${matomoUrl(m, period, method)}`).join("")}`
296
+ : id === "posthog"
297
+ ? ` PostHog: your key and project ID ${p.projectId}, to ${new URL(p.host).host}:${[posthogQuery(period), ...Object.values(POSTHOG_SPLITS).map(q => q(period)), posthogDaily(period)].map(q => `\n POST ${posthogUrl(p)} with the query: ${q}`).join("")}`
298
+ : id === "youtube"
299
+ ? ` YouTube Data API: ${yt}, to ${new URL(endpoints[id]).host}`
300
+ : id === "clarity"
301
+ ? ` Microsoft Clarity: your token only, to ${new URL(endpoints[id]).host}: GET ${endpoints[id]}?numOfDays=${CLARITY_DAYS}&dimension1=URL (nothing about your site: the token names the Clarity project). It uses 1 of the 10 requests Clarity allows a project each day.`
302
+ : ` ${s.name}: ${id === "bing" ? bingWhat : id === "moz" ? `${Math.min(domains.length, MOZ_MAX)} domain name(s) (${list(domains.slice(0, MOZ_MAX))})` : `${domains.length} domain name(s) (${list(domains)})`} and your key, to ${new URL(endpoints[id]).host}`,
303
+ );
304
+ console.log(
305
+ `connect-keys: dry run, nothing sent. With --yes it would send:\n${lines.join("\n")}${skipNote.length ? "\n" + skipNote.join("\n") : ""}\nThese go to outside services, so re-run with --yes once the owner agrees.`,
306
+ );
307
+ return 0;
308
+ }
309
+ const { result, problems } = await fetchKeys({
310
+ site: siteUrl,
311
+ competitors,
312
+ keys,
313
+ endpoints,
314
+ days,
315
+ topics,
316
+ channel,
317
+ bingPages,
318
+ bingSister,
319
+ });
320
+ result.notes.push(...skipNote);
321
+ const out = resolve(str("out") || "seo-audit/keys.json");
322
+ mkdirSync(dirname(out), { recursive: true });
323
+ writeFileSync(out, JSON.stringify(result, null, 2));
324
+ for (const p of problems) console.log("connect-keys: " + p);
325
+ const b = result.bing,
326
+ visits = (name, x) => (x ? `${name} ${Object.keys(x.traffic).length} pages · ` : "");
327
+ console.log(
328
+ `connect-keys: ${b ? `Bing ${Object.keys(b.traffic).length} pages, ${b.queries.length} queries, ${b.backlinks.pages.length} linked pages${b.crawlIssues ? `, ${b.crawlIssues.length} crawl issues` : ""} · ` : ""}${result.authority.length ? `authority for ${result.authority.length} domain(s) · ` : ""}${result.moz?.length ? `Moz for ${result.moz.length} domain(s) · ` : ""}${result.youtube ? `YouTube ${result.youtube.topics.length} topic(s) · ` : ""}${visits("Matomo", result.matomo)}${visits("PostHog", result.posthog)}${result.clarity ? `Clarity ${Object.keys(result.clarity.traffic).length} pages · ` : ""}${result.findings.length} finding(s) · wrote ${out}`,
329
+ );
330
+ return problems.length ? 1 : 0;
331
+ } else if (cmd === "submit-bing") {
332
+ if (!str("site") || !(str("urls") || str("from-diff"))) throw new Fail(USAGE);
333
+ const site = siteOf(args.site),
334
+ key = activeKeys().bing?.key;
335
+ if (!key) fail("no Bing Webmaster Tools key is set. To connect it: node connect-keys.mjs guide bing");
336
+ const read = f => {
337
+ try {
338
+ return readFileSync(f, "utf8");
339
+ } catch (e) {
340
+ fail(`can't read ${f} (${e.code || e.message}).`);
341
+ }
342
+ };
343
+ const found = [];
344
+ if (str("urls"))
345
+ found.push(
346
+ ...read(args.urls)
347
+ .split(/\r?\n/)
348
+ .map(s => s.trim())
349
+ .filter(s => s && !s.startsWith("#")),
350
+ );
351
+ if (str("from-diff")) {
352
+ let d;
353
+ try {
354
+ d = JSON.parse(read(args["from-diff"]));
355
+ } catch (e) {
356
+ if (e instanceof Fail) throw e;
357
+ fail(`${args["from-diff"]} isn't a seo-diff.json (run seo-diff.mjs first).`);
358
+ }
359
+ found.push(...changedPages(d));
360
+ }
361
+ // Bing takes only the site's own URLs, so anything off-origin is dropped before sending.
362
+ const kept = new Set(),
363
+ others = [];
364
+ for (const s of found.filter(s => typeof s === "string")) {
365
+ let u;
366
+ try {
367
+ u = /^(https?:\/\/|\/)/i.test(s) ? new URL(s, site) : null;
368
+ } catch {}
369
+ if (u?.origin === site.origin) {
370
+ u.hash = "";
371
+ kept.add(u.href);
372
+ } else others.push(s);
373
+ }
374
+ const urls = [...kept];
375
+ if (others.length)
376
+ console.log(
377
+ `connect-keys: left out ${others.length} URL(s) that aren't on ${site.origin} (Bing only takes the site's own URLs), e.g. ${others[0]}`,
378
+ );
379
+ if (!urls.length) {
380
+ console.log(`connect-keys: no URLs on ${site.origin} to submit.`);
381
+ return 0;
382
+ }
383
+ if (args.yes !== true) {
384
+ console.log(
385
+ `connect-keys: dry run, nothing sent. With --yes it would ask Bing Webmaster Tools, with your key, for the site's URL submission quota (GetUrlSubmissionQuota), then submit as many of these ${urls.length} URL(s) as fit in it (SubmitUrlBatch, up to ${BATCH} a request):\n${urls
386
+ .slice(0, 20)
387
+ .map(u => " " + u)
388
+ .join(
389
+ "\n",
390
+ )}${urls.length > 20 ? `\n … and ${urls.length - 20} more` : ""}\nIndexNow (indexnow.mjs) already tells Bing about changed pages; this asks Bing directly. It's a write to the owner's Bing Webmaster Tools account, so re-run with --yes once the owner agrees.`,
391
+ );
392
+ return 0;
393
+ }
394
+ const r = await submitBing({
395
+ key,
396
+ site: site.href,
397
+ urls,
398
+ endpoint: process.env[SERVICES.bing.endpointEnv] || SERVICES.bing.endpoint,
399
+ });
400
+ const { quota, sent, notSent, error } = r;
401
+ console.log(
402
+ `connect-keys: Bing's URL submission quota for ${r.siteUrl}: ${num(quota.daily)} URL(s) today${quota.monthly != null ? `, ${num(quota.monthly)} this month` : ""}.`,
403
+ );
404
+ if (!sent && !error) {
405
+ console.log("connect-keys: the quota is used up, so nothing was sent. Submit again on another day.");
406
+ return 1;
407
+ }
408
+ if (sent) console.log(`connect-keys: submitted ${sent} URL(s) to Bing Webmaster Tools.`);
409
+ if (error) console.log(`connect-keys: ${error}`);
410
+ if (notSent.length)
411
+ console.log(
412
+ `connect-keys: ${notSent.length} URL(s) ${error ? "weren't sent" : "didn't fit in the quota and weren't sent"}, starting with ${notSent[0]}. Submit them on another day.`,
413
+ );
414
+ return error ? 1 : 0;
415
+ } else throw new Fail(USAGE, isHelp(cmd) ? 0 : 2);
416
+ return 0;
417
+ }
418
+
419
+ if (isMain(import.meta.url)) {
420
+ warnProxy(); // once, before any request is sent
421
+ await runMain(() => main(process.argv.slice(2)));
422
+ }