@prunellejs/seo 0.0.0-stage → 0.5.1
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/llms.txt +57 -0
- package/package.json +24 -4
- package/src/check.ts +581 -0
- package/src/index.ts +479 -0
- package/README.md +0 -3
package/llms.txt
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
# @prunellejs/seo Reference
|
|
2
|
+
|
|
3
|
+
> SEO `<head>` tags, `titleTemplate`, localized descriptions, canonical URLs, JSON-LD, `sitemap.xml` (i18n-aware), redirects, web manifest, favicons, and self-hosted fonts.
|
|
4
|
+
|
|
5
|
+
## Imports
|
|
6
|
+
|
|
7
|
+
- `@prunellejs/seo`: `seo`, `jsonLd`; types `SeoPluginOptions`, `FontEntry`, `ManifestOptions`, `RedirectTarget`.
|
|
8
|
+
|
|
9
|
+
## Plugin Setup (`seo(options?)`)
|
|
10
|
+
|
|
11
|
+
- `site`: public origin (`https://example.com`, inherits `PrunelleConfig.site`). Required for canonical links, absolute `og:image`, and `sitemap.xml`; a production start refuses without it.
|
|
12
|
+
- `name`: site name (`og:site_name` and fallback `<title>`).
|
|
13
|
+
- `titleTemplate`: e.g. `'%s | My App'` (skips wrapping if `<title>` already contains `name`).
|
|
14
|
+
- `description`: `string` or `Record<locale, string>` (localized fallback when a page doesn't emit `<meta name="description">`; reads `ctx.locals.locale` from `@prunellejs/i18n`).
|
|
15
|
+
- `image`, `imageAlt`: default `og:image`, `twitter:card` (`summary_large_image`), and `og:image:alt`.
|
|
16
|
+
- `locale`: default `og:locale`.
|
|
17
|
+
- `jsonLd`: array of Schema.org objects injected globally (`@context: 'https://schema.org'` auto-added).
|
|
18
|
+
- `sitemap`: `boolean` (default `true`, emitted in `afterPrerender` as `/sitemap.xml` with `xhtml:link` alternates when `@prunellejs/i18n` is active). `sitemapExclude`: `string[]`. `extraUrls`: `() => string[]`.
|
|
19
|
+
- `redirects`: `Record<fromPath, string | { to: string, status?: 301 | 302 | 307 | 308 }>` (mounted as `GET` routes, default `301`).
|
|
20
|
+
- `favicon`: `string | string[]` (relative path or package specifier; emits `favicon.{svg,png,ico}` and `<link rel="icon">`; a path that resolves to no file fails the build). `image` is prefixed with `site` unless it starts with `http://`, `https://` or `//`.
|
|
21
|
+
- `manifest`: `{ name?, shortName?, description?, themeColor?, backgroundColor?, display?, startUrl? }` (emits `/manifest.webmanifest`).
|
|
22
|
+
- `fonts`: `Array<{ family, src, weight?, style?, display?, preload? }>` (resolves local paths or `@fontsource/*` specifiers, emits content-hashed assets + `@font-face` stylesheet + `<link rel="preload">`).
|
|
23
|
+
|
|
24
|
+
## Page-Specific JSON-LD
|
|
25
|
+
|
|
26
|
+
- `jsonLd(schema)` returns a branded `Html` value for `<Head>`: `<Head>{jsonLd({ '@type': 'Article', headline: title })}</Head>`.
|
|
27
|
+
|
|
28
|
+
## Validation (`prunelle check`)
|
|
29
|
+
|
|
30
|
+
- Warns with `[seo/missing-site]` when neither `prunelle.config.ts` `site` nor `seo({ site })` is set.
|
|
31
|
+
- Warns with `[seo/missing-title]` and `[seo/missing-description]` on page routes without `<title>` or `<meta name="description">` (respecting ancestor `_layout.tsx` and `seo({ description })`).
|
|
32
|
+
- Warns with `[seo/long-title]` (> 60 chars, including `titleTemplate`) and `[seo/long-description]` (> 160 chars) on static routes, `seo()` defaults, and prerendered HTML.
|
|
33
|
+
- Warns with `[seo/duplicate-title]` and `[seo/duplicate-description]` when two static routes or prerendered pages share the same title or description.
|
|
34
|
+
- Warns with `[seo/noindex-in-sitemap]` when a route or prerendered page sets `noindex` while still included in `sitemap.xml` (not in `sitemapExclude` and `sitemap !== false`).
|
|
35
|
+
- Warns with `[seo/missing-image]` when `site` is configured and a page has neither `seo({ image })` nor `<meta property="og:image">`.
|
|
36
|
+
|
|
37
|
+
## Snippet
|
|
38
|
+
|
|
39
|
+
```ts
|
|
40
|
+
// prunelle.config.ts
|
|
41
|
+
import { defineConfig } from 'prunelle/config'
|
|
42
|
+
import { seo } from '@prunellejs/seo'
|
|
43
|
+
|
|
44
|
+
export default defineConfig({
|
|
45
|
+
site: 'https://example.com',
|
|
46
|
+
plugins: [
|
|
47
|
+
seo({
|
|
48
|
+
name: 'Acme',
|
|
49
|
+
titleTemplate: '%s | Acme',
|
|
50
|
+
description: 'Fast web apps with Prunelle.',
|
|
51
|
+
favicon: 'public/favicon.svg',
|
|
52
|
+
fonts: [{ family: 'Inter', src: '@fontsource/inter/files/inter-latin-400-normal.woff2', weight: 400 }],
|
|
53
|
+
redirects: { '/old': '/new' },
|
|
54
|
+
}),
|
|
55
|
+
],
|
|
56
|
+
})
|
|
57
|
+
```
|
package/package.json
CHANGED
|
@@ -1,6 +1,26 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prunellejs/seo",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.5.1",
|
|
4
|
+
"description": "SEO meta, JSON-LD, sitemap, redirects, and self-hosted fonts plugin for Prunelle",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"sideEffects": false,
|
|
8
|
+
"files": [
|
|
9
|
+
"src",
|
|
10
|
+
"llms.txt"
|
|
11
|
+
],
|
|
12
|
+
"exports": {
|
|
13
|
+
".": "./src/index.ts"
|
|
14
|
+
},
|
|
15
|
+
"engines": {
|
|
16
|
+
"bun": ">=1.4.0"
|
|
17
|
+
},
|
|
18
|
+
"repository": {
|
|
19
|
+
"type": "git",
|
|
20
|
+
"url": "https://github.com/Kayno0o/prunelle",
|
|
21
|
+
"directory": "packages/plugin-seo"
|
|
22
|
+
},
|
|
23
|
+
"peerDependencies": {
|
|
24
|
+
"prunelle": "^0.5.1"
|
|
25
|
+
}
|
|
26
|
+
}
|
package/src/check.ts
ADDED
|
@@ -0,0 +1,581 @@
|
|
|
1
|
+
// Static & prerendered SEO diagnostics for `@prunellejs/seo`'s `prunelle check` hook.
|
|
2
|
+
|
|
3
|
+
import type { CheckPluginContext } from 'prunelle/config'
|
|
4
|
+
import type { SeoPluginOptions } from './index'
|
|
5
|
+
import { existsSync, readdirSync, readFileSync } from 'node:fs'
|
|
6
|
+
import { basename, dirname, join, relative } from 'node:path'
|
|
7
|
+
import { getAppContext } from 'prunelle/internal/server'
|
|
8
|
+
|
|
9
|
+
const MAX_TITLE = 60
|
|
10
|
+
const MAX_DESC = 160
|
|
11
|
+
const TS_EXT_RE = /\.(?:tsx|ts)$/
|
|
12
|
+
const TEST_FILE_RE = /\.(?:test|spec)\.(?:tsx|ts)$/
|
|
13
|
+
const HEAD_BLOCK_RE = /<Head(?:\s(?:[^>"']|"[^"]*"|'[^']*')*)?(?<!\/)>([\s\S]*?)<\/Head>/g
|
|
14
|
+
const TITLE_TAG_RE = /<title(?:\s[^>]*)?>([\s\S]*?)<\/title>/g
|
|
15
|
+
const HTML_HEAD_RE = /<head\b[^>]*>([\s\S]*?)<\/head>/i
|
|
16
|
+
const HTML_TITLE_RE = /<title\b[^>]*>([\s\S]*?)<\/title>/i
|
|
17
|
+
const HTML_META_RE = /<meta\b[^>]*>/gi
|
|
18
|
+
const HTML_ATTR_RE = /([a-zA-Z_:][a-zA-Z0-9_.:-]*)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+))/g
|
|
19
|
+
const NOINDEX_RE = /\bnoindex\b/i
|
|
20
|
+
const PRERENDER_TRUE_RE = /\bexport\s+(?:const|let|var)\s+prerender\s*=\s*true\b/
|
|
21
|
+
const ENTITY_RE = /&(?:#(\d+)|#x([0-9a-fA-F]+)|([a-zA-Z]+));/g
|
|
22
|
+
const SKIP_PRERENDER_DIRS = new Set(['_pru', 'client', 'server', 'public', 'node_modules'])
|
|
23
|
+
const CONFIG_FILES = ['prunelle.config.ts', 'prunelle.config.js', 'prunelle.config.mjs']
|
|
24
|
+
const NAMED_ENTITIES: Record<string, string> = {
|
|
25
|
+
amp: '&', lt: '<', gt: '>', quot: '"', apos: '\'', nbsp: '\u00A0', ndash: '\u2013',
|
|
26
|
+
mdash: '\u2014', hellip: '\u2026', laquo: '\u00AB', raquo: '\u00BB', copy: '\u00A9', reg: '\u00AE', trade: '\u2122',
|
|
27
|
+
}
|
|
28
|
+
const TS_SCANNER = new Bun.Transpiler({ loader: 'ts' })
|
|
29
|
+
const TSX_SCANNER = new Bun.Transpiler({ loader: 'tsx' })
|
|
30
|
+
|
|
31
|
+
interface TextEntry { value: string | undefined, offset: number }
|
|
32
|
+
interface RouteHeadInfo {
|
|
33
|
+
titles: TextEntry[]
|
|
34
|
+
emptyTitleOffset?: number | undefined
|
|
35
|
+
descriptions: TextEntry[]
|
|
36
|
+
emptyDescriptionOffset?: number | undefined
|
|
37
|
+
hasOgImage: boolean
|
|
38
|
+
noindexOffset?: number | undefined
|
|
39
|
+
}
|
|
40
|
+
interface OwnedEntry { value: string | undefined, file: string, code: string, offset: number, fromLayout: boolean }
|
|
41
|
+
interface StaticState {
|
|
42
|
+
longTitleUrls: Set<string>
|
|
43
|
+
longDescUrls: Set<string>
|
|
44
|
+
noindexUrls: Set<string>
|
|
45
|
+
dupTitles: Set<string>
|
|
46
|
+
dupDescs: Set<string>
|
|
47
|
+
warnedLayouts: Set<string>
|
|
48
|
+
seenTitles: Map<string, { relFile: string, routePath: string }>
|
|
49
|
+
seenDescs: Map<string, { relFile: string, routePath: string }>
|
|
50
|
+
}
|
|
51
|
+
interface ParsedAttr { staticValue?: string | undefined, isDynamic: boolean }
|
|
52
|
+
|
|
53
|
+
const relPosix = (root: string, file: string): string => relative(root, file).replaceAll('\\', '/')
|
|
54
|
+
|
|
55
|
+
function normalizePath(p: string): string {
|
|
56
|
+
const s = p.startsWith('/') ? p : `/${p}`
|
|
57
|
+
return s.length > 1 ? s.replace(/\/+$/, '') || '/' : s
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function isSkippedPath(p: string): boolean {
|
|
61
|
+
const n = normalizePath(p)
|
|
62
|
+
return n === '/api' || n.startsWith('/api/') || n === '/404' || n === '/500' || n === '/__pru_404__'
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function fileToRoutePath(routesDir: string, file: string): string {
|
|
66
|
+
const rel = relPosix(routesDir, file).replace(TS_EXT_RE, '')
|
|
67
|
+
if (rel === 'index') return '/'
|
|
68
|
+
const clean = rel.endsWith('/index') ? rel.slice(0, -6) : rel
|
|
69
|
+
return `/${clean.replace(/\[\.\.\.([^\]]+)\]/g, '*$1').replace(/\[([^\]]+)\]/g, ':$1')}`
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function formatWarn(relFile: string, code: string | undefined, offset: number, rule: string, detail: string, fix: string): string {
|
|
73
|
+
let line = 1
|
|
74
|
+
let col = 1
|
|
75
|
+
if (code !== undefined) {
|
|
76
|
+
for (let i = 0, end = Math.min(Math.max(0, offset), code.length); i < end; i++) {
|
|
77
|
+
if (code.charCodeAt(i) === 10) { line++; col = 1 }
|
|
78
|
+
else { col++ }
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return `${relFile}:${line}:${col}: warning: [seo/${rule}] ${detail}: ${fix}.`
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function decodeEntities(str: string): string {
|
|
85
|
+
if (!str.includes('&')) return str
|
|
86
|
+
return str.replace(ENTITY_RE, (m, dec?: string, hex?: string, named?: string) => {
|
|
87
|
+
const cp = dec !== undefined ? Number.parseInt(dec, 10) : hex !== undefined ? Number.parseInt(hex, 16) : -1
|
|
88
|
+
if (cp > 0 && cp <= 0x10FFFF) return String.fromCodePoint(cp)
|
|
89
|
+
return named !== undefined && Object.hasOwn(NAMED_ENTITIES, named) ? NAMED_ENTITIES[named]! : m
|
|
90
|
+
})
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function skipQuoted(src: string, start: number): number {
|
|
94
|
+
const q = src[start]!
|
|
95
|
+
for (let i = start + 1; i < src.length; i++) {
|
|
96
|
+
if (src[i] === '\\') i++
|
|
97
|
+
else if (src[i] === q) return i
|
|
98
|
+
}
|
|
99
|
+
return src.length - 1
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function stripCommentsPreserveOffsets(code: string): string {
|
|
103
|
+
const chars = code.split('')
|
|
104
|
+
let i = 0
|
|
105
|
+
let quote = ''
|
|
106
|
+
let braceDepth = 0
|
|
107
|
+
const tplDepths: number[] = []
|
|
108
|
+
while (i < chars.length) {
|
|
109
|
+
const ch = chars[i]!
|
|
110
|
+
const next = chars[i + 1]
|
|
111
|
+
if (quote !== '') {
|
|
112
|
+
if (ch === '\\') { i += 2; continue }
|
|
113
|
+
if (quote === '`' && ch === '$' && next === '{') { tplDepths.push(braceDepth++); quote = ''; i += 2; continue }
|
|
114
|
+
if (ch === quote) quote = ''
|
|
115
|
+
i++
|
|
116
|
+
continue
|
|
117
|
+
}
|
|
118
|
+
if (ch === '/' && next === '/') {
|
|
119
|
+
while (i < chars.length && chars[i] !== '\n' && chars[i] !== '\r') chars[i++] = ' '
|
|
120
|
+
continue
|
|
121
|
+
}
|
|
122
|
+
if (ch === '/' && next === '*') {
|
|
123
|
+
chars[i++] = ' '; chars[i++] = ' '
|
|
124
|
+
while (i < chars.length && !(chars[i] === '*' && chars[i + 1] === '/')) {
|
|
125
|
+
if (chars[i] !== '\n' && chars[i] !== '\r') chars[i] = ' '
|
|
126
|
+
i++
|
|
127
|
+
}
|
|
128
|
+
if (i + 1 < chars.length) { chars[i++] = ' '; chars[i++] = ' ' }
|
|
129
|
+
continue
|
|
130
|
+
}
|
|
131
|
+
if (ch === '\'' || ch === '"' || ch === '`') quote = ch
|
|
132
|
+
else if (ch === '{') braceDepth++
|
|
133
|
+
else if (ch === '}' && tplDepths[tplDepths.length - 1] === --braceDepth) { tplDepths.pop(); quote = '`' }
|
|
134
|
+
i++
|
|
135
|
+
}
|
|
136
|
+
return chars.join('')
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function unquoteStringLiteral(expr: string): string | undefined {
|
|
140
|
+
const t = expr.trim()
|
|
141
|
+
const q = t[0]
|
|
142
|
+
if (t.length < 2 || t[t.length - 1] !== q) return undefined
|
|
143
|
+
const body = t.slice(1, -1)
|
|
144
|
+
if (q === '`') return /(?<!\\)\$\{|(?<!\\)`/.test(body) ? undefined : body.replace(/\\(.)/g, '$1')
|
|
145
|
+
if (q !== '"' && q !== '\'') return undefined
|
|
146
|
+
if (new RegExp(`(?<!\\\\)${q}`).test(body)) return undefined
|
|
147
|
+
return body.replace(/\\([nrt"'\\])/g, (_, e: string) => (e === 'n' ? '\n' : e === 't' ? '\t' : e === 'r' ? '\r' : e))
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function readBalancedBrace(src: string, openIndex: number): number {
|
|
151
|
+
let depth = 1
|
|
152
|
+
for (let i = openIndex + 1; i < src.length; i++) {
|
|
153
|
+
const ch = src[i]!
|
|
154
|
+
if (ch === '\'' || ch === '"' || ch === '`') i = skipQuoted(src, i)
|
|
155
|
+
else if (ch === '{') depth++
|
|
156
|
+
else if (ch === '}' && --depth === 0) return i
|
|
157
|
+
}
|
|
158
|
+
return -1
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function analyzeTitleChildren(raw: string): { kind: 'empty' } | { kind: 'static', value: string } | { kind: 'dynamic' } {
|
|
162
|
+
let out = ''
|
|
163
|
+
let i = 0
|
|
164
|
+
while (i < raw.length) {
|
|
165
|
+
const open = raw.indexOf('{', i)
|
|
166
|
+
if (open === -1) { out += decodeEntities(raw.slice(i)); break }
|
|
167
|
+
out += decodeEntities(raw.slice(i, open))
|
|
168
|
+
const close = readBalancedBrace(raw, open)
|
|
169
|
+
if (close === -1) return { kind: 'dynamic' }
|
|
170
|
+
const expr = raw.slice(open + 1, close).trim()
|
|
171
|
+
if (expr !== '' && expr !== 'null' && expr !== 'undefined' && expr !== 'false') {
|
|
172
|
+
const lit = unquoteStringLiteral(expr)
|
|
173
|
+
if (lit === undefined) return { kind: 'dynamic' }
|
|
174
|
+
out += lit
|
|
175
|
+
}
|
|
176
|
+
i = close + 1
|
|
177
|
+
}
|
|
178
|
+
const normalized = out.replace(/\s+/g, ' ').trim()
|
|
179
|
+
return normalized.length === 0 ? { kind: 'empty' } : { kind: 'static', value: normalized }
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function scanMetaTags(headBody: string, bodyOffset: number): Array<{ attrs: string, offset: number }> {
|
|
183
|
+
const tags: Array<{ attrs: string, offset: number }> = []
|
|
184
|
+
let i = 0
|
|
185
|
+
while (i < headBody.length) {
|
|
186
|
+
const start = headBody.indexOf('<meta', i)
|
|
187
|
+
if (start === -1) break
|
|
188
|
+
const after = headBody[start + 5]
|
|
189
|
+
if (after !== undefined && !/[\s/>]/.test(after)) { i = start + 5; continue }
|
|
190
|
+
let j = start + 5
|
|
191
|
+
let depth = 0
|
|
192
|
+
while (j < headBody.length) {
|
|
193
|
+
const ch = headBody[j]!
|
|
194
|
+
if (ch === '\'' || ch === '"' || ch === '`') j = skipQuoted(headBody, j)
|
|
195
|
+
else if (ch === '{') depth++
|
|
196
|
+
else if (ch === '}' && depth > 0) depth--
|
|
197
|
+
else if (ch === '>' && depth === 0) break
|
|
198
|
+
j++
|
|
199
|
+
}
|
|
200
|
+
if (j >= headBody.length) break
|
|
201
|
+
tags.push({ attrs: headBody.slice(start + 5, j).replace(/\/\s*$/, ''), offset: bodyOffset + start })
|
|
202
|
+
i = j + 1
|
|
203
|
+
}
|
|
204
|
+
return tags
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function parseJsxAttrs(src: string): { attrs: Map<string, ParsedAttr>, hasSpread: boolean } {
|
|
208
|
+
const attrs = new Map<string, ParsedAttr>()
|
|
209
|
+
let hasSpread = false
|
|
210
|
+
let i = 0
|
|
211
|
+
while (i < src.length) {
|
|
212
|
+
while (i < src.length && /\s/.test(src[i]!)) i++
|
|
213
|
+
if (i >= src.length) break
|
|
214
|
+
if (src[i] === '{') {
|
|
215
|
+
const close = readBalancedBrace(src, i)
|
|
216
|
+
if (close === -1) break
|
|
217
|
+
if (src.slice(i + 1, close).trim().startsWith('...')) hasSpread = true
|
|
218
|
+
i = close + 1
|
|
219
|
+
continue
|
|
220
|
+
}
|
|
221
|
+
const start = i
|
|
222
|
+
while (i < src.length && /[a-zA-Z0-9_:-]/.test(src[i]!)) i++
|
|
223
|
+
const name = src.slice(start, i).toLowerCase()
|
|
224
|
+
if (name === '') { i++; continue }
|
|
225
|
+
while (i < src.length && /\s/.test(src[i]!)) i++
|
|
226
|
+
if (src[i] !== '=') { attrs.set(name, { staticValue: '', isDynamic: false }); continue }
|
|
227
|
+
i++
|
|
228
|
+
while (i < src.length && /\s/.test(src[i]!)) i++
|
|
229
|
+
const ch = src[i]
|
|
230
|
+
if (ch === '"' || ch === '\'') {
|
|
231
|
+
const end = skipQuoted(src, i)
|
|
232
|
+
attrs.set(name, { staticValue: decodeEntities(src.slice(i + 1, end)), isDynamic: false })
|
|
233
|
+
i = end + 1
|
|
234
|
+
}
|
|
235
|
+
else if (ch === '{') {
|
|
236
|
+
const close = readBalancedBrace(src, i)
|
|
237
|
+
if (close === -1) break
|
|
238
|
+
const expr = src.slice(i + 1, close).trim()
|
|
239
|
+
const lit = unquoteStringLiteral(expr)
|
|
240
|
+
if (lit !== undefined) attrs.set(name, { staticValue: lit, isDynamic: false })
|
|
241
|
+
else if (expr === '' || expr === 'undefined' || expr === 'null' || expr === 'false') attrs.set(name, { staticValue: '', isDynamic: false })
|
|
242
|
+
else attrs.set(name, { isDynamic: true })
|
|
243
|
+
i = close + 1
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
return { attrs, hasSpread }
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
function extractRouteHead(stripped: string): RouteHeadInfo {
|
|
250
|
+
const info: RouteHeadInfo = { titles: [], descriptions: [], hasOgImage: false }
|
|
251
|
+
HEAD_BLOCK_RE.lastIndex = 0
|
|
252
|
+
for (let hm = HEAD_BLOCK_RE.exec(stripped); hm !== null; hm = HEAD_BLOCK_RE.exec(stripped)) {
|
|
253
|
+
const body = hm[1]!
|
|
254
|
+
const bodyOffset = hm.index + hm[0].indexOf('>') + 1
|
|
255
|
+
TITLE_TAG_RE.lastIndex = 0
|
|
256
|
+
for (let tm = TITLE_TAG_RE.exec(body); tm !== null; tm = TITLE_TAG_RE.exec(body)) {
|
|
257
|
+
const res = analyzeTitleChildren(tm[1]!)
|
|
258
|
+
if (res.kind === 'empty') info.emptyTitleOffset ??= bodyOffset + tm.index
|
|
259
|
+
else info.titles.push({ value: res.kind === 'static' ? res.value : undefined, offset: bodyOffset + tm.index })
|
|
260
|
+
}
|
|
261
|
+
for (const meta of scanMetaTags(body, bodyOffset)) {
|
|
262
|
+
const { attrs, hasSpread } = parseJsxAttrs(meta.attrs)
|
|
263
|
+
const nameVal = attrs.get('name')?.staticValue?.trim().toLowerCase()
|
|
264
|
+
const propVal = attrs.get('property')?.staticValue?.trim().toLowerCase()
|
|
265
|
+
const content = attrs.get('content')
|
|
266
|
+
const contentVal = content?.staticValue?.trim()
|
|
267
|
+
if (nameVal === 'description') {
|
|
268
|
+
if (content?.isDynamic || hasSpread) info.descriptions.push({ value: undefined, offset: meta.offset })
|
|
269
|
+
else if (contentVal) info.descriptions.push({ value: contentVal, offset: meta.offset })
|
|
270
|
+
else info.emptyDescriptionOffset ??= meta.offset
|
|
271
|
+
}
|
|
272
|
+
else if (nameVal === 'robots' && contentVal && NOINDEX_RE.test(contentVal)) {
|
|
273
|
+
info.noindexOffset ??= meta.offset
|
|
274
|
+
}
|
|
275
|
+
else if ((propVal === 'og:image' || nameVal === 'og:image') && (hasSpread || content?.isDynamic || Boolean(contentVal))) {
|
|
276
|
+
info.hasOgImage = true
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
return info
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
function hasTopLevelSiteInObject(stripped: string, braceStart: number): boolean {
|
|
284
|
+
let depth = 0
|
|
285
|
+
for (let i = braceStart; i < stripped.length; i++) {
|
|
286
|
+
const ch = stripped[i]!
|
|
287
|
+
if (ch === '\'' || ch === '"' || ch === '`') { i = skipQuoted(stripped, i); continue }
|
|
288
|
+
if (ch === '{') { depth++; continue }
|
|
289
|
+
if (ch === '}') { if (--depth === 0) return false; continue }
|
|
290
|
+
if (depth !== 1 || !stripped.startsWith('site', i)) continue
|
|
291
|
+
const prev = stripped[i - 1]
|
|
292
|
+
if (prev !== undefined && !/[\s,{]/.test(prev)) continue
|
|
293
|
+
const rest = stripped.slice(i + 4)
|
|
294
|
+
if (/^\s*[,}]/.test(rest)) return true
|
|
295
|
+
const m = /^\s*:\s*([^,\n}]+)/.exec(rest)
|
|
296
|
+
if (m !== null && !['undefined', 'null', '\'\'', '""', '``'].includes(m[1]!.trim())) return true
|
|
297
|
+
}
|
|
298
|
+
return false
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
function hasConfiguredSite(root: string, options: SeoPluginOptions, activeSite: string | undefined): boolean {
|
|
302
|
+
if (options.site?.trim() || activeSite?.trim() || getAppContext()?.site?.trim()) return true
|
|
303
|
+
for (const name of CONFIG_FILES) {
|
|
304
|
+
const full = join(root, name)
|
|
305
|
+
if (!existsSync(full)) continue
|
|
306
|
+
const stripped = stripCommentsPreserveOffsets(readFileSync(full, 'utf8'))
|
|
307
|
+
const m = /defineConfig\s*\(\s*\{|export\s+default\s*\{/.exec(stripped)
|
|
308
|
+
if (m !== null && hasTopLevelSiteInObject(stripped, m.index + m[0].length - 1)) return true
|
|
309
|
+
}
|
|
310
|
+
return false
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
function applyTitleTemplate(title: string, options: SeoPluginOptions): string {
|
|
314
|
+
return options.titleTemplate && (!options.name || !title.includes(options.name))
|
|
315
|
+
? options.titleTemplate.replace('%s', () => title)
|
|
316
|
+
: title
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
function walkRouteFiles(dir: string): string[] {
|
|
320
|
+
const out: string[] = []
|
|
321
|
+
if (!existsSync(dir)) return out
|
|
322
|
+
const stack = [dir]
|
|
323
|
+
while (stack.length > 0) {
|
|
324
|
+
const cur = stack.pop()!
|
|
325
|
+
for (const e of readdirSync(cur, { withFileTypes: true })) {
|
|
326
|
+
if (e.isDirectory() && !e.name.startsWith('_') && !e.name.startsWith('.') && e.name !== 'node_modules' && e.name !== 'dist')
|
|
327
|
+
stack.push(join(cur, e.name))
|
|
328
|
+
else if (e.isFile() && TS_EXT_RE.test(e.name) && !e.name.endsWith('.d.ts') && !TEST_FILE_RE.test(e.name))
|
|
329
|
+
out.push(join(cur, e.name))
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
return out.sort()
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
function scanExports(file: string, code: string): string[] | undefined {
|
|
336
|
+
try { return (file.endsWith('.tsx') ? TSX_SCANNER : TS_SCANNER).scan(code).exports }
|
|
337
|
+
catch { return undefined }
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
function ancestorLayouts(routesDir: string, routeFile: string): string[] {
|
|
341
|
+
const result: string[] = []
|
|
342
|
+
const relDir = relative(routesDir, dirname(routeFile))
|
|
343
|
+
const parts = relDir === '' ? [] : relDir.split(/[/\\]/)
|
|
344
|
+
let cur = routesDir
|
|
345
|
+
for (let i = 0; i <= parts.length; i++) {
|
|
346
|
+
if (i > 0) cur = join(cur, parts[i - 1]!)
|
|
347
|
+
const candidate = join(cur, '_layout.tsx')
|
|
348
|
+
if (existsSync(candidate)) result.push(candidate)
|
|
349
|
+
}
|
|
350
|
+
return result
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
function checkConfigOptions(options: SeoPluginOptions, siteConfigured: boolean, warn: (m: string) => void): void {
|
|
354
|
+
if (!siteConfigured)
|
|
355
|
+
warn(formatWarn('prunelle.config.ts', undefined, 0, 'missing-site', 'no `site` is configured, so canonical links, absolute `og:image` URLs, and `sitemap.xml` are disabled', 'set `site` in `prunelle.config.ts` or pass `seo({ site })`'))
|
|
356
|
+
if (options.name !== undefined && options.name.trim().length > MAX_TITLE)
|
|
357
|
+
warn(formatWarn('prunelle.config.ts', undefined, 0, 'long-title', `default seo({ name }) is ${options.name.trim().length} characters (recommended max ${MAX_TITLE})`, `shorten \`name\` to ${MAX_TITLE} characters or fewer`))
|
|
358
|
+
if (typeof options.description === 'string') {
|
|
359
|
+
const len = options.description.trim().length
|
|
360
|
+
if (len > MAX_DESC)
|
|
361
|
+
warn(formatWarn('prunelle.config.ts', undefined, 0, 'long-description', `default seo({ description }) is ${len} characters (recommended max ${MAX_DESC})`, `shorten \`description\` to ${MAX_DESC} characters or fewer`))
|
|
362
|
+
}
|
|
363
|
+
else if (options.description !== undefined) {
|
|
364
|
+
for (const [locale, text] of Object.entries(options.description).sort(([a], [b]) => a.localeCompare(b))) {
|
|
365
|
+
const len = text.trim().length
|
|
366
|
+
if (len > MAX_DESC)
|
|
367
|
+
warn(formatWarn('prunelle.config.ts', undefined, 0, 'long-description', `seo({ description }) for locale "${locale}" is ${len} characters (recommended max ${MAX_DESC})`, `shorten it to ${MAX_DESC} characters or fewer`))
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
function lastOwned(entries: readonly TextEntry[], file: string, code: string, fromLayout: boolean): OwnedEntry | undefined {
|
|
373
|
+
const last = entries[entries.length - 1]
|
|
374
|
+
return last === undefined ? undefined : { value: last.value, file, code, offset: last.offset, fromLayout }
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
function resolveEffectiveHead(
|
|
378
|
+
file: string,
|
|
379
|
+
code: string,
|
|
380
|
+
pageInfo: RouteHeadInfo,
|
|
381
|
+
layouts: readonly string[],
|
|
382
|
+
cache: Map<string, { code: string, info: RouteHeadInfo }>,
|
|
383
|
+
): { title: OwnedEntry | undefined, description: OwnedEntry | undefined, hasOgImage: boolean, noindex: { file: string, offset: number } | undefined } {
|
|
384
|
+
let title: OwnedEntry | undefined
|
|
385
|
+
let description: OwnedEntry | undefined
|
|
386
|
+
let hasOgImage = pageInfo.hasOgImage
|
|
387
|
+
let noindex: { file: string, offset: number } | undefined
|
|
388
|
+
|
|
389
|
+
for (const lf of layouts) {
|
|
390
|
+
let c = cache.get(lf)
|
|
391
|
+
if (c === undefined) {
|
|
392
|
+
const lCode = readFileSync(lf, 'utf8')
|
|
393
|
+
c = { code: lCode, info: extractRouteHead(stripCommentsPreserveOffsets(lCode)) }
|
|
394
|
+
cache.set(lf, c)
|
|
395
|
+
}
|
|
396
|
+
title = lastOwned(c.info.titles, lf, c.code, true) ?? title
|
|
397
|
+
description = lastOwned(c.info.descriptions, lf, c.code, true) ?? description
|
|
398
|
+
if (c.info.hasOgImage) hasOgImage = true
|
|
399
|
+
if (c.info.noindexOffset !== undefined) noindex = { file: lf, offset: c.info.noindexOffset }
|
|
400
|
+
}
|
|
401
|
+
title = lastOwned(pageInfo.titles, file, code, false) ?? title
|
|
402
|
+
description = lastOwned(pageInfo.descriptions, file, code, false) ?? description
|
|
403
|
+
if (pageInfo.noindexOffset !== undefined) noindex = { file, offset: pageInfo.noindexOffset }
|
|
404
|
+
return { title, description, hasOgImage, noindex }
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
function checkRouteTitle(ctx: CheckPluginContext, options: SeoPluginOptions, state: StaticState, relFile: string, routePath: string, code: string, pageInfo: RouteHeadInfo, title: OwnedEntry | undefined): void {
|
|
408
|
+
if (title === undefined) {
|
|
409
|
+
ctx.warn(formatWarn(relFile, code, pageInfo.emptyTitleOffset ?? 0, 'missing-title', `route "${routePath}" has no <title> in <Head>`, `add <Head><title>...</title></Head> to ${relFile} or its _layout.tsx`))
|
|
410
|
+
return
|
|
411
|
+
}
|
|
412
|
+
if (title.value === undefined) return
|
|
413
|
+
const rendered = applyTitleTemplate(title.value, options)
|
|
414
|
+
if (rendered.length > MAX_TITLE) {
|
|
415
|
+
const ownerRel = relPosix(ctx.root, title.file)
|
|
416
|
+
const key = `title:${ownerRel}:${title.offset}`
|
|
417
|
+
if (!title.fromLayout || !state.warnedLayouts.has(key)) {
|
|
418
|
+
state.warnedLayouts.add(key)
|
|
419
|
+
ctx.warn(formatWarn(ownerRel, title.code, title.offset, 'long-title', `title "${rendered}" is ${rendered.length} characters (recommended max ${MAX_TITLE})`, `shorten the <title>${rendered !== title.value ? ' or titleTemplate' : ''} to ${MAX_TITLE} characters or fewer`))
|
|
420
|
+
}
|
|
421
|
+
state.longTitleUrls.add(routePath)
|
|
422
|
+
}
|
|
423
|
+
const prev = state.seenTitles.get(rendered)
|
|
424
|
+
if (prev !== undefined) {
|
|
425
|
+
ctx.warn(formatWarn(relFile, code, title.fromLayout ? 0 : title.offset, 'duplicate-title', `route "${routePath}" has the same <title> ("${rendered}") as "${prev.routePath}" (${prev.relFile})`, 'give each page a unique <title>'))
|
|
426
|
+
state.dupTitles.add(rendered)
|
|
427
|
+
}
|
|
428
|
+
else {
|
|
429
|
+
state.seenTitles.set(rendered, { relFile, routePath })
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
function checkRouteDescription(ctx: CheckPluginContext, state: StaticState, fallbackDesc: boolean, relFile: string, routePath: string, code: string, pageInfo: RouteHeadInfo, description: OwnedEntry | undefined): void {
|
|
434
|
+
if (description === undefined) {
|
|
435
|
+
if (!fallbackDesc)
|
|
436
|
+
ctx.warn(formatWarn(relFile, code, pageInfo.emptyDescriptionOffset ?? 0, 'missing-description', `route "${routePath}" has no meta description`, 'add <meta name="description" content="..." /> inside <Head> or set `description` in `seo()`'))
|
|
437
|
+
return
|
|
438
|
+
}
|
|
439
|
+
if (description.value === undefined) return
|
|
440
|
+
const desc = description.value
|
|
441
|
+
if (desc.length > MAX_DESC) {
|
|
442
|
+
const ownerRel = relPosix(ctx.root, description.file)
|
|
443
|
+
const key = `desc:${ownerRel}:${description.offset}`
|
|
444
|
+
if (!description.fromLayout || !state.warnedLayouts.has(key)) {
|
|
445
|
+
state.warnedLayouts.add(key)
|
|
446
|
+
ctx.warn(formatWarn(ownerRel, description.code, description.offset, 'long-description', `meta description is ${desc.length} characters (recommended max ${MAX_DESC})`, `shorten the description to ${MAX_DESC} characters or fewer`))
|
|
447
|
+
}
|
|
448
|
+
state.longDescUrls.add(routePath)
|
|
449
|
+
}
|
|
450
|
+
const prev = state.seenDescs.get(desc)
|
|
451
|
+
if (prev !== undefined) {
|
|
452
|
+
ctx.warn(formatWarn(relFile, code, description.fromLayout ? 0 : description.offset, 'duplicate-description', `route "${routePath}" has the same meta description as "${prev.routePath}" (${prev.relFile})`, 'give each page a unique meta description'))
|
|
453
|
+
state.dupDescs.add(desc)
|
|
454
|
+
}
|
|
455
|
+
else {
|
|
456
|
+
state.seenDescs.set(desc, { relFile, routePath })
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
function checkStaticRoutes(ctx: CheckPluginContext, options: SeoPluginOptions, siteConfigured: boolean, excluded: ReadonlySet<string>): StaticState {
|
|
461
|
+
const state: StaticState = {
|
|
462
|
+
longTitleUrls: new Set(), longDescUrls: new Set(), noindexUrls: new Set(),
|
|
463
|
+
dupTitles: new Set(), dupDescs: new Set(), warnedLayouts: new Set(),
|
|
464
|
+
seenTitles: new Map(), seenDescs: new Map(),
|
|
465
|
+
}
|
|
466
|
+
const layoutCache = new Map<string, { code: string, info: RouteHeadInfo }>()
|
|
467
|
+
const descOpt = options.description
|
|
468
|
+
const fallbackDesc = typeof descOpt === 'string' ? descOpt.trim().length > 0 : descOpt !== undefined && Object.values(descOpt).some(v => v.trim().length > 0)
|
|
469
|
+
const hasDefaultImage = Boolean(options.image?.trim())
|
|
470
|
+
|
|
471
|
+
for (const file of walkRouteFiles(ctx.routesDir)) {
|
|
472
|
+
if (basename(file).startsWith('_')) continue
|
|
473
|
+
const code = readFileSync(file, 'utf8')
|
|
474
|
+
const exports = scanExports(file, code)
|
|
475
|
+
if (exports === undefined || !exports.includes('default') || exports.includes('GET')) continue
|
|
476
|
+
const routePath = fileToRoutePath(ctx.routesDir, file)
|
|
477
|
+
if (isSkippedPath(routePath)) continue
|
|
478
|
+
|
|
479
|
+
const relFile = relPosix(ctx.root, file)
|
|
480
|
+
const stripped = stripCommentsPreserveOffsets(code)
|
|
481
|
+
const pageInfo = extractRouteHead(stripped)
|
|
482
|
+
const effective = resolveEffectiveHead(file, code, pageInfo, ancestorLayouts(ctx.routesDir, file), layoutCache)
|
|
483
|
+
|
|
484
|
+
checkRouteTitle(ctx, options, state, relFile, routePath, code, pageInfo, effective.title)
|
|
485
|
+
checkRouteDescription(ctx, state, fallbackDesc, relFile, routePath, code, pageInfo, effective.description)
|
|
486
|
+
|
|
487
|
+
const isDynamic = routePath.includes(':') || routePath.includes('*')
|
|
488
|
+
const hasPrerender = exports.includes('prerender') && PRERENDER_TRUE_RE.test(stripped)
|
|
489
|
+
if (effective.noindex !== undefined && options.sitemap !== false && (!isDynamic || hasPrerender) && !excluded.has(routePath)) {
|
|
490
|
+
ctx.warn(formatWarn(relFile, code, effective.noindex.file === file ? effective.noindex.offset : 0, 'noindex-in-sitemap', `route "${routePath}" sets noindex but is included in sitemap.xml`, `add "${routePath}" to \`seo({ sitemapExclude })\` or remove \`noindex\``))
|
|
491
|
+
state.noindexUrls.add(routePath)
|
|
492
|
+
}
|
|
493
|
+
if (siteConfigured && !hasDefaultImage && !effective.hasOgImage)
|
|
494
|
+
ctx.warn(formatWarn(relFile, code, 0, 'missing-image', `route "${routePath}" has no share image while \`site\` is configured`, 'set `seo({ image: \'/og.png\' })` or add <meta property="og:image" content="..." /> in <Head>'))
|
|
495
|
+
}
|
|
496
|
+
return state
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
function collectHtmlFiles(dir: string, skipTopDirs: boolean): string[] {
|
|
500
|
+
const out: string[] = []
|
|
501
|
+
const walk = (cur: string, top: boolean): void => {
|
|
502
|
+
for (const e of readdirSync(cur, { withFileTypes: true })) {
|
|
503
|
+
if (e.isDirectory() && !e.name.startsWith('.') && !(top && skipTopDirs && SKIP_PRERENDER_DIRS.has(e.name)))
|
|
504
|
+
walk(join(cur, e.name), false)
|
|
505
|
+
else if (e.isFile() && e.name.endsWith('.html'))
|
|
506
|
+
out.push(join(cur, e.name))
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
if (existsSync(dir)) walk(dir, true)
|
|
510
|
+
return out.sort()
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
function htmlFileToUrl(htmlRoot: string, file: string): string {
|
|
514
|
+
const rel = relPosix(htmlRoot, file)
|
|
515
|
+
if (rel === 'index.html') return '/'
|
|
516
|
+
if (rel.endsWith('/index.html')) return `/${rel.slice(0, -11)}`
|
|
517
|
+
return rel === '404.html' || rel === '500.html' ? `/${rel.slice(0, -5)}` : `/${rel}`
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
function parsePrerenderedHead(html: string): { title: string | undefined, description: string | undefined, noindex: boolean } {
|
|
521
|
+
const head = HTML_HEAD_RE.exec(html)?.[1] ?? html
|
|
522
|
+
const rawTitle = HTML_TITLE_RE.exec(head)?.[1]
|
|
523
|
+
const title = rawTitle !== undefined ? decodeEntities(rawTitle).replace(/\s+/g, ' ').trim() || undefined : undefined
|
|
524
|
+
let description: string | undefined
|
|
525
|
+
let noindex = false
|
|
526
|
+
HTML_META_RE.lastIndex = 0
|
|
527
|
+
for (let m = HTML_META_RE.exec(head); m !== null; m = HTML_META_RE.exec(head)) {
|
|
528
|
+
const attrs = new Map<string, string>()
|
|
529
|
+
HTML_ATTR_RE.lastIndex = 0
|
|
530
|
+
for (let am = HTML_ATTR_RE.exec(m[0]); am !== null; am = HTML_ATTR_RE.exec(m[0]))
|
|
531
|
+
attrs.set(am[1]!.toLowerCase(), decodeEntities(am[2] ?? am[3] ?? am[4] ?? ''))
|
|
532
|
+
const name = attrs.get('name')?.trim().toLowerCase()
|
|
533
|
+
const content = attrs.get('content')?.trim()
|
|
534
|
+
if (name === 'description' && content) description = content
|
|
535
|
+
else if (name === 'robots' && content && NOINDEX_RE.test(content)) noindex = true
|
|
536
|
+
}
|
|
537
|
+
return { title, description, noindex }
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
function checkPrerenderedHtml(ctx: CheckPluginContext, options: SeoPluginOptions, excluded: ReadonlySet<string>, state: StaticState): void {
|
|
541
|
+
const outDir = getAppContext()?.outDir ?? join(ctx.root, 'dist')
|
|
542
|
+
const prerenderDir = join(outDir, 'prerendered')
|
|
543
|
+
const htmlRoot = existsSync(prerenderDir) ? prerenderDir : (existsSync(join(outDir, '.prunelle-output')) || existsSync(join(outDir, 'index.html'))) ? outDir : undefined
|
|
544
|
+
if (htmlRoot === undefined) return
|
|
545
|
+
|
|
546
|
+
const seenTitles = new Map<string, string>()
|
|
547
|
+
const seenDescs = new Map<string, string>()
|
|
548
|
+
for (const file of collectHtmlFiles(htmlRoot, htmlRoot === outDir)) {
|
|
549
|
+
const url = htmlFileToUrl(htmlRoot, file)
|
|
550
|
+
if (isSkippedPath(url)) continue
|
|
551
|
+
const relFile = relPosix(ctx.root, file)
|
|
552
|
+
const { title, description, noindex } = parsePrerenderedHead(readFileSync(file, 'utf8'))
|
|
553
|
+
|
|
554
|
+
if (title !== undefined) {
|
|
555
|
+
if (title.length > MAX_TITLE && !state.longTitleUrls.has(url))
|
|
556
|
+
ctx.warn(formatWarn(relFile, undefined, 0, 'long-title', `prerendered page "${url}" has a ${title.length}-character <title> (recommended max ${MAX_TITLE})`, `shorten the title to ${MAX_TITLE} characters or fewer`))
|
|
557
|
+
const prev = seenTitles.get(title)
|
|
558
|
+
if (prev !== undefined && !state.dupTitles.has(title))
|
|
559
|
+
ctx.warn(formatWarn(relFile, undefined, 0, 'duplicate-title', `prerendered page "${url}" has the same <title> ("${title}") as "${prev}"`, 'give each prerendered page a unique <title>'))
|
|
560
|
+
else if (prev === undefined) seenTitles.set(title, url)
|
|
561
|
+
}
|
|
562
|
+
if (description !== undefined) {
|
|
563
|
+
if (description.length > MAX_DESC && !state.longDescUrls.has(url))
|
|
564
|
+
ctx.warn(formatWarn(relFile, undefined, 0, 'long-description', `prerendered page "${url}" has a ${description.length}-character meta description (recommended max ${MAX_DESC})`, `shorten the description to ${MAX_DESC} characters or fewer`))
|
|
565
|
+
const prev = seenDescs.get(description)
|
|
566
|
+
if (prev !== undefined && !state.dupDescs.has(description))
|
|
567
|
+
ctx.warn(formatWarn(relFile, undefined, 0, 'duplicate-description', `prerendered page "${url}" has the same meta description as "${prev}"`, 'give each prerendered page a unique meta description'))
|
|
568
|
+
else if (prev === undefined) seenDescs.set(description, url)
|
|
569
|
+
}
|
|
570
|
+
if (noindex && options.sitemap !== false && !excluded.has(url) && !state.noindexUrls.has(url))
|
|
571
|
+
ctx.warn(formatWarn(relFile, undefined, 0, 'noindex-in-sitemap', `prerendered page "${url}" sets noindex but is included in sitemap.xml`, `add "${url}" to \`seo({ sitemapExclude })\` or remove \`noindex\``))
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
export function checkSeo(ctx: CheckPluginContext, options: SeoPluginOptions, activeSite: string | undefined): void {
|
|
576
|
+
const siteConfigured = hasConfiguredSite(ctx.root, options, activeSite)
|
|
577
|
+
const excluded = new Set((options.sitemapExclude ?? []).map(normalizePath))
|
|
578
|
+
checkConfigOptions(options, siteConfigured, ctx.warn)
|
|
579
|
+
const state = checkStaticRoutes(ctx, options, siteConfigured, excluded)
|
|
580
|
+
checkPrerenderedHtml(ctx, options, excluded, state)
|
|
581
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,479 @@
|
|
|
1
|
+
// @prunellejs/seo — SEO metadata, titleTemplate, JSON-LD, sitemap.xml, redirects, manifest, favicon, and self-hosted fonts.
|
|
2
|
+
// Built strictly on the public PrunellePlugin API (server, build, transformHtml).
|
|
3
|
+
|
|
4
|
+
import type { Html } from 'prunelle'
|
|
5
|
+
import type { ActiveI18nConfig, BuildPluginContext, DocumentHeadContext, FinalizeBuildContext, PrunellePlugin, ServerPluginAPI } from 'prunelle/config'
|
|
6
|
+
import type { RequestContext } from 'prunelle/server'
|
|
7
|
+
import { existsSync, readFileSync } from 'node:fs'
|
|
8
|
+
import { basename, extname, join, resolve } from 'node:path'
|
|
9
|
+
import { definePlugin, I18N_CONFIG_SERVICE } from 'prunelle/config'
|
|
10
|
+
import { escAttr, escJson, raw } from 'prunelle/server'
|
|
11
|
+
import { checkSeo } from './check'
|
|
12
|
+
|
|
13
|
+
export interface FontEntry {
|
|
14
|
+
family: string
|
|
15
|
+
/** Local relative path or package specifier (e.g. '@fontsource/inter/files/inter-latin-400-normal.woff2'). */
|
|
16
|
+
src: string
|
|
17
|
+
weight?: number | string | undefined
|
|
18
|
+
style?: 'normal' | 'italic' | undefined
|
|
19
|
+
display?: 'swap' | 'optional' | 'fallback' | 'block' | undefined
|
|
20
|
+
preload?: boolean | undefined
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface ManifestOptions {
|
|
24
|
+
name?: string | undefined
|
|
25
|
+
shortName?: string | undefined
|
|
26
|
+
description?: string | undefined
|
|
27
|
+
themeColor?: string | undefined
|
|
28
|
+
backgroundColor?: string | undefined
|
|
29
|
+
display?: 'standalone' | 'minimal-ui' | 'fullscreen' | 'browser' | undefined
|
|
30
|
+
startUrl?: string | undefined
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export type RedirectTarget = string | { to: string, status?: 301 | 302 | 307 | 308 | undefined }
|
|
34
|
+
|
|
35
|
+
export interface SeoPluginOptions {
|
|
36
|
+
site?: string | undefined
|
|
37
|
+
name?: string | undefined
|
|
38
|
+
titleTemplate?: string | undefined
|
|
39
|
+
description?: string | Record<string, string> | undefined
|
|
40
|
+
image?: string | undefined
|
|
41
|
+
imageAlt?: string | undefined
|
|
42
|
+
locale?: string | undefined
|
|
43
|
+
jsonLd?: Record<string, unknown>[] | undefined
|
|
44
|
+
sitemap?: boolean | undefined
|
|
45
|
+
sitemapExclude?: string[] | undefined
|
|
46
|
+
extraUrls?: (() => string[]) | undefined
|
|
47
|
+
redirects?: Record<string, RedirectTarget> | undefined
|
|
48
|
+
favicon?: string | string[] | undefined
|
|
49
|
+
manifest?: ManifestOptions | undefined
|
|
50
|
+
fonts?: FontEntry[] | undefined
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const JS_SCANNER = new Bun.Transpiler({ loader: 'js' })
|
|
54
|
+
const CANONICAL_LINK_RE = /<link rel="canonical" href="[^"]*">/
|
|
55
|
+
const ABSOLUTE_URL_RE = /^(?:https?:)?\/\//i
|
|
56
|
+
|
|
57
|
+
function serializeJsonLd(schema: Record<string, unknown>): string {
|
|
58
|
+
const payload = '@context' in schema ? schema : { '@context': 'https://schema.org', ...schema }
|
|
59
|
+
return `<script type="application/ld+json">${escJson(JSON.stringify(payload))}</script>`
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Render a page-specific JSON-LD script inside `<Head>{jsonLd({ ... })}</Head>`. */
|
|
63
|
+
export function jsonLd(schema: Record<string, unknown>): Html {
|
|
64
|
+
return raw(serializeJsonLd(schema))
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function resolveFileOrPkg(root: string, spec: string): string | undefined {
|
|
68
|
+
const local = resolve(root, spec)
|
|
69
|
+
if (existsSync(local))
|
|
70
|
+
return local
|
|
71
|
+
try {
|
|
72
|
+
return Bun.resolveSync(spec, root)
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
return undefined
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function normalizePathname(pathname: string): string {
|
|
80
|
+
const withSlash = pathname.startsWith('/') ? pathname : `/${pathname}`
|
|
81
|
+
return withSlash.length > 1 ? withSlash.replace(/\/+$/, '') || '/' : withSlash
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function stripLocaleFromPath(pathname: string, i18n: ActiveI18nConfig): { locale: string, hasPrefix: boolean, basePath: string } {
|
|
85
|
+
const normalized = normalizePathname(pathname)
|
|
86
|
+
const parts = normalized.split('/')
|
|
87
|
+
const first = parts[1]
|
|
88
|
+
if (first !== undefined && i18n.locales.includes(first)) {
|
|
89
|
+
const rest = normalizePathname(`/${parts.slice(2).join('/')}`)
|
|
90
|
+
return { locale: first, hasPrefix: true, basePath: rest }
|
|
91
|
+
}
|
|
92
|
+
return { locale: i18n.defaultLocale, hasPrefix: false, basePath: normalized }
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function localizeSitemapPath(basePath: string, locale: string, i18n: ActiveI18nConfig): string {
|
|
96
|
+
const clean = normalizePathname(basePath)
|
|
97
|
+
if (locale === i18n.defaultLocale && !i18n.prefixDefault)
|
|
98
|
+
return clean
|
|
99
|
+
return clean === '/' ? `/${locale}` : `/${locale}${clean}`
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function localizeRedirectTarget(to: string, locale: string, i18n: ActiveI18nConfig): string {
|
|
103
|
+
if (!to.startsWith('/') || to.startsWith('//'))
|
|
104
|
+
return to
|
|
105
|
+
const cut = to.search(/[?#]/)
|
|
106
|
+
const pathname = cut === -1 ? to : to.slice(0, cut)
|
|
107
|
+
const suffix = cut === -1 ? '' : to.slice(cut)
|
|
108
|
+
const stripped = stripLocaleFromPath(pathname, i18n)
|
|
109
|
+
if (stripped.hasPrefix)
|
|
110
|
+
return to
|
|
111
|
+
return `${localizeSitemapPath(stripped.basePath, locale, i18n)}${suffix}`
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function isErrorLikePath(pathname: string, i18n: ActiveI18nConfig | undefined): boolean {
|
|
115
|
+
const base = i18n !== undefined ? stripLocaleFromPath(pathname, i18n).basePath : normalizePathname(pathname)
|
|
116
|
+
return base === '/404' || base === '/500' || base === '/__pru_404__'
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function isApiPath(pathname: string): boolean {
|
|
120
|
+
const norm = normalizePathname(pathname)
|
|
121
|
+
return norm === '/api' || norm.startsWith('/api/')
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function isApiRouteFile(outDir: string, relFile: string): boolean {
|
|
125
|
+
const abs = join(outDir, relFile)
|
|
126
|
+
if (!existsSync(abs))
|
|
127
|
+
return false
|
|
128
|
+
try {
|
|
129
|
+
const { exports } = JS_SCANNER.scan(readFileSync(abs, 'utf8'))
|
|
130
|
+
return !exports.includes('default') || exports.includes('GET')
|
|
131
|
+
}
|
|
132
|
+
catch {
|
|
133
|
+
return false
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function readPngSize(bytes: Uint8Array): { width: number, height: number } | undefined {
|
|
138
|
+
if (bytes.byteLength < 24)
|
|
139
|
+
return undefined
|
|
140
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
|
|
141
|
+
if (view.getUint32(0) !== 0x89504E47 || view.getUint32(4) !== 0x0D0A1A0A)
|
|
142
|
+
return undefined
|
|
143
|
+
const width = view.getUint32(16)
|
|
144
|
+
const height = view.getUint32(20)
|
|
145
|
+
return width > 0 && height > 0 ? { width, height } : undefined
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function emitFavicons(ctx: BuildPluginContext, favicon: string | string[]): void {
|
|
149
|
+
const favicons = Array.isArray(favicon) ? favicon : [favicon]
|
|
150
|
+
const resolved: Array<{ abs: string, ext: string, bytes: Uint8Array }> = []
|
|
151
|
+
const extCounts = new Map<string, number>()
|
|
152
|
+
for (const fav of favicons) {
|
|
153
|
+
const abs = resolveFileOrPkg(ctx.root, fav)
|
|
154
|
+
if (abs === undefined)
|
|
155
|
+
throw new Error(`@prunellejs/seo: favicon "${fav}" is neither a file under the app root nor a package file: fix the path given to \`seo({ favicon })\`.`)
|
|
156
|
+
const ext = extname(abs).toLowerCase()
|
|
157
|
+
const key = ext === '.svg' ? '.svg' : ext === '.png' ? '.png' : '.ico'
|
|
158
|
+
extCounts.set(key, (extCounts.get(key) ?? 0) + 1)
|
|
159
|
+
resolved.push({ abs, ext: key, bytes: new Uint8Array(readFileSync(abs)) })
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const usedNames = new Set<string>()
|
|
163
|
+
for (const item of resolved) {
|
|
164
|
+
const size = item.ext === '.png' ? readPngSize(item.bytes) : undefined
|
|
165
|
+
let outName: string
|
|
166
|
+
if ((extCounts.get(item.ext) ?? 0) === 1) {
|
|
167
|
+
outName = `favicon${item.ext}`
|
|
168
|
+
}
|
|
169
|
+
else {
|
|
170
|
+
const stem = basename(item.abs, extname(item.abs)).toLowerCase().replace(/[^a-z0-9-_]/g, '-') || 'favicon'
|
|
171
|
+
const candidate = `${stem}${item.ext}`
|
|
172
|
+
if (!usedNames.has(candidate)) {
|
|
173
|
+
outName = candidate
|
|
174
|
+
}
|
|
175
|
+
else if (size !== undefined && !usedNames.has(`${stem}-${size.width}x${size.height}${item.ext}`)) {
|
|
176
|
+
outName = `${stem}-${size.width}x${size.height}${item.ext}`
|
|
177
|
+
}
|
|
178
|
+
else {
|
|
179
|
+
outName = `${stem}-${Bun.hash(item.bytes).toString(36).slice(0, 6)}${item.ext}`
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
usedNames.add(outName)
|
|
183
|
+
const href = ctx.emitPublic(outName, item.bytes)
|
|
184
|
+
const type = item.ext === '.svg' ? 'image/svg+xml' : item.ext === '.png' ? 'image/png' : 'image/x-icon'
|
|
185
|
+
const sizesAttr = size !== undefined ? ` sizes="${size.width}x${size.height}"` : ''
|
|
186
|
+
ctx.addHead(`<link rel="icon" href="${escAttr(href)}" type="${type}"${sizesAttr}>`)
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function emitManifest(ctx: BuildPluginContext, options: SeoPluginOptions): void {
|
|
191
|
+
const m = options.manifest
|
|
192
|
+
if (m === undefined)
|
|
193
|
+
return
|
|
194
|
+
const defaultDesc = typeof options.description === 'string'
|
|
195
|
+
? options.description
|
|
196
|
+
: (options.description ? Object.values(options.description)[0] : undefined)
|
|
197
|
+
const body = JSON.stringify({
|
|
198
|
+
name: m.name ?? options.name ?? '',
|
|
199
|
+
short_name: m.shortName ?? m.name ?? options.name ?? '',
|
|
200
|
+
description: m.description ?? defaultDesc,
|
|
201
|
+
start_url: m.startUrl ?? '/',
|
|
202
|
+
display: m.display ?? 'standalone',
|
|
203
|
+
theme_color: m.themeColor,
|
|
204
|
+
background_color: m.backgroundColor,
|
|
205
|
+
}, null, 2)
|
|
206
|
+
const href = ctx.emitPublic('manifest.webmanifest', body)
|
|
207
|
+
ctx.addHead(`<link rel="manifest" href="${escAttr(href)}">`)
|
|
208
|
+
if (m.themeColor)
|
|
209
|
+
ctx.addHead(`<meta name="theme-color" content="${escAttr(m.themeColor)}">`)
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function emitFonts(ctx: BuildPluginContext, fonts: FontEntry[]): void {
|
|
213
|
+
const cssRules: string[] = []
|
|
214
|
+
for (const font of fonts) {
|
|
215
|
+
const abs = resolveFileOrPkg(ctx.root, font.src)
|
|
216
|
+
if (abs === undefined)
|
|
217
|
+
throw new Error(`@prunellejs/seo: could not resolve font "${font.src}"`)
|
|
218
|
+
const bytes = new Uint8Array(readFileSync(abs))
|
|
219
|
+
const hash = Bun.hash(bytes).toString(36)
|
|
220
|
+
const ext = extname(abs).toLowerCase() || '.woff2'
|
|
221
|
+
const stem = basename(abs, ext).toLowerCase().replace(/[^a-z0-9-_]/g, '-')
|
|
222
|
+
const url = ctx.emitAsset(`fonts/${stem}-${hash}${ext}`, bytes)
|
|
223
|
+
const weight = font.weight ?? 400
|
|
224
|
+
const style = font.style ?? 'normal'
|
|
225
|
+
const display = font.display ?? 'swap'
|
|
226
|
+
const format = ext === '.woff2' ? 'woff2' : ext === '.woff' ? 'woff' : 'truetype'
|
|
227
|
+
cssRules.push(`@font-face{font-family:${JSON.stringify(font.family)};font-style:${style};font-weight:${weight};font-display:${display};src:url(${JSON.stringify(url)}) format(${JSON.stringify(format)});}`)
|
|
228
|
+
if (font.preload !== false && ext === '.woff2')
|
|
229
|
+
ctx.addHead(`<link rel="preload" href="${escAttr(url)}" as="font" type="font/woff2" crossorigin>`)
|
|
230
|
+
}
|
|
231
|
+
if (cssRules.length > 0) {
|
|
232
|
+
const css = cssRules.join('\n')
|
|
233
|
+
const cssHash = Bun.hash(css).toString(36)
|
|
234
|
+
const cssUrl = ctx.emitAsset(`fonts-${cssHash}.css`, css)
|
|
235
|
+
ctx.addStyle(cssUrl)
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function emitSitemap(
|
|
240
|
+
ctx: FinalizeBuildContext,
|
|
241
|
+
site: string,
|
|
242
|
+
options: SeoPluginOptions,
|
|
243
|
+
i18nCfg: ActiveI18nConfig | undefined,
|
|
244
|
+
): void {
|
|
245
|
+
const excluded = new Set(options.sitemapExclude ?? [])
|
|
246
|
+
const urls = new Set<string>()
|
|
247
|
+
for (const r of ctx.routes) {
|
|
248
|
+
if (isApiPath(r.path) || isErrorLikePath(r.path, i18nCfg) || isApiRouteFile(ctx.outDir, r.file))
|
|
249
|
+
continue
|
|
250
|
+
if (r.prerendered) {
|
|
251
|
+
for (const u of Object.keys(r.prerendered)) {
|
|
252
|
+
if (!excluded.has(u) && !isApiPath(u) && !isErrorLikePath(u, i18nCfg))
|
|
253
|
+
urls.add(u)
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
else if (!r.path.includes(':') && !r.path.includes('*')) {
|
|
257
|
+
if (i18nCfg !== undefined && i18nCfg.locales.length > 0) {
|
|
258
|
+
for (const loc of i18nCfg.locales) {
|
|
259
|
+
const localized = localizeSitemapPath(r.path, loc, i18nCfg)
|
|
260
|
+
if (!excluded.has(localized) && !excluded.has(r.path))
|
|
261
|
+
urls.add(localized)
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
else if (!excluded.has(r.path)) {
|
|
265
|
+
urls.add(r.path)
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
if (options.extraUrls !== undefined) {
|
|
270
|
+
for (const u of options.extraUrls()) {
|
|
271
|
+
if (!excluded.has(u) && !isErrorLikePath(u, i18nCfg))
|
|
272
|
+
urls.add(u)
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
const sortedUrls = [...urls].sort()
|
|
276
|
+
if (i18nCfg !== undefined && i18nCfg.locales.length > 0) {
|
|
277
|
+
const localeOrder = new Map(i18nCfg.locales.map((l, idx) => [l, idx]))
|
|
278
|
+
const byBase = new Map<string, Array<{ locale: string, path: string }>>()
|
|
279
|
+
for (const u of sortedUrls) {
|
|
280
|
+
const { locale, basePath } = stripLocaleFromPath(u, i18nCfg)
|
|
281
|
+
let group = byBase.get(basePath)
|
|
282
|
+
if (group === undefined) {
|
|
283
|
+
group = []
|
|
284
|
+
byBase.set(basePath, group)
|
|
285
|
+
}
|
|
286
|
+
if (!group.some(item => item.locale === locale))
|
|
287
|
+
group.push({ locale, path: u })
|
|
288
|
+
}
|
|
289
|
+
for (const group of byBase.values())
|
|
290
|
+
group.sort((a, b) => (localeOrder.get(a.locale) ?? 999) - (localeOrder.get(b.locale) ?? 999))
|
|
291
|
+
|
|
292
|
+
const entries = sortedUrls.map((u) => {
|
|
293
|
+
const { basePath } = stripLocaleFromPath(u, i18nCfg)
|
|
294
|
+
const group = byBase.get(basePath) ?? []
|
|
295
|
+
const alts = group
|
|
296
|
+
.map(a => `<xhtml:link rel="alternate" hreflang="${escAttr(a.locale)}" href="${escAttr(`${site}${a.path === '/' ? '/' : a.path}`)}"/>`)
|
|
297
|
+
.join('')
|
|
298
|
+
return ` <url><loc>${escAttr(`${site}${u === '/' ? '/' : u}`)}</loc>${alts}</url>`
|
|
299
|
+
}).join('\n')
|
|
300
|
+
const xml = `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">\n${entries}\n</urlset>\n`
|
|
301
|
+
ctx.emitPublic('sitemap.xml', xml)
|
|
302
|
+
}
|
|
303
|
+
else {
|
|
304
|
+
const entries = sortedUrls.map(u => ` <url><loc>${escAttr(`${site}${u === '/' ? '/' : u}`)}</loc></url>`).join('\n')
|
|
305
|
+
const xml = `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${entries}\n</urlset>\n`
|
|
306
|
+
ctx.emitPublic('sitemap.xml', xml)
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
function registerRedirects(
|
|
311
|
+
api: ServerPluginAPI,
|
|
312
|
+
redirects: Record<string, RedirectTarget>,
|
|
313
|
+
i18nCfg: ActiveI18nConfig | undefined,
|
|
314
|
+
): void {
|
|
315
|
+
for (const [from, target] of Object.entries(redirects)) {
|
|
316
|
+
const to = typeof target === 'string' ? target : target.to
|
|
317
|
+
const status = typeof target === 'string' ? 301 : (target.status ?? 301)
|
|
318
|
+
// A source with a locale prefix is matched before i18n strips it, so on the raw path, by a middleware scoped to it that leaves every other page alone.
|
|
319
|
+
if (i18nCfg !== undefined && stripLocaleFromPath(from, i18nCfg).hasPrefix) {
|
|
320
|
+
const source = normalizePathname(from)
|
|
321
|
+
api.use((ctx, next) => {
|
|
322
|
+
const read = ctx.request.method === 'GET' || ctx.request.method === 'HEAD'
|
|
323
|
+
return read && normalizePathname(ctx.url.pathname) === source ? ctx.redirect(to, status) : next()
|
|
324
|
+
}, { scope: source })
|
|
325
|
+
continue
|
|
326
|
+
}
|
|
327
|
+
api.route('GET', from, (ctx) => {
|
|
328
|
+
if (i18nCfg === undefined)
|
|
329
|
+
return ctx.redirect(to, status)
|
|
330
|
+
const locale = 'locale' in ctx.locals && typeof ctx.locals.locale === 'string'
|
|
331
|
+
? ctx.locals.locale
|
|
332
|
+
: i18nCfg.defaultLocale
|
|
333
|
+
return ctx.redirect(localizeRedirectTarget(to, locale, i18nCfg), status)
|
|
334
|
+
})
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
function resolveFallbackDescription(
|
|
339
|
+
description: SeoPluginOptions['description'],
|
|
340
|
+
ctx: RequestContext,
|
|
341
|
+
i18nCfg: ActiveI18nConfig | undefined,
|
|
342
|
+
): string | undefined {
|
|
343
|
+
if (typeof description === 'string')
|
|
344
|
+
return description
|
|
345
|
+
if (description === undefined)
|
|
346
|
+
return undefined
|
|
347
|
+
const loc = 'locale' in ctx.locals && typeof ctx.locals.locale === 'string' ? ctx.locals.locale : undefined
|
|
348
|
+
const fallbackLoc = i18nCfg?.defaultLocale
|
|
349
|
+
return (loc && description[loc]) ?? (fallbackLoc && description[fallbackLoc]) ?? Object.values(description)[0]
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
function applySeoHead(
|
|
353
|
+
head: DocumentHeadContext,
|
|
354
|
+
ctx: RequestContext,
|
|
355
|
+
options: SeoPluginOptions,
|
|
356
|
+
activeSite: string | undefined,
|
|
357
|
+
activeI18n: ActiveI18nConfig | undefined,
|
|
358
|
+
errorRequests: WeakSet<Request>,
|
|
359
|
+
seoCanonicalRequests: WeakSet<Request>,
|
|
360
|
+
): void {
|
|
361
|
+
if (options.titleTemplate || options.name) {
|
|
362
|
+
if (head.title !== undefined) {
|
|
363
|
+
if (options.titleTemplate && (!options.name || !head.title.includes(options.name))) {
|
|
364
|
+
const safeTemplate = escAttr(options.titleTemplate)
|
|
365
|
+
head.title = safeTemplate.replace('%s', () => head.title!)
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
else if (options.name) {
|
|
369
|
+
head.title = escAttr(options.name)
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
const fallbackDesc = resolveFallbackDescription(options.description, ctx, activeI18n)
|
|
374
|
+
if (fallbackDesc && !head.headHtml.includes('name="description"')) {
|
|
375
|
+
const content = escAttr(fallbackDesc)
|
|
376
|
+
head.add(`<meta name="description" content="${content}">`)
|
|
377
|
+
if (!head.headHtml.includes('property="og:description"'))
|
|
378
|
+
head.add(`<meta property="og:description" content="${content}">`)
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
if (options.image && !head.headHtml.includes('property="og:image"')) {
|
|
382
|
+
const imgUrl = ABSOLUTE_URL_RE.test(options.image) || !activeSite
|
|
383
|
+
? options.image
|
|
384
|
+
: `${activeSite}${options.image.startsWith('/') ? '' : '/'}${options.image}`
|
|
385
|
+
head.add(`<meta property="og:image" content="${escAttr(imgUrl)}">`)
|
|
386
|
+
if (!head.headHtml.includes('name="twitter:card"'))
|
|
387
|
+
head.add('<meta name="twitter:card" content="summary_large_image">')
|
|
388
|
+
if (options.imageAlt && !head.headHtml.includes('property="og:image:alt"'))
|
|
389
|
+
head.add(`<meta property="og:image:alt" content="${escAttr(options.imageAlt)}">`)
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
if (activeSite && !head.headHtml.includes('rel="canonical"') && !errorRequests.has(ctx.request) && !isErrorLikePath(ctx.url.pathname, activeI18n)) {
|
|
393
|
+
const canonical = escAttr(`${activeSite}${ctx.url.pathname}`)
|
|
394
|
+
head.add(`<link rel="canonical" href="${canonical}">`)
|
|
395
|
+
seoCanonicalRequests.add(ctx.request)
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
export function seo(options: SeoPluginOptions = {}): PrunellePlugin {
|
|
400
|
+
let activeSite = options.site?.replace(/\/$/, '')
|
|
401
|
+
let activeI18n: ActiveI18nConfig | undefined
|
|
402
|
+
const errorRequests = new WeakSet<Request>()
|
|
403
|
+
const seoCanonicalRequests = new WeakSet<Request>()
|
|
404
|
+
|
|
405
|
+
const resolveSite = (ctxSite?: string): string | undefined =>
|
|
406
|
+
options.site?.replace(/\/$/, '') ?? ctxSite?.replace(/\/$/, '') ?? activeSite
|
|
407
|
+
|
|
408
|
+
return definePlugin({
|
|
409
|
+
name: '@prunellejs/seo',
|
|
410
|
+
after: ['@prunellejs/i18n'],
|
|
411
|
+
readsLocals: ['locale'],
|
|
412
|
+
|
|
413
|
+
requires(ctx) {
|
|
414
|
+
return resolveSite(ctx.site) === undefined
|
|
415
|
+
? ['no `site`, so pages go out with no canonical link, no absolute `og:image` and no sitemap: set `site` in `prunelle.config.ts` (or pass it to `seo()`).']
|
|
416
|
+
: []
|
|
417
|
+
},
|
|
418
|
+
|
|
419
|
+
check(ctx) {
|
|
420
|
+
checkSeo(ctx, options, activeSite)
|
|
421
|
+
},
|
|
422
|
+
|
|
423
|
+
onError({ request }) {
|
|
424
|
+
errorRequests.add(request)
|
|
425
|
+
},
|
|
426
|
+
|
|
427
|
+
server(api) {
|
|
428
|
+
activeSite = resolveSite(api.site)
|
|
429
|
+
activeI18n = api.inject<ActiveI18nConfig>(I18N_CONFIG_SERVICE)
|
|
430
|
+
if (options.redirects !== undefined)
|
|
431
|
+
registerRedirects(api, options.redirects, activeI18n)
|
|
432
|
+
|
|
433
|
+
// Strip auto-injected canonical tag on 4xx/5xx fallback pages (e.g. _404.tsx / load() -> notFound()).
|
|
434
|
+
api.use(async (ctx, next) => {
|
|
435
|
+
const res = await next()
|
|
436
|
+
if (res.status >= 400 && seoCanonicalRequests.has(ctx.request) && !res.headers.has('content-encoding') && (res.headers.get('content-type') ?? '').includes('text/html')) {
|
|
437
|
+
const html = await res.text()
|
|
438
|
+
const cleaned = html.replace(CANONICAL_LINK_RE, '')
|
|
439
|
+
if (cleaned !== html) {
|
|
440
|
+
const headers = new Headers(res.headers)
|
|
441
|
+
headers.delete('content-length')
|
|
442
|
+
return new Response(cleaned, { status: res.status, statusText: res.statusText, headers })
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
return res
|
|
446
|
+
}, { scope: 'dynamic' })
|
|
447
|
+
},
|
|
448
|
+
|
|
449
|
+
build(ctx) {
|
|
450
|
+
activeSite = resolveSite(ctx.site)
|
|
451
|
+
activeI18n = ctx.inject<ActiveI18nConfig>(I18N_CONFIG_SERVICE)
|
|
452
|
+
|
|
453
|
+
if (options.name)
|
|
454
|
+
ctx.addHead(`<meta property="og:site_name" content="${escAttr(options.name)}">`)
|
|
455
|
+
if (options.locale)
|
|
456
|
+
ctx.addHead(`<meta property="og:locale" content="${escAttr(options.locale)}">`)
|
|
457
|
+
if (options.jsonLd) {
|
|
458
|
+
for (const schema of options.jsonLd)
|
|
459
|
+
ctx.addHead(serializeJsonLd(schema))
|
|
460
|
+
}
|
|
461
|
+
if (options.favicon)
|
|
462
|
+
emitFavicons(ctx, options.favicon)
|
|
463
|
+
emitManifest(ctx, options)
|
|
464
|
+
if (options.fonts && options.fonts.length > 0)
|
|
465
|
+
emitFonts(ctx, options.fonts)
|
|
466
|
+
},
|
|
467
|
+
|
|
468
|
+
afterPrerender(ctx) {
|
|
469
|
+
const site = resolveSite(ctx.site)
|
|
470
|
+
const i18nCfg = ctx.inject<ActiveI18nConfig>(I18N_CONFIG_SERVICE) ?? activeI18n
|
|
471
|
+
if (site && options.sitemap !== false)
|
|
472
|
+
emitSitemap(ctx, site, options, i18nCfg)
|
|
473
|
+
},
|
|
474
|
+
|
|
475
|
+
head(head, ctx) {
|
|
476
|
+
applySeoHead(head, ctx, options, activeSite, activeI18n, errorRequests, seoCanonicalRequests)
|
|
477
|
+
},
|
|
478
|
+
})
|
|
479
|
+
}
|
package/README.md
DELETED