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.
- package/.claude-plugin/icon.png +0 -0
- package/.claude-plugin/marketplace.json +2 -2
- package/.claude-plugin/plugin.json +16 -3
- package/CHANGELOG.md +430 -0
- package/NOTICE +7 -0
- package/README.md +230 -25
- package/agents/seo-auditor.md +16 -0
- package/agents/seo-reviewer.md +16 -0
- package/bin/agents.mjs +194 -29
- package/bin/extras.mjs +422 -0
- package/bin/prompt.mjs +34 -14
- package/bin/seo-supervisor.mjs +386 -53
- package/commands/seo-audit.md +29 -3
- package/commands/seo-brief.md +28 -0
- package/commands/seo-connect.md +27 -0
- package/commands/seo-fix.md +24 -3
- package/commands/seo-grow.md +26 -0
- package/commands/seo-launch.md +17 -3
- package/commands/seo-review.md +13 -1
- package/commands/seo-rewrite.md +25 -0
- package/commands/seo-setup.md +17 -1
- package/commands/seo-watch.md +28 -0
- package/hooks/hooks.json +117 -0
- package/package.json +20 -7
- package/skills/seo-supervisor/NOTICE +7 -0
- package/skills/seo-supervisor/SKILL.md +302 -21
- package/skills/seo-supervisor/audience.md +61 -0
- package/skills/seo-supervisor/examples/drafts/security.md +41 -0
- package/skills/seo-supervisor/examples/hooks/README.md +28 -0
- package/skills/seo-supervisor/examples/hooks/claude-code-settings.json +15 -0
- package/skills/seo-supervisor/examples/hooks/codex-hooks.json +17 -0
- package/skills/seo-supervisor/examples/hooks/copilot-hooks.json +15 -0
- package/skills/seo-supervisor/examples/hooks/cursor-hooks.json +11 -0
- package/skills/seo-supervisor/examples/hooks/github-actions.yml +21 -0
- package/skills/seo-supervisor/examples/hooks/pre-commit +17 -0
- package/skills/seo-supervisor/examples/hooks/reading-ease.yml +24 -0
- package/skills/seo-supervisor/examples/sample-audit.json +94 -2
- package/skills/seo-supervisor/examples/sample-report.html +111 -61
- package/skills/seo-supervisor/examples/sample-report.md +147 -44
- package/skills/seo-supervisor/examples/scheduled-runs.md +89 -0
- package/skills/seo-supervisor/examples/snippets.md +648 -1
- package/skills/seo-supervisor/grow.md +342 -0
- package/skills/seo-supervisor/og-images.md +85 -0
- package/skills/seo-supervisor/page-types.md +124 -0
- package/skills/seo-supervisor/planning.md +19 -7
- package/skills/seo-supervisor/profile-template.md +41 -0
- package/skills/seo-supervisor/report-format.md +177 -10
- package/skills/seo-supervisor/rewrite.md +59 -0
- package/skills/seo-supervisor/rules/ai-search.md +65 -12
- package/skills/seo-supervisor/rules/content.md +33 -9
- package/skills/seo-supervisor/rules/crawl-index.md +33 -6
- package/skills/seo-supervisor/rules/internal-linking.md +49 -6
- package/skills/seo-supervisor/rules/launch-monitoring.md +17 -8
- package/skills/seo-supervisor/rules/media.md +13 -1
- package/skills/seo-supervisor/rules/metadata.md +41 -9
- package/skills/seo-supervisor/rules/performance.md +50 -5
- package/skills/seo-supervisor/rules/rendering.md +39 -2
- package/skills/seo-supervisor/rules/search-intent.md +32 -0
- package/skills/seo-supervisor/rules/sitemaps-robots.md +24 -12
- package/skills/seo-supervisor/rules/structured-data.md +37 -14
- package/skills/seo-supervisor/rules/trust-security.md +25 -2
- package/skills/seo-supervisor/rules/urls.md +10 -2
- package/skills/seo-supervisor/scripts/ai-answers.mjs +314 -0
- package/skills/seo-supervisor/scripts/backlinks.mjs +412 -0
- package/skills/seo-supervisor/scripts/change-check.mjs +281 -0
- package/skills/seo-supervisor/scripts/checks/agents.mjs +488 -0
- package/skills/seo-supervisor/scripts/checks/assets.mjs +404 -0
- package/skills/seo-supervisor/scripts/checks/bots.mjs +146 -0
- package/skills/seo-supervisor/scripts/checks/business-type.mjs +193 -0
- package/skills/seo-supervisor/scripts/checks/content.mjs +391 -0
- package/skills/seo-supervisor/scripts/checks/coverage.mjs +184 -0
- package/skills/seo-supervisor/scripts/checks/crawl.mjs +95 -0
- package/skills/seo-supervisor/scripts/checks/hreflang.mjs +396 -0
- package/skills/seo-supervisor/scripts/checks/hygiene.mjs +227 -0
- package/skills/seo-supervisor/scripts/checks/lighthouse.mjs +271 -0
- package/skills/seo-supervisor/scripts/checks/link-strength.mjs +59 -0
- package/skills/seo-supervisor/scripts/checks/links.mjs +360 -0
- package/skills/seo-supervisor/scripts/checks/local.mjs +101 -0
- package/skills/seo-supervisor/scripts/checks/media.mjs +194 -0
- package/skills/seo-supervisor/scripts/checks/outbound.mjs +53 -0
- package/skills/seo-supervisor/scripts/checks/page.mjs +223 -0
- package/skills/seo-supervisor/scripts/checks/probes.mjs +130 -0
- package/skills/seo-supervisor/scripts/checks/render.mjs +552 -0
- package/skills/seo-supervisor/scripts/checks/robots.mjs +144 -0
- package/skills/seo-supervisor/scripts/checks/schema.mjs +206 -0
- package/skills/seo-supervisor/scripts/checks/site-agents.mjs +79 -0
- package/skills/seo-supervisor/scripts/checks/site-content.mjs +135 -0
- package/skills/seo-supervisor/scripts/checks/site-hygiene.mjs +202 -0
- package/skills/seo-supervisor/scripts/checks/site-pages.mjs +474 -0
- package/skills/seo-supervisor/scripts/checks/site-security.mjs +102 -0
- package/skills/seo-supervisor/scripts/checks/sitemap.mjs +473 -0
- package/skills/seo-supervisor/scripts/checks/speed.mjs +267 -0
- package/skills/seo-supervisor/scripts/checks/technical.mjs +368 -0
- package/skills/seo-supervisor/scripts/checks/tls.mjs +297 -0
- package/skills/seo-supervisor/scripts/checks/trust.mjs +421 -0
- package/skills/seo-supervisor/scripts/checks/visual.mjs +1132 -0
- package/skills/seo-supervisor/scripts/checks/writing.mjs +192 -0
- package/skills/seo-supervisor/scripts/commoncrawl.mjs +452 -0
- package/skills/seo-supervisor/scripts/connect-keys.mjs +422 -0
- package/skills/seo-supervisor/scripts/content-scan.mjs +515 -158
- package/skills/seo-supervisor/scripts/crawl/catalog.mjs +1248 -0
- package/skills/seo-supervisor/scripts/crawl/fetch.mjs +362 -0
- package/skills/seo-supervisor/scripts/crawl/page.mjs +741 -0
- package/skills/seo-supervisor/scripts/crawl/queue.mjs +190 -0
- package/skills/seo-supervisor/scripts/dashboard.mjs +140 -0
- package/skills/seo-supervisor/scripts/data/ai-bots.json +38 -0
- package/skills/seo-supervisor/scripts/data/build-schema-vocab.mjs +57 -0
- package/skills/seo-supervisor/scripts/data/business-types.json +338 -0
- package/skills/seo-supervisor/scripts/data/google-rich-results.json +79 -0
- package/skills/seo-supervisor/scripts/data/schema-vocab.json +1 -0
- package/skills/seo-supervisor/scripts/deploy-check.mjs +462 -0
- package/skills/seo-supervisor/scripts/disavow.mjs +176 -0
- package/skills/seo-supervisor/scripts/doctor.mjs +174 -0
- package/skills/seo-supervisor/scripts/geo-grid.mjs +371 -0
- package/skills/seo-supervisor/scripts/google/search-console.mjs +151 -0
- package/skills/seo-supervisor/scripts/google/session.mjs +167 -0
- package/skills/seo-supervisor/scripts/google-updates.mjs +189 -0
- package/skills/seo-supervisor/scripts/google.mjs +1341 -0
- package/skills/seo-supervisor/scripts/gsc-import.mjs +298 -0
- package/skills/seo-supervisor/scripts/guard/adapters/claude-code.mjs +149 -0
- package/skills/seo-supervisor/scripts/guard/adapters/cline.mjs +28 -0
- package/skills/seo-supervisor/scripts/guard/adapters/codex.mjs +26 -0
- package/skills/seo-supervisor/scripts/guard/adapters/copilot.mjs +36 -0
- package/skills/seo-supervisor/scripts/guard/adapters/cursor.mjs +33 -0
- package/skills/seo-supervisor/scripts/guard/adapters/devin.mjs +25 -0
- package/skills/seo-supervisor/scripts/guard/adapters/edits.mjs +124 -0
- package/skills/seo-supervisor/scripts/guard/mode.mjs +37 -0
- package/skills/seo-supervisor/scripts/guard/rules.mjs +931 -0
- package/skills/seo-supervisor/scripts/guard.mjs +74 -0
- package/skills/seo-supervisor/scripts/images.mjs +408 -0
- package/skills/seo-supervisor/scripts/indexnow.mjs +300 -0
- package/skills/seo-supervisor/scripts/issues.mjs +217 -0
- package/skills/seo-supervisor/scripts/keys/authority.mjs +135 -0
- package/skills/seo-supervisor/scripts/keys/bing.mjs +239 -0
- package/skills/seo-supervisor/scripts/keys/clarity.mjs +137 -0
- package/skills/seo-supervisor/scripts/keys/dataforseo.mjs +57 -0
- package/skills/seo-supervisor/scripts/keys/googleplaces.mjs +26 -0
- package/skills/seo-supervisor/scripts/keys/http.mjs +212 -0
- package/skills/seo-supervisor/scripts/keys/matomo.mjs +138 -0
- package/skills/seo-supervisor/scripts/keys/openai.mjs +26 -0
- package/skills/seo-supervisor/scripts/keys/perplexity.mjs +26 -0
- package/skills/seo-supervisor/scripts/keys/posthog.mjs +165 -0
- package/skills/seo-supervisor/scripts/keys/semrush.mjs +25 -0
- package/skills/seo-supervisor/scripts/keys/services.mjs +41 -0
- package/skills/seo-supervisor/scripts/keys/store.mjs +140 -0
- package/skills/seo-supervisor/scripts/keys/visits.mjs +58 -0
- package/skills/seo-supervisor/scripts/keys/youtube.mjs +84 -0
- package/skills/seo-supervisor/scripts/keyword-data.mjs +316 -0
- package/skills/seo-supervisor/scripts/keyword-ideas.mjs +503 -0
- package/skills/seo-supervisor/scripts/lib/args.mjs +56 -0
- package/skills/seo-supervisor/scripts/lib/business.mjs +27 -0
- package/skills/seo-supervisor/scripts/lib/cdp.mjs +242 -0
- package/skills/seo-supervisor/scripts/lib/cli.mjs +56 -0
- package/skills/seo-supervisor/scripts/lib/csv.mjs +38 -0
- package/skills/seo-supervisor/scripts/lib/findings.mjs +100 -0
- package/skills/seo-supervisor/scripts/lib/google-client.mjs +9 -0
- package/skills/seo-supervisor/scripts/lib/html.mjs +146 -0
- package/skills/seo-supervisor/scripts/lib/http.mjs +28 -0
- package/skills/seo-supervisor/scripts/lib/image-size.mjs +78 -0
- package/skills/seo-supervisor/scripts/lib/is-main.mjs +13 -0
- package/skills/seo-supervisor/scripts/lib/net.mjs +116 -0
- package/skills/seo-supervisor/scripts/lib/proxy.mjs +47 -0
- package/skills/seo-supervisor/scripts/lib/recheck.mjs +106 -0
- package/skills/seo-supervisor/scripts/lib/redact.mjs +78 -0
- package/skills/seo-supervisor/scripts/lib/robots.mjs +73 -0
- package/skills/seo-supervisor/scripts/lib/score.mjs +266 -0
- package/skills/seo-supervisor/scripts/lib/settings-dir.mjs +81 -0
- package/skills/seo-supervisor/scripts/links-import.mjs +603 -0
- package/skills/seo-supervisor/scripts/log-scan.mjs +597 -0
- package/skills/seo-supervisor/scripts/og-card.mjs +273 -0
- package/skills/seo-supervisor/scripts/osm.mjs +359 -0
- package/skills/seo-supervisor/scripts/rdap.mjs +164 -0
- package/skills/seo-supervisor/scripts/render-report.mjs +324 -690
- package/skills/seo-supervisor/scripts/report/client.js +37 -0
- package/skills/seo-supervisor/scripts/report/diff.mjs +264 -0
- package/skills/seo-supervisor/scripts/report/findings.mjs +165 -0
- package/skills/seo-supervisor/scripts/report/format.mjs +111 -0
- package/skills/seo-supervisor/scripts/report/markdown.mjs +250 -0
- package/skills/seo-supervisor/scripts/report/model.mjs +171 -0
- package/skills/seo-supervisor/scripts/report/overview-lines.mjs +158 -0
- package/skills/seo-supervisor/scripts/report/overview.mjs +224 -0
- package/skills/seo-supervisor/scripts/report/page.mjs +127 -0
- package/skills/seo-supervisor/scripts/report/panel.mjs +172 -0
- package/skills/seo-supervisor/scripts/report/panels/ai.mjs +211 -0
- package/skills/seo-supervisor/scripts/report/panels/connections.mjs +139 -0
- package/skills/seo-supervisor/scripts/report/panels/content.mjs +204 -0
- package/skills/seo-supervisor/scripts/report/panels/data-search.mjs +379 -0
- package/skills/seo-supervisor/scripts/report/panels/data-site.mjs +44 -0
- package/skills/seo-supervisor/scripts/report/panels/links.mjs +380 -0
- package/skills/seo-supervisor/scripts/report/panels/local.mjs +221 -0
- package/skills/seo-supervisor/scripts/report/panels/site.mjs +359 -0
- package/skills/seo-supervisor/scripts/report/panels/speed-media.mjs +267 -0
- package/skills/seo-supervisor/scripts/report/sources.mjs +163 -0
- package/skills/seo-supervisor/scripts/report/styles.css +223 -0
- package/skills/seo-supervisor/scripts/report/traffic.mjs +264 -0
- package/skills/seo-supervisor/scripts/report-plan.mjs +112 -33
- package/skills/seo-supervisor/scripts/schema-check.mjs +717 -0
- package/skills/seo-supervisor/scripts/seo-crawl.mjs +1086 -638
- package/skills/seo-supervisor/scripts/seo-diff.mjs +584 -0
- package/skills/seo-supervisor/scripts/update-check.mjs +82 -0
- package/skills/seo-supervisor/site-types/content.md +34 -1
- package/skills/seo-supervisor/site-types/ecommerce.md +38 -1
- package/skills/seo-supervisor/site-types/local-business.md +96 -6
- package/skills/seo-supervisor/site-types/services.md +46 -0
- package/skills/seo-supervisor/site-types/tools.md +3 -3
- package/skills/seo-supervisor/strategy.md +232 -0
- package/skills/seo-supervisor/troubleshooting.md +56 -0
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// @ts-check
|
|
3
|
+
// Makes 1200x630 Open Graph cards locally: plain HTML with system fonts, screenshotted in headless Chrome or Edge.
|
|
4
|
+
import { execFile } from "node:child_process";
|
|
5
|
+
import { createHash } from "node:crypto";
|
|
6
|
+
import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
7
|
+
import { tmpdir } from "node:os";
|
|
8
|
+
import { dirname, extname, join, resolve } from "node:path";
|
|
9
|
+
import { pathToFileURL } from "node:url";
|
|
10
|
+
import { isMain } from "./lib/is-main.mjs";
|
|
11
|
+
import { parseArgs } from "./lib/args.mjs";
|
|
12
|
+
import { Fail, runMain } from "./lib/cli.mjs";
|
|
13
|
+
import { findBrowser } from "./checks/render.mjs";
|
|
14
|
+
import { CHROME_FLAGS, quietProfile } from "./lib/cdp.mjs";
|
|
15
|
+
|
|
16
|
+
const W = 1200,
|
|
17
|
+
H = 630;
|
|
18
|
+
const esc = s =>
|
|
19
|
+
String(s ?? "").replace(
|
|
20
|
+
/[&<>"']/g,
|
|
21
|
+
c => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c],
|
|
22
|
+
);
|
|
23
|
+
const hex = (v, name) => {
|
|
24
|
+
if (!/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.test(v))
|
|
25
|
+
throw new Error(`${name} must be a hex colour like #2459c9, got "${v}"`);
|
|
26
|
+
return v.length === 4 ? "#" + [...v.slice(1)].map(c => c + c).join("") : v;
|
|
27
|
+
};
|
|
28
|
+
// WCAG relative luminance, so the text is whichever of white or near-black contrasts more with the background.
|
|
29
|
+
const lum = v =>
|
|
30
|
+
[1, 3, 5]
|
|
31
|
+
.map(i => parseInt(v.slice(i, i + 2), 16) / 255)
|
|
32
|
+
.map(c => (c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4))
|
|
33
|
+
.reduce((s, c, i) => s + c * [0.2126, 0.7152, 0.0722][i], 0);
|
|
34
|
+
const contrast = (a, b) => (Math.max(lum(a), lum(b)) + 0.05) / (Math.min(lum(a), lum(b)) + 0.05);
|
|
35
|
+
|
|
36
|
+
// logo: an image URL the page can load offline (the CLI passes a data: URI).
|
|
37
|
+
/** @param {{ title?: string, subtitle?: string, brand?: string, accent?: string, background?: string, logo?: string }} [card] */
|
|
38
|
+
export function cardHtml({
|
|
39
|
+
title,
|
|
40
|
+
subtitle = "",
|
|
41
|
+
brand = "",
|
|
42
|
+
accent = "#2459c9",
|
|
43
|
+
background = "#0b1220",
|
|
44
|
+
logo = "",
|
|
45
|
+
} = {}) {
|
|
46
|
+
const bg = hex(background, "background"),
|
|
47
|
+
ac = hex(accent, "accent");
|
|
48
|
+
const ink = contrast("#ffffff", bg) >= contrast("#0b1220", bg) ? "#ffffff" : "#0b1220";
|
|
49
|
+
const len = String(title ?? "").length,
|
|
50
|
+
size = len <= 40 ? "title-lg" : len <= 80 ? "title-md" : "title-sm";
|
|
51
|
+
return `<!doctype html>
|
|
52
|
+
<html lang="en"><head><meta charset="utf-8">
|
|
53
|
+
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src data:; style-src 'unsafe-inline'">
|
|
54
|
+
<title>${esc(title)}</title>
|
|
55
|
+
<style>
|
|
56
|
+
html, body { margin: 0; width: ${W}px; height: ${H}px; overflow: hidden; }
|
|
57
|
+
body { background: ${bg}; color: ${ink}; font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif; }
|
|
58
|
+
.card { box-sizing: border-box; width: ${W}px; height: ${H}px; padding: 72px 80px 64px; display: flex; flex-direction: column; border-bottom: 10px solid ${ac}; }
|
|
59
|
+
.bar { width: 120px; height: 10px; border-radius: 5px; background: ${ac}; margin-bottom: 40px; flex: none; }
|
|
60
|
+
.title { margin: 0; font-weight: 800; letter-spacing: -0.02em; line-height: 1.2; overflow-wrap: anywhere; display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 3; overflow: hidden; }
|
|
61
|
+
.title-lg { font-size: 80px; } .title-md { font-size: 64px; } .title-sm { font-size: 52px; }
|
|
62
|
+
.subtitle { margin: 24px 0 0; font-size: 32px; line-height: 1.35; opacity: 0.82; display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; overflow: hidden; }
|
|
63
|
+
.brand { margin-top: auto; display: flex; align-items: center; gap: 18px; font-size: 30px; font-weight: 700; flex: none; }
|
|
64
|
+
.brand img { height: 56px; max-width: 220px; object-fit: contain; }
|
|
65
|
+
</style></head>
|
|
66
|
+
<body><main class="card">
|
|
67
|
+
<div class="bar"></div>
|
|
68
|
+
<h1 class="title ${size}">${esc(title)}</h1>
|
|
69
|
+
${subtitle ? `<p class="subtitle">${esc(subtitle)}</p>` : ""}
|
|
70
|
+
<div class="brand">${logo ? `<img src="${esc(logo)}" alt="">` : ""}${brand ? `<span>${esc(brand)}</span>` : ""}</div>
|
|
71
|
+
</main></body></html>
|
|
72
|
+
`;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// { width, height } from a PNG's IHDR chunk, or null when it isn't a PNG.
|
|
76
|
+
export function pngSize(buf) {
|
|
77
|
+
if (
|
|
78
|
+
!buf ||
|
|
79
|
+
buf.length < 24 ||
|
|
80
|
+
buf.readUInt32BE(0) !== 0x89504e47 ||
|
|
81
|
+
buf.readUInt32BE(4) !== 0x0d0a1a0a ||
|
|
82
|
+
buf.toString("latin1", 12, 16) !== "IHDR"
|
|
83
|
+
)
|
|
84
|
+
return null;
|
|
85
|
+
return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
class CardError extends Error {
|
|
89
|
+
constructor(message, code) {
|
|
90
|
+
super(message);
|
|
91
|
+
this.code = code;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// Chrome's command line for one screenshot, with Chrome's own background traffic off (CHROME_FLAGS).
|
|
96
|
+
export const shotArgs = (page, png, profile, extra = []) => [
|
|
97
|
+
"--headless=new",
|
|
98
|
+
"--disable-gpu",
|
|
99
|
+
"--hide-scrollbars",
|
|
100
|
+
"--force-device-scale-factor=1",
|
|
101
|
+
`--window-size=${W},${H}`,
|
|
102
|
+
"--no-first-run",
|
|
103
|
+
"--no-default-browser-check",
|
|
104
|
+
"--disable-extensions",
|
|
105
|
+
...CHROME_FLAGS,
|
|
106
|
+
...extra,
|
|
107
|
+
`--screenshot=${png}`,
|
|
108
|
+
`--user-data-dir=${profile}`,
|
|
109
|
+
pathToFileURL(page).href,
|
|
110
|
+
];
|
|
111
|
+
|
|
112
|
+
// One headless screenshot from a throwaway profile; resolves with the error (or null), never rejects.
|
|
113
|
+
function shoot(browser, page, png, extra = []) {
|
|
114
|
+
const profile = quietProfile(mkdtempSync(join(tmpdir(), "seo-supervisor-og-profile-")));
|
|
115
|
+
return new Promise(ok =>
|
|
116
|
+
execFile(browser, shotArgs(page, png, profile, extra), { timeout: 30000 }, (err, stdout, stderr) => {
|
|
117
|
+
try {
|
|
118
|
+
rmSync(profile, { recursive: true, force: true });
|
|
119
|
+
} catch {}
|
|
120
|
+
ok(err ? Object.assign(err, { stderr }) : null);
|
|
121
|
+
}),
|
|
122
|
+
);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// Renders into a temp folder first, so a failed render never replaces an existing image.
|
|
126
|
+
async function renderCard(browser, opts, out) {
|
|
127
|
+
const work = mkdtempSync(join(tmpdir(), "seo-supervisor-og-"));
|
|
128
|
+
try {
|
|
129
|
+
const page = join(work, "card.html"),
|
|
130
|
+
png = join(work, "card.png");
|
|
131
|
+
writeFileSync(page, cardHtml(opts));
|
|
132
|
+
const err = await shoot(browser, page, png);
|
|
133
|
+
if (!existsSync(png)) {
|
|
134
|
+
const why = String(err?.stderr || err?.message || "")
|
|
135
|
+
.trim()
|
|
136
|
+
.split(/\r?\n/)[0];
|
|
137
|
+
throw new CardError(
|
|
138
|
+
`og-card: ${browser} didn't take a screenshot, so it isn't Chrome or Edge or it failed to start${why ? ` (${why})` : ""}. Set CHROME_PATH to a Chrome or Edge executable.`,
|
|
139
|
+
2,
|
|
140
|
+
);
|
|
141
|
+
}
|
|
142
|
+
let size = pngSize(readFileSync(png));
|
|
143
|
+
// Headless Chrome on Windows can clamp the window size; retry once with a transparent default background.
|
|
144
|
+
// No crop fallback: if clamping persists, capture a larger window and crop the PNG (node:zlib).
|
|
145
|
+
if (size?.width !== W || size?.height !== H) {
|
|
146
|
+
rmSync(png, { force: true });
|
|
147
|
+
await shoot(browser, page, png, ["--default-background-color=00000000"]);
|
|
148
|
+
size = existsSync(png) ? pngSize(readFileSync(png)) : null;
|
|
149
|
+
}
|
|
150
|
+
if (size?.width !== W || size?.height !== H)
|
|
151
|
+
throw new CardError(
|
|
152
|
+
`og-card: ${browser} made a ${size ? `${size.width}x${size.height}` : "unreadable"} image instead of ${W}x${H}. Its headless window size was clamped (reported for Chrome on Windows). Update the browser or try the other one with CHROME_PATH (Chrome or Edge). Nothing was written to ${out}.`,
|
|
153
|
+
1,
|
|
154
|
+
);
|
|
155
|
+
mkdirSync(dirname(out), { recursive: true });
|
|
156
|
+
copyFileSync(png, out);
|
|
157
|
+
} finally {
|
|
158
|
+
try {
|
|
159
|
+
rmSync(work, { recursive: true, force: true });
|
|
160
|
+
} catch {}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const MIME = {
|
|
165
|
+
".svg": "image/svg+xml",
|
|
166
|
+
".png": "image/png",
|
|
167
|
+
".jpg": "image/jpeg",
|
|
168
|
+
".jpeg": "image/jpeg",
|
|
169
|
+
".webp": "image/webp",
|
|
170
|
+
};
|
|
171
|
+
// "/blog/first-post/" -> "blog-first-post"; "/" -> "home"; "/日本語/" (no ASCII letters or digits) -> "page-" + a
|
|
172
|
+
// short hash. Only word characters and dashes, so it can't leave --out-dir.
|
|
173
|
+
const fileOf = slug => {
|
|
174
|
+
const s = String(slug ?? "")
|
|
175
|
+
.trim()
|
|
176
|
+
.replace(/^\/+|\/+$/g, ""),
|
|
177
|
+
name = s.replace(/[^\w-]+/g, "-").replace(/^-+|-+$/g, "");
|
|
178
|
+
return (name || (s ? `page-${createHash("sha256").update(s).digest("hex").slice(0, 8)}` : "home")) + ".png";
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
const USAGE = `usage: node og-card.mjs --title "Plans and pricing" --out public/og/home.png [options]
|
|
182
|
+
node og-card.mjs --pages pages.json --out-dir public/og/ [options]
|
|
183
|
+
|
|
184
|
+
Makes 1200x630 share images on this computer with the installed Chrome or Edge
|
|
185
|
+
(CHROME_PATH picks one). No AI and no outside service.
|
|
186
|
+
--title <text> the card's headline (one card)
|
|
187
|
+
--subtitle <text> a line under the title
|
|
188
|
+
--out <file> where that card's PNG is written
|
|
189
|
+
--pages <file> many cards: a JSON list of { "slug", "title", "subtitle" }
|
|
190
|
+
--out-dir <folder> where those cards are written, one PNG a page, named from its slug
|
|
191
|
+
--brand <name> the name at the bottom of each card
|
|
192
|
+
--accent <#hex> the colour of the bar and bottom edge (default #2459c9)
|
|
193
|
+
--background <#hex> the background colour (default #0b1220)
|
|
194
|
+
--logo <file> a .svg, .png, .jpg or .webp beside the brand name
|
|
195
|
+
--help, -h show this help`;
|
|
196
|
+
|
|
197
|
+
if (isMain(import.meta.url))
|
|
198
|
+
await runMain(async () => {
|
|
199
|
+
const args = parseArgs(process.argv.slice(2), {
|
|
200
|
+
flags: ["title", "subtitle", "brand", "accent", "background", "logo", "out", "pages", "out-dir"],
|
|
201
|
+
positionals: 0,
|
|
202
|
+
usage: USAGE,
|
|
203
|
+
});
|
|
204
|
+
const fail = (msg, code = 2) => {
|
|
205
|
+
throw new Fail(msg, code);
|
|
206
|
+
};
|
|
207
|
+
const single = typeof args.title === "string" && typeof args.out === "string",
|
|
208
|
+
batch = typeof args.pages === "string" && typeof args["out-dir"] === "string";
|
|
209
|
+
if (!single && !batch) fail(USAGE);
|
|
210
|
+
|
|
211
|
+
const shared = {};
|
|
212
|
+
for (const k of ["brand", "accent", "background"]) if (typeof args[k] === "string") shared[k] = args[k];
|
|
213
|
+
if (typeof args.logo === "string") {
|
|
214
|
+
const mime = MIME[extname(args.logo).toLowerCase()];
|
|
215
|
+
if (!mime) fail(`og-card: --logo must be .svg, .png, .jpg or .webp, got ${args.logo}`);
|
|
216
|
+
if (!existsSync(args.logo)) fail(`og-card: logo not found: ${args.logo}`);
|
|
217
|
+
shared.logo = `data:${mime};base64,${readFileSync(args.logo).toString("base64")}`;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
let jobs;
|
|
221
|
+
if (single)
|
|
222
|
+
jobs = [
|
|
223
|
+
[
|
|
224
|
+
{ ...shared, title: args.title, subtitle: typeof args.subtitle === "string" ? args.subtitle : "" },
|
|
225
|
+
resolve(args.out),
|
|
226
|
+
],
|
|
227
|
+
];
|
|
228
|
+
else {
|
|
229
|
+
let pages;
|
|
230
|
+
try {
|
|
231
|
+
pages = JSON.parse(readFileSync(args.pages, "utf8"));
|
|
232
|
+
} catch (e) {
|
|
233
|
+
fail(`og-card: can't read ${args.pages} as JSON: ${e.message}`);
|
|
234
|
+
}
|
|
235
|
+
if (!Array.isArray(pages) || !pages.length || pages.some(p => !p || typeof p.title !== "string" || !p.title))
|
|
236
|
+
fail(
|
|
237
|
+
`og-card: ${args.pages} must be a non-empty array of { "slug", "title", "subtitle" } with a title in each`,
|
|
238
|
+
);
|
|
239
|
+
jobs = pages.map(p => [
|
|
240
|
+
{ ...shared, title: p.title, subtitle: p.subtitle || "" },
|
|
241
|
+
resolve(args["out-dir"], fileOf(p.slug)),
|
|
242
|
+
]);
|
|
243
|
+
const seen = new Set();
|
|
244
|
+
// Case-insensitive: About.png and about.png are one file on Windows and macOS.
|
|
245
|
+
for (const [, out] of jobs) {
|
|
246
|
+
if (seen.has(out.toLowerCase())) fail(`og-card: two pages would both write ${out}; give them different slugs`);
|
|
247
|
+
seen.add(out.toLowerCase());
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
try {
|
|
251
|
+
for (const [opts] of jobs) cardHtml(opts);
|
|
252
|
+
} catch (e) {
|
|
253
|
+
fail(`og-card: ${e.message}`);
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
let browser = null;
|
|
257
|
+
try {
|
|
258
|
+
browser = findBrowser();
|
|
259
|
+
} catch (e) {
|
|
260
|
+
fail(`og-card: ${e.message}`);
|
|
261
|
+
}
|
|
262
|
+
if (!browser) fail("og-card: no Chrome or Edge found. Install one, or set CHROME_PATH to its executable.");
|
|
263
|
+
try {
|
|
264
|
+
for (const [opts, out] of jobs) await renderCard(browser, opts, out);
|
|
265
|
+
} catch (e) {
|
|
266
|
+
fail(e.message, e instanceof CardError ? e.code : 1);
|
|
267
|
+
}
|
|
268
|
+
console.log(
|
|
269
|
+
single
|
|
270
|
+
? `og-card: wrote ${jobs[0][1]} (${W}x${H})`
|
|
271
|
+
: `og-card: wrote ${jobs.length} card(s) (${W}x${H}) to ${resolve(args["out-dir"])}`,
|
|
272
|
+
);
|
|
273
|
+
});
|
|
@@ -0,0 +1,359 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// @ts-check
|
|
3
|
+
// Nearby businesses of the same kind, and a check of the business's address, from OpenStreetMap. Context for the
|
|
4
|
+
// report: never a finding, never scored.
|
|
5
|
+
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
6
|
+
import { dirname, resolve } from "node:path";
|
|
7
|
+
import { isMain } from "./lib/is-main.mjs";
|
|
8
|
+
import { parseArgs } from "./lib/args.mjs";
|
|
9
|
+
import { Fail, runMain, warnProxy } from "./lib/cli.mjs";
|
|
10
|
+
import { bodyUpTo } from "./lib/http.mjs";
|
|
11
|
+
import { VERSION } from "./update-check.mjs";
|
|
12
|
+
import { BUSINESS_TYPES } from "./checks/business-type.mjs";
|
|
13
|
+
|
|
14
|
+
// Nominatim allows 1 request per second and no bulk geocoding, and wants results cached.
|
|
15
|
+
// https://operations.osmfoundation.org/policies/nominatim/
|
|
16
|
+
// overpass-api.de allows 10,000 queries and 1 GB a day; commercial use should run its own server (OSM_OVERPASS).
|
|
17
|
+
// https://wiki.openstreetmap.org/wiki/Overpass_API
|
|
18
|
+
const NOMINATIM = "https://nominatim.openstreetmap.org/search",
|
|
19
|
+
OVERPASS = "https://overpass-api.de/api/interpreter";
|
|
20
|
+
// Both services require a User-Agent that identifies the application.
|
|
21
|
+
const UA = `seo-supervisor-osm/${VERSION} (+https://github.com/m-zaman-khan/seo-supervisor)`;
|
|
22
|
+
// The data is ODbL; this credit, linked to the copyright page, is the accepted attribution.
|
|
23
|
+
// https://osmfoundation.org/wiki/Licence/Attribution_Guidelines
|
|
24
|
+
const CREDIT = "© OpenStreetMap contributors";
|
|
25
|
+
const USAGE =
|
|
26
|
+
'usage: node osm.mjs --crawl seo-audit/seo-crawl.json [--type plumber] [--near 53.7976,-1.5453] [--address "12 Park Row, Leeds"] [--radius 2000] [--out seo-audit/osm.json] [--yes]';
|
|
27
|
+
// The 10 km cap keeps the Overpass query small.
|
|
28
|
+
const RADIUS = 2000,
|
|
29
|
+
MAX_RADIUS = 10000,
|
|
30
|
+
CAP = 16 * 1024 * 1024,
|
|
31
|
+
BUSY = new Set([429, 503, 504]);
|
|
32
|
+
|
|
33
|
+
// Tags per id in data/business-types.json. "a=b&c=d" needs both; null is an online business or a kind OpenStreetMap
|
|
34
|
+
// has no tag for.
|
|
35
|
+
// https://wiki.openstreetmap.org/wiki/Map_features
|
|
36
|
+
export const OSM_TAGS = {
|
|
37
|
+
restaurant: ["amenity=restaurant"],
|
|
38
|
+
cafe: ["amenity=cafe"],
|
|
39
|
+
bar: ["amenity=bar", "amenity=pub"],
|
|
40
|
+
bakery: ["shop=bakery"],
|
|
41
|
+
dentist: ["amenity=dentist"],
|
|
42
|
+
physician: ["amenity=doctors"],
|
|
43
|
+
clinic: ["amenity=clinic"],
|
|
44
|
+
hospital: ["amenity=hospital"],
|
|
45
|
+
pharmacy: ["amenity=pharmacy"],
|
|
46
|
+
optician: ["shop=optician"],
|
|
47
|
+
lawyer: ["office=lawyer"],
|
|
48
|
+
"real-estate": ["office=estate_agent"],
|
|
49
|
+
"car-dealer": ["shop=car"],
|
|
50
|
+
hotel: ["tourism=hotel"],
|
|
51
|
+
motel: ["tourism=motel"],
|
|
52
|
+
"bed-and-breakfast": ["tourism=guest_house"],
|
|
53
|
+
hostel: ["tourism=hostel"],
|
|
54
|
+
resort: ["leisure=resort"],
|
|
55
|
+
campground: ["tourism=camp_site"],
|
|
56
|
+
"vacation-rental": ["tourism=apartment"],
|
|
57
|
+
plumber: ["craft=plumber"],
|
|
58
|
+
electrician: ["craft=electrician"],
|
|
59
|
+
hvac: ["craft=hvac"],
|
|
60
|
+
roofer: ["craft=roofer"],
|
|
61
|
+
builder: ["craft=builder", "office=construction_company"],
|
|
62
|
+
painter: ["craft=painter"],
|
|
63
|
+
locksmith: ["shop=locksmith", "craft=locksmith"],
|
|
64
|
+
movers: ["office=moving_company"],
|
|
65
|
+
"beauty-salon": ["shop=beauty"],
|
|
66
|
+
"hair-salon": ["shop=hairdresser"],
|
|
67
|
+
"nail-salon": ["shop=beauty&beauty=nails"],
|
|
68
|
+
"day-spa": ["shop=beauty&beauty=spa"],
|
|
69
|
+
gym: ["leisure=fitness_centre"],
|
|
70
|
+
"online-store": null,
|
|
71
|
+
"clothing-store": ["shop=clothes"],
|
|
72
|
+
florist: ["shop=florist"],
|
|
73
|
+
"book-store": ["shop=books"],
|
|
74
|
+
"jewelry-store": ["shop=jewelry"],
|
|
75
|
+
"furniture-store": ["shop=furniture"],
|
|
76
|
+
"hardware-store": ["shop=hardware", "shop=doityourself"],
|
|
77
|
+
"pet-store": ["shop=pet"],
|
|
78
|
+
"bike-store": ["shop=bicycle"],
|
|
79
|
+
"grocery-store": ["shop=supermarket", "shop=greengrocer", "shop=convenience"],
|
|
80
|
+
software: null,
|
|
81
|
+
school: ["amenity=school"],
|
|
82
|
+
university: ["amenity=university", "amenity=college"],
|
|
83
|
+
education: ["amenity=prep_school", "amenity=language_school"],
|
|
84
|
+
publisher: null,
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
const reason = e => (e.name === "TimeoutError" ? "no answer within 60 seconds" : e.cause?.code || e.message);
|
|
88
|
+
// body is null when the answer isn't JSON.
|
|
89
|
+
async function call(url, init = {}) {
|
|
90
|
+
const r = await fetch(url, {
|
|
91
|
+
...init,
|
|
92
|
+
headers: { "user-agent": UA, accept: "application/json", ...init.headers },
|
|
93
|
+
redirect: "error",
|
|
94
|
+
signal: AbortSignal.timeout(60000),
|
|
95
|
+
});
|
|
96
|
+
const b = await bodyUpTo(r, CAP);
|
|
97
|
+
if (!b) throw new Error("the answer is over 16 MB");
|
|
98
|
+
try {
|
|
99
|
+
return { status: r.status, body: JSON.parse(b.toString("utf8")) };
|
|
100
|
+
} catch {
|
|
101
|
+
return { status: r.status, body: null };
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
const busy = (who, status, what) =>
|
|
105
|
+
`${who} answered HTTP ${status}${BUSY.has(status) ? " (busy)" : ""}, so ${what}. Try again later.`;
|
|
106
|
+
const rad = d => (d * Math.PI) / 180;
|
|
107
|
+
// Great-circle distance in metres (haversine, the Earth's mean radius).
|
|
108
|
+
const metres = (a, b) =>
|
|
109
|
+
2 *
|
|
110
|
+
6371008.8 *
|
|
111
|
+
Math.asin(
|
|
112
|
+
Math.sqrt(
|
|
113
|
+
Math.sin(rad(b.lat - a.lat) / 2) ** 2 +
|
|
114
|
+
Math.cos(rad(a.lat)) * Math.cos(rad(b.lat)) * Math.sin(rad(b.lon - a.lon) / 2) ** 2,
|
|
115
|
+
),
|
|
116
|
+
);
|
|
117
|
+
const point = (lat, lon) => {
|
|
118
|
+
lat = typeof lat === "string" && lat.trim() ? +lat : lat;
|
|
119
|
+
lon = typeof lon === "string" && lon.trim() ? +lon : lon;
|
|
120
|
+
return Number.isFinite(lat) && Number.isFinite(lon) && Math.abs(lat) <= 90 && Math.abs(lon) <= 180
|
|
121
|
+
? { lat, lon }
|
|
122
|
+
: null;
|
|
123
|
+
};
|
|
124
|
+
const same = s =>
|
|
125
|
+
String(s || "")
|
|
126
|
+
.normalize("NFD")
|
|
127
|
+
.replace(/\p{M}/gu, "")
|
|
128
|
+
.toLowerCase()
|
|
129
|
+
.replace(/[^\p{L}\p{N}]+/gu, " ")
|
|
130
|
+
.trim();
|
|
131
|
+
const km = m => (m < 1000 ? `${m} m` : `${+(m / 1000).toFixed(1)} km`);
|
|
132
|
+
|
|
133
|
+
// A service-area business's street is never sent, only its town, region, postcode and country.
|
|
134
|
+
function addressOf(local) {
|
|
135
|
+
const a = local?.address,
|
|
136
|
+
sab = local?.kind === "service-area";
|
|
137
|
+
if (!a || typeof a !== "object") return null;
|
|
138
|
+
if (a.text) return sab ? null : a.text;
|
|
139
|
+
return (
|
|
140
|
+
[...(sab ? [] : [a.streetAddress]), a.addressLocality, a.addressRegion, a.postalCode, a.addressCountry]
|
|
141
|
+
.filter(s => typeof s === "string" && s.trim())
|
|
142
|
+
.join(", ") || null
|
|
143
|
+
);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// local is the crawl's localBusiness; cached is the last run's geocode, reused for the same address as Nominatim asks.
|
|
147
|
+
async function lookupOsm({
|
|
148
|
+
type,
|
|
149
|
+
near = null,
|
|
150
|
+
address = null,
|
|
151
|
+
radius = RADIUS,
|
|
152
|
+
local = null,
|
|
153
|
+
cached = null,
|
|
154
|
+
nominatim = NOMINATIM,
|
|
155
|
+
overpass = OVERPASS,
|
|
156
|
+
}) {
|
|
157
|
+
const notes = [],
|
|
158
|
+
out =
|
|
159
|
+
/** @type {{ source: string, when: string, credit: string, licence: string, copyright: string, nearby?: any, geocode?: any }} */ ({
|
|
160
|
+
source: "openstreetmap",
|
|
161
|
+
when: new Date().toISOString(),
|
|
162
|
+
credit: CREDIT,
|
|
163
|
+
licence: "ODbL 1.0",
|
|
164
|
+
copyright: "https://www.openstreetmap.org/copyright",
|
|
165
|
+
});
|
|
166
|
+
const sab = local?.kind === "service-area",
|
|
167
|
+
schemaGeo = point(local?.geo?.lat, local?.geo?.lon);
|
|
168
|
+
let center = near ? { ...near, from: "--near" } : schemaGeo ? { ...schemaGeo, from: "the schema's geo" } : null;
|
|
169
|
+
// One Nominatim request a run: to check a storefront's address, or to find a centre when there's none.
|
|
170
|
+
if (address && (!sab || !center)) {
|
|
171
|
+
try {
|
|
172
|
+
const reuse = cached?.query === address && point(cached.found?.lat, cached.found?.lon);
|
|
173
|
+
const u = new URL(nominatim);
|
|
174
|
+
u.search = new URLSearchParams({ q: address, format: "jsonv2", limit: "1" }).toString();
|
|
175
|
+
const { status, body } = reuse
|
|
176
|
+
? { status: 200, body: [{ lat: cached.found.lat, lon: cached.found.lon, display_name: cached.found.label }] }
|
|
177
|
+
: await call(u);
|
|
178
|
+
if (status !== 200 || !Array.isArray(body)) notes.push(busy("Nominatim", status, "the address wasn't looked up"));
|
|
179
|
+
else {
|
|
180
|
+
const hit = point(body[0]?.lat, body[0]?.lon),
|
|
181
|
+
found = hit && { ...hit, label: typeof body[0].display_name === "string" ? body[0].display_name : null };
|
|
182
|
+
out.geocode = {
|
|
183
|
+
query: address,
|
|
184
|
+
found: found || null,
|
|
185
|
+
schemaGeo,
|
|
186
|
+
distanceM: found && schemaGeo ? Math.round(metres(found, schemaGeo)) : null,
|
|
187
|
+
suggestGeo: !!found && !schemaGeo && !sab,
|
|
188
|
+
};
|
|
189
|
+
if (!center && found)
|
|
190
|
+
center = {
|
|
191
|
+
lat: found.lat,
|
|
192
|
+
lon: found.lon,
|
|
193
|
+
from: sab ? "the town, via Nominatim" : "the address, via Nominatim",
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
} catch (e) {
|
|
197
|
+
notes.push(`Couldn't reach Nominatim (${reason(e)}), so the address wasn't looked up.`);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
if (!center) {
|
|
201
|
+
notes.push(
|
|
202
|
+
"No centre for the nearby search: OpenStreetMap couldn't place the address. Pass --near with the business's latitude and longitude.",
|
|
203
|
+
);
|
|
204
|
+
return { ...out, notes };
|
|
205
|
+
}
|
|
206
|
+
// One Overpass query a run; a busy answer ends it with no retry.
|
|
207
|
+
const tags = OSM_TAGS[type];
|
|
208
|
+
const query = `[out:json][timeout:25];(${tags
|
|
209
|
+
.map(
|
|
210
|
+
t =>
|
|
211
|
+
`nwr${t
|
|
212
|
+
.split("&")
|
|
213
|
+
.map(kv => `["${kv.split("=")[0]}"="${kv.split("=")[1]}"]`)
|
|
214
|
+
.join("")}(around:${radius},${center.lat},${center.lon});`,
|
|
215
|
+
)
|
|
216
|
+
.join("")});out center;`;
|
|
217
|
+
try {
|
|
218
|
+
const { status, body } = await call(overpass, {
|
|
219
|
+
method: "POST",
|
|
220
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
221
|
+
body: new URLSearchParams({ data: query }).toString(),
|
|
222
|
+
});
|
|
223
|
+
if (status !== 200 || !Array.isArray(body?.elements)) {
|
|
224
|
+
notes.push(busy("Overpass", status, "nearby businesses weren't counted"));
|
|
225
|
+
return { ...out, notes };
|
|
226
|
+
}
|
|
227
|
+
const own = same(local?.name); // the business itself, left out by name
|
|
228
|
+
const places = body.elements
|
|
229
|
+
.map(e => ({
|
|
230
|
+
name: typeof e.tags?.name === "string" && e.tags.name.trim() ? e.tags.name.trim() : null,
|
|
231
|
+
at: point(e.lat ?? e.center?.lat, e.lon ?? e.center?.lon),
|
|
232
|
+
osm: `${e.type}/${e.id}`,
|
|
233
|
+
}))
|
|
234
|
+
.filter(p => p.at && (!own || same(p.name) !== own))
|
|
235
|
+
.map(p => ({ ...p, distanceM: Math.round(metres(center, p.at)) }))
|
|
236
|
+
.filter(p => p.distanceM <= radius)
|
|
237
|
+
.sort((a, b) => a.distanceM - b.distanceM);
|
|
238
|
+
// perKm2 is a local measure over the search circle, not an OpenStreetMap figure.
|
|
239
|
+
out.nearby = {
|
|
240
|
+
type,
|
|
241
|
+
label: BUSINESS_TYPES.find(b => b.id === type)?.label || type,
|
|
242
|
+
tags,
|
|
243
|
+
center: { lat: center.lat, lon: center.lon },
|
|
244
|
+
centerFrom: center.from,
|
|
245
|
+
radiusM: radius,
|
|
246
|
+
count: places.length,
|
|
247
|
+
unnamed: places.filter(p => !p.name).length,
|
|
248
|
+
perKm2: +(places.length / (Math.PI * (radius / 1000) ** 2)).toFixed(2),
|
|
249
|
+
places: places
|
|
250
|
+
.filter(p => p.name)
|
|
251
|
+
.slice(0, 20)
|
|
252
|
+
.map(p => ({ name: p.name, distanceM: Math.round(p.distanceM / 10) * 10, osm: p.osm })),
|
|
253
|
+
};
|
|
254
|
+
} catch (e) {
|
|
255
|
+
notes.push(`Couldn't reach Overpass (${reason(e)}), so nearby businesses weren't counted.`);
|
|
256
|
+
}
|
|
257
|
+
return { ...out, notes };
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
async function main(argv) {
|
|
261
|
+
const args = parseArgs(argv, {
|
|
262
|
+
flags: ["crawl", "type", "near", "address", "radius", "out"],
|
|
263
|
+
booleans: ["yes"],
|
|
264
|
+
positionals: 0,
|
|
265
|
+
usage: USAGE,
|
|
266
|
+
});
|
|
267
|
+
const str = k => (typeof args[k] === "string" ? args[k].trim() : null);
|
|
268
|
+
let crawl = null;
|
|
269
|
+
if (str("crawl")) {
|
|
270
|
+
try {
|
|
271
|
+
crawl = JSON.parse(readFileSync(str("crawl"), "utf8"));
|
|
272
|
+
} catch (e) {
|
|
273
|
+
throw new Fail(`osm: couldn't read --crawl ${str("crawl")} (${e.code || e.message}).`);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
const local = crawl?.localBusiness && typeof crawl.localBusiness === "object" ? crawl.localBusiness : null;
|
|
277
|
+
const ids = Object.keys(OSM_TAGS)
|
|
278
|
+
.filter(k => OSM_TAGS[k])
|
|
279
|
+
.join(", ");
|
|
280
|
+
const type = str("type") || (typeof crawl?.businessType?.guess === "string" ? crawl.businessType.guess : null);
|
|
281
|
+
if (!type)
|
|
282
|
+
throw new Fail(
|
|
283
|
+
`osm: no business type. Pass --type with one of: ${ids}; or --crawl with a crawl that guessed it.\n${USAGE}`,
|
|
284
|
+
);
|
|
285
|
+
if (!Object.hasOwn(OSM_TAGS, type)) throw new Fail(`osm: unknown --type "${type}". Use one of: ${ids}.`);
|
|
286
|
+
const label = BUSINESS_TYPES.find(b => b.id === type)?.label || type;
|
|
287
|
+
if (!OSM_TAGS[type])
|
|
288
|
+
throw new Fail(`osm: ${label} isn't a place on a map, so there are no nearby businesses to count.`);
|
|
289
|
+
let near = null;
|
|
290
|
+
if (args.near !== undefined) {
|
|
291
|
+
const [a, b] = String(args.near).split(",");
|
|
292
|
+
near = point(a, b);
|
|
293
|
+
if (!near) throw new Fail(`osm: --near must be latitude,longitude, like 53.7976,-1.5453 (got ${args.near}).`);
|
|
294
|
+
}
|
|
295
|
+
const radius = args.radius === undefined ? RADIUS : Number(args.radius);
|
|
296
|
+
if (!Number.isInteger(radius) || radius < 100 || radius > MAX_RADIUS)
|
|
297
|
+
throw new Fail(`osm: --radius must be whole metres from 100 to ${MAX_RADIUS} (got ${args.radius}).`);
|
|
298
|
+
const address = str("address") || addressOf(local),
|
|
299
|
+
schemaGeo = point(local?.geo?.lat, local?.geo?.lon),
|
|
300
|
+
sab = local?.kind === "service-area";
|
|
301
|
+
if (!near && !schemaGeo && !address)
|
|
302
|
+
throw new Fail(
|
|
303
|
+
`osm: no place to search around. Pass --near latitude,longitude or --address, or --crawl with a crawl that found the business's address.\n${USAGE}`,
|
|
304
|
+
);
|
|
305
|
+
// OSM_NOMINATIM and OSM_OVERPASS point at another server, or the tests' fakes.
|
|
306
|
+
const nominatim = process.env.OSM_NOMINATIM || NOMINATIM,
|
|
307
|
+
overpass = process.env.OSM_OVERPASS || OVERPASS;
|
|
308
|
+
const geocodes = !!address && (!sab || (!near && !schemaGeo));
|
|
309
|
+
|
|
310
|
+
if (!args.yes) {
|
|
311
|
+
const around = near
|
|
312
|
+
? `${near.lat}, ${near.lon} (--near)`
|
|
313
|
+
: schemaGeo
|
|
314
|
+
? `${schemaGeo.lat}, ${schemaGeo.lon} (the schema's geo)`
|
|
315
|
+
: "the point Nominatim gives";
|
|
316
|
+
console.log(
|
|
317
|
+
[
|
|
318
|
+
"osm: dry run, nothing sent. With --yes it would:",
|
|
319
|
+
...(geocodes
|
|
320
|
+
? [
|
|
321
|
+
`- send the address “${address}” to Nominatim (${new URL(nominatim).host}), one request, to ${sab ? "find the town" : "see where OpenStreetMap places it"};`,
|
|
322
|
+
]
|
|
323
|
+
: []),
|
|
324
|
+
`- ask Overpass (${new URL(overpass).host}), in one request, for ${label} places (${OSM_TAGS[type].join(", ")}) within ${km(radius)} of ${around}.`,
|
|
325
|
+
`No key is needed. The data is ${CREDIT}, free under the Open Database License (ODbL), and the report credits it.`,
|
|
326
|
+
"For commercial use, the Overpass wiki asks for a self-hosted or paid Overpass server: set OSM_OVERPASS to its address.",
|
|
327
|
+
"These go to outside services, so re-run with --yes once the owner agrees.",
|
|
328
|
+
].join("\n"),
|
|
329
|
+
);
|
|
330
|
+
return 0;
|
|
331
|
+
}
|
|
332
|
+
warnProxy();
|
|
333
|
+
const out = resolve(str("out") || "seo-audit/osm.json");
|
|
334
|
+
let cached = null;
|
|
335
|
+
try {
|
|
336
|
+
cached = JSON.parse(readFileSync(out, "utf8")).geocode;
|
|
337
|
+
} catch {}
|
|
338
|
+
const result = await lookupOsm({
|
|
339
|
+
type,
|
|
340
|
+
near,
|
|
341
|
+
address: geocodes ? address : null,
|
|
342
|
+
radius,
|
|
343
|
+
local,
|
|
344
|
+
cached,
|
|
345
|
+
nominatim,
|
|
346
|
+
overpass,
|
|
347
|
+
});
|
|
348
|
+
mkdirSync(dirname(out), { recursive: true });
|
|
349
|
+
writeFileSync(out, JSON.stringify(result, null, 2));
|
|
350
|
+
for (const n of result.notes) console.log("note: " + n);
|
|
351
|
+
const nb = result.nearby,
|
|
352
|
+
g = result.geocode;
|
|
353
|
+
console.log(
|
|
354
|
+
`osm: ${nb ? `${nb.count} other ${label} place(s) within ${km(radius)} (${nb.perKm2} per km²)` : "nearby businesses not counted"}${g ? ` · address ${g.found ? "found" : "not found"}` : ""} · ${CREDIT} · wrote ${out}`,
|
|
355
|
+
);
|
|
356
|
+
return 0;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
if (isMain(import.meta.url)) await runMain(() => main(process.argv.slice(2)));
|