@lownoise-studio/rendershield 0.3.0 → 1.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 (70) hide show
  1. package/CHANGELOG.md +58 -0
  2. package/CONTRIBUTING.md +41 -0
  3. package/README.md +209 -138
  4. package/SECURITY.md +25 -0
  5. package/dist/cli.d.ts +3 -0
  6. package/dist/cli.d.ts.map +1 -0
  7. package/dist/cli.js +43 -21
  8. package/dist/cli.js.map +1 -1
  9. package/dist/commands/build.d.ts +2 -0
  10. package/dist/commands/build.d.ts.map +1 -0
  11. package/dist/commands/build.js +10 -9
  12. package/dist/commands/build.js.map +1 -1
  13. package/dist/commands/init.d.ts +2 -0
  14. package/dist/commands/init.d.ts.map +1 -0
  15. package/dist/commands/init.js +7 -7
  16. package/dist/commands/init.js.map +1 -1
  17. package/dist/commands/verify.d.ts +19 -0
  18. package/dist/commands/verify.d.ts.map +1 -0
  19. package/dist/commands/verify.js +60 -64
  20. package/dist/commands/verify.js.map +1 -1
  21. package/dist/core/generateRobots.d.ts +3 -0
  22. package/dist/core/generateRobots.d.ts.map +1 -0
  23. package/dist/core/generateSitemap.d.ts +3 -0
  24. package/dist/core/generateSitemap.d.ts.map +1 -0
  25. package/dist/core/generateWorker.d.ts +3 -0
  26. package/dist/core/generateWorker.d.ts.map +1 -0
  27. package/dist/core/generateWorker.js +85 -75
  28. package/dist/core/generateWorker.js.map +1 -1
  29. package/dist/core/loadConfig.d.ts +3 -0
  30. package/dist/core/loadConfig.d.ts.map +1 -0
  31. package/dist/core/loadConfig.js +99 -40
  32. package/dist/core/loadConfig.js.map +1 -1
  33. package/dist/core/loadMarkdown.d.ts +3 -0
  34. package/dist/core/loadMarkdown.d.ts.map +1 -0
  35. package/dist/core/loadMarkdown.js +4 -3
  36. package/dist/core/loadMarkdown.js.map +1 -1
  37. package/dist/core/renderHtml.d.ts +3 -0
  38. package/dist/core/renderHtml.d.ts.map +1 -0
  39. package/dist/core/renderHtml.js +30 -11
  40. package/dist/core/renderHtml.js.map +1 -1
  41. package/dist/core/validateOutput.d.ts +28 -0
  42. package/dist/core/validateOutput.d.ts.map +1 -0
  43. package/dist/core/validateOutput.js +9 -3
  44. package/dist/core/validateOutput.js.map +1 -1
  45. package/dist/errors.d.ts +14 -0
  46. package/dist/errors.d.ts.map +1 -0
  47. package/dist/errors.js +24 -0
  48. package/dist/errors.js.map +1 -0
  49. package/dist/index.d.ts +20 -0
  50. package/dist/index.d.ts.map +1 -0
  51. package/dist/index.js +19 -0
  52. package/dist/index.js.map +1 -0
  53. package/dist/types.d.ts +53 -0
  54. package/dist/types.d.ts.map +1 -0
  55. package/dist/types.js +1 -1
  56. package/dist/types.js.map +1 -1
  57. package/docs/deploy-cloudflare.md +40 -14
  58. package/package.json +30 -4
  59. package/src/cli.ts +86 -60
  60. package/src/commands/build.ts +199 -185
  61. package/src/commands/init.ts +7 -7
  62. package/src/commands/verify.ts +266 -233
  63. package/src/core/generateWorker.ts +97 -87
  64. package/src/core/loadConfig.ts +261 -142
  65. package/src/core/loadMarkdown.ts +11 -5
  66. package/src/core/renderHtml.ts +41 -13
  67. package/src/core/validateOutput.ts +335 -325
  68. package/src/errors.ts +48 -0
  69. package/src/index.ts +40 -0
  70. package/src/types.ts +4 -1
@@ -1,233 +1,266 @@
1
- import fs from "fs-extra";
2
- import path from "node:path";
3
- import { loadConfig } from "../core/loadConfig.js";
4
- import { checkPrerenderContract } from "../core/validateOutput.js";
5
-
6
- function joinUrl(base: string, routePath: string): string {
7
- const b = base.endsWith("/") ? base.slice(0, -1) : base;
8
- const p = routePath.startsWith("/") ? routePath : `/${routePath}`;
9
- return b + p;
10
- }
11
-
12
- async function findFirstIndexHtml(outDirAbs: string): Promise<string | null> {
13
- const stack: string[] = [outDirAbs];
14
-
15
- while (stack.length > 0) {
16
- const current = stack.pop() as string;
17
-
18
- let entries: fs.Dirent[];
19
- try {
20
- entries = await fs.readdir(current, { withFileTypes: true });
21
- } catch {
22
- continue;
23
- }
24
-
25
- entries.sort((a, b) => a.name.localeCompare(b.name));
26
-
27
- for (const entry of entries) {
28
- const full = path.join(current, entry.name);
29
-
30
- if (entry.isDirectory()) {
31
- stack.push(full);
32
- continue;
33
- }
34
-
35
- if (entry.isFile() && entry.name.toLowerCase() === "index.html") {
36
- // Ignore index.html at the output root; prefer a routed page like
37
- // <section>/<slug>/index.html (or deeper).
38
- const rel = path.relative(outDirAbs, full);
39
- const parts = rel.split(path.sep).filter(Boolean);
40
- if (parts.length >= 2) return full;
41
- }
42
- }
43
- }
44
-
45
- return null;
46
- }
47
-
48
- function indexHtmlPathToRoute(outDirAbs: string, indexPathAbs: string): string {
49
- const rel = path.relative(outDirAbs, indexPathAbs);
50
- // rel: <section>/<slug>/index.html
51
- const noFile = rel.replace(/index\.html$/i, "");
52
- const normalized = noFile.split(path.sep).join("/").replace(/\/+$/, "");
53
- return "/" + normalized.replace(/^\/+/, "");
54
- }
55
-
56
- const BOT_UA =
57
- "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)";
58
- const HUMAN_UA =
59
- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";
60
-
61
- /** Heuristic: likely SPA shell if body has almost no visible content and no article. */
62
- function looksLikeSpaShell(html: string): { likely: boolean; reason?: string } {
63
- const bodyMatch = html.match(/<body[^>]*>([\s\S]*?)<\/body>/i);
64
- const bodyHtml = bodyMatch ? bodyMatch[1] : html;
65
- const noScript = bodyHtml
66
- .replace(/<script[\s\S]*?<\/script>/gi, " ")
67
- .replace(/<style[\s\S]*?<\/style>/gi, " ")
68
- .replace(/<noscript[\s\S]*?<\/noscript>/gi, " ");
69
- const text = noScript.replace(/<\/?[^>]+>/g, " ").replace(/\s+/g, " ").trim();
70
- if (text.length < 150) {
71
- return { likely: true, reason: `Body text very short (${text.length} chars); likely app shell.` };
72
- }
73
- if (!/<article\b/i.test(html)) {
74
- return { likely: true, reason: "No <article> present; may be SPA shell." };
75
- }
76
- const rootOnly = /<body[^>]*>\s*<div[^>]*id=["'](?:root|app|__next)["'][^>]*>\s*<\/div>\s*<\/body>/i.test(
77
- html.replace(/\s+/g, " ")
78
- );
79
- if (rootOnly) {
80
- return { likely: true, reason: "Single root div (e.g. #root, #app) with no content." };
81
- }
82
- return { likely: false };
83
- }
84
-
85
- export type VerifyProdOptions = { prodUrl: string };
86
-
87
- export async function cmdVerify(
88
- cwd = process.cwd(),
89
- options?: VerifyProdOptions
90
- ) {
91
- if (options?.prodUrl) {
92
- await runVerifyProd(options.prodUrl);
93
- return;
94
- }
95
-
96
- const cfg = await loadConfig(cwd);
97
-
98
- const outDirAbs = path.join(cwd, cfg.output.outDir);
99
- const exists = await fs.pathExists(outDirAbs);
100
-
101
- if (!exists) {
102
- console.log(`
103
- RenderShield verify
104
-
105
- No prerender output directory found: ${cfg.output.outDir}/
106
-
107
- Run:
108
- node dist/cli.js build
109
- `);
110
- return;
111
- }
112
-
113
- const firstIndex = await findFirstIndexHtml(outDirAbs);
114
-
115
- if (!firstIndex) {
116
- console.log(`
117
- RenderShield verify
118
-
119
- No prerendered pages found inside: ${cfg.output.outDir}/
120
-
121
- Run:
122
- node dist/cli.js build
123
- `);
124
- return;
125
- }
126
-
127
- const routePath = indexHtmlPathToRoute(outDirAbs, firstIndex);
128
- const url = joinUrl(cfg.site.canonicalBase, routePath);
129
-
130
- console.log(`
131
- RenderShield verify
132
-
133
- Using:
134
- canonicalBase: ${cfg.site.canonicalBase}
135
- routePath: ${routePath}
136
- output file: ${path.relative(cwd, firstIndex)}
137
-
138
- Smoke tests:
139
-
140
- 1) Human (usually SPA shell):
141
- curl -s ${url} | grep -i "<title>"
142
-
143
- 2) Bot (should see prerendered, route-specific title):
144
- curl -s -H "User-Agent: Googlebot" ${url} | grep -i "<title>"
145
-
146
- 3) Debug headers (Worker must be routed + proxy ON):
147
- curl -I -H "User-Agent: GPTBot" ${url}
148
-
149
- Expected: x-rendershield: bot-hit (proves Worker served prerender to bot).
150
- If debugHeaders enabled: X-Bot-Detected, X-Prerender, X-Final-Path.
151
- `);
152
- }
153
-
154
- async function runVerifyProd(url: string): Promise<void> {
155
- const normalizedUrl = url.startsWith("http") ? url : `https://${url}`;
156
-
157
- let botHtml: string;
158
- let humanHtml: string;
159
- let botStatus: number;
160
- let humanStatus: number;
161
- let xRenderShield: string | null;
162
-
163
- try {
164
- const [botRes, humanRes] = await Promise.all([
165
- fetch(normalizedUrl, {
166
- headers: { "User-Agent": BOT_UA },
167
- redirect: "follow",
168
- }),
169
- fetch(normalizedUrl, {
170
- headers: { "User-Agent": HUMAN_UA },
171
- redirect: "follow",
172
- }),
173
- ]);
174
-
175
- botStatus = botRes.status;
176
- humanStatus = humanRes.status;
177
- xRenderShield = botRes.headers.get("x-rendershield");
178
- botHtml = await botRes.text();
179
- humanHtml = await humanRes.text();
180
- } catch (err: unknown) {
181
- const msg = err instanceof Error ? err.message : String(err);
182
- throw new Error(
183
- `RenderShield verify --prod: failed to fetch ${normalizedUrl}. ${msg}`
184
- );
185
- }
186
-
187
- // Prove routing: Worker must set x-rendershield: bot-hit for bot requests. No inference.
188
- const routingOk = xRenderShield === "bot-hit";
189
- if (xRenderShield === "bot-fallback") {
190
- throw new Error(
191
- `RenderShield verify --prod: bot request received x-rendershield: bot-fallback. ` +
192
- `Prerender origin returned non-200; Worker fell back to SPA. Fix deployment or origin so bots get prerendered HTML.`
193
- );
194
- }
195
- if (!routingOk) {
196
- throw new Error(
197
- `RenderShield verify --prod: expected x-rendershield: bot-hit (proving Worker routed bot to prerender). ` +
198
- `Got: ${xRenderShield ?? "(missing)"}. Ensure the Worker is deployed and bound to this route.`
199
- );
200
- }
201
-
202
- const contract = checkPrerenderContract(botHtml, {
203
- routePath: normalizedUrl,
204
- outFile: normalizedUrl,
205
- });
206
-
207
- const humanSpa = looksLikeSpaShell(humanHtml);
208
-
209
- // Report
210
- console.log(`
211
- RenderShield verify --prod
212
- URL: ${normalizedUrl}
213
-
214
- Fetch:
215
- Bot (Googlebot): ${botStatus} (${botHtml.length} bytes) x-rendershield: ${xRenderShield ?? "(none)"}
216
- Human (Chrome): ${humanStatus} (${humanHtml.length} bytes)
217
-
218
- Routing: x-rendershield: bot-hit (Worker served prerendered HTML to bot)
219
-
220
- Bot contract (title, meta, canonical, OG, JSON-LD, article):
221
- ${contract.ok ? "PASS all required fields present." : "FAIL missing or invalid:"}
222
- ${contract.missing.length > 0 ? contract.missing.map((m) => ` - ${m}`).join("\n") : ""}
223
-
224
- Human response:
225
- ${humanSpa.likely ? `Likely SPA shell: ${humanSpa.reason ?? "unknown"}` : "Has substantial content (not a minimal SPA shell)."}
226
- `);
227
-
228
- if (!contract.ok) {
229
- throw new Error(
230
- `Production URL did not satisfy bot contract. Missing: ${contract.missing.join("; ")}`
231
- );
232
- }
233
- }
1
+ import fs from "fs-extra";
2
+ import path from "node:path";
3
+ import { loadConfig } from "../core/loadConfig.js";
4
+ import {
5
+ checkPrerenderContract,
6
+ type ContractCheckResult,
7
+ } from "../core/validateOutput.js";
8
+ import { renderShieldError } from "../errors.js";
9
+
10
+ function joinUrl(base: string, routePath: string): string {
11
+ const b = base.endsWith("/") ? base.slice(0, -1) : base;
12
+ const p = routePath.startsWith("/") ? routePath : `/${routePath}`;
13
+ return b + p;
14
+ }
15
+
16
+ async function findFirstIndexHtml(outDirAbs: string): Promise<string | null> {
17
+ const stack: string[] = [outDirAbs];
18
+
19
+ while (stack.length > 0) {
20
+ const current = stack.pop() as string;
21
+
22
+ let entries: fs.Dirent[];
23
+ try {
24
+ entries = await fs.readdir(current, { withFileTypes: true });
25
+ } catch {
26
+ continue;
27
+ }
28
+
29
+ entries.sort((a, b) => a.name.localeCompare(b.name));
30
+
31
+ for (const entry of entries) {
32
+ const full = path.join(current, entry.name);
33
+
34
+ if (entry.isDirectory()) {
35
+ stack.push(full);
36
+ continue;
37
+ }
38
+
39
+ if (entry.isFile() && entry.name.toLowerCase() === "index.html") {
40
+ // Ignore index.html at the output root; prefer a routed page like
41
+ // <section>/<slug>/index.html (or deeper).
42
+ const rel = path.relative(outDirAbs, full);
43
+ const parts = rel.split(path.sep).filter(Boolean);
44
+ if (parts.length >= 2) return full;
45
+ }
46
+ }
47
+ }
48
+
49
+ return null;
50
+ }
51
+
52
+ function indexHtmlPathToRoute(outDirAbs: string, indexPathAbs: string): string {
53
+ const rel = path.relative(outDirAbs, indexPathAbs);
54
+ // rel: <section>/<slug>/index.html
55
+ const noFile = rel.replace(/index\.html$/i, "");
56
+ const normalized = noFile.split(path.sep).join("/").replace(/\/+$/, "");
57
+ return "/" + normalized.replace(/^\/+/, "");
58
+ }
59
+
60
+ const BOT_UA =
61
+ "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)";
62
+ const HUMAN_UA =
63
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";
64
+
65
+ /** Heuristic: likely SPA shell if body has almost no visible content and no article. */
66
+ function looksLikeSpaShell(html: string): { likely: boolean; reason?: string } {
67
+ const bodyMatch = html.match(/<body[^>]*>([\s\S]*?)<\/body>/i);
68
+ const bodyHtml = bodyMatch ? bodyMatch[1] : html;
69
+ const noScript = bodyHtml
70
+ .replace(/<script[\s\S]*?<\/script>/gi, " ")
71
+ .replace(/<style[\s\S]*?<\/style>/gi, " ")
72
+ .replace(/<noscript[\s\S]*?<\/noscript>/gi, " ");
73
+ const text = noScript.replace(/<\/?[^>]+>/g, " ").replace(/\s+/g, " ").trim();
74
+ if (text.length < 150) {
75
+ return { likely: true, reason: `Body text very short (${text.length} chars); likely app shell.` };
76
+ }
77
+ if (!/<article\b/i.test(html)) {
78
+ return { likely: true, reason: "No <article> present; may be SPA shell." };
79
+ }
80
+ const rootOnly = /<body[^>]*>\s*<div[^>]*id=["'](?:root|app|__next)["'][^>]*>\s*<\/div>\s*<\/body>/i.test(
81
+ html.replace(/\s+/g, " ")
82
+ );
83
+ if (rootOnly) {
84
+ return { likely: true, reason: "Single root div (e.g. #root, #app) with no content." };
85
+ }
86
+ return { likely: false };
87
+ }
88
+
89
+ export type VerifyProdOptions = { prodUrl: string };
90
+
91
+ export type VerifyLocalResult = {
92
+ mode: "local";
93
+ canonicalBase: string;
94
+ routePath: string;
95
+ outputFile: string;
96
+ url: string;
97
+ };
98
+
99
+ export type VerifyProdResult = {
100
+ mode: "prod";
101
+ url: string;
102
+ contract: ContractCheckResult;
103
+ };
104
+
105
+ export type VerifyResult = VerifyLocalResult | VerifyProdResult;
106
+
107
+ export async function cmdVerify(
108
+ cwd = process.cwd(),
109
+ options?: VerifyProdOptions
110
+ ): Promise<VerifyResult> {
111
+ if (options?.prodUrl) {
112
+ return runVerifyProd(options.prodUrl);
113
+ }
114
+
115
+ const cfg = await loadConfig(cwd);
116
+
117
+ const outDirAbs = path.join(cwd, cfg.output.outDir);
118
+ const exists = await fs.pathExists(outDirAbs);
119
+
120
+ if (!exists) {
121
+ throw renderShieldError(
122
+ "VERIFY_FAILED",
123
+ `No prerender output directory found: ${cfg.output.outDir}/. Run: rendershield build`,
124
+ { outDir: cfg.output.outDir }
125
+ );
126
+ }
127
+
128
+ const firstIndex = await findFirstIndexHtml(outDirAbs);
129
+
130
+ if (!firstIndex) {
131
+ throw renderShieldError(
132
+ "VERIFY_FAILED",
133
+ `No prerendered pages found inside: ${cfg.output.outDir}/. Run: rendershield build`,
134
+ { outDir: cfg.output.outDir }
135
+ );
136
+ }
137
+
138
+ const routePath = indexHtmlPathToRoute(outDirAbs, firstIndex);
139
+ const url = joinUrl(cfg.site.canonicalBase, routePath);
140
+ const outputFile = path.relative(cwd, firstIndex);
141
+
142
+ console.log(`
143
+ RenderShield verify
144
+
145
+ Using:
146
+ canonicalBase: ${cfg.site.canonicalBase}
147
+ routePath: ${routePath}
148
+ output file: ${outputFile}
149
+
150
+ Smoke tests:
151
+
152
+ 1) Human (usually SPA shell):
153
+ curl -s ${url} | grep -i "<title>"
154
+
155
+ 2) Bot (should see prerendered, route-specific title):
156
+ curl -s -H "User-Agent: Googlebot" ${url} | grep -i "<title>"
157
+
158
+ 3) Debug headers (Worker must be routed + proxy ON):
159
+ curl -I -H "User-Agent: GPTBot" ${url}
160
+
161
+ Expected: x-rendershield: bot-hit (proves Worker served prerender to bot).
162
+ If debugHeaders enabled: X-Bot-Detected, X-Prerender, X-Final-Path.
163
+ `);
164
+
165
+ return {
166
+ mode: "local",
167
+ canonicalBase: cfg.site.canonicalBase,
168
+ routePath,
169
+ outputFile,
170
+ url,
171
+ };
172
+ }
173
+
174
+ async function runVerifyProd(url: string): Promise<VerifyProdResult> {
175
+ const normalizedUrl = url.startsWith("http") ? url : `https://${url}`;
176
+
177
+ let botHtml: string;
178
+ let humanHtml: string;
179
+ let botStatus: number;
180
+ let humanStatus: number;
181
+ let xRenderShield: string | null;
182
+
183
+ try {
184
+ const [botRes, humanRes] = await Promise.all([
185
+ fetch(normalizedUrl, {
186
+ headers: { "User-Agent": BOT_UA },
187
+ redirect: "follow",
188
+ }),
189
+ fetch(normalizedUrl, {
190
+ headers: { "User-Agent": HUMAN_UA },
191
+ redirect: "follow",
192
+ }),
193
+ ]);
194
+
195
+ botStatus = botRes.status;
196
+ humanStatus = humanRes.status;
197
+ xRenderShield = botRes.headers.get("x-rendershield");
198
+ botHtml = await botRes.text();
199
+ humanHtml = await humanRes.text();
200
+ } catch (err: unknown) {
201
+ const msg = err instanceof Error ? err.message : String(err);
202
+ throw renderShieldError(
203
+ "VERIFY_FAILED",
204
+ `verify --prod: failed to fetch ${normalizedUrl}. ${msg}`,
205
+ { url: normalizedUrl }
206
+ );
207
+ }
208
+
209
+ // Prove routing: Worker must set x-rendershield: bot-hit for bot requests. No inference.
210
+ const routingOk = xRenderShield === "bot-hit";
211
+ if (xRenderShield === "bot-fallback") {
212
+ throw renderShieldError(
213
+ "VERIFY_FAILED",
214
+ `verify --prod: bot request received x-rendershield: bot-fallback. ` +
215
+ `Prerender origin returned non-200; Worker fell back to SPA. Fix deployment or origin so bots get prerendered HTML.`,
216
+ { url: normalizedUrl, xRenderShield }
217
+ );
218
+ }
219
+ if (!routingOk) {
220
+ const hint = xRenderShield == null
221
+ ? " If no Worker is deployed, use verify without --prod to check local/build output."
222
+ : "";
223
+ throw renderShieldError(
224
+ "VERIFY_FAILED",
225
+ `verify --prod: expected x-rendershield: bot-hit (proving Worker routed bot to prerender). ` +
226
+ `Got: ${xRenderShield ?? "(missing)"}. Ensure the Worker is deployed and bound to this route.${hint}`,
227
+ { url: normalizedUrl, xRenderShield }
228
+ );
229
+ }
230
+
231
+ const contract = checkPrerenderContract(botHtml, {
232
+ routePath: normalizedUrl,
233
+ outFile: normalizedUrl,
234
+ });
235
+
236
+ const humanSpa = looksLikeSpaShell(humanHtml);
237
+
238
+ // Report
239
+ console.log(`
240
+ RenderShield verify --prod
241
+ URL: ${normalizedUrl}
242
+
243
+ Fetch:
244
+ Bot (Googlebot): ${botStatus} (${botHtml.length} bytes) x-rendershield: ${xRenderShield ?? "(none)"}
245
+ Human (Chrome): ${humanStatus} (${humanHtml.length} bytes)
246
+
247
+ Routing: x-rendershield: bot-hit (Worker served prerendered HTML to bot)
248
+
249
+ Bot contract (title, meta, canonical, OG, JSON-LD, article):
250
+ ${contract.ok ? "PASS — all required fields present." : "FAIL — missing or invalid:"}
251
+ ${contract.missing.length > 0 ? contract.missing.map((m) => ` - ${m}`).join("\n") : ""}
252
+
253
+ Human response:
254
+ ${humanSpa.likely ? `Likely SPA shell: ${humanSpa.reason ?? "unknown"}` : "Has substantial content (not a minimal SPA shell)."}
255
+ `);
256
+
257
+ if (!contract.ok) {
258
+ throw renderShieldError(
259
+ "VERIFY_FAILED",
260
+ `Production URL did not satisfy bot contract. Missing: ${contract.missing.join("; ")}`,
261
+ { url: normalizedUrl, missing: contract.missing }
262
+ );
263
+ }
264
+
265
+ return { mode: "prod", url: normalizedUrl, contract };
266
+ }