belt 0.6.9 → 0.6.11
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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +49 -0
- data/lib/belt/cli/frontend_deploy_command.rb +25 -6
- data/lib/belt/cli/frontend_env_command.rb +35 -0
- data/lib/belt/cli/frontend_prerender.rb +94 -0
- data/lib/belt/cli/frontend_routes.rb +129 -0
- data/lib/belt/cli/frontend_setup_command.rb +8 -0
- data/lib/belt/cli.rb +2 -0
- data/lib/belt/docs/frontend.md +85 -12
- data/lib/belt/frontend/prerender.mjs +290 -0
- data/lib/belt/frontend/router.js +112 -0
- data/lib/belt/version.rb +1 -1
- data/lib/templates/frontend/react/package.json.erb +1 -1
- data/lib/templates/frontend/react/src/App.jsx +2 -0
- data/lib/templates/frontend/react/src/entry-server.jsx +2 -1
- data/lib/templates/frontend/react/src/pages/NotFound.jsx +18 -0
- data/lib/templates/frontend/react/src/seo.js.erb +7 -2
- data/lib/templates/module/frontend.tf.erb +43 -1
- data/lib/templates/new_app/AGENTS.md.erb +7 -2
- metadata +6 -2
- data/lib/templates/frontend/react/scripts/prerender.js +0 -172
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Belt's SEO/AEO prerender step. `belt deploy frontend` (and `belt frontend
|
|
3
|
+
* prerender`) run it after `npm run build` for any frontend with a src/seo.js
|
|
4
|
+
* manifest. The app owns the content (seo.js); belt owns the mechanism.
|
|
5
|
+
*
|
|
6
|
+
* Search and AI answer-engine crawlers mostly don't run JavaScript, so an SPA's
|
|
7
|
+
* empty <div id="root"> tells them nothing. From the manifest this writes into dist/:
|
|
8
|
+
*
|
|
9
|
+
* index.html, <path>.html — each page in seo.pages rendered to HTML (via the SSR
|
|
10
|
+
* bundle of src/entry-server.*, when there is one) with its
|
|
11
|
+
* own <title>, description, canonical URL, Open Graph tags
|
|
12
|
+
* and JSON-LD
|
|
13
|
+
* robots.txt — allows crawlers in indexable environments, `Disallow: /`
|
|
14
|
+
* elsewhere. A project public/robots.txt wins when indexable.
|
|
15
|
+
* sitemap.xml — every public page (needs a site URL)
|
|
16
|
+
* llms.txt — plain-text site summary for LLMs (https://llmstxt.org)
|
|
17
|
+
* .belt-pages.json — S3 key → file map; `belt deploy frontend` uploads each page
|
|
18
|
+
* to its extensionless key (/about → about.html) as text/html
|
|
19
|
+
* 404.html — what an address with no page gets, with HTTP 404: the app's
|
|
20
|
+
* own "not found" route when it has one, never indexed
|
|
21
|
+
* .belt-routes.json — the public pages, plus the app's own routes (every
|
|
22
|
+
* <Route path="/..."> under --src and seo.privatePaths);
|
|
23
|
+
* `belt deploy frontend` publishes them to CloudFront so it can
|
|
24
|
+
* tell a real address from a missing one (see `belt explain
|
|
25
|
+
* seo`, "Real 404s")
|
|
26
|
+
*
|
|
27
|
+
* With --routes-only (a frontend whose own build already prerendered its pages) nothing
|
|
28
|
+
* above is touched except what real 404s need: .belt-routes.json gains the app's routes
|
|
29
|
+
* (keeping any `pages`/`objects` the build wrote, else taking pages from .belt-pages.json),
|
|
30
|
+
* and 404.html is written only if the build didn't write one.
|
|
31
|
+
*
|
|
32
|
+
* Usage: node prerender.mjs --manifest src/seo.js --dist dist [--ssr entry-server.js] [--public public] [--src src]
|
|
33
|
+
*
|
|
34
|
+
* Environment:
|
|
35
|
+
* VITE_SITE_URL canonical origin (belt deploy injects the frontend URL)
|
|
36
|
+
* BELT_ENV environment being built (belt deploy injects it)
|
|
37
|
+
* SEO_INDEXABLE "true"/"false" to override seo.indexableEnvironments
|
|
38
|
+
*/
|
|
39
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
|
|
40
|
+
import { dirname, join, resolve } from 'node:path'
|
|
41
|
+
import { pathToFileURL } from 'node:url'
|
|
42
|
+
import { parseArgs } from 'node:util'
|
|
43
|
+
|
|
44
|
+
const { values: args } = parseArgs({
|
|
45
|
+
options: {
|
|
46
|
+
manifest: { type: 'string' },
|
|
47
|
+
dist: { type: 'string' },
|
|
48
|
+
ssr: { type: 'string' },
|
|
49
|
+
public: { type: 'string' },
|
|
50
|
+
src: { type: 'string' },
|
|
51
|
+
'routes-only': { type: 'boolean' }
|
|
52
|
+
}
|
|
53
|
+
})
|
|
54
|
+
if (!args.manifest || !args.dist) {
|
|
55
|
+
console.error('Usage: node prerender.mjs --manifest src/seo.js --dist dist [--ssr entry-server.js] [--public public] [--src src]')
|
|
56
|
+
process.exit(1)
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const DIST = resolve(args.dist)
|
|
60
|
+
const SSR_ENTRY = args.ssr ? resolve(args.ssr) : null
|
|
61
|
+
const PROJECT_ROBOTS = args.public ? join(resolve(args.public), 'robots.txt') : null
|
|
62
|
+
const SRC = args.src ? resolve(args.src) : null
|
|
63
|
+
const seo = (await import(pathToFileURL(resolve(args.manifest)).href)).default
|
|
64
|
+
|
|
65
|
+
const siteUrl = (process.env.VITE_SITE_URL || seo.siteUrl || '').replace(/\/+$/, '')
|
|
66
|
+
const indexable = process.env.SEO_INDEXABLE
|
|
67
|
+
? process.env.SEO_INDEXABLE === 'true'
|
|
68
|
+
: (seo.indexableEnvironments || ['prod']).includes(process.env.BELT_ENV)
|
|
69
|
+
|
|
70
|
+
const normalize = (path) => `/${path.replace(/^\/+|\/+$/g, '')}`
|
|
71
|
+
const privatePaths = (seo.privatePaths || []).map(normalize)
|
|
72
|
+
const isPrivate = (path) => privatePaths.some((p) => path === p || path.startsWith(`${p}/`))
|
|
73
|
+
const pages = (seo.pages || [])
|
|
74
|
+
.map((page) => ({ ...page, path: normalize(page.path) }))
|
|
75
|
+
.filter((page) => !isPrivate(page.path))
|
|
76
|
+
|
|
77
|
+
const escapeHtml = (s) =>
|
|
78
|
+
String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"')
|
|
79
|
+
const absolute = (path) => `${siteUrl}${path === '/' ? '/' : path}`
|
|
80
|
+
|
|
81
|
+
async function loadRenderer() {
|
|
82
|
+
if (!SSR_ENTRY) return null
|
|
83
|
+
if (!existsSync(SSR_ENTRY)) {
|
|
84
|
+
console.warn(`⚠️ ${SSR_ENTRY} not found — pages get SEO tags but no prerendered content`)
|
|
85
|
+
return null
|
|
86
|
+
}
|
|
87
|
+
try {
|
|
88
|
+
return (await import(pathToFileURL(SSR_ENTRY).href)).render
|
|
89
|
+
} catch (error) {
|
|
90
|
+
console.warn(`⚠️ Could not load the SSR bundle (${error.message}) — pages get SEO tags but no prerendered content`)
|
|
91
|
+
return null
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function renderBody(render, path) {
|
|
96
|
+
if (!render) return ''
|
|
97
|
+
try {
|
|
98
|
+
return render(path)
|
|
99
|
+
} catch (error) {
|
|
100
|
+
// Usually a component touching window/document/localStorage during render.
|
|
101
|
+
// Move that into useEffect to get the content prerendered.
|
|
102
|
+
console.warn(`⚠️ Prerender failed for ${path} (${error.message}) — serving SEO tags only`)
|
|
103
|
+
return ''
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function jsonLd(page) {
|
|
108
|
+
const data = page.jsonLd || {
|
|
109
|
+
'@context': 'https://schema.org',
|
|
110
|
+
'@type': page.path === '/' ? 'WebSite' : 'WebPage',
|
|
111
|
+
name: page.title,
|
|
112
|
+
description: page.description,
|
|
113
|
+
...(siteUrl ? { url: absolute(page.path) } : {})
|
|
114
|
+
}
|
|
115
|
+
return JSON.stringify(data).replace(/</g, '\\u003c')
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function headTags(page) {
|
|
119
|
+
const tags = []
|
|
120
|
+
if (siteUrl) tags.push(`<link rel="canonical" href="${absolute(page.path)}" />`)
|
|
121
|
+
if (!indexable) tags.push('<meta name="robots" content="noindex, nofollow" />')
|
|
122
|
+
tags.push(
|
|
123
|
+
`<meta property="og:type" content="website" />`,
|
|
124
|
+
`<meta property="og:site_name" content="${escapeHtml(seo.siteName)}" />`,
|
|
125
|
+
`<meta property="og:title" content="${escapeHtml(page.title)}" />`,
|
|
126
|
+
`<meta property="og:description" content="${escapeHtml(page.description)}" />`
|
|
127
|
+
)
|
|
128
|
+
if (siteUrl) tags.push(`<meta property="og:url" content="${absolute(page.path)}" />`)
|
|
129
|
+
if (page.image) tags.push(`<meta property="og:image" content="${escapeHtml(page.image)}" />`)
|
|
130
|
+
tags.push(
|
|
131
|
+
`<meta name="twitter:card" content="${page.image ? 'summary_large_image' : 'summary'}" />`,
|
|
132
|
+
'<link rel="alternate" type="text/plain" href="/llms.txt" title="llms.txt" />',
|
|
133
|
+
`<script type="application/ld+json">${jsonLd(page)}</script>`
|
|
134
|
+
)
|
|
135
|
+
return tags.map((tag) => ` ${tag}\n`).join('')
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function pageHtml(template, page, body) {
|
|
139
|
+
return template
|
|
140
|
+
.replace(/<title>[\s\S]*?<\/title>/, () => `<title>${escapeHtml(page.title)}</title>`)
|
|
141
|
+
.replace(/\s*<meta name="description"[^>]*>/, '')
|
|
142
|
+
.replace(
|
|
143
|
+
'</head>',
|
|
144
|
+
() => ` <meta name="description" content="${escapeHtml(page.description)}" />\n${headTags(page)} </head>`
|
|
145
|
+
)
|
|
146
|
+
.replace(
|
|
147
|
+
'<div id="root"></div>',
|
|
148
|
+
// data-prerendered tells main.jsx to hydrate rather than render fresh
|
|
149
|
+
() => (body ? `<div id="root" data-prerendered="${escapeHtml(page.path)}">${body}</div>` : '<div id="root"></div>')
|
|
150
|
+
)
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// The addresses the single-page app routes itself, as patterns for belt's
|
|
154
|
+
// CloudFront router: `*` is one segment, a trailing `**` is the rest. They come
|
|
155
|
+
// from the app's own <Route path="/..."> declarations, so adding a route needs no
|
|
156
|
+
// second list, plus seo.privatePaths for anything declared another way (nested
|
|
157
|
+
// relative routes, a router config object, a path built at runtime).
|
|
158
|
+
const ROUTE_PATH = /<Route\b[^>]*?\bpath=\{?["'`](\/[^"'`]*)["'`]/g
|
|
159
|
+
const SOURCE_FILE = /\.(jsx?|tsx?)$/
|
|
160
|
+
const TEST_FILE = /\.(test|spec)\.|__tests__/
|
|
161
|
+
|
|
162
|
+
function sourceFiles(dir) {
|
|
163
|
+
return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
|
|
164
|
+
const path = join(dir, entry.name)
|
|
165
|
+
if (entry.isDirectory()) return entry.name === 'node_modules' ? [] : sourceFiles(path)
|
|
166
|
+
return SOURCE_FILE.test(entry.name) && !TEST_FILE.test(path) ? [path] : []
|
|
167
|
+
})
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function routePattern(path) {
|
|
171
|
+
const segments = []
|
|
172
|
+
for (const segment of normalize(path).split('/').slice(1)) {
|
|
173
|
+
if (segment === '*' || segment.endsWith('?')) return ['', ...segments, '**'].join('/')
|
|
174
|
+
segments.push(segment.startsWith(':') ? '*' : segment)
|
|
175
|
+
}
|
|
176
|
+
return ['', ...segments].join('/')
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function appRoutes(pagePaths) {
|
|
180
|
+
const declared = SRC && existsSync(SRC)
|
|
181
|
+
? sourceFiles(SRC).flatMap((file) => [...readFileSync(file, 'utf-8').matchAll(ROUTE_PATH)].map((match) => match[1]))
|
|
182
|
+
: []
|
|
183
|
+
const patterns = [...declared.map(routePattern), ...privatePaths.map((path) => `${path}/**`)]
|
|
184
|
+
return [...new Set(patterns)].filter((pattern) => pattern !== '/' && !pagePaths.includes(pattern)).sort()
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// Served for every address that is neither a page nor an app route. It keeps the
|
|
188
|
+
// app's scripts, so a route belt couldn't see still boots the app in a browser.
|
|
189
|
+
const NOT_FOUND_PATH = '/404'
|
|
190
|
+
|
|
191
|
+
function notFoundHtml(template, body) {
|
|
192
|
+
const title = seo.notFound?.title || `Page not found | ${seo.siteName}`
|
|
193
|
+
const description = seo.notFound?.description || `There is no page at this address on ${seo.siteName}.`
|
|
194
|
+
const fallback = `<main><h1>Page not found</h1><p>${escapeHtml(description)}</p><p><a href="/">${escapeHtml(seo.siteName)}</a></p></main>`
|
|
195
|
+
return template
|
|
196
|
+
.replace(/<title>[\s\S]*?<\/title>/, () => `<title>${escapeHtml(title)}</title>`)
|
|
197
|
+
.replace(/\s*<meta name="description"[^>]*>/, '')
|
|
198
|
+
.replace(
|
|
199
|
+
'</head>',
|
|
200
|
+
() =>
|
|
201
|
+
` <meta name="description" content="${escapeHtml(description)}" />\n` +
|
|
202
|
+
' <meta name="robots" content="noindex" />\n </head>'
|
|
203
|
+
)
|
|
204
|
+
.replace(
|
|
205
|
+
'<div id="root"></div>',
|
|
206
|
+
() => (body ? `<div id="root" data-prerendered="${NOT_FOUND_PATH}">${body}</div>` : `<div id="root">${fallback}</div>`)
|
|
207
|
+
)
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function robotsTxt() {
|
|
211
|
+
if (!indexable) return 'User-agent: *\nDisallow: /\n'
|
|
212
|
+
if (PROJECT_ROBOTS && existsSync(PROJECT_ROBOTS)) return readFileSync(PROJECT_ROBOTS, 'utf-8')
|
|
213
|
+
const lines = ['User-agent: *', 'Allow: /', ...privatePaths.map((p) => `Disallow: ${p}`)]
|
|
214
|
+
if (siteUrl) lines.push('', `Sitemap: ${siteUrl}/sitemap.xml`)
|
|
215
|
+
return `${lines.join('\n')}\n`
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function sitemapXml() {
|
|
219
|
+
const urls = pages.map((page) => ` <url><loc>${escapeHtml(absolute(page.path))}</loc></url>`).join('\n')
|
|
220
|
+
return `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${urls}\n</urlset>\n`
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function llmsTxt() {
|
|
224
|
+
const lines = [`# ${seo.siteName}`, '', `> ${seo.description}`, '', '## Pages', '']
|
|
225
|
+
for (const page of pages) lines.push(`- [${page.title}](${absolute(page.path)}): ${page.description}`)
|
|
226
|
+
return `${lines.join('\n')}\n`
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
const readJson = (file) => (existsSync(file) ? JSON.parse(readFileSync(file, 'utf-8')) : null)
|
|
230
|
+
|
|
231
|
+
// The app's build prerendered its own pages. Fill in what real 404s still need.
|
|
232
|
+
function completeRoutes(indexFile) {
|
|
233
|
+
const routesFile = join(DIST, '.belt-routes.json')
|
|
234
|
+
const built = readJson(routesFile) || {}
|
|
235
|
+
const pagePaths = built.pages || Object.keys(readJson(join(DIST, '.belt-pages.json')) || {}).map(normalize)
|
|
236
|
+
const routes = { ...built, pages: pagePaths, app: appRoutes(pagePaths) }
|
|
237
|
+
|
|
238
|
+
writeFileSync(routesFile, `${JSON.stringify(routes, null, 2)}\n`)
|
|
239
|
+
if (!existsSync(join(DIST, '404.html'))) {
|
|
240
|
+
writeFileSync(join(DIST, '404.html'), notFoundHtml(readFileSync(indexFile, 'utf-8'), ''))
|
|
241
|
+
}
|
|
242
|
+
console.log(`SEO: ${routes.app.length} app route(s) and ${pagePaths.length + 1} page(s) answer; any other address is a 404`)
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
async function main() {
|
|
246
|
+
const indexFile = join(DIST, 'index.html')
|
|
247
|
+
if (!existsSync(indexFile)) {
|
|
248
|
+
console.error(`${indexFile} not found — run \`vite build\` first`)
|
|
249
|
+
process.exit(1)
|
|
250
|
+
}
|
|
251
|
+
if (args['routes-only']) return completeRoutes(indexFile)
|
|
252
|
+
if (!pages.some((page) => page.path === '/')) pages.unshift({ path: '/', title: seo.siteName })
|
|
253
|
+
for (const page of pages) {
|
|
254
|
+
page.title ||= seo.siteName
|
|
255
|
+
page.description ||= seo.description
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
const template = readFileSync(indexFile, 'utf-8')
|
|
259
|
+
const render = await loadRenderer()
|
|
260
|
+
const manifest = {}
|
|
261
|
+
|
|
262
|
+
for (const page of pages) {
|
|
263
|
+
const html = pageHtml(template, page, renderBody(render, page.path))
|
|
264
|
+
const key = page.path.slice(1)
|
|
265
|
+
const file = key ? `${key}.html` : 'index.html'
|
|
266
|
+
mkdirSync(dirname(join(DIST, file)), { recursive: true })
|
|
267
|
+
writeFileSync(join(DIST, file), html)
|
|
268
|
+
if (key) manifest[key] = file
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
writeFileSync(join(DIST, '404.html'), notFoundHtml(template, renderBody(render, NOT_FOUND_PATH)))
|
|
272
|
+
const pagePaths = pages.map((page) => page.path).filter((path) => path !== '/')
|
|
273
|
+
const routes = { pages: pagePaths, app: appRoutes(pagePaths) }
|
|
274
|
+
|
|
275
|
+
writeFileSync(join(DIST, '.belt-pages.json'), `${JSON.stringify(manifest, null, 2)}\n`)
|
|
276
|
+
writeFileSync(join(DIST, '.belt-routes.json'), `${JSON.stringify(routes, null, 2)}\n`)
|
|
277
|
+
writeFileSync(join(DIST, 'robots.txt'), robotsTxt())
|
|
278
|
+
writeFileSync(join(DIST, 'llms.txt'), llmsTxt())
|
|
279
|
+
if (siteUrl) writeFileSync(join(DIST, 'sitemap.xml'), sitemapXml())
|
|
280
|
+
|
|
281
|
+
if (PROJECT_ROBOTS && indexable && existsSync(PROJECT_ROBOTS)) console.log('SEO: robots.txt from public/robots.txt')
|
|
282
|
+
if (!siteUrl) console.warn('⚠️ No site URL (VITE_SITE_URL or seo.siteUrl) — skipped canonical URLs and sitemap.xml')
|
|
283
|
+
console.log(`SEO: ${routes.app.length} app route(s) and ${pagePaths.length + 1} page(s) answer; any other address is a 404`)
|
|
284
|
+
console.log(
|
|
285
|
+
`SEO: prerendered ${pages.length} page(s), ${indexable ? 'indexable' : 'noindex'}` +
|
|
286
|
+
`${process.env.BELT_ENV ? ` (${process.env.BELT_ENV})` : ''}`
|
|
287
|
+
)
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
await main()
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
// Belt frontend router — a CloudFront Function (cloudfront-js-2.0), associated
|
|
2
|
+
// with the distribution's default behavior for both viewer-request and
|
|
3
|
+
// viewer-response. It makes an address with no page answer HTTP 404 instead of
|
|
4
|
+
// the app shell with 200, so crawlers and agents can tell a missing page from a
|
|
5
|
+
// real one.
|
|
6
|
+
//
|
|
7
|
+
// `belt deploy frontend` publishes the app's routes (src/seo.js) to the
|
|
8
|
+
// KeyValueStore associated with this function:
|
|
9
|
+
//
|
|
10
|
+
// belt:routes number of chunks
|
|
11
|
+
// belt:routes:N chunk N of the JSON { "app": [...], "pages": [...], "objects": {...} }
|
|
12
|
+
// (a KeyValueStore value holds 1 KB, so the JSON is split)
|
|
13
|
+
//
|
|
14
|
+
// `pages` are prerendered public pages, stored in S3 at their extensionless key
|
|
15
|
+
// unless `objects` names another object for that path ("/" included).
|
|
16
|
+
// `app` are patterns for the addresses the single-page app routes itself, read
|
|
17
|
+
// from its <Route path> declarations and seo.privatePaths: `*` is any one
|
|
18
|
+
// segment, a trailing `**` is anything from there on.
|
|
19
|
+
//
|
|
20
|
+
// a page → served from its own object
|
|
21
|
+
// an app route → /index.html
|
|
22
|
+
// anything else → /404.html, with status 404
|
|
23
|
+
// a path with a file extension (/assets/x.js, /robots.txt) → untouched
|
|
24
|
+
//
|
|
25
|
+
// CloudFront's JavaScript engine is not Node: among other gaps it rejects `await`
|
|
26
|
+
// inside a call's arguments or a condition. Keep every await as its own
|
|
27
|
+
// `const x = await ...` statement (spec/belt/frontend/router_spec.rb checks).
|
|
28
|
+
//
|
|
29
|
+
// Until routes have been published, or if the store can't be read, every request
|
|
30
|
+
// passes through untouched and the distribution's custom error responses serve
|
|
31
|
+
// index.html, exactly as before this function existed.
|
|
32
|
+
import cf from 'cloudfront';
|
|
33
|
+
|
|
34
|
+
const NOT_FOUND = '/404.html';
|
|
35
|
+
|
|
36
|
+
async function loadRoutes() {
|
|
37
|
+
try {
|
|
38
|
+
const kvs = cf.kvs();
|
|
39
|
+
const header = await kvs.get('belt:routes');
|
|
40
|
+
const count = parseInt(header, 10);
|
|
41
|
+
const reads = [];
|
|
42
|
+
for (let i = 0; i < count; i++) reads.push(kvs.get('belt:routes:' + i));
|
|
43
|
+
const chunks = await Promise.all(reads);
|
|
44
|
+
return JSON.parse(chunks.join(''));
|
|
45
|
+
} catch (error) {
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function hasExtension(uri) {
|
|
51
|
+
return uri.substring(uri.lastIndexOf('/') + 1).indexOf('.') !== -1;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// Where a request goes: null to leave it alone, or the object to serve.
|
|
55
|
+
async function resolve(uri) {
|
|
56
|
+
if (hasExtension(uri)) return null;
|
|
57
|
+
const path = uri.replace(/\/+$/, '');
|
|
58
|
+
const routes = await loadRoutes();
|
|
59
|
+
if (!routes) return null;
|
|
60
|
+
|
|
61
|
+
const objects = routes.objects || {};
|
|
62
|
+
if (path === '') return objects['/'] || null;
|
|
63
|
+
if (routes.pages.indexOf(path) !== -1) return objects[path] || path;
|
|
64
|
+
for (let i = 0; i < routes.app.length; i++) {
|
|
65
|
+
if (matches(routes.app[i], path)) return '/index.html';
|
|
66
|
+
}
|
|
67
|
+
return NOT_FOUND;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function matches(pattern, path) {
|
|
71
|
+
const want = pattern.split('/');
|
|
72
|
+
const have = path.split('/');
|
|
73
|
+
for (let i = 0; i < want.length; i++) {
|
|
74
|
+
if (want[i] === '**') return true;
|
|
75
|
+
if (i >= have.length) return false;
|
|
76
|
+
if (want[i] !== '*' && want[i] !== have[i]) return false;
|
|
77
|
+
}
|
|
78
|
+
return want.length === have.length;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// An error thrown from a CloudFront Function is a 503 for the visitor, so
|
|
82
|
+
// anything unexpected leaves the request or response as it came.
|
|
83
|
+
async function handler(event) {
|
|
84
|
+
const request = event.request;
|
|
85
|
+
|
|
86
|
+
if (event.context.eventType === 'viewer-request') {
|
|
87
|
+
try {
|
|
88
|
+
const target = await resolve(request.uri);
|
|
89
|
+
if (target) request.uri = target;
|
|
90
|
+
} catch (error) {
|
|
91
|
+
console.log('belt router: ' + error);
|
|
92
|
+
}
|
|
93
|
+
return request;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// viewer-response. The request here may carry the original address or the one
|
|
97
|
+
// the viewer-request run rewrote, so both are checked. Only a 200 is changed:
|
|
98
|
+
// a 304 revalidation of the 404 page has to stay a 304.
|
|
99
|
+
const response = event.response;
|
|
100
|
+
try {
|
|
101
|
+
if (response.statusCode !== 200) return response;
|
|
102
|
+
let target = request.uri;
|
|
103
|
+
if (target !== NOT_FOUND) target = await resolve(request.uri);
|
|
104
|
+
if (target === NOT_FOUND) {
|
|
105
|
+
response.statusCode = 404;
|
|
106
|
+
response.statusDescription = 'Not Found';
|
|
107
|
+
}
|
|
108
|
+
} catch (error) {
|
|
109
|
+
console.log('belt router: ' + error);
|
|
110
|
+
}
|
|
111
|
+
return response;
|
|
112
|
+
}
|
data/lib/belt/version.rb
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import { Routes, Route } from 'react-router-dom'
|
|
2
2
|
import Home from './pages/Home'
|
|
3
|
+
import NotFound from './pages/NotFound'
|
|
3
4
|
|
|
4
5
|
// The router lives in main.jsx (browser) and entry-server.jsx (prerender).
|
|
5
6
|
function App() {
|
|
6
7
|
return (
|
|
7
8
|
<Routes>
|
|
8
9
|
<Route path="/" element={<Home />} />
|
|
10
|
+
<Route path="*" element={<NotFound />} />
|
|
9
11
|
</Routes>
|
|
10
12
|
)
|
|
11
13
|
}
|
|
@@ -2,7 +2,8 @@ import { renderToString } from 'react-dom/server'
|
|
|
2
2
|
import { StaticRouter } from 'react-router-dom/server'
|
|
3
3
|
import App from './App'
|
|
4
4
|
|
|
5
|
-
// Build-time render used by
|
|
5
|
+
// Build-time render used by belt's SEO prerender (`belt deploy frontend`) — not
|
|
6
|
+
// shipped to the browser.
|
|
6
7
|
export function render(url) {
|
|
7
8
|
return renderToString(
|
|
8
9
|
<StaticRouter location={url}>
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { Link } from 'react-router-dom'
|
|
2
|
+
|
|
3
|
+
// Shown for any address the app has no route for. `belt deploy frontend`
|
|
4
|
+
// prerenders it to 404.html, which CloudFront serves with HTTP 404, so crawlers
|
|
5
|
+
// and agents can tell a missing page from a real one.
|
|
6
|
+
function NotFound() {
|
|
7
|
+
return (
|
|
8
|
+
<main style={{ maxWidth: '36rem', margin: '4rem auto', padding: '0 1.5rem', fontFamily: 'system-ui, sans-serif' }}>
|
|
9
|
+
<h1>Page not found</h1>
|
|
10
|
+
<p>There is no page at this address.</p>
|
|
11
|
+
<p>
|
|
12
|
+
<Link to="/">Back to the home page</Link>
|
|
13
|
+
</p>
|
|
14
|
+
</main>
|
|
15
|
+
)
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export default NotFound
|
|
@@ -1,15 +1,20 @@
|
|
|
1
1
|
// SEO/AEO config — what search engines and AI answer engines (Google, Bing,
|
|
2
2
|
// ChatGPT, Claude, Perplexity) see. Most of those crawlers don't run JavaScript,
|
|
3
|
-
// so `
|
|
3
|
+
// so `belt deploy frontend` prerenders every page listed here to real HTML.
|
|
4
4
|
//
|
|
5
5
|
// For each page the build writes static HTML with its own <title>, description,
|
|
6
6
|
// canonical URL, Open Graph tags and JSON-LD, plus robots.txt, sitemap.xml and
|
|
7
|
-
// llms.txt for the whole site
|
|
7
|
+
// llms.txt for the whole site. Preview locally with `belt frontend prerender`.
|
|
8
|
+
// A public/robots.txt replaces the generated one in indexable environments.
|
|
8
9
|
//
|
|
9
10
|
// Rules of thumb:
|
|
10
11
|
// - Every public route gets an entry in `pages` with a specific title and a
|
|
11
12
|
// one- or two-sentence description that says plainly what the page is.
|
|
12
13
|
// - Login-gated or app-only routes go in `privatePaths` (disallowed in robots.txt).
|
|
14
|
+
// - An address that is neither a page here nor a route of the app answers HTTP
|
|
15
|
+
// 404 with the app's "not found" page. The app's routes are read from its
|
|
16
|
+
// <Route path="/..."> declarations; a route declared any other way needs its
|
|
17
|
+
// prefix in `privatePaths` too, or a fresh load of it answers 404.
|
|
13
18
|
// - Only `indexableEnvironments` are indexable. Every other environment, and
|
|
14
19
|
// local builds, ship `Disallow: /` and <meta name="robots" content="noindex">
|
|
15
20
|
// so dev and ephemeral environments never end up in search results.
|
|
@@ -79,9 +79,22 @@ resource "aws_cloudfront_distribution" "<%= @tf_name %>" {
|
|
|
79
79
|
forward = "none"
|
|
80
80
|
}
|
|
81
81
|
}
|
|
82
|
+
|
|
83
|
+
# Real 404s — see the router resources below.
|
|
84
|
+
function_association {
|
|
85
|
+
event_type = "viewer-request"
|
|
86
|
+
function_arn = aws_cloudfront_function.<%= @tf_name %>_route_request.arn
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function_association {
|
|
90
|
+
event_type = "viewer-response"
|
|
91
|
+
function_arn = aws_cloudfront_function.<%= @tf_name %>_route_response.arn
|
|
92
|
+
}
|
|
82
93
|
}
|
|
83
94
|
|
|
84
|
-
# SPA
|
|
95
|
+
# SPA fallback — serve index.html for a missing object. The router function
|
|
96
|
+
# sends unknown addresses to /404.html itself; this is what a path gets before
|
|
97
|
+
# routes have been published, and what a missing file (/assets/gone.js) gets.
|
|
85
98
|
custom_error_response {
|
|
86
99
|
error_code = 404
|
|
87
100
|
response_code = 200
|
|
@@ -114,6 +127,35 @@ resource "aws_cloudfront_distribution" "<%= @tf_name %>" {
|
|
|
114
127
|
}
|
|
115
128
|
}
|
|
116
129
|
|
|
130
|
+
# Real 404s. `belt deploy frontend` publishes the app's routes (frontend
|
|
131
|
+
# src/seo.js: `pages` and `privatePaths`) to this KeyValueStore, and the router
|
|
132
|
+
# function serves a page from its prerendered object, an app route from
|
|
133
|
+
# index.html, and anything else from /404.html with status 404. The same code
|
|
134
|
+
# runs on both events; <%= Belt::CLI::FrontendRoutes::ROUTER_FILE %> is belt's (refresh it with
|
|
135
|
+
# `belt frontend router`).
|
|
136
|
+
resource "aws_cloudfront_key_value_store" "<%= @tf_name %>_routes" {
|
|
137
|
+
name = "${var.app_name}-${var.environment}-<%= @bucket_slug %>-routes"
|
|
138
|
+
comment = "Routes published by belt deploy frontend"
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
resource "aws_cloudfront_function" "<%= @tf_name %>_route_request" {
|
|
142
|
+
name = "${var.app_name}-${var.environment}-<%= @bucket_slug %>-route-req"
|
|
143
|
+
runtime = "cloudfront-js-2.0"
|
|
144
|
+
comment = "Send each address to its page, the app, or the 404 page"
|
|
145
|
+
publish = true
|
|
146
|
+
key_value_store_associations = [aws_cloudfront_key_value_store.<%= @tf_name %>_routes.arn]
|
|
147
|
+
code = file("${path.module}/<%= Belt::CLI::FrontendRoutes::ROUTER_FILE %>")
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
resource "aws_cloudfront_function" "<%= @tf_name %>_route_response" {
|
|
151
|
+
name = "${var.app_name}-${var.environment}-<%= @bucket_slug %>-route-res"
|
|
152
|
+
runtime = "cloudfront-js-2.0"
|
|
153
|
+
comment = "Answer 404 for the 404 page"
|
|
154
|
+
publish = true
|
|
155
|
+
key_value_store_associations = [aws_cloudfront_key_value_store.<%= @tf_name %>_routes.arn]
|
|
156
|
+
code = file("${path.module}/<%= Belt::CLI::FrontendRoutes::ROUTER_FILE %>")
|
|
157
|
+
}
|
|
158
|
+
|
|
117
159
|
# S3 bucket policy — CloudFront OAC access only
|
|
118
160
|
resource "aws_s3_bucket_policy" "<%= @tf_name %>" {
|
|
119
161
|
bucket = aws_s3_bucket.<%= @tf_name %>.id
|
|
@@ -272,12 +272,17 @@ answer engines (`belt explain frontend`). When you add or change a public page:
|
|
|
272
272
|
- Add it to `frontend/src/seo.js` → `pages` with a specific `title` and a one- or
|
|
273
273
|
two-sentence `description` that names what the page is and who it's for.
|
|
274
274
|
- Put login-gated routes in `privatePaths` (they're disallowed in `robots.txt`).
|
|
275
|
+
- An address that is neither a page nor a route of the app answers HTTP 404. Belt
|
|
276
|
+
reads the app's routes from `<Route path="/...">` in `frontend/src`, so a normal
|
|
277
|
+
new route needs nothing. A route declared another way (nested relative path,
|
|
278
|
+
router config object) needs its prefix in `privatePaths`, or a fresh load of it
|
|
279
|
+
answers 404; `frontend/dist/.belt-routes.json` shows what belt found.
|
|
275
280
|
- Keep the page's content in the rendered markup — no `window`/`document`/
|
|
276
281
|
`localStorage` during render (use `useEffect`), and no content that only appears
|
|
277
282
|
after an API call if crawlers need to see it.
|
|
278
283
|
- Use one `<h1>` per page and real links (`<Link>`/`<a href>`), not click handlers.
|
|
279
|
-
-
|
|
280
|
-
`dist/<page>.html`
|
|
284
|
+
- Run `belt frontend prerender`: expect `SEO: prerendered N page(s)` with no
|
|
285
|
+
warnings, and `frontend/dist/<page>.html` containing the content.
|
|
281
286
|
|
|
282
287
|
Only `prod` is indexable; other environments ship `noindex`.
|
|
283
288
|
|
metadata
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
|
2
2
|
name: belt
|
|
3
3
|
version: !ruby/object:Gem::Version
|
|
4
|
-
version: 0.6.
|
|
4
|
+
version: 0.6.11
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- Stowzilla
|
|
@@ -137,7 +137,9 @@ files:
|
|
|
137
137
|
- lib/belt/cli/frontend_deploy_command.rb
|
|
138
138
|
- lib/belt/cli/frontend_env_command.rb
|
|
139
139
|
- lib/belt/cli/frontend_env_map.rb
|
|
140
|
+
- lib/belt/cli/frontend_prerender.rb
|
|
140
141
|
- lib/belt/cli/frontend_registry.rb
|
|
142
|
+
- lib/belt/cli/frontend_routes.rb
|
|
141
143
|
- lib/belt/cli/frontend_setup_command.rb
|
|
142
144
|
- lib/belt/cli/generate_command.rb
|
|
143
145
|
- lib/belt/cli/generator_registry.rb
|
|
@@ -179,6 +181,8 @@ files:
|
|
|
179
181
|
- lib/belt/docs/structure.md
|
|
180
182
|
- lib/belt/docs/testing.md
|
|
181
183
|
- lib/belt/errors.rb
|
|
184
|
+
- lib/belt/frontend/prerender.mjs
|
|
185
|
+
- lib/belt/frontend/router.js
|
|
182
186
|
- lib/belt/helpers/cors_origin.rb
|
|
183
187
|
- lib/belt/helpers/error_logging.rb
|
|
184
188
|
- lib/belt/helpers/response.rb
|
|
@@ -214,13 +218,13 @@ files:
|
|
|
214
218
|
- lib/templates/frontend/react/env.yml.example
|
|
215
219
|
- lib/templates/frontend/react/index.html.erb
|
|
216
220
|
- lib/templates/frontend/react/package.json.erb
|
|
217
|
-
- lib/templates/frontend/react/scripts/prerender.js
|
|
218
221
|
- lib/templates/frontend/react/src/App.jsx
|
|
219
222
|
- lib/templates/frontend/react/src/entry-server.jsx
|
|
220
223
|
- lib/templates/frontend/react/src/index.css
|
|
221
224
|
- lib/templates/frontend/react/src/lib/apiClient.js.erb
|
|
222
225
|
- lib/templates/frontend/react/src/main.jsx
|
|
223
226
|
- lib/templates/frontend/react/src/pages/Home.jsx.erb
|
|
227
|
+
- lib/templates/frontend/react/src/pages/NotFound.jsx
|
|
224
228
|
- lib/templates/frontend/react/src/seo.js.erb
|
|
225
229
|
- lib/templates/frontend/react/vite.config.js
|
|
226
230
|
- lib/templates/frontend_infra/frontend.tf.erb
|